text
stringlengths
175
47.7k
meta
dict
Q: What is the voltage divider rule? Can anyone explain what the voltage divider rule is? How has the author of this book used it for analyzing the Voltage Divider Bias circuit for transistors? And can anyone explain how the two resistors are parallel? And how has the author assumed the battery to be a short circuit (as shown in Figure 4.28)? Thanks a lot. ________________________________--- From above link: A: We are looking at an AC amplifier. The DC part of the amplifier is only about setting up the Q-Point, or Working Point of the transistor. Once that is determined, the actual AC workings can be looked at. I would propose you get hold of a complete book on basic electronics. The text you showed us here expects quite a bit of knowledge in the reader. But lets see how this works out: Fig. 4.25: We describe the circuit. Fig. 4.27: The step showing the DC Part of the input side Fig. 4.28: What remains if we look at AC -> VCC is replaced with a shortcut. This is a way to calculate the internal resistance of the network we are looking at. This is only a hypothetical step in a mathematical technique. "Applying the Voltage Divider Rule", meaning no other thing than "seeing how in 4.28 the Resistances are in parallel, we calculate the parallel resistance using the well known formula. But lets call it a rule". This all happens expecting the reader knows how to apply the Thevenin Theorem, which doubtlessly was explained earlier in the book. Fig. 4.29 Lets draw the resulting Network, showing the black box we are transforming. Eq 4.30 Calculating Ib using the Theremin replacement, this also happens in DC. Fig. 4.30 Two steps in this one: First, 4.29 is replaced by the appropriate Thevenin replacement. Secondly, it is applied to the base of the transistor. Equation 4.31 has very little to do with the whole path so far, it is simply the summation of the voltages on the output side. In fact, Msr. Thevenin was a French pioneer of electronics, read the Wikipedia article. He was not at all mentioned in my studies as an electrical engineer. A: (1) It MAY be of assistance to you to note that equation 4.29 in the above cited text COULD be called "the voltage divider rule" as it refers to R1, R2 and Vcc. ie changing what it says just slightly without changing the meaning: Vout = Vin x R2 / (R1 + R2) ie R1 & R2 form a voltage divider and the above equation defines a "rule" of the result. BUT (2) There IS NO "voltage divider rule" as such. Even if somebody uses that term there is still no such rule. BECAUSE the terminology is much too general. That's even more general than saying eg "The Ohm's law rule" where you at least have some guide. If you have a specific question you should explain it clearly in words and not use general terms or few words or the real requirement is liable to be missed. Added: Re question: Can you tell me how this 'rule' is derived? I'm a beginner so I didn't understand how he got the relation Vr2= (R2)(Vcc)/(R1+R2) (1) Short answer. Voltage across each resistor is proportional to current in it (Ohm's law). As current in both resistors = battery current = the same THEN the voltages across each resistor are proportional to their resistance value. THIS IS THE KEY FACTOR THAT MAKES THIS WORK Vout = Vr2 = ib x R2 Vcc = Vr1+Vr2 = ib x R1 + ib x R2 = ib x (R1 + R2) So Vout / Vcc = Vr2 / (Vr1 + VR2) = ib x R2 / (ib x (R1 + R2) ) Cancel ib's Vout/Vcc= R2/(R1 + R2) Multiply both sides by Vcc. Vout = Vcc x R2 / (R1 + R2) QED. (2) Longer answer. You MUST know Ohms law. If you don't know Ohms law and it's various re arrangements, stop reading this now, drop all lse and learn it. Wikipedia and Google know all about it N time over ... time lapse ... or no time at all as the case may be ... So we know you know Ohm's law. So - one version of Ohm's law says, as you know V = i x R ie the voltage drop across a resistor is equal to the value of the resistor multiplied by the current flowing in it. Now look at fig 4-29 Take this circuit in isolation. The current from the battery flows from B+ at the top left of R1, via R1, then via R2 and back to B- and the bottom left. Look at the diagram and be SURE that you agree with the above. Now, lets call the battery current Ib. Call the current in R1 I_R1. It can be seen "by inspection that I_R1 = Ib. Call the current in R2 I_R2. It can be seen "by inspection that I_R2 = Ib. So I_R1 = IR2 = Ib. ie the current is the same in each resistor and out of and into the battery. Now, the voltage across R1 = VR1 is, based on Ohm's law = I_R1 x R1. And, the voltage across R2 = VR2 is, based on Ohm's law = I_R2 x R2. BUT I_R1 = Ib and IR2 = Ib. So VR1 = I_R1 x R1 = Ib x R1 And VR2 = I_R2 x R2 = Ib x R2 The ratio of VR2 / VR1 = Ib x R2 / Ib x R1 = R2/R1 ie the voltages across the two resistors are proportional to their resistance values. Look at the diagram. Vbattery = Vcc Vcc = the voltage across R1 + the Voltage across R2 Vcc = VR1 + VR2 Vcc = ib x R1 + ib x R2 Vcc = ib (R1 + R2) So To determine the ratio Vout / Vcc: Vout / Vcc = V_R2 / Vcc = ib x R2 / ib (R1 + R2) but the ib's cancel so Vout/ Vcc = R2 / (R1 + R2) and rearranging Vout = Vcc x R2 / (R1 + R2) So the voltage across R2 compared to battery voltage = Vr2= (R2)(Vcc)/(R1+R2)
{ "pile_set_name": "StackExchange" }
Q: PHP/MySQL Get autoincremented value after insert In my mysql table i have an id-column which is set to autoincrement. then i do queries like this: INSERT INTO table (id, foo) VALUES ('', 'bar') how can i then safely find out which id was generated with this insert? if i just query the last id this might not be safe, since another insert could have happened in the meantime, right? A: There's a PHP and also a MySQL function for this: mysqli_insert_id() and PDO::lastInsertId(). http://php.net/manual/en/function.mysql-insert-id.php A: Use LAST_INSERT_ID() in SQL SELECT LAST_INSERT_ID(); Use mysql_insert_id() in PHP A: If you are using PHP to get the auto_incremented value that is returned after an INSERT statement, try using the MySQLi insert_id function. The older mysql_insert_id() version is being deprecated in PHP. An example below: <?php $mysqli = new mysqli("localhost", "my_user", "my_password", "world"); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } $mysqli->query("CREATE TABLE myCity LIKE City"); $query = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)"; $mysqli->query($query); printf ("New Record has id %d.\n", $mysqli->insert_id); /* drop table */ $mysqli->query("DROP TABLE myCity"); /* close connection */ $mysqli->close(); ?>
{ "pile_set_name": "StackExchange" }
Q: After Tomcat restart on VM, Youtrack resets I've installed Tomcat today on my local VMware Workstation and loaded *.war YouTrack there. Everything was great until I needed to stop VM and reboot my PC. After that I started my VM again, went to address where YouTrack is based and it took me to "setUp" page immediately. What might be the reason for that? Am I loading it incorrectly? Why did it reset and began everything from the start? Thank you for help. A: What OS do you use? How do you Start Tomcat? Most likely after restart Tomcat is running from the system service or different user account and therefore is using the blank database (since database is specific to the user account). You need to ensure that Tomcat is always running from the same user account and there are read/write permissions for the directory where YouTrack stores its data.
{ "pile_set_name": "StackExchange" }
Q: How to control fan speed in Dell Inspiron 5010 (15R)? How can I control fan speed on Inspiron 15R? I installed i8kutils as instructed on ubuntuforums but don't know how to use it. Fan makes quite a noise and runs all the time. A: So doing the research on this, it looks like the way to control the fan is to issue the following command: i8kctl fan R L Where R is the right fan mode and L is the left fan mode. The modes are as follows: 0 turn the fan off 1 set low speed 2 set high speed - don't change the state of this fan You should install sensors-applet which contains an applet you can add to your gnome panel. This keeps track of the temperature of your cpu and system and you should certainly keep a track on it if you are going to change the fan speed. Once you've got the applet installed, you just have to right click on your gnome panel and click Add to panel... look down the list for Hardware Sensors Applet
{ "pile_set_name": "StackExchange" }
Q: const enum in typescript (tsc.js vs typescript.js) I have a const enum in typescript: const enum LogLevel { TRACE = 0, DEBUG = 1, INFO = 2, WARN = 3, ERROR = 4, SILENT = 5 } Based on the typescript spec the following field: private foo: number = LogLevel.DEBUG; should be compiled as: this.foo = 1 /* DEBUG */; When I use tsc from the command line (Windows) it works as expected. But when it is compiled with awesome-typescript-loader in a webpack project (which uses the typescript.js from node_modules as opposed to the tsc.js which is used by tsc), then the enum constant is not getting inlined: this.foo = LogLevel.DEBUG; Both the tsc and the node module version are the same (2.0.2). I think there should not be a difference between the two. Does anybody know why? A: It turned out it was caused by the declaration option in tsconfig.json. If it is set to false, the two compilations produce the above inconsistent result. But when it is set to true, it works as expected. Not sure why this flag has such an effect on the outcome.
{ "pile_set_name": "StackExchange" }
Q: Fix AAPT2 ERROR in Android Studio with non-ASCII characters in Windows user name I installed the latest Android Studio and started to play around it. I created a new navigationbar project and put a gridview into it. Then when I try to build and run it I get this really annoying AAPT2 error, see logs for details. I've found several "fixes" for this saying to set android.enableAapt2 = false If I have understood correctly, that does not actually fix the problem, but just reverts the building back to aapt, am I right? And because AAPT2 is going to be the actual base builder from now on, I'd like to stick with it. So how do I actual fix this problem then? First what and where are the logs the error is pointing to? And second, what is actually going wrong with the build? I get this error even, if I just initialize a brand new Android Studio example project. Edit: Run the gradlew clean assembleDebug command in Android Studio Terminal and then got this insanely long output. I clipped it here, because it's repeating this same pattern: C:\Users\M?tz\.gradle\caches\transforms-1\files-1.1\appcompat-v7-27.1.1.aar\ff82df9d8c1253200bf8902d44d783bd\res\drawable-xxhdpi-v4\abc_ic_star_black_48dp.png: error: file not found. C:\Users\M?tz\.gradle\caches\transforms-1\files-1.1\appcompat-v7-27.1.1.aar\ff82df9d8c1253200bf8902d44d783bd\res\drawable-mdpi-v4\abc_list_pressed_holo_light.9.png: error: file not found. C:\Users\M?tz\.gradle\caches\transforms-1\files-1.1\appcompat-v7-27.1.1.aar\ff82df9d8c1253200bf8902d44d783bd\res\drawable-xxxhdpi-v4\abc_ic_menu_selectall_mtrl_alpha.png: error: file not found. C:\Users\M?tz\.gradle\caches\transforms-1\files-1.1\appcompat-v7-27.1.1.aar\ff82df9d8c1253200bf8902d44d783bd\res\drawable-mdpi-v4\abc_ab_share_pack_mtrl_alpha.9.png: error: file not found. C:\Users\M?tz\.gradle\caches\transforms-1\files-1.1\appcompat-v7-27.1.1.aar\ff82df9d8c1253200bf8902d44d783bd\res\drawable-hdpi-v4\abc_scrubber_primary_mtrl_alpha.9.png: error: file not found. C:\Users\M?tz\.gradle\caches\transforms-1\files-1.1\appcompat-v7-27.1.1.aar\ff82df9d8c1253200bf8902d44d783bd\res\drawable-hdpi-v4\abc_textfield_activated_mtrl_alpha.9.png: error: file not found. C:\Users\M?tz\.gradle\caches\transforms-1\files-1.1\design-27.1.1.aar\ccb9f9993808b605fecf0f43596e26e5\res\layout\design_navigation_menu.xml: error: file not found. C:\Users\M?tz\.gradle\caches\transforms-1\files-1.1\appcompat-v7-27.1.1.aar\ff82df9d8c1253200bf8902d44d783bd\res\drawable-hdpi-v4\abc_list_pressed_holo_light.9.png: error: file not found. C:\Users\M?tz\.gradle\caches\transforms-1\files-1.1\appcompat-v7-27.1.1.aar\ff82df9d8c1253200bf8902d44d783bd\res\drawable-xxhdpi-v4\abc_btn_switch_to_on_mtrl_00001.9.png: error: file not found. C:\Users\M?tz\.gradle\caches\transforms-1\files-1.1\appcompat-v7-27.1.1.aar\ff82df9d8c1253200bf8902d44d783bd\res\drawable-xxxhdpi-v4\abc_ic_star_black_36dp.png: error: file not found. C:\Users\M?tz\.gradle\caches\transforms-1\files-1.1\appcompat-v7-27.1.1.aar\ff82df9d8c1253200bf8902d44d783bd\res\drawable-hdpi-v4\abc_ab_share_pack_mtrl_alpha.9.png: error: file not found. C:\Users\M?tz\.gradle\caches\transforms-1\files-1.1\support-compat-27.1.1.aar\caef404a17c5959b4adfcdd5b4226763\res\drawable-xhdpi-v4\notification_bg_normal_pressed.9.png: error: file not found. C:\Users\M?tz\.gradle\caches\transforms-1\files-1.1\appcompat-v7-27.1.1.aar\ff82df9d8c1253200bf8902d44d783bd\res\color-v23\abc_color_highlight_material.xml: error: file not found. C:\Users\M?tz\.gradle\caches\transforms-1\files-1.1\appcompat-v7-27.1.1.aar\ff82df9d8c1253200bf8902d44d783bd\res\drawable-xhdpi-v4\abc_list_pressed_holo_light.9.png: error: file not found. C:\Users\M?tz\.gradle\caches\transforms-1\files-1.1\appcompat-v7-27.1.1.aar\ff82df9d8c1253200bf8902d44d783bd\res\drawable-mdpi-v4\abc_switch_track_mtrl_alpha.9.png: error: file not found. C:\Users\M?tz\.gradle\caches\transforms-1\files-1.1\appcompat-v7-27.1.1.aar\ff82df9d8c1253200bf8902d44d783bd\res\drawable-xxhdpi-v4\abc_ic_star_half_black_48dp.png: error: file not found. C:\Users\M?tz\.gradle\caches\transforms-1\files-1.1\support-compat-27.1.1.aar\caef404a17c5959b4adfcdd5b4226763\res\drawable-xhdpi-v4\notification_bg_low_pressed.9.png: error: file not found. C:\Users\M?tz\.gradle\caches\transforms-1\files-1.1\appcompat-v7-27.1.1.aar\ff82df9d8c1253200bf8902d44d783bd\res\drawable-hdpi-v4\abc_btn_check_to_on_mtrl_015.png: error: file not found. C:\Users\M?tz\.gradle\caches\transforms-1\files-1.1\appcompat-v7-27.1.1.aar\ff82df9d8c1253200bf8902d44d783bd\res\drawable-hdpi-v4\abc_btn_check_to_on_mtrl_000.png: error: file not found. C:\Users\M?tz\.gradle\caches\transforms-1\files-1.1\appcompat-v7-27.1.1.aar\ff82df9d8c1253200bf8902d44d783bd\res\drawable-hdpi-v4\abc_list_focused_holo.9.png: error: file not found. C:\Users\M?tz\.gradle\caches\transforms-1\files-1.1\appcompat-v7-27.1.1.aar\ff82df9d8c1253200bf8902d44d783bd\res\drawable-mdpi-v4\abc_ic_star_half_black_36dp.png: error: file not found. C:\Users\M?tz\.gradle\caches\transforms-1\files-1.1\appcompat-v7-27.1.1.aar\ff82df9d8c1253200bf8902d44d783bd\res\anim\abc_grow_fade_in_from_bottom.xml: error: file not found. C:\Users\M?tz\.gradle\caches\transforms-1\files-1.1\appcompat-v7-27.1.1.aar\ff82df9d8c1253200bf8902d44d783bd\res\drawable-hdpi-v4\abc_text_select_handle_right_mtrl_dark.png: error: file not found. C:\Users\M?tz\.gradle\caches\transforms-1\files-1.1\design-27.1.1.aar\ccb9f9993808b605fecf0f43596e26e5\res\layout\design_layout_snackbar.xml: error: file not found. The problem here is, I assume, that I have non-ASCII characters in my username in Windows. Even though I have pointed Android Studio to use different folders than anything under the C:\Users\\, gradle still needs to do something there and clearly doesn't like the 'ä' letter in my username. If this is the case, then I'd need somehow to tell gradle to use those other folders as well or change my username in Windows. I've tried the latter, but only managed to change the visible name, not the underlying one that's actually used in Windows and in the folder structure. Edit2: Renaming the windows user folder is not possible without reinstalling the whole system and that's not an option for me this time. So is there a way to change the folder gradle is using? A: The problem in this case was that I have non-ASCII characters in my Windows user name and thus in my user folder and gradle was set to use a folder under this user folder. You can change your visible user name in Windows, but you can not change your user name from your user folder without reinstalling. Luckily you can change the folder gradle is using from Android Studio settings. First make a .gradle folder somewhere in your file system where you don't have those non-ASCII characters. (I chose to use C:\android-sdk\.gradle) Open File -> Settings -> Gradle and there you can choose the "Service directory path" that Gradle is using. Change this to the folder you created and this problem should be solved. NOTE! I've faced this same problem when building react-native android apps too, so if you came here, because you got this same AAPT2 error with RN as well, try to change the gradle folder from you RN project's gradle files. At the moment I don't know how to do that and that's another question and topic too.
{ "pile_set_name": "StackExchange" }
Q: Unable to get Stencil Buffer to work in iOS 4+ (5.0 works fine). [OpenGL ES 2.0] So I am trying to use a stencil buffer in iOS for masking/clipping purposes. Do you guys have any idea why this code may not work? This is everything I have associated with Stencils. On iOS 4 I get a black screen. On iOS 5 I get exactly what I expect. The transparent areas of the image I drew in the stencil are the only areas being drawn later. Code is below. This is where I setup the frameBuffer, depth and stencil. In iOS the depth and stencil are combined. -(void)setupDepthBuffer { glGenRenderbuffers(1, &depthRenderBuffer); glBindRenderbuffer(GL_RENDERBUFFER, depthRenderBuffer); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8_OES, self.frame.size.width * [[UIScreen mainScreen] scale], self.frame.size.height * [[UIScreen mainScreen] scale]); } -(void)setupFrameBuffer { glGenFramebuffers(1, &frameBuffer); glBindFramebuffer(GL_FRAMEBUFFER, frameBuffer); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, colorRenderBuffer); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthRenderBuffer); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, depthRenderBuffer); // Check the FBO. if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { NSLog(@"Failure with framebuffer generation: %d", glCheckFramebufferStatus(GL_FRAMEBUFFER)); } } This is how I am setting up and drawing the stencil. (Shader code below.) glEnable(GL_STENCIL_TEST); glDisable(GL_DEPTH_TEST); glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); glDepthMask(GL_FALSE); glStencilFunc(GL_ALWAYS, 1, -1); glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE); glColorMask(0, 0, 0, 0); glClear(GL_STENCIL_BUFFER_BIT); machineForeground.shader = [StencilEffect sharedInstance]; [machineForeground draw]; machineForeground.shader = [BasicEffect sharedInstance]; glDisable(GL_STENCIL_TEST); glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); glDepthMask(GL_TRUE); Here is where I am using the stencil. glEnable(GL_STENCIL_TEST); glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP); glStencilFunc(GL_EQUAL, 1, -1); ...Draw Stuff here glDisable(GL_STENCIL_TEST); Finally here is my fragment shader. varying lowp vec2 TexCoordOut; uniform sampler2D Texture; void main(void) { lowp vec4 color = texture2D(Texture, TexCoordOut); if(color.a < 0.1) gl_FragColor = color; else discard; } A: I was able to solve this by addressing my shader. This code works fine as intended but my vertex data structs were asking for more data than I was providing to the shader. Not entirely sure what happened under the hood the allow it work on iOS 5 but I was able to fix it. That said glColorMask(0, 0, 0, 0); didn't actually accomplish what I was going for. What I wanted was to set the clear color and even then I only wanted to clear the stencil so I was actually looking for glStencilMask(1);
{ "pile_set_name": "StackExchange" }
Q: Implementing FluentSecurity over Ninject (aka porting StructureMap to Ninject) I'm a beginner on IoC and dependency injection. I'm reading about it, but I just can't get it. While I figure out how stuff works, I'm trying to implement some of these patterns on my project (and maybe learn by trial and error). I'm implementing security control by using FluentSecurity package (from NuGet, btw). I need to implement a Policy Violation Handler, as described on this wiki. The problem is that the example is written for StructureMap IoC-container, and I'm using (or trying to) Ninject 2.2 (it seemed more simple for a beginner). On their code, they suggest (a): configuration.ResolveServicesUsing(type => ObjectFactory.GetAllInstances(type).Cast<object>()); And then (b): public class WebRegistry : Registry { public WebRegistry() { Scan(scan => { scan.TheCallingAssembly(); scan.AddAllTypesOf<IPolicyViolationHandler>(); }); } } My concerns: I know that code (a) will be included on Global.asax. But what is Ninject's alternative to ObjectFactory.GetAllInstances()? I have no idea neither where this code should be inserted nor what are the equivalents for WebRegistry, Scan, and the internal functions TheCallingAssembly and AddAllTypesOf. I know this is a bit extensive question, but I appreciate any help! Thanks in advance. A: Marius Schulz has written an excellent article that should help anyone wanting to use Ninject together with FluentSecurity. Setting Up FluentSecurity to Use Ninject for Dependency Resolution A: I think this would be roughly equivelent //add an instance of IKernel to your MvcApplication [Inject] public IKernel Kernel { get; set; } ... configuration.ResolveServicesUsing(type => Kernel.GetAll(type)); To get the ability to scan an assembly for dependencies you would need an extension for ninject called Ninject.Extensions.Conventions, which was modeled after the one from SM. public class WebModule : NinjectModule { public WebModule() { Kernel.Scan(a => { a.FromAssemblyContaining<YourType>(); a.BindWithDefaultConventions(); a.InTransientScope(); }); } } The assembly scanning business obviously isn't strictly necassary for what you're doing, this would work just as well. Personally I'm not a fan of assembly scanning because it seems a little too "magic", and when it doesn't work, it's not fun to debug. Kernel.Bind<YourType>().ToSelf();
{ "pile_set_name": "StackExchange" }
Q: How to insert text into existing text in a div using jQuery I'm using jQuery 1.8.2 with a jsp and I'm trying to get text dynamically inserted into a div. Here is what I've tried: var selectButton = "Your " + $(this).val(); alert("The selectButton value is: ") $('#submitMsg').prepend(selectButton); $('#submitMsg').show(); ... <p/> <div id="submitMsg" style="display: none;"><h3> request is being submitted..</h3></div> <p/> <div id="trueDiv" style="display: none;"><h3> request was successful!</h3></div> <div id="falseDiv" style="display: none;"><h3> request was not successful!</h3></div> I want to dynamically pass in which request, based on which submit button was clicked, to the message div. Then I want to use that same text value and insert it into the request message confirmation, based on the result of the web service call, still using the same size font, but I've been unable to do this. Using .prepend doesn't seem to merge the text well, so I need something that will directly insert it into the text of the div. What should I be using? After I got the answer here I found a tutorial at this link. Should be helpful for similar tasks. A: Instead of using .prepend use .text or .html. .prepend is for DOM elements, not strings. You can retain the rest of the current text like so: $("#submitMsg").html("Your " + $(this).val() + $("#submitMsg").html());
{ "pile_set_name": "StackExchange" }
Q: Properly dismissing (or "destructing") views in Swift I'm concerned about tiny lags and memory issues, and how they might scale. My app is programmed using Swift and I've been doing everything in the app programmatically, including page navigation using presentViewController and dismissViewControllerAnimated. Note: the app's page hierarchy can be several pages deep and each page contains quite a number of images. I started experiencing tiny, occasional, lags which could appear more often on older phones; I can only test on iPhone 6 right now. I also noticed a small increase in memory while navigating through pages. Of course the memory level on the app (as observed in XCode) is not the same as opening the app in fresh state compared to going back to the first page after navigating through tens of pages, I'm expecting the memory level comparison could come at least close. Now, my question: is there a proper way to "destruct" my page views (including UIKit elements, images, etc.) when such page view is dismissed? A: I assume that by "page" you mean a viewController: There is no way to directly destroy objects with ARC (automatic reference counting), as they are deallocated automatically when their strong reference counter is zero. Since you experience unusual memory increase, it might be that you have some strong reference cycles in your code. Make sure to declare properties as weak wherever necessary. You should check out the ARC Guide for detailed explanation. I hope this helps.
{ "pile_set_name": "StackExchange" }
Q: reading sql server log files (ldf) with spark this is probably far fetched but... can spark - or any advanced "ETL" technology you know - connect directly to sql server's log file (the .ldf) - and extract its data? Agenda is to get SQL server's real time operational data without replicating the whole database first (nor selecting directly from it). Appreciate your thoughts! Rea A: to answer your question, I have never heard of any tech to read an LDF directly, but there are several products on the market that can "link-clone" a database almost instantly by using some internal tricks. Keep in mind that the data is not copied using these tools, but it allows instant access for use cases like yours. There may be some free ways to do this, especially using cloud functions, or maybe linked-clone functions that Virtual Machines offer, but I only know about paid products at this time like Dell EMC, Redgate's and Windocks. The easiest to try that are not in the cloud are: Red Gate SQL Clone with a 14 day free trial: Red Gate SQL Clone Link Windocks.com (this is free for some cases, but harder to get started with)
{ "pile_set_name": "StackExchange" }
Q: Adding a custom initWith? If I create a custom initWith for an object do I essentially include the code I would add should I want to override init? -(id) init { self = [super init]; if (self) { NSLog(@"_init: %@", self); } return(self); } e.g. -(id) initWithX:(int) inPosX andY:(int) inPosY { self = [super init]; if(self) { NSLog(@"_init: %@", self); posX = inPosX; posY = inPosY; } return(self); } gary A: You can create one designated initializer that accepts all parameters that you want to make available in initialization. Then you call from your other -(id)init your designated initializer with proper parameters. Only the designated initializer will initialize super class [super init]. Example: - (id)init { return [self initWithX:defaultX andY:defaultY]; } - (id)initWithPosition:(NSPoint)position { return [self initWithX:position.x andY:position.y]; } - (id)initWithX:(int)inPosX andY:(int)inPosY { self = [super init]; if(self) { NSLog(@"_init: %@", self); posX = inPosX; posY = inPosY; } return self; } The designated initializer is -(id)initWithX:andY: and you call it from other initializers. In case you want to extend this class you call your designated initializer from subclass. A: I'd suggest creating one main initializer that handles most of the work. You can then create any number of other initializers that all call this main one. The advantage of this is if you want to change the initialization process, you'll only have to change one spot. It might look like this: -(id) initWithX:(float)x { if (self = [super init]) { /* do most of initialization */ self.xVal = x; } return self; } -(id) init { return [self initWithX:0.0f]; } In this example initWithX: is our main initializer. The other initializer (init) simply calls initWithX: with a default value (in this case 0). A: Yes, that's exactly how I do it. One slight change will cut out a line of code: if (self = [super init]) { As opposed to: self = [super init]; if(self) {
{ "pile_set_name": "StackExchange" }
Q: What is the number of people that leave the meeting? In a business meeting, each person shakes hands with each other person, with the exception of Mr. L. Since Mr. L arrives after some people have left, he shakes hands only with those present. If the total number of handshakes is exactly 100, how many people left the meeting before Mr. L arrived? (Nobody shakes hands with the same person more than once.) The question is from CMI2011 UG entrance exam paper. A: Let $n$ be the total number of people at the meeting before Mr. L arrived. Then the number of handshakes will be $\dfrac{n(n-1)}{2}$. Suppose $m$ people left before Mr. L arrived .So he shakes $n-m$ hands. Then \begin{align*} \frac{n(n-1)}{2}+n-m & =100\\ n^2+n-2m & = 200\\ m & = \frac{n(n+1)}{2}-100. \end{align*} But $0 < m < n$ (assuming that at least one person left). So we want \begin{align*} 0 & < \frac{n(n+1)}{2}-100 < n\\ 200 & < n(n+1) < 2n+\color{red}{200}. \end{align*} edit: I had made a typo because of which my initial conclusion was incorrect: The first inequality suggests that $n \geq 14$ but the second inequality suggests $n \leq 14$. So $n=14$ is the answer. This yields $m=5$.
{ "pile_set_name": "StackExchange" }
Q: How to draw lines on the bitmap used in ImageViewZoom? I recently started using ImageViewZoom (https://github.com/sephiroth74/ImageViewZoom) and what I'm going to do is to draw some lines on the bitmap used in this View from time to time. I tried to do it in the following way, but the result is that the View is no longer able to zoom. protected void onDraw(Canvas canvas) { // TODO Auto-generated method stub super.onDraw(canvas); Canvas bmp_canvas = new Canvas(bmp);//bmp is the original bitmap Paint paint = new Paint(); //Draw map paint. setColor(Color.BLUE); paint. setStrokeWidth(10); int i; for(i=0; i<toDraw.size();i++) { Segment now = toDraw.get(i); //toDraw is a List and stores the lines PointType tmp_start = now.s; PointType tmp_end = now.e; bmp_canvas.drawLine((float)tmp_start.x, (float)tmp_start.y, (float)tmp_end.x, (float)tmp_end.y, paint); } Matrix matrix = getImageViewMatrix(); setImageBitmap(bmp, matrix, ZOOM_INVALID, ZOOM_INVALID); return; } So what is the correct way to do it? Thank you very much! A: Well, I solved it myself! I did it in the following way: public void drawMap(Bitmap bmp) //a new function outside of onDraw() { Bitmap now_bmp = Bitmap.createBitmap(bmp); Canvas canvas = new Canvas(now_bmp); Paint paint = new Paint(); //Draw map paint. setColor(Color.BLUE); paint. setStrokeWidth(10); int i; for(i=0; i<toDraw.size();i++) { Segment now = toDraw.get(i); PointType tmp_start = now.s; PointType tmp_end = now.e; canvas.drawLine((float)tmp_start.x, (float)tmp_start.y, (float)tmp_end.x, (float)tmp_end.y, paint); } Matrix matrix = getDisplayMatrix(); setImageBitmap(now_bmp, matrix, ZOOM_INVALID, ZOOM_INVALID); } In short, just create a Canvas with the origin Bitmap, then draw something on it, the result will be stored in the bitmap, and get the current matrix, and set the new bitmap to the ImageViewZoom, that's all.
{ "pile_set_name": "StackExchange" }
Q: How do I apply AddHandler using OnCommand in ASP.NET I've been racking my brain trying to get this to work. My event for my LinkButton isn't firing. I'm figuring that it has SOMETHING to do with ViewState and that the button is not there when it tries to fire the event after the Postback or something. When I click the Add button,it adds the link to the page and then when I click the Diplay Time" linkbutton it should fire the event and display the CommandArgument data but it's not and i can't figure out why. Here's my code: <%@ Page Language="VB" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) End Sub Protected Sub btnDelete_OnCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.CommandEventArgs) Response.Write(e.CommandArgument) End Sub Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Dim btn As New LinkButton() btn.ID = "lbn" btn.Text = "Display Time" btn.ValidationGroup = "vgDeleteSigner" AddHandler btn.Command, AddressOf btnDelete_OnCommand btn.CommandArgument = Now.TimeOfDay.ToString() btn.EnableViewState = True Panel1.Controls.Add(btn) End Sub </script> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" /> <asp:Panel ID="Panel1" runat="server"> </asp:Panel> </div> </form> </body> </html> A: The reason that's happening is that your dynamic button "lbn" needs to be drawn again on post back when it's clicked because the button doesn't exist after you click it. Basically you just have to dynamically add the button to the page again on post back of click of that button. I would recommend having the button already on the page but visible = false and then just showing it when you click the other button.
{ "pile_set_name": "StackExchange" }
Q: Constant Password Checking? I have read on stackoverflow the following: never store the users password or even a hash of the password in session or cookie data. I'm in the middle of making a system to check for a constant password, if it's different from one saved in a session, then force a logout; something like facebook does? When you change your password, or a password has been changed, you get logged out. My code follows below: function ConstantPassword($Password) { if ($_SESSION['Password'] !== $Password) { include "Logout.php"; } } But, If it's said not to store passwords in a session/cookie? What could be another workaround for this? A: You can do the check once, and then store a $_SESSION['logged_in'] = TRUE variable. On logging out, you unset($_SESSION['logged_in']) it and session_destroy() the session. No need to put the password nor the salt in the session. Also, you should not implement passwords on your own but instead, use this: https://github.com/ircmaxell/password_compat It's the library that's going to be in PHP 5.5.
{ "pile_set_name": "StackExchange" }
Q: How to get objects correctly placed when zoomed in on fabricjs canvas? I'm using fabricjs to load an image, use the mouse wheel to zoom on pointer position, and click to add a circle. When no zoom, objects are created where clicked. When zoomed in, the only circle that is placed correctly is where you zoom in on (don't move the mouse after zoom, and click). If you click anywhere else while zoomed in, the circle is placed elsewhere. Which you can see after zooming out. I've gone through many stack answers with related. Tried many things. No solution has worked. I'm very new to fabricjs, and the whole positioning system seems unnecessarily complicated. How can I get the circle to the place where clicking on the image even when zoomed in? https://jsfiddle.net/wonx3qvd/ Thanks in advance. canvas.on('mouse:wheel', function (opt) { var delta = opt.e.deltaY; var pointer = canvas.getPointer(opt.e); var zoom = canvas.getZoom(); zoom = zoom - delta * 0.01; if (zoom >= 20) { zoom = 20; } if (zoom <= 1) { zoom = 1; canvas.viewportTransform = [1, 0, 0, 1, 0, 0] } canvas.zoomToPoint({ x: opt.e.offsetX, y: opt.e.offsetY }, zoom); canvas.forEachObject(function (o) { o.setCoords(); }); opt.e.preventDefault(); opt.e.stopPropagation(); }); canvas.on('mouse:up', function (opt) { if (opt.button === 1) { circle = new fabric.Circle({ left: opt.e.offsetX, top: opt.e.offsetY, radius: 10, strokeWidth: 3, stroke: 'red', fill: null, opacity: .5, selectable: false, originX: 'center', originY: 'center' }); circle.setCoords(); group.addWithUpdate(circle); canvas.renderAll(); canvas.calcOffset(); } }); A: Just set your cursor as the input coorinates for your cirlce object... var pointer = canvas.getPointer(); circle = new fabric.Circle({ left: pointer.x, top: pointer.y, radius: 10, strokeWidth: 3, stroke: 'red', fill: null, opacity: .5, selectable: false, originX: 'center', originY: 'center' }); var vw = $('#container').width(); var vh = $('#container').height(); var canvas, group, image = {}; // to be avail throughout $('#container').append('<canvas id="canvasview" width="' + vw + '" height="' + vh + '"></canvas>'); var canvas = new fabric.Canvas("canvasview", { fireRightClick: true, stopContextMenu: false }); canvas.setWidth(vw); canvas.setHeight(vh); canvas.imageSmoothingEnabled = false var ogi = $('img'); $(ogi).on('load', function() { // had to do this slop in particular case oiw = ogi.width(); var ogs = ogi.attr('src'); ogi.remove(); var img = document.createElement("img"); img.src = ogs; img.setAttribute("id", "photo"); //image ratio var nw = img.width * vh / img.height; image = new fabric.Image(img, {}); image.scaleToHeight(vh); image.center(); var name = new fabric.Text("WALLPAPERIMAGE", { left: 0, top: 0, fontSize: 10, cornerSize: 6 }); group = new fabric.Group([image, name], { lockMovementX: true, lockMovementY: true, hasControls: false, hasBorders: false, hasRotatingPoint: false, subTargetCheck: true, selectable: false }); canvas.add(group); group.scaleToHeight(vh); group.clipPath = image; group.center(); group.setCoords(); canvas.renderAll(); }); canvas.on('mouse:wheel', function(opt) { var delta = opt.e.deltaY; var pointer = canvas.getPointer(opt.e); var zoom = canvas.getZoom(); zoom = zoom - delta * 0.01; if (zoom >= 20) { zoom = 20; } if (zoom <= 1) { zoom = 1; canvas.viewportTransform = [1, 0, 0, 1, 0, 0] } canvas.zoomToPoint({ x: opt.e.offsetX, y: opt.e.offsetY }, zoom); canvas.forEachObject(function(o) { o.setCoords(); }); opt.e.preventDefault(); opt.e.stopPropagation(); }); canvas.on('mouse:up', function(opt) { if (opt.button === 1) { //set your cursor as the input coordinates var pointer = canvas.getPointer(); circle = new fabric.Circle({ left: pointer.x, top: pointer.y, radius: 10, strokeWidth: 3, stroke: 'red', fill: null, opacity: .5, selectable: false, originX: 'center', originY: 'center' }); circle.setCoords(); group.addWithUpdate(circle); canvas.renderAll(); canvas.calcOffset(); } }); #container { width: 600px; height: 400px; } <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.4.0/fabric.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="container"> </div> <img src="https://wallpaper-gallery.net/top/wallpapers-1.jpg" />
{ "pile_set_name": "StackExchange" }
Q: Using combineLatest with UITextFields in RAC 3+ I would like to simply "combine" the signals emitted by a number of textfields and fire a block of code. It seems there are a few ways this "should" work using methods like combineLatest() or the values: SignalProducer initializer. But I am not able to get anything to compile or function as expected. RAC documentations uses the following example combineLatest(numbersSignal, lettersSignal) |> observe(next: println, completed: { println("Completed") }) But I am not able to compile this kind of usage I am able to do the following with redundant blocks... locationTextfield.rac_textSignal().toSignalProducer() |> start(next: { txt in println(txt) }) aircraftTextfield.rac_textSignal().toSignalProducer() |> start(next: { txt in println(txt) }) I also am not understanding why I need to use toSignalProducer() and start rather than just observing the rac_textsignal itself. This "compiles" but nothing seems to be sent on the signal unless a producer is created and started. This question/answer ReactiveCocoa combine SignalProducers into one also works, but still seems like a work around, and doesn't explain why signal producers need to be created rather than observing the original rac_textSignal()s A: Observing rac_textSignal without transformations is possible, we just need to clarify that rac_textSignal is RACSignal. RACSignal is the ReactiveCocoa 2.0 signal and is related to the Objective-C version. So you need to apply RAC2 operators to such signals, combineLatestWith: could help you to solve such task. Transformations are necessary to apply Swift operators due to diff in the basic concept in RAC3. In RAC2 such core entity was RACSignal, against Signal and SignalProducer in the RAC3.
{ "pile_set_name": "StackExchange" }
Q: VARCHAR2 should perhaps be DT_WSTR when working with SSIS against a Oracle Database? When using SSIS with Oracle database, it seems to always assume that a VARCHAR2 maps to a DT_STR. However, if my Oracle encoding is set to AL32UTF8, I should be able to store any unicode character in a VARCHAR2, right? Is there any way to force SSIS to map an Oracle VARCHAR2 to a DT_WSTR? Should there be? I looked up a few other questions on this, but nothing seems to address it. I have a data source that has many columns as DT_WSTR, and I want each to go into a VARCHAR2 column without having to convert every column. A: Looks like I need to be careful to specify my column length in CHAR. For example, Instead of VARCHAR2(255), I need to ensure it is VARCHAR2(255 CHAR). If I do this, SSIS sees it as DT_WSTR.
{ "pile_set_name": "StackExchange" }
Q: I can't ping from my server to google.com, how can I diagnose issue? I'm on my server and I can't ping anything outside. I tried for example google.com. How can I diagnose this issue? I can ping my localhost (ping works) This is my traceroute to google.com: [root@ip-10-112-63-16 tony]# traceroute google.com traceroute to google.com (74.125.113.147), 30 hops max, 40 byte packets 1 * * * 2 * * * 3 * * * 4 * * * 5 * * * 6 * * * 7 * * * 8 * * * 9 * * * 10 * * * 11 * * * 12 * * * 13 * * * 14 * * * 15 * * * 16 * * * 17 * * * 18 * * * 19 * * * 20 * * * 21 * * * 22 * * * 23 * * * 24 * * * 25 * * * 26 * * * 27 * * * 28 * * * 29 * * * 30 * * * And this is the result of route -n: [root@ip-10-112-63-16 tony]# /sbin/route -n Kernel IP routing table Destination Gateway Genmask Flags Metric Ref Use Iface 10.112.62.0 0.0.0.0 255.255.254.0 U 0 0 0 eth0 0.0.0.0 10.112.62.1 0.0.0.0 UG 0 0 0 eth0 And these are my iptables: [root@ip-10-112-63-16 tony]# /sbin/iptables -L Chain INPUT (policy ACCEPT) target prot opt source destination Chain FORWARD (policy ACCEPT) target prot opt source destination Chain OUTPUT (policy ACCEPT) target prot opt source destination A: According to this (http://aws.amazon.com/articles/1145) EC2 blocks ICMP by default. You need to issue this command to allow it ec2-authorize default -P icmp -t -1:-1 -s 0.0.0.0/0
{ "pile_set_name": "StackExchange" }
Q: How to focus same input after onSubmitEditing? I want to focus again to the same input after onSubmitEditing function. But couldn't achieve yet. Any help would be appreciated. Here is my code: <Input ref='barcode' style={styles.barcodeInput} autoFocus={true} onChangeText={(text) => { this.setState({barcodeNumber: text}); }} onSubmitEditing={(event)=> { this.getResult(); }} placeholder='Barcode Number'/> getResult(){ if ( this.state.barcodeNumber === '021200507878' ){ this.setState({backgroundColor: '#2ecc71', status:'success'});//green } else { this.setState({backgroundColor: '#c0392b', status:'error'}); //red } this.clearText('barcode'); } clearText(fieldName) { this.refs[fieldName].setNativeProps({text: ''}); } I know how to do it by button or by other input field's submit. But i can not do it with the same input. A: Oh, how fool i am. Just add the below line into the TextInput will work. blurOnSubmit={false}
{ "pile_set_name": "StackExchange" }
Q: How to display invalid call exceptions from fluent controller in MVCContrib? How can I pass the exception thorwn by the action in MVCContrib.FluentController CheckValidCall(action)? [ExportModelStateToTempData] public ActionResult Index(int itemId, int page) { return CheckValidCall(() => MyService.GetResults(itemId, page)) .Valid(x => View(x)) .Invalid(() => RedirectToAction(RestfulAction.Index)); } When GetResults() throws exception I want to display it in the view. I've tired ModelState <%if (ViewData.ModelState.ContainsKey("_FORM")) {%> <div class="notificationError"> <%= ViewData.ModelState["_FORM"].Errors.FirstOrDefault().ErrorMessage %> </div> <%}%> but the ModelState is valid and contains no errors. Is there any way to access the exception message without wrapping service method in try-catch block? If it helps here is my unit test to check ModelState which fails as TestController.ModelState.IsValid is true: [Fact] public void ServiceExceptionIsConvertedToModelStateErrorInFluentController() { // Set up MockService.Setup(x => x.GetResults(It.IsAny<int>(), It.IsAny<int>())) .Throws(new InvalidOperationException("Mocked Service Exception")); // Excercise Assert.Throws<InvalidOperationException>(() => TestController.GetResults(1, 1)); // Verify Assert.False(TestController.ModelState.IsValid); Assert.True(TestController.ModelState["_FORM"].Errors.Count > 0); } A: I've manage to pass exception into ModelState by overriding MvcContrib.FluentController.AbsteactFluentController.ExecuteCheckValidCall(Func action): protected override object ExecuteCheckValidCall(Func<object> action) { try { return base.ExecuteCheckValidCall(action); } catch (Exception exception) { ModelState.AddModelError("_Exception", exception); return null; } } Which is called by CheckValidCall. However the method is described as "public for testing purposes only and shouldn't be used" the alternative way of doing it is to override MvcContrib.FluentController.AbstractFluentController.CheckValidCall().
{ "pile_set_name": "StackExchange" }
Q: Check if a Cookie exists or not? I am trying to find out if a cookie exists or not, if it doesn't I want to create it. I am doing this in Internet Explorer and its stopping at if(readCookie(count) == null) of the code below. if(readCookie("count") == null) { createCookie("count", 0, 10); } function readCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null; } What am I doing wrong here? A: Try using undefined instead of null See the following link: http://jsfiddle.net/sssonline2/D38WM/1/ Tested on both IE and FireFox Here's a Stack Overflow link for more info: typeof !== "undefined" vs. != null
{ "pile_set_name": "StackExchange" }
Q: C++ while loop with 2 conditions, VS. for loop with 2 conditions? If I wanted to iterate through a string, and stop once I found either the letter "o" or the end of the string, would it make any difference to use a while loop to check the 2 conditions, or a for loop with 2 conditions? const int STRING_SIZE = 16; char str[STRING_SIZE] = "a bunch of words"; for loop for (int i = 0; i < STRING_SIZE && str[i] != 'o'; i++){ //do something } while loop int i = 0; while (i < STRING_SIZE && str[i] != 'o'){ //do something i++ } Is there a performance difference between the two? Is one better practice than the other? A: There is no difference in performance between the two loops except that: for() Checks condition then if true its body is executed. So for is simile to while loop. do-while loop works a slightly different: It executes then checks so at least an execution is ensured.
{ "pile_set_name": "StackExchange" }
Q: assigning an R object to run a chain of command I am learning to use bookdown to render a PDF and Word document simultaneously from the same Rmd file. Since I want to view the PDF output using Sumatra PDF reader, which cannot auto reload modified documents for documents shown in the ebook UI (refer to ReloadModified Documents in https://www.sumatrapdfreader.org/settings.html). I have created a single line to run everytime when I render the PDF file and view it in Sumatra PDF reader like below: bookdown::render_book('index.Rmd',output_format = 'all',new_session = TRUE,preview=TRUE); system('cmd.exe',input='taskkill /IM SumatraPDFPortable.exe'); system('cmd.exe',input='"C:/PortableApps/SumatraPDFPortable/SumatraPDFPortable.exe" "E:/output.pdf"') I would like to know if it is possible to assign a R object (say: rendernow) to this line so that every time when I type "rendernow" and enter in R console, the above line will be executed. Thanks! A: Just make it a function: rendernow <- function() { bookdown::render_book('index.Rmd',output_format = 'all',new_session = TRUE,preview=TRUE); system('cmd.exe',input='taskkill /IM SumatraPDFPortable.exe'); system('cmd.exe',input='"C:/PortableApps/SumatraPDFPortable/SumatraPDFPortable.exe" "E:/output.pdf"') } Then you can invoke it via rendernow() (so you need the parenthesis) Just for the fun of it, here's a solution where you do not need the parenthesis: rendernow <- structure("", class = "rendernow") print.rendernow <- function(x, ...) { bookdown::render_book('index.Rmd',output_format = 'all',new_session = TRUE,preview=TRUE); system('cmd.exe',input='taskkill /IM SumatraPDFPortable.exe'); system('cmd.exe',input='"C:/PortableApps/SumatraPDFPortable/SumatraPDFPortable.exe" "E:/output.pdf"') } Then you just type rendernow and your steps are invoked.
{ "pile_set_name": "StackExchange" }
Q: CSS styling for paragraph not taking effect in head but takes effect when declared in the body I'm fairly a newbie at HTML and CSS. I've been following procedures on w3schools and also experimenting with things on my own. One of the first problems I've faces so far is in this code: <!DOCTYPE html> <html> <head> <title>vector5 - Home</title> <link href="https://fonts.googleapis.com/css?family=Roboto:100" rel="stylesheet"> <style> <!-- Link Styling-->a { text-decoration: none; color: #6a9496; } a:visited { text-decoration: none; color: #6a9496; } a:hover { text-decoration: none; color: #6a9496; } a:focus { text-decoration: none; color: #6a9496; } a:active { text-decoration: none; color: #6a9496; } <!-- Paragraph Styling-->p { margin-top: 0px; margin-bottom: 0px; margin-right: 250px; margin-left: 100px; border: 10px solid powderblue; color: #757575; text-align: justify; font-size: 100%; font-family: 'Roboto', sans-serif; } </style> <link rel="shortcut icon" href="favicon.ico" type="image/x-icon"> </head> <body style="background-color: #99bfc1;"> <h1 style="color: #6a9496; font-family: 'Roboto'; font-size: 200%;">Lorem Di Ipsum</h1> <p style="margin-top: 0px; margin-bottom: 0px; margin-right: 250px; margin-left: 100px; border: 10px solid powderblue; color: #757575; text-align: justify; font-size: 100%; font-family: 'Roboto', sans-serif;" title="Lorem Di Ipsum"> Lorem Ipsum is simply dummy text of the printing and typesetting industry, used for <b><abbr title="Hypertext Markup Language">HTML</abbr></b> and design in modern times. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when a unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing cursive cursive Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. To learn more about the <i>'Lorem Di Ipsum test'</i>, you can visit <a href="https://www.cs.tut.fi/~jkorpela/www/justify.html" style="text-decoration: none;" target="_blank">this website</a>. </p> </body> </html> The styling for the paragraph works when I attribute it as a style with the paragraph element. However, when I deleted the style attributes with the paragraph element in the body and left the paragraph css styling in the head, within the style elements, the text in the browser reverted back to the default text (black Times New Roman font). I don't understand what is going on or why my code works for the body, can anyone shed some light on this? I also have another question. What should I do if I want to use the same font in the paragraph, but of different thickness? A: You are using a HTML comment in CSS either remove the comment or change too. /*'Paragraph Styling' */
{ "pile_set_name": "StackExchange" }
Q: Confused about finding non-brute force way to solve for matrix to the 2019th power I am attempting to solve this problem, it has four parts. I solved part a (a trivial matrix problem), but the next three parts appear to be a bit confusing to me. I just would like some help getting started so I can see and observe this matrix and come up with a solution. The Questions Note: The idea here is NOT to use brute force computation to get $A^{2019}$ matrix, instead use some observations which can significantly reduce computational work and will also give you an insight into such problems. Obviously this is some huge numbered matrix, but I do not understand what observation will reduce this? My first thought was just to use a calculator and calculate $A^{2019}$ and then just multiply that by each vector. But that appears to be not the point of the question. $$ Let A = \left[\begin{array}{rrr} -4 & -6 & -12 \\ -2 & -1 & -4 \\ 2 & 3 & 6 \end{array}\right] $$ And Let $u$ = [6 5 -3], $v$ = [-2 0 1], and $w$ = [-2 -1 1]. b). Compute $A^{2019}\mathbb v$ A: I assume that you're asking about $A^{2019}v$. To that end, observe that $Av = 2v$ (I'll leave it to you to verify that this is true). It follows that $$ A^2v = AAv = A(2v) = 2Av = 4v. $$ Similarly, $A^3 v = 8v$, and in general we have $A^k v = 2^k v$ for any positive integer $k$.
{ "pile_set_name": "StackExchange" }
Q: what is the code for table rates shipping method & cash on delivery" payment method I am using this shipping "Table rates" and "webshopapp matrix rates" shipping methods. what i need is that , if we use table rates shipping method, i want to hide "cash on delivery" payment method. i am following this link : https://stackoverflow.com/questions/26604267/magento-onepage-checkout-hide-payment-method-depending-on-shipping-method please help me to find what is the code for 1)table rates shipping method 2)cash on delivery" payment method.... A: AS i have seen in your reference link you can also see code for 1) table rates shipping method == flatrate_flatrate 2) cash on delivery" payment method. == cashondelivery EDIT class Mage_Shipping_Model_Carrier_Tablerate extends Mage_Shipping_Model_Carrier_Abstract implements Mage_Shipping_Model_Carrier_Interface { /** * code name * * @var string */ protected $_code = 'tablerate'; } Simple Magento shipping method code <pre>Array ( [0] => Array ( [value] => Array ( [0] => Array ( [value] => flatrate_flatrate [label] => Fixed ) ) [label] => Flat Rate ) [1] => Array ( [value] => Array ( [0] => Array ( [value] => freeshipping_freeshipping [label] => Free ) ) [label] => Free Shipping ) [2] => Array ( [value] => Array ( [0] => Array ( [value] => tablerate_bestway [label] => Table Rate ) ) [label] => Best Way ) [3] => Array ( [value] => Array ( ) [label] => Best Way ) ) i am sure it will help you.
{ "pile_set_name": "StackExchange" }
Q: Invalid Date Issue but Date is Invalid I have a date format 03.03.2016 20:01 And I have a code aData._date = new Date(aData[3]).getTime(); error is that date is invalid but, at different computer it worked well but now it is not working .What is the problem? Thanks in advance A: What is the problem? Parsing of strings using the Date constructor (or Date.parse, they are equivalent for parsing) is largely implementation dependent and is not recommended. Manually parse strings, either with a small function if you only have to deal with a single format, or use a library (there are many good ones to choose from) and provide the format otherwise. ECMAScript 2015 specifies that Date.parse correctly parse ISO 8601 extended format dates, however any other format is implementation dependent. Many browsers in use do not correctly (i.e. per the specification) parse ISO 8601 format dates either. "03.03.2016 20:01" is not an ISO 8601 date format. Assuming it's DD.MM.YYYY hh:mm it can be parsed as a local date and time using: function parseDMYHM(s){ var b = ('' || s).split(/\D/); return new Date(b[2], b[1]-1, b[0], b[3], b[4]); } document.write(parseDMYHM('03.03.2016 20:01')); Or if you have a library with a parse function that accepts a format to parse (as such libraries that are any good will), using something like: var d = parse('03.03.2016 20:01', 'DD.MM.YYYY hh:mm');
{ "pile_set_name": "StackExchange" }
Q: Enumerated constants property does not stream Given the following type declaration: TMyEnum = (onehundred,twohundred,threehundred); TMyEnum2 = (Aonehundred = 100 , Atwohundred = 200 , Athreehundred = 300); TMyComponent = class(TComponent) private FMyEnum: TMyEnum; FMyEnum2: TMyEnum2; published property MyEnum: TMyEnum read FMyEnum write FMyEnum; property MyEnum2: TMyEnum2 read FMyEnum2 write FMyEnum2; end; using TStream.WriteComponent does not stream MyEnum2. Does anybody know why that is, and if this can be fixed ? A: Unfortunately this is a limitation of the streaming system. The documentation says (emphasis mine): Some properties, although publishable, are not fully supported by the streaming system. These include properties of record types, array properties of all publishable types, and properties of enumerated types that include anonymous values. If you publish a property of this kind, the Object Inspector will not display it correctly, nor will the property's value be preserved when objects are streamed to disk. You can't workaround that easily and would need to provide your own custom streaming.
{ "pile_set_name": "StackExchange" }
Q: Unable to connect to Postgres on Vagrant Box - Connection refused? First off, I'm new to Vagrant and Postgres. I created my Vagrant instance using http://files.vagrantup.com/lucid32.box without any trouble. I am able to run vagrant up and vagrant ssh without issue. I followed the instructions with one minor alteration, I installed the "postgresql-8.4-postgis" package instead of "postgresql postgresql-contrib". I started the server using: postgres@lucid32:/home/vagrant$ /etc/init.d/postgresql-8.4 start While connected to the vagrant instance I can use psql to connect to the instance without issue. In my Vagrantfile I had already added: config.vm.forward_port 5432, 5432 but when I try to run psql from the localhost I get: psql: could not connect to server: Connection refused Is the server running locally and accepting connections on Unix domain socket "/tmp/.s.PGSQL.5432"? I'm sure I am missing something simple. Any ideas? Update: I found a reference to an issue like this and the article suggested using: psql -U postgres -h localhost with that I get: psql: server closed the connection unexpectedly This probably means the server terminated abnormally before or while processing the request. A: The instructions from the blog post you mentioned are not right at all for ubuntu: they use pieces from the installation of a self-compiled server that don't mix well with a packaged version. One should not create /usr/local/pgsql/data and run initdb to that directory, because the ubuntu package uses /var/lib/postgresql/<pg-version-number>/<cluster-name> and runs initdb on behalf of the the user. The error mentioning "/tmp/.s.PGSQL.5432" shows that the expected location for this file is incorrect (for ubuntu). It should be in /var/run/postgresql. This is probably due to running initdb manually with parameters that are incompatible with ubuntu. The postgresql.conf and pg_hba.conf files to edit to enable non-local connections should be inside /etc/postgresql/8.4/main, and not /usr/local/pgsql/data. The /etc/init.d/postgresql-8.4 should be launched by root (as everything else in /etc/init.d), not by the postgres user. PGDATA should not be set manually, because again it really gets in the way of how the ubuntu postgres packages works. My answer would be to purge and reinstall the postgresql-8.4 package without following any of the instructions from the blog post. postgresql-8.4-postgis depends on postgresql-8.4 so it will be removed as well. Also make sure to undo the setting of PGDATA in /etc/bash.bashrc.
{ "pile_set_name": "StackExchange" }
Q: Displaying better error message than "No JSON object could be decoded" Python code to load data from some long complicated JSON file: with open(filename, "r") as f: data = json.loads(f.read()) (note: the best code version should be: with open(filename, "r") as f: data = json.load(f) but both exhibit similar behavior) For many types of JSON error (missing delimiters, incorrect backslashes in strings, etc), this prints a nice helpful message containing the line and column number where the JSON error was found. However, for other types of JSON error (including the classic "using comma on the last item in a list", but also other things like capitalising true/false), Python's output is just: Traceback (most recent call last): File "myfile.py", line 8, in myfunction config = json.loads(f.read()) File "c:\python27\lib\json\__init__.py", line 326, in loads return _default_decoder.decode(s) File "c:\python27\lib\json\decoder.py", line 360, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "c:\python27\lib\json\decoder.py", line 378, in raw_decode raise ValueError("No JSON object could be decoded") ValueError: No JSON object could be decoded For that type of ValueError, how do you get Python to tell you where is the error in the JSON file? A: I've found that the simplejson module gives more descriptive errors in many cases where the built-in json module is vague. For instance, for the case of having a comma after the last item in a list: json.loads('[1,2,]') .... ValueError: No JSON object could be decoded which is not very descriptive. The same operation with simplejson: simplejson.loads('[1,2,]') ... simplejson.decoder.JSONDecodeError: Expecting object: line 1 column 5 (char 5) Much better! Likewise for other common errors like capitalizing True. A: You wont be able to get python to tell you where the JSON is incorrect. You will need to use a linter online somewhere like this This will show you error in the JSON you are trying to decode. A: You could try the rson library found here: http://code.google.com/p/rson/ . I it also up on PYPI: https://pypi.python.org/pypi/rson/0.9 so you can use easy_install or pip to get it. for the example given by tom: >>> rson.loads('[1,2,]') ... rson.base.tokenizer.RSONDecodeError: Unexpected trailing comma: line 1, column 6, text ']' RSON is a designed to be a superset of JSON, so it can parse JSON files. It also has an alternate syntax which is much nicer for humans to look at and edit. I use it quite a bit for input files. As for the capitalizing of boolean values: it appears that rson reads incorrectly capitalized booleans as strings. >>> rson.loads('[true,False]') [True, u'False']
{ "pile_set_name": "StackExchange" }
Q: Make Windows require password after hibernate I set password for User-Accounts and for the Windows (Using syskey), but when I turn on my system after a hibernate, it don't require neither system password nor accounts password. and directly navigate me to desktop! Why?! Note: I have this problem only after hibernate! (After a shutdown or restart everything is ok). A: Strictly speaking, the purpose of a SYSKEY password is not to lock down boot, but only to protect the system account database (the SAM). So the only time you'll be asked for it is when Windows needs to open the account database for the first time. Now, the whole point of hibernation is that it does not terminate the running OS; it merely pauses it, and later resumes the kernel and all processes completely intact. So Windows doesn't need the SYSKEY password because it already has the SAM open ever since the last time you rebooted. As for the account passwords – this needs to be enabled in the power management settings: Open Power Options by clicking the Start button Picture of the Start button, clicking Control Panel, clicking System and Security, and then clicking Power Options. On the Select a power plan page, in the task pane, click Require a password on wakeup. If necessary, click Change settings that are currently unavailable. On the Define power buttons and turn on password protection page, click Don't require a password. Click Save changes.
{ "pile_set_name": "StackExchange" }
Q: Пустое значение в заявке Кто может подсказать в чем причина? Когда нажимаю кнопку отправить, полученное значение становится NaN let input = $('#total_price'); $('button').on('click', function(){ let price = parseInt($('.'+$(this).attr('id')).text()), // раз класс "цены" и ид кнопки совпадает, то будем это использовать. check = $(this).attr('data-check'), // для проверки, типо "вкл\выкл" altText = $(this).attr('data-alt-text'); // будем менять текст на кнопке. // изменяем данные кнопки $(this) .attr({ 'data-check': (check == 1 ? 0 : 1), // заменим "статус" активации 'data-alt-text': $(this).text() // поменяем местами название кнопки }) .text(altText); // относится к смене названия местами // дальше меняем цену в инпуте let val = parseInt(input.val()); // получаем текущую цену input.val(check == 1 ? (val - price) : (val + price)); // есть "добавить", то + к цене, если "убрать", то минус. }); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form method="post" order="post.php"> <input id="total_price" type="text" value="50" readonly> <hr> <div class="price_1">1</div> <button id="price_1" data-check="0" data-alt-text="Убрать">Добавить</button> <br> <div class="price_2">2</div> <button id="price_2" data-check="0" data-alt-text="Убрать">Добавить</button> <br> <div class="price_3">3</div> <button id="price_3" data-check="0" data-alt-text="Убрать">Добавить</button> <button type="submit">Отправить</button> </form> A: Вы слушаете событие click на всех кнопках $('button'). Кнопка отправки тоже имеет тег <button>, поэтому, когда вы на неё нажимаете, загорается событие и срабатывает функционал пересчета. Быстрым фиксом будет заменить селектор на $('button[type!=submit]'). То есть слушать событие на всех кнопках, кроме кнопки, у которой атрибут type="submit".
{ "pile_set_name": "StackExchange" }
Q: WMQ V8 Connection Factory setup on Tomcat using JNDI Currently on our Tomcat configuration with JNDI is based on this recommendation which currently is working. How do I connect to a Websphere MQ (MQ Series) server using JMS and JNDI? Since we are upgrading to v8 I would like to take advantage of the JMS 2.0 features. This would require updating the jar files to the JMS 2.0 versions. So I have removed the following jars from the tomcat lib folder. com.ibm.mq.jar com.ibm.mqjms.jar connector.jar dhbcore.jar geronimo-j2ee-management_1.0_spec-1.0.jar geronimo-jms_1.1_spec-1.0.jar And replaced them with these jars. Base on this link com.ibm.mq.allclient.jar com.ibm.mq.traceControl.jar My JNDI configuration matches this configuration. <Resource name="jms/MyQCF" auth="Container" type="com.ibm.mq.jms.MQQueueConnectionFactory" factory="com.ibm.mq.jms.MQQueueConnectionFactoryFactory" description="JMS Queue Connection Factory for sending messages" HOST="<mymqserver>" PORT="1414" CHAN="<mychannel>" TRAN="1" QMGR="<myqueuemanager>"/> Now with the updated jar files I'm getting the following exceptions. Caused by: java.lang.NoClassDefFoundError: javax/jms/JMSRuntimeException at com.ibm.mq.jms.MQQueueConnectionFactoryFactory.getObjectInstance(MQQueueConnectionFactoryFactory.java:69) at org.apache.naming.factory.ResourceFactory.getObjectInstance(ResourceFactory.java:141) at javax.naming.spi.NamingManager.getObjectInstance(NamingManager.java:321) at org.apache.naming.NamingContext.lookup(NamingContext.java:842) at org.apache.naming.NamingContext.lookup(NamingContext.java:153) at org.apache.naming.NamingContextBindingsEnumeration.nextElementInternal(NamingContextBindingsEnumeration.java:117) at org.apache.naming.NamingContextBindingsEnumeration.next(NamingContextBindingsEnumeration.java:71) at org.apache.naming.NamingContextBindingsEnumeration.next(NamingContextBindingsEnumeration.java:34) at org.apache.catalina.mbeans.GlobalResourcesLifecycleListener.createMBeans(GlobalResourcesLifecycleListener.java:138) at org.apache.catalina.mbeans.GlobalResourcesLifecycleListener.createMBeans(GlobalResourcesLifecycleListener.java:110) at org.apache.catalina.mbeans.GlobalResourcesLifecycleListener.lifecycleEvent(GlobalResourcesLifecycleListener.java:82) at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:117) at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90) at org.apache.catalina.util.LifecycleBase.setStateInternal(LifecycleBase.java:402) at org.apache.catalina.util.LifecycleBase.setState(LifecycleBase.java:347) at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:724) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) ... 7 more Questions: Should I be including another jar file to the class path? Or has the configuration of JNDI changed for v8? A: Please do NOT try adding the JMS Jar found in the MQ installation. IBM has as of v8.0 repackaged JMS so that a stand-alone install of the jar files is now supported. But only if you use the complete and intact set of jars and do not mix and match them on a whim. To do so would be reckless and ill-advised. You are on the right track but for your purposes I would go grab the file from the latest 8.0.0.x MQ Client Fix Pack. I would then go to the Technote that explains the install procedure and try that. I'm sure that IBM has a process for grabbing jars from the server install, however since these appear to be packaged differently, I'd put my money on the package designed and tested for stand-alone delivery - e.g. the one I linked to above. By the way, since this is now supported if it doesn't work you can open a PMR, tell IBM you followed their instructions to the letter, and make them walk through fixing it with you. (Then post here what it was that fixed it.) But they won't do that if you just go grabbing random jar files and hope it works.
{ "pile_set_name": "StackExchange" }
Q: Android/iOS mobile browser - disable events How can I disable default mobile browser events like zoom (dblclick, expand) and options (when you hold down your finger on a screen a popup appears with options)? I tried this: document.addEventListener('ontouchstart', function(event) { event.preventDefault(); }, false); A: You can prevent the finger move(scroll the page) like this: document.addEventListener('ontouchstart', function(e) { e.preventDefault(); }); document.body.addEventListener('touchmove', function(e) { e.preventDefault(); }); And the zoom you just need to adjust the viewport like this: <meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
{ "pile_set_name": "StackExchange" }
Q: Can we get a custom Tour page? This feature request is related to PPCG not being a Q&A site. The most important part of the onboarding experience for new users (especially those who don't arrive via other sites from the network) is the tour page. Moderators can customise the first paragraph and a few details in the right column, but in the case of PPCG this is hardly enough, because the rest of the page is strongly misleading: Ask questions, get answers, no distractions Get answers to practical, detailed questions Focus on questions about an actual problem you have faced. Include details about what you have tried and exactly what you are trying to do. Ask about... None of these are things that users should actually do here. It would be great if a) those misleading bits could be removed and ideally b) replaced with some important information that applies here instead. The usual process for new users on a Q&A site is that they join the site to ask a question and then start answering others as well when they feel confident about it. Around here, we prefer users to start with solving challenges so they can get a feeling for how challenges work around here before writing their own. (Yes, CH, you are an exception to that...) The things that are most problematic are: The (already customisable) first paragraph start with "Programming Puzzles & Code Golf is a question and answer site for programming puzzle enthusiasts and code golfers." Except it's not. The first two sections "Ask questions, get answers, no distractions" and "Get answers to practical, detailed questions" are the most misleading because they tell people to use this as a Q&A site. These should instead explain how you can solve challenges here and pose your own as well (in that order). The sections about tags, edits, reputation and badges are generally alright, except that some instances of "question" could be replaced with "challenge" and that we might want to mention that edits here shouldn't be used to improve the score (comments should be used instead, as the example there already shows - although that example could possibly be improved). The final bit that sends people off to the site would probably also better be phrased in terms of "posing challenges" rather than "asking questions". "Like this site? Stack Exchange is a network of 152 Q&A sites just like it." Well... Please use the answers to suggest new content for the problematic sections. When we find a consensus what we'd rather have on the tour page, I can inform the CMs to take a look at this. A: I don't know whether to post all my stuff in a single answer or as multiple, I'll just put everything here for now. Things in {braces} are my comments, not part of the text. Most of this is just word/sentence replacement. Our changes may or may not be more extensive than this. Welcome to Programming Puzzles & Code Golf Stack Exchange Programming Puzzles & Code Golf is a site for hosting and participating in programming competitions. It's built and run by you as part of the Stack Exchange network of Q&A sites. With your help, we're working together to build a library of programming puzzles and their solutions create an environment of friendly competition, open to programming enthusiasts of all skill levels {note: kinda cheesy but IDK}. We're a little bit different from other sites {note: this is accurate}. Here's how: Ask questions, get answers, no distractions Compete in challenges, create your own, and have fun This site is all about hosting programming competitions. It's not a discussion forum or a regular Q&A site. There's no chit-chat. Just challenges... And submissions... Good submissions are voted up and rise to the top. The best submissions show up first so that they are always easy to find. The person who created the challenge can mark one submission as "accepted". Accepting doesn't mean it's the best answer, it just means that it worked for the person who asked generally indicates that it is the winner of the contest. {note: should we even mention accepted answers?} {note: I also kinda think we should change the example question that's shown to the right, the current one has a 2-line spec. This may be difficult if they are auto-selected.} Get answers to practical, detailed questions Participate in high-quality programming competitions {note: this section pretty much has to be completely rewritten. I think we should replace it with something that goes into more detail about what is/isn't appropriate here.} Focus on questions about an actual problem you have faced. Include details about what you have tried and exactly what you are trying to do. Focus on challenges which have detailed specifications and clear objectives. All challenges should have an objective winning criterion, which is a well-defined way to determine which submission is the best. {note: it might not worth our time to explain exceptions like the tips tag} Create posts about... Code golf (details) Programming puzzles Other programming contests or challenges {note: maybe include a brief list?} Certain non-challenge topics, such as tips for golfing in a specific language Not all challenges work well in our format. Avoid challenges that are primarily opinion-based, lack a clear objective, or that are likely to generate discussion rather than submissions. Challenges that need improvement may be closed placed on hold until they are improved and reopened. Tags make it easy to find interesting challenges All challenges are tagged with their subject areas and the type of competition. Each can have up to 5 tags, since a challenge might be related to several subjects. Click any tag to see a list of challenges with that tag, or go to the tag list to browse for topics that interest you. You earn reputation when people vote on your posts {note: basically keeping this as-is. Some of the s/question/challenge/gi also needs to be applied to the small image caption text.} Your reputation score goes up when others vote up your challenges, submissions and edits. As you earn reputation, you'll unlock new privileges like the ability to vote, comment, and even edit other people's posts. At the highest levels, you'll have access to special moderation tools. You'll be able to work alongside our community moderators to keep the site focused and helpful. Improve posts by editing or commenting Our goal is to have the best submissions to every challenge, so if you see challenges or submissions that can be improved, you can edit them. Use edits to fix minor mistakes, improve formatting, or clarify the meaning of a post. Edits shouldn't be used to change the informational content of other users' posts, or to change other users' programs. Use comments to ask for more information, clarification, or to suggest improvements to posts. You can always comment on your own posts. Once you earn 50 reputation, you can comment on anybody's post. Remember: we're all here to learn, so be friendly and helpful! Unlock badges for special achievements {note: nothing really to change here either} Badges are special achievements you earn for participating on the site. They come in three levels: bronze, silver, and gold. In fact, you've already earned a badge: Informed Read the entire tour page Participate in an existing challenge, or create your own {note: I wonder if we could add a link to/explanation of the sandbox here} See new challenges Create a challenge Looking for more in-depth information on the site? Visit the Help Center Programming Puzzles & Code Golf Stack Exchange is part of the Stack Exchange network Like this site? Stack Exchange is a network of 152 Q&A sites just like it. Check out the full list of sites.
{ "pile_set_name": "StackExchange" }
Q: New Yorker Dieresis Rule; prosaic, unionized? There are lots of informal references to the traditional / "New Yorker" style of using diereses to disambiguate runs of vowels, however I have yet to find a definitive guide. See, for example: http://www.newyorker.com/online/blogs/culture/2012/04/the-curse-of-the-diaeresis.html http://en.wikipedia.org/wiki/Diaeresis_(diacritic) What is the standard rule for using or not using hyphen and diaeresis on the words like reelect , reexamine, and cooperate? My major question is: Is there a definitive reference that one can consult for proper traditional use of the dieresis in English? The accepted answer in last link above outlines some cases (e.g., no dieresis in "coalesce" or "react") but notably does not provide a reference to an authoritative source. My minor questions are: Is it appropriate to use a dieresis in "prosaïc?" How does one most correctly differentiate the two words spelled "unionized" ("union-ized" about the formation of a group or "un-ionized" about how many free electrons a material has)? Assume for a moment that you have to write both within the same document. A: There are lots of informal references to the traditional / "New Yorker" style of using diereses to disambiguate runs of vowels, however I have yet to find a definitive guide. The definitive guide to the "New Yorker" style, is that you submit a piece to the New Yorker, and if it is accepted for publication it will be cast into that orthography whether you had originally attempted it or not. The earlier traditional use of diæreses do not have a definitive guide, because it is traditional, and as such was never consistent. It also isn't really all that traditional, and never dominated English orthography, though it certainly was once more common than before: It was a traditional way of writing, not the traditional way. And, to dash your hopes of finding a definitive guide further, it was, and remains, used to different degrees by some than by others. Today, it would still be very common to use a diæresis with a proper noun, like Zoë, Chloë, or Boötes. Likewise with related proper adjectives. Overlapping with that, it would be much more common to use it in a foreign loan-word that had the diæresis in the original spelling (likewise its identical cousin the umlaut). This though raises another question; how long is a word in English before it is no longer a loan-word? It also brings up a point about how the language has changed, for not only have loan-words become more and more considered to be fully English, but also writers' sensitivity to the foreignness of loan-words has declined so the average scribe is less likely to choose to italicise in a given case than they would a couple of centuries ago. Of such words, perhaps naïve and its relatives (naïf, naïvety, etc.) may be the only word both widely known as English and widely retaining the diacritic it brought with it from France even though it is now 400 years in English use. Perhaps the very fact that it is learnt of relatively early in a child's developing vocabulary that makes it retain the mark; children learn it as "the one with the dots" just as they learn fo'c's'le as "the one with all the apostrophes" and so a general tendency to remove diacritics is resisted just as the general tendency to reduce apostrophes to a ration of one per word. At the other extreme, those who did (or remain) fond of its use, have no logical reason for avoiding it in react and reaction, beyond the simple fact that it is so commonly seen without one that even the most given to affected feel slightly silly using it. In-between, some would use it where there was primary stress on the second vowel, and some more widely. Similarly, many (relatively speaking) would use it where the word was formed by joining two parts, particularly where another might be tempted to hyphenate. Many would take how likely they thought mispronunciation would be without it. There is no doubt some influence too from the lack of such a mark in the Latin source; it coming from Latin already joined rather than combined from re- and act in English, but that also applies to some words where one does see it: It's an influence perhaps, but not a self-sufficient reason. Is it appropriate to use a dieresis in "prosaïc". It would be technically defensible on the basis of the French prosaïque. Some would only use the diæresis when the primary stress is on the second syllable, and so not use it. Some who would tend to use the diæresis anyway still wouldn't as it is so well-known without and not (unlike the also well-known coöperation for example) formed from combining two parts. The New Yorker, incidentally, spells it prosaic. How does one most correctly differentiate the two words spelled "unionized" ("union-ized" about the formation of a group or "un-ionized" about how many free electrons a material has)? From context. Assume for a moment that you have to write both within the same document. As a rule even in the same document the two adjectives are unlikely to be applied to very similar subjects or objects, though certainly if workers are finding themselves ionised on a regular basis they definitely need to organise into a trade union. As such, it's unlikely to cause that much difficulty here. If though, you really wanted to distinguish them orthographically, then the diæresis is not going to be of any help. Note that the hyphen is allowed, albeit unpopular, in one but not the other. Hence: "Organised into a trade union": unionised/unionized "Not ionised": un-ionised/un-ionized "Not made more Ionian": un-Ionised/un-Ionized or even un-Ionicised/un-Ionicized.
{ "pile_set_name": "StackExchange" }
Q: CentoOS SSH Access I'm executed this commands with root user i'm on a CentOS 6.3 server: #useradd newuser #passwd newuser #visudo then I added this line at end of file: AllowUsers newuser #service sshd restart #exit Now, I can't access server with deployer or root user! Both accounts return: **Permission denied, please try again.** Any suggestions? EDIT: Why add AllowUsers newuser dont allows newuser to login by ssh? A: AllowUsers, quoting man sshd_config, "If specified, [allows] only user names that match one of the patterns". To work around the problem, try logging in as newuser, and then use sudo -i (if newuser is allowed to run the command) or su root (if you know the root password) to become root and take the AllowUsers line out. After modifying sshd_config, restart sshd.
{ "pile_set_name": "StackExchange" }
Q: Using a variable in android XML or otherwise programmatically setting an XML attribute Say I have a style that I want to change: <?xml version="1.0" encoding="utf-8"?> <resources> <style parent="Widget.TitlePageIndicator" name="Widget.MyTitlepageIndicator"> <item name="footerColor">#14A804</item> </style> </resources> And I want to change the value of "footerColor", more specifically cycle through the spectrum. Is this possible? How would I obtain a reference to that memory address? A: As far as I know, you can't change the value within this resource file. That is the whole point of a resource file, having a static resource that does not change. What you can do is have multiple definitions of different styles in this resource file, and change the style that is being applied to a layout element. That can be done using this answer. Hope that helps!
{ "pile_set_name": "StackExchange" }
Q: concatenating tuples of array within a tuple I have a tuple which contains many tuples. Each tuple within my main tuple has two elements -- the first element is an array with a shape of (700,) and the second element is a integer. Here is a small representation of my tuple: x =( (np.array[3,3,3],1), (np.array[4,4,4],2), (np.array[5,5,5],3)) I'm looking to combine all the arrays into one big matrix, and all the integers into one column vector, which all fit into one tuple. So my output should be something like this: y= (np.array([[3,3,3],[4,4,4], [5,5,5]]), np.array([1,2,3])) One tuple with the first element as an array with shape (3,3), and the second element as an array with a shape of (3,) I'm assuming we can use one of numpy's stack methods but I can't wrap my head around how to access all elements of the tuples to do so. Thank you. A: >>> x = ((np.array([3,3,3]),1), (np.array([4,4,4]),2), (np.array([5,5,5]),3)) >>> y = (np.array([e for e, _ in x]), np.array([i for _, i in x])) (array([[3, 3, 3], [4, 4, 4], [5, 5, 5]]), array([1, 2, 3])) Or, without comprehensions: >>> map(np.array, zip(*x)) [array([[3, 3, 3], [4, 4, 4], [5, 5, 5]]), array([1, 2, 3])]
{ "pile_set_name": "StackExchange" }
Q: Attempting to write float to CSV, but it becomes an integer I'm using python 3 to create a csv file with different types of data, one of them being a float. Strings and integers show up correctly on the generated file, but the float becomes a large integer instead of retaining the decimals. For exmaple, 64.5232323 becomes 645.232.323. The data is organized in an array and I'm using python's csv module. Here's the code for writing to file: index_file_exists = os.path.isfile(full_dir+index_filename) with open(full_dir+index_filename, 'a+') as f: csv_file = csv.writer(f, delimiter=";") csv_file.writerow(index_line) index_line is the array containing all the data for that row. I have tried converting the float to a formatted string, as in: index_line[12] = "%.5f" % index_line[12] But the value is still displayed as an integer when opened with Excel. If opened with a text editor like notepad, the float is shown correctly. I don't use excel or csv files regularly, so I'm at a loss here. Any suggestions? A: Check the locale / region settings of Excel. If your region specifies "." as "thousands separator", then your formatted number will be treated as integer. And use the str.format() function, which has a locale-sensitive formatter: # Python < 3.6 index_line[12] = "{:.5n}".format(index_line[12]) # Python >= 3.6 index_line[12] = f"{index_line[12]:.5n}"
{ "pile_set_name": "StackExchange" }
Q: Numeric MaskedEditExtender issue onfocus I'm using latest toolkit (v18) and I have a strange behaviour when textbox receive focus. This is my markup: <asp:textbox runat="server" maxlength="10" id="txtBadge" name="txtBadge" placeholder="Codice badge" required="required"></asp:textbox> <asp:MaskedEditExtender runat="server" TargetControlID="txtBadge" Mask="9999999999" MaskType="Number" PromptCharacter="" /> I can correctly insert only numbers, but when txtBadge receive focus the text changes like this: NORMAL I entered the badge number ODD I just clicked on the textbox When I click outside of the textbox, then it shows again the correct text. what can it depend on? Thanks A: Ok, on github they suggest me to use FilteredTextBoxExtender that I didn't know of. Now it works as expected. <asp:TextBox runat="server" ID="TextBox1" MaxLength="10" /> <ajaxToolkit:FilteredTextBoxExtender runat="server" TargetControlID="TextBox1" FilterType="Numbers" />
{ "pile_set_name": "StackExchange" }
Q: How to derive cosine difference formula? I was asked on a take home quiz to "Derive the Cosine Difference Formula". I've looked for an hour but I've gotten different results this is kind of my last chance. A: And here is a totally inappropriate way. $e^{i(a-b)} = \cos(a-b)+i\sin(a-b) $ and $\begin{array}\\ e^{i(a-b)} &=e^{i(a)}e^{i(-b)}\\ &=(\cos(a)+i\sin(a))(\cos(-b)+i\sin(-b))\\ &=(\cos(a)+i\sin(a))(-i\sin(b))\\ &=\cos(a)\cos(b)+\sin(a)\sin(b)+i(\sin(a)\cos(b)-\cos(a)\sin(b))\\ \end{array} $ Equating real and imaginary parts, $\cos(a-b) =\cos(a)\cos(b)+\sin(a)\sin(b) $ and $\sin(a-b) =\sin(a)\cos(b)-\cos(a)\sin(b) $. As is often the case, there is absolutely nothing original here.
{ "pile_set_name": "StackExchange" }
Q: Etiquette for email asking graduate administrator to contact my reference regarding a deadline extension I've applied to the University of ....... for fall 2016 graduate admission. The deadline for my references to submit the recommendation letters is December 01. One of my references is currently extremely busy and has asked me to request the graduate administrator to contact him regarding the reference letter deadline. I'm trying to think of some way to communicate this to the graduate administrator. Is the following e-mail alright? Dear ......., I am a Physics graduate applicant to the University of ....... for fall 2016 entry. My Application Number is ........... One of my referees, Professor .......... from the University of .........., is currently under extenuating circumstances and will not be able to complete my reference letter in time. He's asked me to contact you regarding this urgent matter. I would be grateful if you could contact him at his e-mail address ......@.......... , and also to kindly confirm if you have received this e-mail. Yours sincerely, ........ Does the e-mail look proper and ready to be sent? A: The letter looks fine. However, it seems strange that the professor would involve you to intercede on his behalf in asking for an extension. Surely he can't be that busy! (I disagree with phys_chem_prof on the amount of time needed to write a reference letter. I would estimate writing a convincing letter to take the better part of an afternoon.) Unless this letter is crucial and the grace period asked for is not more than a few days, you may be better off approaching some one else, even at this late date.
{ "pile_set_name": "StackExchange" }
Q: J2SE getting a json response throwing exception 451? I'm creating an application that needs to get an answer from a webservice that response as json object. I've already test URL on browser and it works very well but using Java(J2SE) it doesn't works and throws an exception 451 from server. I don't know why it works on browser and doesn't works on j2se and how to fix it. How could I fix this ? The URL: https://economia.awesomeapi.com.br/all/USD-BRL Exception Server returned HTTP response code: 451 for URL: https://economia.awesomeapi.com.br/all/USD-BRL Method public void getJsonFromURL(){ try{ URL u = new URL("https://economia.awesomeapi.com.br/all/USD-BRL"); HttpURLConnection c = (HttpURLConnection) u.openConnection(); c.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); c.setRequestProperty("Accept", "application/json"); c.setRequestProperty("access-control-allow-origin", "*"); c.setRequestProperty("server", "keycdn-engine"); c.setRequestMethod("GET"); c.setDoOutput(true); c.setDoInput(true); c.connect(); int status = c.getResponseCode(); System.out.println("Code Response: " + status); //Exception Server returned HTTP response code: 451 for URL: https://economia.awesomeapi.com.br/all/USD-BRL }catch(Exception e){ System.out.println("Erro: " + e.getLocalizedMessage()); } } A: Seems I found it, the server doesn't like if the user-agent header isn't there. The request below gave me a result. Even if the parameter has no value, its accepted. I couldn't be some certificate/ssl/tls issue since the connection was established and the server actually replied, it just didn't like the request very much. This line did it: con.setRequestProperty("User-Agent", "");
{ "pile_set_name": "StackExchange" }
Q: property value is not changing in subscribe block in angular4 I am implementing authentication in asp.net core angular application. In my login component I am sending credentials in auth service which returns either true or false. when that returns true it is working fine. But when it is returning false, it is not changing the value of 'invalidLogin' property to true. I have tried this putting outside the subscribe block, only then it works. I have no idea why it is not changing inside subscribe block. ` export class LoginComponent implements OnInit { invalidLogin:boolean | undefined; loginCredentials:loginModel={ email:"", password:"" }; constructor(private router:Router, private authService:AuthService) { } ngOnInit() { this.invalidLogin=false; } signIn() { this.authService.login(this.loginCredentials).subscribe(result=>{ if(result) this.router.navigate(['/']); this.invalidLogin=true; }); } } ` A: Check for the status code in response, if it's not 200 (success status code range) then it will be handled via error callback like this: .subscribe((data) => { // Success case console.log(data); }, (e) => { // Error case console.log(e); });
{ "pile_set_name": "StackExchange" }
Q: PHP - Changing the datetime to mysql readable datetime My date and time string is: January 28, 2010 1417 with the last four numbers being the time. How should I go about converting it to a string that would be acceptable by mysql? when I try using strtotime I get Warning: strtotime(): It is not safe to rely on the system's timezone settings. A: $timestamp = strtotime($string); date("Y-m-d H:i:s", $timestamp);
{ "pile_set_name": "StackExchange" }
Q: Magento 2: How can I do an integration with magento 2 and sap business one? i want to create a integration with magento 2 and SAP B1, I created a web application in magento 2 I gave it a name and I gave it permission to API and it was saved then create a new role, assign the roles that the API will use, then create the user who will use the roles you previously believed when I make the call https: // HOST_IP / rest / V1 / customer / me give me this back The request does not match any route. Can you tell me if I'm forgetting a step or something? A: In Magento web-API when you pass user name and password then it generates token for that specific customer (Which is only valid for 1 hour - configurable from admin) http://ventas.interlatin.com.mx/index.php/rest/V1/integration/customer/token?username=testapi@hotmail.com&password=testapi12345 method POST which returns token.
{ "pile_set_name": "StackExchange" }
Q: How can I determine an empty string when its contents is \0\0\0\0 I have a SizeOfData variable of byte[4] which returns: byte[0] == 0 byte[1] == 0 byte[2] == 0 byte[3] == 0 When I do Encoding.ASCII.GetString(SizeOfData) the string variable's length is 4 and String.IsNullOrEmpty() returns false however when I look at the string in Visual Studio there is nothing in it. How can I determine that if it contains all \0\0\0\0 then do X else Y? A: A little bit of linq magic if (bytes.All(b => b == 0)) or the slightly better if (bytes.Any(b => b != 0))
{ "pile_set_name": "StackExchange" }
Q: School Assignment of understanding the definition of a specific C pointer During a C introductory course (in an Engineering University), we were asked to identify a declaration with pointers along the lines of int (*(*f[5])(void))[10];. my current understanding of the declaration would be "an array containing 10 function pointers returning an int pointer each and not taking any args". Could someone confirm my understanding of the declaration, and tell me if such definitions would be of any use in practice ? A: int (*(*f[5])(void))[10] declares (*(*f[5])(void))[10] to be an int. Which means (*(*f[5])(void)) is an array of 10 int. Which means (*f[5])(void) is a pointer to an array of 10 int. Which means (*f[5]) is a function taking void and returning a pointer to an array of 10 int. Which means f[5] is a pointer to a function taking void and returning a pointer to an array of 10 int. Which means f is an array of 5 pointers to functions taking void and returning a pointer to an array of 10 int.
{ "pile_set_name": "StackExchange" }
Q: Counting Sentences using NLTK (5400) and Spacy(5300) gives different answers. Need to know why? I am new to NLP. Using Spacy and NLTK to count the sentences from JSON file but there is a big difference in both of the answers. I thought that the answers will be same. Anyone who can tell me that?? or any web link which will help me about this. Please I'm confused here A: Sentence segmentation & tokenization are NLP subtasks, and each NLP library may have different implementations, leading to different error profiles. Even within the spaCy library there are different approaches: the best results are obtained by using the dependency parser, but a more simple rule-based sentencizer component also exists which is faster, but usually makes more mistakes (docs here). Because no implementation will be 100% perfect, you will get discrepancies between different methods & different libraries. What you can do, is print the cases in which the methods disagree, inspect these manually, and get a feel of which of the approaches works best for your specific domain & type of texts.
{ "pile_set_name": "StackExchange" }
Q: Default Ringtone Preference to silent I have a ringtone preference in a preferences.xml that currently defaults to the system notification sound. I'd like to default it to silent, but am having trouble finding the content URI to the silent sound. <RingtonePreference android:defaultValue="content://settings/system/notification_sound" android:key="@string/pref_alarm_tone_scan_notification_sound" android:ringtoneType="notification" android:showDefault="true" android:showSilent="true" android:title="@string/pref_alarm_notification_sound_title" /> In a subclass of Application, I am setting the default values from the xml file as follows: // apply defaults as stored in preferences.xml PreferenceManager.setDefaultValues(this, R.xml.preferences, false); A: the silent sound is an empty string android:defaultValue=""
{ "pile_set_name": "StackExchange" }
Q: Interactive labeling of images in jupyter notebook I have a list of pictures: pictures = {im1,im2,im3,im4,im5,im6} Where im1: im2: im3: im4: im5: im6: I want to assign the pictures to labels (1,2,3,4 etc.) For instance, here pictures 1 to 3 belong to label 1, picture 4 belongs to label 2, picture 5 to label 3, and picture 6 to label 4. -> label = {1,1,1,2,3,4} Since I need to see the images when I label them, I need a method to do that while labeling them. I was thinking of creating an array of images: And then I define the ranges by clicking on the first and last picture belonging to the same labels, so for example: What do you think ? Is this somehow possible ? I would like to assign different labels to different ranges of pictures. For instance: When one has finished selecting the first label one could indicate it by a Double-click and then do the selection of the second label range, then Double-click, then do the selection of the third label range, then Double-click, then do the selection of the fourth label range, etc. It does not have to be Double-clicking to change the selection of the labels, it could also just be a buttom or any other idea that you might have. In the end one should have the list of labels. A: Essentially, most of the interaction you are looking for boils down to being able to display images, and detect clicks on them in real time. As that is the case, you can use the jupyter widgets (aka ipywidgets) module to achieve most (if not all) of what you are looking for. Take a look at the button widget which is described here with explanation on how to register to its click event. The problem - we can't display an image on a button, and I didn't find any way to do this within the ipywidgets documentation. There is an image widget, but it does not provide an on_click event. So construct a custom layout, with a button underneath each image: COLS = 4 ROWS = 2 IMAGES = ... IMG_WIDTH = 200 IMG_HEIGHT = 200 def on_click(index): print('Image %d clicked' % index) import ipywidgets as widgets import functools rows = [] for row in range(ROWS): cols = [] for col in range(COLS): index = row * COLS + col image = widgets.Image( value=IMAGES[index], width=IMG_WIDTH, height=IMG_HEIGHT ) button = widgets.Button(description='Image %d' % index) # Bind the click event to the on_click function, with our index as argument button.on_click(functools.partial(on_click, index)) # Create a vertical layout box, image above the button box = widgets.VBox([image, button]) cols.append(box) # Create a horizontal layout box, grouping all the columns together rows.append(widgets.HBox(cols)) # Create a vertical layout box, grouping all the rows together result = widgets.VBox(rows) You can technically also write a custom widget to display an image and listen for a click, but I simply don't believe it's worth your time and effort. Good luck!
{ "pile_set_name": "StackExchange" }
Q: GestureDetectorCompat not reacting to events In the following code, I do not get any response to touch events when I setup my GestureDetectorCompat. Could it be because I use data binding? If so, do you have any ideas why and how to get around the problem? private lateinit var mDetector: GestureDetectorCompat private fun setupDataBinding() { binding = DataBindingUtil.setContentView(this, R.layout.activity_main) binding.lifecycleOwner = this } private fun setupViewListener() { mDetector = GestureDetectorCompat(this, MyGestureListener()) } private class MyGestureListener : GestureDetector.SimpleOnGestureListener() { private val DEBUG_TAG = "Gestures" override fun onDown(event: MotionEvent): Boolean { Log.d(DEBUG_TAG, "onDown: $event") return true } A: You should override onTouchEvent() and dispatchTouchEvent() in your activity as below: @Override public boolean onTouchEvent(MotionEvent motionEvent) { this.mDetector.onTouchEvent(motionEvent); return super.onTouchEvent(motionEvent); } @Override public boolean dispatchTouchEvent(@NonNull MotionEvent ev) { super.dispatchTouchEvent(ev); return mDetector.onTouchEvent(ev); }
{ "pile_set_name": "StackExchange" }
Q: Android : Combine normal widget and SurfaceView I have create a screen with two kind of views : normal view (buttons to receive up/down action ) and surfaceview. The SurfaceView implements SurfaceHolder.Callback and run on another thread and have a method name Tick(). When those buttons receive action, they will call method Tick(), and I want this method will run same thread with SurfaceView (for synchronize purpose), but don't know how to. Please give me some idea for my issues. Thanks :) A: If you really want to run Tick() method in separate thread which also draws on the surface you can use HandlerThread for it. So you will be able to create Handler for it and post runnables which will be executed in this thread. But this also will put some restrictions on your drawing routine - you need to prevent it from sleeping or waiting because thread need to process message queue. But actually I suppose any other reasonable way of synchronization will be easier than running this method on the same thread.
{ "pile_set_name": "StackExchange" }
Q: Spline on multiple factors in data frame This question is in the context where I have a lot Model types, each of the same class, but the amount of data for each Model is small and I want to spline to get a fuller dataset. I'm hoping to find a way to do this without having to individually spline every Model once at a time. So I have the following df: mydf<- data.frame(c("a","a","b","b","c","c"),c("e","e","e","e","e","e") ,as.numeric(c(1,2,3,10,20,30)), as.numeric(c(5,10,20,20,15,10))) Give some names: colnames(mydf)<-c("Model", "Class","Seconds", "Speed") Which creates: > mydf Model Class Seconds Speed 1 a e 1 5 2 a e 2 10 3 b e 3 20 4 b e 10 20 5 c e 20 15 6 c e 30 10 So I want a spline on the Seconds and Speed columns for each Model. So for example if I used spline on Model "a", it you only spline those elements on "a" as the model. Like: spline(x=mydf[1:2,3], y=mydf[1:2,4]) $x [1] 1.0 1.2 1.4 1.6 1.8 2.0 $y [1] 5 6 7 8 9 10 This works but when you have a hundreds of models... I want to spline "a" only using "a" and then it moves to "b" and splines only "b" etc. Ideally it would output as a new dataframe but at this point I'd just like to not get an error. I tried ddply in plyr but getting errors. I'm hoping to avoid using loops or functions with loops but if that's the only option then... Thanks and please let me know if I can improve the question. A: What about this: ddply(mydf, .(Model), summarise, Spline = spline(x = Seconds, y = Speed), Var = c("Seconds", "Speed")) Model Spline Var 1 a 1.0, 1.2, 1.4, 1.6, 1.8, 2.0 Seconds 2 a 5, 6, 7, 8, 9, 10 Speed 3 b 3.0, 4.4, 5.8, 7.2, 8.6, 10.0 Seconds 4 b 20, 20, 20, 20, 20, 20 Speed 5 c 20, 22, 24, 26, 28, 30 Seconds 6 c 15, 14, 13, 12, 11, 10 Speed
{ "pile_set_name": "StackExchange" }
Q: Search for exact word or phrase in Flash Builder's "Search" tool? How do I search for an exact match to a phrase or word in Flash Builder's search tool? For example, in my project I have a class with a function named "removeEvent". If I search on it, I get all instances where "removeEventListener" is used and of course that is not helpful. I have searched on the web but only come up with similarly unhelpful false hits (how ironic). It appears I can use regex but I don't know how to do that and trying this answer to a regex question was no help A: Enable the regular expression option and then use the below regex. \bremoveEvent\b \b called word boundary which helps to do an exact match.. \b matches between a word charcater and non-word character, vice-versa..
{ "pile_set_name": "StackExchange" }
Q: Does retagging a question count as an edit for Strunk & White? Possible Duplicate: What kind of edits contribute to the editor badges? Does retagging a question count as an edit for the Strunk and White badge? A: It does not count for the Strunk and White badge A: No, it doesn't count towards the badge. Edits to your own posts and retagging are not counted towards the Strunk and White badge. See this answer by Jeff himself in meta. I don't know if the rules have changed since then.
{ "pile_set_name": "StackExchange" }
Q: row span not working proper in dynamic generated html content via jquery <table> <tr> <td rowspan="2">test</td> <td>test</td> </tr> <tr> <td rowspan="0">test</td> <td>test</td> </tr> </table> $.each(data.shopTimeArray,function(i) { $tbodyTR = $("<tr>",{}).appendTo($tbody); $tbodyTH = $("<th>",{'scope':'row','html':data.shopTimeArray[i].slice(0,-3)}).appendTo($tbodyTR); $.each(data.workerids,function(j) { $.each(data.workerAppointments[data.workerids[j]],function(k) { if(data.workerAppointments[data.workerids[j]][k].timeArray != "undefined") { $.each(data.workerAppointments[data.workerids[j]][k].timeArray,function(y){ $rowSpan++; }); } else { $rowSpan = 0; } }); }); $tbodyTD = $("<td>",{'class':classname,'onclick':click,'html':html,'rowspan':$rowSpan,'data-time':time,'workerid':data.workerids[j]}).appendTo($tbodyTR); }); {"shopTimeArray":["10:00:00","10:15:00","10:30:00","10:45:00","11:00:00","11:15:00","11:30:00","11:45:00","12:00:00"],"workernames":["Kapper 1","Kapper 2"],"workerTimes":{"148":["10:00:00","10:15:00","10:30:00","10:45:00","11:00:00","11:15:00","11:30:00","11:45:00","12:00:00"],"196":["10:00:00","10:15:00","10:30:00","10:45:00","11:00:00","11:15:00","11:30:00","11:45:00","12:00:00"]},"workerAppointments":{"148":[{"timeArray":["10:00:00","10:15:00","10:30:00","10:45:00"]}],"196":[{"timeArray":["09:30:00","09:45:00"]},"workerids":["148","196"],"today":"2017-06-19","dayname":"1"} Here i m creating dynamic html, i want to skip next 5 td if there is a rowspan = 5 value want to skip is in workerAppointments[workerid][timearray] Looking for help https://imgur.com/a/xCais "tooltip" Look i add table which is generated by jquery you can see in table if rowspan = 2 than in next tr first td will not add, but by my above jquery code it add create like above table. A: You could have a variable called skipColumnCount and in your inner loop do something like if (skipColumnCount > 0) { skipColumnCount--; continue; } So, to skip 5 columns, you'd set it equal to 5.
{ "pile_set_name": "StackExchange" }
Q: CancellationTokenSource.Cancel doesn't work during WPF app exit Here is a simple async call with cancellation code snippet. The code sits in a WPF application class. If I call the Cancel method via a WPF UI Command, the async method will exit properly. However, if the Cancel is invoked during the OnExit method, nothing happens. My actual code requires OnExit call because the async method uses IO resources that should be cleaned up properly. Any ideas? Edit: the expected behavior is that Task.Delay method should throw the OperationCancelledException when cancel is invoked. What I want to know is why it doesn't during app exit and if there are work around to get it behaving properly. public partial class App : Application { protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); ListenAsync(source.Token); } ManualResetEvent waitHandle = new ManualResetEvent(false); CancellationTokenSource source = new CancellationTokenSource(); public void Cancel() { source.Cancel(); } async void ListenAsync(CancellationToken token) { try { while (true) { await Task.Delay(300000, token); } } catch (OperationCanceledException) { Console.WriteLine("Cancelled"); } catch (Exception err) { Console.WriteLine(err.Message); } finally { Console.WriteLine("Terminate"); waitHandle.Set(); } } protected override void OnExit(ExitEventArgs e) { Cancel(); waitHandle.WaitOne(); base.OnExit(e); } } A: Found the problem. The Cancel call during WPF App Exit is on the same synchronization context as the ListenAsync function. Because the thread is blocked by the waitHandle.WaitOne, there is no way for the ListenAsync method to resume executing on the same synchronization context. The problem can be resolved by changing the async call to await Task.Delay(300000, token).ConfigureAwait(false); This allows the remainder of the ListenAsync function to stay on the sync context of the Task.Delay function.
{ "pile_set_name": "StackExchange" }
Q: Connect to MongoDB in C# with Credentials Hi I'm trying to connect to my remote MongoDB with Visual Studio 2013 in c# using the latest Official MongoDB supported driver for MongoDB. The problem I'm having is I'm unable to insert a collection or possibilly even establishing the connection. I'm using the following code to create mongo credential (DBName, User, Password) mongoCredential = MongoCredential.CreateMongoCRCredential("MongoDB", "xxxxxxxxxxxxx", "xxxxxxxxxxxxxxxxxxxxxxx"); Setup credentials List mongoClientSettings = new MongoClientSettings { Credentials = new[] { mongoCredential }, Server = new MongoServerAddress("xx.xxx.xx.xxx", 38180) }; Add our mongo server credentials to our client mongoClient = new MongoClient(mongoClientSettings); Then to connect: private void button1_Click(object sender, EventArgs e) { // Connect to database mongoDatabase = mongoClient.GetDatabase("MongoDB"); } Now I try and insert a collection: private void button4_Click(object sender, EventArgs e) { // Create a collection mongoDatabase.CreateCollectionAsync("aCollection"); } This method is not working for we as when I run mongo from prompt and connect to remote db with credentials then run db.stats() it returns an empty db: > db.stats() { "db" : "MongoDB", "collections" : 0, "objects" : 0, "avgObjSize" : 0, "dataSize" : 0, "storageSize" : 0, "numExtents" : 0, "indexes" : 0, "indexSize" : 0, "fileSize" : 0, "ok" : 1 } > MongoDB is not my thing and any help here would be much appreciated as I'm going round in circles with this? A: It's possible (likely?) that CreateCollectionAsync is throwing an exception but that you aren't observing that exception. Like all async methods in C#, CreateCollectionAsync returns immediately, and the actual work is done asynchronously in the background. You should "await" this method. When you use await, the calling Task is suspended until the called Task completes, at which point await either returns the result of the called Task or rethrows an exception if the called Task faulted.
{ "pile_set_name": "StackExchange" }
Q: Putting NewLine in writing CSV documents Perl I am trying to write data calculated by my perl script into a csv file which will be repeatedly opened and input to. I have encountered two issues. One, the CSV created ocupies a single row, adding each new field to a new column. The seccond is that the CSV file once created does not succesfully close so I am unable to reopen and edit it by running the script again. the code that I am using is this: push my @rows, ["Entries Missing from English doc:"," " , "Entries Missing from French doc:"]; push @rows, ["$englishUnincluded[0]", " ", "$frenchUnincluded[0]"]; my $csv = Text::CSV->new ({binary=>1}) or die "cannot use CSV: ".Text::CSV->error_diag (); open my $csvFile, ">:encoding(utf8)", "telt.csv" or die "telt.csv: $!"; $csv->column_names(@{$rows[0]}); $csv->print($csvFile, $_) for @rows; close $csvFile or die "teet.csv: didnt close at all"; I have also tried using consecutive print statements rather than the $csv->print(..) for @rows; I previously had statments looking like $field_vals = ["$val", "something", " "]; $csv->print($csvFile, $field_vals); and reloaded all the values into field vals and printed them as lines to the CSV but had the same two issues continuously. ** note that CSV not closing issue goes away if only one line is printed. Also, script does not print the "or die" message on not closing the file properly. thank you in advance for any help you provide! A: You've forgotten to declared end of line: my $csv = Text::CSV->new ({binary=>1, eol => $/}) or die "cannot use CSV: ".Text::CSV->error_diag (); # here __^^^^^^^^^^^^
{ "pile_set_name": "StackExchange" }
Q: NeuPy: Input shapes issues I want to build a neural network using neupy. Therefore I consturcted the following architecture: network = layers.join( layers.Input(10), layers.Linear(500), layers.Relu(), layers.Linear(300), layers.Relu(), layers.Linear(10), layers.Softmax(), ) My data is shaped as follwoing: x_train.shape = (32589,10) y_train.shape = (32589,1) When I try to train this network using: model.train(x_train, y_trian) I get the follwoing error: ValueError: Input dimension mis-match. (input[0].shape[1] = 10, input[1].shape[1] = 1) Apply node that caused the error: Elemwise{sub,no_inplace}(SoftmaxWithBias.0, algo:network/var:network-output) Toposort index: 26 Inputs types: [TensorType(float64, matrix), TensorType(float64, matrix)] Inputs shapes: [(32589, 10), (32589, 1)] Inputs strides: [(80, 8), (8, 8)] Inputs values: ['not shown', 'not shown'] Outputs clients: [[Elemwise{Composite{((i0 * i1) / i2)}}(TensorConstant{(1, 1) of 2.0}, Elemwise{sub,no_inplace}.0, Elemwise{mul,no_inplace}.0), Elemwise{Sqr}[(0, 0)](Elemwise{sub,no_inplace}.0)]] How do I have to edit my network to map this kind of data? Thank you a lot! A: Your architecture has 10 outputs instead of 1. I assume that your y_train function is a 0-1 class identifier. If so, than you need to change your structure to this: network = layers.join( layers.Input(10), layers.Linear(500), layers.Relu(), layers.Linear(300), layers.Relu(), layers.Linear(1), # Single output layers.Sigmoid(), # Sigmoid works better for 2-class classification ) You can make it even simpler network = layers.join( layers.Input(10), layers.Relu(500), layers.Relu(300), layers.Sigmoid(1), ) The reason why it works is because layers.Liner(10) > layers.Relu() is the same as layers.Relu(10). You can learn more in official documentation: http://neupy.com/docs/layers/basics.html#mutlilayer-perceptron-mlp
{ "pile_set_name": "StackExchange" }
Q: Instagram post's caption is not showing properly I am trying to get instagram profile's post with captions, everything is working fine except captions. It showing : [object Object] I haven't used any api. My code: function nFormatter(num){ if(num >= 1000000000){ return (num/1000000000).toFixed(1).replace(/\.0$/,'') + 'G'; } if(num >= 1000000){ return (num/1000000).toFixed(1).replace(/\.0$/,'') + 'M'; } if(num >= 1000){ return (num/1000).toFixed(1).replace(/\.0$/,'') + 'K'; } return num; } $.ajax({ url:"https://www.instagram.com/bhudiptaakash?__a=1", type:'get', success:function(response){ $(".profile-pic").attr('src',response.graphql.user.profile_pic_url); posts = response.graphql.user.edge_owner_to_timeline_media.edges; posts_html = ''; for(var i=0;i<posts.length;i++){ caption = posts[i].node.edge_media_to_caption; likes = posts[i].node.edge_liked_by.count; posts_html += '<a href="https://instagram.com/p/'+shortcode+'">: '+caption+'; } $(".posts").html(posts_html); } }); How can I solve this?? A: The value of the edge_media_to_caption property is an object like this: { "edges": [{ "node": { "text": "Still alive" } }] } You need to loop over the edges and get the node.text properties. for (var i = 0; i < posts.length; i++) { let caption = posts[i].node.edge_media_to_caption.edges.map(e => e.node.text).join('<br>'); let likes = posts[i].node.edge_liked_by.count; posts_html += '<a href="https://instagram.com/p/' + shortcode + '">: ' + caption + '</a>'; }
{ "pile_set_name": "StackExchange" }
Q: What is the correct/ fastest way to update/insert a record in sql (Firebird/MySql) I need some SQL to update a record in a database if it exists and insert it when it does not, looking around there looks to be several solutions for this, but I don't know what are the correct/ accepted ways to do this. I would ideally like it to work on both Firebird 2 and MySQL 5 as the update will need to be ran against both databases, and it would be simpler if the same SQL ran on both, if it worked on more database that would be a plus. Speed and reliability also factor in, reliability over speed in this case but it will potentially be used to update 1000's of records in quick succession (over different tables). any subjections? A: In Firebird 2.1 you can use UPDATE OR INSERT for simple cases or MERGE for more complex scenarios. A: You should either use something like this: BEGIN TRANSACTION IF EXISTS (SELECT * FROM the_table WHERE pk = 'whatever') UPDATE the_table SET data = 'stuff' WHERE pk = 'whatever' ELSE INSERT INTO the_table (pk, data) VALUES ('whatever', 'stuff') COMMIT Or this, but send them separately and ignore any errors from the INSERT about violating primary key constraints: INSERT INTO the_table (pk, data) VALUES ('whatever', 'stuff') UPDATE the_table SET data = 'stuff' WHERE pk = 'whatever'
{ "pile_set_name": "StackExchange" }
Q: Print login page url in node.tpl.php It seems nevertheless rather simple, but I do not find the solution. How to print in node.tpl.php the url of the login page? The url has to serve for a link: <a href="<?php print ... ?>"><span>Login</span></a> A: Use this if you just want the URL: <?php print url('user/login'); ?> If you want to print a link: <?php print l(t('Login'), 'user/login'); ?> And in your case it would be: <?php print l('<span>' . t('Login') . '</span>', 'user/login', array('html' => TRUE)); ?>
{ "pile_set_name": "StackExchange" }
Q: How do you prove that the following 2 hypothesis classes' VC-dimensions are equal? Given a hypothesis class $H=\{h:X\to\{0,1\}\}$. Let $c\in H$ be the correct predictor. Denote $H^c = \{c\Delta h:h\in H\}$, where $c\Delta h=(h\backslash c)\cup (c\backslash h)$. Please prove that VCdim($H^c$) = VCdim($H$) A: If some $A = (a_1,\dots,a_d\}\subset X$ is shattered by $H$, then, for any vector $b$ = $\{0,1\}^d$,$\exists$ $h \in H s.t. (h(a_1),\dots,h(a_d)) = b$. It suffices to prove that for any vector $(h(a_1),\dots,h(a_d)) = b$, $\exists$ $h' \in H s.t. (c\Delta h'(a_1),\dots,c\Delta h'(a_d)) = (h(a_1),\dots,h(a_d))$. Proof of my claim: $\forall x_i \in A$, if $c(a_i) = 0$,let $h'(a_i) = h(a_i)$, then $c\Delta h' (a_i) = h(a_i)$. If $c(a_i) = 1$, let $h'(a_i) = -h(a_i)$, then $c\Delta h'(a_i) = h(a_i)$. Then $(c\Delta h'(a_1),\dots,c\Delta h'(a_d)) = (h(a_1),\dots,h(a_d))$. For the same reason, the inverse is also true.
{ "pile_set_name": "StackExchange" }
Q: Two groups of checkboxes, if first one is checked second can not be I have two "groups" of checkboxes (although the first group only contains one checkbox), but if user checks the checkbox from the first group I want to restrict the ability of checking the checkboxes from second group... <div> <h3>First group</h3> <label> <input type="checkbox" value="1" name="group1" />If checked, checks all the checkboxes in 2nd group</label> <label> </div> <div> <h3>Second Group</h3> <label> <input type="checkbox" class="radio" value="1" name="group2" />1</label> <label> <input type="checkbox" class="radio" value="1" name="group2" />1</label> </div> A: I've used a simple jQuery script to solve it. initially it didn't exactly do what I wanted it to do, but I've managed to work around it with php as I had to make sure that if someone checked the checkbox from the second group that it didn't go to the database. $('#checkbox1').click(function() { if( $(this).is(':checked')) { $("#checkbox2").hide(); } else { $("#checksbox2").show(); } }); As for php I simply used a ternary operator to make sure that if checkbox with id checkbox1 is checked then I want to ignore the rest of the checkboxes... $smnrs = !empty($_POST['all']) ? explode(';', $_POST['all']) : $_POST['seminars']; in this case $_POST['all'] refers to the first checkbox that if clicked it hides the div holding the other checkboxes.
{ "pile_set_name": "StackExchange" }
Q: Summation over a sympy Array I want to sum over a sympy Array (called arr) using the two indices i and j. Summing over arr[i] results in an integer as In [4] below shows. However, summing over arr[j] does not give a number as result (see In [5] below). Why is that? In [1]: from sympy import * In [2]: i, j = symbols("i j", integer=True) In [3]: arr = Array([1, 2]) In [4]: summation( ...: arr[i], ...: (j, 0, i), (i, 0, len(arr)-1) ...: ) Out[4]: 5 In [5]: summation( ...: arr[j], ...: (j, 0, i), (i, 0, len(arr)-1) ...: ) Out[5]: Sum([1, 2][j], (j, 0, i), (i, 0, 1)) A: SymPy will evaluate summation if either Both the summand and the limits for summation are explicit; or It can find a symbolic expression for the sum, based on the formula for the summand. Nested summation is performed from left to right. In the first version, summation(arr[i], (j, 0, i)) falls under item 2: since the summand does not depend on the index j, the sum evaluates to symbolically to (i + 1)*arr[i]. Then the outer sum becomes summation((i + 1)*arr[i], (i, 0, len(arr)-1)) and this falls under item 1: both the summand and the limits are explicit. But in the second version, summation(arr[j], (j, 0, i)) fits neither 1 nor 2. The summand depends on j, we don't have any formula for it (it's just some numbers [1, 2]), and the upper limit of summation is symbolic. There is nothing for SymPy to do with such a sum, so it remains undone. Subsequently, the outer sum is not going anywhere since the inner was not done. Workaround In the second case, replacing the outer sum with Python sum makes the inner one explicit, so it gets evaluated. >>> sum([summation(arr[j], (j, 0, i)) for i in range(len(arr))]) 4 Of course, this does not really use symbolic capabilities of SymPy: the inner sum could be Python's sum as well.
{ "pile_set_name": "StackExchange" }
Q: Why windows 10 UWP framework Stream class does not have Close method? Why windows 10 UWP framework Stream class does not have Close method? What do I do in order to release the used stream, I have used Dispose method as of now but is there any other way I can release the stream? And why microsoft have removed Close method from the Stream class? A: You are indeed supposed to be using Dispose(), or better yet enclosing your streams in a using block. MSDN says you're not expected to call System.IO.Stream.Close() directly and you should be calling Dispose() instead anyway. So there isn't much of an issue here.
{ "pile_set_name": "StackExchange" }
Q: Difference between listing a generator and looping Looking at this answer, it seems that using a list comprehension (or for loop with append) is equivalent to calling list(..) on an iterator. Since generators are iterators too, I'd expect the same for generators. However, if you run def permute(xs, count, low = 0): if low + 1 >= count: yield xs else: for p in permute(xs, low + 1): yield p for i in range(low + 1, count): xs[low], xs[i] = xs[i], xs[low] for p in permute(xs, low + 1): yield p xs[low], xs[i] = xs[i], xs[low] print("Direct iteration") for x in permute([1, 2], 2): print(x) print("Listing") for x in list(permute([1, 2], 2)): print(x) It prints: Direct iteration [1, 2] [2, 1] Listing [1, 2] [1, 2] Why is this happening? A: You're modifying and yielding the same list xs over and over. When the generator is running the list contents are changing. It looks like it's working because although each print(x) prints the same list object, that object has different contents each time. On the other hand, the second loop runs the generator to completion and collects all of the list references up. Then it prints out the lists—except they're all the same list, so every line is the same! Change the two print(x) lines to print(x, id(x)) and you'll see what I mean. The ID numbers will all be identical. Direct iteration [1, 2] 140685039497928 [2, 1] 140685039497928 Listing [1, 2] 140685039497736 [1, 2] 140685039497736 A quick fix is to yield copies of the list instead of the original list. The yield p's are fine, but yield xs should become: yield xs[:] With that fix, the results are as expected: Direct iteration [1, 2] 140449546108424 [2, 1] 140449546108744 Listing [1, 2] 140449546108424 [2, 1] 140449546108808 Same results from both loops, and the ID numbers are different.
{ "pile_set_name": "StackExchange" }
Q: Manipulating CSV Data with Javascript I have two .csv files and i need to make one table for both files in simple html page. First file (devices.csv) has id,name,units where units the number of ports that device can connect. Second file (connections.csv) has reference id for the first file and unit_number that is connected in each device. Now the final result should read the text files and display the information in a way that will allow the user to check how many units are within each devices and which units are connected or free. devices.csv id,name,units 1,CAB-01,20 2,CAB-02,10 3,DP-01,4 4,DP-02,12 5,CAB-01,0 6,DP-01,24 connections.csv device_id,unit_number 1,1 1,3, 1,17 1,18 1,19 7,1 1,20 2,10 3,1 3,2 1,5 4,12 4,1 1,6 2,1 1,7 3,4 1,8 1,9 4,11 4,1 4,3 1,10 2,2 2,3 2,4 3,3 1,12 1,14 4,4 1,15 1,16 2,6 2,8 5,1 my js file : function handleFiles(files) { // Check for the various File API support. var data = new Object; if (window.FileReader) { var j = 0, k = files.length; for (var i = 0; i < k; i++) { //j++; getAsText(files[i]); }; } // FileReader are supported. //} else { alert('FileReader are not supported in this browser.'); }} function getAsText(fileToRead) { var reader = new FileReader(); reader.onload = loadHandler; reader.onerror = errorHandler; reader.readAsText(fileToRead); } function loadHandler(event) { var csv = event.target.result; processData(csv); } function processData(csv) { var allTextLines = csv.split(/\r\n|\n/); var lines = []; while (allTextLines.length) { lines.push(allTextLines.shift().split(',')); } console.log(lines); drawOutput(lines); } function errorHandler(evt) { if(evt.target.error.name == "NotReadableError") { alert("Canno't read file !"); } } function drawOutput(lines){ var table = document.createElement("table"); for (var i = 0; i < lines.length; i++) { var row = table.insertRow(-1); for (var j = 0; j < lines[i].length; j++) { var firstNameCell = row.insertCell(-1); firstNameCell.appendChild(document.createTextNode(lines[i][j])); console.log(firstNameCell); }; } document.getElementById("output").appendChild(table); } please help A: Before pushing it all into DOM (or HTML) you should convert the data from the two sources into one. Say, each device should be represented as: "name", "units", "unit_numbers" Let's try & implement it: var data_devices = ["1,CAB-01,20", "2,CAB-02,10", "3,DP-01,4", "4,DP-02,12", "5,CAB-01,0", "6,DP-01,24"]; var data_connections = ["1,1", "1,3,", "1,17", "1,18", "1,19", "7,1", "1,20", "2,10", "3,1", "3,2", "1,5", "4,12", "4,1", "1,6", "2,1", "1,7", "3,4", "1,8", "1,9", "4,11", "4,1", "4,3", "1,10", "2,2", "2,3", "2,4", "3,3", "1,12", "1,14", "4,4", "1,15", "1,16", "2,6", "2,8", "5,1"]; var data = {}; data_devices.forEach(function(d) { d = d.split(","); data[d[0]] = { "name":d[1], "units":d[2], "unit_numbers":[] }; }); data_connections.forEach(function(d) { d = d.split(","); if(data[d[0]]) data[d[0]].unit_numbers.push(d[1]); }); The data variable is now queryable & looks like this: { "1": { "name": "CAB-01", "units": "20", "unit_numbers": [ "1", "3", "17", "18", "19", "20", "5", "6", "7", "8", "9", "10", "12", "14", "15", "16" ] }, "2": { "name": "CAB-02", "units": "10", "unit_numbers": [ "10", "1", "2", "3", "4", "6", "8" ] }, "3": { "name": "DP-01", "units": "4", "unit_numbers": [ "1", "2", "4", "3" ] }, "4": { "name": "DP-02", "units": "12", "unit_numbers": [ "12", "1", "11", "1", "3", "4" ] }, "5": { "name": "CAB-01", "units": "0", "unit_numbers": [ "1" ] }, "6": { "name": "DP-01", "units": "24", "unit_numbers": [] } }
{ "pile_set_name": "StackExchange" }
Q: Changing ListView.ShowItemToolTips raises ItemChecked events Hi when I set ShowItemToolTips of a ListView with checkbox items to true in designer and change it to false in the code, the event ItemChecked is raised. The checked state itself is not changed though. But inside the (also raised) ItemCheck event the old value is not equal to the new value but the new value is the value that was previously visible. It seems like the items are re-inserted or reset in some way. I tested this on two machines and projects. Why does this happen and how can I avoid it? A: I'll explain the "why", a workaround is hard to come by. Some control properties are very impactful and can have odd side-effects when you change them. Like ShowItemToolTips, changing it after the ListView is created requires Winforms to completely destroy the native control and recreate it from scratch. Under the hood, it is a style flag (LVS_EX_INFOTIP) that's specified in the CreateWindowEx() call. The Control.RecreateHandle() method ensures it is effective. You'll see the flicker that this causes if you look closely. So for a brief moment, the native control exists without yet being initialized with the original checkbox states. Getting a flaky event for that is a bug, but it is the kind that was either never fixed because doing so was too difficult or was just never discovered because nobody ever changes the ShowItemToolTips property after the control was created. It is very uncommon to do so. In general, this native control re-creation trick has been a significant bug generator in Winforms. And workarounds are hard to come by, they fit either in the "deal with it" or the "don't do it" category. With the latter one strongly recommended in this case.
{ "pile_set_name": "StackExchange" }
Q: Searching not exists in Neo4j via Cypher I have some relations between persons in my graph. my data (generate script below) create (s:Person {name: "SUE"}) create(d:Person {name: "DAVID"}) create(j:Person {name: "JACK"}) create(m:Person {name: "MARY"}) create(js:Person {name: "JASON"}) create(b:Person {name: "BOB"}) create(a1:Adress {id:1}) create(a2:Adress {id:2}) create(a3:Adress {id:3}) create(a4:Adress {id:4}) create(a5:Adress {id:5}) merge (d)-[:MOTHER]->(s) merge(j)-[:MOTHER]->(s) merge(js)-[:MOTHER]->(m) merge(b)-[:MOTHER]->(m) merge(b)-[:CURRENT_ADRESS]->(a1) merge(js)-[:CURRENT_ADRESS]->(a2) merge(j)-[:CURRENT_ADRESS]->(a3) merge(s)-[:CURRENT_ADRESS]->(a4) merge(d)-[:CURRENT_ADRESS]->(a5) ; I can get mothers who live with her child: MATCH (p:Person)-[:CURRENT_ADRESS]->(a:Adress)<-[:CURRENT_ADRESS]-(t), (t)-[:MOTHER]->(p) return p.name,t.name p.name t.name MARY JASON but i want to get mothers who is not living with any child of her. How can i do that in Cyper? A: Actually in your graph, everybody is living at a different address due to different identifiers. Let's build a graph example introducing the sister which lives at the same address : CREATE (p:Person)-[:MOTHER]->(m:Person), (p)-[:FATHER]->(f:Person), (p)-[:SISTER]->(s:Person), (p)-[:CURRENT_ADDRESS]->(a:Adress), (m)-[:CURRENT_ADDRESS]->(b:Adress), (f)-[:CURRENT_ADDRESS]->(c:Adress), (s)-[:CURRENT_ADDRESS]->(a) Now this is very simple, match family members that don't have a CURRENT_ADDRESS relationship in depth2 to the family member : MATCH (p:Person)-[:MOTHER|:FATHER|:SISTER]->(familyMember) WHERE NOT EXISTS((p)-[:CURRENT_ADDRESS*2]-(familyMember)) RETURN familyMember
{ "pile_set_name": "StackExchange" }
Q: Use 'forceget' error when calling GET :urn/​metadata/​:guid/​properties I am trying to retrieve the properties using this method: GET :urn/​metadata/​:guid/​properties This is something that we have running and works daily in our workflows, but I think this is an especailly large model. For this particular model we are getting the following repsonse: 413 Request Entity Too Large {Diagnostic": "Please use the 'forceget' parameter to force querying the data."} Can anyone advise me as to how I do apply the forceget parameter to this call as I can't see any mention of it in the api docs. A: forceget (string): To force get the large resource even if it exceeded the expected maximum length. Possible values: true, false. The implicit value is false.
{ "pile_set_name": "StackExchange" }
Q: What does it mean for a git repo to have multiple remotes? I was reading over Pro Git, and the section on remote repositories is sort of confusing for me. In particular, there's a section where the author says: http://git-scm.com/book/en/Git-Basics-Working-with-Remotes "If you have more than one remote, the command lists them all. For example, my Grit repository looks something like this. $ cd grit $ git remote -v bakkdoor git://github.com/bakkdoor/grit.git cho45 git://github.com/cho45/grit.git defunkt git://github.com/defunkt/grit.git koke git://github.com/koke/grit.git origin git@github.com:mojombo/grit.git This means I can pull contributions from any of these users pretty easily. But notice that only the origin remote is an SSH URL, so it’s the only one I can push to (we’ll cover why this is in Chapter 4)." My question is, what are the four remote repositories (bakkdoor, cho, defunkt, koke) in relation to grit? Are they repos make up the grit repo? Or are they separate copies of the same grit repo? Or are they not related at all? Furthermore, if the grit repo is made up of those 4 separate repos, why are they separately named? Wouldn't it make more sense to have them all under "origin"? As you can see, I'm pretty much totally lost on this. I feel like the way it's being explained to me is going right over my head. A: The idea is that you can create a remote repository ("origin") and push your project's code there. Let's say that since you are the creator of that project, your repository is considered the official version of your project. Suppose that you are the only one allowed to push to that remote repository, but others can pull from it. So other people can clone your repository and create their own remote repositories based on it (Got example, GitHub allows you to create a remote repository based on another user's repository). They can add features to your code on their own repositories. Now if they want to contribute to the official version (maintained by you), they can tell you about the new features they added and ask you to add them to your project. One of the ways for you to do that is to add their repositories as additional remote repositories (bakkdoor, cho45, etc... are such repositories and they are named after the GitHub users who created them). Since you don't own those repositories, you'll only have read access to them. Then you can pull whatever changes you want from them, and push them to your remote repository, thus integrating these changes into the official version. This type of collaboration is discussed later in the Pro Git book. You should continue reading and everything will become clearer.
{ "pile_set_name": "StackExchange" }
Q: Subject from Dropdown using enum Django I have ContactForm with subject dropdown using enum, the subject is three different string: 1. I have a question. 2. Help/Support 3. Please give me a call. When the user send a message have to select one of the above three, here is my code below: *forms.py* from django_enumfield import enum class SubjectEnum(enum.Enum): subject_one = 'I have a question' subject_two = 'Help/Support' subject_three = 'Please give me a call' class ContactForm(forms.ModelForm): name = forms.CharField(required=True) email = forms.EmailField(required=True) subject = forms.TypedChoiceField(choices=SubjectEnum.choices(), coerce=str) message = forms.CharField(widget=forms.Textarea) def __init__(self, *args, **kwargs): self.helper = FormHelper() self.helper.add_input(Submit('submit', 'Submit')) super(ContactForm, self).__init__(*args, **kwargs) And view.py file like belwo: class ContactFormView(FormView): form_class = ContactForm template_name = "contact/email_form.jade" success_url = '/email-sent/' def form_valid(self, form): message = "{name} / {email} said: ".format( name=form.cleaned_data.get('name'), email=form.cleaned_data.get('email')) message += "\n\n{0}".format(form.cleaned_data.get('message')) send_mail( subject=form.cleaned_data.get('-subject').strip(), message=message, from_email="enquiries@example.com", recipient_list=[settings.LIST_OF_EMAIL_RECIPIENTS], ) return super(ContactFormView, self).form_valid(form) Contact Form: - extends "base.jade" - load crispy_forms_tags block meta_title | Contact Us block content .jumbotron h1 Contact Us .row .span6 {% crispy form form.helper %} I get an error say, ValueError: ModelForm has no model class specified. Any idea guys? Thanks A: You should specify a Meta class inside your model form and set the model used. Note that you don't need to specify the form fields that are not different from your model's fields. class ContactForm(forms.ModelForm) name = forms.CharField(required=True) email = forms.EmailField(required=True) subject = forms.TypedChoiceField(choices=SubjectEnum.choices(), coerce=str) message = forms.CharField(widget=forms.Textarea) class Meta: model = Contact fields = ['name', 'email', 'subject', 'message'] If you don't have a model Contact, you should be using a Form instead of a ModelForm: class ContactForm(forms.Form): name = forms.CharField(required=True) email = forms.EmailField(required=True) subject = forms.TypedChoiceField(choices=SubjectEnum.choices(), coerce=str) message = forms.CharField(widget=forms.Textarea) def __init__(self, *args, **kwargs): self.helper = FormHelper() self.helper.add_input(Submit('submit', 'Submit')) super(ContactForm, self).__init__(*args, **kwargs) See the documentation for more information on ModelForms and their use.
{ "pile_set_name": "StackExchange" }
Q: How can I use a hlp file for context sensitive help in my application? I have a .hlp file that goes with the application. Because the functionality has not changed since I last wrote the app the hlp (written in 2003) is still valid. However when I compile the app in Delphi XE7 I cannot get the application to recognose the hlp file. In the .dpr file I have begin Application.Initialize; Application.HelpFile := 'Life32.hlp'; Application.Run; //sometimes the application hung here, due to OLE issues //exitprocess prevents that. ExitProcess(0); end. When I do procedure TProgCorner.Button2Click(Sender: TObject); begin Application.HelpContext(4); end; I get First chance exception at $75EEB9BC. Exception class EHelpSystemException with message 'No context-sensitive help installed'. The helpfile property of the form is set to exename.hlp. Manually double-clicking on the .hlp file in explorer opens the hlp file just fine. How do I get Delphi to open the hlp file when called upon? A: You must include the Vcl.WinHelpViewer unit in your project for the WinHelp system to be installed. Be warned that WinHelp support ended at XP and on later versions the WinHelp component must be installed separately.
{ "pile_set_name": "StackExchange" }
Q: Prove that the restriction of a Lebesgue measure on a subset is a complete measure Given a Lebesgue measure $m$ on a $\sigma$-field $\mathcal M$ and Lebesgue measurable set $B$ let $ \mathcal M_B = \{A \cap B\colon A \in \mathcal M\}$ and $ m_B(A) = m(A) $ How do I first show that $\mathcal M_B$ is a $\sigma$-field on subsets of $B$. $B$ belongs to $\mathcal M_B$ since $B = B \cap B $ and $B \in \mathcal M$ $ \bigcup_{i}(A_i \cap B) = (\bigcup_iA_i)\cap B $ How do I prove that if $A \cap B \in \mathcal M_B$, then $ (A \cap B) ^c \in \mathcal M_B$? A: Take the solution to this problem : Show: $\mathcal{G}:=\left\{B\in\mathcal{B}(\mathbb{R}^n)|t+B\in\mathcal{B}(\mathbb{R}^n)\right\}$ is $\sigma$-Algebra, and apply it to the inclusion function from $B$ to $\mathbb{R}$
{ "pile_set_name": "StackExchange" }
Q: Getting API response payload using fetch I am using fetch to get the API response for GET and POST requests. When an error occurs, I am able to see the status code and the text i.e, 400 Bad Request. However, there is additional information being passed that explains why the error was thrown (i.e. username did not match). I can see this additional message in the response payload via Firefox developer tool's console but I am not sure how to get it via handling the fetch response. Here's an example request: fetch(url, { method: 'POST', body: JSON.stringify({ name: name, description: description }), headers: { "Content-type": "application/json; charset=UTF-8", "Authorization": "Bearer " + token } }).then(response => { if (!response.ok) { throw Error(response.statusText) } return response }) .catch(error => { console.log(error) }) Any ideas? Thanks. A: Thank you everyone for your suggestions. This tutorial helped me understand what to do. https://css-tricks.com/using-fetch/ My problem was that when there is an error, the response is not JSON, it's text. So I needed to do something like this (taken from css-tricks.com): fetch('https://api.github.com/users/chriscoyier/repos') .then(response => response.text()) .then(data => { console.log(data) });
{ "pile_set_name": "StackExchange" }
Q: BigQuery - Group by on arrays I want to group by on an array. sample query: #standardSQL WITH `project.dataset.table` AS ( SELECT 'compute' description, '[{"key":"application","value":"scaled-server"},{"key":"department","value":"hrd"}]' labels, 0.323316 cost UNION ALL SELECT 'compute' description, '[{"key":"application","value":"scaled-server"},{"key":"department","value":"hrd"}]' labels, 0.342825 cost ) SELECT description, ARRAY( SELECT AS STRUCT JSON_EXTRACT_SCALAR(kv, '$.key') key, JSON_EXTRACT_SCALAR(kv, '$.value') value FROM UNNEST(SPLIT(labels, '},{')) kv_temp, UNNEST([CONCAT('{', REGEXP_REPLACE(kv_temp, r'^\[{|}]$', ''), '}')]) kv ) labels, cost FROM `project.dataset.table` Result of the above query: Row description labels.key labels.value cost 1 compute application scaled-server 0.323316 department hrd 2 compute application scaled-server 0.342825 department hrd I want result like below: Row description labels.key labels.value cost 1 compute application scaled-server 0.666141 department hrd A: #standardSQL WITH `project.dataset.table` AS ( SELECT 'compute' description, '[{"key":"application","value":"scaled-server"},{"key":"department","value":"hrd"}]' labels, 0.323316 cost UNION ALL SELECT 'compute' description, '[{"key":"application","value":"scaled-server"},{"key":"department","value":"hrd"}]' labels, 0.342825 cost ), temp AS ( SELECT description, labels, SUM(cost) AS cost FROM `project.dataset.table` GROUP BY description, labels ) SELECT description, ARRAY( SELECT AS STRUCT JSON_EXTRACT_SCALAR(kv, '$.key') key, JSON_EXTRACT_SCALAR(kv, '$.value') value FROM UNNEST(SPLIT(labels, '},{')) kv_temp, UNNEST([CONCAT('{', REGEXP_REPLACE(kv_temp, r'^\[{|}]$', ''), '}')]) kv ) labels, cost FROM temp
{ "pile_set_name": "StackExchange" }
Q: Angular-Highcharts: Cannot read property of 'Apartment' of undefined of an object I am using Highcharts with Angular and I have two objects. Object one have mock data and object two have data pull from the cloud via xmlHttpRequest. When I use object one in Highcharts I get the intended result but with object two I get ERROR TypeError: Cannot read property 'Condo' of undefined ERROR TypeError: Cannot read property 'Apartment' of undefined According to the console.log, two objects look and should be identical. Object One: var secondChartData = { Condo: [120], Apartment: [302], } //console log: secondChartData {Condo: Array(1), Apartment: Array(1)} Object Two: buildingTypeObj = {}; buildingType: any[] = []; buildingSize: any[] = []; constructor() { // other codes this.buildingType.push(...from Firebase...); this.buildingSize.push(...from Firebase...); for(var j = 0; j < this.buildingType.length; j++) { this.buildingTypeObj[this.buildingType[j]] = [this.buildingSize[j]]; } //console log: secondChartData {Condo: Array(1), Apartment: Array(1)} } Highcharts: ngAfterViewInit): void { // other codes function renderSecond(e) { var point = this; series: [{ data: this.buildingTypeObj[point.name], // doesn't work //data: secondChartData[point.name], // works }] } } REST API via async because that was the system was setup: static async getInfo() { // other codes const xmlHttp = new XMLHttpREquest(); xmlHttp.open("GET", groupsEndpoint, false); // false for async // other codes } I do not understand why object two returns an error. Can the error be caused by async? Here is my Fiddle to show the intended behaviors A: Since you used an ES5 function syntax, the context of this is changed. You can no longer access buildingTypeObj inside your component with this. Instead, have above your function a reference of this. ngAfterViewInit() { // other codes const self = this; function renderSecond(e) { series: [{ data: self.buildingTypeObj[this.name], data: secondChartData[this.name], }] } }
{ "pile_set_name": "StackExchange" }
Q: New to unity, why does this script not move the object? (Unity 3D) I am new to c# and unity, and I am trying to make a 3d game. This code is supposed to make a sword move back and forth, and when I press the button, unity acknowledges it, but the sword doesn't move. Does anyone know why it's doing this? using System.Collections; using System.Collections.Generic; using UnityEngine; public class slash : MonoBehaviour { // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { bool slas = false; if (Input.GetKeyDown(KeyCode.DownArrow)) { slas = true; } if (slas = true) { transform.Rotate(0, 30, 0); transform.Rotate(0,-30,0); } } } A: What you do right now in code is move your Sword 30 degress and than isntantly move it back 30 degrees. transform.Rotate(0, 30, 0); transform.Rotate(0,-30,0); And because it happens so fast you don't see it actually moving. What you need to do is add a Delay between these two actions to actually see it move. You could either use Animations and then play that Animation in code or you just use an IEnumerator to delay the second action. Code with IEnumerator: float delay = 0.5f; void Update() { if (Input.GetKeyDown(KeyCode.DownArrow)) { // Starting IEnumerator StartCoroutine(SwingSword()); } } IEnumerator SwingSword() { // Swing forwards transform.Rotate(0, 30, 0); // Delay yield return new WaitForSeconds(delay); // Swing backwards transform.Rotate(0,-30,0); }
{ "pile_set_name": "StackExchange" }
Q: Java character conversion to UTF-8 I am using: InputStreamReader isr = new InputStreamReader(fis, "UTF8"); to read in characters from a text file and converting them to UTF8 characters. My question is, what if one of the characters being read cannot be converted to utf8, what happens? Will there be an exception? or will get the character get dropped off? A: You are not converting from one charset to another. You are just indicating that the file is UTF 8 encoded so that you can read it correctly. If you want to convert from 1 encoding to the other then you should do something like below File infile = new File("x-utf8.txt"); File outfile = new File("x-utf16.txt"); String fromEncoding="UTF-8"; String toEncoding="UTF-16"; Reader in = new InputStreamReader(new FileInputStream(infile), fromEncoding); Writer out = new OutputStreamWriter(new FileOutputStream(outfile), toEncoding); After going through the David Gelhar's response, I feel this code can be improved a bit. If you doesn't know the encoding of the "inFile" then use the GuessEncoding library to detect the encoding and then construct the reader in the encoding detected. A: If the input file contains bytes that are not valid utf-8, read() will by default replace the invalid characters with a value of U+FFFD (65533 decimal; the Unicode "replacement character"). If you need more control over this behavior, you can use: InputStreamReader(InputStream in, CharsetDecoder dec) and supply a CharsetDecoder configured to your liking.
{ "pile_set_name": "StackExchange" }
Q: Could there be a meta CW or curated list of other venues for OT questions? I think I'm probably inviting the Paradox Police here, but... I wanted to post a URL to an author site and ask for a design/UX critique. A little poking around and I found a principle of "Don't ask for website critiques; besides a potential spam smell, critique questions are subjective and therefore off-topic." The natural question that leaves me with is, "The website critique I want is not appropriate anywhere under the SE umbrella; where might I go instead?" I have on a piecemeal basis found other good venues, i.e. Tom's for computer hardware / product recommendations. Perhaps (donning asbestos) there could be one exception, a curated community wiki for good places to go to a question that is off-topic under the entire SE umbrella. It is my opinion that there are some good, valuable questions that fall off-topic at times; I know it is not helpful to say "XYZ is a valuable question; if it's valuable we should change principles of inclusion," but it might be helpful, instead of saying "Your potentially valuable question is off-topic [note that I am not making that claim necessarily for my intended request for a website critique]; here are some other forums listed in the CW that would be more appropriate." Ok, waiting to get arrested by the Paradox Police... A: The very creation and curation of such a list would be subjective. What sites are better? Why did site A deserve mention or deserve being mentioned first over site B? As such, the list would be subject to edit wars, and attract spammers that want to see their current client's site listed, or listed higher, or whatever. And spammers don't limit themselves to links that are on topic either, anything for more visibility and page rank! There is a reason Stack Exchange avoids lists and recommendations, and a curated list of sites to take your off-topic post to is subject to the same limitations and problems. Instead, I think it is better to stick to a more non-committal statement: take open-ended discussions to another site, it is off-topic here. And we leave it at that.
{ "pile_set_name": "StackExchange" }
Q: 2008 Honda Accord turns over but wont start I have a 2008 Honda Accord 2.2 Diesel which turns over but won't start. There is 240,000 km on the clock. This issue first occurred about 9 weeks ago. I got in my car to go to work and it kept turning over but would not start. There is not a problem with the battery. A mechanic came to tow my car away, and dismiss any small problems, and he sprayed some starting fluid near the engine while I tried to start it. The car would start but would not stay running and would then cut out. The mechanic took the car away and fixed it by doing something to fix an issue with the car taking in air somewhere. I am unsure exactly what this fix was because in my eagerness to get home I did not clarify exactly what the problem was and what was fixed. My car broke down six weeks from the initial fix again in a completely different location, with the exact same problem, which necessitated a fix by a completely different mechanic. I contacted the first mechanic to see if they could remember exactly what they addressed the first time but they could not recall the exact problem and therefore I could not pass this information onto the next mechanic. The second mechanic fixed the car again but this fix only lasted two days this time as opposed to six weeks. The fix that this mechanic made was related to fuel injectors. The car is back with the same mechanic again as he is a competent mechanic but for my own peace of mind I am putting this question up and seeing if anyone can pinpoint the problem. Does anyone know what the problem could be? Edit: Still having the problem. The mechanic has put in a new diesel pump, one new injector and a new pressure switch. The problem is still occurring and I have returned the car to him. Possible fix found: My mechanic got a second opinion from a Honda specialist who was also stumped for an hour or so before they concluded that there was a problem with a weak release valve that was releasing excessive fuel back into the fuel tank. The car is currently starting sharply and I will be picking it up tomorrow. A: Since this car is a diesel, there are only 3 things required to make it run - fuel, air, and compression. As the problem is intermittent, it's probably not the compression (though that should be checked anyway). That leaves fuel and air, which must mix at a certain ratio to detonate in the cylinders. So, you either have a fuel system problem causing you to not get enough fuel (or too much fuel in some cases, but probably not enough based on your comments), or you have a problem with unmetered air entering the engine (intake, hoses, other leaks in the system). Diagnosing it would go something like this: Check for air leaks. This is done by a visual inspection, and can be tested with either a smoke test, or if the engine runs, by spraying flammable substances (starting fluid, carb cleaner, brake cleaner, etc) around the engine and seeing if the idle changes. Fix any leaks by replacing hoses, gaskets, and any broken parts. Check for fuel pressure. The fuel pump pressurizes the system, and there's a specific pressure rating defined by the manufacturer that must be present in order to spray the right amount of fuel. If you don't have enough fuel pressure, check the fuel pump, relay, wiring, fuse, fuel filters, release valve etc. If you have enough fuel pressure, next is the injectors. Make sure they're firing. If they're not, the injectors could be bad, or the computer (or mechanical system in some cases) controlling them could have failed. If the injectors are firing, they could still be partially or completely clogged, or even stuck open dumping too much fuel in. They should be removed and tested - whether or not you or your mechanic can do this depends on the injectors, they may have to be sent out to a specialist. From your story, the first mechanic addressed an air leak, and the second one addressed fuel pressure. It's hard to say if those were the actual problems, but I'd suggest looking for more air leaks first since that seemed to fix the problem for longer.
{ "pile_set_name": "StackExchange" }
Q: Using superuser.com to warn my own users In 2 days from now, users of legacy versions of our client-side software will no longer be able to login due to forced SSL setup update server-side. the error message will be cryptic. Also, we don't have the email of all such users hence can't easily communicate with them. Is it acceptable practice to ask a question on superuser.com (with error screenshot) and answer it ourselves (tell user to upgrade)? The idea is that superuser.com is well indexed and page ranked hence would show up high in results of users looking up the error message. A: I'd suggest a few things. Firstly, remember the question and answer format and don't make it like an ad. So, ask a question as a confused, lost user would, and answer it likewise Secondly, make it clear you work for the company - I notice you have it in your profile, but including it in your answer as well. Third is a general thing. Answers that link to a specific version are slightly lame. Link to a general update page rather than a direct link, so it would be usable should the version go off. Its unusual, but ought to be fine, as long as you do it right. I do notice some other non product activity and you've asked nicely, so as far as I go, I'm sure you aren't a spammer for doing this.
{ "pile_set_name": "StackExchange" }
Q: Soft question, matching multiplication tables I'm having troubles with an excercise from "Algebra: Chapter 0" Both $(\mathbb{Z}/5\mathbb{Z})^*$ and $\mathbb{Z}/12\mathbb{Z}$ * consist of 4 elements. Write their multiplication tables, and prove that no re-ordering of the elements will make them match. $(\mathbb{Z}/n\mathbb{Z})^*$ is multiplicative group of integers modulo n. $(\mathbb{Z}/5\mathbb{Z})^* = \{[1]_5,[2]_5,[3]_5,[4]_5\}$ and $(\mathbb{Z}/12\mathbb{Z})^* = \{[1]_{12}, [5]_{12}, [7]_{12}, [11]_{12}\}$ Here are the tables $\begin{array}{|c|c|c|c|c|} \hline * &[1]_5& [2]_5 & [3]_5 & [4]_5 \\ \hline [1]_5& [1]_5 & [2]_5 & [3]_5 & [4]_5 \\ \hline [2]_5& [2]_5 & [4]_5 & [1]_5 & [3]_5 \\ \hline [3]_5& [3]_5 & [1]_5 & [4]_5 & [2]_5 \\ \hline [4]_5& [4]_5 & [3]_5 & [2]_5 & [1]_5 \\ \hline \end{array}$ $\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \begin{array}{|c|c|c|c|c|} \hline * &[1]_{12}& [5]_{12} & [7]_{12} & [11]_{12} \\ \hline [1]_{12}& [1]_{12} & [5]_{12} & [7]_{12} & [11]_{12} \\ \hline [5]_{12}& [5]_{12} & [1]_{12} & [11]_{12} & [7]_{12} \\ \hline [7]_{12}& [7]_{12} & [11]_{12} & [1]_{12} & [5]_{12} \\ \hline [11]_{12}& [11]_{12} & [7]_{12} & [5]_{12} & [1]_{12} \\ \hline \end{array}$ But I do not really understand the task? What does it mean for tables to "match"? How do they match in this case? The only thing that comes to mind is that there are only two multiplication tables for any group of order $4$, one has single element of order $2$ and the other $3$. These two tables are representatives of such two types. I cannot really think of something else, what exactly should I prove and how? Could you help me? A: The right one always has one element on the diagonal, the left one does not. This is invariant under relabelling of the elements. (alternatively, every element in the right group (Kleinse Viergruppe) has order 2, while this is not the case for the cyclic left group.
{ "pile_set_name": "StackExchange" }
Q: Does a quantum channel being time-translation invariant imply that its Kraus operators commute with the Hamiltonian? Let $\mathcal E\in\mathrm{T}(\mathcal X,\mathcal Y)$ be a quantum channel (i.e. a completely positive, trace-preserving linear map sending states in $\mathrm{Lin}(\mathcal X,\mathcal X)$ into states in $\mathrm{Lin}(\mathcal Y,\mathcal Y)$). It is well known that any such map can be written in the Kraus decomposition as: $$\mathcal E(\rho)=\sum_a A_a\rho A_a^\dagger,$$ for a set of operators $A_a$ such that $\sum_a A_a^\dagger A_a=I$ (one can also choose these operators to be orthogonal with respect to the $L_2$ inner product structure: $\operatorname{Tr}(A_a^\dagger A_b)=\delta_{ab}p_a$). Suppose now that $\mathcal E$ is time-translation invariant. This means that, given an underlying Hamiltonian $H$ generating a time-evolution operator $U(t)$, we have $$\mathcal E(U(t)\rho U(t)^\dagger)=U(t)\mathcal E(\rho)U(t)^\dagger,\quad\forall t,\rho. \tag{1} $$ If $\mathcal E$ represented a simple unitary evolution $V$ (that is, $\mathcal E(\rho)=V\rho V^\dagger$), it would follow that $[V,H]=0$. Does this still apply for the Kraus operators of a general $\mathcal E$? In other words, does time-translation invariance imply that $[A_a,H]=0$ for all $a$? This question is related to this other question about how time-translation invariance implies preservation of coherence, as if the statement in this question is correct, then it should be easy to prove the statement in the other post. A: No. Take, for instance, the fully depolarizing channel, where $A_a=\{I,X,Y,Z\}$. Since $\mathcal E(\rho)=\tfrac12 I$, your condition $(1)$ holds for all $H$. On the other hand, there is no operator which commutes with all $A_a$. (Let me take the opportunity to advertise my list of canonical counterexamples for quantum channels ;) ). A: Writing the requirement explicitly $$\mathcal{E}(U\rho U^\dagger)=U\mathcal{E}(\rho)U^\dagger $$ in terms of Kraus operators $$\sum_a A_aU\rho U^\dagger A_a^\dagger=\sum_a U A_a\rho A_a^\dagger U^\dagger $$ Hence we want the channel with Kraus operators $ A'_a=A_aU $ and $A_a''=UA_a$ to be equal. We know that two channels are equal if and only if their Kraus representations are unitarily related, i.e. we have to find $B_{ij}$ such that $$ A''_j=\sum_k B_{jk}A_k'$$ and $$\sum_k B_{jk}B_{ik}^* =\delta_{ij}$$ the first condition is just $$ UA_j=\sum_k B_{jk}A_kU$$ or equivalently $$ UA_jU^\dagger=\sum_k B_{jk}A_k$$ This is a weaker requirement than commutation with $U$, as that is the particular case $B_{ij}=\delta_{ij}$. As Norbert Schuch said in his comment, this boils down to the Kraus representation being non unique (and thus in a sense, non physical). In a sense, the channel commutes with the evolution if the evolution scrambles the Kraus operators to a set that would produce the same physical effect.
{ "pile_set_name": "StackExchange" }
Q: LabelEncoder within Lambda function I'm working with the Ames, Iowa housing data, and I'd like to use a LabelEncoder within a lambda function to label encode my string values in my categorical features while skipping over the NaN values (so I can impute them later). This is what I have so far: train['Fireplace Qu'].apply(lambda x: LabelEncoder(x).fit_transform if type(x) != np.float else x) But it throws this error: TypeError: object() takes no parameters Any help would be greatly appreciated - trying to figure out a way to impute categorical data. A: Let us using factorize pd.Series(pd.factorize(df.group)[0]).replace(-1,np.nan) Out[141]: 0 NaN 1 NaN 2 0.0 3 0.0 4 NaN 5 NaN 6 NaN 7 NaN 8 1.0 dtype: float64 Or df.loc[df.group.notnull(),'group']=df.group.astype('category').cat.codes Data input group 0 NaN 1 NaN 2 a 3 a 4 NaN 5 NaN 6 NaN 7 NaN 8 b
{ "pile_set_name": "StackExchange" }
Q: What does 'ido-everywhere' actually do? When reading about ido, we are instructed to add this to .emacs: (ido-everywhere t) The doc says that it Toggle use of Ido for all buffer/file reading. What does it mean? Everything seems to work whether ido-everywhere is set or not. A: ido-everywhere function (define-minor-mode ido-everywhere "Toggle use of Ido for all buffer/file reading. With a prefix argument ARG, enable this feature if ARG is positive, and disable it otherwise. If called from Lisp, enable the mode if ARG is omitted or nil." :global t :group 'ido (remove-function read-file-name-function #'ido-read-file-name) (remove-function read-buffer-function #'ido-read-buffer) (when ido-everywhere (add-function :override read-file-name-function #'ido-read-file-name) (add-function :override read-buffer-function #'ido-read-buffer))) It overrides read-file-name-function (https://www.gnu.org/software/emacs/manual/html_node/elisp/Reading-File-Names.html), read-buffer-function (ftp://ftp.gnu.org/old-gnu/Manuals/elisp-manual-20-2.5/html_chapter/elisp_20.html). You can see the effect when you try File->Open File from menu bar. With ido-everywhere disabled, it opens graphical interface, but with ido-everywhere enabled it shows file list in mini buffer (ido style). Effect can be seen where ever these overrided functions are used.
{ "pile_set_name": "StackExchange" }
Q: React Performance Issues in Firefox? I'm experiencing some performance issues with a react application that I developed. These issues specifically (or most notably) occur with Firefox (both FF developer 77.0b7 and FF 76.0.1). When using this application in Firefox, CPU usage gets extremely high, and my fans start spinning up to very high speeds. I get about 15-19fps in firefox according to the performance tools in FF. I get roughly 60fps in Chrome and Safari. These issues occur when I begin typing into the input field, and get worse as the input gets longer (which makes sense) The application is available here: https://text-to-aura-generator.netlify.app/ Source code available here: https://github.com/paalwilliams/Text-to-Aura/tree/master/src I'm almost certain that this is something I'm doing incorrectly, or that I've written the code inefficiently, but that isn't necessarily supported by the stark performance difference between browsers. Is chrome just that much better and handling react/constant rerenders? I know that this is a broad question, but I honestly don't understand what is happening here, or necessarily how to troubleshoot it beyond the developer tools. Any input or thoughts would be greatly appreciated. A: The problem is your application is rendering too fast. In your particular case, there a few ways to improve that. Every time you update the state, React needs to re-render your application, so updating the state within a loop is usually a bad idea. Also, you are using useState 3 times, but only colors should be there, as App actually needs to re-render to reflect the changes there. The other two pieces of state (text and hex) are only being used to pass data from the handleChange to the callback inside useEffect. You can restructure your code to: Avoid updating the state within a loop. Use a simple variable instead of state. Use useCallback to define a function with that logic that is not re-created on each render, as that forces TextInput to re-render as well. Throttle this callback using something like this: import { useCallback, useEffect, useRef } from 'react'; export function useThrottledCallback<A extends any[]>( callback: (...args: A) => void, delay: number, deps?: readonly any[], ): (...args: A) => void { const timeoutRef = useRef<number>(); const callbackRef = useRef(callback); const lastCalledRef = useRef(0); // Remember the latest callback: // // Without this, if you change the callback, when setTimeout kicks in, it // will still call your old callback. // // If you add `callback` to useCallback's deps, it will also update, but it // might be called twice if the timeout had already been set. useEffect(() => { callbackRef.current = callback; }, [callback]); // Clear timeout if the components is unmounted or the delay changes: useEffect(() => window.clearTimeout(timeoutRef.current), [delay]); return useCallback((...args: A) => { // Clear previous timer: window.clearTimeout(timeoutRef.current); function invoke() { callbackRef.current(...args); lastCalledRef.current = Date.now(); } // Calculate elapsed time: const elapsed = Date.now() - lastCalledRef.current; if (elapsed >= delay) { // If already waited enough, call callback: invoke(); } else { // Otherwise, we need to wait a bit more: timeoutRef.current = window.setTimeout(invoke, delay - elapsed); } }, deps); } If the reason to use useEffect is that you were not seeing the right values when updating colors, try using the version of setState that takes a callback rather then the new value, so instead of: setColors([...colors, newColor]); You would have: setColors(prevColors => ([...prevColors , newColor]));
{ "pile_set_name": "StackExchange" }
Q: make app universally compatible for device with and without camera I face a strange problem, My application works perfectly on devices with or without a camera; only a few functionalities are not available if you don't have a camera. After uploading my app to the play store, the play store excluded some devices without a camera in which the app actually works fine! By using this permission: <uses-permission android:name="android.permission.CAMERA"/> play store auto excludes. Has anybody faced similar problems? Sorry if this is a duplicate (I hope it is not). A: From the docs: In some cases, the permissions that you request through can affect how your application is filtered by Google Play. If you request a hardware-related permission — CAMERA, for example — Google Play assumes that your application requires the underlying hardware feature and filters the application from devices that do not offer it. To control filtering, always explicitly declare hardware features in elements, rather than relying on Google Play to "discover" the requirements in elements. Then, if you want to disable filtering for a particular feature, you can add a android:required="false" attribute to the declaration. So, just add this to your manifest: <uses-feature android:name="android.hardware.camera" android:required="false"/>
{ "pile_set_name": "StackExchange" }
Q: LocationRequest constructor is marked as internal I'm trying to set up location updates in my Android app using com.google.android.gms:play-services-location:12.0.0, but I'm getting the following error: LocationRequest constructor is marked as internal and should not be accessed from apps My location updates request looks like this: locationClient.requestLocationUpdates( new LocationRequest() .setInterval(5000) .setFastestInterval(1000) .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY), locationCallback, null ); I have followed the docs and the example, which do it the same way. If I'm not supposed to call new LocationRequest(), then what is the proper way to do it? A: Use static methodLocationRequest create (). LocationRequest locationRequest = LocationRequest.create(); locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); locationRequest.setInterval(5000); locationRequest.setFastestInterval(1000); A: LocationRequest initialization procedure has changed into latest Google Play Service dependencies ( > 12.0.0). Now you can use its create() method to initialize this. e.g. LocationRequest request = LocationRequest.create();
{ "pile_set_name": "StackExchange" }
Q: Has an entire generation of a young children in a civilization ever been orphaned and raised as loyals? In a movie I watched a ruler kills all of the adults in a kingdom in order to raise the young children (who were too young to remember or at least understand the event) as loyal soldiers. Has anything like this ever happened in history? If so, which was the largest occurance? A: This is quite reminiscent of the Ottoman Empire's original Janissaries. At first these were young boys forcibly taken from Christian families as slaves and raised to be the Sultan's personal guard. Not being from Muslim families they could legally be enslaved, and they had no social position in the Empire apart from their relationship to the Sultan. So not only were they indoctrinated to be loyal soldiers, but their position was entirely dependent on their Sultan. Thus, unlike Muslim volunteer troops, they had nothing to gain and everything to lose if something were to happen to the Sultan.
{ "pile_set_name": "StackExchange" }
Q: Stop highligtning Bar color in MPAndroidChart? I am using MPAndroidChart in my application. The problem is, whenever I click any particular bar, it gets highlighted. I want to stop that and want it to be normal as it was before get clicked. I have tried these methods I found after doing study about it but nothing works fine: barChart.setClickable(false); barChart.setEnabled(false); barChart.setDrawHighlightArrow(false); barChart.setDrawBarShadow(false); barChart.getData().setHighlightEnabled(false); barChart.setHighlightPerTapEnabled(false); A: Try this to see if the problem solved barchart.setTouchEnabled(false);
{ "pile_set_name": "StackExchange" }
Q: Unsure of meaning of assignment function (variable assignment) in semantics of predicate logic? I'm currently in a mathematical linguistics course, and I'm having trouble understanding the meaning of 'g[d/v]: the variable assignment g′ that is exactly like g except (maybe) for g(v), which equals the individual d' in the semantics of predicate logic. If given a variable assignment in an example model, does this mean that (v) refers to all variables (d) that is in the universe, thus that all elements of the universe replaces the variable (v)? g1 = x1 → John x2 → Mary x3 → Pete xn → Pete (where n≥4) g1[John/x3] = x1 → John x2 → Mary x3 → John xn → Pete (where n≥4) g1[[John/x3]Pete/x1] = x1 → Pete x2 → Mary x3 → John xn → Pete (where n≥4) Also, I have an exercise based on variable assignment equivalence, but I do not know how to approach answering these questions since I do not entirely understand the meaning of variable assignment, and modified variable assignment. QUESTION: Complete the equivalences assuming: g(x) = Mary, and g(y) = Susan. 1. g[Paul/x)(x) = 2. g[Paul/x)(y) = 3. g[[Paul/x]Susan/x)(x) = 4. g[[Paul/x]Susan/x)(y) = 5. g[(Paul/x)Susan/y)(x) = 6. g[[Paul/x]Susan/y)(y) = If anyone could explain this concept to me, I would be very grateful! EDIT: sorry, i'm quite new to this site! the questions were cut off by the closed bracket. I've tried attempting the questions below. 1.g[Paul/x)(x) = x: Paul 2.g[Paul/x)(y) = y: Susan 3.g[[Paul/x]Susan/x)(x) = x: Susan? 4.g[[Paul/x]Susan/x)(y) = y: Susan? 5.g[[Paul/x]Susan/y)(x) = x: Paul? 6.g[[Paul/x]Susan/y)(y) = y: Susan? I'm a bit unsure about some of these, if x is originally mapped to Mary, then to Paul & Susan in (3&4) A: If given a variable assignment in an example model, does this mean that (v) refers to all variables (d) that is in the universe, thus that all elements of the universe replaces the variable (v)? No. A variable assignment maps every variable to a specific individual. You can see that with your first example: g1 = x1 → John x2 → Mary x3 → Pete xn → Pete (where n≥4) However, we can change those assignments when we do something like: g1[John/x3] This means that everything gets assigned the same individual as above, except that we now map $x3$ to John, so we get: g1[John/x3] = x1 → John x2 → Mary x3 → John xn → Pete (where n≥4) So, for last exercise at the end, your initial g is: g = x → Mary y → Susan So that means that g[Paul/x] is: g[Paul/x] = x → Paul y → Susan Can you do the others?
{ "pile_set_name": "StackExchange" }
Q: Undo: export GIT_ASKPASS="" I'm relatively new to git/gitlab. For my school gitlab account, I was trying to setup git push to not continuously ask for my rsa passphrase by using: export GIT_ASKPASS="<password goes here>" It did not work, and now I'm stuck trying to push to gitlab with a refused connection. Is there an easy way out? Or do I have to setup my rsa keys all over again? Thanks in advance for helping a noob in distress. A: It is best at first to generate ssh keys without a passphrase. Or you would have to deal with ssh-agent, as described in "Adding your SSH key to the ssh-agent" ssh-keygen -t rsa -C "key for xxx access" -q -P "" Publish your public key to your GitLab account, and it should not ask for a passphrase (provided you are using a git@gitlab.com:<username>/<reponame> ssh url, not an https one)
{ "pile_set_name": "StackExchange" }
Q: Why isn't every vertex connected to every other vertex in TextRank? I've been reading up on the automatic text summarization approach TextRank, particularly for generating summaries of a text using sentence extraction as opposed to keyword or phrase extraction. In the published paper, an example body of text and the resulting ranked graph of all sentences/vertices and their edges is given. I'm unclear as to why every vertex doesn't have an edge connecting it to every other vertex in the graph - shouldn't all sentences be compared with each other? This doesn't seem to be addressed in the paper. One possible explanation I've produced is that there is no edge if the similarity between two sentences is 0. Does anyone know for sure? Link to paper: https://web.eecs.umich.edu/~mihalcea/papers/mihalcea.emnlp04.pdf A: After getting in touch with the authors of the paper, the reason why every vertex isn't connected to every other vertex in the graph is because only edges with a non-zero weight are added to the graph.
{ "pile_set_name": "StackExchange" }