text
stringlengths
64
81.1k
meta
dict
Q: Best packages for writing a script for a comedy sketch Possible Duplicate: What are good packages for laying out a play? I'm about to start writing some scripts for some comedy sketches and I would like some advice on how to do it best in LaTeX. The scripts will need to have bits of information like stage directions and dialogue. A: Have a look at the dramatist package. Some other packages which might help you: drama plari play
{ "pile_set_name": "StackExchange" }
Q: Show data when it's attribute is clicked using bootstrap collapsing I wanted to show $request, $order_no, $site_location, $item_code, $Time when the $name is clicked. How can I do it? I want to use bootstrap collapsing but I am stuck. How can I pass the value as it's in a while loop and contains many elements. How could I identify which one is clicked, using bootstrap? <div class="row"> <tr><td><div class="col-md-2"> <?php echo $name;?></div></td> <td><div class="col-md-2"> <?php echo $request;?></div></td> <td><div class="col-md-2"> <?php echo $order_no;?></div></td> <td><div class="col-md-2"> <?php echo $site_location;?></div></td> <td><div class="col-md-2"> <?php echo $item_code;?></div></td> <td><div class="col-md-2"> <?php echo $request;?></div></td> <td> <div class="col-md-2"><?php echo $Time;?></div></td> <td><div class="col-md-2"><a href=update_status.php?flag=p&ep=<?php echo $ee; ?>><span class="glyphicon glyphicon-lock" style='margin-right:60px'></span></a></div></td> <td><div class="col-md-2"><a href=update_status.php?flag=a&ep=<?php echo $ee; ?>><span class="glyphicon glyphicon-thumbs-up" style='margin-right:60px'></span></a></div></td> <td><div class="col-md-2"><a href=update_status.php?flag=r&ep=<?php echo $ee; ?>><span class="glyphicon glyphicon-thumbs-down" style='margin-right:60px'></span></a></div></tr></td> </div> A: If I understand it correctly, you have multiple elements (in a loop) and when you click on the td/col-md-2 with the $name you want to show the rest of the columns? The Bootstrap collapse let you define a element and set it's target with: data-toggle="collapse" data-target="#collapseExample" See: http://getbootstrap.com/javascript/#collapse Your html could become something like this (haven't tried it yet): <div class="row"> <tr> <td><div class="col-md-2" data-toggle="collapse" data-target="#collapse<?php echo $name; ?>"> <?php echo $name;?></div></td> <div class="collapse" id="collapse<?php echo $name; ?>"> <td><div class="col-md-2"> <?php echo $request;?></div></td> <td><div class="col-md-2"> <?php echo $order_no;?></div></td> <td><div class="col-md-2"> <?php echo $site_location;?></div></td> <td><div class="col-md-2"> <?php echo $item_code;?></div></td> <td><div class="col-md-2"> <?php echo $request;?></div></td> <td> <div class="col-md-2"><?php echo $Time;?></div></td> <td><div class="col-md-2"><a href=update_status.php?flag=p&ep=<?php echo $ee; ?>><span class="glyphicon glyphicon-lock" style='margin-right:60px'></span></a></div></td> <td><div class="col-md-2"><a href=update_status.php?flag=a&ep=<?php echo $ee; ?>><span class="glyphicon glyphicon-thumbs-up" style='margin-right:60px'></span></a></div></td> <td><div class="col-md-2"><a href=update_status.php?flag=r&ep=<?php echo $ee; ?>><span class="glyphicon glyphicon-thumbs-down" style='margin-right:60px'></span></a></div></td> </div> </tr> </div> Hope I pointed you into the right direction.
{ "pile_set_name": "StackExchange" }
Q: Visual Studio 2008 Setup Project - Include .NET Framework 3.5 I built a Visual Studio 2008 setup Project wich depends on .NET 3.5. I added Prerequisites like: .NET 3.5, Microsoft office interoperability, VS tools for office System 3.0 Run time, .etc. After that Selected "Download Prerequisite from Same location as my application" in Specify install location for Prerequisite. I Built the setup and found mysetup.msi in Release directory. In a new machine I started fresh installation of my application. A dialog shows like this "This Setup Requires .NET framework 3.5 , Please install .NET setup then run this setup, .NET Framework can be obtained from web Do you want to do that now?" it gives "Yes" and "No" option - if I press yes it goes to Microsoft website. How can avoid it? I wanted setup take .NET Framework to be installed from same location where I put all setup files including mysetup.msi? In case of quiet installation cmd /c "msiexec /package mysetup.msi /quiet /log install.log" ..in log I can see only half way through installation then error Property(S): HideFatalErrorForm = TRUE MSI (s) (D0:24) [00:07:08:015]: Product: my product-- Installation failed. === Logging stopped: 3/23/2010 0:07:08 === How can complete I the installation without user intervention and without error using VS2008 setup project? Thanks for all the help in advance for any input. A: On a default installation of Visual Studio 2008, the .NET Framework 3.5 SP1 prerequisite is not available for local installation. If you want to include the .NET Framework 3.5 SP1 setup with you application installer you need to follow the instructions listed in How to Include .NET Framework 3.5 SP1 with Your Installer. On a side note, welcome to SO. Don't forget to check out the FAQ to get to information on how the site works.
{ "pile_set_name": "StackExchange" }
Q: Get ArrayList index I'm trying to access the current index of an array list but can't figure out how to do it in the following method: public String getNextMessage(){ String s = getMessageArray(index); index++; return s; } The "getMessageArray" comes up with an error and I don't know hwo to resolve it. This method worked with Arrays[] but I don't know how to do it with an ArrayList. Here is the whole class file: package com.game.main; import java.util.ArrayList; public class Message { private int index; private ArrayList<String> messageArray; private String intro = "Welcome."; public Message() { messageArray = new ArrayList<String>(); messageArray.add(intro); } public String getNextMessage(){ String s = getMessageArray(index); index++; return s; } public ArrayList<String> getMessageArray() { return messageArray; } public void setMessageArray(ArrayList<String> messageArray) { this.messageArray = messageArray; } } A: As I wrote in an earlier answer public String getNextMessage(){ String s = messages.get(indx); indx++; return s; } however, it seems you changed the part where the list is accessed from String s = messages.get(indx); to String s = getMessageArray(index); The reason your version doesnt work is, that the you are trying to call a method called getMessageArray(index), that returns the ArrayList object itself, which is an ArrayList. What you actually want to do is to call the get()-method of the ArrayList class. You have declared a variable called messages earlier in your class private ArrayList<String> messages; Here you can see messages is of type ArrayList. ArrayList has a method called get(int index) which retrieves the element at the specified index. You can call this method the way I wrote at the beginning of this answer. For reference, you can view all methods available on arraylist here.
{ "pile_set_name": "StackExchange" }
Q: Create vertical space (gaps) between rows in CSS Grid Is there any way to have my vertically stacked buttons have a gap between them, other than using the break (<br>) tag? I've exhausted every other option and nothing seems to work other than using the break (<br>) tag in the html sheet after each div. Here is my code (break tags taken out): $(document).ready(function() { var lat; var long; $.getJSON("https://freegeoip.net/json/", function(data2) { lat = data2.latitude; long = data2.longitude; console.log(lat); console.log(long); //creating an api with the user's geolocation var api = "https://api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + long + "&appid=b6e4d569d1718b07a44702443dd0ed77" //json call for the api $.getJSON(api, function(data) { var fTemp; var cTemp; var tempSwap = true; var weatherType = data.weather[0].description; var kTemp = data.main.temp; var windSpeed = data.wind.speed; var city = data.name; $("#city").html(city); fTemp = (kTemp * (9 / 5) - 459.67).toFixed(2); cTemp = (kTemp - 273).toFixed(1); $("#api").html(api); $("#weatherType").html(weatherType); $("#fTemp").html(fTemp + "&#8457;"); $("#fTemp").click(function() { if (tempSwap === false) { $("#fTemp").html(fTemp + "&#8457;"); tempSwap = true; } else { $("#fTemp").html(cTemp + "&#8451;"); tempSwap = false; } }); $("#windSpeed").html(windSpeed + "m/sec"); }) if (fTemp >= 100) { $("container").css("background-image", "url(https://s2.postimg.org/6ss6kyuhl/yamaha_yzf_r1-wallpaper-1024x768.jpg)"); } else if (fTemp < 90) { $("container").css("background-image", "url(https://s2.postimg.org/lapdsz8y1/beyonce_knowles_2-wallpaper-1024x768.jpg)") } else if (fTemp > 80) { $("container").css("background-image", "url(https://s2.postimg.org/i54s2ennd/Beyonce_in_Jamaica.jpg)") } else if (fTemp < 70) { $("container").css("background-image", "url(https://s2.postimg.org/t4pzebr0p/golf_course_landscape-wallpaper-1024x768.jpg)") } else if (fTemp < 60) { $("container").css("background-image", "url()") } else if (fTemp < 50) { $("container").css("background-image", "url(https://s2.postimg.org/8xcjlpoax/rihanna_9-wallpaper-1024x768.jpg)") } else if (fTemp = 37.40) { $("container").css("background-image", url("https://s2.postimg.org/8xcjlpoax/rihanna_9-wallpaper-1024x768.jpg")) } else if (fTemp < 30) { $("container").css("background-image", "url(https://s2.postimg.org/nhtmgb6c9/white_snowy_road-wallpaper-1024x768.jpg)") } else if (fTemp < 20) { $("container").css("background-image", "url(https://s2.postimg.org/9a3xrntnd/rihanna_dior_sunglasses-wallpaper-1024x768.jpg)") } else if (fTemp < 10) { $("container").css("background-image", "url()") } else if (fTemp < 0) { $("container").css("background-image", "url(https://s2.postimg.org/r05mdaf49/snowy_cabin_mountains_winter-wallpaper-1024x768.jpg)") } else if (fTemp < -10) { $("container").css("background-image", "url(https://s2.postimg.org/7v2d3i5l5/skiing-wallpaper-1024x768.jpg)") }; }); }); .container { text-align: center; background: url("https://s1.postimg.org/14i3xf2um7/Hummer-_H1-_Snow-_Turn-_Headlights-1024x768.jpg") no-repeat fixed; background-size: cover; background-position: center; /*background-color: blue;*/ width: 100%; height: 1000px; margin: auto; } .About { /*background-color: blue;*/ /*transform: translateY(650%)*/ position: fixed; top: 35%; left: 0; right: 0; margin: auto; } h2 { color: white; font-size: 1.5em } .holder { border: 3px; background-color: rgba(0, 0, 0, .80); width: 55%; height: auto; position: fixed; top: 50%; left: 0; right: 0; margin: auto; padding-top: 5px; padding-bottom: 10px; padding-left: 3px; padding-right: 3px; border: 3px solid grey; border-radius: 10px; } #city, #weatherType, #fTemp, #windSpeed { transform: translateY(9%); background-color: #c6c6c4; border-bottom: 2px inset #FFF; border-right: 2px inset #FFF; border-radius: 5px; height: 30px; width: 90%; margin: auto; /*padding-bottom: 2px ;*/ } .btn.btn-default { color: #0040ff; font-size: .80em; font-family: Orbitron, sans-serif; line-height: 2.45em; } @media(min-width: 500px) { .holder { display: grid; grid-template-columns: 1fr 1fr 1fr 1fr; } } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <html> <title></title> <head> <link href='https://fonts.googleapis.com/css?family=Orbitron' rel='stylesheet' type='text/css'> </head> <body> <div class="container"> <div class="About"> <h2>Your Local Weather App</h2> </div> <div class="holder"> <div class="btn btn-default" id="city"> </div> <div class="btn btn-default" id="weatherType"> </div> <div class="btn btn-default" id="fTemp"> </div> <div class="btn btn-default" id="windSpeed"> </div> </div> </div> </body> Here is my CodePen. A: This is what you already have for wider screens: @media (min-width: 500px) { .holder { display: grid; grid-template-columns: 1fr 1fr 1fr 1fr; } } Add this for smaller screens, where you want your elements vertically stacked in one column: .holder { display: grid; grid-template-columns: 1fr; grid-row-gap: 1em; } Revised CodePen Grid provides grid-column-gap, grid-row-gap and grid-gap (the shorthand), which create space between grid items (but not between items and the container). 10.1. Gutters: the grid-column-gap, grid-row-gap, and grid-gap properties These properties specify the gutters between grid rows and grid columns, respectively.
{ "pile_set_name": "StackExchange" }
Q: array.shape() giving error tuple not callable I have a 2D numpy array called results, which contains its own array of data, and I want to go into it and use each list: for r in results: print "r:" print r y_pred = np.array(r) print y_pred.shape() This is the output I get: r: [ 25. 25. 25. 25. 25. 25. 26. 26. 26. 26. 26. 22. 27. 27. 42. 23. 23. 23. 28. 28. 28. 44. 29. 29. 30. 30. 30. 18. 18. 18. 19. 30. 17. 17. 17. 17. 2. 19. 2. 17. 17. 17. 17. 17. 17. 4. 17. 17. 41. 7. 17. 19. 19. 19. 10. 32. 4. 19. 34. 19. 34. 34. 34. 34. 34. 34. 20. 20. 20. 36. 36. 36. 4. 36. 36. 22. 22. 22. 22. 22. 22. 23. 23. 23. 27. 27. 27. 24. 39. 39. 10. 10. 10. 6. 10. 10. 11. 11. 11. 11. 11. 11. 12. 12. 12. 12. 12. 12. 13. 13. 13. 14. 14. 14. 15. 15. 15. 1. 17. 1. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 19. 19. 19. 2. 2. 4. 3. 3. 3. 4. 4. 4. 4. 4. 4. 4. 19. 4. 4. 4. 17. 5. 5. 5. 6. 6. 6. 6. 6. 6. 7. 7. 7. 7. 7. 7. 8. 8. 8. 8. 8. 8. 9. 9. 9. 23. 38. 38. 34. 34. 10. 17. 17. 26. 0. 42. 0. 18. 32. 32. 0. 0. 21. 38. 38. 38. 27. 27. 27. 0. 0. 0. 34. 2. 2. 0. 26. 26. 36. 0. 36. 36. 36. 23. 0. 27. 38. 25. 25. 25. 26. 26. 26. 0. 15. 15. 32. 38. 38. 0. 32. 32. 32. 41. 32. 7. 34. 32. 42. 34. 34. 36. 36. 25. 32. 32. 32. 36. 17. 8. 32. 17. 38. 3. 3. 3. 18. 18. 18. 0. 1. 1. 34. 1. 1. 34. 17. 17. 34. 34. 34. 34. 34. 34. 17. 17. 17. 24. 2. 32. 2. 2. 2. 0. 2. 2. 0. 34. 34. 0. 1. 1. 38. 23. 38.] Traceback (most recent call last): File "C:\Users\app\Documents\Python Scripts\gbc_classifier_test.py", line 93, in <module> print y_pred.shape() TypeError: 'tuple' object is not callable I don't understand why y_pred is not a regular array and why it's being considered a tuple, I've assigned it to be an array using r. A: shape is just an attribute, not a method. Just use y_pred.shape (no parentheses). (The error message isn't telling you that y_pred is a tuple, it's telling you that y_pred.shape is a tuple.)
{ "pile_set_name": "StackExchange" }
Q: Both OpenID and normal Login on the same View? Is there any site that show both OpenID and normal login on the same view? Most of the sites either have OpenID implementation or Normal Login implementation on different views. I tried to do that, but it seems my code is very dirty, passing a blank username and password if using OpenID, otherwise OpenID will be blank but passed the username and password. But then I lose the capability of verifying whether the user has entered the correct values, is there any best practice for me to do that? Thanks a lot A: Have you taken a look at NerdDinner? It's an open source sample that includes the dual login screen that you're asking for. It uses DotNetOpenAuth, so it should be easy to apply to your site as well.
{ "pile_set_name": "StackExchange" }
Q: Difference between cryptanalysis and brute force attacks I wonder about the difference between brute force and cryptanalysis attack? as my professor asked us about the difference, but i searched and found that the brute force is one type of cryptanalysis attacks is that true or there's a difference between them ? Thanks in advance. A: That's a matter of terminology, but generally cryptanalysis and brute force attack are mutually exclusive. Cryptanalysis means attacking a cryptographic system by looking for something clever that the designers of the system didn't think of, for example finding a mathematical relation that makes some computation fasters. A brute force attack is one that doesn't use any intelligence and enumerates all possibilities; cryptography is always vulnerable to brute force attacks, but if properly designed it makes them practically impossible by arranging for the probability of success to be utterly negligible.
{ "pile_set_name": "StackExchange" }
Q: Parsing a faxed form Looking at a scenario where a form (consisting of, for simplicity sake, checkboxes only) is faxed to a fax server capable of OCR. Now, with typographic text, I've see various OCR implementations doing a decent job, but I'm not sure how it would handle checkboxes, especially handwritten "x" or checks, not to mention the coordinates. Back in grade school, we used to fill in those Gauss (sic) tests with HB pencil shading in the correct answer; somewhere, somehow, that was parsed and analyzed. Where are we at today? Is there anything out-of-the-box? A: You are referring to Optical Mark Recognition (OMR) technology commonly user by Scantron and NCS in many US schools. Most OCR servers would have no real concept of reading OMR unless it is specifically designed to recognise different form types. It sounds like your OCR fax server software probably only does a full page OCR and would have no concept of OMR fields. You could possibly rig something up without investing too much effort or cost. If you design you questions as per the following guidelines it could possibly work quite well. Which fruit do you prefer to eat ? < > Apple < > Pear < > Orange < > Banana When the OCR engine comes back with the OCR text you could assume that any characters read between the < and > characters is an OMR mark even if it is an unrecognised character. Which fruit do you prefer to eat ? < > Apple < x > Pear < ? > Orange < > Banana This would indicate that Pear and Orange were marked. TeleForm is a commercial package that could import the images and process the fax pages but you would need to design the form in Teleform first. http://www.cardiff.com/products/index.html
{ "pile_set_name": "StackExchange" }
Q: Can a gas cloud of pure helium collapse and ignite into a star? Assuming there could be a giant gas cloud with negligible amount of hydrogen and metal (elements with atomic number $Z\geq3$), could it collapse gravitationally and form a pure helium star that would skip the main sequence entirely? I think it's possible in principle but my main concern is that the ignition of $^4$He is a 3-body reaction (the triple alpha process) and requires a higher temperature and a higher density than the pp-chain or the CNO cycle. Would the gas keep collapsing until it reaches the critical density for carbon formation or would it reach hydrostatic equilibrium before that point, preventing further collapse and star formation? Perhaps it's only a matter for the cloud to have a minimal mass that allows the nuclear reaction? If so, how can I predict this minimal mass? A: The answer is that if you ignore degeneracy pressure, then indeed a collapsing cloud of helium must eventually reach a temperature that is sufficient to initiate the triple alpha $(3\alpha)$ process. However, electron degeneracy pressure means that below a threshold mass, the centre will not become hot enough to ignite He before the star is supported against further collapse. The virial theorem tells us that (roughly) $$ \Omega = - 3 \int P\ dV\ ,$$ where $\Omega$ is the gravitational potential energy, $P$ is the pressure and the integral is over the volume of the star. In general this can be tricky to evaluate, but if we (for a back of the envelope calculation) assume a uniform density (and pressure), then this transforms to $$ -\frac{3GM^2}{5R} = -3 \frac{k_B T}{\mu m_u} \int \rho\ dV = -3 \frac{k_B T M}{\mu m_u}\ , \tag*{(1)}$$ where $M$ is the stellar mass, $R$ the stellar radius, and $\mu$ the number of mass units per particle ($=4/3$ for ionised He). As a contracting He "protostar" radiates away gravitational potential energy, it will become hotter. From equation (1) we have $$ T \simeq \left(\frac{G \mu m_u}{5k_B}\right) \left( \frac{M}{R} \right)$$ Thus for a star of a given mass, there will be a threshold radius at which the contacting protostar becomes hot enough to ignite He ($T_{3\alpha} \simeq 10^{8}$ K). This approximation ignores any density dependence, but this is justified since the triple alpha process goes as density squared, but temperature to the power of something like 40 (Clayton, Principles of Stellar Evolution and Nucleosynthesis, 1983, p.414). Putting in some numbers $$ R_{3\alpha} \simeq \left(\frac{G \mu m_u}{5k_B}\right) \left( \frac{M}{T_{3\alpha}} \right) = 0.06 \left(\frac{M}{M_{\odot}}\right) \left( \frac{T_{3\alpha}}{10^8\ {\rm K}}\right)^{-1}\ R_{\odot} \tag*{(2)}$$ The question then becomes, can the star contract to this sort of radius before degeneracy pressure steps in to support the star and prevent further contraction? White dwarfs are supported by electron degeneracy pressure. A "normal" white dwarf is composed of carbon and oxygen, but pure helium white dwarfs do exist (as a result of mass transfer in binary systems). They have an almost identical mass-radius relationship and Chandrasekhar mass because the number of mass units per electron is the same for ionised carbon, oxygen or helium. A 1 solar mass white dwarf governed by ideal degeneracy pressure has a radius of around $0.008 R_{\odot}$, comfortably below the back-of-the envelope threshold at which He burning would commence in a collapsing protostar. So we can conclude that a 1 solar mass ball of helium would ignite before electron degeneracy became important. The same would be true for higher mass protostars, but at lower masses there will come a point where electron degeneracy is reached prior to helium ignition. According to my back-of-the-envelope calculation that will be below around $0.3 M_{\odot}$ (where a white dwarf would have a radius of $0.02 R_{\odot}$), but an accurate stellar model would be needed to get the exact figure. I note the discussion below the OP's question. We could do the same thing for a pure hydrogen protostar, where $\mu=0.5$ and the number of mass units per electron is 1. A hydrogen white dwarf is a factor of $\sim 3$ bigger at the same mass (since $R \propto $ the number of mass units per electron to the power of -5/3 e.g. Shapiro & Teukolsky, Black Holes, White Dwarfs and Neutron Stars). But of course it is not the triple alpha reaction we are talking about now, but the pp-chain. Figuring out a temperature at which this is important is more difficult than for the $3\alpha$ reaction, but it is something like $5\times 10^{6}$ K. Putting this together with the new $\mu$, the leading numerical factor in equation (2) grows to 0.5. Thus my crude calculation of a threshold radius for pp hydrogen burning would intersect the hydrogen white dwarf mass-radius relationship at something like $0.15M_{\odot}$, which is quite near the accepted star/brown dwarf boundary of $0.08M_{\odot}$ (giving some confidence in the approach).
{ "pile_set_name": "StackExchange" }
Q: Why does a node try all grey peers to create a connection? I am currently analysing the source code of Monero. If a node makes a new connection, it first checks what fraction of its current outgoing connections are to nodes in its white list. If it is above an expected fraction (default is 70 percent), then it attempts to connect to grey-listed peers and then (if necessary) white-listed peers. However, If I understand that part of the code correctly, it will try all grey peers to create a connection. In case we want to connect to a white peer, we will try a limited (probably 3 iteration and we try 20 peers per iteration) number of peers. Has anybody an idea why the developers chose to do it that way? Isn't it wasteful to try the whole grey list (up to 5,000 entries)? Where at the same time we maintain a white list of probably online peers? A: This does not try all entries in the set, it picks one entry in that set.
{ "pile_set_name": "StackExchange" }
Q: Javascript error while calculating I have a php simple program to calculate a textbox with another textbox, 1 years ago, there's no problem after now, I have problem with my JavaScript. It can't count my textbox. My form code is here (without html tag, to minimize code in here): <table> <tr> <td>Tol</td> <td>:</td> <td><input type="text" maxlength="11" name="tol" onkeydown="calculate()" value="0" /></td> </tr> <tr> <td>Parkir</td> <td>:</td> <td><input type="text" maxlength="11" name="parkir" onkeydown="calculate()" value="0" /></td> </tr> <tr> <td>Joki</td> <td>:</td> <td><input type="number" maxlength="11" name="joki" onkeydown="calculate();" value="0" /></td> </tr> <tr> <td>Other</td> <td>:</td> <td><input type="number" name="other" maxlength="11" onkeydown="calculate();" value="0" /> <input type="text" name="othername" maxlength="50" /> </td> </tr> <tr> <td>Total</td> <td>:</td> <td><input type="text" id="subtotal" onfocus="this.value = numberFormat(this.value);" name="subtotal" maxlength="100" value="0" /> <input type="text" id="totalbox" name="totalbox" maxlength="100" /> </td> </tr> </table> and my JS script: function calculate(){ var num1=document.myform.tol.value; var num2=document.myform.parkir.value; var num3=document.myform.joki.value; var num4=document.myform.other.value; var sum=parseFloat(num1)+parseFloat(num2)+parseFloat(num3)+parseFloat(num4); document.getElementById('totalbox').value=sum.toString(); document.getElementById('subtotal').value=sum.toString(); } can somebody correct my code or is there any update from JS that made my JS code doesn't work now? A: Try using the onkeyup event instead of onkeydown. The onkeydown event fires before the value of your textbox reflects the input being typed in.
{ "pile_set_name": "StackExchange" }
Q: How Can I Download A Computer Backup? Using Backup and Sync by Google, I had backed up my prior computer (a Mac Mini) to Google Drive (I have a lot of storage). Now, I just got my new computer (a Macbook Pro), and I'm having trouble downloading the backup. When I try to do the usual right click and download, the zipping of the folder always takes forever and times out (I've left the computer on overnight, making sure it won't turn off and it always tells me that the zip failed). Is there a better way to do this? I tried Google Takeout but it doesn't access the Computer section of Google Drive. A: If it is a large folder, downloading as a zip from Google will often time out due to Google converting all the Gdoc files and then splitting all your files in that folder into 2GB Zip files. (Have done many times before) I would recommend installing backup and Sync onto your new Macbook Pro, not selecting any folders on the first step (My Macbook) - this is asking what you want to send into the cloud. But then on step 3 selecting sync My Drive to this computer, and sync all your files. After it is completed downloading from Google drive you can move them where you like out of the Google drive folder and exit the Backup and Sync. (I've done this recently from Macbook to iMac, and can say it is the easiest and fastest way by far)
{ "pile_set_name": "StackExchange" }
Q: How to get the Windows "Digit Grouping" setting In the Windows Regional control panel is a "Digit Grouping" setting, which indicates whether the Indian numbering system is used, where the thousands separator character groups the first three digits to the left of the decimal together, and thereafter every two digits, vs. the more common grouping where every three digits to the left the decimal are grouped together. How can I get that setting in VB6? Or, alternatively, what is the best way to determine when to use that Indian numbering system? A: Private Const LOCALE_SGROUPING = &H10 Private Const LOCALE_USER_DEFAULT = &H400 Private Declare Function GetLocaleInfo Lib "kernel32" Alias "GetLocaleInfoA" (ByVal Locale As Long, ByVal LCType As Long, ByVal lpLCData As String, ByVal cchData As Long) as Long Private Function Grouping() As String Dim retVal As Long, sBuf As String sBuf = String(255, vbNullChar) retVal = GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_SGROUPING, sBuf, Len(sBuf)) Grouping = Left$(sBuf, retVal - 1) End Function Example: will output: 3;0 for 123.456,789 and 3;2;0 for 12.34.56,789
{ "pile_set_name": "StackExchange" }
Q: Rerender view in emberjs I have an array object in View with binding from Controller. When I change the array in controller, the array in view change properly. But my template for view that seems to be broken: http://jsfiddle.net/secretlm/2C4c4/84/ When I try to use rerender method in view. My template isn't broken. This fiddle works well: http://jsfiddle.net/secretlm/2C4c4/85/ HTML: <script type="text/x-handlebars" data-template-name="test"> <button {{action "changeContent" target="App.latController"}}> Change</button> {{#each element in view.content}} <!-- if openTag is true, <ol> tag is created --> {{#if element.openTag}} <ol> {{/if}} <li>{{element.teo.item.Name}}</li> <!-- if closeTag is true, </ol> tag is created --> {{#if element.closeTag}} </ol> {{/if}} {{/each}} </script>​ Javascript: App = Ember.Application.create({}); App.LatView = Ember.View.extend({ templateName: "test", contentBinding: "App.latController.contentWithIndices", onRerender: function() { this.rerender(); console.log(this.get('content')); }.observes('content') }); App.latController = Ember.Object.create({ changeContent: function() { this.set('model', []); var model = this.get('model'); var obj1 = { item: { "DisplayOrder": 1, "Public": true, "Description": "The test1", "Name": "The name1" } }; var obj2 = { item: { "DisplayOrder": 1, "Public": true, "Description": "The test2", "Name": "The name2" } } var obj3 = { item: { "DisplayOrder": 1, "Public": true, "Description": "The test3", "Name": "The name3" } } var obj4 = { item: { "DisplayOrder": 1, "Public": true, "Description": "The test4", "Name": "The name4" } } var obj5 = { item: { "DisplayOrder": 1, "Public": true, "Description": "The test5", "Name": "The name5" } } model.pushObject(obj1); model.pushObject(obj2); model.pushObject(obj3); model.pushObject(obj4); model.pushObject(obj5); }, model: [ { item: { "DisplayOrder": 1, "Public": true, "Description": "The test1", "Name": "The name1" } } , { item: { "DisplayOrder": 1, "Public": true, "Description": "The test2", "Name": "The name2" } } , { item: { "DisplayOrder": 1, "Public": true, "Description": "The test3", "Name": "The name3" } }, { item: { "DisplayOrder": 1, "Public": true, "Description": "The test4", "Name": "The name4" } }, { item: { "DisplayOrder": 1, "Public": true, "Description": "The test5", "Name": "The name5" } } ], contentWithIndices: function() { var length = this.get('model').length; return this.get('model').map(function(i, idx) { return { teo: i, openTag: (idx % 4 == 0), closeTag: ((idx % 4 == 3) || (idx == length - 1)) }; }); }.property('model.@each') }); var view = App.LatView.create({}); view.append(); When should we use rerender method manually? Is there any way to do that without re-rendering my view? Any idea is welcomed, thanks in advance. A: I have tried to rewrite your example by using another strategy http://jsfiddle.net/davidsevcik/FjB3E/ Instead of counting the indices I used the Array.slice function to create groups of four items. It also makes the code clearer. <script type="text/x-handlebars" data-template-name="test"> <button {{action "changeContent" target="App.latController"}}> Change</button> {{#each elementGroup in view.content}} <ol> {{#each element in elementGroup}} <li>{{element.item.Name}}</li> {{/each}} </ol> {{/each}} </script>​ Javascript: App = Ember.Application.create({}); App.LatView = Ember.View.extend({ templateName: "test", contentBinding: "App.latController.contentSlicedBy4" }); App.latController = Ember.Object.create({ changeContent: function() { this.set('model', []); var model = this.get('model'); var obj1 = { item: { "DisplayOrder": 1, "Public": true, "Description": "The test1", "Name": "The name1" } }; var obj2 = { item: { "DisplayOrder": 1, "Public": true, "Description": "The test2", "Name": "The name2" } } var obj3 = { item: { "DisplayOrder": 1, "Public": true, "Description": "The test3", "Name": "The name3" } } var obj4 = { item: { "DisplayOrder": 1, "Public": true, "Description": "The test4", "Name": "The name4" } } var obj5 = { item: { "DisplayOrder": 1, "Public": true, "Description": "The test5", "Name": "The name5" } } model.pushObject(obj1); model.pushObject(obj2); model.pushObject(obj3); model.pushObject(obj4); model.pushObject(obj5); }, model: [ { item: { "DisplayOrder": 1, "Public": true, "Description": "The test1", "Name": "The name1" }} , { item: { "DisplayOrder": 1, "Public": true, "Description": "The test2", "Name": "The name2" }} , { item: { "DisplayOrder": 1, "Public": true, "Description": "The test3", "Name": "The name3" }}, { item: { "DisplayOrder": 1, "Public": true, "Description": "The test4", "Name": "The name4" }}, { item: { "DisplayOrder": 1, "Public": true, "Description": "The test5", "Name": "The name5" }}, { item: { "DisplayOrder": 1, "Public": true, "Description": "The test6", "Name": "The name6" }}, { item: { "DisplayOrder": 1, "Public": true, "Description": "The test7", "Name": "The name7" }}, { item: { "DisplayOrder": 1, "Public": true, "Description": "The test8", "Name": "The name8" }}, { item: { "DisplayOrder": 1, "Public": true, "Description": "The test9", "Name": "The name9" }}], contentSlicedBy4: function() { var result = [], begin = 0, model = this.get('model'), slice = model.slice(begin, begin + 4); while (!Em.empty(slice)) { result.push(slice); begin += 4; slice = model.slice(begin, begin + 4); } return result; }.property('model.@each', 'model') }); var view = App.LatView.create({}); view.append();​
{ "pile_set_name": "StackExchange" }
Q: Pixmap screenshot convert to low-quality i'm using qt creator to create sample Remote Assistance my project have 2 part server and client the client taking screenshot and send it to server but screenshot pictures have to much quality and it take too much size and is not good idea to send it from local area network or internet protocol i need to resize image size or convert it to low quality so that can be almost Recognizable this is my screenshot codes void MainWindow::shootScreen() { originalPixmap = QPixmap(); // clear image for low memory situations // on embedded devices. originalPixmap = QGuiApplication::primaryScreen()->grabWindow(0); //emit getScreen(originalPixmap); updateScreenshotLabel(); } void MainWindow::updateScreenshotLabel() { this->ui->label_2->setPixmap(originalPixmap.scaled(this->ui->label_2- >size(), Qt::KeepAspectRatio, Qt::SmoothTransformation)); } A: Looks like you know how to change an image size, why isn't that enough? Just do: QPixmap smallPixmap = originalPixmap.scaled( QSize( originalPixmap.size().x()/4, originalPixmap.size().y()/4 ), Qt::KeepAspectRatio, Qt::SmoothTransformation ); And send smallPixmap instead of originalPixmap. You could (should) also compress the image using QImageWriter, this will allow you to create an image compressed with jpeg format, which should also reduce the memory usage. Check this, looks like they do what you are trying to do.
{ "pile_set_name": "StackExchange" }
Q: What's the significance of the blue glow on Peacemaker? Peacemaker normally glows orange, when shooting demons, revenants, witches, whatever. However, we've seen it glow blue twice: once when Wynnona shot Willa, and once when Waverly shot at Rosita. It's not because of who's shooting it, clearly. It's not because of the character of whom it's shooting at (Rosita might not have been so horrible, but Willa was pretty bad, and in any case it still glowed orange when Wynnona shot a few nice revenants previously). And it doesn't seem to be about shooting non-demonic things, either, because (even if witches are demonic), it glowed blue when shooting Rosita, who's definitely a revenant. So what's up with the blue glow? A: According to Tim Rozon (an author of the Wynonna Earp graphic novel by IDW publishing), Peacemaker glows blue when there's a better way to deal with something besides a bullet. https://mobile.twitter.com/realtimrozon/status/902178828361109505/actions
{ "pile_set_name": "StackExchange" }
Q: Issues with Multiple MKMapViews in IOS Application I've been having an issue with having multiple MKMapViews in my iOS application. We are currently using a TabBarController for basic navigation. The issue comes up when a MKMapView's annotation's button segues to another view that has a button that leads to another MKMapView. The first MKMapView works fine with annotations and functionality, but the second MKMapView won't add annotations. I believe the class is linked to the StoryBoard's layout fine since it triggers the viewDidLoad function upon the segue. When I step through the viewDidLoad function it reaches the addAnnotation function call, but the annotations do not get added to the map. I know the post "Multiple map views in same app" covers a similar issue, but the poster didn't seem too friendly and didn't get any answers due to that. Please let me know what you think, if you need more information, or if you've implemented multiple MKMapViews in your iOS project. Thanks! A: Look closely at your setup of delegates & IBOutlets to make sure each view is pointing to the right mapview. Then make sure each function uses the parameters it was given, e.g. - (MKAnnotationView *)mapView:(MKMapView *)aMapView viewForAnnotation:(id < MKAnnotation >)annotation { //Only use "aMapView here not "mapView" }
{ "pile_set_name": "StackExchange" }
Q: "Origin null is not allowed by Access-Control-Allow-Origin." Error when calling a web service with jQuery I have created a web service which returns some data and am trying to access it using jquery but the console displays the following errors: OPTIONS http://localhost:56018/PhoneWebServices.asmx?op=GetMyChildren 405 (Method Not Allowed) jQuery.ajaxTransport.sendjquery-1.7.1.js:8102 jQuery.extend.ajaxjquery-1.7.1.js:7580 LoginButton_onclickindex.html:26 (anonymous function)index.html:59 onclickindex.html:60 XMLHttpRequest cannot load http://localhost:56018/PhoneWebServices.asmx?op=GetMyChildren. Origin null is not allowed by Access-Control-Allow-Origin. I assumed the 405 error was due the 'Origin null is not allowed' error. These are the steps I've taken so far: Created a website (work in progress) and created the web service in the website. I tested the web service by typing the url in my browser and it works. Created a mobile web app which tries to call the webservice but shows the above errors. My Client-side (mobile app code): <script type="text/javascript"> document.addEventListener("deviceready", onDeviceReady, false); function onDeviceReady() { } function LoginButton_onclick() { var email=document.getElementById("EmailBox").value; var pass=document.getElementById("PasswordBox").value; $.ajax({ type: "POST", contentType: "application/json; charset=utf-8", url: "http://localhost:56018/PhoneWebServices.asmx?op=GetMyChildren", data: '{ "email" : "' + email + '", "password": "' + pass + '" }', dataType: "json", success: GetChildrenSuccess, failure: GetChildrenFailed }); } function GetChildrenSuccess(response) { var children = eval('(' + response.d + ')'); var child; for(child in children) { $('#ResultsDiv').innerHTML = "ID: "+child.ID+ " Name: "+child.Name+" Surname: "+child.Surname+" \r\n"; } } function GetChildrenFailed(error) { document.getElementById('ResultsDiv').innerHTML = "Error"; } </script> I was thinking maybe it was because I did not publish the website or webservice with IIS-do I need to do this? Even though the url worked when typed into the browser I am not sure whether it should be the same in the client side code. I am very new to web programming so if you know what's wrong please explain it in simple terms, any help is greatly appreciated. A: The problem is most likely to go away if you run the file through a local web server, and not just open the HTML-file with the browser. When you just open the file, without going through a web server, you don't get an origin domain - thus the error message that the origin is null.
{ "pile_set_name": "StackExchange" }
Q: How to split two values in one textBox How to split the values in one textBox using / as a separator? Value format: 192.168.0.0/24 Two textBoxes are currently used, and this is not convenient: A: Simply use Split method: string str = "192.168.0.0/24"; var result = str.Split('/'); Console.WriteLine(result[0]); // ip Console.WriteLine(result[1]); // mask Demo
{ "pile_set_name": "StackExchange" }
Q: Getting last row for each day in MySQL I have problem in selecting other columns for the max(datetime) records. In layman terms I need to get relevant columns where max(DialDateTime) records for all the dates in Mysql. mysql> select max(DialDateTime) as max from log_AP group by date(DialDateTime) ; +---------------------+ | max | +---------------------+ | 2012-12-03 07:37:26 | | 2012-12-04 07:37:04 | | 2012-12-05 07:37:04 | | 2012-12-06 07:37:04 | | 2012-12-07 07:37:04 | | 2012-12-08 07:37:04 | | 2012-12-09 07:37:04 | +---------------------+ 7 rows in set (0.00 sec) A: You should be able to use a subquery to get the max date and then join that to you table to return the remaining columns: select a1.* from log_AP a1 inner join ( select max(DialDateTime) as max from log_AP group by date(DialDateTime) ) a2 on a1.DialDateTime = a2.max
{ "pile_set_name": "StackExchange" }
Q: JavaScript: onmouseout event not working after onmouseover I'm trying to write code for a ToolTip, where when the mouse goes over it the text shows, and when it moves away it goes away. I'm trying to do it by changing classes (tipHide in css has display:none, and tipShow has display: block), but the onmouseout event doesn't change the class back (which I know from seeing the generated source after). How can I fix it so the onmouseout event will trigger if the onmouseover event already has changed the class. My HTML: <div id="zha" class="cfield"> <p id="qmark"></p> <p id="toolTip" class="tipHide">Text Shown</p> </div> and JavaScript: function toolTip() { document.getElementById('qmark').onmouseover = function() { var toolTip = document.getElementById('toolTip'); toolTip.className = 'tipShow'; } document.getElementById('qmark').onmouseout = function() { var toolTip = document.getElementById('toolTip'); toolTip.classname = 'tipHide'; } } Also I'd like to do it without using JQuery A: Maybe a typo on the className property? In your onmouseout you got this: toolTip.classname = 'tipHide'; Which should be(the same you did on onmouseover): toolTip.className = 'tipHide'; ^
{ "pile_set_name": "StackExchange" }
Q: Year and day of year to date using Date::Calc How do you get the date from year and day of year using Date::Calc? I managed to figure it out using DateTime but I need to use Date::Calc. The following works, but I don't know how to get it working using Date::Calc. use DateTime; my $dt = DateTime->from_day_of_year( year => 2018, day_of_year => 70, ); # Prints the correct date of March something. print($dt->strftime('%Y-%m-%d') . "\n"); What I have so far is use Date::Calc 'Add_Delta_Days'; my $dt = Add_Delta_Days(2018, 70); A: The documented usage is ($year,$month,$day) = Add_Delta_Days($year,$month,$day, $Dd); So my ($y,$m,$d) = Add_Delta_Days(2018,1,1,70-1); Note that the 70th day is 69 days after the 1st, thus the use of 70-1.
{ "pile_set_name": "StackExchange" }
Q: initWithCoder has been explicitly marked unavailable error using newest version of Xamarin.iOS I'm seeing the following error during compile time when working with the latest version of Xamarin.iOS that was released yesterday: UIActivityViewController.h:23:1: note: 'initWithCoder:' has been explicitly marked unavailable here - (nullable instancetype)initWithCoder:(NSCoder *)aDecoder NS_UNAVAILABLE; I don't recall ever having this issue before and my code hasn't changed much between the last update and now. Can anyone help me figure out what's going on? A: It's a known issue which is harder to diagnose because of a clang bug, i.e. it has nothing to do with UIActivityViewController. You might be able to workaround this by removing [Export ("initWithCoder:")] inside your code. That should be fine unless your managed object needs to be created from native code. YMMV
{ "pile_set_name": "StackExchange" }
Q: Given numbers $a,b,c\geqq0$ and $-\frac{2}{11}\leqq k\leqq0$. Prove that $(k+1)^{6}(a+b+c)^{2}(\!ab+bc+ca\!)^{2}-81\prod\limits_{sym}(ka+b)\geqq0$ . Problem. Given three numbers $a, b, c\geqq 0$ and $k= constant$ so that $- \dfrac{2}{11}\leqq k\leqq 0$. Prove that : $$(\!k+ 1\!)^{6}(\!a+ b+ c\!)^{2}(\!ab+ bc+ ca\!)^{2}\!- 81(ka+ b)(kb+ a)(kb+ c)(kc+ b)(kc+ a)(ka+ c)\!\geqq 0$$ Remark. By using discriminant, I determined the value of $k$ so that the inequality holds for $a, b, c\geqq 0$, thus I gave $a= b= 1$ and $c\rightarrow 0^{+}$, and I also have the coefficient of $a^{4}$ must be positive. I make it involving a pretty good inequality as the following one for $a, b, c\geqq 0$ and $k= constant$ : $$3\sum \sqrt{(a+ kb)(a+ kc)}\leqq (k+ 1)\left ( (a+ b+ c)+ 2\sqrt{3(ab+ bc+ ca)} \right )\,\therefore\,k= 2\,only\,true\,!$$ This one that Ji Chen's Symmetric Function Theorem applies. Return the OP, we may use $uvw$ here ! A: $$\prod_{cyc}(ka+b)(kb+a)=\prod_{cyc}(k(a^2+b^2)+(k+1)ab)=$$ $$=\sum_{cyc}(k^3(a^4b^2+a^4c^2)+(k^3+k^2)a^3b^3+(k^3+k^2)a^4bc)+$$ $$+abc\sum_{cyc}\left((2k^3+3k^2+k)(a^2b+a^2c)+\left(k^3+k^2+k+\frac{1}{3}\right)abc\right).$$ Now, let $a+b+c=3u$, $ab+ac+bc=3v^2$ and $abc=w^3$. Thus, the coefficient before $w^6$ s equal to $$-3k^3+3(k^3+k^2)+3(k^3+k^2)-3(2k^3+3k^2+k)+3\left(k^3+k^2+k+\frac{1}{3}\right)=1,$$ which says that our inequality is equivalent to $f(w^3)\geq0,$ where $f$ is a concave function. But the concave function gets a minimal value for the extreme value of $w^3$, which happens in the following cases: $w^3=0$. For $b=c=0$ our inequality is an equality for all $k$. Let $b=1$ and $c=0$. We obtain: $$(k+1)^6(a+1)^2a^2\geq81k^2(ka+1)(a+k)a^2$$ or $$((k+1)^6-81k^3)a^2+(2(k+1)^6-81k^2(k+1))a+(k+1)^6-81k^3\geq0$$ and since $(k+1)^6-81k^3>0$, for $1(k+1)^6-81k^2(k+1)\geq0$ the equality is true. But for $2(k+1)^6-81k^2(k+1)<0$ we need $$(2(k+1)^6-81k^2(k+1))^2-4((k+1)^6-81k^3)^2\leq0$$ or $$(1-k)k^2(4k^6+24k^5+60k^4-163k^3-21k^2-24k+4)\geq0,$$ which is wrong for $k=-\frac{2}{11}$ and from here you can make a counterexample. The case $b=c=1$ is not relevant already.
{ "pile_set_name": "StackExchange" }
Q: Is it correct to say that H2SO4 is an acid in this reaction? Is it correct to say that $\ce{H2SO_4}$ acts as an acid in the following reaction? $\ce{2Ag + H2SO_4} \rightarrow \ce{Ag_2SO_4 + 2H_2O + SO_2}$ I know it acts as an oxidizing agent, but is it correct to say it shows acidic properties? A: Do you get the same reaction with sodium sulfate? I do not think so, at least under "normal" conditions. When the sulfuric acid acts as an oxidizing agent giving off $\ce{SO_2}$, the excess oxygen comes off as oxide ions which must be somehow put into more stable form. The protons from the sulphuric acid do that by turning them to water. Getting the reaction to go requires the sulfuric acid to act as both an acid and an oxidizing agent.
{ "pile_set_name": "StackExchange" }
Q: Loop gives correct output if script run in steps but not when skript runs from scratch My script contains a while loop: import numpy as np ptf = 200 #profiltiefe dz = 5 DsD0 = 0.02 D0 = 0.16 #cm2/sec bei 20°C Ds= D0 * DsD0 eps= 0.3 R= 8.314 Ptot=101300 Te = 20 dt = 120 modellzeit = 86400*3 J=modellzeit/dt PiA = 0.04 CA = PiA*1000/Ptot respannual = 10 #t C ha-1 a-1 respmol = respannual/12*10**6/10000/(365*24) respvol_SI = respmol * R * (Te+273)/(Ptot*3600) respvol = respvol_SI * 100 I= ptf/dz S = np.zeros(40) for i in range(40): if i <= 4: S[i] = respvol/(2*4*dz) if i > 4 and i <= 8: S[i] = respvol/(4*4*dz) if i > 8 and i <= 16: S[i] = respvol/(8*4*dz) Calt = np.repeat(CA,len(range(int(I+1)))) Cakt = Calt.copy() res_out = range(1,int(J),1) Cresult = np.array(Cakt) faktor = dt*Ds/(dz*dz*eps) timestep=0 #%% while timestep <= J: timestep = timestep+1 for ii in range(int(I)): if ii == 0: s1 = Calt[ii+1] s2 = -3 * Calt[ii] s3 = 2 * CA elif ii == int(I-1): s1 = 0 s2 = -1 * Calt[ii] s3 = Calt[ii-1] else: s1 = Calt[ii+1] s2 = -2 * Calt[ii] s3 = Calt[ii-1] result = Calt[ii]+S[ii]*dt/eps+faktor*(s1+s2+s3) print(result) Cakt[ii] = result Cresult = np.vstack([Cresult,Cakt]) Calt = Cakt.copy() What is intersting: If I run the complete script print(result) gives me different (and incorrect) values. But if I add all my constants before and run the loop part of the code (shown above) the loop performs well and delivers the output I want. Any idea why this might happen? I am on Python 2.7.5 / Mac OS X 10.9.1/ Spyder 2. A: You are using python 2.7.5, so division of integers gives integer results. I suspect that is not what you want. For example, the term respannual/12 will be 0, so respmol is 0. Either change your constants to floating point values (e.g. respannual = 10.0), or add from __future__ import division at the top of your script.
{ "pile_set_name": "StackExchange" }
Q: wicket how to update the header of modal I'm making a page using wicket. The main page consists of a table displaying invoice information. In the last column of the table has a link for each one of the invoices displaying the full information for that invoice, by opening a modal. I'm using de.agilecoders.wicket.core.markup.html.bootstrap.dialog.Modal My goal is when I open the modal, the header of the modal shows the invoice number of that invoice that was opened. I'm able to get it only after refreshing the page, and if I open the modal of another invoice the header is not updated, it shows the number of the previous invoice. I have to refresh again the page. I don't know how to open a modal that shows in the header the number of the respective invoice without refreshing the page. below the markup of the main page. <wicket:extend> <div class="page-header"> <h2> <wicket:message key="invoices-welcome">[Welcome message]</wicket:message> </h2> </div> <div> <span wicket:id="navigator">[dataview navigator]</span> </div> <div> <table cellspacing="0" class="table table-condensed"> <tr> <th>Status</th> <th>Invoice number</th> <th>Supplier</th> <th>Customer</th> <th>Amount</th> <th>Actions</th> </tr> <tr wicket:id="rows"> <td><span wicket:id="status">[status]</span></td> <td><span wicket:id="invoiceN">[invoiceN]</span></td> <td><span wicket:id="supplier">[supplier]</span></td> <td><span wicket:id="customer">[customer]</span></td> <td><span wicket:id="amount">[amount]</span></td> <td><a wicket:id="showModal">View</a></td> </tr> </table> </div> <div wicket:id="modal"></div> </wicket:extend> Java code of the main page package nl.riskco.liberobc.web.pages.invoices; import java.util.List; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.AjaxLink; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.navigation.paging.PagingNavigator; import org.apache.wicket.markup.repeater.Item; import org.apache.wicket.markup.repeater.data.DataView; import org.apache.wicket.markup.repeater.data.ListDataProvider; import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; import org.apache.wicket.request.mapper.parameter.PageParameters; import nl.riskco.liberobc.client.business.model.InvoiceDomain; import nl.riskco.liberobc.client.business.services.IInvoiceService; import nl.riskco.liberobc.client.business.services.InvoiceServiceMocked; import nl.riskco.liberobc.web.pages.BasePage; //@AuthorizeInstantiation("VIEWER") public class InvoicesPage extends BasePage { private static final long serialVersionUID = 1L; private InvoiceModalAgile modal2; public InvoicesPage(PageParameters parameters) { super(parameters); IInvoiceService service = new InvoiceServiceMocked(); List<InvoiceDomain> invoicesToTest2; invoicesToTest2 =service.getInvoices(1, 30); modal2 = new InvoiceModalAgile("modal", Model.of(new InvoiceDomain())); modal2.addCloseButton(); modal2.setOutputMarkupId(true); add(modal2); DataView<InvoiceDomain> dataview = new DataView<InvoiceDomain>("rows", new ListDataProvider<InvoiceDomain>(invoicesToTest2)) { private static final long serialVersionUID = 1L; @Override protected void populateItem(Item<InvoiceDomain> item) { // TODO Auto-generated method stub InvoiceDomain invoice = item.getModelObject(); item.add(new Label("status", invoice.getStatus())); item.add(new Label("invoiceN", String.valueOf(invoice.getInvoiceGUID()))); item.add(new Label("supplier", invoice.getSupplier())); item.add(new Label("customer", invoice.getCustomer())); item.add(new Label("amount", String.valueOf(invoice.getAmount()))); item.add(new AjaxLink("showModal") { private static final long serialVersionUID = 1L; @Override public void onClick(AjaxRequestTarget target) { modal2.setInvoiceModel(Model.of(invoice), target); modal2.show(target); } }); } }; dataview.setItemsPerPage(10L); add(dataview); add(new PagingNavigator("navigator", dataview)); } @Override protected void onDetach() { // TODO Auto-generated method stub super.onDetach(); } } Markup of the modal <wicket:extend> <div class="panel panel-default"> <div class="panel-heading">Invoice details</div> <div class="panel-body"> <table class="table table-bordered"> <tr> <th><wicket:message key="invoice-id">[invoice-id]</wicket:message></th> <td><div wicket:id="invoiceN"></div></td> </tr> <tr> <th><wicket:message key="invoice-status">[invoice-status]</wicket:message></th> <td><div wicket:id="status"></div></td> </tr> <tr> <th><wicket:message key="invoice-customer">[invoice-customer]</wicket:message></th> <td><div wicket:id="customer"></div></td> </tr> <tr> <th><wicket:message key="invoice-supplier">[invoice-supplier]</wicket:message></th> <td><div wicket:id="supplier"></div></td> </tr> <tr> <th><wicket:message key="invoice-ibanSupplier">[invoice-ibanSupplier]</wicket:message></th> <td><div wicket:id="iban"></div></td> </tr> <tr> <th><wicket:message key="invoice-amount">[invoice-amount]</wicket:message></th> <td><div wicket:id="amount"></div></td> </tr> <tr> <th>Approved</th> <td><form wicket:id="form"><input type="checkbox" wicket:id="checkbox1"></form></td> </tr> <tr> <th>Early payment</th> <td><form wicket:id="form2"><input type="checkbox" wicket:id="checkbox2"></form></td> </tr> <tr> <th>Paid (by customer)</th> <td><form wicket:id="form3"><input type="checkbox" wicket:id="checkbox3"></form></td> </tr> </table> </div> </div> </wicket:extend> Java code of the modal package nl.riskco.liberobc.web.pages.invoices; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.form.CheckBox; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; import org.apache.wicket.model.StringResourceModel; import de.agilecoders.wicket.core.markup.html.bootstrap.behavior.BootstrapResourcesBehavior; import de.agilecoders.wicket.core.markup.html.bootstrap.dialog.Modal; import nl.riskco.liberobc.client.business.model.InvoiceDomain; public class InvoiceModalAgile extends Modal<InvoiceDomain>{ private static final long serialVersionUID = 1L; private Label labelGuid; private Label status; private Label customer; private Label iban; private Label amountLabel; private Label supplierLabel; private CheckBox approved; private CheckBox earlyPayment; private CheckBox customerPaid; private Form form; private Form form2; private Form form3; private WebMarkupContainer header; private WebMarkupContainer footer; public InvoiceModalAgile(String id , IModel<InvoiceDomain> model) { super(id, model); add(form = new Form<>("form")); add(form2 = new Form<>("form2")); add(form3 = new Form<>("form3")); status = (new Label("status",model.getObject().getStatus())); status.setOutputMarkupId(true); add(status); supplierLabel = (new Label("supplier",model.getObject().getSupplier())); supplierLabel.setOutputMarkupId(true); add(supplierLabel); labelGuid = new Label("invoiceN",model.getObject().getInvoiceGUID()); labelGuid.setOutputMarkupId(true); add(labelGuid); customer = (new Label("customer",model.getObject().getCustomer())); customer.setOutputMarkupId(true); add(customer); iban = new Label("iban",model.getObject().getIBANsupplier()); iban.setOutputMarkupId(true); add(iban); amountLabel = new Label("amount",model.getObject().getAmount()); amountLabel.setOutputMarkupId(true); add(amountLabel); approved = new CheckBox("checkbox1"); approved.setOutputMarkupId(true); approved.setEnabled(false); add(approved); form.setOutputMarkupId(true); add(form); form.add(approved); earlyPayment = new CheckBox("checkbox2"); earlyPayment.setOutputMarkupId(true); earlyPayment.setEnabled(false); add(earlyPayment); form2.setOutputMarkupId(true); add(form2); form2.add(earlyPayment); customerPaid = new CheckBox("checkbox3"); customerPaid.setOutputMarkupId(true); customerPaid.setEnabled(false); add(customerPaid); form3.setOutputMarkupId(true); add(form3); form3.add(customerPaid); BootstrapResourcesBehavior.addTo(this); } public void setInvoiceModel(IModel<InvoiceDomain> invoice, AjaxRequestTarget target){ this.labelGuid.setDefaultModel(Model.of(invoice.getObject().getInvoiceGUID())); target.add(labelGuid); this.amountLabel.setDefaultModel(Model.of(invoice.getObject().getAmount())); target.add(amountLabel); this.status.setDefaultModel(Model.of(invoice.getObject().getStatus())); target.add(status); this.customer.setDefaultModel(Model.of(invoice.getObject().getCustomer())); target.add(customer); this.supplierLabel.setDefaultModel(Model.of(invoice.getObject().getSupplier())); target.add(supplierLabel); this.iban.setDefaultModel(Model.of(invoice.getObject().getIBANsupplier())); target.add(iban); this.approved.setDefaultModel(Model.of(invoice.getObject().getApprovedFlag())); target.add(approved); this.earlyPayment.setDefaultModel(Model.of(invoice.getObject().getOptForEarlyPaymentFlag())); target.add(earlyPayment); this.customerPaid.setDefaultModel(Model.of(invoice.getObject().getHasCustomerPaidFlag())); target.add(customerPaid); this.header(Model.of(String.valueOf(invoice.getObject().getInvoiceGUID()))); } @Override protected void onDetach() { // TODO Auto-generated method stub super.onDetach(); } } A: The problem is that you use the model object of the empty model that you pass at Modal construction. You need to use dynamic models for the properties. Static/simple model: label = new Label("staticValue", personModel.getObject().getName()); Here the label will use the name of the current person for each rendering. Dynamic model: label = new Label("staticValue", new AbstractReadOnlyModel<String>() { @Override public String getObject() { return personModel.getObject().getName()); } } You see that the dynamic version reads personModel's name lazily and it is called at each rendering of the Label. This way it will read the name of the person even if you put a new Person into the Label's Model. In your case you need something like: status = new Label("status", new PropertyModel(this, "model.object.status")); For more information read: https://cwiki.apache.org/confluence/display/WICKET/Working+with+Wicket+models
{ "pile_set_name": "StackExchange" }
Q: How to Configure the Google Maps for Rails Map config file? I'm using the GM4Rails Gem. I'm very newbie to Rails and I'm trying to find the config file so I can get a HYBRID Google Maps instead of the ROADMAP. I couldn't find the file: https://github.com/apneadiving/Google-Maps-for-Rails/wiki/Map Is there anyway I can change the config? A: You have to know that: <%= gmaps4rails(@json) %> is a shortcut for: <%= gmaps("map_options" => { "auto_adjust" => true}, "markers" => { "data" => @json }) %> When you need to pass additional options, you have to use the gmaps helper. In your case: <%= gmaps("map_options" => { "auto_adjust" => true, "type" => "HYBRID" }, "markers" => { "data" => @json }) %> As you saw many more options are available.
{ "pile_set_name": "StackExchange" }
Q: ¿Como saltar de registros mysql usando bucle en php, y de cada registro iterado hacer un calculo entre valores de campos? Lo que hace este código es recibir en una variable el número de clases impartidas, en un array el número de inasistencias de cada alumno, en otro ´array´ el idGrupo, que siempre es el mismo, y en otro array recibe el idAlumno, estos datos son mandados desde una tabla como formulario. Lo que intentaba hacer es que en base a núm. de sesiones y asistencias mediante una regla de 3 calcular el porcentaje de asistencia obtenido de cada alumno. Esta parte parece funcionar bien, pero aparte tiene que calcular el promedio de 3 calificaciones de cada alumno, estas calificaciones son recuperadas de la base de datos, se debe evaluar si el porcentaje de asistencia de cada alumno es mayor o igual a 80, guardar en el registro correspondiente el promedio obtenido anteriormente, de ser menor a 80 debe tener una calificación reprobatoria = 5. Lo que logró hacer bien es el salto de registro en registro, para hacer esos cálculos en cada uno de ellos. Lo estaba intentado hacer inicializando una variable con el primer idAlumno encontrado y de ahí compararlo en el bucle si es el mismo del recuperado por otra variable. Es más un error de lógica. //CALCULO DE PROMEDIOS DE ALUMNO Y % DE ASISTENCIAS elseif( (isset($_POST['numsesiones']) ) && (!empty($_POST['asistotales'])) ) { $grupo4 = $_POST['idgpo']; //arreglo idgrupo[] siempre es el mismo $gpo4 = $grupo4[0]; //el idGrupo es el mismo en todo el arreglo $alumno4 = $_POST['idalumno']; //arreglo idalumno[] $consulta1 = "SELECT A.matricula, A.nombre, AG.parcial1, AG.parcial2, AG.parcial3, AG.final, AG.idAlumno, AG.idGrupo FROM alumno A, alumno_grupo AG, materias M, periodos Pr, profesores P, grupos G WHERE M.idMateria = G.materia and A.idAlumno = AG.idAlumno and G.idGrupo = AG.idGrupo and G.profesor = P.idProfesor and G.periodo = Pr.idPeriodo and AG.idGrupo = $gpo4 ORDER BY A.nombre"; $res = mysqli_query($conexion,$consulta1); $res2 = mysqli_query($conexion,$consulta1); $fila = $res->fetch_assoc(); //array asociativo para obtener el primer registro de alumno $fila2 = $res2->fetch_assoc(); //array asociativo para obtener los demas registros $nalumno = count($alumno4); //cuenta los elementos del arreglo de los id alumno[] $asistenciasalumno = $_POST['asistotales']; //valores de arreglo recibido $numsesiones = $_POST['numsesiones']; //1 valor recibido de un input $bandera = $fila['idAlumno']; //asignamos a variable el primer registro de alumno encontrado for ($a = 0; $a < $nalumno; $a++) { //for recorre elementos del array[] idAlumno $alum = $alumno4[$a]; //variable toma valor del arreglo en el id $gpos = $grupo4[$a]; //variable toma el valor del arreglo de idgrupo, (siempre es el mismo) //asignanle a variable el indice del arreglo $asis = $asistenciasalumno[$a]; $regla = $asis * 100; $asis = $regla/$numsesiones; //regla de 3 para sacr porcentaje de asistencia, $asis = round($asis); echo $asis; //prueba echo "<br>"; //prueba $sqlp = mysqli_query($conexion, "UPDATE alumno_grupo SET asistencias = '{$asis}' WHERE idAlumno = '{$alum}' AND idGrupo = '{$gpos}'") or die (mysqli_error($conexion)); while ($fila2 = $res2->fetch_assoc()) { if($bandera == $fila2['idAlumno']) { //si la bandera es igual al primer idAlumno //obteniendo las calificaciones de los 3 parciales por alumno $p1b = $fila2['parcial1']; $p2b = $fila2['parcial2']; $p3b = $fila2['parcial3']; $suma = $p1b+$p2b+$p3b; $promedio = $suma/3; } else { $p1b = $fila2['parcial1']; $p2b = $fila2['parcial2']; $p3b = $fila2['parcial3']; $suma = $p1b+$p2b+$p3b; $promedio = $suma/3; } $bandera = $fila['idAlumno']; } if ($asis >= 80) { //DE SER MENOR EL % DE ASSITENCIAS OBTENIDO DEL 80 $sqlb = mysqli_query($conexion, "UPDATE alumno_grupo SET final = '{$promedio}' WHERE idAlumno = '{$alum}' AND idGrupo = '{$gpos}'") or die (mysqli_error($conexion)); } elseif ($asis < 80) { $sqlb = mysqli_query($conexion, "UPDATE alumno_grupo SET final = 5 WHERE idAlumno = '{$alum}' AND idGrupo = '{$gpos}'") or die (mysqli_error($conexion)); } } //for recorre } //if empty numsesiones && isset asistotales/ A: simplifique un poco tu codigo para facilitar la compresion. Uno de los problemas que tenias era que estabas recorriendo un array de claves incremetales usando un FOR de forma incorrecta creo que fue a raiz de esto que complicaste por demas la logica guardando un flag con el id del alumno que estabas recorriendo. Te dejo el codigo arreglado y mas abajo te explico. <?php if(isset($_POST['numsesiones']) && !empty($_POST['asistotales'])) { $id_grupo = $_POST['idgpo'][0]; // Valor fijo, es siempre igual $alumnos = $_POST['idalumno']; // Array de idalumno[] $asistencias = $_POST['asistotales']; //valores de arreglo recibido $numsesiones = $_POST['numsesiones']; //1 valor recibido de un input $sql = "SELECT A.matricula, A.nombre, AG.parcial1, AG.parcial2, AG.parcial3, AG.final, AG.idAlumno, AG.idGrupo FROM alumno A, alumno_grupo AG, materias M, periodos Pr, profesores P, grupos G WHERE M.idMateria = G.materia and A.idAlumno = AG.idAlumno and G.idGrupo = AG.idGrupo and G.profesor = P.idProfesor and G.periodo = Pr.idPeriodo and AG.idGrupo = $gpo4 ORDER BY A.nombre"; $query = mysqli_query($conexion,$sql); for ($a = 0; $a < count($alumnos); $a++) { //for recorre elementos del array[] idAlumno $id_alumno = $alumnos[$a]; //asignanle a variable el indice del arreglo $alumno_asistencias = $asistencias[$a]; //Promedio de asistencias $alumno_asistencias_promedio = round(($alumno_asistencias * 100) / $numsesiones); echo $alumno_asistencias_promedio; //prueba echo "<br>"; //prueba //Update mysqli_query($conexion, "UPDATE alumno_grupo SET asistencias = '{$alumno_asistencias_promedio}' WHERE idAlumno = '{$id_alumno}' AND idGrupo = '{$id_grupo}'") or die (mysqli_error($conexion)); while ($row = $query->fetch_assoc()) { $promedio = ($row['parcial1'] + $row['parcial2'] + $row['parcial3'])/3; if ($alumno_asistencias_promedio >= 80){ $sqlb = mysqli_query($conexion, "UPDATE alumno_grupo SET final = '{$alumno_asistencias_promedio}' WHERE idAlumno = '{$id_alumno}' AND idGrupo = '{$id_grupo}'") or die (mysqli_error($conexion)); }else{ $sqlb = mysqli_query($conexion, "UPDATE alumno_grupo SET final = 5 WHERE idAlumno = '{$id_alumno}' AND idGrupo = '{$id_grupo}'") or die (mysqli_error($conexion)); } } } } ?> La verdad solo correji el codigo usando sentido comun pero no termino de entender los valores que estas recibiendo, en caso de que no te funcione podrias añadir a tu pregunta un print_r / var_dump de todo lo que estas recibiendo por POST?.
{ "pile_set_name": "StackExchange" }
Q: Validate Windows username/pwd as having Admin privs I'm writing a Windows Forms app that runs from a non-privileged user account. For one action, I need to prompt for a username/pwd for an account with Admin privs. So, the app doesn't actually have to run from a privileged account; but the user has to specify an admin account in order to be allowed to do certain actions. Does anyone know how to validate a username/pwd as an account which has admin privs? A: As Harry Johnston commented, you can use the following to authenticate a username/password: Private Declare Auto Function CloseHandle Lib "kernel32.dll" (ByVal clsTokenToClose As IntPtr) As Integer Private Declare Auto Function LogonUser Lib "advapi32.dll" ( _ ByVal lpszUsername As String, _ ByVal lpszDomain As String, _ ByVal lpszPassword As String, _ ByVal dwLogonType As Integer, _ ByVal dwLogonProvider As Integer, _ ByRef phToken As IntPtr) As Boolean Const DOMAIN_NAME As String = "MYDOMAIN" Dim token As IntPtr 'Use the Win32API LogonUser to authenticate UserName and Password. 'If successful, a token representing the user is returned. If LogonUser("UserName", DOMAIN_NAME, "password", LOGON32_LOGON_BATCH, LOGON32_PROVIDER_DEFAULT, token) Then 'The token is used to create a WindowsIdentity, which is in turn 'used to create a WindowsPrincipal. The WindowsPrincipal is checked 'to see if it belongs to the desired group in ActiveDirectory. Dim WIdent As New WindowsIdentity(token) Dim WPrincipal As New WindowsPrincipal(WIdent) If WPrincipal.IsInRole("Administrators") Then 'User has admin privilege, carry on. End If CloseHandle(token) End If Be sure to replace "Administrators" in the WPrincipal.IsInRole call with the group you want to check against.
{ "pile_set_name": "StackExchange" }
Q: Environment variabels unaccessible from rails I am building a rails application where I have some initial configuration files that use environment variables, and I'm using the cloud9 ide. I am setting the environment variables using export, yet when the server is running rails tells me the parameter whose value is supposed to be one of the environment variables is missing, and when I used the debugger, ENV["VAR_NAME"] returns nothing. Any ideas why? When I run echo $VAR_NAME in bash, it returns the correct value. EDIT: When I run console --sandbox, the environment variables are also available. Only in the controller are they not available. A: I fixed this by adding export VAR_NAME=var_value in .bashrc.
{ "pile_set_name": "StackExchange" }
Q: Need help on CSS Styling for Email Template I have designed a Email Template that we are going to use for one of our client. When i see it from the System Preview i am able to see the color but once email is received the format is set but color is not visible it is displaying as Black & White photo without any colors in the body. Below is my CSS Code: <p style="text-align: left;"><span style="font-family: cambria;"> <span style="font-size: 18pt;"> <span style="color: #00629f;">IBM Service Desk</span> </span> </span> <span style="font-family: cambria;">&nbsp;<img style="align: right;" title="" src="sys_attachment.do?sys_id=0d50b5462f49c010209857892799b644" alt="" width="60" height="60" align="right" border="" hspace="" vspace="" /></span></p> <style><!-- table { font-family: cambria; } td.bg1{ background-color:#E2E2E3; color:#00629F; } td.bg2{ color:black; } --></style> <table style="width: 100%;"> <tbody> <tr> <td style="height: 40px;" colspan="5"> <p>Click here to view Incident: ${URI_REF}</p> </td> </tr> <tr> <td class="bg1" colspan="5">Short Description</td> </tr> <tr> <td class="bg2" colspan="5">${short_description}</td> </tr> <tr> <td class="bg1" colspan="5">Description</td> </tr> <tr> <td class="bg2" colspan="5">${description}</td> </tr> </tbody> </table> <hr /> <p><span style="font-family: cambria;"><span style="font-size: 12pt;">Thank you</span>,</span></p> <p><span style="font-family: cambria;"><span style="font-size: 14pt;"><span style="color: #00629f;">IBM Service Desk</span>&nbsp;</span></span></p> Output when i previewed in the System: System Preview Email Once it is received to outlook then the email i am getting as shown Outlook Email A: There is no any big mistake in your code, Please arrange your code properly. Table data color not shown because the style property not consuming. In your code you put the style tag as alone, Please move your style tag into head tag. The code will be work fine. <head> <style> table { font-family: cambria; } td.bg1{ background-color:#E2E2E3; color:#00629F; } td.bg2{ color:black; } </style> </head <body> <p style="text-align: left;"><span style="font-family: cambria;"> <span style="font-size: 18pt;"> <span style="color: #00629f;">IBM Service Desk</span> </span> </span> <span style="font-family: cambria;">&nbsp;<img style="align: right;" title="" src="sys_attachment.do?sys_id=0d50b5462f49c010209857892799b644" alt="" width="60" height="60" align="right" border="" hspace="" vspace="" /></span></p> <style> </style> <table style="width: 100%;"> <tbody> <tr> <td style="height: 40px;" colspan="5"> <p>Click here to view Incident: ${URI_REF}</p> </td> </tr> <tr> <td class="bg1" colspan="5">Short Description</td> </tr> <tr> <td class="bg2" colspan="5">${short_description}</td> </tr> <tr> <td class="bg1" colspan="5">Description</td> </tr> <tr> <td class="bg2" colspan="5">${description}</td> </tr> </tbody> </table> <hr /> <p><span style="font-family: cambria;"><span style="font-size: 12pt;">Thank you</span>,</span></p> <p><span style="font-family: cambria;"><span style="font-size: 14pt;"><span style="color: #00629f;">IBM Service Desk</span>&nbsp;</span></span></p> </body>
{ "pile_set_name": "StackExchange" }
Q: Speculative Close This question of mine was recently closed due to being off topic because it is speculative. The hold explanation includes a reference to this meta question from a couple of years ago, and I find some of the criteria a little vague. Taken too far, this reason could (IMO) be used to close almost any riddle as well as many other types of questions that rely on the interpretation of the puzzle. Can we specify more stringent criteria for this close reason, and (on a more personal request) can an outside viewpoint tell my biased self where this puzzled strayed into this territory? A: I think the comment by @MasonWheeler on the selected answer kinda explains it best. The girl is the guy's wife. If she said "Hey Honey, I'm going to be at work all day" or "I'm going to xyz's house for the night" the husband would know where to go. The assumption that this question hinges on is that the husband has no idea where his wife is. You can't answer the riddle if that changes, and this wasn't addressed. It would, honestly, be less likely that the husband didn't know (you probably know where at least most if not all of your household are right now, yes?) In regards to the closing reason, it addresses that; The question is posed such that there are assumptions necessary to answer it. You want to ask the questions in such a way that when the answer is revealed, everyone goes 'Oh yeah that's the one true answer.' The answer in this case still depends on information that isn't included in the question that isn't guaranteed to be true in general. Even if that was resolved, to me (i.e. this part is more an opinion of mine, and less important than the above) this is more of a 'Gotcha!' sort of trick than a puzzle requiring alternative interpretations or problem-solving. It verges on a punchline of a joke more than the answer to a problem to be solved. The second part is up for debate, I'll agree, but I think the first part really makes a concrete case.
{ "pile_set_name": "StackExchange" }
Q: With GIT show commits older than a specific date with specific format I need to print the latest 10 commits that are older than a specific date with specific format. I need to handle the date, obtained through the bash command: date +"%Y%m%d%H%M" I tried some options, but so far nothing e.g.: git log -5 --no-merges --format=format:%cd --after=201506301524 A: You need to use --until instead of --after and furthermore, the correct date format, but you can use date to convert it: git log --no-merges --format=format:%cd -10 --until "$(date -d "$(echo "201506301524" | sed 's/....$/ &/')")" $(echo "201506301524" | sed 's/....$/ &/') converts the date to 20150630 1524 which is a valid input format for date.
{ "pile_set_name": "StackExchange" }
Q: how to sort mapreduce results? I have written a method in C# which retrieves tweets from mongoDB and would like to count and sort authors by the number of retweets. Right now, the method already performs map and reduce and returns unsorted results the following way: public void RetweetsCount() { string wordMap = @"function wordMap() { var usernameOrigin = this.text.match(/\brt\s*@(\w+)/i); if (usernameOrigin === null) { return; } // loop every word in the document emit(usernameOrigin[1], { count : 1 }); }"; string wordReduce = @"function wordReduce(key, values) { var total = 0; for (var i = 0; i < values.length; i++) { total += values[i].count; } return { count : total }; }"; var options = new MapReduceOptionsBuilder(); options.SetOutput(MapReduceOutput.Inline); var results = collection.MapReduce(wordMap, wordReduce, options); foreach (var result in results.GetResults()) { Console.WriteLine(result.ToJson()); } } Does anyone know how sort results by descending count value (number of retweets)? A: Here's the solution. After retrieving results from MapReduce, I first converted the IEnumerable to list and then ordered the list the folliwing way: var results = collection.MapReduce(wordMap, wordReduce, options); IEnumerable<BsonDocument> resultList = results.GetResults(); List<BsonDocument> orderedList = resultList.ToList().OrderByDescending(x => x[1]).ToList();
{ "pile_set_name": "StackExchange" }
Q: number of events overlapping with date I have start and end dates of events and i want to find out events overlapping with the event date. The input contains only two elements representing the start and end date of an event. intervals=[[29,31],[23,26],[24,25]] The next line of input will have the event date. date=24 I am expecting an output should have the number of events overlapping with the event date but not able to get it. Kindly help here. Sample output=2 A: The goal is to check if date is "inside" interval (element from intervals list), and then count "positive checks": intervals = [[29,31],[23,26],[24,25]] date = 24 # Mark interval as "1" if date is inside it, than sum "ones" counter = sum([1 for interval in intervals if date in range(interval[0], interval[1] + 1)]) # +1 because range function doesn’t include upper limit in the result print(counter) # prints 2 Another way to perform "checks" is to use interval comparison: counter = sum([1 for interval in intervals if interval[0] <= date <= interval[1]])
{ "pile_set_name": "StackExchange" }
Q: Vue js + HighChart - how can I make a synchronous axios call before the component get rendered? Dear all I am new to vue js. I made a little vue js + NUXT application which renders with the HighCharts a chart. The data get retrieved via webservice call axios. The problem: the webservice call get made asynchronous and my chart get already initialized. How can I make the call synchronous before my chart get rendered? While the Highchart itself requires time to initialize I had to use to set a time out function. In case you would omit this I have the issue that the data get set while the chart is initializing this lead to issues that the chart get wrongly displayed. <template> <div> <highcharts :options="chartOptions"></highcharts> </div> </template> <script> import axios from 'axios'; import {Chart} from 'highcharts-vue' import Highcharts3D from 'highcharts/highcharts-3d' import Highcharts from 'highcharts' if (typeof Highcharts === 'object') { Highcharts3D(Highcharts); } export default { layout: 'contentOnly', auth: false, components: { highcharts: Chart }, data() { return { data: [], chartOptions: { title: { text: '' }, tooltip: { pointFormat: '{point.percentage:.2f}%', }, chart: { type: 'pie', options3d: { enabled: true, alpha: 50, }, // plotBackgroundColor: 0, // plotBorderWidth: 0, // plotShadow: true, }, series: [{ name: '', data: [1], tooltip: { valueDecimals: 0 } }], plotOptions: { pie: { allowPointSelect: true, cursor: 'pointer', innerSize: '30%', depth: 100, dataLabels: { enabled: true, percentageDecimals: 2, color: '#002a52', connectorColor: '#002a52', formatter: function () { return '<b>' + this.point.name + '</b>: ' + this.percentage.toFixed(2) + ' %'; } } } }, credits: { enabled: false }, exporting: { buttons: { printButton: { enabled: false }, contextButton: { enabled: false } } }, } }; }, mounted() { this.fetchData() setTimeout(function(){ let data = [] var index = 0 for (var key in this.data) { data[index] = [] data[index][0] = key if (key == '30') data[index][0] = '< 30' if (key == '999') data[index][0] = '> 65' data[index][1] = this.data[key] index++; } this.chartOptions.series[0].data = data }.bind(this), 1000); }, methods: { fetchData() { axios.post(this.$axios.defaults.baseURL + 'api/analytics/age', { locale: this.$i18n.locale, onlyPaid: this.$route.query.onlyPaid }).then(response => { this.data = response.data }).catch(e => { console.log(e) }) } } } </script> A: You need to get data in the beforeCreate hook, save it in a component data and make component rendering dependent on that data: <template> <div v-if="chartOptions.series[0].data.length"> <highcharts class="hc" :options="chartOptions" ref="chart"></highcharts> </div> </template> <script> export default { beforeCreate() { fetch("https://api.myjson.com/bins/hj6se") .then(resp => resp.json()) .then(resp => { this.chartOptions.series[0].data = resp; }); }, data() { return { chartOptions: { series: [{ data: [] }] } }; } }; </script> Live demo: https://codesandbox.io/s/highcharts-vue-demo-nekm0
{ "pile_set_name": "StackExchange" }
Q: Download key with `gpg --recv-key` and simultaneously check fingerprint in a script How can I import a key via gpg --recv-key and check it's fingerprint automatically? Ideally, I would use gpg --recv-key $fingerprint directly, but gpg only recently added a check, that the received key(s) actually had the correct fingerprint instead of trusting the key-server blindly and the fix has not landed in all distributions I care about (e.g. the Docker Ubuntu Image still has an old gpg version). I want to use it in combination with apt-key to add a PPA to a docker container. A: Solution: #!/bin/bash set -e tempName=$(mktemp) gpg --status-fd 1 --keyserver keyserver.ubuntu.com --recv-keys $fingerprint 1> $tempName 2>/dev/null grep "^\[GNUPG\:\] IMPORT_OK "[[:digit:]]*" "$fingerprint"$" $tempName grep "^\[GNUPG\:\] IMPORT_RES 1" $tempName This script will return with a non-zero exit code if the key can't be downloaded or if the keyserver returns a malicious key. Beware: The malicious key still ends up in the gpg keyring, so you if you use it outside of a Dockerfile you will probably want to restore the original key ring afterwards. The commands for use in a Dockerfile (adding a rust PPA as an example): RUN echo "deb http://ppa.launchpad.net/hansjorg/rust/ubuntu trusty main" >> /etc/apt/sources.list RUN echo "deb-src http://ppa.launchpad.net/hansjorg/rust/ubuntu trusty main" >> /etc/apt/sources.list RUN bash -c 'set -e;tempName=$(mktemp);apt-key adv --status-fd 1 --keyserver keyserver.ubuntu.com --recv-keys C03264CD6CADC10BFD6E708B37FD5E80BD6B6386 1> $tempName 2>/dev/null;grep "^\[GNUPG\:\] IMPORT_OK [[:digit:]]* C03264CD6CADC10BFD6E708B37FD5E80BD6B6386$" $tempName;grep "^\[GNUPG\:\] IMPORT_RES 1" $tempName' Explanation: The first building block to consider is GnuPGs --status-fd option. It tells gpg to write machine readable output to the given file descriptor. The file descriptor 1 always references stdout, so we will use that. Then we will have to find out what the output of --status-fd looks like. The documentation for that is not in the manpage, but in doc/DETAILS. An example output looks like this: # gpg --status-fd 1 --keyserver keyserver.ubuntu.com --recv-keys BD6B6386 2>/dev/null [GNUPG:] IMPORTED 37FD5E80BD6B6386 Launchpad PPA for Hans Jørgen Hoel [GNUPG:] IMPORT_OK 1 C03264CD6CADC10BFD6E708B37FD5E80BD6B6386 [GNUPG:] IMPORT_RES 1 0 1 1 0 0 0 0 0 0 0 0 0 0 So we are looking for IMPORT_OK and IMPORT_RES lines. The second parameter after IMPORT_OK is the actual fingerprint of the imported key. The first parameter after IMPORT_RES is the number of keys imported. In the output, gpg escapes newlines, so it is ok to match for lines beginning with [GNUPG:] to assert we not matching in strings that are controlled by an attacker (for example the name field in the key could otherwise contain \n[GNUPG:] IMPORT_OK 1 C03264CD6CADC10BFD6E708B37FD5E80BD6B6386] and fool us by creating a match). With grep we can match for a line beginning with [GNUPG] sometext via grep "^\[GNUPG\:\]" and for a whole line with grep "^\[GNUPG\:\] sometext$" (^ and $ represent the start and end of a line). According to the documentation, any number following IMPORT_OK is ok for us, so we match against "[[:digit:]]*". Thus, as regular expressions we get "^\[GNUPG\:\] IMPORT_OK "[[:digit:]]*" "$fingerprint"$" and "^\[GNUPG\:\] IMPORT_RES 1" As we want to match the output twice, we safe it into a temporary file (by creating an empty temporary file with mktemp and rerouting the output in that file). If grep does not match any lines it returns with a non-zero error code. We can use that by instructing bash to abort on any error via set -e. Overall we end up with: set -e tempName=$(mktemp) gpg --status-fd 1 --keyserver keyserver.ubuntu.com --recv-keys $fingerprint 1> $tempName 2>/dev/null grep "^\[GNUPG\:\] IMPORT_OK "[[:digit:]]*" "$fingerprint"$" $tempName grep "^\[GNUPG\:\] IMPORT_RES 1" $tempName How to use with apt to add a repository key: apt-key features the adv command to hand over command line parameters directly to gpg (run the above command without output rerouting to see the actual gpg command generated by apt-key). So we can simply exchange gpg with apt-key adv to operate on the repository key ring.
{ "pile_set_name": "StackExchange" }
Q: pagination in css/php two questions: --1-- it displays all the number of pages. but i'd like it to display as: << Prev . . 3 4 [5] 6 7 . . Next >> --2-- when i hover on the current page no, it should change color or increase the font-size, but when i modify the css of a:hover, all the page nos change color or size instead of the one which i'm pointing to. also, when modifying a:active, nothing happens. this is my paging code in php: $self = $_SERVER['PHP_SELF']; $limit = 2; //Number of results per page $numpages=ceil($totalrows/$limit); $query = $query." ORDER BY idQuotes LIMIT " . ($page-1)*$limit . ",$limit"; $result = mysql_query($query, $conn) or die('Error:' .mysql_error()); ?> <div class="caption">Search Results</div> <div class="center_div"> <table> <?php while ($row= mysql_fetch_array($result, MYSQL_ASSOC)) { $cQuote = highlightWords(htmlspecialchars($row['cQuotes']), $search_result); ?> <tr> <td style="text-align:right; font-size:15px;"><?php h($row['cArabic']); ?></td> <td style="font-size:16px;"><?php echo $cQuote; ?></td> <td style="font-size:12px;"><?php h($row['vAuthor']); ?></td> <td style="font-size:12px; font-style:italic; text-align:right;"><?php h($row['vReference']); ?></td> </tr> <?php } ?> </table> </div> <div class="searchmain"> <?php //Create and print the Navigation bar $nav=""; $next = $page+1; $prev = $page-1; if($page > 1) { $nav .= "<span class=\"searchpage\"><a onclick=\"showPage('','$prev'); return false;\" href=\"$self?page=" . $prev . "&q=" .urlencode($search_result) . "\">< Prev</a></span>"; $first = "<span class=\"searchpage\"><a onclick=\"showPage('','1'); return false;\" href=\"$self?page=1&q=" .urlencode($search_result) . "\"> << </a></span>" ; } else { $nav .= "&nbsp;"; $first = "&nbsp;"; } for($i = 1 ; $i <= $numpages ; $i++) { if($i == $page) { $nav .= "<span class=\"searchpage\">$i</span>"; }else{ $nav .= "<span class=\"searchpage\"><a onclick=\"showPage('',$i); return false;\" href=\"$self?page=" . $i . "&q=" .urlencode($search_result) . "\">$i</a></span>"; } } if($page < $numpages) { $nav .= "<span class=\"searchpage\"><a onclick=\"showPage('','$next'); return false;\" href=\"$self?page=" . $next . "&q=" .urlencode($search_result) . "\">Next ></a></span>"; $last = "<span class=\"searchpage\"><a onclick=\"showPage('','$numpages'); return false;\" href=\"$self?page=$numpages&q=" .urlencode($search_result) . "\"> >> </a></span>"; } else { $nav .= "&nbsp;"; $last = "&nbsp;"; } echo $first . $nav . $last; ?> </div> and this is how it displays currently: alt text http://img714.imageshack.us/img714/7184/pag1l.jpg css: .searchmain { margin:30px; text-align: center; } .searchpage { border: solid 1px #ddd; background: #fff; text-align:left; font-size: 16px; padding:9px 12px; color: #FEBE33; margin-left:2px; } .searchpage a{ text-decoration: none; color: #808080; } .searchpage a:hover { color: #FEBE33; border-color: #036; text-decoration: none; } .searchpage a:visited { color: #808080; } A: The solution to your first program seems pretty straightforward; you know the number of surrounding links you want to display so you can simply loop from current_page - surrounding_links to current_page + surrounding_links. Add some conditions for the beginning, the end and for when to show the dots and you're done. For the css; I´m not entirely sure what you want to achieve but I think you can solve it by using just a tags, the surrounding spans seem redundant, you only need them for the items that are not links (.no_link in the example below): a, .no_link { float: left; display: block; padding:9px 12px; border: solid 1px #ddd; background: #fff; text-align:left; font-size: 16px; } a { color: #808080; } a:hover { color: #FEBE33; border-color: #036; } .no_link { color: #FEBE33; }
{ "pile_set_name": "StackExchange" }
Q: Was Picard speaking French and being translated the entire time? Someone forwarded me this link titled Sudden Star Trek realization : (Also found on reddit) So, is there any clue that indicate that Picard is really speaking French and being translated to English by the universal translator? A: No. In fact, I would say there is small evidence to suggest he is speaking Federation Standard (thought to be a form of English). In 11001001 (S1E15), the Bynars upgrade the Holodeck to create characters and environments that produce more realistic interactions. Riker creates a jazz bar and it is populated with a sophisticated holographic women named Minuet. At some point, Picard goes to the Holodeck to see how Riker is doing, and meets Minuet. She recognizes his French surname and begins talking to Picard in French, and he replies in French. Meanwhile, Riker stands there looking impressed that Minuet knows French. (The entire script for the episode can be found here.) The point of that little anecdote is that if the universal translators were constantly altering Picard's speech from French to English, then it would have been no different in this situation. Riker, and us, would have heard the conversation in English anyway. We can confirm that Riker heard French from the episode's script: Riker is surprised that she speaks French and a little jealous that she and Picard are hitting it off so well. Since Riker heard French in this interaction, we could assume that this is not standard for Picard to speak French. It is more likely that he uses Federation Standard in everyday interactions. I think you could also make a logical argument that Picard uses Federation Standard rather than French. In order to be captain of a ship, it would be much easier to have a common language. What if the universal translators broke down? From a command perspective, this would be pretty detrimental to making sure things run smoothly. Memory Alpha also notes that Federation Standard is used in official documents by the Federation government so it must have been used by Picard regularly. I think the anecdotal evidence and widespread use of Federation Standard shows that Picard was not speaking French for the entire show. A: There really isn't any firm evidence either way. I was about to raise the fact that Picard is explicitly heard to say, "Merde!", untranslated in "The Last Outpost", as evidence that he is not usually speaking French. Then I realized that doesn't really constitute evidence either way, and here's why. By and large, from Star Trek: The Motion Picture forward, alien languages are used mainly for "color", even when aliens are speaking amongst themselves. For example, in that movie, the scenes on Vulcan, and on the Klingon cruisers, are all enacted solely in their respective languages. From that point forward, however, even language amongst aliens is usually rendered in English...unless the writer or director has decided for dramatic reasons to do otherwise. This sort of device is not confined to Star Trek by any means, or even science fiction. These reasons seem to include: Hiding information from the audience (in which case, they won't even be subtitled). Simply providing a reminder that these people are aliens, and generally trying to impress the audeince with it (Spock and Saavik snarking about Kirk in The Wrath of Khan; most Klingon-language conversation from Star Trek: The Search for Spock forward). Rituals. Vulcan, Klingon, and Bajoran rituals are almost always rendered in the native tongue (with an assumption that characters who don't speak it are also hearing their Universal Translator whispering in their ears). Insults and exclamations. Picard's "Merde!" falls into that last category, even tho' it's not an "alien" language. We actually never do find out what a pataQ (Klingon) or a verul (Romulan) is, although we do know that the Klingon insult Ha'DIbaH means "animal". Most of the time, everyone appears to understand everyone else, except on occasions when the translator is either confiscated (The Undiscovered Country) or doesn't have the necessary cultural information ("Darmok"), or it's otherwise convenient for the writers (various occasions when Worf spouts something in Klingon and people say, "What's that mean?") In short, not just the Universal Translator, but language itself, is a plot device, which unfortunately means it behaves however it needs to behave for a given plot, without much consistency. None of which solves the dilemma of the original question either way, I'm afraid; any more than we really know, most of the time, what language the Doctor is speaking in Doctor Who (cf: "Does The Doctor hear everyone speaking in Gallifreyan?"). It's certainly possible, however, that throughout Star Trek, characters may have been speaking their own native language, even when we're hearing English. A: In the TNG episode "Code of Honor" Data tells Picard(?) "For example, what Lutan did is similar to what certain American Indians once did, called 'counting coup'. That is from an obscure language known as French. Counting coup..." http://en.memory-alpha.org/wiki/Code_of_Honor_%28episode%29 Surely Data would have noted if Picard were actively speaking French at the time.
{ "pile_set_name": "StackExchange" }
Q: What is the difference between Intel (CISC) and ARM (RISC) architecture? what is the basic difference between Intel (CISC) and ARM (RISC) architecture? A: In the 70's and early 80's: RAM was very very expensive it ran at the same speed as the CPU. programming by hand in assembly language was common So - simplifying very much here - it made sense to design CPUs where each instruction performed a lot of work, was easy to translate from high-level languages, and where programs were expected to use memory as a scratchpad, as opposed to internal CPU registers. This makes the CPU design complicated and power-hungry. The RISC principle advocates making instructions simple and lightweight, recognizes that compilers are the ones usually generating assembly language and not humans, and provides lots of registers (faster than RAM) for use of intermediate calculations. This makes the CPU design simpler and requires less power. The assembly language is more complicated and you usually need more instructions to do things - but as RISC was becoming prevalent, RAM prices were falling. RISC looked like it was going to win out in the late 80's/early 90's, but Intel started putting RISC-like features into it's CISC-like CPUs - and moved forward with additional performance features such as caching, branch prediction, register renaming, etc., and today's 64-bit CPUs from Intel and AMD can be considered a hybrid. However, ARM CPUs: are still much more simpler internally. ARM licenses its CPU core to chipset manufactuers. So it's easy for companies such as Qualcomm or Apple to integrate a CPU core into a phone chipset. the above two contribute to power savings which are very important on mobile devices, even though they do not perform as well as Intel hardware.
{ "pile_set_name": "StackExchange" }
Q: How do I reply to "thank you" and "sorry"? I am a foreigner and I am wondering how to respond "thank you" and "sorry". I think I could respond to "thank you" like this: You’re welcome. Don’t mention it. Not at all. (It’s ) my pleasure. That’s all right./That ok. No problem. I think I could respond to "sorry" like this: It doesn’t matter. That's all right./That’s OK. Never mind. Am I right? Do you have something else to add? Thank you so much. A: I'm an American native speaker. For "Thank you." I often use these: "You're welcome." "I'm happy to help." "No problem." (Informal, and can sound a little arrogant in some situations, but it really means "It was no trouble to help you.".) And, in America, we often return the thanks, especially when it's a mutual exchange such as buying food or something from a store: "Thank you." For "sorry": "Oh, that's okay." / "That's alright." "No big deal." Informal, but friendly. It's a nicer way to say "It doesn't matter.". "No problem." Also informal. (Yes, we can use it to answer "Thank you." and also "Sorry." -- in each case it means that you weren't bothered. But I don't recommend using this phrase in formal settings until you are really comfortable with how it feels.) "Don't worry about it." I would not say "It doesn't matter.", because that can sound like "It's not important.", which can sound dismissive, or someone might misunderstand you to be saying "It doesn't matter to me that you're sorry.". I wouldn't use it! Also, "Never mind." sounds funny in America. We usually use it to say, "You can forget what I was talking about, because it's not important.".
{ "pile_set_name": "StackExchange" }
Q: SQL Server 2014 standard edition slows the machine when Database size grows I have a scenario where an application server saves 15k rows per second in SQL Server database. At first initial hours machine is still usable but whenever the database size increases ~20gig, it seems that machine is becoming unusable. I saw some topics/forums/answers/blogs suggesting to limit the max memory usage of SQL Server. Any thoughts on this? Btw, using SQL Bulkcopy to insert rows in the database. A: I have two suggestions for you: 1 - Database settings: When you create the database, try to use a large initial size, and consider to have a bigger autogrowth percentage/size. You will want to minimize the times your filegroups need to grow. 2 - Server settings: In your SQL Server settings I would recommend that you remove one logical processor from the SQL Server. The OS will use this processor when the SQL Server is busy with heavy loads on the other processors. In my experience, this usually gives a nice boost to the OS .
{ "pile_set_name": "StackExchange" }
Q: How can i share file with virtualbox? I want to simply send a picture and other files to a virtual box and after reading a lot from this platform I still cant find my way through it. How would one do this in the most simple way possible? A: The simpliest way is probably to enable Drag'n'Drop between Guest & Host, but since you wrote neither about your Host OS nor about your Guest OS you might face some Problems. (Also the Virtual Box Version is unknown.) Nevertheless you can enable Drag'n'Drop in the VM Settings: You can choose between: Disabled Host to Guest Guest to Host Bidirectional Version is 5.0.2. The feature was introduced in 4.2. Facing problems this topic might help. Regardless of your OS there are additional information as well: Bidirectional drag'n drop is not working with VirtualBox and ubuntu 14.04 A: Since you did not give enough details about your virtualbox I can give only a general solution. There are two simple ways: 1) use dropbox or any other similar programs - this is maybe not the optimal, but the easiest 2) set up a shared drive, depending on the OS on the virtualbox this can differ, but there is a pretty detailed guide here: http://www.howtogeek.com/189974/how-to-share-your-computers-files-with-a-virtual-machine/ Hope it helps...
{ "pile_set_name": "StackExchange" }
Q: AngularJS, TypeScript, RequireJS common base controller I am looking to create a common angular base controller with some custom methods, one of which allowing me to change the $scope of the controller (defaulting to $rootScope). All other controllers can implement this base controller. Can anyone provide any advanced examples or possibly some insight as to which direction I should take? Thank you! A: I am looking to create a common angular base controller with some custom methods All nested controllers inherit from the parent controllers. So this might be of use to you : https://stackoverflow.com/a/24971239/390330 can implement this base controller. AngularJS favors composition over inheritance. If you do the controller inheritance (and not angular like in the previous example) you need to manage the $inject in each controller to pass any parameters to the parent e.g. class Base{ constructor(iNeedThisSevice){} } class Child extends Base{ static $inject = ['iNeedThisService']; constructor(iNeedThisSevice){super(iNeedThisService);} }
{ "pile_set_name": "StackExchange" }
Q: Why pi-systems and Dynkin/lambda systems? On the relative merits of approaches in measure theory. What is the point of $\pi$-systems and $\mathcal{D}$ / Dynkin / $\lambda$-systems? I am an analyst in the process of consolidating my measure theory knowledge before moving on to harder/newer things, having been first introduced to measure theory in a course with a probability as opposed to an analysis viewpoint. So far, everything that I've needed from elementary measure theory for analysis can be done (and is done in all of my analysis textbooks) without mention of the $\pi$-systems and $\mathcal{D}$-systems which were used in my first course. Do these set systems belong strictly to probability and not analysis? Heuristically, are they useful or important in any way? Why? A: My guess is that they are more useful in probability than in analysis. Many people have the impression that probability is just analysis on spaces of measure 1. However, this is not exactly true. One way to tell analysts and probabilists apart: ask them if they care about independence of their functions. Suppose that $\mathcal{F}_1,\mathcal{F}_2,...,\mathcal{F}_n$ are families of subsets of some space $\Omega$. Suppose further that given any $A_i\in \mathcal{F}_i$ we know that $P(A_1\cap A_2 \cap ...\cap A_n)=P(A_1)P(A_2)...P(A_n)$. Does it follow that the $\sigma(\mathcal{F}_i)$ are independent? No. But if the $\mathcal{F}_i$ are $\pi$-systems, then the answer is yes. When proving the uniqueness of the product measure for $\sigma$-finite measure spaces, one can use the $\pi$-$\lambda$ lemma, though I think there is a way to avoid it (I believe Bartle avoids it, for instance). However, do you know of a text which avoids using the monotone class theorem for Fubini's theorem? This, to me, has a similar feel to the $\pi$-$\lambda$ lemma. Stein and Shakarchi might avoid it, but as I recall their proof was fairly arduous. Here is a direct consequence of the $\pi$-$\lambda$ lemma when you work on probability spaces: Let a linear space H of bounded functions contain 1 and be closed under bounded convergence. If H contains a multiplicative family Q, then it contains all bounded functions measurable with respect to the $\sigma$-algebra generated by Q. Why is this useful? Suppose that I want to check that some property P holds for all bounded, measurable functions. Then I only need to check three things: If P holds for f and g, then P holds for f+g. If P holds for a bounded, convergent sequence $f_n$ then P holds for $\lim f_n$. P holds for characteristic functions of measurable sets. This theorem completely automates many annoying "bootstrapping from characteristic functions" arguments, e.g. proving Fubini's theorem. A: I'm not sure that $\pi$-systems and $\lambda$-systems are important objects in their own right, not in the same way that $\sigma$-algebras are. I think they're convenient names attached to two sets of technical conditions that appear in Dynkin's theorem. The theorem itself, though, is a huge convenience. It's properly a theorem of measure theory (measurable theory, if you want to be pedantic, since it doesn't have any measures in its statement), and so it belongs to both probability and analysis. It does seem to be more widely used in probability, most likely because Dynkin himself was a probabilist, and some popular books from the Cornell probability school use it, such as Durrett and Resnick. But it's also very useful in analysis, especially in the functional form cited by Peter (hi!). For instance, lots of approximation theorems about things being dense in $L^p$ spaces can be obtained from it. A: I think there's indeed a lot of confusion here, in that in many situations the $\pi-\lambda$ is applied where a weaker result would suffice. What one uses most of the time is not the $\pi-\lambda$ theorem itself, but the following corollary: If $\mu_1$ and $\mu_2$ are two probability measures that agree on a $\pi$-system, then they agree on the $\sigma$-algebra generated by that $\pi$-system. The example about independent events given above by Peter Luthy falls into this category. In many textbook situations the $\pi$-system in question is actually a semi-ring. For ($\sigma$-)finite premeasures, Carathéodory extension is unique for very simple reasons: any extension of the measure is bounded from above by the outer measure, and by passing to the complement it is also bounded from below. Thus, for semi-rings the above corollary is trivial. A typical example of a $\pi$-system that is not a semi-ring are closed sets in a topological space. But here, the fact that a Borel measure is determined by its values on closed sets follows from regularity, which does not require $\pi-\lambda$ theorem either. One place where you need $\pi-\lambda$ theorem (or a similar result) in an essential way is Fubini. There, you have a $\pi$-system (which is also a semi-ring) of sets of the form $E_1\times E_2$, and two ways to extend the pre-measure: by product-measure (= Carathéodory extension), and by integrating the measures of the slices. What is tricky to show is that the collection of sets for which the latter is well defined is a $\sigma$-algebra, in particular, that it is closed under pairwise intersections. Indeed, it's not clear under such operation, the function under the integral remains measurable. The $\pi-\lambda$ theorem allows one to bypass this difficulty in a very neat way. That said, once you have the $\pi-\lambda$ theorem at hand, it is often just shorter to write down the proof that something is a $\lambda$-system than that it is a $\sigma$-algebra. No wonder the authors of textbooks use it systematically even when it's an overkill.
{ "pile_set_name": "StackExchange" }
Q: Homeomorphism between del Pezzo surfaces Let $X$ and $Y$ be smooth del Pezzo surfaces of the same degree $K_X^2=K_Y^2$. Are the sets $X(\mathbb{C})$ and $Y(\mathbb{C})$ homeomorphic, or at least homotopy equivalent? A: Yes, with precisely one exception. If $K^2 \neq 8$, then the del Pezzo surface is the blow-up of the plane at $9-K^2$ points, so it is homeomorphic to the connected sum of $\mathbb{CP}^2$ with $9-K^2$ copies of $\overline{\mathbb{CP}^2}$. If $K^2=8$, then we have either the quadric $\mathbb{P}^1 \times \mathbb{P}^1$, which is clearly homeomorphic to $S^2 \times S^2$, or the blow-up of $\mathbb{P}^2$ at one point, which is homeomorphic to $\mathbb{CP}^2 \# \, \overline{\mathbb{CP}^2}$. These surfaces are not homeomorphic, since in the former case the class of $K$ is $2$-divisible in (co)homology whether in the latter case is not, and the divisibility of the canonical class is known to be a topological invariant.
{ "pile_set_name": "StackExchange" }
Q: Is it safe to eat potatoes that have sprouted? I'm talking about potatoes that have gone somewhat soft and put out shoots about 10cm long. Other online discussions suggest it's reasonably safe and the majority of us have been peeling and eating soft sprouty spuds for years. Is this correct? A: Not safe enough for me to try it. Potatoes actually contain a very dangerous toxin called solanine. This toxin is concentrated enough in the green parts in the plant to cause solanine poisoning. This includes the sprouts/eyes, and the potato itself if it's green. This article from the New York Times health guide indicates that it is something to be taken seriously. Per this article, if the sprouts have been removed, and the potato is not green then it is safe to eat as far as solanine poisoning is concerned. However, a potato as far gone as you have described sounds disgusting. A soft potato is on its way to going bad. Where I am from, potatoes are cheap enough that it's just not worth the gross factor for me to eat a potato that has 10 cm sprouts and is squishy. I do eat potatoes that have little nub sprouts on them and that are slightly less than firm, after removing the sprouts of course. A: It is safe to eat a sprouted potato if it is still firm (source: University of Illinois); however, don't expect it to act the way an unsprouted potato would. Part of the starch will have converted to sugar. Be sure to store potatoes somewhere cool and dry with good air circulation. Also, keep them away from onions. A: Other online discussions suggest it's reasonably safe and the majority of us have been peeling and eating soft sprouty spuds for years. Is this correct? Um... Well, I grew up eating them. Towards the end of winter, all the potatoes looked like that. We snapped off the sprouts, ate the firmer ones, and saved the rest for planting. We didn't die. I don't think. Unless this is all a dream, the last twenty years merely the illusion of my dying, spasming, potato-poisoned brain. That said, if you have a choice, I would stick with potatoes that haven't sprouted...
{ "pile_set_name": "StackExchange" }
Q: How to retrieve docstrings from functions and variables? I'm trying to write a function that will retrieve the docstrings from any sexps in a file that match (def.*). I'd want to both be able to retrieve any functions/macros, as well as any variables that are defined. For variables I would want the docstring, while for any functions I would also want the argument lists. A: If the goal is to get information about functions and variables already in the environment: For docstrings of functions and macros, see the documentation function. For variable docstrings, use documentation-property; for example: (documentation-property 'user-init-file 'variable-documentation) For function arity and the argument list, see this Emacs.SE question, the answer, and comments to the question. (I found this by pressing C-h k C-h f and skimming the source code of describe-function (same for variable docstrings, but studying describe-variable).) To analyze an Emacs Lisp source code file, assuming that the goal is to get information about top-level def.* forms, one can do something similar to the following. (defun get-defun-info (buffer) "Get information about all `defun' top-level sexps in a buffer BUFFER. Returns a list with elements of the form (symbol args docstring)." (with-current-buffer buffer (save-excursion (save-restriction (widen) (goto-char (point-min)) (let (result) ;; keep going while reading succeeds (while (condition-case nil (progn (read (current-buffer)) (forward-sexp -1) t) (error nil)) (let ((form (read (current-buffer)))) (cond ((not (listp form)) ; if it's not a list, skip it nil) ((eq (nth 0 form) 'defun) ; if it's a defun, collect info (let ((sym (nth 1 form)) (args (nth 2 form)) (doc (when (stringp (nth 3 form)) (nth 3 form)))) (push (list sym args doc) result)))))) result))))) This can be easily extended to defvar, defconst, etc. To handle defun appearing inside top-level forms one would have to descend into these forms, possibly using recursion.
{ "pile_set_name": "StackExchange" }
Q: Why is bluetooth-agent getting stuck on authorizing? I am trying to manually connect between my laptop and phone. I have bluez-utils version 4.98-2ubuntu7 installed. When I run the agent on the terminal, I get: asheesh@U32U:~$ sudo bluetooth-agent 4835 Pincode request for device /org/bluez/980/hci0/dev<id> Authorizing request for /org/bluez/980/hci0/dev<id> The pincode request line gets printed when I try to pair from my phone. After I enter the passkey on being prompted, the device gets authorized. I can now send files to the laptop from my phone. However, the application gets stuck after authorizing request and control is not passed back to the terminal. Why is this happening? How do I get back control? This seems to be contrary to examples I have seen across the internet, where the terminal becomes available after authorization to run further commands. I realise that running it in the background is a possible solution, but since I need to run certain other tasks once pairing is completed, I would prefer to have it run in the foreground. I tried using this: bluetooth-agent "$PIN" 1> ./bluelog #Background run tested also However, the process does not write its output to file till it completes (or is killed), so I cannot test the output in bluelog. Is there a way to force the process to write output before completion? A: This is just a workaround to the problem. Any suggestions on how to tackle the actual problem of bluetooth-agent stalling are welcome. I used stdbuf to disable line buffering of STDOUT when running bluetooth-agent in the background. This updates the log file in real time, thereby letting me check and trigger the rest of the activities that need to be done. stdbuf -o 0 bluetooth-agent "$PIN" 1> ./bluelog &
{ "pile_set_name": "StackExchange" }
Q: Obfuscate text using JavaScript? I'm looking to obfuscate (to make obscure, unclear, or unintelligible) paragraph text. Essentially I need to be able to control where it starts and stops. I don't want people previewing the source and getting the original text where it is hidden. The obfuscated text needs to follow the original formatting - keeping the spacing, line breaks, capitalisation and punctuation etc. Alphabetical characters need swapping with another random alphabetical character. I'm trying to hide text in an article. What would be the best way to do this using javascript? Example See the following example from the Make book Note: I came across the baffle library does something similar but doesn't quite do the job... A: You can make a reasonable attempt at this using vanilla JavaScript, while noting the concerns in the comments of course, particularly the point that if the original text is sent to the client it will of course be available to them. let inputText = `“It Will Feed my Revenge!” To bait fish withal: if it will feed nothing else, it will feed my revenge. He hath disgraced me, and hindered me half a million; laughed at my losses, mocked at my gains, scorned my nation, thwarted my bargains, cooled my friends, heated mine enemies; and what's his reason?`; function getRandomChar() { const characters = 'abcdefghijklmnopqrstuvwxyz'; return characters.charAt(Math.floor(Math.random() * characters.length)); } function getReplacement(char) { if (/^[^a-z]+$/i.test(char)) { return char; } let replacement = getRandomChar(); if (char.toUpperCase() === char) { replacement = replacement.toUpperCase(); } return replacement; } function obfuscate(text, start = 0, end) { end = end || text.length; const obfuscatedSection = Array.prototype.map.call(text.substring(start,end), getReplacement).join(""); return text.substring(0, start) + obfuscatedSection + text.substring(end); } console.log("Original text:", inputText); console.log("\nObfuscated text:", obfuscate(inputText, 15, 200));
{ "pile_set_name": "StackExchange" }
Q: Solr: Number of posted files does not equal maxDoc I apologize in advance if this question has already been answered somewhere - I wasn't able to find it. I'm relatively new to Solr, and have been following the instructions given by the tutorial for using the default SimplePostTool to index my data from the command line. I'm currently using Solr 4.0 in my testing. First, I delete everything in my index by query. Then I point the SimplePostTool to several directories and index tens of thousands of files. In my case, for right now, each XML file is a separate document. Some of the documents may have the same uniqueKey ID. If it matters, the XML document sizes range from 4-60kB. SimplePostTool returns when it's finished and says 26,541 files were indexed. Then I look in the Admin collection1 page and see Num Docs = 20,985 and Max Doc = 22,921. I've seen other posts discussing the discrepancy between Num Docs and Max Doc (I feel I understand that overwrite behavior sufficiently). My question is why the number of indexed docs reported by SimplePostTool does not match Max Doc given by the Solr Admin page? A: The reason you have different number of numDocs and maxDoc: numDocs represents the number of searchable documents in the index (and will be larger than the number of XML files since some files contained more than one ). maxDoc may be larger as the maxDoc count includes logically deleted documents that have not yet been removed from the index. You can re-post the sample XML files over and over again as much as you want and numDocs will never increase, because the new documents will constantly be replacing the old. From:Solr official Tutorial . This apply for older versions. You could remove logically deleted files by optimizing your index ->
{ "pile_set_name": "StackExchange" }
Q: Unable to add Imageview reference in dictionary to view I'm not sure if I'm doing this correctly, but essentially I want to instantiate my uiimageviews when the controller loads. Afterwards, when I implement a method that executes on a timer, I want to grab the reference of the uiimageview depending on the index and add it to the view. I'm using a NSMutableDictionary. I have all the code in the same method just to test it out. Shouldn't [self.view addSubview:poster]; place the first image in the current view? self.images = [NSMutableDictionary dictionary]; CGRect imageFrame = CGRectMake(0.0, 0.0, 1024.0, 280.0); UIImageView *image_one = [[UIImageView alloc] initWithFrame:imageFrame]; image_one.image = [UIImage imageNamed:@"image_one.png"]; NSString *theKey = [NSString stringWithFormat:@"%d",0]; [self.images setObject:image_one forKey:theKey]; UIImageView *image_two = [[UIImageView alloc] initWithFrame:imageFrame]; image_two.image = [UIImage imageNamed:@"image_two.png"]; NSString *theKey1 = [NSString stringWithFormat:@"%d",1]; [self.images setObject:image_two forKey:theKey1]; UIImageView *poster = (UIImageView *)[self.images objectForKey:0]; [self.view addSubview:poster]; A: First, I would suggest using an NSMutableArray. Since you are referencing the items in the array by an index anyways, might as well use an array. Although with this code, there are a couple things you should change. You should allocate the NSMutableArray instead of using the autoreleased version. When you are accessing the UIImageView, the key is a string, not an integer. So, it should read: UIImageView *poster = (UIImageView *)[self.images objectForKey:@"0"];
{ "pile_set_name": "StackExchange" }
Q: Differences between `class` and `def` What is the main difference between class and def in python? Can a class in python interact with django UI (buttons)? A: class is used to define a class (a template from which you can instantiate objects). def is used to define a function or a method. A method is like a function that belongs to a class. # function def double(x): return x * 2 # class class MyClass(object): # method def myMethod(self): print ("Hello, World") myObject = MyClass() myObject.myMethod() # will print "Hello, World" print(double(5)) # will print 10 No idea about the Django part of your question sorry. Perhaps it should be a separate question? A: class defines a class. def defines a function. class Foo: def Bar(self): pass def Baz(): pass f = Foo() # Making an instance of a class. f.Bar() # Calling a method (function) of that class. Baz() # calling a free function
{ "pile_set_name": "StackExchange" }
Q: Where can I find documentation on the raspberry pi 3 peripherals? I know there was an armv5 and armmv6 data sheet for this kind of thing, but there is none for the armv8, at least no publicly given. I went through: https://people-mozilla.org/~sstangl/arm/AArch64-Reference-Manual.pdf I didn't actually read through all of it, but parsing things like: System timer, clock, peripherals, base address... is not giving me any satisfactory results. All I want is a list of base addresses telling me what the base peripheral address is, and what the system clock's relative address is, and what the mailbox relative address is... and any and all other memory mapped peripherals. A: The ARM Architecture Reference Manual is not where the peripherals or the memory map are described. ARM is not a chip, it is a licensed processor core IP built into chips by various licencee manufacturers who implement their own peripheral designs around it. Broadcom provide the SoC for RPi, and it is a proprietary chip used internally by Broadcom, so that publish limited public data. The published Broadcom peripheral documentation refers to the RPi1's BCM2835 but is mostly identical to the RPi2 BCM2836 and RPi3 BCM2387 with respect to the peripheral set.
{ "pile_set_name": "StackExchange" }
Q: How To Play MP4 Video In Java Swing App Does anyone know any way I can play an .mp4 video file in a JPanel? I have tried JMF with .avi file but found no success and now I'm baffled and frustrated at how such a simple task of playing a video file is becoming so tedious. Anyone out there please shed some light on what path I could take and I would greatly appreciate it. I've heard of VLCJ but the issue is I can't guarantee that every machine running this app will have VLC player installed. Is there a way I can bundle VLC player in the distribution folder? Originally, the video we're using is on Vimeo but it turns out it's practically impossible to embed it due a lack of API support and I thought okay I will just play it locally and then even that is becoming so difficult now. A: Thanks to @VGR for bringing JavaFX to my attention, I just integrated a JFXPanel into a JPanel of where I wanted the video to be. It's working perfectly fine in my case since it's a simple screen with one video to play. Here's the full code snippet below: private void getVideo(){ final JFXPanel VFXPanel = new JFXPanel(); File video_source = new File("tutorial.mp4"); Media m = new Media(video_source.toURI().toString()); MediaPlayer player = new MediaPlayer(m); MediaView viewer = new MediaView(player); StackPane root = new StackPane(); Scene scene = new Scene(root); // center video position javafx.geometry.Rectangle2D screen = Screen.getPrimary().getVisualBounds(); viewer.setX((screen.getWidth() - videoPanel.getWidth()) / 2); viewer.setY((screen.getHeight() - videoPanel.getHeight()) / 2); // resize video based on screen size DoubleProperty width = viewer.fitWidthProperty(); DoubleProperty height = viewer.fitHeightProperty(); width.bind(Bindings.selectDouble(viewer.sceneProperty(), "width")); height.bind(Bindings.selectDouble(viewer.sceneProperty(), "height")); viewer.setPreserveRatio(true); // add video to stackpane root.getChildren().add(viewer); VFXPanel.setScene(scene); //player.play(); videoPanel.setLayout(new BorderLayout()); videoPanel.add(VFXPanel, BorderLayout.CENTER); } Once the getVideo() function is made, I called it in the constructor of the JFrame to trigger it on the applications launch.
{ "pile_set_name": "StackExchange" }
Q: How to fix "Error: ';' expected" or "Error: ')' expected" and errors in the boolean I am trying to create a validation for the ExpenseName and ExpenseCost Edittext so that if there is no user input it will alert the user to input some data and the "text" in the boolean also has an error on it cause it is colour red. I copied the code from another .java so that I'm pretty sure it's working just fine package com.example.back4app.userregistrationexample.Classes; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import com.example.back4app.userregistrationexample.R; public class ExpenseActivity extends AppCompatActivity { private EditText ExpenseName; private EditText ExpenseCost; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_expense); ExpenseName = (EditText) findViewById(R.id.txt_expensename); ExpenseCost = (EditText) findViewById(R.id.txt_expensecost); final Button btn_addexpense = findViewById(R.id.btn_addexpense); btn_addexpense.setOnClickListener(new View.OnClickListener()); { @Override public void onClick(View v) { //Validating the log in data boolean validationError = false; StringBuilder validationErrorMessage = new StringBuilder("Please, insert "); if (isEmpty(ExpenseCost)) { validationError = true; validationErrorMessage.append("the cost of the expense"); } if (isEmpty(ExpenseName)) { if (validationError) { validationErrorMessage.append(" and "); } validationError = true; validationErrorMessage.append("the name of the expense"); } } } private boolean isEmpty(EditText text) { if (text.getText().toString().trim().length() > 0) { return false; } else { return true; } } } } I tried putting '(' and ')' outside the "text" but it is still colour red, and I also tried changing the "isEmpty" to any other name cause maybe it's reading on the other .java but still the same thing happen. Also, I tried to Rebuild Project and Clean Project but nothing worked, Also I tried to Invalidate Caches / Restart cause I have read someone said it is not uncommon for android to have bugs like this. Is there a problem with my code? EDIT: Okay. So I closed the OnClickListener but now more "error: ';' expected" appeared and "OnClickListener' is abstract; cannot be instantiated" A: You did not close onCreate or setOnClickListener in the code you posted. @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_expense); ExpenseName = (EditText) findViewById(R.id.txt_expensename); ExpenseCost = (EditText) findViewById(R.id.txt_expensecost); final Button btn_addexpense = findViewById(R.id.btn_addexpense); btn_addexpense.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Validating the log in data boolean validationError = false; StringBuilder validationErrorMessage = new StringBuilder("Please, insert "); if (isEmpty(ExpenseCost)) { validationError = true; validationErrorMessage.append("the cost of the expense"); } if (isEmpty(ExpenseName)) { if (validationError) { validationErrorMessage.append(" and "); } validationError = true; validationErrorMessage.append("the name of the expense"); } } }); // here } private boolean isEmpty(EditText text) { if (text.getText().toString().trim().length() > 0) { return false; } else { return true; } }
{ "pile_set_name": "StackExchange" }
Q: Will this approach pass the security review? Can I pass security review using the next code? I worry about: document.addEventListener('mousemove', drag); document.addEventListener('mouseup', mouseup); and var x = (e.originalEvent && e.originalEvent.x) || e.clientX; var y = (e.originalEvent && e.originalEvent.y) || e.clientY; # Some Component helper.js: mousedown: function(component, data) { var id = data.index; var target = data.target; var list = component.get('v.list')[target]; component.set('v.dragElement', { id: id, name: list[id].name }); // Drag() var drag = $A.getCallback(function(e) { e.preventDefault(); if(!component.isValid()) return; var x = (e.originalEvent && e.originalEvent.x) || e.clientX; var y = (e.originalEvent && e.originalEvent.y) || e.clientY; component.set('v.dragOptions', { top: y - 40 + 'px', left: x + 6 + 'px', display: 'block', }); }); // Mouseup() var mouseup = $A.getCallback(function(e) { if(!component.isValid()) return; component.set('v.dragOptions', { top: '-9999px', left: '-9999px', display: 'none', }); component.set('v.dragElement', null ); document.removeEventListener('mousemove', drag); document.removeEventListener('mouseup', mouseup); return false; }); document.addEventListener('mousemove', drag); document.addEventListener('mouseup', mouseup); } A: Short Answer: When Locker is enforced everywhere, the Security Review won't bother at all about this construction. Until then, yes you can do it if you provide a (reasonable) rationale that you are not interfering with other components and also clean up after yourself. Long Answer: Try to design your app in such a way as to attach listeners to the DOM elements belonging to your component rather than attaching listeners to other components or elements of the DOM that don't belong to your app. In certain situations, you can't do this. For example, suppose you want to hide a certain element if the user clicks anywhere outside of it. In some sense, this is a bad design because you may be stealing clicks from other components. But it's a common use case that makes sense in many UI contexts in which the user, by clicking outside of a DOM element, is really intending to send an event to your code ("close this floating box"). So provide a rationale as to why you are not really stealing clicks, or mouse movements, or whatever, and then you can go ahead and do this as long as you handle it properly: 1) Add code to remove the listeners when your component is unrendered in a custom unrender handler. Although listeners attached to your own DOM elements will be deleted when the DOM elements are themselves removed by the framework, this wont happen for listeners that you added to elements not in your component, such as Document or Window, so you need to delete them in your own custom unrender method. 2) For the same reason, please handle the situation of your component being no longer valid by making cmp.isValid() checks and if you are calling framework methods also use the appropriate re-entry mechanism provided by $A.getCallback(). There have been some situations of event handlers attached to window that modify an attribute of a DOM element (say in an animation) that may have been garbage collected, resulting in many exceptions being thrown. Really check that things still exist in the expected state in your async code. In Locker, the scoping issues go away (but #2 still needs to be handled). Because at the moment, Locker is not always guaranteed to be enforced everywhere, you still need to write your code so that it works both in and out of Locker. An update will be made in the Requirements Checklist and Lightning Component Security Best Practices when this changes.
{ "pile_set_name": "StackExchange" }
Q: Download script for PHP In my website I want the users to download a music file when a button is clicked. The problem I am experiencing is that when the button is clicked the download starts but only 506 KB on a total of 4 MB are downloaded and when it is opened it shows unsupported format. I use this php download script with html form to make the download: HTML FORM <FORM ACTION="download.php" METHOD=POST> <INPUT TYPE="hidden" NAME="music" VALUE= "music/<? print $file; ?>" > <INPUT TYPE="SUBMIT" NAME="download" VALUE="Download"> </FORM> PHP DOWNLOAD SCRIPT <?php $FileName = $_POST["music"]; $FilePath = "music"; $size = filesize($FilePath . $FileName); header("Content-Type: application/force-download; name=\"". $FileName ."\""); header("Content-Transfer-Encoding: binary"); header("Content-Length: ". $size .""); header("Content-Disposition: attachment; filename=\"". $FileName ."\""); header("Expires: 0"); header("Cache-Control: private"); header("Pragma: private"); echo (readfile($FilePath . $FileName)); ?> Can you please point me to the problem? A: Your code is looking for a file in a location like: musicmusic/file.mp3 Assuming your file is actually stored in something like music/file.mp3, and variable $file contains something like file.mp3, you want to replace: <INPUT TYPE="hidden" NAME="music" VALUE= "music/<? print $file; ?>"> with: <INPUT TYPE="hidden" NAME="music" VALUE= "<? print $file; ?>"> and then replace this: $FilePath = "music"; with: $FilePath = "music/"; (or delete $FilePath at all) Also, I would recommend you to check $_POST["music"] doesn't contain .. or start with / before you let anyone download any file from your server.
{ "pile_set_name": "StackExchange" }
Q: CSS is not working as expected within the HTML file The output is not appearing unless I provide text between the tag. Is there a way to fix this? Thanks in advance HTML CODE .Top { height: 20%; width: 80%; background: linear-gradient(#bc581e, #e27b36); border-radius: 50% 50% 0 0; box-shadow: inset -15px 0 #c15711; margin: 2% auto; position: relative; } <div class="Top">top</div> JSBIN url : CLICK HERE A: If you want to set height in % you have to define height to parent of element, In your case html/body are parents so set height:100%; to parents html,body{ height:100%; } .Top { height: 20%; width: 80%; background: linear-gradient(#bc581e, #e27b36); border-radius: 50% 50% 0 0; box-shadow: inset -15px 0 #c15711; margin: 2% auto; position: relative; } <div class="Top"></div> Or set height in px not % .Top { height: 20px; width: 80%; background: linear-gradient(#bc581e, #e27b36); border-radius: 50% 50% 0 0; box-shadow: inset -15px 0 #c15711; margin: 2% auto; position: relative; } <div class="Top"></div>
{ "pile_set_name": "StackExchange" }
Q: How to get value from checked checkbox, which are in a table I have a form: <form action='send.php' method ='post'> SMS: <input type='checkbox' name = 'sms'> E-mail: <input type='checkbox' name = 'email' id='mailcheck'><br> <TEXTAREA NAME='message' WRAP='virtual' COLS='40' ROWS='3'> </TEXTAREA><br> <input type ='submit' name ='Send' size = '10' value = 'send'> </form> I have a table which construct from DB: $table = "<table border=1 width=100% align=center>\n"; $table .= "<tr>\n"; $i = 1; while ($i < mysql_num_fields($queryResult)) { $meta = mysql_fetch_field($queryResult, $i); $i++; $table .= "<td>".$meta->name."</td>\n"; } $table .= "<td> Выбрать все: <input type='checkbox' name='maincheck' value='main' id='chkSelectAll'</td>\n"; $table .= "</tr>\n"; $i = 1; while ($row = mysql_fetch_assoc($queryResult)){ $table .= "<tr>\n"; $table .= "<td>".$row['name']."</td>\n"; $table .= "<td>".$row['post']."</td>\n"; $table .= "<td>".$row['section']."</td>\n"; $table .= "<td>".$row['company']."</td>\n"; $table .= "<td>".$row['phone_number']."</td>\n"; $table .= "<td>".$row['email']."</td>\n"; $table .= "<td>".$row['status']."</td>\n"; $table .= "<td>".$row['lock_time']."</td>\n"; $table .= "<td>".$row['reason_for_blocking']."</td>\n"; $table .= "<td><input type='checkbox' class=".check." name='cbname3[]' id='chkItems' value=".$row['id']." /></td>"; $table .= "</tr>\n"; $i++; } $table .= "</table>\n"; echo $table; I want to take value of checked checkboxes from table to send.php. I cant take this throw $_POST, because it's different forms! A: I cant take this throw $_POST, because it's different forms! With your code as written in the question, the checkboxes are not inside any form and you have only one form. Put the table inside that form.
{ "pile_set_name": "StackExchange" }
Q: NullPointerExeption Android I am having problems locating the nullpointerexeption that keeps coming up. The log cat does not show a "caused by" tag and that is what is making it difficult to find out what the actual problem is. If anyone could just guide me to finding out what the problem is then that would be great. I have also tried running the debugger and I get the provided error, but I have no clue what to do about it. Below is the error messages that I keep getting, and if need be I will post the code. Debugger: Thread [<1> main] (Suspended (exception NullPointerException)) <VM does not provide monitor information> Choreographer.doCallbacks(int, long) line: 565 Choreographer.doFrame(long, int) line: 532 Choreographer$FrameDisplayEventReceiver.run() line: 735 Handler.handleCallback(Message) line: 725 Choreographer$FrameHandler(Handler).dispatchMessage(Message) line: 92 Looper.loop() line: 137 ActivityThread.main(String[]) line: 5329 Method.invokeNative(Object, Object[], Class, Class[], Class, int, boolean) line: not available [native method] Method.invoke(Object, Object...) line: 511 ZygoteInit$MethodAndArgsCaller.run() line: 1102 ZygoteInit.main(String[]) line: 869 NativeStart.main(String[]) line: not available [native method] Log Cat Error: 10-09 13:14:35.675: D/dalvikvm(12528): GC_CONCURRENT freed 825K, 9% free 35986K/39424K, paused 3ms+6ms, total 26ms 10-09 13:14:35.675: D/dalvikvm(12528): WAIT_FOR_CONCURRENT_GC blocked 2ms 10-09 13:14:35.705: I/endeffect(12528): AbsListView.onMeasure(), getWidth()=1080, getHeight()=1806, this=android.widget.ExpandableListView{43a168c0 VFED.VC. .F....ID 0,0-1080,1806 #7f060023 app:id/exp_list_view_deals_events} 10-09 13:14:35.705: D/AndroidRuntime(12528): Shutting down VM 10-09 13:14:35.705: W/dalvikvm(12528): threadid=1: thread exiting with uncaught exception (group=0x41467ac8) 10-09 13:14:35.716: E/AndroidRuntime(12528): FATAL EXCEPTION: main 10-09 13:14:35.716: E/AndroidRuntime(12528): java.lang.NullPointerException 10-09 13:14:35.716: E/AndroidRuntime(12528): at android.widget.AbsListView.obtainView(AbsListView.java:2615) 10-09 13:14:35.716: E/AndroidRuntime(12528): at android.widget.ListView.measureHeightOfChildren(ListView.java:1253) 10-09 13:14:35.716: E/AndroidRuntime(12528): at android.widget.ListView.onMeasure(ListView.java:1165) 10-09 13:14:35.716: E/AndroidRuntime(12528): at android.view.View.measure(View.java:16059) 10-09 13:14:35.716: E/AndroidRuntime(12528): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4923) 10-09 13:14:35.716: E/AndroidRuntime(12528): at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1410) 10-09 13:14:35.716: E/AndroidRuntime(12528): at android.widget.LinearLayout.measureVertical(LinearLayout.java:695) 10-09 13:14:35.716: E/AndroidRuntime(12528): at android.widget.LinearLayout.onMeasure(LinearLayout.java:588) 10-09 13:14:35.716: E/AndroidRuntime(12528): at android.view.View.measure(View.java:16059) 10-09 13:14:35.716: E/AndroidRuntime(12528): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4923) 10-09 13:14:35.716: E/AndroidRuntime(12528): at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1410) 10-09 13:14:35.716: E/AndroidRuntime(12528): at android.widget.LinearLayout.measureVertical(LinearLayout.java:695) 10-09 13:14:35.716: E/AndroidRuntime(12528): at android.widget.LinearLayout.onMeasure(LinearLayout.java:588) 10-09 13:14:35.716: E/AndroidRuntime(12528): at android.view.View.measure(View.java:16059) 10-09 13:14:35.716: E/AndroidRuntime(12528): at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:681) 10-09 13:14:35.716: E/AndroidRuntime(12528): at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461) 10-09 13:14:35.716: E/AndroidRuntime(12528): at android.view.View.measure(View.java:16059) 10-09 13:14:35.716: E/AndroidRuntime(12528): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4923) 10-09 13:14:35.716: E/AndroidRuntime(12528): at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1410) 10-09 13:14:35.716: E/AndroidRuntime(12528): at android.widget.LinearLayout.measureVertical(LinearLayout.java:695) 10-09 13:14:35.716: E/AndroidRuntime(12528): at android.widget.LinearLayout.onMeasure(LinearLayout.java:588) 10-09 13:14:35.716: E/AndroidRuntime(12528): at android.view.View.measure(View.java:16059) 10-09 13:14:35.716: E/AndroidRuntime(12528): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4923) 10-09 13:14:35.716: E/AndroidRuntime(12528): at android.widget.FrameLayout.onMeasure(FrameLayout.java:310) 10-09 13:14:35.716: E/AndroidRuntime(12528): at android.view.View.measure(View.java:16059) 10-09 13:14:35.716: E/AndroidRuntime(12528): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4923) 10-09 13:14:35.716: E/AndroidRuntime(12528): at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1410) 10-09 13:14:35.716: E/AndroidRuntime(12528): at android.widget.LinearLayout.measureVertical(LinearLayout.java:695) 10-09 13:14:35.716: E/AndroidRuntime(12528): at android.widget.LinearLayout.onMeasure(LinearLayout.java:588) 10-09 13:14:35.716: E/AndroidRuntime(12528): at android.view.View.measure(View.java:16059) 10-09 13:14:35.716: E/AndroidRuntime(12528): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4923) 10-09 13:14:35.716: E/AndroidRuntime(12528): at android.widget.FrameLayout.onMeasure(FrameLayout.java:310) 10-09 13:14:35.716: E/AndroidRuntime(12528): at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2414) 10-09 13:14:35.716: E/AndroidRuntime(12528): at android.view.View.measure(View.java:16059) 10-09 13:14:35.716: E/AndroidRuntime(12528): at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2133) 10-09 13:14:35.716: E/AndroidRuntime(12528): at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1286) 10-09 13:14:35.716: E/AndroidRuntime(12528): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1497) 10-09 13:14:35.716: E/AndroidRuntime(12528): at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1183) 10-09 13:14:35.716: E/AndroidRuntime(12528): at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4863) 10-09 13:14:35.716: E/AndroidRuntime(12528): at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749) 10-09 13:14:35.716: E/AndroidRuntime(12528): at android.view.Choreographer.doCallbacks(Choreographer.java:562) 10-09 13:14:35.716: E/AndroidRuntime(12528): at android.view.Choreographer.doFrame(Choreographer.java:532) 10-09 13:14:35.716: E/AndroidRuntime(12528): at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735) 10-09 13:14:35.716: E/AndroidRuntime(12528): at android.os.Handler.handleCallback(Handler.java:725) 10-09 13:14:35.716: E/AndroidRuntime(12528): at android.os.Handler.dispatchMessage(Handler.java:92) 10-09 13:14:35.716: E/AndroidRuntime(12528): at android.os.Looper.loop(Looper.java:137) 10-09 13:14:35.716: E/AndroidRuntime(12528): at android.app.ActivityThread.main(ActivityThread.java:5329) 10-09 13:14:35.716: E/AndroidRuntime(12528): at java.lang.reflect.Method.invokeNative(Native Method) 10-09 13:14:35.716: E/AndroidRuntime(12528): at java.lang.reflect.Method.invoke(Method.java:511) 10-09 13:14:35.716: E/AndroidRuntime(12528): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102) 10-09 13:14:35.716: E/AndroidRuntime(12528): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869) 10-09 13:14:35.716: E/AndroidRuntime(12528): at dalvik.system.NativeStart.main(Native Method) A: You are return null in your getView() function. See here: Crash in ListView at AbsListView.obtainView for ListActivity
{ "pile_set_name": "StackExchange" }
Q: Can php call non static method without instantiating the class first? I register class methods for actions in my Wordpress plugin. When my method gets called by Wordpress, if I try to use the $this variable, php throws an error saying the call to $this variable is illegal outside the context of an object. How can that be? I thought unless the method is static, you're not supposed to be able to call class methods if the class isn't instantiated! My method isn't static! What is happening? The source code Obviously the initialize is called from the main plugin file: add_action('init', array('AffiliateMarketting', 'initialize'), 1); My class looks like this: class AffiliateMarketting { public function __construct() { // some initialization code } public function initialize() { add_action('woocommerce_before_single_product', array("AffiliateMarketting", "handleAffiliateReferral")); } public function handleAffiliateReferral($post) { $this->xxx(); // <---- offending function call } public function xxx() { } } The received error message is in fact Fatal error: Using $this when not in object context in <filename> on line <linenumber>. A: You have to instantiate the class first. Something like this: $affiliatemarketing = new AffiliateMarketing; and then do the following: add_action('init', array(&$affiliatemarketing, 'initialize'), 1); Edit: forgot to add, your action in your method should be added like this: add_action('woocommerce_before_single_product', array(&$this, "handleAffiliateReferral"));
{ "pile_set_name": "StackExchange" }
Q: How to address situtations where the effort to avoid plagiarism results in less effective communication? I have been contemplating this topic because of something that happened a number of years ago. Do you have any suggestions on alternative ways to handle the following case: A student in one of my community college classes (Introduction to Public Speaking) wrote a moving self-introduction for his “icebreaker” speech. The student was a homeless person who had resolved to become a college graduate and his brief autobiographic speech offered the class a rather poignant insight into what it actually meant to be homeless. The following year that same student was in another of my COMM classes and the students were required to deliver a persuasive speech based on one of the three classic rhetorical modes of persuasion: ethos, pathos, or logos. The aforementioned student’s speech topic attempted to persuade his classmates to help the homeless by appealing to their emotions. A great deal of his speech was clearly “lifted” verbatim from his icebreaker text. To his credit his speech introduction did include the following sentence: “Last year I wrote a speech describing what it means to be homeless and today I would like to revisit that topic.” and he also correctly cited his own speech in the written outline. When a student just re-uses all or most of a speech without acknowledging the prior work I consider that self-plagiarism. When a student copies verbatim text but gives clear attribution I consider that a lazy effort. However, in this case the precise phrasing and constructions used by the student had such strong emotional appeal I would be hard-pressed to find any way to revise the speech without lessening its impact. Imagine having Martin Luther King in your speech class and requiring him to rewrite his "I Have A Dream" speech without using any repetitive phrases. In this case his grade was based on the 2nd speech alone without factoring in the 1st speech in any way. However I did follow up and educate the student on the subject of self-plagiarism (amazing how few students are aware of this concept) and cautioned him to be avoid or at the least to be extremely careful when re-using his work. Considering this particular student's overall performance I am fine with his specific work and the grade he received for this project. However I wonder what I would do if a similar case happened again and felt it would make a good question here. It relates somewhat to the opposite scenario in which a student desperately trying to avoid plagiarism contorts the phrasing of a source into an awkward and ineffective communication. In the one case the underlying question is: Do you ignore or mitigate the duplication of the (correctly attributed) source to respect the effectiveness of the wording? In the other case the question is: Do you ignore or mitigate the horrible wording in order to respect the avoidance of duplication? A: Let's split this into two different cases: Is re-using a speech self-plagiarism? Is re-using a speech appropriate in that specific classroom context? Addressing the first question, the reason why self-plagiarism is an issue is that there is an expectation of novelty in scientific communication: re-using text from a previous manuscript is thus "cheating." There is no such expectation of novelty in speeches. It is thus just fine to re-use content in a talk, and there is not even any requirement to acknowledge that one has given the same talk elsewhere. Consider, for example, a person doing faculty interviews and giving the same talk at different places: this is perfectly normal, acceptable, and even desirable. Now, if you give the same talk to the same audience multiple times, they'll probably get bored and stop inviting you to talk, because you don't have anything new to say. Similarly, because talks are often tied to manuscripts, e.g., at conferences, it will necessarily be the case that they contain much new material. Still, these are byproducts of the nature of the communication, not ethical principals. Now, to the second question: should the student have re-used the same speech in class? Here, I would say that it depends greatly on the educational goal of the class. If the goal is to workshop particular aspects of the content or delivery of a speech, then I think that it would be fine, since you can work on new aspects of a speech even if it is not new (or even yours!): for example, you might want to work on delivery and oration, and even just quoting Martin Luther King could be just fine for that. If, on the other hand, the goal is to learn how to create a speech, then it's failing to satisfy the educational objectives of the class. To take the analogy: even if Martin Luther King's best speech was "I have a dream," it shouldn't mean it's the only speech he can ever give. I wouldn't call it self-plagiarism, since novelty is not the default expectation in speeches, but it would be failing to follow instructions. Not knowing the exact nature and instructions of your class, however, I'm not sure which category it falls into.
{ "pile_set_name": "StackExchange" }
Q: C++ - Seg Fault from Deleting Dynamic Array Having some trouble deleting a dynamically allocated array, and I'm not 100% sure why. The only thing I do to this array is copy over some values from it individually (in a for loop), in another routine, which is verified to work correctly. Here is the declaration in class: std::complex<float> * frameData; instantiation in constructor: this->frameData = new std::complex<float>[n]; srand( time(NULL) ); std::complex<float> randUnityRoot; for( int i = 0; i < this->n; i++){ randUnityRoot = std::polar(1.0, 2*M_PI * (rand() % 1000000)/1e06); this->frameData[i] = randUnityRoot; } deletion in destructor(this is the line 70 mentioned in the backtrace): delete[] this->frameData; gdb backtrace after segfault at program completion: (gdb) f 4 #4 0x00007ffff7bc579c in Frame::~Frame (this=0x602940, __in_chrg=<optimized out>) at Frame.cpp:70 70 delete[] this->frameData; (gdb) f 3 #3 0x00007ffff7669b96 in ?? () from /lib/x86_64-linux-gnu/libc.so.6 (gdb) f 2 #2 0x00007ffff765f39e in ?? () from /lib/x86_64-linux-gnu/libc.so.6 (gdb) f 1 #1 0x00007ffff7624b8b in abort () from /lib/x86_64-linux-gnu/libc.so.6 (gdb) f 0 #0 0x00007ffff7621425 in raise () from /lib/x86_64-linux-gnu/libc.so.6 (gdb) I've been staring at this for a while and am right out of ideas. I figured I would turn to the hive mind. Please let me know if you would like any more information. Thanks! EDIT: I updated everything to a vector and vector* based approach. No segfaults :). To generate some sort of "knowledge gained" from this however, in another class I had called something like: std::complex<float> * frameGet; frameGet = this->Frame->getFrame(); // Do stuff with frameGet //THIS NEXT LINE IS THE BAD PART delete[] frameGet; Half question, half assertion: delete[] frameGet calls delete on original array content? If frameGet needs to be deleted should do something like: frameGet = NULL; delete frameGet; A: You most probably do not have either copy-ctor nor assignment operator explicitly defined in your class. So describe them in private section of your class (make then inaccessible): class Frame { //... private: Frame( const Frame & ); Frame &operator=( const Frame & ); // ... }; you do not even have to implement them and compiler will show exact locations where your problem is by compilation errors. About second half of your question. For some reason you think if you assign one raw pointer to another you copy that memory and need to delete them separately. That not the case, raw pointer is just a number - address in memory. So: int *pi = new int[N]; // now pi has address of memory reserved by new, lets say 0x1234 int *api = pi; // now api has the same address 0x1234 as pi delete[] api; // you tell environment that you do not need memory at address 0x1234 anymore delete[] pi; // you tell environment that you do not need memory at address 0x1234 again, which is error The fact you just assign one pointer to another directly or do that through function result or parameter pass does not change anything.
{ "pile_set_name": "StackExchange" }
Q: How do you get this field using reflection? I have a class with a field that always returns the same string: public class A { // cool C# 6.0 way to implement a getter-only property. public string MyString => "This is a cool string!" } Is there any way using reflection (or some other way I might be missing) to return MyString without having to instantiate a new instance of A? The signature can not be changed, so making it static is not an option. A: Nope, it's an instance property, if it were a static property, then yes you could but otherwise you need to instantiate the object to get the actual return value because you need to provide an instance to the GetValue method for reflection, and pass in null for static properties A: No, since the property in the question is a instance one (not static) willy-nilly, you have to provide an instance. To obtain the property via Reflection: A myA = new A(); ... String value = myA.GetType().GetProperty("MyString").GetValue(myA) as String; You may want to declare the property as static, and in this case you don't have to have any instances. Note, that Reflection doesn't want an instance: public class A { // note "static" public static string MyString => "This is a cool string!"; } ... String value = typeof(A).GetProperty("MyString").GetValue(null) as String;
{ "pile_set_name": "StackExchange" }
Q: Passing 'this' to an onclick event Possible Duplicate: The current element as its Event function param Would this work <script type="text/javascript"> var foo = function(param) { param.innerHTML = "Not a button"; }; </script> <button onclick="foo(this)" id="bar">Button</button> rather than this? <script type="text/javascript"> var foo = function() { document.getElementId("bar").innerHTML = "Not a button"; }; </script> <button onclick="foo()" id="bar">Button</button> And would the first method allow me to load the javascript from elsewhere to perform actions on any page element? A: The code that you have would work, but is executed from the global context, which means that this refers to the global object. <script type="text/javascript"> var foo = function(param) { param.innerHTML = "Not a button"; }; </script> <button onclick="foo(this)" id="bar">Button</button> You can also use the non-inline alternative, which attached to and executed from the specific element context which allows you to access the element from this. <script type="text/javascript"> document.getElementById('bar').onclick = function() { this.innerHTML = "Not a button"; }; </script> <button id="bar">Button</button> A: You can always call funciton differently: foo.call(this); in this way you will be able to use this context inside the function. Example: <button onclick="foo.call(this)" id="bar">Button</button>​ var foo = function() { this.innerHTML = "Not a button"; }; A: Yeah first method will work on any element called from elsewhere since it will always take the target element irrespective of id. check this fiddle http://jsfiddle.net/8cvBM/
{ "pile_set_name": "StackExchange" }
Q: Lambda long running task gets executed two times with no errors I am calling a lambda via aws-sdk with explicit RequestResponse const Lambda = require("aws-sdk/clients/lambda"); const lambda = new Lambda({region: "region"}); const params = { FunctionName: "myFunctionArn", InvocationType: "RequestResponse", Payload: JSON.stringify({ //... my payload }) }; lambda.invoke(params).promise().then(data => { console.log(data); }); It is a long running task >~5 minutes and my timeout is set to 10 minutes. I download an mp3, compress it, save it to S3 and then return the url to the client. There are no errors in cloudwatch and the process goes smoothly, the mp3 is store with lower quality to S3, however the function gets executed two times. If the mp3 file is small enough (~8 MB) there is only one execution, however if it is a big file (~100MB) it will get executed two times and of course the function will timeout. I am using the /tmp folder to store the file temporarily, I will as well remove them after the mp3 has been safely stored in S3 I have scattered my function with logging and there is absolutely no sign of errors and this is happening every single time, not sporadically. Those are my cloudwatch logs Thanks EDIT_1: I have tried by adding some options to the lambda client const Lambda = require("aws-sdk/clients/lambda"); const lambda = new Lambda({ region: "ap-southeast-1", httpOptions: { timeout: 10 * 60 * 1000, connectTimeout: 10 * 60 * 1000 } }); But looks like nothing has changed EDIT_2: seems like now this is happening also for short running tasks and is completely random. I am at loss here I really don't know what to do A: After spending countless hours through debugging, I just discovered that the cause of this weird behavior was because the function was going out of memory. Incredibly enough nothing showed up on Cloudwatch.
{ "pile_set_name": "StackExchange" }
Q: How is type information stored in memory (if at all) I know how C-style languages store the data in a variable. They use one or two blocks on the stack, and in the case of objects space is also allocated on the heap, for its fields. But where does java store whether two blocks make a double or an int? How does it know that a particular object reference in the stack points to an object. The thought that spawned this question is what happens if I do String s; If I understand correctly, this creates an object reference in the stack that is set to null, so two bytes of zeros, and no corresponding space on the heap. If so, how does Java "remember" that this reference belongs to a String? I can imagine that remembering types isn't necessary, and the bytecode just operates on raw data, and we know it does so correctly, because it compiles. On the other hand, that sounds like type erasure, which leads to lots of corner cases and unsafety. If this is the case, why is the type erasure on generics different from type erasure on the primitives and objects themselves? (ie. for the latter, you never ever have to think about it, and with generics it crops up all the time). NB: I say C-style, because I assume the solution is the same for all languages in that family. If there are different approaches, I'd like to know about the differences as well. A: If String s is a variable inside a method, the bytecode is compiled with the knowledge that that reference is a String. a variable in a class, static or non-static, then the class definition includes the knowledge that that field holds a String, though that's almost never used -- it's not really necessary. Each object in Java has a few bytes allocated that refer to its own type. (This is not stored in the reference -- it's stored in the object itself.)
{ "pile_set_name": "StackExchange" }
Q: Equation is solved quickly using Solve but takes too long using NSolve I have the following simple command to solve for h in an equation: Solve[(1 - 2.25577*^-5*h)^5.25588 == 0.9644952131579817, h] This works just fine, but throws the warning that inverse functions are used so some solutions may not be found. Not a problem. However, if I use NSolve, Literally by just adding an N in front of Solve, it takes forever, and I end up aborting it because it takes too long. Does anyone know why exactly this is happening? I'm using Mathematica 10.0 Student Edition on a Windows 8.1 system. A: It is probably because it is solving a degree 131397 equation: (1 - 2.25577*^-5*h)^5.25588 == 0.9644952131579817 // Rationalize[#, 0] & (* (1 - (225577 h)/10000000000)^(131397/25000) == 79369373/82291101 *) Simpler comparison, to show equivalence with a rationalized equation: s1 = NSolve[(1 - 2.25577*^-5*h)^5.30 == 0.9644952131579817 // Rationalize[#, 0] &, h]; s2 = NSolve[(1 - 2.25577*^-5*h)^5.30 == 0.9644952131579817, h]; s1 == s2 (* True *) Update - Remarks: What I've gleaned from the documentation and this site is that NSolve is based on algorithms for solving polynomial systems. It can be used to solve systems that can be converted to polynomial systems, such as the OP's equation with rationalized coefficients and power. It can be converted to a degree 131397 polynomial equation, with a RHS involving some pretty large integers, probably another factor in the slowness. One would expect that many of the 131397 solutions to the polynomial equation would be extraneous. Note: A recent improvement has extended the capabilities of NSolve and Solve to transcendental equations over a bounded domain; e.g., NSolve[Erfc[x] == BesselJ[1, x] && 0 < Re@x < 5 && 0 < Im@x < 5, x]. NSolve to my mind is not the numeric analog to a symbolic Solve. NSolve is more specialized. Further NSolve I believe will find all roots, and it will find all real roots if we specify the domain Reals with NSolve[eqn, h, Reals]. Solve is content to return just one in the OP's case. There is a big difference in verifying that all solutions have been found and that one has been found. In the case where one has a numeric equation with a single real root, NSolve seems the wrong tool to me. FindRoot would be my first thought. But clearly, Solve turns out to be a good choice here. Knowing that Solve would use inverse functions, one can suppress the message with Quiet[Solve[(1 - 2.25577*^-5*h)^5.25588 == 0.9644952131579817, h], Solve::ifun]
{ "pile_set_name": "StackExchange" }
Q: Problems with using float "possible lossy conversion" This is a code I've written for one of my CS classes, but I guess I dont have a proper understanding of the term float yet. It works for the first 3 conversions, and then it gives me error for pints, quarts and gallons (where decimals start). I've tried converting them into fractions but the program just ends up spitting out 0 as the result then. The error that results is incompatible types: possible lossy conversion from double to float My code is as follows: import java.lang.*; import java.util.*; /* Description: This application will be used to convert a user given volume in cups to its equivalent number of teaspoons, tablespoons, ounces, pints quarts, or gallons. This program will allow us to view what a certain volume of cups would be in tablespoons, teaspoons etc. This program will need the number of cups from the user. Then the program will output the neccessary teaspoons, tablespoons etc. 4 cups equals 4 * 48 = 192 teaspoons 4 cups equals 4 * 16 = 64 tablespoons 4 cups equals 4 * 8 = 32 ounces 4 cups equals 4 * 0.5 = 2 pints 4 cups equals 4 * 0.25 = 1 quart 4 cups equals 4 * 0.0625 = 0.2500 gallon java.util and java.text will be used The input and output will be simple text based interactions using system.out.Println and scanner Psuedocode: Output a welcome message Output a message that describes what the program will do Output a message requesting the number cups the user wishes to convert read the input value and store it calculate the teaspoons, tablespoons etc and store it. output a message that displays this values so the user can see it */ class cupsconversion { public static void main(String[] args) { System.out.println("Welcome to Shahrukhs Cup Conversion Program"); System.out.println(); System.out.println("This application will be used to convert a user given volume"); System.out.println("in cups to its equivalent number of teaspoons, tablespoons, ounces, pints"); System.out.println("quarts, or gallons"); System.out.println("\n \n"); System.out.println("Please type in a +ve real value for the number of cups you want converted"); System.out.print(" Number of cups = "); Scanner input = new Scanner(System.in); float cups; // We are storing the input the user puts in float. cups = input.nextFloat(); float teaspoons = cups * 48; float tablespoons = cups * 16; float ounces = cups * 8; float pints = cups * 0*5; float quarts = cups * 0.25; float gallons = cups * 0.0625; System.out.println(" Given " + cups + " cups, the volume in teaspoons are " + teaspoons); System.out.println(" Given " + cups + " cups, the volume in tablespoons are " + tablespoons); System.out.println(" Given " + cups + " cups, the volume in ounces are " + ounces); System.out.println(" Given " + cups + " cups, the volume in pints are " + pints); System.out.println(" Given " + cups + " cups, the volume in quarts are " + quarts); System.out.println(" Given " + cups + " cups, the volume in gallons are " + gallons); } } A: float quarts = cups * 0.25; Here 0.25 is interpreted as a double, forcing cups * 0.25 to be represented as a double, which has higher precision than cups. You have several options: write cups * 0.25f write cups / 4 write (float) (cups * 0.25) Also, note that you wrote cups * 0*5; instead of cups * 0.5, which will set cups to 0.
{ "pile_set_name": "StackExchange" }
Q: How can I get sed to only match to the first occurrence of a character? I'm using GNU Sed 4.2.1. I'm trying to replace the second field in the following line (the password in /etc/shadow). Awk is not an option. username:P@s$w0rDh@$H:15986:0:365:::: I've tried sed -i 's/\(^[a-z]*\):.*?:/\1:TEST:/' but nothing. I've tried many variations but for some reason I can't get it to only match that field. Help? A: Use [^:]* to match everything up until the next : sed -i 's/^\([^:]*\):\([^:]*\):/\1:TEST:/'
{ "pile_set_name": "StackExchange" }
Q: php how to know that a click came from google My adsense ad have a dedicated land page. I want to show the content only to those who came through that ad. The page is coded with PHP so I'm using $_SERVER['HTTP_REFERER']. Two questions here: Is there a better alternative to $_SERVER['HTTP_REFERER'] ? To what strings/domains should I compare the referrer's domain (I'll handle extracting it)? I mean, I'm guessing that google has more than one domain they're using for the ads, or not? There's doubleclick.com.... any other domain? How can I check it, besides try/fail? A: $_SERVER['HTTP_REFERER'] is the canonical way to determine where a click came from generally. There are more reliable (and complicated) methods for clicks within a site you fully control, but that's not much help for clicks from Google. Yes, it can be spoofed, and yes, it can be null, but as long as you're not targeting nuclear weapons based on that data, and you can handle null values gracefully, it should be good enough. As for domains, you have to consider the international google domains, as well as all the google*.com domains.
{ "pile_set_name": "StackExchange" }
Q: JDBC mssql's tsql not work I have a JDBC program want to use transaction, if statement is a single sql string, such as: update tab1 set name='killy' where code='admin' but statement contain "if exists...",for example: if exists(select * form tab1 where code='admin') then update tab1 set name='killy' where code='admin' else insert into tab1 values('admin','killy') This problem has been confused me. A: Sorry, I try it,it's work well.
{ "pile_set_name": "StackExchange" }
Q: Dot product, ported from C to Swift This is how I posted a method from C to Swift. I tested it well, it seems to work. It's there a way to write this better, following good practices of Swift? The original is in C and the target must be in Swift. Original C Code: inline float mac(const float *a, const float *b, unsigned int size) { float sum = 0; unsigned int i; for (i = 0; i < size; i++) sum += (*a++) * (*b++); return sum; } and the translation to Swift: func mac(a : [Float], b : [Float], size : Int) -> Float { var sum : Float = 0; for (var i = 0; i < size; i++){ sum += (a[i]) * (b[i]); } return sum; } A: You can remove the size parameter as arrays know their own size in Swift, and use the zip, map and reduce functions to perform the computation rather than the C-style for loop, which is now unavailable in the latest versions of Swift (as is i++): func mac(a: [Float], b: [Float]) -> Float { return zip(a, b).map(*).reduce(0, +) } The zip function takes two arrays and makes a single array of tuples, with each tuple containing the nth element from each array. The map function changes each element of the array with a user-supplied function. In this case, the multiplication operator is passed in, which multiplies each pair. The reduce function performs the task of summing each result (starting at 0).
{ "pile_set_name": "StackExchange" }
Q: Are there any underground cities known except those found in Cappadocia? I've recently read the story about the discovery of the underground city of Derinkuyu. Now I'm a bit curious if there are other similar archaeological discoveries: I mean something we could really call a city, a place where many people would be able to live for a long while (at least a month) and deal a "normal" life. My first steps and researches lead me to rather "Modern" underground cities such as Coober Pedy, the Wieliczka Salt Mine, Dìxià Chéng and a couple of malls which have been built in the underground of bigger cities. But what I'm looking for is something that is much older (middle age or earlier). Strictly speaking "City" is somewhat incorrect, but I think it is clear what I mean a refuge which is big and well equipped enough to accommodate a lot of people for a longer duration and where they could still deal a good life. About Derinkuyu they pretended that the people where able to go ahead with their trade, handcraft and even gather their live stock inside this labyrinth. That staying there for a very long time would have effects on ones health is clear. A: There are a few underground cities that I can think of, some may fit your requirements better than others. If you consider tunneling into rocks, then Petra would be a very large city that was built into the cliffs and ground. If you are only considering cities that are entirely under the ground, Naours France has an underground city that was built in an old Roman quarry and occupied in the middle ages. It has enough space to host several thousand people and several churches, wells, bakeries, wine presses, etc... A: Dating in its origins from the 2 millenium BCE and still inhabited by up to 40 million people today: The first type of yaodong were underground dwellings that date back to the 2nd millennium BC, China's Bronze Age, and according to Chinese tradition, the Xia Dynasty. Chinese scholars generally believe that this type of habitat has developed mainly from the Han dynasty (206 BC to 220 AD), along with a progressive improvement of construction techniques to the dynasties Sui (581 to 618) and Tang (618 to 907). But it is during the dynasties Ming (1368 to 1644) and Qing (1644 to 1912) that the pace of construction reached its peak. Source: Wikipedia – Yaodong The number of 40 million is a quote from the Wikipedia page, which relies on: In northern China, an estimated 40 million people currently live in cave homes known as yaodong. As the human population of the entire planet in 8,000 BC was probably only five million, there are eight times as many cavemen now than there were people of any kind then. Source: "Where did Stone Age people live?" in: John Lloyd and John Mitchinson: "The Book of General Ignorance. The Noticeably Stouter Edition", Faber and Faber: Londom, 2010. While the exact number of people living in these kind of structures may be hard to ascertain, the order of magnitude seems to check out: Some 30 million Chinese still live in caves and over a 100 million people reside in houses with one or more walls built in a hillside. Many of the cave and hill dwellings are in the Shanxi, Henan and Gansu provinces. Caves are cool in the summer, warm in the winter and generally utilize land that can not be used for farming. On the down side, they are generally dark and have poor ventilation. Modern caves with improved designs have large windows, skylights and better ventilation. Some larger cave have over 40 rooms. Others are rented out as three-bedroom apartments. Source: Facts and Details: Cave Homes and Ant People in China, that number is apparently based on: Ronald G. Knapp: "Chinese Landscapes The Village as Place", University of Hawaii Press: Honululu, 1992, p25. A "Remarkable aerial pictures reveal China's 'invisible village' where local residents live in subterranean caves - a lifestyle they have kept for 4,000 years" (DailyMail.UK, 5 April 2016) for one conglomeration with 10000 homes: A: Nushabad in Iran was apparently used to avoid Mongol invasions (13th Century), but is perhaps older as artefacts from earlier periods have been found within. It is not clear how long people stayed down there, but there is an extensive ventilation system to allow fresh air within the underground city.
{ "pile_set_name": "StackExchange" }
Q: Text paragraph with fixed ratio within svg I generate dynamic SVG graphics on the fly using JavaScript. For this purpose a paragraph of text should be added into a box with a fixed aspect ratio inside the svg image. The text length may differ between short and also very long text length. As the actual font size is not important for my purpose I use the viewBox attribute to show the whole paragraph within the box. As far as I researched and tested until now, svg does not provide any automatic line breaking functionality, therefore I might use a standard HTML div within a foreignObject to make use of HTML line breaking. Are there any possibilities to get a div with fixed aspect ratio based on its content length? I already managed to get such a div by an ittertive decreasing of width until the ratio more or less fits the purpose. But this solution is rather imprecise and needs to add the div to the DOM before actually inserting it into the svg. Are there any CSS solutions? A: As unfortunately nobody could help to solve this problem, I implemented the following (more or less working) solution: for(var i = 0; i < 200; i++){ if($('#wrapper').width()/$('#wrapper').height() <= 5){ console.log($('#wrapper').width()/$('#wrapper').height()) break; } $('#wrapper').width($('#wrapper').width()*0.8); } for(var y = 0; y < 200; y++){ if($('#wrapper').width()/$('#wrapper').height() >= 4.9){ break; } $('#wrapper').width($('#wrapper').width()*1.02); } This approach tries to itteratively converge the aspect ratio towards an approximately correct ratio. This is by far not an optimal solution, but at least a working one.
{ "pile_set_name": "StackExchange" }
Q: Oracle GROUP BY question I am using Oracle8i Enterprise Edition Release 8.1.7.4.0 - Production. Yes an ancient version but the license is embedded in an application that we use and this is the Oracle version that they use. Here is an SQL query that I am using: SELECT EntryDate, COUNT(OrderNo) FROM Orders GROUP BY EntryDate; I get results like: EntryDate COUNT(OrderNo) --------- -------------- 01-NOV-12 543 02-NOV-12 555 03-NOV-12 91 There are currently 472 rows with dates up to today, so the above is only a small snapshot of results. Is it possible to group the results by month instead of the current date i.e. get results like: EntryDate COUNT(OrderNo) --------- -------------- Nov12 X Dec12 X Jan14 X A: Round to the beginning of the month: SELECT trunc(EntryDate,'MM'), COUNT(OrderNo) FROM Orders GROUP BY trunc(EntryDate,'MM'); In oracle 8i the results are sorted because of the internal algorithm used by the database to do the 'GROUP BY'. In higher Oracle version beginning with 10g a different algorithm is used and the results will not be sorted. So if you want a sorted result you should tell it the database by querying SELECT trunc(EntryDate,'MM'), COUNT(OrderNo) FROM Orders GROUP BY trunc(EntryDate,'MM') ORDER by trunc(EntryDate,'MM'); even if the result will be sorted by accident. To get exactly the output of your query execute the following statement: SELECT to_char(trunc(EntryDate,'MM'),'MonYY'), COUNT(OrderNo) FROM Orders GROUP BY trunc(EntryDate,'MM') ORDER by trunc(EntryDate,'MM');
{ "pile_set_name": "StackExchange" }
Q: Getting MissingRequirementError after moving classes to another package So I was trying to organize my packages a bit better, and after moving some classes to another package my code now gives me this exception: Exception in thread "main" scala.reflect.internal.MissingRequirementError: class Track not found. at scala.reflect.internal.MissingRequirementError$.signal(MissingRequirementError.scala:16) at scala.reflect.internal.MissingRequirementError$.notFound(MissingRequirementError.scala:17) at scala.reflect.internal.Mirrors$RootsBase.ensureClassSymbol(Mirrors.scala:90) at scala.reflect.internal.Mirrors$RootsBase.staticClass(Mirrors.scala:119) at scala.reflect.internal.Mirrors$RootsBase.staticClass(Mirrors.scala:21) at scala.pickling.internal.package$.typeFromString(package.scala:61) at scala.pickling.internal.package$$anonfun$2.apply(package.scala:63) at scala.pickling.internal.package$$anonfun$2.apply(package.scala:63) at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:244) at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:244) at scala.collection.immutable.List.foreach(List.scala:318) at scala.collection.TraversableLike$class.map(TraversableLike.scala:244) at scala.collection.AbstractTraversable.map(Traversable.scala:105) at scala.pickling.internal.package$.typeFromString(package.scala:63) at scala.pickling.FastTypeTag$.apply(FastTags.scala:57) at scala.pickling.json.JSONPickleReader$$anonfun$beginEntry$2.apply(JSONPickleFormat.scala:204) at scala.pickling.json.JSONPickleReader$$anonfun$beginEntry$2.apply(JSONPickleFormat.scala:193) at scala.pickling.PickleTools$class.withHints(Tools.scala:425) at scala.pickling.json.JSONPickleReader.withHints(JSONPickleFormat.scala:159) at scala.pickling.json.JSONPickleReader.beginEntry(JSONPickleFormat.scala:193) at scala.pickling.json.JSONPickleReader.beginEntryNoTag(JSONPickleFormat.scala:192) at BillboardsHot100.deserializeTrackList(Billboards.scala:60) at BillboardsHot100.checkForChanges(Billboards.scala:31) at Main$.main(Main.scala:7) at Main.main(Main.scala) If I leave everything in the same package or declare these classes in the same file, it works fine. Can someone enlighten me on how to fix this? SOLVED: In case has this problem too, the problem was in how Pickling serializes. In the json, there's a field 'tpe' for type, and it changed from "tpe": "Track" to "tpe": "com.new.package.path.Track" which was the new package (not really my package name). Hope this example can help someone else out in the future. A: Maybe you are trying to read some old data that is pickled under the old class name. Obviously this won't work. You need to temporarily serialize it in some alternative way, I think, in order to get around this problem.
{ "pile_set_name": "StackExchange" }
Q: Best approach to disable elements What is the best approach to disable elements such as buttons and form inputs? I am going to use a collection of buttons with different styling (demonstrated in the image below) as a scenario to better explain my question. The old-fashioned way which I used to disable these buttons was to apply the following CSS to every and each one of them. .button.disabled, .button.disabled:hover { color: #fff !important; background-color: #666C80 !important; border: 1px solid rgba(0,0,0,0.2) !important; } .button.button-outlined.disabled, .button.button-outlined.disabled:hover { color: #2B508F; background-color: #fff; border: 1px solid #2B508F; } Obviously, each button has different style rules, which means the .disabled styling rules will have to change every time we change them in the normal style. For example, if I wanted to change the border-radius or add shadow to the button, I will have to apply the default of these to the disabled style section of that button as well. Before asking this question on here, I had a play trying to solve this issue myself by attempting the following approach: /*Disbiled settings*/ .button.disabled, .button.disabled:hover, button.disabled, button.disabled:hover, button:disabled, button:disabled:hover { opacity: 0.7; border: 1px solid inherit !important; -webkit-box-shadow: none !important; -moz-box-shadow: none !important; box-shadow: none !important; } .disabled:after { content: ""; width: 100%; height: 100%; position: absolute; left: 0; top: 0; bottom: 0; right: 0; cursor: not-allowed; pointer-events: normal; } So, when .disabled is applied to the element, an invisible box will be placed above the element and cover it completely using ":after" - just as the code above explains. This method should work as having this invisible box above the element, should disable clicking or hovering the elements behind it, it should simply 'disable' the :hover effect. But it is not! What I am missing? I have put a JSfiddle together here: https://jsfiddle.net/pdnxreyd/1 FYI: 1) The following JS snippet is used to disabled clicking on disabled elements: //Prevent Clicking on .active & disabled links $('.active, .noLink > a, a[href="#"], .disabled, disabled').click(function(e) { e.preventDefault(); }); 2) I really just want to apply opacity: 0.8; and cursors: not-allowed to all .disabled elements. A: It is difficult to understand what you are asking in your question from what I understand there are 2 possible questions you are asking. 1. How to remove touch/click events from the button when it is disabled https://css-tricks.com/almanac/properties/p/pointer-events/ pointer events will disable the click event via css .disabled { ... pointer-events: none; } 2. A generic style that can be applied to all disabled button styles. Simply reducing the opacity of the element may be sufficient to signify that the button is disabled. This will dim the button no matter what styles are applied to it. .disabled { opacity: .4; pointer-events: none; cursor: not-allowed; }
{ "pile_set_name": "StackExchange" }
Q: JavaScript New Date from a 12 hour format date and time string Example string: 2014-12-31 11:59 pm As it stands, JavaScript isn't even parsing the time as the resulting time code returns 12:00 am regardless of what time I provide. Output after new Date("2014-12-31 11:59 pm") results in: 2014-12-31 12:00 am EDIT: Even after expecting a format and manually parsing the string, the new Date() constructor isn't behaving... var sourceTime = "2014-12-31 11:59 pm"; var dateRaw = sourceTime.split(' '); var dateYMD = dateRaw[0].split('-'); var dateTime = dateRaw[1].split(':'); var dateAmPm = dateRaw[2].toLowerCase(); // Adjust human month to system month... dateYMD[1] = (parseInt(dateYMD[1]) - 1).toString(); // Convert 12h to 24h... if(dateAmPm == 'pm') { if(parseInt(dateTime[0]) < 12) dateTime[0] = (parseInt(dateTime[0])+12).toString(); } else { if(parseInt(dateTime[0]) == 12) dateTime[0] = 0; } console.log(dateYMD); console.log(dateTime); var dateParsed = new Date(dateYMD[0], dateYMD[1], dateYMD[2], dateTime[0], dateTime[1]); The console log shows the correct values being passed into new Date() but I'm still getting an incorrect output :( A: Instead of using the standard Date from JavaScript I always use Moment.js when working with dates. It makes is very easy to work with different formats of dates and customizing everything. In your case you could do something like: var datestr = "2014-12-31 11:59 pm"; var date = moment(datestr,"YYYY-MM-DD HH:mm a") $("#log").text(date.format("HH:mm:SS MMM DD YYYY")); Here's a jsfiddle to try it.
{ "pile_set_name": "StackExchange" }
Q: Biographical informations on Igor Ado Ado's Theorem is a very reelvant result in Lie theory (every finite-dimensional Lie algebra is isomorphic to a matrix Lie algebra). I've been, however, unable to find anything more than very basics information on who is the mathematician that proved it. Igor Ado (1910-1983), student of Chebotaryov, graduated in Kazan University in 1935. And basically that's all. Does anyone know of some more related informations? A: In: D.V. Anosov, M.I. Monastyrskii, M.A. Soloviev, Nas ostalos' tak malo... (So few of us remained...), Istoriko-Matematicheskie Issledovaniya 7 (2002), 166-189 (in Russian) (the periodical is available in many places, for example here), Ado is mentioned in passing. It is claimed that Chebotarev failed to create an algebraic school in Kazan' due to bureaucratic/political obstacles; Ado was unable to find a suitable employment in academia, has left pure mathematics (what is apparent from his list of publications), and has switched to numerical mathematics. A: There is the one-page obituary mentioned by Keith Conrad. V. Gubarev and me have uploaded an English translation to the arXiv, see here. Furthermore I have tried to provide a more detailed English wikipedia page for Igor Dmitrievich Ado, see here. I am grateful to Yurii Neretin for providing me with information.
{ "pile_set_name": "StackExchange" }
Q: Standard for implementing GUIs for command line utilities I wrote a command-line utility and I want to develop a GUI for it. I saw that almost every tool on linux comes command-line, and it eventually has a GUI which interacts with the command line utility making life easier for those who aren't familiar with command-line. I want to do something similar, what is the standard in linux to do so? I thought of two possible solutions: Create a GUI that simply spawns command-line utility processes, with some arguments to do the required task and wait for it to finish and update the GUI with the results Implement some kind of server in the command line utility that the GUI can use to gather informations and display them to the user Is there a standard in linux for linking GUIs to command line utilities? If yes, what is it? A: What's most favorably looked upon I think is to actually write SweetApp and libsweetapp together, with the SweetApp commandline application a full-featured but minimalist CLI wrapper around the library. Then, the graphical GSweetApp or KSweetApp uses that lib to build out the GUI application. Beyond that, there is no authoritative standard and ultimately whatever gets the job done for people is all that matters. What I described and both of your possible solutions are all commonplace.
{ "pile_set_name": "StackExchange" }
Q: Table class generated by javascript not working I need to do my homework, it's very simple, everything is right, but just the table class doesn't work.. When it's executed, the table appears, but without the classes characteriscts (like border color, width, etc.). How can I solve this? function Gerar() { if (Entrada.C.value < 0 || Entrada.C.value > 10 || Entrada.L.value < 0 || Entrada.L.value > 10) alert("As colunas e linhas devem ser positivas e menores que 10 (dez)"); else { var C, L, contl = 0, contc = 0; L = Entrada.L.value; C = Entrada.C.value; document.write("<table class='Tabela'>"); for (i = 0; i < L; i++) { document.write("<tr>"); contl += 1; for (j = 0; j < C; j++) { contc += 1; document.write("<td> " + contc + "," + contl + " </td>"); } j = 0; document.write("</tr>"); contc = 0; } document.write("</table>"); } } .Tabela { border-color: blue; border-style: solid; border-width: 4px; } <form id="Entrada"> <table> <tr> <td>Coluna:</td> <td><input type="text" name="C" size="1" /></td> </tr> <tr> <td>Linha:</td> <td><input type="text" name="L" size="1" /></td> </tr> <tr> <td colspan="2" align="center"><input type="button" value="Ok" onclick="Gerar();" /></td> </tr> </table> </form> A: You should use DOM instead of writing tags into strings. So this is a example of a DOM based solution: function createTable(intRows, intColomns) { var objTable = document.createElement("table"); objTable.setAttribute("class", "Tabela") // Here goes your class to make the css work for (var i = 0; i < intRows; i++) { var objRow = document.createElement("tr") for (var j = 0; j < intColomns; j++) { var objColomn = document.createElement("td") objColomn.innerHTML = j + ", " + i; objRow.appendChild(objColomn); } objTable.appendChild(objRow); } document.body.appendChild(objTable); } You should also change the input from "name" to "id" to make them unique Your "Ok" button would than look something like this: <input type="button" value="Ok" onclick="createTable(document.getElementById('L').value, document.getElementById('C').value);" /> If you realy want to keep the document.write() (Which i don't recommend) you can go for a in-line solution: document.write("<table style='border-color: blue; border-style: solid; border-width: 4px;'>"); instead of document.write("<table class='Tabela'>");
{ "pile_set_name": "StackExchange" }
Q: binding a listview to a property of an object in a list of objects I'm a new to C# and I'm practicing my knowledge through WPF.. I'm trying to create an "EmployeeDatabase" public EmployeeDB() { _employeeList.Add(new EmployeeApp1.Employee() { Name = "Hecbert Doval", Email = "[email protected]", Salary = 14000 }); _employeeList.Add(new EmployeeApp1.Employee() { Name = "Harry Pottah", Email = "[email protected]", Salary = 653000 }); _employeeList.Add(new EmployeeApp1.Employee() { Name = "Amino Vikola", Email = "[email protected]", Salary = 230 }); _employeeList.Add(new EmployeeApp1.Employee() { Name = "Mila Spino", Email = "[email protected]", Salary = 30000 }); _employeeList.Add(new EmployeeApp1.Employee() { Name = "Tila Tequila", Email = "[email protected]", Salary = 90700 }); _employeeList.Add(new EmployeeApp1.Employee() { Name = "TheRock Johnson", Email = "[email protected]", Salary = 14500 }); } private List<Employee> _employeeList; that uses a List of "Employee" objects and each of these Employee objects has "Name, Salary, email" as properties. public class Employee { public string Name { get; set; } public string Email { get; set; } public int Salary { get; set; } } Next I created 3 listviews, arranged them to side by side, and each one should receive "Name" "Email" and "Salary" alone. <ListView Name="lvName" Margin="20" Grid.Column="0" /> <ListView Name="lvEmail" Margin="20" Grid.Column="1" /> <ListView Name="lvSalary" Margin="20" Grid.Column="2" /> My question is how can I bind each ListView to the Name / Email/ Salary ? if it's possible.. if not any alternatives to achieve the same result ? Thanks in advance! A: Out of curiosity, why would you want three adjacent listviews, each displaying only one property? By the way, are you implementing INotifyPropertyChanged? You should be. Anyway, this is easy. First, expose _employeeList: private ObservableCollection<Employee> _employeeList = new ObservableCollection<Employee>(); public ObservableCollection<Employee> EmployeeList { get { return _employeeList; } } Then, bind: <ListView ItemsSource="{Binding EmployeeList}" DisplayMemberPath="Name" Name="lvName" Margin="20" Grid.Column="0" /> <ListView ItemsSource="{Binding EmployeeList}" DisplayMemberPath="Email" Name="lvEmail" Margin="20" Grid.Column="1" /> <ListView ItemsSource="{Binding EmployeeList}" DisplayMemberPath="Salary" Name="lvSalary" Margin="20" Grid.Column="2" /> If you'd rather do everything in codebehind, that's trivial to figure out for yourself given what I've shown you.
{ "pile_set_name": "StackExchange" }
Q: Regular expression: cannot start with and exact number of digits I have to match a set of numbers that do not start with "3400" and must exactly be 13 digits. So far this is what I've got: ^(?:(?!3400).)*$ this makes it match with a set of characters that does not start with "3400"; but how do I impose the restriction of 13 digits? A: The ^(?:(?!3400).)*$ pattern matches a string consisting of any chars other than line break chars, 0+ occurrences, that does not contain 3400 substring. What you seek is to match a string consisting of 13 digits only and does not start with some custom digit sequences. Use ^(?!3400])\d{13}$ to match 13 digit string that does not start with 3400. You may further customize the pattern, e.g. to also avoid matching number strings starting with both 3400 and 3401 using ^(?!340[01])\d{13}$ ^^^^ where [01] is a character class matching either 0 or 1. ^(?!3400|3401)\d{13}$ is also possible, but it is best practice that alternatives should not match at the same location (and here, they both match 340), which impacts performance, especially with longer patterns and many more alternatives.
{ "pile_set_name": "StackExchange" }
Q: Python Class: Singleton or Not Singleton by Passing a Value? I have a Python 3 class that is currently a singleton defined using a @singleton decorator, but occasionally it needs to not be a singleton. Question: Is it possible to do something similar to passing a parameter when instantiating an object from the class and this parameter determines whether the class is a singleton or not a singleton? I am trying to find an alternative to duplicating the class and making that not a singleton, but then we will have tons of duplicated code. Foo.py def singleton(cls): instances={} def getinstance(*args, **kwargs): if cls not in instances: instances[cls] = cls(*args, **kwargs) return instances[cls] return getinstance @singleton Class Foo: def hello(self): print('hello world!') FooNotSingleton.py Class FooNotSingleton: def hello(self): print('hello world!') main.py from Foo import Foo from FooNotSingleton import FooNotSingleton foo = Foo() foo.hello() bar = FooNotSingleton() bar.hello() A: You can add some extra handling in your singleton wrapper with a keyword trigger to bypass the non-single instantiations with singleton=False in your class: def singleton(cls): instances={} def getinstance(*args, **kwargs): # thanks to sanyash's suggestion, using a default return instead of try/except singleton = kwargs.pop('singleton', True) if singleton: if cls not in instances: instances[cls] = cls(*args, **kwargs) return instances[cls] else: return cls(*args, **kwargs) return getinstance @singleton class Foo: def __init__(self, val): self.val = val def hello(self): print(f'I have value {self.val}') Test: s1 = Foo('single') s2 = Foo('another single') ns = Foo('not single', singleton=False) s1.hello() # I have value single s2.hello() # I have value single ns.hello() # I have value not single The caveat is you'll want to reserve a keyword that aren't likely to be used to be in any of your decorated class. The benefit is you only need to create the class once without duplication.
{ "pile_set_name": "StackExchange" }
Q: Hangfire dependency injection with .net core How can I use .net core's default dependency injection in Hangfire ? I am new to Hangfire and searching for an example which works with asp.net core. A: See full example on GitHub https://github.com/gonzigonz/HangfireCore-Example. Live site at http://hangfirecore.azurewebsites.net/ Make sure you have the Core version of Hangfire: dotnet add package Hangfire.AspNetCore Configure your IoC by defining a JobActivator. Below is the config for use with the default asp.net core container service: public class HangfireActivator : Hangfire.JobActivator { private readonly IServiceProvider _serviceProvider; public HangfireActivator(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } public override object ActivateJob(Type type) { return _serviceProvider.GetService(type); } } Next register hangfire as a service in the Startup.ConfigureServices method: services.AddHangfire(opt => opt.UseSqlServerStorage("Your Hangfire Connection string")); Configure hangfire in the Startup.Configure method. In relationship to your question, the key is to configure hangfire to use the new HangfireActivator we just defined above. To do so you will have to provide hangfire with the IServiceProvider and this can be achieved by just adding it to the list of parameters for the Configure method. At runtime, DI will providing this service for you: public void Configure( IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider serviceProvider) { ... // Configure hangfire to use the new JobActivator we defined. GlobalConfiguration.Configuration .UseActivator(new HangfireActivator(serviceProvider)); // The rest of the hangfire config as usual. app.UseHangfireServer(); app.UseHangfireDashboard(); } When you enqueue a job, use the registered type which usually is your interface. Don't use a concrete type unless you registered it that way. You must use the type registered with your IoC else Hangfire won't find it. For Example say you've registered the following services: services.AddScoped<DbManager>(); services.AddScoped<IMyService, MyService>(); Then you could enqueue DbManager with an instantiated version of the class: BackgroundJob.Enqueue(() => dbManager.DoSomething()); However you could not do the same with MyService. Enqueuing with an instantiated version would fail because DI would fail as only the interface is registered. In this case you would enqueue like this: BackgroundJob.Enqueue<IMyService>( ms => ms.DoSomething()); A: DoritoBandito's answer is incomplete or deprecated. public class EmailSender { public EmailSender(IDbContext dbContext, IEmailService emailService) { _dbContext = dbContext; _emailService = emailService; } } Register services: services.AddTransient<IDbContext, TestDbContext>(); services.AddTransient<IEmailService, EmailService>(); Enqueue: BackgroundJob.Enqueue<EmailSender>(x => x.Send(13, "Hello!")); Source: http://docs.hangfire.io/en/latest/background-methods/passing-dependencies.html A: As far as I am aware, you can use .net cores dependency injection the same as you would for any other service. You can use a service which contains the jobs to be executed, which can be executed like so var jobId = BackgroundJob.Enqueue(x => x.SomeTask(passParamIfYouWish)); Here is an example of the Job Service class public class JobService : IJobService { private IClientService _clientService; private INodeServices _nodeServices; //Constructor public JobService(IClientService clientService, INodeServices nodeServices) { _clientService = clientService; _nodeServices = nodeServices; } //Some task to execute public async Task SomeTask(Guid subject) { // Do some job here Client client = _clientService.FindUserBySubject(subject); } } And in your projects Startup.cs you can add a dependency as normal services.AddTransient< IClientService, ClientService>(); Not sure this answers your question or not
{ "pile_set_name": "StackExchange" }
Q: unable to connect ios 9.1 device to xcode 7.1 I am trying to run application in a device with iOS 9.1 from xcode 7.1. xcode is keep crashing. I am unable to install the application in any ios 9.1 devices. I have tried 3 different devices and getting the same problem. My code is in objective-c. A: I have uninstalled the xcode and then installed xcode 7.2 again. It solved my issue.
{ "pile_set_name": "StackExchange" }
Q: How do I specify a degree character (U+00B0) in a Label I'm specifying the degree character as '\u00B0', which is the proper unicode code point, but it's showing up as the inverted exclamation point! I put it in a Label. When I run it in the simulator it shows up as the degree character, as it should, but on my Android, it's the inverted exclamation point. I'm doing this on the Mac using IntelliJ. Does anyone else see this? A: Open nbproject/project.properties and edit the source.encoding property to UTF-8 instead of the current default.
{ "pile_set_name": "StackExchange" }
Q: Porque o CakePHP seta o _method igual a PUT ao invés de POST? Atualizei recentemente meu projeto CakePHP para a versão 2.4.5. Desde então, alguns dos meus formulários, estão com o input hidden _method setado como PUT automaticamente. A única maneira de contornar isso, é setando o 'type' => 'POST'. Porém, isso não era precisa antigamente. Não sei se estou fazendo algo errado, ou se é um BUG. Esse é o formulário <?php echo $this->Form->create('User', array('url' => array('action' => 'new_password', $this->request->data['User']['forget_password'], 'admin' => false), 'autocomplete' => 'off')) ?> <?php echo $this->Form->hidden('User.id') ?> <fieldset> <label class="block clearfix"> <span class="block input-icon input-icon-right"> <?php echo $this->Form->password('User.password', array('label' => false, 'div' => false, 'class' => 'form-control', 'placeholder' => 'Digite a nova senha')) ?> <i class="icon-user"></i> </span> </label> <label class="block clearfix"> <span class="block input-icon input-icon-right"> <?php echo $this->Form->password('User.password_confirmation', array('label' => false, 'div' => false, 'class' => 'form-control', 'placeholder' => 'Digite novamente a nova senha')) ?> <i class="icon-user"></i> </span> </label> <div class="space"></div> <div class="clearfix"> <?php echo $this->Form->button('<i class="icon-key"></i> '. __('Enviar'), array('class' => 'width-35 pull-right btn btn-sm btn-success', 'escape' => false)) ?> </div> <div class="space-4"></div> </fieldset> <?php echo $this->Form->end() ?> E essa é a action: /** * new_password method * * @access public * @param String $forget_password * @return void * @since 1.0 * @version 1.0 * @author Patrick Maciel */ public function new_password($forget_password) { $user = $this->User->findByForgetPassword($forget_password); if ($user == false) { $this->Session->setFlash(__('Link inválido'), 'flash/frontend/error'); $this->redirect('/'); } $this->layout = 'login'; if ($this->request->is('post')) { $this->User->set = $this->request->data; if ($this->User->validates(array('fieldList' => array('id', 'forget_password', 'password', 'password_confirmation')))) { // ... } else { // ... } } $user['User']['password'] = null; $this->request->data = $user; } Obs.: Eu não setei o *type do formulário acima, justamente para testar se o mesmo iria ocorrer, e o ocorreu.* A: Pelo que eu vi o que acontece é que se tu tens um registro selecionado ele considera o método PUT como padrão, caso tu não tenha um registro ativo ele coloca como POST. Podemos ver isso aqui: if ($model !== false && $key) { $recordExists = ( isset($this->request->data[$model]) && !empty($this->request->data[$model][$key]) && !is_array($this->request->data[$model][$key]) ); if ($recordExists) { $created = true; $id = $this->request->data[$model][$key]; } } Depois vemos isto: 'type' => ($created && empty($options['action'])) ? 'put' : 'post', Então pelo que entendi se tu utilizar um formulário que seja de criação e que tu não esteja recuperando dados do model ele vai fazer um POST. Fonte: https://github.com/cakephp/cakephp/blob/master/lib/Cake/View/Helper/FormHelper.php
{ "pile_set_name": "StackExchange" }
Q: How to put a redstone block in clock mode? I saw this video by SethBling. (The video is caught up to the moment of my question) He says "Make sure these are in clock mode" what does he mean by clock mode? A: As a note, Sethbling asks you to import the schematic. Anyways... What Sethbling refers to as clock mode is a redstone block that is continually being replaced. As you see in the video, as he destroys the block, it immediately appears again. This is a neat little trick - you can make a redstone clock that signals up to 20 times per second. To do this, have a layout like this: z-- <- [C][R][C] -> z++ Where Cs are the command blocks and R is the redstone block. Open up F3 and make sure that the z coordinate of the right command block > redstone block > left command block. If you want to line it up over a different axis, just change the following codes. Remember - first x, then y, finally z. On the leftmost command block, type this: /fill ~ ~ ~1 ~ ~ ~1 redstone_block On the rightmost: /fill ~ ~ ~-1 ~ ~ ~-1 air Finally, put the redstone block in the middle. Now, it will magically become the fastest clock in Minecraft. (As far as we know.)
{ "pile_set_name": "StackExchange" }
Q: Flexible instances needed? I want to write a Convertible instance for a Haskell type to its C representation It looks like this: instance Convertible Variable (IO (Ptr ())) where Now GHC complains: Illegal instance declaration for `Convertible Variable (IO (Ptr ()))' (All instance types must be of the form (T a1 ... an) where a1 ... an are *distinct type variables*, and each type variable appears at most once in the instance head. Use -XFlexibleInstances if you want to disable this.) In the instance declaration for `Convertible Variable (IO (Ptr ()))' I thought Flexible Instances were needed if you had free types in your instance declaration, but this is not the case. I can get it to compile when adding the right pragma, but can anyone explain why I need this? A: Yes you need flexible instances. Without it, all of your typeclass instance would have to look like instance Foo (Maybe a) where instance Foo (IO a) where instance Foo (Either a b) where If you want to do anything other than TypeConstructor a1 a2 a3 ... (and as have to be type variables) than you need flexible instances. But it's one of the most common language extensions, don't sweat using it.
{ "pile_set_name": "StackExchange" }
Q: JavaScript getElementsByCustomTag('value')? I know getElementsByName('something') that returns the elements with name="something", but I want to return a list of elements where custom="something", how would I do that? A: To answer my own question, it seems it was easier than I thought. elements = document.getElementsByTagName('pre'); for (elem = 0;elem < elements.length;elem++) { element = elements[elem]; if (element.lang != 'php') break; ... } The above happened to work in my situation. :)
{ "pile_set_name": "StackExchange" }
Q: return in try-catch's finally block in java. Is there any good point in this example? I'm not familiar with java and I've been recently looking at some code written by some colleagues that's baffling me. Here's the gist of it: public response newStuff(//random data inside) { try { response or = //gives it a value log.info(or.toString()); return or; } catch ( Exception e) { e.printStackTrace(); } finally { return null; } } Is there really any point in adding a finally block here? Couldn't I just add the return null inside the catch block, which would execute the same behavior, or am I wrong? A: Is there really any point in adding a finally block here? The answer to this is a resounding "no": putting a return statement in the finally block is a very bad idea. I just add the return null inside the catch block, which would execute the same behavior, or am I wrong? It wouldn't match the original behavior, but that's a good thing, because it would fix it. Rather than returning null unconditionally the way the original code does, the code with the return inside the catch block would return null only on errors. In other words, the value returned in the try branch would be returned to the caller unless there is an exception. Moreover, if you add return null after the catch block, you would see the correct effect of returning null on exception. I would go even further, and put a single return in the method, like this: response or = null; try { or = //gives it a value log.info(or.toString()); } catch ( Exception e) { e.printStackTrace(); } return or; A: Actually, no. Finally is (nearly) always run, no matter what the result in the try-catch block; so this block always returns null. Here, look at this example: public class Finally { /** * @param args */ public static void main(String[] args) { System.out.println(finallyTester(true)); System.out.println(finallyTester(false)); } public static String finallyTester(boolean succeed) { try { if(succeed) { return "a"; } else { throw new Exception("b"); } } catch(Exception e) { return "b"; } finally { return "c"; } } } It will print "c" both times. The above mentioned exception to the rule would be if the thread itself is interrupted; e.g. by System.exit(). This is however a rare thing to happen. A: The finally is always executed no matter what, and normally can be used to close sessions, etc. Don't put returns inside a finally block.
{ "pile_set_name": "StackExchange" }
Q: Additional Line in my Chapter I did not notice when the additional unwanted LINE at the upper part appeared. I have changed from Article, Report and Book but in vain. These are my code of chapter I used for the style ( I forgot from where I copied from). FYI, the language is Khmer ( Cambodian) \makeatletter \let\stdchapter\chapter \renewcommand*\chapter{% \@ifstar{\starchapter}{\@dblarg\nostarchapter}} \newcommand*\starchapter[1]{% \stdchapter*{#1} \thispagestyle{fancy} \markboth{\MakeUppercase{#1}}{} } \def\nostarchapter[#1]#2{% \stdchapter[{#1}]{#2} \thispagestyle{fancy} } \makeatother Thanks in advance. A: The problem is due to \thispagestyle{fancy} in \newcommand*\starchapter[1]{% \stdchapter*{#1} \thispagestyle{fancy} \markboth{\MakeUppercase{#1}}{} } or \def\nostarchapter[#1]#2{% \stdchapter[{#1}]{#2} \thispagestyle{fancy} } I think one can remove it and use \pagestyle{plain} for the whole document
{ "pile_set_name": "StackExchange" }
Q: Computing stats on generators in single pass. Python When working with generators you can only pull out items on a single pass. An alternative is to load the generator into an list and do multiple passes but this involves a hit on performance and memory allocation. Can anyone think of a better way of computing the following metrics from a generator in a single pass. Ideally the code computes the count, sum, average, sd, max, min and any other stats you can think of. UPDATE Initial horrid code in this gist. See the gist here: https://gist.github.com/3038746 Using the great suggestions from @larsmans here is the final solution I went with. Using the named tuple really helped. import random from math import sqrt from collections import namedtuple def stat(gen): """Returns the namedtuple Stat as below.""" Stat = namedtuple('Stat', 'total, sum, avg, sd, max, min') it = iter(gen) x0 = next(it) mx = mn = s = x0 s2 = x0*x0 n = 1 for x in it: mx = max(mx, x) mn = min(mn, x) s += x s2 += x*x n += 1 return Stat(n, s, s/n, sqrt(s2/n - s*s/n/n), mx, mn) def random_int_list(size=100, start=0, end=1000): return (random.randrange(start,end,1) for x in xrange(size)) if __name__ == '__main__': r = stat(random_int_list()) print r #Stat(total=100, sum=56295, avg=562, sd=294.82537204250247, max=994, min=10) A: def statistics(it): """Returns number of elements, sum, max, min""" it = iter(it) x0 = next(it) maximum = minimum = total = x0 n = 1 for x in it: maximum = max(maximum, x) minimum = min(minimum, x) total += x n += 1 return n, total, maximum, minimum Add other statistics as you please. Consider using a namedtuple when the number of statistics to compute grows large. If you want to get really fancy, you can build an OO hierarchy of statistics collectors (untested): class Summer(object): def __init__(self, x0=0): self.value = x0 def add(self, x): self.value += x class SquareSummer(Summer): def add(self, x): super(SquareSummer, self).add(x ** 2) class Maxer(object): def __init__(self, x0): self.value = x0 def add(self, x): self.value = max(self.value, x) # example usage: collect([Maxer, Summer], iterable) def collect(collectors, it): it = iter(it) x0 = next(it) collectors = [c(x0) for c in collectors] for x in it: for c in collectors: c.add(x) return [c.value for c in collectors]
{ "pile_set_name": "StackExchange" }
Q: Carrierwave dynamic extension_white_list I have two models (Document & DocumentType). Using carrierwave I want to dynamically restrict the file extensions allowed on the Document based on it's DocumentType (which holds an array of acceptable file extensions). The problem is that extension_white_list seems to get called before the DocumentType gets associated with the Document. Ideas, Thoughts? def create @document = Document.new document_params end A: In your uploader, you can do whatever you need, class, instance methods or fixed data. def extension_white_list # Document.some_class_method # model.some_instance_method # fixed: %w(jpg jpeg gif png) end The issue could stem from the way Rails assigns params: you can't control the order. In this case, split the lines to get the order you desire: @document = Document.new document_params_without_file @document.assign_attributes document_file_params #or a mere @document.file_accessor = document_file_params
{ "pile_set_name": "StackExchange" }
Q: Highcharts: Get stack of series Stacked columns in highcharts have the stacked defined in the series like so (http://www.highcharts.com/demo/column-stacked-and-grouped): series: [{ name: 'John', data: [5, 3, 4, 7, 2], stack: 'male' }, { name: 'Joe', data: [3, 4, 4, 2, 5], stack: 'male' }] But I cannot figure out how to get a reference to the name of the stack from the series. Is there any way to get the stack from the series object? I specificially need it for the tooltip: tooltip: { formatter: function() { return '<b>'+ this.series.stack // is undefines +'</b><br/>'+ this.series.name +': '+ this.y; } }, A: You need to use this.series.options.stack instead. The series.options object contains the options that were set for that series while constructing the chart tooltip: { formatter: function() { return '<b>'+ this.series.options.stack + '</b><br/>'+ this.series.name +': '+ this.y; } } Accessing chart/series options | Highchart & Highstock @ jsFiddle
{ "pile_set_name": "StackExchange" }