text
stringlengths
64
89.7k
meta
dict
Q: Regarding the query speed of dijkstra and A* algorithm I am trying to profile the speed of A* and Dijkstra algorithm. I am using the code available at http://www.boost.org/doc/libs/1_38_0/libs/graph/example/astar-cities.cpp and http://www.boost.org/doc/libs/1_50_0/libs/graph/doc/dijkstra_shortest_paths.html. I tried a simple graph with 500 edges and 300 nodes. I was expecting A* to perform better than Dijkstra since in Dijkstra the shortest distance from the source vertex to every other vertex is found. On the other hand in A* the shortest distance to the goal node is only found. However, profiling showed that Dijkstra performed slightly better than A*. Is it possible or I am missing something? A: Djikstra's algorithm uses a queue while A* uses a priority queue. In general, queues will perform better than priority queues (eg. enqueue/dequeue from a queue using a linked-list or circular-array is O(1), while enqueue/dequeue from a priority queue using a heap is O(log n)). However, again in general, the cases where this small difference causes A* to run slower than Djikstra's tend to be the cases where both algorithms run extremely fast anyways - in small mazes, and mazes with only a small number of paths to consider (such as a zig-zagging maze). In the slower cases (out in the open with few obstacles), A * should run much faster. Since your case has 300-nodes, there's a good chance there's something wrong with your code. Without seeing it, we can't help you any further.
{ "pile_set_name": "StackExchange" }
Q: Trac templating system I am trying to understand the templating system. There is a /templating directory with following README: It is not advised to make local modifications to those files after installation, as they might be lost during the installation of a new Trac version. As an alternative, you can copy the templates you want to modify and place them in the templates/ directory of your Trac environment or in the location specified in the trac.ini file under the [inherit] templates_dir setting (the former having precedence over the latter). This would be nice - I could have templates for my project nicely separated in the same path as my project. But this directory contains only part of the templates and for example ticket templates modification is impossible within this path. So what is the correct way to modify Trac templates? Thanks! A: It is discouraged in general, because local/custom templates take precedence, and this could come in the way, if upstream releases have significant changes. You'll never get warned about a changed template and you'll have to re-base your template customization on-top of each new template. Anyway, start from a fresh template copy from source. Templates are to be found in sub-directories templates of the respective Trac realm (i.e. ticket/templates, versioncontrol/templates, wiki/templates) and put it to all directly into <env>/templates (initially empty) or for reusing them in multiple Trac environments as per your [inherit] configuration. Since Trac-0.11 Trac uses the Genshi template engine. See it's own wiki documentation about the available syntax.
{ "pile_set_name": "StackExchange" }
Q: Horizontal scrolling shadows on top of colored elements I've been wanting to add an horizontal shadow on a table but the current solutions (Lea Verou) use background gradients on the wrapper and the rows on the table have a background color so the effect goes away. I was thinking in adding a pseudo element to be on top but I'm having a hard time to make it as wide as the table and have another wrapper to set the background gradients for the shadows. Here's the current solutions and how it does not work well with elements with a background. <div class="scrollbox"> <ul> <li>Scroll right</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> <li>6</li> <li>7</li> <li>8</li> <li>9</li> <li>10</li> <li>The end!</li> <li>No shadow there.</li> </ul> </div> .scrollbox { overflow: auto; max-width: 400px; max-height: 200px; margin: 50px auto; ul { max-width: 200%; } li { display: table-cell; padding: 1em; border: 1px solid #bebebe } li:nth-child(odd) { color: #fff; background-color: rebeccapurple; } background-image: linear-gradient(to right, white, white), linear-gradient(to right, white, white), linear-gradient(to right, rgba(0,0,0,.25), rgba(255,255,255,0)), linear-gradient(to left, rgba(0,0,0,.25), rgba(255,255,255,0)); background-position: left center, right center, left center, right center; background-repeat: no-repeat; background-color: white; background-size: 20px 100%, 20px 100%, 10px 100%, 10px 100%; background-attachment: local, local, scroll, scroll; } https://codepen.io/ramiro-ruiz/pen/KKPmoaV A: I found a simple solution by just using colors with opacity rgba(0,0,0,.1) I let the wrapper background gradient to pass and keeps the illusion of shadows being on top. Working example: https://codepen.io/ramiro-ruiz/pen/YzKVOGK
{ "pile_set_name": "StackExchange" }
Q: GAE - mail API - dialy limits According to https://developers.google.com/appengine/docs/quotas#Mail a GAE app developed by a third party (anyone of us) and hosted in GA Cloud has a limit of 20.000 messages that can send each day, right ? What if an app has registered 100.000 end-users that accepted to receive a daily email notification ? isnt GAE a platform for this kind of apps ? do we have to find out for another provider ? does the app must use a third-party service like mailchimp api or similar to do this job ? thanks, d.- A: GAE no longer supports sending more than 100 emails and they will not increase your quota using this form request. They are nudging people to SendGrid (why SendGrid specifically in unclear). Its an unfortunate reduction in GAE capabilities.
{ "pile_set_name": "StackExchange" }
Q: Visualforce page URL with embedded login details I know how to provide URL to Salesforce.com instance with embedded login details by using this structure: https://servername.com?pw=qwerty&un=myname%40example.com Now the question is how to provide URL with login details to VF page? Could it be achieved using similar URL structure? My VF page URL is something similar to this: https://servername.com/apex/VF_Page?param=true A: It is possible to do by including a startURL parameter. https://login.salesforce.com/?pw=qwerty&un=myname%40example.com&startURL=%2Fapex%2FVF_Page%3Fparam%3Dtrue
{ "pile_set_name": "StackExchange" }
Q: interactive cd-rom software Could someone please recommend any software that can be used to create interactive CDROMs? we have a possible job whereby an interactive CD ROM with basic animation is required. Company information is to be placed in various "Pages", and if possible some kind of "catalogue system" for a lot of PDFs would be available. Any suggestions? I've seen some existing CD ROM makers but they all look really cheap and unprofessional (like cheesy banners and colours etc) - what would you recommend? Thanks for any input A: it's while since I used it, but Adobe Director (or Macromedia Director as I know it as!) was good. Lots of built in functionality, and also has the 'Lingo' scripting language if you want to do anything clever (and by the looks of things now also supports JavaScript).
{ "pile_set_name": "StackExchange" }
Q: Is there a "right" way for a Jedi to defeat a Sith? Every time someone becomes Sith, they plan to destroy the Jedi by shooting or cutting them all down. Then the Jedi have no choice but to fight back. A battle will inevitably be forced, yet such an inherently aggressive and destructive activity is a slippery slope to the dark side in itself. Look at how the defeat of Sidious and Tyranus are viewed as a requirement to victory, yet both attempts are manipulated to draw Anakin to the dark side. Likewise, Obi-Wan and Yoda trained Luke to defeat the Sith, yet Palpatine manipulated Luke into engaging in battle in order to turn him. Is there a proper approach, as a Jedi, to defeating a Sith in battle with minimal risk of falling to the dark side yourself, without sucking up the hurt and letting them wither the Jedi and the galaxy away while waiting for them to tear their own order apart first, and without appearing like some pacifist coward who always run from battle waiting for a nonviolent solution - like redemption - to present itself? Sometimes, a Jedi just got to fight, you know? How can a light-sider fight prolonged battles or even sustained periods as expected in wartime without compromising their moral position? A: Basing on the Jedi approaches we see in the movies, it seems the Jedi policy in dealing with dangerous enemies, like Siths, is attempting to arrest them, not necessarly engaging in a fight-till-death, but just enough to get them captured. So it seems that Jedi are instructed to use a defensive fight style, instead of a mad rage attack, which would keep them from the anger of trying to kill someone to just engaging enough strenght in battle to imobilize the foe. EPISODE II (Obi-Wan / Anakin vs Dooku) Obi Wan: We move in together - you slowly on the left... Anakin: I'm taking him now! Before Anakin's foolish attack, Obi-wan, as an experienced Jedi, intended to use an slower defensive approach, which he mantained during this battle. The same as Yoda did when entered this same battle. He kept defensive until there was no way but to fight Dooku. EPISODE III (Obi-Wan / Anakin vs Dooku) (again) Palpatine: Good, Anakin, good. Kill him. Kill him now! Anakin: I shouldn't... Palpatine: Do it!! Palpatine: You did well, Anakin. He was too dangerous to be kept alive. Anakin: Yes, but he was an unarmed prisoner. It's not the Jedi way. Anakin's and Obi-Wan's instructions were primarily to arrest Dooku as a prisioner. Although Anakin let himself be carried out by rage, he knew that a Jedi is suppose to use just enough strenght not to kill, but to capture. EPISODE III (Jedi Council meeting) Anakin: A partial message was intercepted in a diplomatic packet from the Chairman of Utapau. Yoda: Act on this, we must. The capture of General Grievous will end this war. Quickly and decisively we should proceed. Again, the main Jedi policy when dealing even with the most dangerous enemies is to arrest, not kill. EPISODE III (Mace Windu (and other Jedi) vs Palpatine) Mace Windu: In the name of the Galactic Senate of the Republic, you are under arrest, Chancellor. Palpatine: Are you threatening me, Master Jedi? Mace Windu: The Senate will decide your fate. Palpatine: I am the Senate! Mace Windu: Not yet! This is the one I believe best example the point. The Jedi approach was aggressive, they went for battle, with their lightsabers engaged. But not to kill, in rage, but to arrest. Here's where I believe there's the balance: Is there a proper approach, as a Jedi, to defeating a Sith in battle with minimal risk of falling to the dark side yourself... without appearing like some pacifist coward who always run from battle waiting for a nonviolent solution...? Yes, a defensive fight, meant to neutralize the opponent, not kill it. A: Yes, the way Obi-Wan defeated Darth Maul, in cool headed, emotionless combat. In both of your examples, Palpatine is there toying with the jedi's emotions. In the Dooku vs. Anakin fight, Palpatine urges Anakin to finish off Dooku. Anakin has a history with Dooku and Palpatine is able to use that to incite hatred in Anakin. In the Luke vs. Vader fight, there are already a lot of emotions going on with the whole father and son final confrontation thing, and Palpatine is there taunting Luke, causing him to have even more. If you look at the fight at the end of Episode I, Obi-wan is able to stay emotionless through most of the fight. When Maul kills Qui-Gon, Obi-wan has a brief flair up of anger, but is able to keep a relatively cool-head and defeat Maul with no risk of turning to the dark side.
{ "pile_set_name": "StackExchange" }
Q: When is the connected sum of manifolds orientation-independent? Given $M$ and $N$, two connected orientable manifolds of the same dimension, when is $M$ # $N$ diffeomorphic to $M$ # $\overline{N}$, where $\overline{N}$ is $N$ with the orientation reversed? If $N$ has an orientation-reversing automorphism, is this a necessary or sufficient condition for $M$#$N$ to be diffeomorphic to $M$#$\overline{N}$? If it isn't a necessary condition, what invariants can be used to distinguish $M$ # $N$ from $M$ # $\overline{N}$? (As a baby example, how does one show that $CP^2$ # $CP^2\ncong CP^2 $#$ \overline{CP ^2}$ ?) Zygund A: What kind of object do you want to consider $M \# N$ to be, an oriented manifold, or unoriented? Presumably you're taking the connect sum up to some kind of equivalence. You'll also need for $M$ and $N$ to be connected if you want connect-sum to be well-defined in any sense. In the oriented sense, $M \# N$ is well-defined up to orientation-preserving diffeomorphism, and contains both the punctured $M$ and the punctured $N$ as oriented submanifolds, so it depends on the orientations of $M$ and $N$ respectively. As an unoriented object taken up to diffeomorphism, a connect-sum is well defined provided either input manifold has an orientation-reversing diffeomorphism. Explicit examples where you can see there is or is not diffeomorphisms between such are connect sums of complex projective spaces (and/or their orientation reverses). There's also examples with $3$-dimensional lens spaces but working out which ones of those admit orientation-reversing diffeomorphisms is more work. All $1$ and $2$-manifolds admit orientation-reversing diffeomorphisms so there's no good examples there. edit: in detail for $\mathbb CP^2$, the intersection form on $H_2(\mathbb CP^2 \# \mathbb CP^2)$ is definite, regardless of what orientation you give the connect-sum. But if you take the connect sum with one factor orientation-reversed $H_2(\mathbb CP^2 \# \overline{\mathbb CP^2})$, the intersection form is indefinite. For $3$-dimensional lens spaces, the torsion linking form is a good analogous invariant. Have you looked at a book like Kosinski's Differential Topology? It covers these kinds of operations on manifolds. If you want a lower-dimensional example that's easier to see, you could take the analogous connect-sum of knots in $S^3$. This is well-defined for oriented knots, but for unoriented knots you only get a well-defined operation when the knots are invertible, which means there's an orientation-preserving diffeo of $S^3$ that preserves the knot and reverses the orientation of the knot. A: In the oriented category it's not true that if $M\#N$ is oriented diffeomorphic to $M\#(-N)$ then $N$ admits an orientation reversing diffeomorphism. I suspect there are easier counterexamples but the following works. Take $M^{4k+3}=S^3\times \mathbb{CP}^{2k}$ with $k\ge 1$. Then there exists an exotic sphere $\Sigma^{4k+3}$ such that $\Sigma$ does not admit an orientation reversing diffeomorphism but $M\#\Sigma$ is oriented diffeomorphic to $M$ (and hence also to $M\#(-\Sigma)$). Note that $M$ obviously admits an orientation reversing diffeomorphism because $S^3$ does. I read about this fact in a paper by Belegradek, Kwasik and Schultz "Codimension two souls and cancellation phenomena". Not sure if this is the earliest reference, perhaps Igor can clarify this - he visits MO regularly. More specifically they show that if $I(M)$ is the inertia group of $M$ (the group of oriented exotic $4k+3$-spheres $\Sigma$ such that the standard homeomorphis $M\#\Sigma\to M$ is homotopic to a diffeomorphism) then $I(S^3\times \mathbb{CP}^{2k})\cap bP_{4(k+1)}$ has index 2 in $bP_{4(k+1)}$ where $bP_{4(k+1)}$ is the group of exotic $(4k+3)$-spheres bounding parallelizable manifolds. It's known that $bP_{4(k+1)}$ is cyclic or order exponentially growing in $k$ so any nontrivial element $\Sigma$ of $I(S^3\times \mathbb{CP}^{2k})\cap bP_{4(k+1)}$ of order different from 2 works.
{ "pile_set_name": "StackExchange" }
Q: Trouble copying bitmapped images to pasteboard in cocoa osx I'm writing an image processing app that that calculates bitmapped images. It displays them in multiple windows and I want to be able to copy images to the pasteboard. Each window has it's own controller (sub class of NSWindowController) and imageView (subclass of NSImageView). My code will successfully copy the image from the most recently displayed window, but gives EXC_BAD_ACCESS (code 1) when I copy from a previously displayed window. The code in the window controller for setting up the bitmapped image is this: -(void) placeImage:(NSRect) theRect{ windowRect = theRect; [[self window] setTitle:windowName]; NSBitmapImageRep* bitmap = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes: iBitmap.getpixdatap() pixelsWide: iBitmap.getwidth() pixelsHigh: iBitmap.getheight() bitsPerSample: 8 samplesPerPixel: 4 hasAlpha: YES isPlanar:NO colorSpaceName:NSCalibratedRGBColorSpace bytesPerRow: 4*iBitmap.getwidth() bitsPerPixel: 32]; NSImage* im = [[NSImage alloc] initWithSize:NSMakeSize(iBitmap.getwidth(), iBitmap.getheight())]; [im addRepresentation:bitmap]; //NSImage* im = [[NSImage alloc] initByReferencingFile:@"./Contents/Resources/curve.jpg"]; NSRect rect = NSMakeRect(0, 0, windowRect.size.width,windowRect.size.height-TITLEBAR_HEIGHT); [imageView setFrame:rect]; [imageView setImageScaling:NSScaleToFit]; [imageView setImage:im]; [imageView display]; } For the copy operation: - (IBAction)copy:sender { NSImage *image = [imageView image]; if (image != nil) { NSPasteboard *pasteboard = [NSPasteboard generalPasteboard]; [pasteboard clearContents]; NSArray *copiedObjects = @[image]; [pasteboard writeObjects:copiedObjects]; } } If I replace the bitmapped image with an image from a jpeg file (commented out line in placeImage above), then the copy is successful for any window. Any suggestions would be appreciated. The stack frames look like this: 0 _platform_memmove$VARIANT$Nehalem 1 vImageCopyBuffer 2 Copy_Convert 3 AnyToAnyBiock 4 vImageConvert_AnyToAny 5 ConvertBytesWithRange 6 _CGimagePiuginWriteTIFF 7 CGimageOestinationFinalize 8 +[NSBitmaplmageRep(NSBitmaplmageFileTypeExtensions) representationOflmageRepslnArray:usingType:properties:] 9 -[NStmage TIFFRepresentationUsingCompression:factot:] 10 -[NSimage pasteboardPropertylistForType:] 11 -[NSPasteboard writeObjects:] 12 -[DataWindowController copy:] 13 -[NSApplication sendAction:to:from:] 14 -[NSMenultem _corePerformAction] 15 -[NSCarbonMenulmpl performActionWithHighlightingForltemAtlndex:] 16 -[NSMenu performKeyEquivalent:] 17 -[NSApplication _handleKeyEquivalent:] 18 -[NSApplication sendEvent:] 19 -[NSApplication run] 20 NSApplicationMain 21 main 22 start A: This is evidently a memory management issue. Helpful information was here: question 16094748 Initializing the bitmap data plane with nil and then copying the data over explicitly seems to solve the problem. -(void) placeImage:(NSRect) theRect{ windowRect = theRect; [[self window] setTitle:windowName]; NSBitmapImageRep* bitmap = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes: nil pixelsWide: iBitmap.getwidth() pixelsHigh: iBitmap.getheight() bitsPerSample: 8 samplesPerPixel: 4 hasAlpha: YES isPlanar:NO colorSpaceName:NSCustomColorSpace bytesPerRow: 4*iBitmap.getwidth() bitsPerPixel: 32]; memcpy([bitmap bitmapData], iBitmap.getpixdata(), iBitmap.getheight()*iBitmap.getwidth()*4); NSImage* im = [[NSImage alloc] initWithSize:NSMakeSize(iBitmap.getwidth(), iBitmap.getheight())]; [im addRepresentation:bitmap]; //NSImage* im = [[NSImage alloc] initByReferencingFile:@"./Contents/Resources/curve.jpg"]; NSRect rect = NSMakeRect(0, 0, windowRect.size.width,windowRect.size.height-TITLEBAR_HEIGHT); [imageView setFrame:rect]; [imageView setImageScaling:NSScaleToFit]; [imageView setImage:im]; [imageView display]; }
{ "pile_set_name": "StackExchange" }
Q: Why does playing the piano give me a pain in the neck? I have a keyboard set up with a proper stool so my arms are held straight out, with music at eye level - almost identical to how I set up my PC for good posture. But while I can use the PC all day with no issues, within 5 minutes of playing the keyboard - I'm just starting - I get stiffness pain at the bottom of my neck, probably one vertebra above the shoulders. Can anyone advise what is causing this and how to adjust? I think my main posture can't be too bad - I'm not hunching or craning my neck - but wondered if perhaps I am 'clenching' somehow? A: I'm a violinist, not a pianist, but it's very common for beginning violin players to have severe pain because they are too tense, especially when they are self taught. I'm going to suggest a few generic techniques to start minimizing tension. When you sit down at the piano, think about how you are sitting. Look for any tension, especially in your neck and shoulders. Close your eyes, and take a few deep, slow breaths to help you relax. Play a note. Not a piece, or even a scale, just a single note. Think about how relaxed you feel playing that note. Think about tension in your back and shoulders. If you find any, slow down again and relax. Now try two notes, or maybe even three or four. But still think about relaxing, not about music. This is what your body should feel like all the time when you play. Now you've got a baseline for how you should feel while playing. So play something simple. Either a short tune you know well, or a scale, or whatever you find easy. Halfway through, stop and think about tension. Did you tense up again? If you did, sit back, relax, and start over, slower. Slowing down makes it easier to play, and easier to think about not getting tense. Another exercise is to practice breathing while playing. A lot of beginners tend to hold their breathe, which just adds stress and tension. So play a scale. Depending on your speed, you may want to breathe in going up, and out going down, or breathe in for 4 notes, out for 4 notes. Just practice breathing in rhythm, and being aware of your breathe. When you are playing music, start thinking about when you breathe in general. Breathing exercises aren't just for singers. In summary: Consciously relax before playing, and check for tension as you play. If you get tense, back off, relax, and slow down. Make sure you breathe. If the tension is caused more by your posture, you may need to find a teacher to help you out, since we can't see how you hold yourself over the net. A teacher could also help with the sort of tension issues I'm talking about here, so if lessons are an option, it would probably be worthwhile, even if only for a short time.
{ "pile_set_name": "StackExchange" }
Q: Get json from request flask Client code: import requests import json url = 'http://127.0.0.1:5050/login' user = "newUser" password = "password" headers = {'content-type': 'application/json'} response = requests.post(url, data={"user": user,"pass": password}, headers = headers) Server code: from flask import Flask, request, make_response app = Flask(__name__) @app.route('/login', methods=['GET','POST']) def login(): if request.method == 'POST': username = request.form.get("user") password = request.form.get("pass") //more code return make_response("",200) if __name__ == "__main__": app.run(host = "127.0.0.1", port = 5050) The problem is that my username and password are always None. I also tried using: content = request.get_json(force = True) password = content['pass'] and request.form['user'] When I print the content I have: < Request 'http://127.0.0.1:5050/login' [POST]> .So I cannot find the json send from the client. EDIT: I did add json.dumps and used request.get_json() and it worked A: You are sending form encoded data, not JSON. Just setting the content-type doesn't turn your request into JSON. Use json= to send JSON data. response = requests.post(url, json={"user": user,"pass": password}) Retrieve the data in Flask with: data = request.get_json() A: I tried executing the same code that you have posted and I was able to fetch values for username and password instead of None.
{ "pile_set_name": "StackExchange" }
Q: Condition For json Array via PHP I'm Parsing This json Array and I Want to Take text Object of answer and Put That in New Column awnser2, and This is one Row of My json Rows, answer 38 and 39 in json Are Same as text But anser 40 Is Descriptive Awnser, I Got Illegal string offset 'text' for Hello Word, How Can I Make a Condition to Have Both of Them in Output? [{"id":"38","answer":[{"option":"3","text":"HIGH"}],"type":"a"}, {"id":"39","answer":[{"option":"3","text":"LOW"}],"type":"b"}, {"id":"40","answer":["Hello Word"],"type":"c"}] This Is My Code: <?php $con=mysqli_connect("localhost","root","","array"); mysqli_set_charset($con,"utf8"); // Check connection if (mysqli_connect_errno()){ echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $sql="SELECT `survey_answers`,us_id FROM `user_survey_start`"; if ($result=mysqli_query($con,$sql)){ while ($row = mysqli_fetch_row($result)){ $json = $row[0]; if(!is_null($json)){ $json = preg_replace('/\r|\n/','\n',trim($json)); $jason_array = json_decode($json,true); $answers = array(); foreach ($jason_array as $data) { if (array_key_exists('answer', $data)) { foreach($data['answer'] as $ans){ $answers[] =$ans['text'] ; } } } if(!empty($answers)) { $answers= implode('',$answers); /// implode yes if you got values } else { $answers = 'Nothing Find'; //blank if not have any values } $sql3="update user_survey_start set awnser2='$answers' where us_id=".$row[1];//run update sql echo $sql3."<br>"; mysqli_query($con,$sql3); } } } mysqli_close($con); ?> I Want to Have text of Awnser: for ....to 39 and Awnser: for 40 , 40 is last awnser A: check key is set or not otherwise assign value foreach ($jason_array as $data) { if (array_key_exists('answer', $data)) { foreach($data['answer'] as $ans){ $answers[] = isset($ans['text']) ? $ans['text'] : $ans; } } }
{ "pile_set_name": "StackExchange" }
Q: How to implement mapping from type to object method call using C++ templates? I'd like to develop (yet another) wrapper for java arrays in JNI code using C++ templates. Main goal is to improve my C++ template programming skills. I compile the code using Android NDK (compiler is Clang 6.0.2) What I've managed to do so far: #include <jni.h> template <typename T> struct TypeToObjectType; template <> struct TypeToObjectType<jbyteArray> { typedef jbyte type; }; template <> struct TypeToObjectType<jintArray> { typedef jint type; }; template <typename javaArrayT, typename nativeT> class Java_array{ JNIEnv *env; jboolean is_copy; jsize array_len; javaArrayT array; typename TypeToObjectType<javaArrayT>::type *array_elements; public: Java_array(JNIEnv *_env, javaArrayT _array) : env(_env) , array(_array) , array_len(-1) { array_elements = env->GetByteArrayElements(array, &is_copy); //TODO: make it resolving automatically to other primitives } ~Java_array() { env->ReleaseByteArrayElements(array, array_elements, JNI_ABORT); } jsize len(){ if (array_len < 0) array_len = env->GetArrayLength(array); return array_len; } operator nativeT* () const { return reinterpret_cast<nativeT*>(array_elements); }; }; This does not work for int[], float[] and other arrays except byte[], since this class calls GetByteArrayElements. I use struct TypeToObjectType to establish mapping jbyteArray -> jbyte, jintArray -> jint. This mapping is missing part java type -> JEnv method calls, that is jbyteArray -> (GetByteArrayElements, ReleaseByteArrayElements), jintArray -> (GetIntArrayElements, ReleaseIntArrayElements)` How can I do it? How can I improve my code using features from C++11, C++14? A: You can add pointer to members to your trait. template <> struct TypeToObjectType<jbyteArray> { typedef jbyte type; static constexpr jbyte * (JNIEnv::* const GetElements)(jbyteArray, jboolean *) = &JNIEnv::GetByteArrayElements; static constexpr void (JNIEnv::* const ReleaseElements)(jbyteArray, jbyte *, decltype(JNI_ABORT)) = &JNIEnv::ReleaseByteArrayElements; }; template <> struct TypeToObjectType<jintArray> { typedef jint type; static constexpr jint * (JNIEnv::* const GetElements)(jintArray, jboolean *) = &JNIEnv::GetIntArrayElements; static constexpr void (JNIEnv::* const ReleaseElements)(jintArray, jint *, decltype(JNI_ABORT)) = &JNIEnv::ReleaseIntArrayElements; }; Which you call through slightly different syntax Java_array(JNIEnv *_env, javaArrayT _array) : env(_env) , array(_array) , array_len(-1) { array_elements = (env->*TypeToObjectType<javaArrayT>::GetElements)(array, &is_copy); } ~Java_array() { (env->*TypeToObjectType<javaArrayT>::ReleaseElements)(array, array_elements, JNI_ABORT); }
{ "pile_set_name": "StackExchange" }
Q: Teaching a student who refuses to learn How to deal with a student who refuses to learn? I've met a few of those over the years as a a private-class math teacher. They don't want to learn anything about the subject. Some of them are just not motivated, some have serious gaps in their past education, such that whatever I'm teaching makes very little sense for them. They offer resistance to being given explanations, as if everything (or most of what) I'm saying is unnecessary and excessive. They are usually only permissive of the solution to problems that are known to be on their school's exams, and prefer step-by-step instructions free from any context/theory/mathematical properties. To give some context: I usually deal with either very young students who have some respect for older people authority (and come to think of it, this still exists), or pre-admittance exam students, who have well accepted the fact that they need to learn the subjects they are being taught. But recently, I've been teaching this college student from a humanities field who needs to pass a class on high-school level mathematics. He's older than I'm used to, and confident he'll never need math in his "real" life. Hence, the problem I've been used to face reached a whole new level. Things I usually do, but aren't working: Instruct the student to show some important result (such as proving Pythagorean theorem), the proof being written by his own hands usually puts a whole new meaning to theorems and formulas. Give application examples about finance (because everyone is usually interested in money). Explain that understanding things makes it easier to remember and harder to forget. Explain that other subjects/classes will require knowledge in mathematics. EDIT There have been a few very good answers, but some of them and a few comments made me realize another point: Yes, I get that I usually can teach only the step-by step solution as a short term solution, this should allow the student to pass the test. The problem I'm struggling right now is that over ten years worth of teachers have used this kludge with this student already. The result is that I'm expected to make a college student be able to solve high-school level problems while being oblivious to elementary school math and refusing to learn it. Think about this: The student needs to pass tests on arithmetic progressions and trigonometry, but forbids you to explain how to simplify fractions or solve first degree equations. A: If you are a private tutor, hired by an undergrad or adult student, or hired by the parents of a student in 6-12 (middle school/high-school), then I'd suggest that when you meet with a "client" as a potential tutor, that you develop a contract with the student and/or parents to make clear your expectations: what is the minimum level of participation/effort that you expect of the student you may agree to tutor? Making this explicit ahead of engagement, then, allows you to determine when the "contract is broken" if such participation and effort does not materialize. The "things you usually do" are spot on. The only thing I would add is working from the beginning, to evaluate each student, inform each tutee (and/or their parents) of how you plan to address their needs, and what you need in return from the students (and/or their parents). Hence the "contract" I suggest. In addition, try as early as possible to build a "team" mentality with the tutee: spend a few minutes, particularly at the start, trying to get to know the students you are tutoring, what they are passionate about (helps with respect to using applications in your tutoring), so you can present yourself as being there to help them accomplish their goals. Offer yourself as a "coach", someone there to help them better their performance. But, explain to them that you can be most helpful to them, and are willing to spend the time and effort to help, but it won't work only they too commit some time and effort (training). Try to convey to your students that making mistakes in NOT a problem: the best of mathematicians make mistakes! Sometimes a formerly unsuccessful student wrt math may appear completely disinterested in math, and like "it doesn't matter at all to them". Most of the time, that attitude has emerged, defensively, after previous shaming, or lack of success in earlier math classes. Instead, many such students focus on and build their self-esteem around being a great athlete, or dancer, or artist, or musician, etc. Sometimes, for pre-college students, they might not be yet able to relate to your efforts wrt #4. Try to show how math can be interesting to them, right now: use football stats, or a book like "How to lie with statistics", or budgeting (similar to your financing example) for something they are currently passionate about (clothes, concerts, a new smartphone, sports equipment, vidio games, dates, etc.). It is clear, from your post, that you care about your work, and want very much to help the students you work with. That's a huge plus for you. But you have the right to negotiate the "terms of engagement, as much as the person paying you has. The best teachers/professors I've ever had the pleasure to work with expected A LOT from students, but their expectations were reasonable, and they also brought to the table patience, dedication, excitement, and encouragement. [Added]: I should also suggest that in the "contracts" you set up with clients, for both your benefit, and the benefit of the student you will potentially tutor, that you write a sentence or two emphasizing that it is possible that there may be no immediate results of your work with the student: Often times, a lot of time has elapsed between when the student was struggling, and when tutoring begins. Hence, immediate results (in homework success or passing a test) after one or two or three teaching-sessions is likely unrealistic. But success in renewed hope and effort from the student is an even more positive outcome for the future success of the student. A: This is not an answer, but an assertion that what you are experiencing is not something new. Here are some quotes from a 1993 article of a Russian (actually, native Estonian) math prof, who moved to the U.S. in the early 1990s, so the problem is at least thirty years old. Some say that the commoditization of universities started from the Reagan times. This quote is not directly related to your student's situation, after all the author's students studied some watered-down version of calculus, not high-school math, still I think the general idea applies. I guess, the blame can be distributed between subpar school math programs, inadequate preparation of school teachers, constant pressure of high-stake tests, as well the students' expectation that good grades by themselves are a measure of success. Bold in quotations is by me. When I had taught in Russia, I was thanked for teaching my students to be humans, to behave reasonably in unusual situations. But I met a lot of resistance from some of my American undergraduate students, especially when I tried to give them something unexpected. On tests they wanted to do practically the same as what they had done before, only with different numerical data. It is a common opinion that the United States of America supports democracy. Democracy always was connected in my mind with good education for all people, and I knew that American thinkers also believed in this connection. Thus, when I came to this country, I expected to have rich opportunities to teach students to think critically, independently, and creatively and to solve non-standard problems without hindrance from authorities. But ... when I started to teach so-called "business calculus" to undergraduates, I got into absolutely new situation. All my ideas about teaching students to think became completely out of place. Never before had I seen so many young people in one place who were so reluctant to meet challenges and to solve original problems. All they wanted were high grades, and they wanted to get them with a conveyor belt regularity. I found out that every technical calculation, which I was used to ignoring, was a considerable obstacle for my students. It took a considerable amount of time for me to understand how poor they were in basic algebraic calculations. ... I had to learn by trial and error, how much of elementary mathematics was taboo in the business calculus course. Not at once I realized that I was lecturing about exponential functions to students who were not required to know about geometrical progressions. ... Another mistake made by me was to include a trigonometrical function in a test problem. I could not imagine that students who take "calculus" were not supposed to know trigonometry, but it was the case. At one of my lectures of business calculus, when asked why I gave problems unlike those in the book, I answered: "Because I want you to know elementary mathematics." I expected to convince students by this answer. In Moscow a university student who was told that he or she did not know elementary mathematics got ashamed and checked into the matter immediately. Elementary mathematics was normally taught to children who looked like children. Now imagine my astonishment when right after my answer an imposing train of well-grown adults stood up and tramped out. They decided (correctly) that they could graduate from the university without knowing elementary mathematics. And that they would easily find a lecturer who would teach them from the text. The basic principle of market economy is that everybody tries to get as much as possible paying as little as possible. Nothing wrong with this when paying for goods. But some students apply the same rule to learning: they seem to think that they BUY grades and PAY for them by learning. And they try to pay as little as possible. The advantages enjoyed by Americans are the results of real competence and real efforts of previous generations, whose heritage is now getting devalued as a results of the bureaucratic character of the education system. And someday ignorant people with degrees and diplomas may want power according to their papers rather than real competence. A: This is how most students perceive math tests. Whether it's fair or not, this is the perception and it is the normal response to a broken math education system. Imagine you are a teenager and your driving test for your full license is in a week. The Department of Motor Vehicles is massively understaffed, so if you fail, you can't book another test for a year. You hire a driving instructor to help you with step-by-step instructions for parallel parking, how to not forget to shoulder-check before changing lanes, etc. But when you go for your driving lesson, you're instead told to learn about the static vs kinetic friction of tires on the road, mechanical engineering principles that underlie the internal combustion engine, and civil engineering theories about traffic. When you resist and ask for step-by-step instructions you know will be on the test, your driving instructor responds: "...the proof [of civil engineering traffic formulae and Newton's Laws of Motion] being written by [your] own hands usually puts a whole new meaning to theorems and formulas." Obviously, you and I know that real math, by definition, requires understanding, while safe driving only requires good physical habits. The student, though, may have experienced nothing but pseudo-math (100% step-by-step instructions) for more than a decade. In their minds, the proof of the irrelevance of abstractions is the fact that they're not tested or incentivized, the same way a driving test excludes conceptual applications of Newtonian physics. Given how prevalent this sad misperception is, one must blame the math education system, years of bad teaching and awful testing. So, keep in mind when you say that you want them to "understand", to know why symbolic mathematical statements are true or false, they may have no idea what you're talking about while facing enormous incentives to just focus on step-by-step instructions. In their minds, every moment you spend on Pythagorean Theorem proof is meaningless, ivory tower gibberish akin to learning the history of petroleum engineering research the day before the only driving test they can book for the next year. The idea that understanding will help them in the long-run is just incredibly foreign and "obviously" false, an irrational leap of faith that requires doing worse on an imminent, high-stakes test. In fact, they may have experienced the opposite of this many times! Some will have tried to seek deep understanding, only to fail (because of prior knowledge gaps), then gotten burned on a test where rote memorization would have earned them a higher grade. Against such entrenched delusion ("Math is just steps and rules!") and terrible incentives ("The math test is just steps and rules!"), it's no surprise that your arguments for deep understanding don't have much effect. I'm not going to BS you and say that I have a great solution for this. I've talked to dozens of teachers, been to countless math education workshops and conferences, read zillions of books and websites, etc. and am unaware of anybody who claims to have solved this problem, especially when one doesn't control how abstract the assessments are. The closest thing to a solution I've come up with is the following toolbox. It often does not work because students are missing years of prior knowledge and the teachers' math tests are such #$@&*, but it's the best I've got. Empathy. Tell them the story of the driving test and do so with great passion and anguish. Tell it better than they could. Earn an Oscar for your storytelling. Ask them if it's a fair comparison of their experience, motives, and incentives. This will massively boost your credibility while making them feel much more understood. (If you don't like the driving analogy, you could also make one up where a consultant insists an employee spend a ton of time on tasks for which the boss does not pay them or promote them for, when the annual review and promotions are in a week.) Safe Grades. At this point, they may be a little more open to things you have to say. Tell them they've been doing grammar exercises while you want to teach them poetry. Ask them what minimal grade they'd need to be earning before being willing to explore other aspects of math. Ask them how hard they're willing to work to achieve that Safe Grade. Deal or No Deal? If that willingness is way beneath what you consider necessary to earn the safe grade, then tell them to find another tutor. You're here posting on Mathematics Educators Stack Exchange, suggesting you are more caring and skillful than average, but that caring and skill is not necessary to help students rote memorize for tests. Tell them to move along. If they are willing to earn that Safe Grade, then giddy up! Get that over with ASAP, then you'll have time to do real math. :) P.S.: Use statistics to convince students that they'll need math. "We're all going to get sick one day. What should you know about medical research? You seem to care about politics. How do you know if policies are working?"
{ "pile_set_name": "StackExchange" }
Q: Python raw_input() string as instance name I'm working on a PhoneBook in python and I have a class from which I want the user to call instances via raw_input. For example class PhoneBook(): def Add(self): print "Name added" def main(): pb = PhoneBook() Input = raw_input() #Here I want to call pb.add() (and in the future other alternatives) #using the string Input. As I want it (but I know doesn't work): pb.Input[0] #provided the user types Add Is it possible to use the string to call pb.Add()? Thanks in advance! A: Use getattr: getattr(pb, Input)() getattr returns the function, and doesn't call it. Hence the extra () at the end. Some other things: You should return "name added" instead of printing it. Leave uppercased-named variables for classes :). Lowercase for functions, etc.
{ "pile_set_name": "StackExchange" }
Q: using find, sed, and xargs to fix filenames from data recovery on a mac Okay, I'm going in circles. I'm using this command find . -print0 -name '*.1.*' | sed -e 'p;s/\.1//' | xargs -0 -n2 mv To try and rename hundreds of files that had ".1." added just before the file extension when they were archived after someone accidentally deleted 200GB worth of data. I'm caught between the mac xargs interpreting spaces in filenames as separate arguments, and not being able to set the delimiter to only newlines, not spaces. I cannot figure out how to have find print the '\0' character as well as newlines between. Any ideas on how to get this to work? I've been searching in circles and it seems simply being on a mac environment is making this more complicated than necessary. Alternatively trying rename command but still having issues find . -name '*.1.*' -type f -exec rename -n 's/\.1//' '{}' \; ANSWER as per @Wildcard below find . -name '*.1.*' -type f -exec sh -c ' for f do suf="${f##*.1}" new="${f%.1.*}$suf" if [ -e "$new" ]; then printf "Cannot move file <%s>\n" "$new" else mv -n "$f" "$new" fi done ' find-sh {} + A: The following should be safe always and should work on a Mac: find . -name '*.1.*' -type f -exec sh -c ' for f do suf="${f##*.1.}" new="${f%.1.*}.$suf" if [ -e "$new" ]; then printf "Cannot move file <%s>\n" "$new" else mv -n "$f" "$new" fi done ' find-sh {} + Note the mv -n exits successfully without renaming the file, if it would overwrite an existing file. You would probably like it reported on. So this does so. Also, in the odd edge case where there is a directory with the target new name, mv would move the file into it without the safety check I added (even with -n). That wouldn't be desirable either. If a file has more than one .1. string in its name, this command will remove the last one only. (Which is probably closer to what was intended than removing the first one would be.) Theoretically you don't need the -n switch at all with the safety check if block, but I left it in to safeguard data in event of race conditions (if some other process creates a target file just before you move a file on top of that name). Most importantly, this won't blow up no matter how bizarre your file names are. Even if they have embedded newlines, single quote characters, asterisks and all sorts of other things. Come to think of it, though, I'm not sure how well bash parameter expansion works on Unicode.
{ "pile_set_name": "StackExchange" }
Q: Why am I getting error for apple-touch-icon-precomposed.png I have created a new rails3 project but I am seeing following logs many times in my server logs. Why I am getting these request and how can I avoid these? Started GET "/apple-touch-icon-precomposed.png" for 192.168.6.2 at 2012-09-18 20:03:53 +0530 ActionController::RoutingError (No route matches [GET] "/apple-touch-icon-precomposed.png"): I haven't given this link anywhere and don't want to render this image anywhere. I am clueless why this resource is being tried to be loaded. A: I guess apple devices make those requests if the device owner adds the site to it. This is the equivalent of the favicon. To resolve, add 2 100×100 png files, save it as apple-touch-icon-precomposed.png and apple-touch-icon.png and upload it to the root directory of the server. After that, the error should be gone. I noticed lots of requests for apple-touch-icon-precomposed.png and apple-touch-icon.png in the logs that tried to load the images from the root directory of the site. I first thought it was a misconfiguration of the mobile theme and plugin, but found out later that Apple devices make those requests if the device owner adds the site to it. Source: Why Webmasters Should Analyze Their 404 Error Log (Mar 2012; by Martin Brinkmann) A: If a user from Safari Web browser (Apple devices) visit your site. The browser tries to fetch the site icon if it is not defined in <head> in the following order: apple-touch-icon-57x57-precomposed.png apple-touch-icon-57x57.png apple-touch-icon-precomposed.png apple-touch-icon.png To resolve this issue either define an icon for safari web browsers or apple devices. Add something like this to head section of your site: <link rel="apple-touch-icon" href="/custom_icon.png"/> If you want to keep <head> clean then upload the icon to root dir of your site with proper name. The default icon size is 57px. You can find more details on iOS developer library. A: If you ended here googling, this is a simple configuration to prevent this error full the web server logs: Apache virtualhost Redirect 404 /apple-touch-icon-precomposed.png <Location /apple-touch-icon-precomposed.png> ErrorDocument 404 "apple-touch-icon-precomposed does not exist" </Location> Nginx server block: location =/apple-touch-icon-precomposed.png { log_not_found off; access_log off; } PS: Is possible you want to add apple-touch-icon.png and favicon.ico too.
{ "pile_set_name": "StackExchange" }
Q: Rails 4 Rspec Capybara: Extracting common test functionality to Ruby module not working I want to extract sign_in out of my feature tests into a Ruby module, consistent with this Thoughtbot article. Feature is not seeing sign_in. What am I doing wrong? Failures: 1) User signs in with valid email and password Failure/Error: sign_in NameError: undefined local variable or method `sign_in' for #<RSpec::ExampleGroups::UserSignsIn:0x0000000238a958> # ./spec/features/sign_in_spec.rb:16:in `block (2 levels) in <top (required)>' # .bundle/binstubs/rspec:16:in `load' # .bundle/binstubs/rspec:16:in `<main>' Finished in 0.17549 seconds (files took 2.77 seconds to load) 1 example, 1 failure spec/features/sign_in_spec.rb require 'rails_helper' feature 'User signs in' do scenario 'with valid email and password' do sign_in expect(page).to have_content 'Signed in successfully' end end spec/support/features/session_helpers.rb module Features module SessionHelpers def sign_in user = create(:user) visit '/' find(:xpath, "//a[@href='/users/sign_in']").click fill_in 'Email', with: user.email fill_in 'Password', with: user.password click_button 'Sign in' end end end spec/support/features.rb RSpec.configure do |config| config.include Features::SessionHelpers, type: :feature end rails_helper.rb ENV['RAILS_ENV'] ||= 'test' require File.expand_path('../../config/environment', __FILE__) abort("The Rails environment is running in production mode!") if Rails.env.production? require 'spec_helper' require 'rspec/rails' require 'pry' require 'faker' require 'devise' require 'email_spec' ActiveRecord::Migration.maintain_test_schema! RSpec.configure do |config| config.include FactoryGirl::Syntax::Methods # Include Factory Girl syntax to simplify calls to factories config.use_transactional_fixtures = true config.include Devise::TestHelpers, type: :controller config.infer_spec_type_from_file_location! config.include(EmailSpec::Helpers) config.include(EmailSpec::Matchers) end spec_helper.rb require 'codeclimate-test-reporter' CodeClimate::TestReporter.start require 'capybara/rspec' require 'capybara/email/rspec' RSpec.configure do |config| config.before(:each) { ActionMailer::Base.deliveries.clear } # uses email_spec gem to clear mail delivereies config.expect_with :rspec do |expectations| expectations.include_chain_clauses_in_custom_matcher_descriptions = true end config.mock_with :rspec do |mocks| mocks.verify_partial_doubles = true end end A: Do you have something in your rails_helper.rb or spec_helper.rb that will cause your helper to be loaded? Change your rails_helper.rb to start with: ENV['RAILS_ENV'] ||= 'test' require File.expand_path('../../config/environment', __FILE__) abort("The Rails environment is running in production mode!") if Rails.env.production? require 'spec_helper' require 'rspec/rails' require 'pry' require 'faker' require 'devise' require 'email_spec' Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f } ActiveRecord::Migration.maintain_test_schema! RSpec.configure do |config| config.include Features::SessionHelpers, type: :feature ... And delete spec/support/features.rb. This will ensure that the order of execution is correct, creating your Helper module (and anything else in your support folder) and then including the helper in RSpec's namespace.
{ "pile_set_name": "StackExchange" }
Q: jqGrid error when setting width using new API I'm using the new API to set the width of my jqGrid like this: $('#grid').jqGrid('setGridWidth', $(window).width() * 0.98); The problem is that in IE7 I'm getting this error: 'p.cellLayout' is null or not an object This only happens in IE7 (IE8, Firefox and Chrome work fine). Has anybody else encounter this problem and fixed it? A: Probably you try to use setGridWidth function on the wrong place. I would recommend you to place this call inside of loadComplete or gridComplete event. UPDATED: I have no IE7, so I can not test this problem. There are parameter cellLayout of jqGrid which has default value 5 and is documented on http://www.trirand.com/jqgridwiki/doku.php?id=wiki:options. This parameter are used inside of setGridWidth function. If is not clear you me why this parameter should be null, but you can verify this before calling of setGridWidth. The construct alert($('#grid')[0].p.cellLayout); will show you this value. You can try to set this value to 5 before calling of setGridWidth, but if you really have this property as null, you have definitively a problem somewhere else. In all situations like your problem it is always good to post a code example in your question, so that other could reproduce your problem. Sometimes you have a real problem not on the place which you describe. So a code example is always very helpful.
{ "pile_set_name": "StackExchange" }
Q: @color/gray “Validates resource references inside Android XML files” I followed the directions on https://www.bignerdranch.com/blog/splash-screens-the-right-way/ to make a splash screen for my app, but in my background_splash.xml file, the code: <item android:drawable="@color/gray"/> returns the message “Validates resource references inside Android XML files”. How do I fix this? Thanks! Update with code: background_splash.xml: <?xml version="1.0" encoding="utf-8"?> <layer-list xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@color/white"/> <item> <bitmap android:gravity="center" android:src="@drawable/splash"/> </item> </layer-list> SplashActivity.java: package PACKAENAME; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; public class SplashActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = new Intent(this, MainActivity.class); startActivity(intent); finish(); } } AndroidManifest.xml: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="PACKAGENAME"> <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".SplashActivity" android:theme="@style/SplashTheme"> </activity> </application> </manifest> A: add value to color in your color.xml like below <color name="grey">#6E6E6E</color>
{ "pile_set_name": "StackExchange" }
Q: Know size of argument in fscanf(fp , "%s" , strr1) char str1[10]; fscanf(fp , "%s", str1); I want to know size of %s before assigning to str1 to avoid crashing in case of huge input data. A: Since this is C++, you don't have to rely on fscanf. We can avoid buffer overflow altogether by using std::istream: std::string readWord(std::istream& input) { std::string word; if(input >> word) { return word; } else { // Handle error } } This will automatically read characters until reaching the first whitespace character is encountered, and it'll automatically allocate memory as needed. A: You can specify the maximum number of characters to read: fscanf(fp, "%9s", str1); This will not write more than 10 chars into str1 including the null terminator. But in C++ you should use streams and strings which are safe in this respect.
{ "pile_set_name": "StackExchange" }
Q: Blood pH at Higher Altitudes My Campbell's Biology Textbook says the following: "For example, when an elk or other mammal moves up into the mountains from sea level, physiological changes that occur over several days facilitate activity at the higher elevations. The lower oxygen concentration in the air stimulates the animal to breathe more rapidly and deeply. It therefore loses more CO2 through exhalation, raising blood pH above its set point. I was wondering if anyone could explain why blood pH increases as your altitude increases? I know that an increase in pH is a sign of less H+ ions in the blood, but what exactly causes you to lose the ions when you're exhaling CO2? Thanks! A: The following chemical equation explains why pH decreases with increased $CO_2$: $CO_2 + H_2O \rightleftharpoons H^+ + HCO^{-3}$ pH changes are the reason why oxygen binds to hemoglobin in you lungs and then dissociates from hemoglobin at other parts in your body where the oxygen is low because cellular respiration turned the oxygen into carbon dioxide. The binding of oxygen to hemoglobin is in turn explained by the Bohr effect.
{ "pile_set_name": "StackExchange" }
Q: -ERR POP3 is available only with SSL or TLS connection enabled Подскажите кто знает. Уже несколько дней мучаюсь с попыткой подключиться к серверу pop.mail.ru по 110 порту. При отправке USER получаю ошибку от сервера: -ERR POP3 is available only with SSL or TLS connection enabled В интернете все примеры не рассчитаны на то, что будет использоваться шифрование SSL или TLS, как подключиться с этим шифрованием? Может статьи какие нибудь есть? Спасибо за ответ. Код: mailclient = new TcpClient("pop.mail.ru", 110); NetworkStream ns = mailclient.GetStream(); StreamReader sr = new StreamReader(ns); StreamWriter sw = new StreamWriter(ns); sw.WriteLine("USER " + "***@mail.ru"); sw.Flush(); A: Нужно использовать SslStream вместе с TcpClient, а затем использовать SslStream для чтения данных, а не TcpClient. Что-то вроде: TcpClient mail = new TcpClient(); SslStream sslStream; int bytes = -1; mail.Connect("pop.mail.ru", 995); sslStream = new SslStream(mail.GetStream()); sslStream.AuthenticateAsClient("pop.mail.ru"); byte[] buffer = new byte[2048]; // Чтение потока, чтобы убедиться, что мы подключены bytes = sslStream.Read(buffer, 0, buffer.Length); Console.WriteLine(Encoding.ASCII.GetString(buffer, 0, bytes)); //Отправить имя пользователя для входа в систему sslStream.Write(Encoding.ASCII.GetBytes("USER USER_EMAIL\r\n")); bytes = sslStream.Read(buffer, 0, buffer.Length); Console.WriteLine(Encoding.ASCII.GetString(buffer, 0, bytes)); //Отправить пароль для входа в систему sslStream.Write(Encoding.ASCII.GetBytes("PASS USER_PASSWORD\r\n")); bytes = sslStream.Read(buffer, 0, buffer.Length); Console.WriteLine(Encoding.ASCII.GetString(buffer, 0, bytes)); //Получить первое письмо sslStream.Write(Encoding.ASCII.GetBytes("RETR 1\r\n")); bytes = sslStream.Read(buffer, 0, buffer.Length); Console.WriteLine(Encoding.ASCII.GetString(buffer, 0, bytes)); Взято отсюда
{ "pile_set_name": "StackExchange" }
Q: read /etc/fstab entries from python Is there a python package that knows how to parse the fstab file? Perhaps similar to getmntent(3) in linux. Admittedly it's not hard to grok that with python (or awk(1), etc.), but I was wondering if that wheel had already been invented. A: A simple Google search would have given you this: https://launchpad.net/python-fstab
{ "pile_set_name": "StackExchange" }
Q: Complex convert html table into xml using xslt I got stuck with making the two options in converting html table into 2 types of xml. I needed to make a xslt to convert Html table like this <html> <categories place="row">1</categories> <dataset place="head">Characteristics</dataset> <table caption="City statistics"> <thead> <tr> <th id="1">Name</th> <th id="2">Population</th> <th id="3">Area</th> <th id="4">Elevation</th> </tr> </thead> <tbody> <tr> <td id="1">Moscow</td> <td id="2">4.7</td> <td id="3">11.54</td> <td id="4">13</td> </tr> <tr> <td id="1">London</td> <td id="2">6</td> <td id="3">15.54</td> <td id="4">15</td> </tr> </tbody> </table> </html> Into xml like this <?xml version="1.0" encoding="UTF-8"?> <chart caption="City statistics" xAxisName="Сharacteristics" yAxisName="Values"> <categories> <category label="Moscow"/> <category label="London"/> </categories> <dataset seriesName="Population"> <set value="4.7"/> <set value="6"/> </dataset> <dataset seriesName="Area"> <set value="11.54"/> <set value="15.54"/> </dataset> <dataset seriesName="Elevation"> <set value="13"/> <set value="15"/> </dataset> </chart> What I tried to do is: <?xml version='1.0' encoding='utf-8' ?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:output method="xml"/> <!-- Default template --> <xsl:template match="/"> <chart caption="" xAxisName="City name" yAxisName="Values"> <xsl:attribute name="caption"> <xsl:value-of select="html/table/@caption"/> </xsl:attribute> <xsl:apply-templates select="html/table/thead"/> <xsl:apply-templates select="html/table/tbody"/> </chart> </xsl:template> <!-- template for the thead = categories container --> <xsl:template match="thead"> <dataset> <xsl:apply-templates select="tr/th[@id &gt; 1]"/> </dataset> </xsl:template> <!-- template for the th = each category --> <xsl:template match="th"> <dataset> <xsl:attribute name="seriesName"> <xsl:value-of select="."/> </xsl:attribute> <!--<xsl:apply-templates select="../../../tbody/tr/td[@id = ../../../thead/tr/th/@id]"/>\ --> <xsl:for-each select="../../../tbody/tr/td[@id=../../../thead/tr/th/@id]"> <set value=""> <xsl:attribute name="value"> <xsl:value-of select="."/> </xsl:attribute> </set> </xsl:for-each> </dataset> </xsl:template> <!-- template for the thead = categories container --> <xsl:template match="tbody"> <categories> <xsl:apply-templates select="tr/td[@id=1]"/> </categories> </xsl:template> <!-- template for the th = each category --> <xsl:template match="td"> <category> <xsl:attribute name="label"> <xsl:value-of select="."/> </xsl:attribute> </category> </xsl:template> <!-- <xsl:template match="td"> <set value=""> <xsl:attribute name="value"> <xsl:value-of select="."/> </xsl:attribute> </set> </xsl:template> --> </xsl:stylesheet> I had an answer for the first condition. And it is at Convert html table into xml using xslt A: try the following stylesheet <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" omit-xml-declaration="yes" indent="yes"/> <xsl:template match="/"> <chart caption="{html/table/@caption}" xAxisName="City name" yAxisName="Values"> <categories> <xsl:for-each select="descendant::td[@id='1']"> <category label="{.}"/> </xsl:for-each> </categories> <xsl:for-each select="descendant::th[@id &gt; 1]"> <xsl:variable name="curr_id" select="@id"/> <dataset seriesName="{.}"> <xsl:for-each select="../../../descendant::td"> <xsl:if test="@id=$curr_id"> <set value="{.}"/> </xsl:if> </xsl:for-each> </dataset> </xsl:for-each> </chart> </xsl:template> </xsl:stylesheet>
{ "pile_set_name": "StackExchange" }
Q: python pandas String to TimeStramps convert ambigous I'm trying to slice a Dataframe using DateTimeIndex, but a got one issue. When the new DataFrame Change Month, he switch the day and the month. Here is my dataframe: Valeur date 2015-01-08 00:00:00 93 2015-01-08 00:10:00 90 2015-01-08 00:20:00 88 2015-01-08 00:30:00 103 2015-01-08 00:40:00 86 2015-01-08 00:50:00 88 2015-01-08 01:00:00 86 2015-01-08 01:10:00 84 2015-01-08 01:20:00 95 2015-01-08 01:30:00 88 2015-01-08 01:40:00 85 2015-01-08 01:50:00 92 ... ... 2016-10-30 22:20:00 98 2016-10-30 22:30:00 94 2016-10-30 22:40:00 94 2016-10-30 22:50:00 103 2016-10-30 23:00:00 92 2016-10-30 23:10:00 85 2016-10-30 23:20:00 98 2016-10-30 23:30:00 96 2016-10-30 23:40:00 95 2016-10-30 23:50:00 101 [65814 rows x 1 columns] Here my two TimeStamps: startingDate : 2015-10-31 23:50:00 lastDate : 2016-10-30 23:50:00 When i slice my df like this : dfconso = dfconso[startingDate:lastDate] i got something like this : Valeur date 2015-10-31 23:50:00 88 2015-01-11 00:00:00 83 2015-01-11 00:10:00 82 2015-01-11 00:20:00 87 2015-01-11 00:30:00 77 2015-01-11 00:40:00 72 2015-01-11 00:50:00 86 2015-01-11 01:00:00 77 2015-01-11 01:10:00 80 ... ... 2016-10-30 23:10:00 85 2016-10-30 23:20:00 98 2016-10-30 23:30:00 96 2016-10-30 23:40:00 95 2016-10-30 23:50:00 101 The problem is the slice start at the good date, but when the DateTimeIndex change month, something wrong append. Pass from 31 October 2015 to 11 January 2015. And i don't understand why.. I try to print the month and day to see and i got that : In: print("Index 0 : month", dfconso.index[0].month, ", day", dfconso.index[0].day) print("Index 1 : month", dfconso.index[1].month, ", day", dfconso.index[1].day) Out: Index 0 : month 10 , day 31 Index 1 : month 1 , day 11 If someone has an idea EDIT : After df.sort_index() my df, i can see the convert of String date to TimeStamps date, didn't work sometimes, and switch Month and Day. Format at String : "31/08/2015 20:00:00" My code to transform from String to TimeStamps: dfconso.index = pd.to_datetime(dfconso.index, infer_datetime_format=True, format="%d/%m/%Y") A: SOLUTION : that was a bad use of pd.to_datetime, i change infer_date_time_format to Dayfirst : dfconso.index = pd.to_datetime(dfconso.index, dayfirst=True) That solve my problem.
{ "pile_set_name": "StackExchange" }
Q: Is Java BitSet thread safe for concurrent readonly operations I have multiple threads in my application accessing a BitSet concurrently. The documentation says: A BitSet is not safe for multithreaded use without external synchronization. It doesn't say if it is not safe for reading or writing. Can anybody explain. A: A BitSet is only safe for read-only operations if there is a "happens before" relationship between the last action that initializes the BitSet and the actions that read it. The simplest way to achieve this is using a final. For example: public class BitsetHolder { private final BitSet b; public BitSetHolder() { b = new BitSet(); // operations to initialize b. } public BitSet getBitSet() { return b; } } This is sufficient to ensure that the BitSet is "safely published". However, if you don't do something like this, there is no guarantee that threads that read the BitSet will see the fully initialized state. Another alternative to explicit synchronization is to use a volatile variable to hold the reference to the BitSet. However, that inserts a memory barrier on each read and write of the variable. Note that the same reasoning applies to all non-thread-safe "effectively immutable" objects; i.e. objects that have mutable state which you don't mutate.
{ "pile_set_name": "StackExchange" }
Q: The 'pwd' command take much time cost after loading a big file(eg:40M) The following test shell code test at: centOS 7 with bash shell; The code contains three phrase; phrase 1, call pwd command; phrase 2, read a big file(cat the file); phrase 3, do the same thing as phrase 1; The phrase 3 time cost is much bigger than phrase 1(eg: 21s vs 7s) But at the MacOS platform, the time cost of phrase 1 and phrase 3 is equal. #!/bin/bash #phrase 1 timeStart1=$(date +%s) for ((ip=1;ip<=10000;ip++)); do nc_result=$(pwd) done timeEnd1=$(date +%s) timeDelta=$((timeEnd1-timeStart1)) echo $timeDelta #phrase 2 fileName='./content.txt' #one big file,eg. a 39M file content=`cat $fileName` #phrase 3 timeStart2=$(date +%s) for ((ip=1;ip<=10000;ip++)); do nc_result=$(pwd) done timeEnd2=$(date +%s) timeDelta2=$((timeEnd2-timeStart2)) echo $timeDelta2 A: Slawomir's answer has a key part of the problem, but without full explanation. The answer to What does it mean 'fork()' will copy address space of original process? on Unix & Linux StackExchange has some good background. A command substitution -- $(...) -- is implemented by fork()ing off a separate copy of your shell, which a command -- in this case pwd -- is executed in. Now, on most UNIXlike systems, fork() is extremely efficient, and doesn't actually copy all your memory until an operation is performed that changes those memory blocks: Each copy keeps the same virtual memory ranges as the original (so its pointers remain valid), but with the MMU configured to throw an error when there's a write to it, so the OS can silently catch that error and allocate separate physical memory for each branch. There's still a cost to setting up the pages configured to be copied to new physical memory when they change, though! Some platforms -- like Cygwin -- have worse / more expensive fork implementations; some (apparently MacOS?) have faster ones; that difference is what you're measuring here. Two takeaways: It's not pwd that's slow, it's $( ). It'd be just as slow with $(true) or any other shell builtin, and considerably slower with any non-builtin command. Don't use $(pwd) at all -- there's no reason to pay that cost to split off a child process to measure its working directory, when you could just ask the parent shell for its working directory directly by using nc_result=$PWD.
{ "pile_set_name": "StackExchange" }
Q: How to close split window / adjacent editor - Xcode 4 I've managed, by playing around with the menus in Xcode 4, to open a window in an adjacent editor (Navigate, open in adjacent editor). Unfortunately, I'm having trouble figuring out how to close that window. How do you do that? A: Cmd+Enter or View -> Standard Editor -> Show Standard Editor A: I fixed this by going to 'view > editor > standard' and this reset the view to the standard one window view. I have yet to figure out why the x in the upper right corner of the new window is grayed out. Not a perfect solution, but a solution. A: There's a close button in the upper right corner of an assistant editor to close the editor. The first assistant editor doesn't have buttons to add and close editors, which can be confusing.
{ "pile_set_name": "StackExchange" }
Q: Classic ASP (VBScript) convert HTML codes to plain text I'm trying to convert HTML Codes like the &#XXXX; (where XXXX is a number) to plain text using classic ASP (VBScript). I'm adding the text to an email which is in plain text format and if I add them as HTML Codes, it just displays the code and doesn't convert them. One fix would be to change the email to be HTML which does fix that problem but then causes other problems for my email which I won't go into. Is there a built in function or a custom function I can use to convert these HTML Codes to plain text? A: What you need is HTML Decode, though unfortunately ASP doesn't include one. This function, found on ASP Nut, and modified heavily by me, should do what you need. I tested it as vbscript running on my local computer and it seemed to work well, even with Unicode symbols in the 1000+ range. Function HTMLDecode(sText) Dim regEx Dim matches Dim match sText = Replace(sText, "&quot;", Chr(34)) sText = Replace(sText, "&lt;" , Chr(60)) sText = Replace(sText, "&gt;" , Chr(62)) sText = Replace(sText, "&amp;" , Chr(38)) sText = Replace(sText, "&nbsp;", Chr(32)) Set regEx= New RegExp With regEx .Pattern = "&#(\d+);" 'Match html unicode escapes .Global = True End With Set matches = regEx.Execute(sText) 'Iterate over matches For Each match in matches 'For each unicode match, replace the whole match, with the ChrW of the digits. sText = Replace(sText, match.Value, ChrW(match.SubMatches(0))) Next HTMLDecode = sText End Function Note: You'll need script version 5.0 installed on your server to use the RegExp object.
{ "pile_set_name": "StackExchange" }
Q: Implicit conversion for matching overloads C++ I have a problem understanding how function overloading works, it boils down to this simple example: class Foo { public: void bar(const bool & val) {} }; void DoFn(std::function<void( Foo*, const wxString&)> fn ) {} if I now call DoFn like so: DoFn( &Foo::bar ); it compiles fine. How is it converting from bool to wxString within the template parameter for std::function? If I change wxString to std::string then it fails to compile as expected. (wxString is a class in wxWidgets, version 2.8) What I really don't understand is how the wxString class is able to declare it can be converted to from a bool. I have tried making a class as follows: class FakeString { public: FakeString(bool) {}; FakeString(const bool &){}; }; and replacing wxString in DoFn with FakeString, but it doesn't compile saying: could not convert '&Foo::bar' from 'void (Foo::*)(const bool&)' to 'std::function<void(Foo*, const FakeString&)>' A: You got the conversion order wrong: It's about converting wxStrging to bool, not in the other direction. class FakeString { public: operator bool() const { return false; } }; wxString has no bool conversion operator, but something similar: an implicit conversion to const char*: class FakeString { public: operator const char*() const { return nullptr; } }; If you built wxWidgets with wxUSE_STL set to 1, the implicit conversions to both narrow and wide C strings are disabled and replaced with implicit conversions to std::string and std::wstring. And these are the wxString methods you are looking for, the pointer conversion operators.
{ "pile_set_name": "StackExchange" }
Q: how can I use UIImageView on full screen in UIViewController? I am developing a software and in it I am making a new file, which is subclass of UIViewController, when I do use UIImageView, then there is little border remaining in it, what should I do so that my image should cover all area around it, my coding of UIImageView in ViewDidLoad is UIImageView* view = [[UIImageView alloc] initWithImage: [UIImage imageNamed: @"frontnew.png"]]; view.frame = CGRectMake(0, 0, 320, 415); [self.view addSubview:view]; now what should I do ???? If I increase height and width then it will increase from two sides, not all ??? A: you should set imageview property as scalltoFit May be it can help you
{ "pile_set_name": "StackExchange" }
Q: Accordion content inside each dropdown option not working I'm trying to create an accordion inside each dropdown, but it's not working properly. The all accordions for each dropdown option displayed in the first dropdown options and if I choose another dropdown option, the accordion is cannot open when clicked it. How to fix this? Here's the link for full snippet $(function() { $('#faqDrodpown').change(function(){ $('.faqs').hide(); $('#' + $(this).val()).show(); }); $('#accordion-faq').find('.accordionfaq-toggle').click(function() { /*Expand or collapse this panel*/ $(this).next().slideToggle('fast'); $(".accordionfaq-content").not($(this).next()).slideUp('fast'); }); }); A: Just changed jquery $('#accordion-faq').find('.accordionfaq-toggle') to $('#accordion-faq .accordionfaq-toggle') and its work fine for me Edit: Changed $('#faqDrodpown').change() function that toggle class hide and added css on that class for hide content and for onload to hide other faq block i added some js code $(function() { $('.faqs').addClass('hide'); $('#' + $('#faqDrodpown').val()).removeClass('hide'); $('#faqDrodpown').change(function(){ $('.faqs').addClass('hide'); $('#' + $(this).val()).removeClass('hide'); }); $('#accordion-faq .accordionfaq-toggle').click(function(){ /*Expand or collapse this panel*/ $(this).next('.accordionfaq-content').slideToggle('fast'); $(".accordionfaq-content").not($(this).next()).slideUp('fast'); }); }); .faq-dropdown { position: relative; display:block; margin-top:0.5em; padding:0; } .faq-dropdown select { width:100%; margin:0; background:none; border: 1px solid transparent; outline: none; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; appearance: none; -webkit-appearance: none; font-size:1.25em; color: #444; padding: .6em 1.9em .5em .8em; line-height:1.3; } .faq-dropdown::after { content: ""; position: absolute; width: 9px; height: 8px; top: 50%; right: 1em; margin-top:-4px; z-index: 2; background: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 12'%3E%3Cpolygon fill='rgb(102,102,102)' points='8,12 0,0 16,0'/%3E%3C/svg%3E") 0 0 no-repeat; pointer-events:none; } /* This hides native dropdown button arrow in IE 10/11+ so it will have the custom appearance, IE 9 and earlier get a native select */ @media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) { .faq-dropdown select::-ms-expand { display: none; } /* Removes the odd blue bg color behind the text in IE 10/11 and sets the text to match the focus style text */ select:focus::-ms-value { background: transparent; color: #222; } } /* Firefox 7+ -- Will let us hide the arrow, but inconsistently (see FF 30 comment below). We've found the simplest way to hide the native styling in FF is to make the select bigger than its container. */ /* The specific FF selector used below successfully overrides the previous rule that turns off the custom icon; other FF hacky selectors we tried, like `*>.dropdown::after`, did not undo the previous rule */ /* Set overflow:hidden on the wrapper to clip the native select's arrow, this clips hte outline too so focus styles are less than ideal in FF */ _::-moz-progress-bar, body:last-child .dropdown { overflow: hidden; } /* Show only the custom icon */ _::-moz-progress-bar, body:last-child .dropdown:after { display: block; } _::-moz-progress-bar, body:last-child .dropdown select { /* increase padding to make room for menu icon */ padding-right: 1.9em; /* `window` appearance with these text-indent and text-overflow values will hide the arrow FF up to v30 */ -moz-appearance: window; text-indent: 0.01px; text-overflow: ""; /* for FF 30+ on Windows 8, we need to make the select a bit longer to hide the native arrow */ width: 110%; } /* At first we tried the following rule to hide the native select arrow in Firefox 30+ in Windows 8, but we'd rather simplify the CSS and widen the select for all versions of FF since this is a recurring issue in that browser */ /* @supports (-moz-appearance:meterbar) and (background-blend-mode:difference,normal) { .dropdown select { width:110%; } } */ /* Firefox 7+ focus style - This works around the issue that -moz-appearance: window kills the normal select focus. Using semi-opaque because outline doesn't handle rounded corners */ _::-moz-progress-bar, body:last-child .dropdown select:focus { outline: 2px solid rgba(180,222,250, .7); } /* Opera - Pre-Blink nix the custom arrow, go with a native select button */ x:-o-prefocus, .dropdown::after { display:none; } /* Hover style */ .faq-dropdown:hover { border:1px solid #888; } /* Focus style */ select:focus { outline:none; box-shadow: 0 0 1px 3px rgba(180,222,250, 1); background-color:transparent; color: #222; border:1px solid #aaa; } /* Firefox focus has odd artifacts around the text, this kills that */ select:-moz-focusring { color: transparent; text-shadow: 0 0 0 #000; } option { font-weight:normal; } /* These are just demo button-y styles, style as you like */ .faq-dropdown-btn { border: 1px solid #bbb; border-radius: .3em; box-shadow: 0 1px 0 1px rgba(0,0,0,.04); background: #f3f3f3; /* Old browsers */ background: -moz-linear-gradient(top, #ffffff 0%, #e5e5e5 100%); /* FF3.6+ */ background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#ffffff), color-stop(100%,#e5e5e5)); /* Chrome,Safari4+ */ background: -webkit-linear-gradient(top, #ffffff 0%,#e5e5e5 100%); /* Chrome10+,Safari5.1+ */ background: -o-linear-gradient(top, #ffffff 0%,#e5e5e5 100%); /* Opera 11.10+ */ background: -ms-linear-gradient(top, #ffffff 0%,#e5e5e5 100%); /* IE10+ */ background: linear-gradient(to bottom, #ffffff 0%,#e5e5e5 100%); /* W3C */ } .output { margin: 0 auto; padding: 1em; } .accordionfaq-toggle { cursor: pointer; font-size: 1.1em; font-weight: 700; text-align: left; border-radius: 3px; padding: 19px 19px 19px 60px; border: 1px solid #CCC; box-shadow: 0 0 5px rgba(0, 0, 0, .19), 0 3px 3px rgba(0, 0, 0, .23); background: #FFF; border-radius: 3px; } .accordionfaq-toggle:active { border-bottom: none; } .accordionfaq-content { display: none; border-radius: 3px; border: 1px solid #CCC; border-top: 0 !important; background: #FFF; box-shadow: 0 0 5px rgba(0, 0, 0, .19), 0 3px 3px rgba(0, 0, 0, .23); margin: -87px 0 19px 0; padding: 4em 3em 3em 4em; } .accordionfaq-content>p { margin-top: 2.5em; } .faqs.hide { display:none; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="faq-dropdown-btn faq-dropdown"> <select id="faqDrodpown"> <option value="red">Red</option> <option value="yellow">Yellow</option> <option value="blue">Blue</option> </select> </div> <div class="output"> <div id="red" class="faqs"> <div id="accordion-faq"> <h4 class="accordionfaq-toggle"><span class="arrow">Lorem ipsum title</span></h4> <div class="accordionfaq-content">Lorem ipsum content</div> </div> </div> <div id="yellow" class="faqs"> <div id="accordion-faq"> <h4 class="accordionfaq-toggle"><span class="arrow">Lorem ipsum title</span></h4> <div class="accordionfaq-content">Lorem ipsum content</div> <h4 class="accordionfaq-toggle"><span class="arrow">Lorem ipsum title</span></h4> <div class="accordionfaq-content">Lorem ipsum content</div> </div> </div> <div id="blue" class="faqs"> <div id="accordion-faq"> <h4 class="accordionfaq-toggle"><span class="arrow">Lorem ipsum title</span></h4> <div class="accordionfaq-content">Lorem ipsum content</div> <h4 class="accordionfaq-toggle"><span class="arrow">Lorem ipsum title</span></h4> <div class="accordionfaq-content">Lorem ipsum content</div> <h4 class="accordionfaq-toggle"><span class="arrow">Lorem ipsum title</span></h4> <div class="accordionfaq-content">Lorem ipsum content</div> </div> </div> </div>
{ "pile_set_name": "StackExchange" }
Q: Using this.setState in the callback of this.setState in React JS? Is it possible to call this.setState in the callback of this.setState? I am making a Roguelike Dungeon and have a setup where in the callback of this.setState a helper function is used, that calls this.setState again. My game freezes at this point. So I have an object in the React component that has a method to generate a random 2D array map: this.Dungeon.Generate(); When the game starts, we call in componentDidMount() the following function in the component: componentDidMount: function() { this.Dungeon.Generate(); this.setState({ board: this.Dungeon.map }, function() { this.generateGamePlay(); }); }, this.generateGamePlay() looks like this and basically generates and places the player, boss and items randomly on the board: generateGamePlay: function() { var board = this.state.board.slice(); var startPosition = this.randomPosition(); board[startPosition[0]][startPosition[1]] = this.state.player; var bossPosition = this.randomPosition(); board[bossPosition[0]][bossPosition[1]] = this.state.boss[this.state.dungeonLevel]; this.generateWeapons(this.state.dungeonLevel,board); this.generateFood(this.state.dungeonLevel, board); this.generateEnemies(this.state.dungeonLevel, board); this.setState({ board: board }); }, But when a player dies, we call above again to reset the game: this.Dungeon.Generate(); //generate a new dungeon map, available in this.Dungeon.map this.setState({ board: this.Dungeon.map, currentMessage: "Game restarted", player: player, weapon: weapon, dungeonLevel: 0 }, function(){ this.generateGamePlay(); }) But then is when my game freezes. So the first time I call this.generateGamePlay() (which calls this.setState) it works but the second time it freezes. Anyone can help me? A: I would look at the part where you are setting this.Dungeon.map in state. this.setState({ board: this.Dungeon.map, currentMessage: "Game restarted", player: player, weapon: weapon, dungeonLevel: 0 }, function(){ this.generateGamePlay(); }) my guess is that something else may be changing the map object and not using setstate since it is a property of the Dungeon. from the react docs Never mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable. when you pass the map property to setstate it will keep a reference to this.Dungeon.map which if you then modify will cause issues. You should make a copy of what ever .map is and pass that to state. You should also make one component in charge of the state instead of calling it multiple times in different functions. From the react docs setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value. There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains. your freezing could be from race conditions in the render method due to all the multiple setstate calls.
{ "pile_set_name": "StackExchange" }
Q: Sinatra / Rack fails with non-ascii characters in url I am getting Encoding::UndefinedConversionError at /find/Wrocław "\xC5" from ASCII-8BIT to UTF-8 For some mysterious reason sinatra is passing the string as ASCII instead of UTF-8 as it should. I have found some kind of ugly workaround... I don't know why Rack assumes the encoding is ASCII-8BIT ... anyway, a way is to use string.force_encoding("UTF-8")... but doing this for all params is tedious A: I was having some similar problems with routing to "/protégés/:id". I posted to the Rack mailing list, but the response wasn't great. The solution I came up with isn't perfect, but it works for most cases. First, create a middleware that unencodes the UTF-8: # in lib/fix_unicode_urls_middleware.rb: require 'cgi' class FixUnicodeUrlsMiddleware ENVIRONMENT_VARIABLES_TO_FIX = [ 'PATH_INFO', 'REQUEST_PATH', 'REQUEST_URI' ] def initialize(app) @app = app end def call(env) ENVIRONMENT_VARIABLES_TO_FIX.each do |var| env[var] = CGI.unescape(env[var]) if env[var] =~ /%[A-Za-z0-9]/ end @app.call(env) end end Then use that middleware in your config/environment.rb (Rails 2.3) or config/application.rb (Rails 3). You'll also have to ensure you've set the right encoding HTTP header: Content-type: text/html; charset=utf-8 You can set that in Rails, in Rack, or in your web server, depending on how many different encodings you use on your site.
{ "pile_set_name": "StackExchange" }
Q: TableView shows duplicate cells on reloading I want to show the data related to a particular date that is selected from the datePicker in the tableView. But, when I reload the tableView it shows duplicate cells. Here is my code sessionViewController.swift import UIKit class sessionViewController: UIViewController{ @IBOutlet weak var dateLabel: UILabel! @IBOutlet weak var datePicker: UIDatePicker! override func viewDidLoad() { super.viewDidLoad() datePicker.datePickerMode = UIDatePickerMode.Date datePicker.addTarget(self, action: Selector("datePickerChanged:"), forControlEvents: UIControlEvents.ValueChanged) let date = NSDate() let formatter = NSDateFormatter() formatter.dateFormat = "M/d/yyyy" let today = formatter.stringFromDate(date) dateLabel.text = today } func datePickerChanged(datePicker:UIDatePicker) { let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "M/d/yyyy" var strDate = dateFormatter.stringFromDate(datePicker.date) dateLabel.text = strDate Singelton.setTutorDate(strDate) NSNotificationCenter.defaultCenter().postNotificationName("load", object: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } sessionTableViewController.swift import UIKit class sessionTableViewController: UITableViewController{ var myData: Array<tutor> = [] var myDummy: Array<String> = [] var date: String! override func viewDidLoad() { super.viewDidLoad() println("\(myData)") NSNotificationCenter.defaultCenter().addObserver(self, selector: "loadList:",name:"load", object: nil) date = Singelton.getTutorDate() myDummy = ["Harsh","Akash","A","B","C","d","e","f","g","h","i","j","k","l","m","n"] let cond = AWSDynamoDBCondition() let v1 = AWSDynamoDBAttributeValue(); v1.S = date cond.comparisonOperator = AWSDynamoDBComparisonOperator.EQ cond.attributeValueList = [ v1 ] let exp = AWSDynamoDBScanExpression() exp.scanFilter = [ "startDate" : cond ] self.scan(exp).continueWithSuccessBlock({ (task: AWSTask!) -> AWSTask! in NSLog("Scan multiple values - success") let results = task.result as! AWSDynamoDBPaginatedOutput for r in results.items { let myItem: secondItem = r as! secondItem let myTutor: tutor = tutor() myTutor.setName(myItem.name) myTutor.seteMail(myItem.email) myTutor.setStartDate(myItem.startDate) myTutor.setStartTime(myItem.startTime) myTutor.setEndTime(myItem.endTime) println(myItem.name) self.myData.append(myTutor) println("\(self.myData)") } dispatch_async(dispatch_get_main_queue(), { self.tableView.reloadData() }); return nil }) } func loadList(notification: NSNotification){ //load data here // myData.removeAll(keepCapacity: false) self.myData.removeAll(keepCapacity: false) self.viewDidLoad() } func scan(expression : AWSDynamoDBScanExpression) -> AWSTask! { let mapper = AWSDynamoDBObjectMapper.defaultDynamoDBObjectMapper() return mapper.scan(secondItem.self, expression: expression) } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Potentially incomplete method implementation. // Return the number of sections. return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete method implementation. // Return the number of rows in the section. return myData.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cellID: String = "cell1" var cell = tableView.dequeueReusableCellWithIdentifier(cellID) as! timeCell // cell.separatorInset = UIEdgeInsetsZero // cell.nameTutor.text = self.myData[indexPath.row].getName() as String cell.nameTutor.text = self.myData[indexPath.row].getName() as String cell.timeLabel.text = self.myData[indexPath.row].getstartDate() as String cell.hourLabel.text = "\(self.myData[indexPath.row].getStartTime())-\(self.myData[indexPath.row].getendTime())" return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let indexPath = tableView.indexPathForSelectedRow(); println("\(indexPath?.row)") } Below are the screenshots. When I change the date from datePicker the tableView gets reloaded but the cell gets duplicated. It would be a great help if someone could suggest me a way out. Thanks } A: You shouldn't ever need to call ViewDidLoad manually. Let the View Lifecycle events be called by the framework. Move your code that populates the myData array into a separate method. Call this method from ViewDidLoad in place of the current logic. Then in your loadData method, call this method again to repopulate your list and reload the table data.
{ "pile_set_name": "StackExchange" }
Q: scala-breeze/spark replace a row of a densematrix with another densevector I have a breeze.linalg.DenseMatrix: breeze.linalg.DenseMatrix[Int] = 1 5 9 2 6 10 3 7 11 4 8 12 and a breeze.linalg.DenseVector: breeze.linalg.DenseVector[Int] = DenseVector(13, 14, 15) Slicing allows me to get a particular row of a DenseMatrix but not replace/reassign it. How can I replace one of the rows(for eg. 2nd row) of the matrix with the vector to get something as shown below? 1 5 9 13 14 15 3 7 11 3 8 12 Also, is there a way to achieve such matrix manipulations using any of Spark's matrix types? If yes, that would be much more desirable. A: Slicing allows me to get a particular row of a DenseMatrix but not replace/reassign It does, you just need a correct shape - row slice is transposed val m = DenseMatrix((1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)) // breeze.linalg.Transpose[breeze.linalg.DenseVector[Int]] = Transpose(DenseVector(10, 11, 12)) so you need matching transposed vector val v = DenseVector(10, 11, 12) m(1, ::) := v.t m // breeze.linalg.DenseMatrix[Int] = // 1 5 9 // 10 11 12 // 3 7 11 // 4 8 12 Also, is there a way to achieve such matrix manipulations using any of Spark's matrix types? If yes, that would be much more desirable. Spark ml.linalg and mllib.linalg are not full featured linear algebra tools and exist mostly to support other ml / mllib functions, so slicing, and modifications are not supported. You'll have to access underlying RDD and transform data manually with joins.
{ "pile_set_name": "StackExchange" }
Q: Installing Xubuntu. Should I use repositories or install directly from the xubuntu disc image? I am considering two options for installing Xubuntu 14.04.1 on my PC. I can install Ubuntu using this disc image, and then use the repositories to install the Xubuntu desktop. The other option is to install Xubuntu using this disc image directly. What are the differences between these two paths to getting the Xubuntu desktop on my PC? What are the pros and cons? A: You're better off with instaling Xubuntu. Althoug they share the same base (Ubuntu), Xubuntu is more clean and you'll get only the packages you need. For example: 1 - Installing Ubuntu and then installing XFCE (Xubuntu), you'll end up with a lot of packages and customizations that you don't want or need. 2 - Installing Xubuntu will get you a clean, strimmed version of Xubuntu, wich is what you need. 3 - There's a team dedicated to Xubuntu that's dedicated to this customized distro, and therefore you will have a space more dedicated for the DE you want. If later you decide do install something else (Gnome, Unity, etc) you still can do it, because Xubuntu is Ubuntu.
{ "pile_set_name": "StackExchange" }
Q: regex get last two paths of directory Given http://host/test/google/oop/a/a I'm trying to retrieve the last two elements seperated by / so I can do $myvar = "a_a";. There could be an ending / or not it needs to work both ways. I have the following working but it's pretty ugly, how else could I do it? $href = preg_split("/[\/]+/", "http://host/test/google/oop/a/a"); $myvar = $href[count($href)-3] . "_" . $href[count($href)-2]; A: I'd argue that your current method is good - it's succinct, makes sense, and not over-complicated. If you wanted to use regex you could try regex (@ is the delimiter instead of /, it makes escaping a little simpler): @/([^/]+)/([^/]+)/?$@ And groups \1_\2 would be your $myvar. The regex looks for the bit of your string that starts from a / and has exactly 1 more / in the string (unless there is a / at the end of the string with no following text, in which case you can have one extra). (Note the '$' in the regex meaning "end of string"). A: Alternatively you could do it this way: <?php $link = 'http://host/test/google/oop/a/a'; $linkParts=explode('/',rtrim($link,'/')); $count=count($linkParts); $desired = $linkParts[$count-2].'_'.$linkParts[$count-1]; echo $desired; //a_a ?>
{ "pile_set_name": "StackExchange" }
Q: action for oncreateoptionsmenu using the following i get the menu. but how to make any action when the menu is selected can anyone help me out. thanks in advance. public boolean OnCreateOptionsMenu(Menu menu){ menu.add(1, 200, 0, "snapshot"); menu.add("more"); menu.add("exit"); return super.onCreateOptionsMenu(menu); } is it possible to make the action using the following. but the layout doesnt load while using the following public boolean OnOptionsItemsSelected(MenuItem item){ switch(item.getItemId()){ case 200: setContentView(R.layout.main2); return true; } return super.onOptionsItemSelected(item); } A: Step #1: Rename OnCreateOptionsMenu() to onCreateOptionsMenu(), as Java is case-sensitive. Step #2: Rename OnOptionsItemsSelected() to onOptionsItemSelected(), as Java is case-sensitive.
{ "pile_set_name": "StackExchange" }
Q: How to install archived R packages on windows machine? I am trying to install the archived R packages from these websites: https://cran.r-project.org/src/contrib/Archive/sentiment/ https://cran.r-project.org/src/contrib/Archive/Rstem/ However, I cannot get it to work for around 2 hours now! I have been using a variety of different approaches including installing them manually, nothing worked :( Do you know a trick for that? A: There are several ways you can try to install archived packages. Using the devtools package. require(devtools) install_version("sentiment", version = "0.2", repos = "http://cran.r-project.org") install_version("Rstem", version = "0.4.1", repos = "http://cran.r-project.org") Installing from source in R sentimenturl <- "https://cran.r-project.org/src/contrib/Archive/sentiment/sentiment_0.2.tar.gz" rstemurl <- "https://cran.r-project.org/src/contrib/Archive/Rstem/Rstem_0.4-1.tar.gz" install.packages(sentimenturl, repos=NULL, type="source") install.packages(rstemurl, repos=NULL, type="source") Installing from source from the command line wget https://cran.r-project.org/src/contrib/Archive/sentiment/sentiment_0.2.tar.gz R CMD INSTALL sentiment_0.2.tar.gz wget https://cran.r-project.org/src/contrib/Archive/Rstem/Rstem_0.4-1.tar.gz R CMD INSTALL Rstem_0.4-1.tar.gz For a Windows machine you will most likely need to have Rtools installed. You can follow the installation steps here: https://github.com/stan-dev/rstan/wiki/Install-Rtools-for-Windows Credit: https://support.rstudio.com/hc/en-us/articles/219949047-Installing-older-versions-of-packages Hope that helps!
{ "pile_set_name": "StackExchange" }
Q: AVCapture capturing and getting framebuffer at 60 fps in iOS 7 I'm developping an app which requires capturing framebuffer at as much fps as possible. I've already figured out how to force iphone to capture at 60 fps but - (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection method is being called only 15 times a second, which means that iPhone downgrades capture output to 15 fps. Has anybody faced such problem? Is there any possibility to increase capturing frame rate? Update my code: camera = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo]; if([camera isTorchModeSupported:AVCaptureTorchModeOn]) { [camera lockForConfiguration:nil]; camera.torchMode=AVCaptureTorchModeOn; [camera unlockForConfiguration]; } [self configureCameraForHighestFrameRate:camera]; // Create a AVCaptureInput with the camera device NSError *error=nil; AVCaptureInput* cameraInput = [[AVCaptureDeviceInput alloc] initWithDevice:camera error:&error]; if (cameraInput == nil) { NSLog(@"Error to create camera capture:%@",error); } // Set the output AVCaptureVideoDataOutput* videoOutput = [[AVCaptureVideoDataOutput alloc] init]; // create a queue to run the capture on dispatch_queue_t captureQueue=dispatch_queue_create("captureQueue", NULL); // setup our delegate [videoOutput setSampleBufferDelegate:self queue:captureQueue]; // configure the pixel format videoOutput.videoSettings = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithUnsignedInt:kCVPixelFormatType_32BGRA], (id)kCVPixelBufferPixelFormatTypeKey, nil]; // Add the input and output [captureSession addInput:cameraInput]; [captureSession addOutput:videoOutput]; I took configureCameraForHighestFrameRate method here https://developer.apple.com/library/mac/documentation/AVFoundation/Reference/AVCaptureDevice_Class/Reference/Reference.html A: I am getting samples at 60 fps on the iPhone 5 and 120 fps on the iPhone 5s, both when doing real time motion detection in captureOutput and when saving the frames to a video using AVAssetWriter. You have to set thew AVCaptureSession to a format that supports 60 fps: AVsession = [[AVCaptureSession alloc] init]; AVCaptureDevice *videoDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo]; AVCaptureDeviceInput *capInput = [AVCaptureDeviceInput deviceInputWithDevice:videoDevice error:&error]; if (capInput) [AVsession addInput:capInput]; for(AVCaptureDeviceFormat *vFormat in [videoDevice formats] ) { CMFormatDescriptionRef description= vFormat.formatDescription; float maxrate=((AVFrameRateRange*)[vFormat.videoSupportedFrameRateRanges objectAtIndex:0]).maxFrameRate; if(maxrate>59 && CMFormatDescriptionGetMediaSubType(description)==kCVPixelFormatType_420YpCbCr8BiPlanarFullRange) { if ( YES == [videoDevice lockForConfiguration:NULL] ) { videoDevice.activeFormat = vFormat; [videoDevice setActiveVideoMinFrameDuration:CMTimeMake(10,600)]; [videoDevice setActiveVideoMaxFrameDuration:CMTimeMake(10,600)]; [videoDevice unlockForConfiguration]; NSLog(@"formats %@ %@ %@",vFormat.mediaType,vFormat.formatDescription,vFormat.videoSupportedFrameRateRanges); } } } prevLayer = [AVCaptureVideoPreviewLayer layerWithSession: AVsession]; prevLayer.videoGravity = AVLayerVideoGravityResizeAspectFill; [self.view.layer addSublayer: prevLayer]; AVCaptureVideoDataOutput *videoOut = [[AVCaptureVideoDataOutput alloc] init]; dispatch_queue_t videoQueue = dispatch_queue_create("videoQueue", NULL); [videoOut setSampleBufferDelegate:self queue:videoQueue]; videoOut.videoSettings = @{(id)kCVPixelBufferPixelFormatTypeKey: @(kCVPixelFormatType_32BGRA)}; videoOut.alwaysDiscardsLateVideoFrames=YES; if (videoOut) { [AVsession addOutput:videoOut]; videoConnection = [videoOut connectionWithMediaType:AVMediaTypeVideo]; } Two other comment if you want to write to a file using AVAssetWriter. Don't use the pixelAdaptor, just ad the samples with [videoWriterInput appendSampleBuffer:sampleBuffer] Secondly when setting up the assetwriter use [AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeVideo outputSettings:videoSettings sourceFormatHint:formatDescription]; The sourceFormatHint makes a difference in writing speed. A: I have developed the same function for Swift 2.0. I post here the code for who could need it: // Set your desired frame rate func setupCamera(maxFpsDesired: Double = 120) { var captureSession = AVCaptureSession() captureSession.sessionPreset = AVCaptureSessionPreset1920x1080 let backCamera = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo) do{ let input = try AVCaptureDeviceInput(device: backCamera) captureSession.addInput(input) } catch { print("Error: can't access camera") return } do { var finalFormat = AVCaptureDeviceFormat() var maxFps: Double = 0 for vFormat in backCamera!.formats { var ranges = vFormat.videoSupportedFrameRateRanges as! [AVFrameRateRange] let frameRates = ranges[0] /* "frameRates.maxFrameRate >= maxFps" select the video format desired with the highest resolution available, because the camera formats are ordered; else "frameRates.maxFrameRate > maxFps" select the first format available with the desired fps */ if frameRates.maxFrameRate >= maxFps && frameRates.maxFrameRate <= maxFpsDesired { maxFps = frameRates.maxFrameRate finalFormat = vFormat as! AVCaptureDeviceFormat } } if maxFps != 0 { let timeValue = Int64(1200.0 / maxFps) let timeScale: Int64 = 1200 try backCamera!.lockForConfiguration() backCamera!.activeFormat = finalFormat backCamera!.activeVideoMinFrameDuration = CMTimeMake(timeValue, timeScale) backCamera!.activeVideoMaxFrameDuration = CMTimeMake(timeValue, timeScale) backCamera!.focusMode = AVCaptureFocusMode.AutoFocus backCamera!.unlockForConfiguration() } } catch { print("Something was wrong") } let videoOutput = AVCaptureVideoDataOutput() videoOutput.alwaysDiscardsLateVideoFrames = true videoOutput.videoSettings = NSDictionary(object: Int(kCVPixelFormatType_32BGRA), forKey: kCVPixelBufferPixelFormatTypeKey as String) as [NSObject : AnyObject] videoOutput.setSampleBufferDelegate(self, queue: dispatch_queue_create("sample buffer delegate", DISPATCH_QUEUE_SERIAL)) if captureSession.canAddOutput(videoOutput){ captureSession.addOutput(videoOutput) } let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) view.layer.addSublayer(previewLayer) previewLayer.transform = CATransform3DMakeRotation(-1.5708, 0, 0, 1); previewLayer.frame = self.view.bounds previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill; self.view.layer.addSublayer(previewLayer) captureSession.startRunning() } A: Had the same problem. Fixed by using this function after [AVCaptureSession addInput:cameraDeviceInput]. Somehow I could not change the framerate on my iPad pro before capture session was started. So at first I changed video format after the device was added to the capture session. - (void)switchFormatWithDesiredFPS:(CGFloat)desiredFPS { BOOL isRunning = _captureSession.isRunning; if (isRunning) [_captureSession stopRunning]; AVCaptureDevice *videoDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo]; AVCaptureDeviceFormat *selectedFormat = nil; int32_t maxWidth = 0; AVFrameRateRange *frameRateRange = nil; for (AVCaptureDeviceFormat *format in [videoDevice formats]) { for (AVFrameRateRange *range in format.videoSupportedFrameRateRanges) { CMFormatDescriptionRef desc = format.formatDescription; CMVideoDimensions dimensions = CMVideoFormatDescriptionGetDimensions(desc); int32_t width = dimensions.width; if (range.minFrameRate <= desiredFPS && desiredFPS <= range.maxFrameRate && width >= maxWidth) { selectedFormat = format; frameRateRange = range; maxWidth = width; } } } if (selectedFormat) { if ([videoDevice lockForConfiguration:nil]) { NSLog(@"selected format:%@", selectedFormat); videoDevice.activeFormat = selectedFormat; videoDevice.activeVideoMinFrameDuration = CMTimeMake(1, (int32_t)desiredFPS); videoDevice.activeVideoMaxFrameDuration = CMTimeMake(1, (int32_t)desiredFPS); [videoDevice unlockForConfiguration]; } } if (isRunning) [_captureSession startRunning]; }
{ "pile_set_name": "StackExchange" }
Q: Netbeans 6.9 startup error javax.xml.transform.TransformerException:java.lang.NullPointerException I have Netbeans 6.9 installed. Suddenly it doesn't start. It gives me an error.. javax.xml.transform.TransformerException:javax.xml.transform.TransformerException:java.lang.NullPointerException This is just one line error, occurs when creating a new project.. at the time when I select frameworks on which I want to make my project... Please help to get me out of this error.. I have searched a lot of time.. but no luck... Any help will be appreciated..Thank you. A: I have already installed Jdk 7 .. then now I went back to JDK6.. then installed netbeans 6.9 again.. now Everything works perfect !! Don't know where the problem is?? But now its gone.
{ "pile_set_name": "StackExchange" }
Q: Silverlight in ASP.NET Duplicate: How do I use Silverlight from ASP.NET? How do I add some Silverlight content to an already created ASP.NET website? A: Add a new Silverlight application to your existing solution. Here's an MSDN article which shows how to integrate it with your existing website, so building the Silverlight application will deploy the Silverlight control to your ASP.NET website's Client_Bin folder. To add a Silverlight control to a webpage in your site, you can reference the Silverlight test page that's automatically created for you, or you can use the ASP:Silverlight control, which will take care of loading the Silverlight object.
{ "pile_set_name": "StackExchange" }
Q: Find $x\in R$ such that undermentioned numbers create geometric sequence: $\cos(x), \sin(x), \tan(x)$. Find $x \in R$ such that undermentioned numbers create geometric sequence: $\cos(x), \sin(x), \tan(x)$. I know that $D:x \neq \frac{\pi}{2} + k\pi, k \in Z$. I could get the result solving this equation: $\frac{\sin(x)}{\cos(x)} = \frac{\tan(x)}{\sin(x)}$ but I'm not sure if I can do this because I don't know if $\sin(x) = 0$ or not. Or maybe I should do this for two cases? EDIT: Is this method correct? As we can see in @Rory Daulton post we have: $\sin{x} = r\cos{x}, \tan{x} = r\sin{x}$. We can transform the first equation to the form: $r = \frac{\sin{x}}{\cos{x}} = \tan{x}$ (because due to the domain, $\cos{x} \neq 0$). So now we can transform the second equation to the form: $\tan{x} = \tan{x}\sin{x} \iff \tan{x}(\sin{x} - 1) = 0 \iff \tan{x} = 0 \vee \sin{x} = 1$. A: SHORT ANSWER: Yes, you can use cases, but you should use three cases. The first case is $\sin x=0$, the second is $\cos x=0$ (since that is also a denominator in your equation), and the third is your equation $\frac{\sin(x)}{\cos(x)} = \frac{\tan(x)}{\sin(x)}$. Solve those equations and check for extraneous solutions. LONGER ANSWER: It is possible to avoid divisions in our solution method. In a geometric sequence of three elements we have $a_2=ra_1,\ a_3=ra_2$. So from your requirements we get $$\sin x=r\cos x, \quad \tan x=r\sin x$$ Reversing the second equation and multiplying the two equations together we get $$r\sin^2 x=r\tan x\cos x$$ Using $\tan x=\frac{\sin x}{\cos x}$, moving everything to the left, and factoring, we get $$r\sin x (\sin x-1)=0$$ From that we get three cases: $r=0$ From the starting equations we get $\sin x=0,\ \tan x=0$. These have the same solutions $x=k\pi,\ k\in\Bbb Z$. Checking these answers we get the sequence $$\pm 1,\ 0, 0$$ which is indeed a geometric sequence, with initial value $-1$ or $1$ and common ratio $0$. $\sin x=0$. This gives us the same solutions as case 1. $\sin x-1=0$. This has the solutions $x=2k\pi+\frac{\pi}2$. When we try check these answers we get the sequence $$0,\ 1,\ \text{undefined}$$ which is not a geometric sequence for multiple reasons. So these answers are extraneous. So the final answer is $x=k\pi,\ k\in\Bbb Z$
{ "pile_set_name": "StackExchange" }
Q: Clustering text file into segments I have a big text file (over 5 GB) of log files from some network devices. The log consists of outputs from these devices after performing many different commands on them. However outputs are not labeled or seperated in any way. When one output ends next starts, often without even a new empty line between. What I want to do is to scan through this text file and at least make these commands seperated somehow. I thought about using some kind of clustering but I didn't use much of unsupervised learning. What could you recommend to deal with this task? A: An unsupervised approach such as clustering cannot work. Because it does not know what you want to separate by. You have a very specific spearation in mind, making his a supervised problem (just that you have not labeled data yet). If you want the algorithm to separate the data in the way you want it, then you'll have to label some training data and use a supervised approach.
{ "pile_set_name": "StackExchange" }
Q: Nightmare.js not working as expected on Ubuntu Linux cloud server I can't seem to get nightmare.js to work on an Ubuntu Linux 14.04 server [via DigitalOcean]. I've installed PhantomJS (1.9.8) and Node (4.2.4), and they are working well as far as I can tell. For example, when I run this: phantomjs loadspeed.js http://www.yahoo.com with loadspeed.js containing this: "use strict"; var page = require('webpage').create(), system = require('system'), t, address; if (system.args.length === 1) { console.log('Usage: loadspeed.js <some URL>'); phantom.exit(1); } else { t = Date.now(); address = system.args[1]; page.open(address, function (status) { if (status !== 'success') { console.log('FAIL to load the address'); } else { t = Date.now() - t; console.log('Page title is ' + page.evaluate(function () { return document.title; })); console.log('Loading time ' + t + ' msec'); } phantom.exit(); }); } I get the following output: Page title is Yahoo Loading time 700 msec However, when I try running a simple nightmare: node --harmony hello_nightmare.js with hello_nightmare.js containing this: var Nightmare = require('nightmare'); var google = new Nightmare() .goto('http://google.com') .wait() .run(function(err, nightmare) { if (err) return console.log(err); console.log('Done!'); }); I get no output whatsoever; it feels like I just pressed 'Enter' on the command line. I also tried the example on the nightmare github site: npm install nightmare vo node --harmony hello_nightmare_main.js with hello_nightmare_main.js containing this: var Nightmare = require('nightmare'); var vo = require('vo'); vo(function* () { var nightmare = Nightmare({ show: true }); var link = yield nightmare .goto('http://yahoo.com') .type('input[title="Search"]', 'github nightmare') .click('.searchsubmit') .wait('.ac-21th') .evaluate(function () { return document.getElementsByClassName('ac-21th')[0].href; }); yield nightmare.end(); return link; })(function (err, result) { if (err) return console.log(err); console.log(result); }); And it still doesn't work. How do I fix this nightmare? A: Your issue is most likely described by https://github.com/segmentio/nightmare/issues/224 Nightmare uses Electron which requires an X display; since your server doesn't have a display, you can use Xvfb to provide a virtual one. Install xvfb, and run xvfb-run node --harmony hello_nightmare.js A: I'm just posting this for posterity. Below is the bash script to install nightmarejs with node (4.2.4) on a clean Ubuntu Linux machine. I've tested this on a DigitalOcean droplet running 14.04. apt-get -y update apt-get -y upgrade apt-get -y --force-yes install make unzip g++ libssl-dev git xvfb x11-xkb-utils xfonts-100dpi xfonts-75dpi xfonts-scalable xfonts-cyrillic x11-apps clang libdbus-1-dev libgtk2.0-dev libnotify-dev libgnome-keyring-dev libgconf2-dev libasound2-dev libcap-dev libcups2-dev libxtst-dev libxss1 libnss3-dev gcc-multilib g++-multilib mkdir src cd src wget https://nodejs.org/dist/v4.2.4/node-v4.2.4.tar.gz tar xzf node-v4.2.4.tar.gz cd node-v4.2.4 ./configure make -j2 make install cd .. mkdir nightmarejs cd nightmarejs npm -f init npm install --save nightmare vo Then you simply create the .js file (e.g. hello_nightmare.js) (in the same directory where nightmarejs is installed) and then run it using the command below (as already mentioned in @yoz's answer): xvfb-run node --harmony hello_nightmare.js I hope this helps. A: Since electron requires X display you need to install all the following packages sudo apt-get install -y xvfb x11-xkb-utils xfonts-100dpi xfonts-75dpi xfonts-scalable xfonts-cyrillic x11-apps clang libdbus-1-dev libgtk2.0-dev libnotify-dev libgnome-keyring-dev libgconf2-dev libasound2-dev libcap-dev libcups2-dev libxtst-dev libxss1 libnss3-dev gcc-multilib g++-multilib Tested in ubuntu server in aws ec2 and it worked then run your script: xvfb-run node --harmony script.js
{ "pile_set_name": "StackExchange" }
Q: Shutdown monitor on debian server I'm running a debian server and because the pc is in my room and always running I want to shutdown the monitor. I have no graphic interface so xset dpms force off doesn't work (returning: xset: unable to open display "") I try "setterm powerdown" commands but it only "clear" the screen but it still produces light (black screen but with background light ... ) So after major google research I'm comming here. The cool thing will be shutdown monitor after inactivity and power on if a keyboard keys is pressed. Only poweroff the screen will be fine because I'm using ssh to manage the server. A: I'm not an expert on linux commands but i remember that it is similiar to something "xset -display :0 dpms force off". You can try this one.
{ "pile_set_name": "StackExchange" }
Q: Is there a way to get results based on the results of a sub query? I am trying to generate a list of projects that members of my website are connected to via tasks they are assigned to. So for example my MySQL query looks like: $result = $con->query("SELECT ProjectID, ProjectName, StartDate, EndDate, Bio, AStartDate, AEndDate, POwnerID FROM projects WHERE ProjectID = (SELECT ProjectID FROM tasks INNER JOIN usertasks ON tasks.TaskID = usertasks.TaskID WHERE UserID = '$User') ORDER BY StartDate"); So the nested query is returning the two expected values (9,10), but the main query returns boolean false. Is it possible to use MySQL query to gain the results I am looking for? A: when your nested query return more than 1 value you must use in WHERE ProjectID IN (SELECT ProjectID to be: $result = $con->query("SELECT ProjectID, ProjectName, StartDate, EndDate, Bio, AStartDate, AEndDate, POwnerID FROM projects WHERE ProjectID IN (SELECT ProjectID FROM tasks INNER JOIN usertasks ON tasks.TaskID = usertasks.TaskID WHERE UserID = '$User') ORDER BY StartDate");
{ "pile_set_name": "StackExchange" }
Q: How to trigger a method invocation of an activity from another activity? I have a CropViewActivity that crops an image, saves the cropped image to the external storage. The process of decoding the bitmap and saving it to external storage is done in another thread. So the crop activity finishes, while the image processing still goes on in the background. Now I want a way to inform my other Activity, which contains an ImageView. At the end of the image processing in the background, the ImageView should then fetch the saved image from memory and load it. How to achieve this inter-thread cum inter-activity communication? Please help.. A: There are several ways of doing that. I would like to refer you some. You might consider using BroadcastReceiver when you are finished processing your image. You need to register the receiver in your activity which contains the ImageView and after processing the image in another activity, send the broadcast with the desired intent that you are listening to receive. Here's a sample implementation on how you can implement a BroadcastReceiver. Another way of communicating between activities is starting an activity for a result. See developers documentation to see how you can use startActivityForResult and then get the result from the activity which is processing the image and getting the result back to the calling activity which contains the ImageView in your case. You might pick any of these two which is best suited according to your use-case. Hope that helps.
{ "pile_set_name": "StackExchange" }
Q: Getting the largest value of a row among multiple entries My question is similar to the following post: Find largest value among repeated entries in an sql table but it is for mysql and and I cannot understand how it translates in sqlite. I want to get the max value of pages from my table metadata with multiple file_ids and multiple entries My table with the two columns I am interested in. file_id pages 1 2 1 5 2 10 3 20 4 12 4 1 5 4 6 5 6 14 7 12 What I am looking for is file_id pages 1 5 2 10 3 20 4 12 5 4 6 14 7 12 I am trying to make a query but don't know how String[]cols = {"file_id","pages"}; String groupBy = {"pages"}; all others params are null that's as far as I can think. What will be the query like. Please help. I want the query in normal sqlite format rather than the raw query if possible. A: This uses the query() method: String tableName = "metadata"; String[] cols = {"file_id", "max(pages) AS pages"}; String[] groupBy = {"file_id"}; Cursor cursor = db.query(tableName, cols, null, null, groupBy, null, null); Replace db with your SQLiteOpenHelper variable.
{ "pile_set_name": "StackExchange" }
Q: Error on array using math notation I don't know why this equation have the errors. Thanks if you can help me. \documentclass{article} \usepackage{array} \usepackage{amssymb,amsthm,amsmath} \begin{document} \begin{equation*} \left[h(t)-\lambda t\right]_k=h_{k}-\frac{\lambda}{2 \pi}\int_{0}^{2\pi}e^{i\theta(1-k)}d\theta= \left\{\begin{array}{lcm} h_{k}-\lambda & if & k=1 \\ \\ h_{k} & if & k \neq 1 \\ \end{array} \right. \\ \end{equation*} \end{document} A: The column type m is wrong. Besides you have a trailing \\ that doesn't belong there. However, you should use cases. \documentclass{article} \usepackage{amssymb,amsthm,amsmath} \begin{document} \begin{equation*} [h(t)-\lambda t]_k = h_{k}-\frac{\lambda}{2 \pi}\int_{0}^{2\pi}e^{i\theta(1-k)}\,d\theta = \begin{cases} h_{k}-\lambda & \text{if $k=1$} \\[2ex] h_{k} & \text{if $k \neq 1$} \end{cases} \end{equation*} \end{document} Note that I removed the wrong \left and \right; I added \, in front of the differential symbol.
{ "pile_set_name": "StackExchange" }
Q: WPF Binding to ListView SelectedItem Is Not Working I'm using a ListView to display contents of a log in my application. I want to change the icon and visibility of a context MenuItem based upon the user's currently selected entry in the ListView. Here is how I'm populating the ListView: // Create the collection view source. m_CollectionViewSource = new CollectionViewSource(); m_CollectionViewSource.SortDescriptions.Add(new System.ComponentModel.SortDescription("Time", System.ComponentModel.ListSortDirection.Descending)); m_CollectionViewSource.Filter += new FilterEventHandler(LogEventCollectionViewSource_Filter); // Create the binding. Binding binding = new Binding(); binding.Source = m_CollectionViewSource; this.LogEventListView.SetBinding(ListView.ItemsSourceProperty, binding); m_CollectionViewSource.Source = LogEventManager.Instance.LogEventCollection; And here is where I'm creating my ListView control. <ListView x:Name="LogEventListView" Grid.Row="0" Grid.Column="0" SelectionMode="Single" VirtualizingStackPanel.IsVirtualizing="True"> <ListView.ContextMenu> <ContextMenu Opened="ContextMenu_Opened"> <MenuItem x:Name="ContextMenuViewDetails" Header="View Details..." ToolTip="Shows all of the data associated with the log event message." Visibility="{Binding ElementName=LogEventListView, Path=SelectedItem, Converter={StaticResource NullToVisibilityConverter}}"> <MenuItem.Icon> <Image MaxHeight="16" MaxWidth="16" Source="{Binding ElementName=LogEventListView, Path=SelectedItem.Category, Converter={StaticResource LogEventCategoryConverter}, ConverterParameter='Small'}" /> </MenuItem.Icon> </MenuItem> Everything works fine except for the binding of the first menu item. When an item is not selected, I want the first menu item's Visibility to be Collapsed. I also want the context MenuItem image to match that of the selected log event. I have verified that BOTH of my IValueConverter classes are working properly. For some reason the first MenuItem is always visible and never has an icon. Can someone tell me what I'm overlooking? UPDATE: There seem to be some real issues with binding to the Icon property of a MenuItem in .NET 3.5 as seen here and here. Problems are compounded by the fact that I'm using an IValueConverter to select the appropriate image. Although it's not the solution I prefer, for now I've just decided to set the values in code-behind in the ContextMenu's opening event. ContextMenu menu = sender as ContextMenu; if (menu != null) { MenuItem item = LogicalTreeHelper.FindLogicalNode(menu, "ContextMenuViewDetails") as MenuItem; if (item != null) { if (this.LogEventListView.SelectedItems.Count <= 0) item.Visibility = Visibility.Collapsed; else item.Visibility = Visibility.Visible; } } } A: Edit: after look at it again, this might actually be an example of the problem described here Original answer below, but probably won't work Without seeing the converter I can't comment on why it might not be working, but you could try to achieve the same with a style instead: <ContextMenu.Style> <Style> <Style.Triggers> <DataTrigger Binding="{Binding SelectedItem, ElementName=LogEventListView} Value="{x:Null}"> <Setter Property="Visibility" Value="Collapsed"/> </DataTrigger> </Style.Triggers> </Style> </ContextMenu.Style>
{ "pile_set_name": "StackExchange" }
Q: Should 'traverse' word only be used to describe/tell the route to a place or can be used for a process or procedure even? Like 'you will have to traverse through all these steps again'. A: The word "traverse" should only be used to indicate traveling over or through something, often over a specific kind of terrain. It can, however, be used in metaphors that express a different concept by invoking an image similar to traveling over a specific kind of terrain or traveling through a given location. The example sentence is not a correct usage. Here are some correct usage examples: "To reach Mount Doom, Frodo and his companion had to traverse the treacherous paths of the Dead Marshes." This is correct because the travelers are traveling through the Dead Marshes. "Traversing the complex code base is daunting, but this map makes it more manageable." Here, "traverse" is used to support a metaphor. You don't actually traverse through a code base, but trying to make sense of the code behind a complex application can oftentimes resemble a journey of sorts. This sentence invokes that metaphor and then uses "traverse" to indicate traveling through the application's code. A better phrasing of the example sentence would be, "You will have to repeat all these steps again."
{ "pile_set_name": "StackExchange" }
Q: Why does the Artscroll commentary to Vayeira mention Ishmael? The Artscroll commentary to the first pasuk of Vayeira says that Abraham pressed Ishmael into service to teach him about hospitality. From whence this comment about Ishmael? A: They're coming from Genesis 18:7: וְאֶל־הַבָּקָ֖ר רָ֣ץ אַבְרָהָ֑ם וַיִּקַּ֨ח בֶּן־בָּקָ֜ר רַ֤ךְ וָטוֹב֙ וַיִּתֵּ֣ן אֶל־הַנַּ֔עַר וַיְמַהֵ֖ר לַעֲשׂ֥וֹת אֹתֽוֹ Then Abraham ran to the herd, took a calf, tender and choice, and gave it to a servant-boy, who hastened to prepare it. Rashi there comments: אל הנער. זֶה יִשְׁמָעֵאל, לְחַנְּכוֹ בְּמִצְוֹת (בראשית רבה): TO THE YOUNG MAN — This was Ishmael whom he bade to do this in order to train him to the performance of religious duties (in this case the duty of hospitality) (Genesis Rabbah 48:13). His comment comes from Bereishis Rabbah 48:13: וַיִּתֵּן אֶל הַנַּעַר, זֶה יִשְׁמָעֵאל, בִּשְׁבִיל לְזַרְזוֹ בְּמִצְווֹת. Eitz Yosef ad. loc. says this is evident from the fact that Avraham gave away the mitzvah. He wouldn't give it to anyone else, were it not for the mitzvah of chinuch. Also, Yishmael elsewhere is called נער (Genesis 21:12).
{ "pile_set_name": "StackExchange" }
Q: Two navigation bars are extended together when displayed on mobile I use two Bootstrap 3 navbars, first one is default and the second is inverse. The problem is when I display the page in mobile devices the two are collapsed normally, but when I extend the second navbar both extended together. Also, when I collapse the second both of them are collapsed. <!--Start NAVBAR 1--> <nav class="navbar navbar-default" style="font-weight: bold; background-color: white; margin-bottom: 0; margin-top: 0; border-color: transparent;" role="navigation"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <img src="" class="img-responsive" href="#" style="padding-left:50px;"> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse navbar-center" id="bs-example-navbar-collapse-1"> <div class="col-xs-offset-3 col-xs-6 text-center"> <ul class="nav navbar-nav navbar-center"> <li> <form class="navbar-form" role="search" style="padding-top:15px"> <div class="input-group"> <input type="text" class="form-control" placeholder="Search" name="q"> <div class="input-group-btn"> <button class="btn btn-default" type="submit"><i style="color:#183F66" class="glyphicon glyphicon-search"></i></button> </div> </div> </form> </li> </ul> </div> <ul class="nav navbar-nav navbar-right" style="padding-top:10px; margin:0 !important;"> <li><a href="#" style="color:#183F66"><span class="glyphicon glyphicon-log-out" style="color:#183F66"></span> Logout</a></li> <li><a href="#" style="color:#183F66"><span class="glyphicon glyphicon-user" style="color:#183F66"></span> username</a></li> </ul> </div> </nav> <!--END NAVBAR 1--> <!--Start NAVBAR 2--> <div class="navbar navbar-inverse"> <!-- <div class="container"> --> <div style="margin-left:5px;margin-right:5px"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> </div> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav" style="color:white"> <li>@Html.ActionLink("News", "About", "Home", new { Style = "color:White; font:bold" })</li> <li>@Html.ActionLink("Supervisors", "Contact", "Home", new { Style = "color:White; font:bold" })</li> <li>@Html.ActionLink("About SaVeIT", "Contact", "Home", new { Style = "color:White; font:bold" })</li> </ul> </div> </div> </div> A: The problem is that, your second toggle button has data-target=".navbar-collapse" which targets both navbars. Use an id on the second collapsible and target it with that, just like in the example below (I use #bs-example-navbar-collapse-2 here). <!--Start NAVBAR 1--> <nav class="navbar navbar-default" style="font-weight: bold; background-color: white; margin-bottom: 0; margin-top: 0; border-color: transparent;" role="navigation"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <img src="" class="img-responsive" href="#" style="padding-left:50px;"> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse navbar-center" id="bs-example-navbar-collapse-1"> <div class="col-xs-offset-3 col-xs-6 text-center"> <ul class="nav navbar-nav navbar-center"> <li> <form class="navbar-form" role="search" style="padding-top:15px"> <div class="input-group"> <input type="text" class="form-control" placeholder="Search" name="q"> <div class="input-group-btn"> <button class="btn btn-default" type="submit"><i style="color:#183F66" class="glyphicon glyphicon-search"></i></button> </div> </div> </form> </li> </ul> </div> <ul class="nav navbar-nav navbar-right" style="padding-top:10px; margin:0 !important;"> <li><a href="#" style="color:#183F66"><span class="glyphicon glyphicon-log-out" style="color:#183F66"></span> Logout</a></li> <li><a href="#" style="color:#183F66"><span class="glyphicon glyphicon-user" style="color:#183F66"></span> username</a></li> </ul> </div> </nav> <!--END NAVBAR 1--> <!--Start NAVBAR 2--> <div class="navbar navbar-inverse"> <!-- <div class="container"> --> <div style="margin-left:5px;margin-right:5px"> <div class="navbar-header"> <!-- Note: data-target="#bs-example-navbar-collapse-2" --> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-2"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> </div> <!-- Note the new id: #bs-example-navbar-collapse-2 --> <div class="navbar-collapse collapse" id="bs-example-navbar-collapse-2"> <ul class="nav navbar-nav" style="color:white"> <li>@Html.ActionLink("News", "About", "Home", new { Style = "color:White; font:bold" })</li> <li>@Html.ActionLink("Supervisors", "Contact", "Home", new { Style = "color:White; font:bold" })</li> <li>@Html.ActionLink("About SaVeIT", "Contact", "Home", new { Style = "color:White; font:bold" })</li> </ul> </div> </div> </div> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet"/> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
{ "pile_set_name": "StackExchange" }
Q: TZ Portfolio Joomla gallery issue I am using the TZ Portfolio extension for Joomla 2.5. In this extension, the image gallery option will open up a popup with more image sections. It's open in a popup, but the entire page (like the entire website opens) in the popup, and the print function starts executing (when I click on the popup the printer is also showing). Any help or documentation URL for this issue? A: You can check TZ Portfolio wiki http://wiki.templaza.com/Main_Page Video tutorial: http://www.youtube.com/channel/UCykS6SX6L2GOI-n3IOPfTVQ/videos
{ "pile_set_name": "StackExchange" }
Q: How to enforce the maximum and minimum number of characters allowed in a string I want to limit my string, so that you have to put a minimum of 3 chars and a max of 10 chars in. Is this possible in the following code below? main.cs: class Program { static void Main(string[] args) { Something hello = new Something(); string myname; Something test = new Something(); myname = Console.ReadLine(); test.Name = myname; } } class with properties: class Okay : IYes { private string thename; public string Name { get {return thename;} set {thename = value;} //what to put here??? } } A: class Okay : IYes { private string name; public string Name { get { return name; } set { if (value == null) throw new ArgumentNullException("Name"); if (value.Length < 3 || value.Length > 10) throw new ArgumentOutOfRangeException("Name"); name = value; } } } You can also truncate the string if it's too long, rather than throwing an exception by just taking (up to) the first 10 characters: class Okay : IYes { private string name; public string Name { get { return name; } set { if (value == null) throw new ArgumentNullException("Name"); if (value.Length < 3) throw new ArgumentOutOfRangeException("Name"); name = string.Join("", value.Take(10)); } } } private static void GenericTester() { Okay ok = new Okay {Name = "thisIsLongerThan10Characters"}; Console.WriteLine(ok.Name); } // Output: // thisIsLong
{ "pile_set_name": "StackExchange" }
Q: Adding two cells in a double loop I am trying add two cells together and put the result into the first. I created a double loop to go through all the cells and add them together. I am stuck at how to add the two cells together. Private Sub CommandButton1_Click() Dim i As Integer, p As Integer, r As Integer, v As Integer ' i is for the column in Inventory ' p is for the column in Pending ' r is for the current row ' v is the holding variable for the Sum of both cells For r = 2 to 30 For i = 2 To 18 'This is not proper syntax I think Range("AR2").Formula = "=SUM(Cells(r,i),Cells(r,p)" v = Range("AR2").Value 'Assigning the value fo he forumla to the variable Cells(r, i).ClearContents Cells(r, p).ClearContents 'need to add an if/then statment to clear cell is value is zero Cells(r, i).Value = v 'Do I really need this here cant I add this after the loop? Range("AR2").ClearContents Next i Next r End Sub I have my comments/questions in the code. A: You do not need to use AR2 as a 'holding cell. Simply retain the value. If you need to use the safety overhead of the worksheet's native SUM function (cell values may be text) then use the WorksheetFunction object or Excel Application object to facilitate its use. For r = 2 to 30 For i = 2 To 18 v = Application.Sum(Cells(r,i), Cells(r,p)) Cells(r, i).ClearContents Cells(r, p).ClearContents if cbool(v) then 'v is not zero Cells(r, i).Value = v end if Next i Next r btw, the original formula was missing a closing bracket and you needed the Range.Address property, not the Range object. Range("AR2").Formula = "=SUM(" & Cells(r,i).Address & "," & Cells(r,p).Address & ")"
{ "pile_set_name": "StackExchange" }
Q: Token Session and Post Token always different although from the same paramater i'm generate a token for my form like this: /*** set a form token ***/ $token = md5( uniqid(rand(), true) ); /*** set the session form token ***/ $_SESSION['form_token'] = $token; and put hidden input in my form like this: <input type="hidden" name="token" value="<?php echo $token; ?>" /> but when i submit the pages and compare the token it give me a different token id. can anyone tell me am i doing something wrong? A: Make sure you only (re)generate a token if the form is not submitted yet. <?php // Process request OR show form.. if($_SERVER['REQUEST_METHOD'] === 'POST') { // check if we receive a token if(isset($_POST['form_token'])) { // compare the token if($_POST['form_token'] === $_SESSION['form_token']) { // do the magic here... unset($_SESSION['form_token']); } else { die('No token match'); } } else { die('No token found'); } } else { $token = md5( uniqid(rand(), true)); $_SESSION['form_token'] = $token; // print form with hidden token.. }
{ "pile_set_name": "StackExchange" }
Q: Show that RP is closed under concatenation I'm trying to prove the following problem: Show that $RP$ is closed under concatenation Now, let's say that the two languages are $L_{1}$ and $L_{2}$ (both in $RP$). Then I accept a word iff the TM of $L_{1}$ accepted the first part of the word (with a probability $\geq\frac{1}{2}$), and the TM of $L_{2}$ accepted the second part of the word (with a probability $\geq\frac{1}{2}$). But then each word in the language $L_{1} \circ L_{2}$ would be accept with a probability of $\frac{1}{2}\cdot\frac{1}{2}=\frac{1}{4}$, so the language $L_{1} \circ L_{2}$ will not be in $RP$. So what is the correct proof to the problem? A: Do the following $poly(|x|)$ times: Check for every possible (contiguous) partition of the input string $x = x_1x_2$ and apply the $\mathrm{RP}$ machine to each of $x_i$ if the answer is $\mathrm{YES}\:\mathrm{YES}$ outputs $\mathrm{YES}$ and halt. If after polynomially many times, still no definite $\mathrm{YES}$ answer has been put down, output $\mathrm{NO}$ with a little bit of fear as it is always like so with $\mathrm{RP}$ algorithms.
{ "pile_set_name": "StackExchange" }
Q: Recursive select with inner join So I'm trying to write a recursive query that will get an item and it's parents. The problem is my structure can have many parents and the query isn't getting the last row. The structure is: Entity Id | 1 | 2 | 3 | EntityMembership ChildId | ParentId 3 | 2 2 | 1 And so far the query looks like : with results(BaseId, Id, ParentId) as ( select e.id as BaseId, e.id, em.parentid from entity e left join EntityMembership em on e.Id = em.ChildID union all select r.BaseId, e.id, em.parentid from entity e inner join EntityMembership em on e.Id = em.ChildID inner join results r on r.parentid = e.id where r.Id<> r.ParentId ) select results.Id from results where BaseId = 3 Which comes out as: 3 | 2 | Obviously the inner join is preventing the "1" from appearing in the results because it doesn't have a parent, but I have no idea how to rewrite this to include it. A: The problem is that you are doing an inner join on EntityMembership in the second part of your CTE, so you aren't getting "1" in the results. It should be an outer join (as in the first part), but you aren't allowed to have an outer join in a recursive CTE. My solution is to join Entity and EntityMembership ahead of time in another CTE and use that in the recursion instead. with joined(ChildId, ParentId) as (select e.id, em.parentid from entity e left outer join entitymembership em on em.childid = e.id ), results(BaseId, Id, ParentId) as ( select j.ChildId as BaseId, j.ChildId, j.parentid from joined j union all select r.BaseId, j.ChildId, j.parentid from joined j inner join results r on r.parentid = j.ChildId where r.Id <> r.ParentId ) select Id from results where BaseId = 3 Here's a slightly different way to write it, filtering on the child Id inside the CTE instead of afterwards: with joined(ChildId, ParentId) as (select e.id, em.parentid from entity e left outer join entitymembership em on em.childid = e.id ) ,results(ChildId, ParentId) as ( select j.childid, j.parentid from joined j where j.childid = 3 union all select j.childid, j.parentid from joined j join results r on r.parentid = j.childid ) select ChildId from results
{ "pile_set_name": "StackExchange" }
Q: Problems defining JSON API data in JS Am trying to use Jquery to get data from an API and update the API URL based on a select box option. However, there is something wrong with my code in the below snippet. It is meant to allow the user the option to select a date range (default of 30 days as value) and onchange the API URL is updated, using AJAX also allows the HTML content to be updated. function datePeriod() { let datePeriod = $("#DateSelector").val(); $("#DateShow").html(datePeriod); $.getJSON(`https://discovrbookings.innocraft.cloud/?module=API&method=API.get&format=json&idSite=2&period=day&date=last${datePeriod}&token_auth=68aa5bd12137f13255dcb98794b65dff`, data => { let visitors; let uniq_visitors; let pageviews; let uniq_pageviews; let actions; let outlinks; let bounces; let avgtime; for (i in data) { let a = data[i].nb_visitors; if (a) { visitors += a; } let b = data[i].nb_uniq_visitors; if (b) { uniq_visitors += b; } let c = data[i].nb_pageviews; if (c) { pageviews += c; } let d = data[i].nb_uniq_pageviews; if (d) { uniq_pageviews += a; } let e = data[i].nb_actions; if (e) { actions += b; } let f = data[i].nb_outlinks; if (f) { outlinks += c; } let g = data[i].bounce_count; if (g) { bounces += c; } let h = data[i].avg_time_on_site; if (h) { avgtime += c; } } $("#visitors").html(visitors); $("#uniq_visitors").html(uniq_visitors); $("#pageviews").html(pageviews); $("#uniq_pageviews").html(uniq_pageviews); $("#actions").html(actions); $("#outlinks").html(outlinks); $("#bounces").html(bounces); $("#avgtime").html(avgtime); }); } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select name="DateSelector" id="DateSelector" onchange="return datePeriod();"> <option selected value="30">Last 30 Days</option> <option value="90">Last 90 Days</option> <option value="365">Last 365 Days</option> </select> <span id="DateShow"></span> <p id="visitors"></p> <p id="uniq_visitors"></p> <p id="pageviews"></p> <p id="uniq_pageviews"></p> <p id="actions"></p> <p id="outlinks"></p> <p id="bounces"></p> <p id="avgtime"></p> As seen in the snippet, whilst the select box works with #DateShow the return values of the JSON are not displaying. JSON is retrieved as example {"2017-12-18":{"nb_uniq_visitors":1,"nb_visits":1,"nb_users‌​":0...}}, seen here https://discovrbookings.innocraft.cloud/?module=API&method=API.get&format=json&idSite=2&period=day&date=last30&token_auth=68aa5bd12137f13255dcb98794b65dff I want the keys as per date to be totalled over the set period from the select box, i.e. if a user selects last 90 days the API URL is changed to https://...date=last90.... The content of each should be updated with the new JSON data. A: Problems I can see... You have a return in the onChange, as QuietOran said. remove it. If you are loading / inserting your javascript at the end of the document, it wont work because the datePeriod function will be undefined when the onChange is read in the source. I can't tell if this is a problem as I can't see from your post how/when you are loading the javascript. To fix it, either have your function defined before the onChange, or attach the event listener with addEventListener() or the jquery eqivilent which I think is: $('#DateSelector').on('change', function(){//do stuff}) You are trying to use data[i].nb_visitors, which should probably be data[i].nb_visits. Check your additions within your if statements, a few are wrong, for example, when you are checking d, you are adding a. if (d) { uniq_pageviews += a; // this is wrong I think } With these few problems fixed, it seems to work, though the summed data for 30, 90 and 365 days seems to add up to the same values. <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script> function datePeriod() { let datePeriod = $("#DateSelector").val(); $("#DateShow").html(datePeriod); $.getJSON(`https://discovrbookings.innocraft.cloud/?module=API&method=API.get&format=json&idSite=2&period=day&date=last${datePeriod}&token_auth=68aa5bd12137f13255dcb98794b65dff`, (data) => { //console.log(data); let visitors = 0; let uniq_visitors = 0; let pageviews = 0; let uniq_pageviews = 0; let actions = 0; let outlinks = 0; let bounces = 0; let avgtime = 0; for (i in data) { if (data[i].nb_visits) { visitors += data[i].nb_visits; } if (data[i].nb_uniq_visitors) { uniq_visitors += data[i].nb_uniq_visitors; } if (data[i].nb_pageviews) { pageviews += data[i].nb_pageviews; } if (data[i].nb_uniq_pageviews) { uniq_pageviews += data[i].nb_uniq_pageviews; } if (data[i].nb_actions) { actions += data[i].nb_actions; } if (data[i].nb_outlinks) { outlinks += data[i].nb_outlinks; } if (data[i].bounce_count) { bounces += data[i].bounce_count; } if (data[i].avg_time_on_site) { avgtime += data[i].avg_time_on_site; } } $("#visitors").html(visitors); $("#uniq_visitors").html(uniq_visitors); $("#pageviews").html(pageviews); $("#uniq_pageviews").html(uniq_pageviews); $("#actions").html(actions); $("#outlinks").html(outlinks); $("#bounces").html(bounces); $("#avgtime").html(avgtime); }); } </script> <select name="DateSelector" id="DateSelector" onchange="datePeriod();"> <option selected value="30">Last 30 Days</option> <option value="90">Last 90 Days</option> <option value="365">Last 365 Days</option> </select> <span id="DateShow"></span> <p id="visitors"></p> <p id="uniq_visitors"></p> <p id="pageviews"></p> <p id="uniq_pageviews"></p> <p id="actions"></p> <p id="outlinks"></p> <p id="bounces"></p> <p id="avgtime"></p>
{ "pile_set_name": "StackExchange" }
Q: R - Extract portions of matching and non matching strings I need to extract portions of strings that match and those that do not match between two columns: x <- c("apple, banana, pine nuts, almond") y <- c("orange, apple, almond, grapes, carrots") j <- data.frame(x,y) To get: yonly <- c("orange, grapes, carrots") xonly <- c("banana, pine nuts") both <- c("apple, almond") k <- data.frame(cbind(x,y,both,yonly,xonly)) I looked into str_detect, intersect etc. but these would appear to require major surgery on the existing cells to separate them into different cells. This is a sizable data set with other columns so I'd prefer to not manipulate it too much. Can you help me come up with a simpler solution? Thanks! A: You can use setdiff and intersect > j <- data.frame(x,y, stringsAsFactors = FALSE) > X <- strsplit(j$x, ",\\s*")[[1]] > Y <- strsplit(j$y, ",\\s*")[[1]] > > #Yonly > setdiff(Y, X) [1] "orange" "grapes" "carrots" > > #Xonly > setdiff(X, Y) [1] "banana" "pine nuts" > > #Both > intersect(X, Y) [1] "apple" "almond"
{ "pile_set_name": "StackExchange" }
Q: SQL How to count by same date I have this SQL query: select u.EMSUnitCallSign as Unit_number, d.DestinationName, CONVERT(date, i.IncidentDate) as Incident_date, COUNT(d.DestinationName) as Count_by_unit from INC_Disposition d left join INC_UnitInformation u on u.IncidentID = d.IncidentID left join INC_Incident i on i.IncidentID = d.IncidentID where (d.DestinationName like '%hospital%' or d.DestinationName like '%center%') and i.PatientArrivedDestDate is not null group by u.EMSUnitCallSign, d.DestinationName, i.IncidentDate order by u.EMSUnitCallSign, i.IncidentDate It's current result show as: A701 HospitalA 2015-04-15 1 A701 HospitalB 2015-04-15 1 A701 HospitalB 2015-04-15 1 A701 HospitalC 2015-04-16 1 A701 HospitalC 2015-04-16 1 A701 HospitalC 2015-04-16 1 A701 HospitalC 2015-04-16 1 A701 HospitalA 2015-04-16 1 How do I group the ones on the same date and count them together? A: The problem is that IncidentDate has a date component. I am guessing that you are using SQL Server, and SQL Server doesn't allow the use of aliases in the GROUP BY clause. So, the solution is to do the conversion in both places: select u.EMSUnitCallSign as Unit_number, d.DestinationName, CONVERT(date, i.IncidentDate) as Incident_date, COUNT(d.DestinationName) as Count_by_unit from INC_Disposition d left join INC_UnitInformation u on u.IncidentID = d.IncidentID left join INC_Incident i on i.IncidentID = d.IncidentID where d.DestinationName like '%hospital%' or d.DestinationName like '%center%' and i.PatientArrivedDestDate is not null group by u.EMSUnitCallSign, d.DestinationName, CONVERT(date, i.IncidentDate) order by u.EMSUnitCallSign, min(i.IncidentDate); Based on your where conditions, I'm quite confident that you really want inner joins and not outer joins.
{ "pile_set_name": "StackExchange" }
Q: Should a Perl module raise exceptions (die/croak)? When writing a Perl module, is it a good practice to use croak/die inside the module? After all, if the caller doesn't use an eval block, the module might crash the program calling it. What is the best practice in these cases? A: I generally prefer exceptions if you're indicating an error of some kind. Otherwise you have to spend much more time sprinkling error handling code at different levels of your codebase rather than centralising the error handling in appropriate layers of the system - amongst other reasons. You may find this old thread on perlmonks a useful read. I'll reproduce my comment there below - since I mostly agree with what I wrote back then :-) Some reasons I like exceptions: Robustness. I can forget to check for an returned error value. I cannot forget to check for an exception. Brevity. I prefer: $o->foo->bar->fribble->ni to $o->foo or return(ERROR_FOO); $o->bar or return(ERROR_BAR); $o->fribble or return(ERROR_FRIBBLE); $o->ni or return(ERROR_NI); Clarity. With exception based code the "normal" flow of control is more explicit because it is not obscured by error handling code. I think that the first of the two code examples above shows the intent of the code more directly than the second does. Separation of concerns. The error condition and the error handler are different ideas. You may want an error to be handled in different ways depending on the context. You may also not know how the error should be handled at the point it occurs. You may not know how the error should be handled at the time you write the code. With the return-error-code style you end up having to either: propogate error conditions to where the decision on how they should be handled can be made. propogating error handlers down to where the errors may occur Both options rapidly become messy if there are many levels of code between the error condition and the error handler. No confusion between return values and error conditions. There are probably some more ;-)
{ "pile_set_name": "StackExchange" }
Q: Approximating the inverse of an exponent equation Let $$m=a_{1}n^{\alpha}+a_{2}n^{\beta}$$ where $1>\alpha>\beta>0$ and $a_{1},a_{2}$ are positive constants, and we want to understand $n$ as a function of $m$ , the first order is clearly $$n=a_{1}^{-\frac{1}{\alpha}}m^{\frac{1}{\alpha}}$$ but how can we fine the sceond order and the error magnitude, for large $m$. Any help would be much appreciated. A: One may solve to get $$n=a_1^{-1/\alpha}(m-a_2n^\beta)^{1/\alpha}$$ and with an initial estimate of $n=0$, we get using fixed-point iteration the first few expansions can be turned into asymptotic expansions with the generalized binomial expansion theorem: \begin{align} n&\approx a_1^{-1/\alpha}m^{1/\alpha}\\\\ n&\approx a_1^{-1/\alpha}(m-a_2a_1^{-\beta/\alpha}m^{\beta/\alpha})^{1/\alpha}\\ &\approx a_1^{-1/\alpha}m^{1/\alpha}-\alpha^{-1}a_2a_1^{-(\beta+1)/\alpha}m^{(\beta-\alpha)/\alpha} \end{align} Since the sign changes, the error of the first approximation can be bounded by $$|n-a_1^{-1/\alpha}m^{1/\alpha}|\le\alpha^{-1}a_2a_1^{-(\beta+1)/\alpha}m^{(\beta-\alpha)/\alpha}$$ for large $m$. Repeated iterations can give higher order terms but quickly become very messy to expand.
{ "pile_set_name": "StackExchange" }
Q: How to plot overlapping squares with similar size? I try to plot a pattern with overlapping squares using matplotlib.pyplot. I am not sure how to get all squares of the same size. Here is my code: import matplotlib.pyplot as plt plt.plot([2.2,2.2,3.5,3.5,2.2],[4.1,2.5,2.5,4.1,4.1],linestyle='solid',color="red") plt.plot([3.2,4.2,4.2,3.2,3.2],[3.2,3.2,4.5,4.5,3.2],linestyle='solid',color="blue") plt.plot([2.5,2.5,3.8,3.8,2.5],[1.8,3.8,3.8,1.8,1.8],linestyle='solid',color="green") plt.plot([3.6,4.8,4.8,4.8,3.6,3.6],[2.2,2.2,0,0,0,2.2],linestyle='solid',color="black") plt.title('square pattern') A: Here is some code to draw 4 squares of the same size. The squares are represented by their lower left position. You can change these coordinates to easily position each square. import matplotlib.pyplot as plt from math import sqrt colors = [ 'crimson', 'dodgerblue', 'limegreen', 'black'] side = 2 square1 = [1, 1.3] square2 = [2.1, 0.5] square3 = [1.3, 1.6] square4 = [1.7, 2.8] squares = [square1, square2, square3, square4] for square, col in zip(squares, colors): x = square[0] y = square[1] plt.plot([x, x + side, x + side, x, x], [y, y, y + side, y + side, y], color=col, linestyle='solid') plt.title('square pattern') plt.gca().set_aspect('equal') plt.show()
{ "pile_set_name": "StackExchange" }
Q: Threading test question I recently had a interview question in a test that was similar to the below, I do not have very much experience of development using threads can someone please help advise me how to approach this question?: public class StringQueue { private object _lockObject = new object(); private List<string> _items = new List<string>(); public bool IsEmpty() { lock (_lockObject) return _items.Count == 0; } public void Enqueue(string item) { lock (_lockObject) _items.Add(item); } public string Dequeue() { lock (_lockObject) { string result = _items[0]; _items.RemoveAt(0); return result; } } } Is the following method thread safe with the above implementation and why? public string DequeueOrNull() { if (IsEmpty()) return null; return Dequeue(); } A: It seems to me the answer is no. While isEmpty() procedure locks the object, it is released as soon as the call is returned - a different thread could potentially call DequeueOrNull() between the call to IsEmpty() and Dequeue() (at which time the object is unlocked), thus removing the only item that existed, making Dequeue() invalid at that time. A plausible fix would be to put the lock over both statements in DequeueOrNull(), so no other thread could call DeQueue() after the check but before the DeQueue(). A: It is not threadsafe. At the marked line it is possible that the Dequeue method is called from another thread and thus, the consequent Dequeue return a wrong value: public string DequeueOrNull() { if (IsEmpty()) return null; /// << it is possible that the Dequeue is called from another thread here. return Dequeue(); } The thread safe code would be: public string DequeueOrNull() { lock(_lockObject) { if (IsEmpty()) return null; return Dequeue(); } }
{ "pile_set_name": "StackExchange" }
Q: What causes S&P 500 to grow faster than inflation? Facts Average annual rate of USA's inflation is ~2% for the past couple of years Average annual return of S&P 500 is 10% Why? Many people suggest to move your money of your bank, which is maybe paying 1.5% APY, and into index funds so that your money is not depreciating. I agree with this advice because the math is simple: 1.5% < 2% < 10%. But I'd feel more comfortable if I knew why I was following the advice. Why does S&P 500 grow faster than inflation? To play devil's advocate, I'm throwing out two counter examples below to the 10% growth. By no means am I a skilled economist, so I will not be offended if you correct me. Spread of Wealth I think the companies in the S&P 500 grow by selling more products. When their profits grow, investors have more faith in the company and buy their stock. Buying stock bumps up their NAV. But why would consumers only buy from these 500 USA companies? Aren't they also buying from the thousands of other companies in the world? Competition Google and Apple are both in the S&P 500. Let's say someone buys an iPhone from Apple. They would be unlikely to buy an Android phone and thus Google's operating system is unused. This is just one example of competition. Many other pairs of competitors exist in the S&P 500. The bottom line is when one company succeeds, their competitor may fail. So the net success of the two companies should remain neutral. The net will not grow 10% a year. A: The answer boils down to, are publicly-listed companies able to grow earnings faster than the rate of inflation? If the answer is "yes", then no surprise that the S&P500 grows faster than inflation. And the answer is unequivocally "yes". According to this CNBC article from July for example, we're currently in the midst of an earnings boom with earnings growing by as much as 20% - way more than 2% inflation. Of course this kind of boom will not last, but on average you can see that the big get bigger and the 500 current biggest US companies historically grow earnings by ~10% a year. To address the two situations you gave: I think the companies in the S&P 500 grow by selling more products. When their profits grow, investors have more faith in the company and buy their stock. Buying stock bumps up their NAV. But why would consumers only buy from these 500 USA companies? Aren't they also buying from the thousands of other companies in the world? Because these 500 USA companies - like any other good company, including those from elsewhere in the world - have some kind of competitive edge. For example, if you want a Big Mac, you have to buy it from McDonald's. You don't have an alternative! This advantage, known as a "moat", means that a new upstart company can't just enter the burger market and displace McDonald's by offering a better, cheaper burger. In principle, it can be done. In practice, McDonald's brand name is such that the new competitor will need a fantastically superior product to displace McDonald's. Google and Apple are both in the S&P 500. Let's say someone buys an iPhone from Apple. They would be unlikely to buy an Android phone and thus Google's operating system is unused. This is just one example of competition. Many other pairs of competitors exist in the S&P 500. The bottom line is when one company succeeds, their competitor may fail. So the net success of the two companies should remain neutral. The net will not grow 10% a year. This assumes that the smartphone market overall doesn't grow, which is certainly not the case. 10 years ago there were much fewer smartphones in the world than today. The market is bigger now, which of course leads to both Apple and Google making more money. There're other factors as well. For example, Apple makes a lot more money per phone sold than Samsung (Google doesn't sell many phones directly). So if people buy iPhones, Apple's profits grow by more than Samsung's profits drop.
{ "pile_set_name": "StackExchange" }
Q: How to fix my Background solution to make thread-safe calls? I tried to set Text property of TextBox from another thread. I got this exception below; "Cross-thread operation not valid: Control 'recTpcTxt' accessed from a thread other than the thread it was created on." Then, I used BackgroundWorker to solve this issue. However, I faced with the same exception message. EDIT[1]: Actually, I take a guide myself this link ; https://msdn.microsoft.com/en-us/library/ms171728(v=vs.110).aspx. I can solve my problem by using invokeproperty. However, I cannot solve my problem with backgroundworker. Is there something wrong in my solution? How do I fix my solution to set some property of UI variable? EDIT[2]: More code to clarify the issue; MqttManager.cs; public partial class MqttManager : Form { MqttHandler mqttHandler = new MqttHandler(); public static MqttManager managerInst; public MqttManager() { InitializeComponent(); managerInst = this; ... } ... private BackgroundWorker backgroundWorker; public void NotifyUIForRecMsg(string topic, string message) { object[] objArr = { topic, message }; this.backgroundWorker.RunWorkerAsync(objArr); } private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e) { System.Threading.Thread.Sleep(5000); e.Result = e.Argument; } private void backgroundWorker_RunWorkerCompleted( object sender, RunWorkerCompletedEventArgs e) { object[] res = (object[])e.Result; this.recTpcTxt.Text = (String)res[0]; } } MqttManager.Design.cs; partial class MqttManager { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { ... this.backgroundWorker = new System.ComponentModel.BackgroundWorker(); this.backgroundWorker.DoWork += new System.ComponentModel.DoWorkEventHandler(this.backgroundWorker_DoWork); this.backgroundWorker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.backgroundWorker_RunWorkerCompleted); } #endregion ... } MqttHandler.cs; class MqttHandler { MqttClient client; ... /// <summary> /// Publish received event handler. /// </summary> private void client_MqttMsgPublishReceived(Object sender, MqttMsgPublishEventArgs e) { MqttManager.managerInst.NotifyUIForRecMsg(e.Topic, Encoding.UTF8.GetString(e.Message)); } } A: check this: https://msdn.microsoft.com/en-us/library/ms171728(v=vs.110).aspx Basically, to set a control propertiy you have to be in the same UI thread. This simple solution move the call to textbox1.Text = someText in the UI thread private void SetText(string text) { // InvokeRequired required compares the thread ID of the // calling thread to the thread ID of the creating thread. // If these threads are different, it returns true. if (this.textBox1.InvokeRequired) { SetTextCallback d = new SetTextCallback(SetText); this.Invoke(d, new object[] { text }); } else { this.textBox1.Text = text; } } also, you can use textBox1.BeginInvoke instead of Invoke: it will run in UI thread, without locking the caller thread waiting for SetText delegate to be completed [Edit] to do it in your backgroundWorker: private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e) { object[] arg = (object[])e.Argument; SetTextToTextBox(recTpcTxt, (string)arg[0]); SetTextToTextBox(recMsgTxt, (string)arg[1]); } private void SetTextToTextBox(TextBox toSet, string text) { // InvokeRequired required compares the thread ID of the // calling thread to the thread ID of the creating thread. // If these threads are different, it returns true. if (toSet.InvokeRequired) { SetTextCallback d = new SetTextCallback(SetText); toSet.Invoke(d, new object[] { text }); } else { toSet.Text = text; } } [Edit 2] To properly use backgroundworker Register for events DoWork and RunWorkerCompleted this.backgroundWorker1.DoWork += new System.ComponentModel.DoWorkEventHandler(this.backgroundWorker1_DoWork); this.backgroundWorker1.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.backgroundWorker1_RunWorkerCompleted); Before exiting backgroundWorker1_DoWork, set result property of eventArgs, and read them in backgroundWorker1_RunWorkerCompleted private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { System.Threading.Thread.Sleep(5000); e.Result = new string[] { "one", "two" }; } private void backgroundWorker1_RunWorkerCompleted( object sender, RunWorkerCompletedEventArgs e) { string[] res = (string[])e.Result; this.textBox1.Text = res[0]; }
{ "pile_set_name": "StackExchange" }
Q: Vector equation of a plane passing through $r=(1,1,-2)$, $s=(3,0,1)$, $p=(1,1,1)$ For this question I did the cross product so I found $rs$ then $rp$ and using those I did the cross product method to find $(a,b,c)$. After getting $a$, $b$, $c$ which was $(-3,-6,0)$. I plugged it into $a(x-x_0)+b(y-y_0)+c(z-z_0)$. This gave me a final equation of $3x+6y=9$. The answer however is completely different where they said the equation is $(1,1,-2)+ \lambda(2,-1,3)+\mu(0,0,3)$ . How would I know if my answer was correct from this equation and also how will I know when to do the cross product and when to not do it. A: If you set $(x,y,z)=(1,1,-2)+ \lambda(2,-1,3)+\mu(0,0,3)=(1+2\lambda,1-\lambda,-2+3\lambda+3\mu)$, then $3x+6y=3(1+2\lambda)+6(1-\lambda)=9$ The two forms essentially represent the same plane. (Since only $z$ depends on $\mu$, $z$ can be any real number.)
{ "pile_set_name": "StackExchange" }
Q: Javascript Moodle Hi I am fairly new to moodle. I have been trying to test if my Javascript runs but to no avail. Here is what I have: In /videojs/amd/src I made a test.js file with a simple command define(['jquery'], function() { return { init: function() { // Put whatever you like here. $ is available // to you as normal. alert("It changed!!"); } }; }); Then I grunt the file and everything succeed, and made minified. But when I go to the page it doesn't run. Now I read Moodle's Javascript Doc and I see it says The idea here is that we will run the 'init' function from our (PHP) code to set things up. This is called from PHP like this... Where do I call this PHP? A: Somewhere in the page you are outputting, you need to add a call like this: $PAGE->requires->js_call_amd('PLUGINTYPE_videojs/test', 'init); It's not entirely clear from your example what sort of plugin you are creating, so whichever type you are creating (https://docs.moodle.org/dev/Plugin_types), you need to put it in the appropriate subdirectory for your site (e.g. /mod/videojs, /local/videojs, etc.), then add some sort of PHP script as the entry point for your plugin and call the js_call_amd function from there.
{ "pile_set_name": "StackExchange" }
Q: Can you prevent your ASP.NET application from shutting down? I think I heard that ASP.NET applications will shut down after a while of being idle (i.e. no visitors). Is there a way to prevent this behavior from happening? I have a timer that runs some code from the global.asax.cs application_start event, and want to make sure that it continues to run, even when no visitors are hitting the site. Thanks in advance! A: You can do it a few ways. If you have control over IIS, you can change the "Idle Timeout" within the application pool, by default it is 20 minutes. If you do NOT have control over IIS (Shared or other hosting), you can use an external service to ping the site. MyWebKeepAlive or Pingdom are good options for this. If you are under option two, I strongly recommend an external source, as it is less to manage, and if you don't have IIS available to configure, you most likely don't have the server available to add a ping application to. In addition, I do not recommend something that sits in-process with the web application, as I have found that those can cause issues when the application really does need to recycle... One last thought If you do go the route of modifying the IIS Idle timeout, I do recommend setting a regular recycle of the application pool. As many web applications do benefit from a periodic recycle, and most commonly the idle timeout is the biggest regular recycle factor. A: Besides external keep alive you can make an internal keep alive inside global.asax: static Thread keepAliveThread = new Thread(KeepAlive); protected void Application_Start() { keepAliveThread.Start(); } protected void Application_End() { keepAliveThread.Abort(); } static void KeepAlive() { while (true) { WebRequest req = WebRequest.Create("http://www.mywebsite.com/DummyPage.aspx"); req.GetResponse(); try { Thread.Sleep(60000); } catch (ThreadAbortException) { break; } } } A: In IIS 6, go to the Application Pools section, and right-click > Properties on the pool which hosts the ASP.NET application in question. Go to the Performance tab and uncheck "Shutdown worker processes after being idle for:" In IIS 7, go to the Connections pane and find Application Pools, and select Advanced Settings for the pool which hosts your application. Find the "Idle Timeout" property and set it to "0" (this disables it). The default is 20 minutes of inactivity. By unchecking the box, once your AppDomain is loaded by the worker process, it will never die (unless you kill the process or something of course). By default, IIS will recycle the process when it reaches some limit, such as a memory cap, but it will also start a new one and "phase over" all incoming requests until the old one is unused, so as to minimize disruption. If you do not have direct control over your IIS configuration (shared host, for example) your best bet is to have a small application running on a separate system - say, an always-on workstation - which hits your site every x minutes to keep the application pool from timing out. Nothing fancy - a simple WebRequest and a while() loop in a console application will do.
{ "pile_set_name": "StackExchange" }
Q: Dates in Java, how to manipulate the year? I have a Date object in Java. Sometimes the date's year is set to 17. When I go to output it using a SimpleDateFormat, it gets printed out as 0017. All my years are going to be in the 2000's. Is there a way to check if the year is belowe a certain value and then add 2000 to it if it is? Then once you do that, how do you recreate the Date object to use the new year? Seems like everything in the Date object is deprecated. A: I would use a Calendar: Date myDate = new Date(); Calendar cal = Calendar.getInstance(); cal.setTime(myDate); int year = cal.get(Calendar.YEAR); if(year < 2000) cal.add(Calendar.YEAR, 2000); // add two thousand years
{ "pile_set_name": "StackExchange" }
Q: Are 70% of programs/business applications/something based in COBOL? I heard this number and a quick google search reveals a whole lot of touting this number and absolutely zero data (honestly most articles promoting COBOL read like 95% propoganda). Perhaps it's true in an extremely limited context of banking software or something, but with millions of applications coded in dozens of languages and near-zero new COBOL projects I don't see how this is possible. Is this a myth from the 70s (when it would have seemed entirely plausible) or is there some limited definition where this is actually true? I know there is a great deal still being maintained and I'm sure a large % of businesses have at least one COBOL program around, but this invisible 70% seems absurd. A: The COBOL wiki page cites the Gartner quote, but there isn't a source from Gartner provided. It is all over the Net. 80% of businesses, 200 billion lines of code, 5 billion new lines of code each year. Some places, the numbers vary a bit. However, one number is almost always missing from that Gartner quote on the COBOL wiki page, and missing number is the year. 1997. Let's assume the quote was true, in 1997. I have worked in COBOL for 20 years, and for the last 13 years I have witnessed COBOL development disappear. ERP solutions? The last one I know of that had at least some COBOL in the product was PeopleSoft, when I talked to PeopleSoft reps at an IT conference in 2004. I was working for the UW at that time, and I talked to literally dozens of people, maybe upwards of 100, from universities all over the country. A very common story was repeated. "We replaced our homegrown ERP solution, written in COBOL, with " PeopleSoft, Oracle, SAP, SunGard. Delve into the careers links of those companies, and look at IT positions. See if there is any mention of COBOL, DB2, CICS, etc. Healthcare? Well, I worked for GE Healthcare for 3 years, and they were among the last hospital clinical software vendors writing in COBOL. 3 big layoffs in 3+ years, an office that dwindled from 600 employees to under 300 employees, clients converting to Epic or Cerner. Not a very bright future for COBOL there. Neither Epic nor Cerner writes in COBOL. Check out their career pages. McKesson appears to still be written in COBOL, but I see a number of hospitals converting away from them as well. State and federal government might end up the last bastion of COBOL, but some of those projects have gone away. Completely replaced with .NET or Java. At 44, I'm one of the youngest COBOLers I know. Oh, there are 5 or 6 I know who are younger than me, but the 100 or more others I know are probably on average 10-15 years my senior. IBM 390 and zSeries, HP NonStop, Unisys 2200, and Unisys MCP are the big iron boxes out there running COBOL. Every one of them supports Java development. From what I have read and know Java on big iron, which is mostly limited to the HP NonStop, if it is done right then Java can replace COBOL over time. There have been efforts, that I know of or worked on, since 1994 to replace clunky mainframe green screens with GUI front ends written in VB, .NET or Java. A lot of COBOLers I talk to who are certain of COBOL's future are out of work, like me, and aren't finding work. Best shot I have is a state gig where there are likely more than a couple of people within a few years of retirement. Assuming I get in, I expect over the next couple of years my role will evolve into how to clean, efficiently, and without interrupting the business administer a lethal injection, figuratively speaking, to COBOL through step by step replacement. Finally, back to Gartner. They charge for everything they publish, and it ain't cheap. But venture over to Gartner.com, set up a free account, go to the Research tab, and search on the keyword COBOL. You won't get the whole article, but you will get a summary and a snippet. Reading and analyzing Gartner's work, I think it's very clear they are signalling the death of COBOL. A: Depending on how you define the 100%, that number might be correct. For example, it might very well be that 70% of the programs written for banks and financial institutions until 2010 is based in COBOL. Wouldn't be surprised. But I don't think that it is a fair statement to say that out of all the software in the world, 70% would be written in COBOL. Frankly, I don't know if you can even measure it. A: the Gartner Group reported that 80% of the world's business ran on COBOL with over 200 billion lines of code in existence and with an estimated 5 billion lines of new code annually. Source is: COBOL-1. I have no idea how do they count these numbers. I worked in several companies where no one actually tried to count all lines of code in one shop accurately, even when it was used as a measure of complexity. So how did they come up with these numbers? COBOL is alive and well. It is not true to say that there are zero projects starting using COBOL. Remember that lots of the enterprise projects are interdependent. Unless there is a reason to extend a project in a different language you use the original architecture and software. Remember that most of such systems are large and re-writing them in a different language is risky, expensive and usually adds little or no value to the business. There are many resources on the net that tells us that COBOL is alive and well.
{ "pile_set_name": "StackExchange" }
Q: How do I copy a OCaml closure? I want to store a OCaml closure for later use by an external C-library. I am able to do the following: <TARGET> = caml_alloc(Wosize_val(<SOURCE>), Tag_val(<SOURCE>)); caml_register_global_root(<TARGET>); Code_val(<TARGET>) = Code_val(<SOURCE>); But as the name "closure" suggests, it does not suffice to copy just the code location. How do I make a (garbage collector friendly) copy of <SOURCE>? A: In our work on using OCaml in iOS, we often need to save OCaml closures and call them later (when interfacing to CocoaTouch libraries). So I have code that has been working for years. However, it's too complicated to make a good example (and it's written in Objective C). Here's some code I just wrote that captures the essence of what we're doing. First some C code that saves some number of closures of type unit -> unit and lets you call them later by chronological index. (It's just an example.) $ cat saveclo.c #include "caml/mlvalues.h" #include "caml/memory.h" #include "caml/callback.h" static value saved_closures[10]; static int saved_closure_count = 0; value save_closure(value clo) { CAMLparam1(clo); saved_closures[saved_closure_count] = clo; caml_register_global_root(&saved_closures[saved_closure_count]); saved_closure_count++; CAMLreturn(Val_unit); } value call_closure(value index) { CAMLparam1(index); int ix = Int_val(index); // For simplicity assume closure : unit -> unit (void) caml_callback(saved_closures[ix], Val_unit); CAMLreturn(Val_unit); } Then some OCaml code that exercises these functions: $ cat clo.ml external save_closure : (unit -> unit) -> unit = "save_closure" external call_closure : int -> unit = "call_closure" let save alist = let howlong () = Printf.printf "list length %d\n" (List.length alist) in save_closure howlong let call () = call_closure 1; call_closure 0 let () = save [1;2;3;4;5]; save ['a'; 'b'; 'c'; 'd'; 'e'; 'f']; Gc.full_major(); call () A test run looks like this: $ cc -I /usr/local/lib/ocaml -c -o saveclo.o saveclo.c $ ocamlopt -c clo.ml $ ocamlopt -o clo clo.cmx saveclo.o $ ./clo list length 6 list length 5 $ I think the salient points are (a) the OCaml object representing a closure already contains what you need (a code reference of some kind, and the data). (b) You don't need to copy it, you just need to make sure it doesn't get garbage collected. (c) The call to caml_register_global_root creates a reference to the closure so the GC knows not to collect it. I hope this is helpful. If anybody sees problems with this code, let me know and I'll be more than happy to correct errors. But I believe it's correct.
{ "pile_set_name": "StackExchange" }
Q: restore sd card to full capacity I have faced a problem when all partition tools see my SD card as a card of 30 GB size. But when I bought the card I clearly remeber the card had 64 GB and moreover it is written on the card "ScanDisk Ultra 64 GB". The max capacity changed after I decided to reformat my SD card with ext4 filesystem (filesystem was exFAT before). Then whatever I have tried to do, nothing helped me to restore capacity back. What I tried was gparted, fdisk, and even tried to use Windows tools SDFormatterv4 and diskpart. But I use windows tools under VirtualBox because my primary OS is Ubuntu. I do not have preinstalled Windows OS on phisycal drive. I googled and found only solutions when Windows does see only first partiton on SD cards. But I think it is not my case because I do not use Windows at least. But anyway I tried those solutions what did not helped me. How to restore capacity to original size? ADDED as ByteCommander asked # lsblk NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT sda 8:0 0 698.7G 0 disk ├─sda1 8:1 0 171.2G 0 part / ├─sda2 8:2 0 7.6G 0 part ├─sda3 8:3 0 163G 0 part └─sda4 8:4 0 356.9G 0 part /home sdb 8:16 1 27.5G 0 disk sr0 11:0 1 1024M 0 rom # parted -l ... /dev/sda skipped ... Model: Generic USB SD Reader (scsi) Disk /dev/sdb: 29.5GB Sector size (logical/physical): 512B/512B Partition Table: msdos Number Start End Size Type File system Flags I connect SD Card through SD reader. As you can see /dev/sdb has no partitions at all ADDED as zhongfu asked # dmesg | tail -n 20 [ 9203.022463] usb 2-5: New USB device found, idVendor=090c, idProduct=6200 [ 9203.022475] usb 2-5: New USB device strings: Mfr=1, Product=2, SerialNumber=3 [ 9203.022482] usb 2-5: Product: Generic USB2.0 card [ 9203.022487] usb 2-5: Manufacturer: Silicon Motion, Inc. [ 9203.022492] usb 2-5: SerialNumber: 12345678901234567890 [ 9203.022997] usb-storage 2-5:1.0: USB Mass Storage device detected [ 9203.024017] scsi17 : usb-storage 2-5:1.0 [ 9204.024052] scsi 17:0:0:0: Direct-Access Generic USB SD Reader 1.00 PQ: 0 ANSI: 0 CCS [ 9204.024780] sd 17:0:0:0: Attached scsi generic sg2 type 0 [ 9204.027078] sd 17:0:0:0: [sdb] 57626624 512-byte logical blocks: (29.5 GB/27.4 GiB) [ 9204.030200] sd 17:0:0:0: [sdb] Write Protect is off [ 9204.030205] sd 17:0:0:0: [sdb] Mode Sense: 4b 00 00 08 [ 9204.031340] sd 17:0:0:0: [sdb] No Caching mode page found [ 9204.031344] sd 17:0:0:0: [sdb] Assuming drive cache: write through [ 9204.034209] sd 17:0:0:0: [sdb] No Caching mode page found [ 9204.034212] sd 17:0:0:0: [sdb] Assuming drive cache: write through [ 9204.049098] sdb: [ 9204.051865] sd 17:0:0:0: [sdb] No Caching mode page found [ 9204.051876] sd 17:0:0:0: [sdb] Assuming drive cache: write through [ 9204.051885] sd 17:0:0:0: [sdb] Attached SCSI removable disk magic :-( 64 Gb disappeared. here is a photo of my SD card and its reader ADDED as Rod Smith asked # hdparm -N /dev/sdb /dev/sdb: SG_IO: bad/missing sense data, sb[]: 70 00 05 00 00 00 00 0a 00 00 00 00 20 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 SG_IO: bad/missing sense data, sb[]: 70 00 05 00 00 00 00 0a 00 00 00 00 20 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 max sectors = 0/1, HPA is enabled EDIT What I tried to remember and found out with your help guys! thanks to NGRhodes for refreshing my mind At first time I bought the card I did not check on PC if my SD card has 64 GB capacity. Only my camera shows me that I can recording video during 9 hours. If I insert 32 GB SD card then my camera shows I can record video during 4 hours. It means one of card bigger than another. Plus there is a title on cards 64 GB and 32 GB accordingly. So on those facts I made a conclusion that one card 32GB and another 64GB. But when I insert 64GB card into my PC I found out it only has 30 GB. And I started associating it to formating with ext4 filesystem mistakenly (because I formated before I check the size)! Why I think it was a mistake? Because I reformated the SD card back to exFat then checked the size on PC and it was still ~30GB. Then I inderted to my camera. My camera shows I can record video 9 hours long against 4 hours with 32GB card! It means capacity is not lost. So the question who lies camera or PC? It seems HPA is the root cause and PC got some space of my SD card. EDIT2 I tried to format the SD card on my android device. And finally PC shows me 64GB # dmesg | tail -n 20 [15394.096958] usb-storage 2-5:1.0: USB Mass Storage device detected [15394.097115] scsi22 : usb-storage 2-5:1.0 [15395.097725] scsi 22:0:0:0: Direct-Access Generic USB SD Reader 1.00 PQ: 0 ANSI: 0 CCS [15395.097962] sd 22:0:0:0: Attached scsi generic sg2 type 0 [15395.099192] sd 22:0:0:0: [sdb] 57626624 512-byte logical blocks: (29.5 GB/27.4 GiB) [15395.099822] sd 22:0:0:0: [sdb] Write Protect is off [15395.099824] sd 22:0:0:0: [sdb] Mode Sense: 4b 00 00 08 [15395.100449] sd 22:0:0:0: [sdb] No Caching mode page found [15395.100452] sd 22:0:0:0: [sdb] Assuming drive cache: write through [15395.108424] sd 22:0:0:0: [sdb] No Caching mode page found [15395.108427] sd 22:0:0:0: [sdb] Assuming drive cache: write through [15395.123181] sdb: sdb1 [15395.123185] sdb: p1 size 124733440 extends beyond EOD, enabling native capacity [15395.125048] sd 22:0:0:0: [sdb] No Caching mode page found [15395.125056] sd 22:0:0:0: [sdb] Assuming drive cache: write through [15395.125836] sdb: sdb1 [15395.125847] sdb: p1 size 124733440 extends beyond EOD, truncated [15395.129559] sd 22:0:0:0: [sdb] No Caching mode page found [15395.129570] sd 22:0:0:0: [sdb] Assuming drive cache: write through [15395.129578] sd 22:0:0:0: [sdb] Attached SCSI removable disk # df -h | grep sdb /dev/sdb1 60G 20K 60G 1% /media/alek/C8AE-0ADD But still HPA is enabled # hdparm -N /dev/sdb /dev/sdb: SG_IO: bad/missing sense data, sb[]: 70 00 05 00 00 00 00 0a 00 00 00 00 20 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 SG_IO: bad/missing sense data, sb[]: 70 00 05 00 00 00 00 0a 00 00 00 00 20 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 max sectors = 0/1, HPA is enabled EDIT3 Summary I bought card. Camera shows I can record with the new card longer (in two times) video than if I used old one with size 32GB. I formated the SD card on my PC with ext4 filesystem. I checked the capacity first time and it was about 30 GB. I formated the SD card back with exFat. I checked capacity on PC. It was still about 30GB. I inserted the SD card to my camera. Camera shows I can record video longer that using 32GB card as before. I reformated the SD card on an android device. Android device shows the card has 60 GB capacity. Then I inserted the card to PC. PC started showing correct capacity - 60GB. ADDED as Rinzwind asked It was added after I formated on the android device. So it shows about 64GB. # sgdisk --print /dev/sdb *************************************************************** Found invalid GPT and valid MBR; converting MBR to GPT format in memory. *************************************************************** Warning! Secondary partition table overlaps the last partition by 67108897 blocks! You will need to delete this partition or resize it in another utility. Disk /dev/sdb: 57626624 sectors, 27.5 GiB Logical sector size: 512 bytes Disk identifier (GUID): B5FDFA69-32D4-42B0-B8A3-B14DF7A513B5 Partition table holds up to 128 entries First usable sector is 34, last usable sector is 57626590 Partitions will be aligned on 2048-sector boundaries Total free space is 2014 sectors (1007.0 KiB) Number Start (sector) End (sector) Size Code Name 1 2048 124735487 59.5 GiB 0700 Microsoft basic data EDIT4 I created a file - 1GB size. dd if=/dev/zero of=1gb_file bs=1024 count=1048576 Copied it 60 times to the SD card for i in seq 1 60; do echo -n ($i) ; cp -v 1gb_file /media/alek/C8AE-0ADD/$i ; done (1)«1gb_file» -> «/media/alek/C8AE-0ADD/1» (2)«1gb_file» -> «/media/alek/C8AE-0ADD/2» (3)«1gb_file» -> «/media/alek/C8AE-0ADD/3» ... (57)«1gb_file» -> «/media/alek/C8AE-0ADD/57» (58)«1gb_file» -> «/media/alek/C8AE-0ADD/58» (59)«1gb_file» -> «/media/alek/C8AE-0ADD/59» (60)«1gb_file» -> «/media/alek/C8AE-0ADD/59» cp: error writing ‘/media/alek/C8AE-0ADD/60’: No space left on device cp: failed to extend ‘/media/alek/C8AE-0ADD/60’: No space left on device Only latest command failed because disk was full. So I could write about 60 GB to my SD card. And I tried to copy them back. This test passed too. So I do not think the SD card is counterfeit. EDIT5 as psusi asked. After I formated on the android device. lsblk NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT sda 8:0 0 698,7G 0 disk ├─sda1 8:1 0 171,2G 0 part / ├─sda2 8:2 0 7,6G 0 part ├─sda3 8:3 0 163G 0 part └─sda4 8:4 0 356,9G 0 part /home sdb 8:16 1 27,5G 0 disk └─sdb1 8:17 1 27,5G 0 part /media/alek/C8AE-0ADD sr0 11:0 1 1024M 0 rom EDIT6 as psusi asked # dd if=/dev/sdb of=/dev/null 57626624+0 records in 57626624+0 records out 29504831488 bytes (30 GB) copied, 1518,73 s, 19,4 MB/s Conclusion. It is a problem of SD card reader. A: I suppose I'll write up my conclusions as an answer now. The short answer is that your USB SD card reader is defective. It is reporting that the size of the card is smaller than it really is. When you format the card in your android device ( using its full capacity ), then mount it in your computer, you can't correctly access the full disk so you will quickly corrupt files. Return or otherwise get rid of your current reader and get a new one that properly recognizes the full capacity of the card.
{ "pile_set_name": "StackExchange" }
Q: Is there a .net framework method to generate a collection from a property of all items in a collection? I have myObjects = List(of myObject) myObject has Public Property myProperty as string Is there a framework method to produce myObjectProperties = List(of string) from each myObject.myProperty in myObjects? Obviously I can easily create one. I'm just wondering if there's a framework solution. A: Linq: myObjectProperties = myObjects.Select(x => x.myProperty).ToList() (sorry, it's C# and not VB.NET, but you are just talking about .NET ...)
{ "pile_set_name": "StackExchange" }
Q: How to identify binary and text files using Python? I need identify which file is binary and which is a text in a directory. I tried use mimetypes but it isnt a good idea in my case because it cant identify all files mimes, and I have strangers ones here... I just need know, binary or text. Simple ? But I couldn´t find a solution... Thanks A: Thanks everybody, I found a solution that suited my problem. I found this code at http://code.activestate.com/recipes/173220/ and I changed just a little piece to suit me. It works fine. from __future__ import division import string def istext(filename): s=open(filename).read(512) text_characters = "".join(map(chr, range(32, 127)) + list("\n\r\t\b")) _null_trans = string.maketrans("", "") if not s: # Empty files are considered text return True if "\0" in s: # Files with null bytes are likely binary return False # Get the non-text characters (maps a character to itself then # use the 'remove' option to get rid of the text characters.) t = s.translate(_null_trans, text_characters) # If more than 30% non-text characters, then # this is considered a binary file if float(len(t))/float(len(s)) > 0.30: return False return True A: It's inherently not simple. There's no way of knowing for sure, although you can take a reasonably good guess in most cases. Things you might like to do: Look for known magic numbers in binary signatures Look for the Unicode byte-order-mark at the start of the file If the file is regularly 00 xx 00 xx 00 xx (for arbitrary xx) or vice versa, that's quite possibly UTF-16 Otherwise, look for 0s in the file; a file with a 0 in is unlikely to be a single-byte-encoding text file. But it's all heuristic - it's quite possible to have a file which is a valid text file and a valid image file, for example. It would probably be nonsense as a text file, but legitimate in some encoding or other... A: If your script is running on *nix, you could use something like this: import subprocess import re def is_text(fn): msg = subprocess.Popen(["file", fn], stdout=subprocess.PIPE).communicate()[0] return re.search('text', msg) != None
{ "pile_set_name": "StackExchange" }
Q: static variables as global, and when are static objects garbage collected? I want to access a variable anywhere in the android app, even if I never open to view the Activity class that the variable is declared in. Is a static variable possible to use for this. and if i move around between different activities can i access this variable to modify and change it without losing the changes? i understand that shared preferences and sqlite database can be used to store variable for this purpose, however I wanted to know if I can safely use a static for this. my only worry is if for some reason while the app is still being used that the static variable will be garbage collected while the app is open and in use. also i did not want to make a Application class global variable, instead i wanted to know about just using a static variable in a one of java or android class of the app. A: Static variables cannot be eligible for garbage collection while the class is loaded. They can be collected when the respective class loader drops the class or is itself collected for garbage.
{ "pile_set_name": "StackExchange" }
Q: SocketIO4Net - Error initializing handshake with https://localhost/ I'm trying to use SocketIO4Net to connect with my node.js server via socket.io. Can't seem to get it to work, when it comes to HTTPS. Getting this: Error initializing handshake with https://localhost/ Couldn't find a solution in other similar questions. If you have other solutions to connect to socket.io sockets from C# feel free to share the information. A: .NET seems to block my self signed certificate. Implementing the RemoteCertificateValidationCallback seems to solve the problem. ServicePointManager.ServerCertificateValidationCallback += new System.Net.Security.RemoteCertificateValidationCallback(pass); private static bool pass(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors error) { return true; }
{ "pile_set_name": "StackExchange" }
Q: NDSolve doesn't solve my system of ODEs What is causing the error in this code? N0 = 4; μ = 2; ρ = 1; d = 1; n = 1; eqone = Flatten[ Join[ Table[x[i]''[t] == ϵ*(1 - x[i][t]^2)*x[i]'[t] - x[i][t] + d (z[t] - x[i][t]), {i, 0, N0}], {z'[t] == ρ*d/n (Sum[x[i][t] - z[t], {i, 0, N0}])}, z[0]==0, x[0][0] == 1, x[0]'[0] == .5, x[N0/2][0] == 0, x[N0/2]'[0] == 0}, Table[x[i]'[0] == 0, {i, 1, N0/2 - 1}], Table[x[i][0] == 0, {i, 1, N0/2 - 1}], Table[x[i]'[0] == 0, {i, N0/2 + 1, N0}], Table[x[i][0] == 0, {i, N0/2 + 1, N0}] ] ] and once I get my equations, I should be able to solve the differential equation, but it isn't working. I get a message that starts out: The function value is not a list of numbers with dimensions ... I think I have to flatten something again in the NDSolve, but I'm not entirely sure how to do that and why. eqtwo = NDSolve[eqone, {Table[x[i], {i, 0, N0}],z}, {t, 100}] A: This seems to be a combination of simple errors. If I give ϵ a value (I used 0.1), and fix some delimiter errors in eqone and add z properly to the list of unknowns in eqtwo, I get a solution. N0 = 4; μ = 2; ρ = 1; d = 1; n = 1; ϵ = 0.1; eqone = Flatten[ Join[Table[ x[i]''[t] == ϵ*(1 - x[i][t]^2)*x[i]'[t] - x[i][t] + d (z[t] - x[i][t]), {i, 0, N0}], {z'[t] == ρ*d/n (Sum[x[i][t] - z[t], {i, 0, N0}]), z[0] == 0, x[0][0] == 1, x[0]'[0] == .5, x[N0/2][0] == 0, x[N0/2]'[0] == 0}, Table[x[i]'[0] == 0, {i, 1, N0/2 - 1}], Table[x[i][0] == 0, {i, 1, N0/2 - 1}], Table[x[i]'[0] == 0, {i, N0/2 + 1, N0}], Table[x[i][0] == 0, {i, N0/2 + 1, N0}]]]; eqtwo = NDSolve[eqone, Append[Table[x[i], {i, 0, N0}], z], {t, 100}] {{x[0]->InterpolatingFunction[{{0.,100.}},<>], x[1]->InterpolatingFunction[{{0.,100.}},<>], x[2]->InterpolatingFunction[{{0.,100.}},<>], x[3]->InterpolatingFunction[{{0.,100.}},<>], x[4]->InterpolatingFunction[{{0.,100.}},<>], z->InterpolatingFunction[{{0.,100.}},<>]}} Edit The OP asked for more info about Append. This is a basic Mathematica function. I recommend reading the Wolfram docs on Append
{ "pile_set_name": "StackExchange" }
Q: equal sign with haskell literals What exactly happens in GHCi when I load a file with a line that says: 0=1 ? I was expecting that this would give an error but it doesn't seem to do anything at all. Does it do anything? I assume it's equivalent in GHCi to just saying "let 0=1". What does that do? A: The 0 in your let binding is actually a pattern match on the literal 0. I wasn't sure what was going on at first too, but you can confirm this by using strict pattern matching like so: Prelude> :set -XBangPatterns Prelude> let !0 = 1 in 0 *** Exception: <interactive>:13:5-10: Non-exhaustive patterns in pattern binding A: If you give the failing pattern match a name x, you can also force it like so: x @ 0 = 1 main = print x Which produces the error: FILE.hs: /path/to/FILE.hs:1:5-13: Irrefutable pattern failed for pattern x@0 A: 0=1 is just a pattern binding. Haskell 2010 Language Report describes 4.4.3 Function and Pattern Bindings decl → (funlhs | pat) rhs funlhs → var apat { apat } | pat varop pat | ( funlhs ) apat { apat } rhs → = exp [where decls] | gdrhs [where decls] gdrhs → guards = exp [gdrhs] guards → | guard1, …, guardn (n ≥ 1) guard → pat We distinguish two cases within this syntax: a pattern binding occurs when the left hand side is a pat; otherwise, the binding is called a function binding. Either binding may appear at the top-level of a module or within a where or let construct. Patterns have this syntax: pat → lpat qconop pat (infix constructor) | lpat lpat → apat | - (integer | float) (negative literal) | gcon apat1 … apatk (arity gcon = k, k ≥ 1) apat → var [ @ apat] (as pattern) | gcon (arity gcon = 0) | qcon { fpat1 , … , fpatk } (labeled pattern, k ≥ 0) | literal | _ (wildcard) | ( pat ) (parenthesized pattern) | ( pat1 , … , patk ) (tuple pattern, k ≥ 2) | [ pat1 , … , patk ] (list pattern, k ≥ 1) | ~ apat (irrefutable pattern) fpat → qvar = pat Language Report also states A pattern binding binds variables to values. A simple pattern binding has form p = e. The pattern p is matched “lazily” as an irrefutable pattern, as if there were an implicit ~ in front of it. So, 0 in 0=1 is just a pattern. In essence, 0=1 and x=1 are the same thing. They are both pattern bindings. The pattern is irrefutable, 0=1 does not fail, thus no error occurred and nothing happened. If we have the following top level declaration. Something will happen. x@(Just y) | z /= Nothing = Just 1 where z = Just 0 x and y are binding to Just 1 and 1.
{ "pile_set_name": "StackExchange" }
Q: How can I utilize global variables within the `WithCriteria` of my Cake Tasks? I have a number of tasks that use WithCriteria to specify when that Task should be run. That criteria is established in the main Setup method of the Cake script. However, when executing the script, I get a null reference exception... As you an see, the Paths property is null, even though within my Setup method I am settings that property. Why is this? How can I utilize global variables within my WithCriteria? A: The issue you're having is because with WithCriteria overload you're using the criteria is evaluated before the task is executed. In general this is fine with constants / state created before task are executed. With WithCriteria has two overloads the one you're using above public static CakeTaskBuilder<T> WithCriteria( this CakeTaskBuilder<T> builder, bool criteria ) As it takes a bool it's evaluated as the tasks created, which won't work if state is created & changed during setup or previous tasks, to solve this change you code to use the below overload public static CakeTaskBuilder<T> WithCriteria( this CakeTaskBuilder<T> builder, Func<bool> criteria ) This over load takes a Func<bool> criteria which is evaluated just before the task is executed, thus has access to any state created or modified before the task is executed. So the fix for your issue is just to add ()=> before your criteria and it'll be lazy loaded like this: Task("Test-NUnit") .WithCriteria(()=>DirectoryExists(parameters.Paths.Directories.NUnitTestResults)) .Does(()=> { });
{ "pile_set_name": "StackExchange" }
Q: Can "Dumb Starbucks" be legally considered Fair Use as satire or parody? About a year ago, a new, familiar-looking coffee shop opened in LA. Their reasoning for this was, basically, that it's making fun of the popular coffeehouse chain and is thus fair use: Naturally, it attracted a lot of attention and was later revealed that it was really a publicity stunt created by a comedian, but he still made a statement that "as long as we're making fun of Starbucks, we're allowed to use their corporate identity" (as seen here). Had Starbucks sued for trademark infringement (which they probably planned to do, but the thing was actually closed for operating without a valid public health permit), would the whole parody as fair use thing hold in court (or at least have some relevance in the case)? A: This is likely not fair use. At first blush it appeared similar to things one might see in The Onion (parody print and online newspaper) or other parody publications or shows (SNL, Key and Peele, etc.). In this case, the context would have likely been deemed transformative. However, since they are selling coffee called "Dumb Starbucks" while using their trademark, they would be be found liable if sued. You can parody a trademark brand, so long as the work is transformative such that the use of the brand goes from selling coffee to making a commentary in which the brand itself is relevant. Amendment I don't think this would pass the test as a parody/commentary. Originally, I failed to notice that they are actually selling coffee. This takes it out of fair use and they would almost certainly lose if sued. If they never sold the coffee, but just had it open as a performance art (like I had originally read this) giving the coffee away to complete the parody, I think they'd be fine. However, they are literally using the Starbucks logo, and selling the same product. This is clearly an infringement of their copyright and not fair use. Sorry for the confusion. A: In the UK, it would not be allowed, as the company is selling coffee while making it likely that customers will believe it is Starbucks coffee. As well as Starbuck being able to take action over the use of their trade mark, trading standards could take action as the company is clearly likely to deceive customers. A: Considering their own FAQ (as shown in the question) specifically states that they're only calling it a parody to try to get away using Starbucks' name and logo for the purpose of selling coffee, they almost certainly would not be able to get away with this in court were they sued by Starbucks. They openly admit that their intention is not parody at all, but rather an attempt to get away with trademark infringement. Their comparison to Weird Al's spoof of 'Beat It' is rather absurd, since the value of 'Eat It' is purely comedy, not just an attempt to rip off Michael Jackson's IP to sell records. Also, as a side note, Weird Al gets permission from the people he's parodying before he actually releases a parody (though he isn't legally required to do so thanks to fair use.) The only thing I can see here that they might possibly be poking fun at, ironically enough, is the parody fair use exception itself (i.e. by trying to make a ridiculous example of fair use.) If that were the intention, though, it isn't a very good parody, since such a use almost certainly wouldn't hold up as fair use.
{ "pile_set_name": "StackExchange" }
Q: Review focus on code or on solution? I was wondering what should be the focus of review. I thought the focus would have been more on: correctness (no syntax or logic error) readability (clarity, respect of coding standard ...) robustness (ability to handle edge cases) performance I've noticed, instead, that the discussion sometimes shifts on the fact that there might be other solutions that might be "better" without pointing to specific flaws of the code under review. What do you think? A: The review has to be driven by the situation of the poster and the shape and quality of the posted code. Sometimes the poster's approach is basically fine and the appropriate things to review are documentation, variable naming, layout, and so on. But often the overall strategy is poor and the review would be failing the poster if it didn't reflect that. It's important to keep an eye on the big picture. Code is only a means to the end of solving somebody's problem, and if the posted code is not solving that problem very well, there's no point in getting down into the details. The biggest issues have to be tackled first. For example: This poster was basically trying to invent his own database system. This poster was writing a parser with no separate lexical analysis stage. This poster was implementing bitwise operations on numbers by converting the numbers to lists of strings "0" and "1" and performing the operations elementwise. The need to rethink the algorithm often arises for optimization questions. Big speedups mostly come from finding better algorithms: replacing an \$Ω(n^2)\$ algorithm with one that's \$O(n)\$ usually beats any amount of loop unrolling and strength reduction and other piecewise optimizations. Some examples where merely discussing the poster's code would have been a gross disservice: A Burrows–Wheeler transform implemented using a \$Ω(n^3 \log n)\$ algorithm when an \$O(n \log n)\$ algorithm is available. A hacker cup solution that would take months to run to completion, when a better algorithm might run in a couple of seconds. And from today, a Project Euler solution which takes tens of minutes, when a better algorithm needs only a couple of seconds. A: I think a good question will point out the flaws in the original code. Its okay to point out alternate and better ways, but you should really point out what was wrong the original.
{ "pile_set_name": "StackExchange" }
Q: Sorting Gridview in Visual Basic I am trying to sort a gridview in visual basic using the following method, however the second line of code (Dim dv as DataView...) throws a NullReferenceException. When I debug the code and step through it, I can see that the DataTable dt has a value of "Nothing" after it is instantiated. Any help would be greatly appreciated. Dim dt As DataTable = grdExpProd.DataSource Dim dv As DataView = dt.DefaultView If (blnExTraining) Then dv.Sort = "ExpirationDate DESC" Else dv.Sort = "ExpirationDate ASC" End If grdExpProd.DataSource = dv grdExpProd.DataBind() A: After postback the DataSource of any Web-Databound-Control like GridView is Nothing (null in C#). Note that HTTP is stateless, all objects that are created in a page's life-cycle will be destroyed as soon as the page was rendered. So the solution is easy, select the DataSource again with the correct ORDER BY.
{ "pile_set_name": "StackExchange" }
Q: How to remove the slowness of this regex? I have the following Regex: (\d+\s+[-]\s+.*?(?=\s+-)|\d+\s+[-].*) Regex will use this text "Option 01 - Random phrase - Top Menu", "Option 02 - Another Random Phrase - Su Menu", "Option 03 - More 01 Phrase - Menu", "Option 04 - More Phrase -", "Option 05 - Simple Phrase" To stay like this 01 - Random phrase ", 02 - Another Random Phrase ", 03 - More 01 Phrase ", 04 - More Phrase ", 05 - Simple Phrase ", The function of this Regex is to get the number with dash at the beginning, and go before the last dash. Ex: dfhdjfhdjf01 - text text - dkfdçsjf When there is no trace in the end basically this happens: dfhdjfhdjf01 - text text dkfdçsjf However, debugging this regex on regex101.com accuses you of having 63 to 122 steps. That is, this regex is very slow. Before criticizing the question, I have read all the documentation of the regex, I want you to know that I am referring to specific terms .. A problem that needs to be solved. After all, is not the site for this? Tell me, how am I going to solve the slowness of this regex? A: You should not worry too much about the steps you see at regex101.com, because C# regex library is very reliable. If you test a simple regex like (?s)a.*?b at regex101 with a very long string, it will report catastrophic backtracking while it will work just fine in C# code. There is a way to improve your pattern since it has some redundancy: see the repeating \d+\s+[-] pattern. All you need is \d+\s+-.*?(?=\s+-|$) See the regex demo at regex101 and RegexStorm. If the .*?(?=\s+-) should only match if there is whitespace after -, use \d+\s+-(?:\s.*?(?=\s+-)|.+) See another demo 1 (fewer steps :)) / demo 2. If you want to optimize it further, you might want to study the unroll-the-loop principle that leads to \d+\s+-(?:\s+\S*(?:\s(?!\s*-)\S*)*|.+) See this regex demo (the fewest step amount). Here, \S*(?:\s(?!\s*-)\S*)* is the equivalent (almost) of .*?(?=\s+-|$), but is more efficient as the chunks up to a whitespace are matched in "batches", the checks for a hyphen are made only when a whitespace is encountered. Details \d+ - 1+ digits \s+ - 1+ whitespaces - - a hyphen .*?(?=\s+-|$) - any 0+ chars, as few as possible, up to the first occurrence of 1+ whitespaces and - or up to the end of the string. (?:\s.*?(?=\s+-)|.+) - a non-capturing group: \s.*?(?=\s+-) - whitespace, 0+ chars as few as possible, up to 1+ whitespaces and - | - or .+ - the rest of the string. \S*(?:\s(?!\s*-)\S*)* : \S* - 0+ non-whitespace chars (?:\s(?!\s*-)\S*)* - 0 or more repetitions of \s - a whitespace (?!\s*-) - not followed with 0+ whitespaces and - \S* - 0+ non-whitespace chars
{ "pile_set_name": "StackExchange" }
Q: conditional select with time adding calculation I have this table: id | PlateNumber | ImgDate | ImgTime| 1 | abc123 | 2020-03-01 | 09:10:33| 2 | qwe128 | 2020-03-02| 09:13:39| 3 | abc123 | 2020-03-01| 09:11:21| So, there are too many repeated plate numbers based on image capturing time. I need a select statement that returns repeated records only when there is a time difference of more than 3 minutes. I hope that this makes sense. Please help Thank you guys! A: You need to provide a bit more info, but you would want to compare the current row with the previous one (for each PlateNumber). You can do that using an analytical function like LAG. WITH CTE as ( Select id ,PlateNumber ,ImgDate ,ImgTime ,LAG(ImgDate) OVER (PARTITION BY PlateNumber ORDER BY ImgDate,ImgTime) as PreviousDate ,LAG(ImgTime) OVER (PARTITION BY PlateNumber ORDER BY ImgDate,ImgTime) as PreviousImgTime FROM YourTable ) Select id ,PlateNumber ,ImgDate ,ImgTime FROM CTE WHERE (PreviousDate is null and PreviousImgTime is null) -- to keep the first occurence OR ( DATEDIFF(second, DATEADD(day, 0, DATEDIFF(day, 0, PreviousDate)) + DATEADD(day, 0 - DATEDIFF(day, 0, PreviousImgTime), PreviousImgTime) , DATEADD(day, 0, DATEDIFF(day, 0, ImgDate)) + DATEADD(day, 0 - DATEDIFF(day, 0, ImgTime), ImgTime) ) > 180 ) If your columns are DATE and TIME datatype OR ( DATEDIFF(second, cast(PreviousDate as DATETIME) +cast(PreviousImgTime as DATETIME) , cast(ImgDate as DATETIME) + cast(ImgTime as DATETIME), ) > 180 )
{ "pile_set_name": "StackExchange" }
Q: Find the time (in seconds) Tom would need to catch Jerry I have a question about The 2015 ACM-ICPC Asia Phuket Regional Programming Contest Problem I.Tom and Jerry.The problem is as follow. Tom and Jerry are very fond of cat and mice games, which might be rather obvious to you. Today they are playing a very complicated game. The goals are simple as usual though, Jerry would be running and Tom would have to catch Jerry. However, today Jerry is running on a perfect circular path with radius R meters, at a constant speed of V m/s. Initially Tom is sitting at the very center of the circle. He wants to catch Jerry as soon as possible, but we all know, Tom is not very intelligent. Instead of calculating an optimal direction to catch Jerry, he is just running towards Jerry. As Jerry is also moving, the path Tom has taken start to look like a curve.At any given moment, Tom’s position is between Jerry’s current position and the center of the circle. Tom is also moving at a constant speed of V m/s, same speed as Jerry. Find the time (in seconds) Tom would need to catch Jerry. Input file has T (T <= 10000) test cases, each case consists of two integer R and V. Here, 0 < R, V <= 10000. For each test case, print the case number and the time Tom will need to catch Jerry. Floating point rounding error lower than 1e-5 will be ignored by the judge. Example Sample Input 4 45 100 5 1547 1000 10000 5668 5467 Sample Output Case 1: 0.70685835 Case 2: 0.00507691 Case 3: 0.15707963 Case 4: 1.62854830 How can I solve the problem? I can't post image.In the question,it has an image.You can see the image in the below link. http://i.stack.imgur.com/dfzU4.jpg Thank in advance. A: You're looking at solving something like this:
{ "pile_set_name": "StackExchange" }
Q: Compare graphs by using different slopes I have two equations First one is $\beta q_1 x_1 + q_2 x_2 =I-\gamma$ Second one is $q_1x_1+q_2 x_2=I$ where $\beta q_1\lt q_1$ and $I-\gamma\lt I$ and all are positive. The slope of the first model is =-$q_2\over\beta q_1$ And the slope of the second model is =-$q_2\over q_1$ I think the first slope is greater than the second slope. Right? I am not sure. Please check the comparison again. Then, how are their graphs? I posted below. First figure or second figure represents the equations ? Which graph is true? The second one seems more correct to me. Am I right? A: The second one is correct! Because $I - \gamma < I$, you get $\frac{I - \gamma}{q_2} < \frac{I}{q_2} $ That enables you to find the intersections with the $x_2$ axis like you have in the second drawing. On the other hand, the slopes you found are wrong! Or at least the ones yoi wrote in your question. Please review the steps you did. Can you find the mistake? As you ask, I will do the second equation: $$q_1 x_1 + q_2 x_2 = I \iff q_2 x_2 = -q_1x_1 + I \iff x_2 = -\frac{q_1}{q_2}x_1 + \frac{I}{q_2}$$
{ "pile_set_name": "StackExchange" }
Q: What happens to a branch when the master is deleted? Say I create a branch of folder Master in my repository and make some commits to it. I used TortoiseSVN's Create Branch command, which executes: svn copy FROMURL TOURL to create the branch on the server using the HEAD revision. Later, the SVN administrator deletes the Master folder, but leaves my branch alone. Since SVN branches are shallow copies, is my branch now corrupt, or does SVN smartly make a deep copy at the deletion of Master? A: Branch has a reference to a specific revision. Your branch should be safe. SVN uses references most of the time.
{ "pile_set_name": "StackExchange" }
Q: Wordpress: Custom post type with no single page I am using wordpress as cms for a small website and i do not have a great deal of experience with wordpress. I am trying to create a custom post type with no single.php layout. On the homepage of design of the website, there is a ticker that displays ... "Latest news" - I am able to create a custom post type, loop through it and display all news on the homepage. However this is leading to unintentional creation of links of each individual news item. Which i don't need. How do i get rid of it? - is there a way to have custom post type with no "permalink" URL? i searched google for the issue and seems like only way is to just use forced url redirection. But i wanted to know if there is a better way to achieve my goal? is there anything else other than custom post types that can be used? A: If you are infact talking about linkable titles from your loop output then @JP Lew is correct. Remove the tag from the loop. In addition: The post type will show up on your sitemap and they will be crawled by search engines. You must use a robots.txt file and include: User-Agent: * Disallow: /wp-content/plugins/ Disallow: /custom_type/ to tell bots to forget about directories that do not contain content like these custom post types and wp-content areas like the plugins directory. Also within your register_post_type() function's arguments the 'public' argument should be set to false for several related reasons including exclusion from WordPress search results, wp-admin etc.
{ "pile_set_name": "StackExchange" }
Q: How to control length of the result of string.format(bool_value) in Python? What the equivalent way to str.format function for converting booleans into strings? >>> "%5s" % True ' True' >>> "%5s" % False 'False' Please note the space in ' True'. This always makes the length the same for 'True' and 'False'. I've check the methods in this post: How are booleans formatted in Strings in Python? None of them can do the same thing. A: You can use type conversion flags to do what you wanted: '{:_>5}'.format(True) # Oh no! it's '____1' '{!s:_>5}'.format(True) # Now we get '_True' Note the !s. I used an underscore to show the padding more clearly. Relevant documentation: 6.1.3. Format String Syntax [...] The conversion field causes a type coercion before formatting. Normally, the job of formatting a value is done by the __format__() method of the value itself. However, in some cases it is desirable to force a type to be formatted as a string, overriding its own definition of formatting. By converting the value to a string before calling __format__(), the normal formatting logic is bypassed. Three conversion flags are currently supported: '!s' which calls str() on the value, '!r' which calls repr() and '!a' which calls ascii(). Some examples: "Harold's a clever {0!s}" # Calls str() on the argument first "Bring out the holy {name!r}" # Calls repr() on the argument first "More {!a}" # Calls ascii() on the argument first A: I found that "{:>5}".format(str(True)) works fine. The output is exactly the same as "%5s" % True, ie ' True'. So the length of "{:>5}".format(str(bool_value)) is alway 5, no matter bool_value is True or False. Of course you may change the length or the alignment direction as you want. eg. "{:6}".format(str(True)) outputs 'True '.
{ "pile_set_name": "StackExchange" }
Q: Get content from a text file to String (Android) (FileNotFound) (Java) I want to get the text from a text file I have in my project (android studio) and make that text to a string. I am currently having trouble getting the correct path or something. I'm using two methods I found here on Stackoverflow to get the textfiles to Strings. These are the methods: public static String convertStreamToString(InputStream is) throws Exception { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line).append("\n"); } reader.close(); return sb.toString(); } public static String getStringFromFile (String filePath) throws Exception { File fl = new File(filePath); FileInputStream fin = new FileInputStream(fl); String ret = convertStreamToString(fin); //Make sure you close all streams. fin.close(); return ret; } And I'm calling the methods like this, and I have tried all kinds of pathing but none seems to work: Log.i("er0r", Solve.getStringFromFile("\\tables\\lowerLayer\\cross\\whiteRed.txt")); This is just an attempt to print the content of the textfile. I get the following error: java.io.FileNotFoundException: .\tables\lowerLayer\cross\whiteRed.txt: open failed: ENOENT (No such file or directory) This is how I have ordered my packages: http://imgur.com/a/rK9R5 How can i fix this? Thanks EDIT: public String LoadData(String inFile) { String str = ""; try{ StringBuilder buf=new StringBuilder(); InputStream json=getAssets().open(inFile); BufferedReader in= new BufferedReader(new InputStreamReader(json, "UTF-8")); while ((str=in.readLine()) != null) { buf.append(str); } in.close(); } catch (Exception e) { Log.e("er0r", e.toString()); } return str; } Tried this with inFile = "assets\whiteRed.txt" Got me this error: java.io.FileNotFoundException: assets\whiteRed.txt ADDITIONAL CODE: Constructor of the class that's calling the LoadData method public class Solve { private Context context; //constructor public Solve(Context context){ this.context = context; } A: If at design time, in Android Studio, you want to supply files which your app can read at run time then put them in the assets folder of your Android Studio project. Maybe you have to create that assets folder first. After that your app can read those files from assets using assets manager. Just google for how to do this exactly. All has been posted here many times.
{ "pile_set_name": "StackExchange" }
Q: ListView not showing ListViewItems Hopefully this is an easy question! I have a listview with some items (These items do not change at all, so I am adding them in XAML not dynamically). Here is the code: <ListView x:Name="SelectImageBox" ScrollViewer.HorizontalScrollBarVisibility="Disabled" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" Margin="72,53,60,20" Background="Transparent" Opacity="1"> <ListView.ItemsPanel> <ItemsPanelTemplate> <WrapPanel IsItemsHost="True"/> </ItemsPanelTemplate> </ListView.ItemsPanel> <ListViewItem> <DynamicResource ResourceKey="Book"/> </ListViewItem> <ListViewItem> <DynamicResource ResourceKey="Book"/> </ListViewItem> <ListViewItem> <DynamicResource ResourceKey="Book"/> </ListViewItem> <ListViewItem> <DynamicResource ResourceKey="Book"/> </ListViewItem> </ListView> My problem is that in the designer, it shows the 4 books. However, when I run the program, none of the items are displayed. If anyone could possibly explain what I'm missing? A: Okay, I fixed the problem. The listview items were getting added, except the image that they were using was being used by another control, the fix was to change the declaration in the resources to include x:Shared="False" (This does NOT show up in intellisense, but is legit code.
{ "pile_set_name": "StackExchange" }
Q: display variable value each n iterations with condition outside the loop When I have to display the variable value every n iterations of a for loop I always do something along these lines: for ii=1:1000 if mod(ii,100)==0 display(num2str(ii)) end end I was wondering if there is a way to move the if condition outside the loop in order to speed up the code. Or also if there is something different I could do. A: You can use nested loops: N = 1000; n = 100; for ii = n:n:N for k = ii-n+1:ii-1 thingsToDo(k); end disp(ii) thingsToDo(ii); end where thingsToDo() get the relevant counter (if needed). This a little more messy, but can save a lot of if testing.
{ "pile_set_name": "StackExchange" }
Q: How to increase number of recent files in Sublime Text 3? Is it possible to increase the number of recent files that appear in the File -> Open recent menu in Sublime Text 3 (Ubuntu)? I have already read Increase number of recent projects in Sublime Text 2? And I can't find this ~/Library folder at my PC. I can find ~/.config/sublime-text-3/Packages but there's no "Default" subfolder inside. A: On OSX, at least, the Default.sublime-package is in the application itself: /Applications/Sublime Text.app/Contents/MacOS/Packages/Default.sublime-package. To edit the config easily without changes being overwritten on update, you need a copy of Main.sublime-menu in your Packages directory ~/Library/Application Support/Sublime Text 3/Packages/Default/Main.sublime-menu The easiest way to effect these changes is to install the excellent PackageResourceViewer by skuroda (using Package Control), then: Command+Shift+p type 'resource' and select 'PackageResourceViewer: Open resource' you see a list of available packages: select 'Default' select 'Main.sublime-menu' PackageResourceViewer now copies Main.sublime-menu into the correct location and opens the new file for editing (note: the file doesn't seem to be actually created in the filesystem until hitting save, and updates seem immediately visible without requiring an update). As per Rufus_12's answer, alter the number of open_recent_folder and open_recent_file statements that appear, increasing the index each time. { "command": "open_recent_folder", "args": {"index": 0 } }, { "command": "open_recent_folder", "args": {"index": 1 } }, { "command": "open_recent_folder", "args": {"index": 2 } }, { "command": "open_recent_folder", "args": {"index": 3 } }, { "command": "open_recent_folder", "args": {"index": 4 } }, { "command": "open_recent_folder", "args": {"index": 5 } }, { "command": "open_recent_folder", "args": {"index": 6 } }, ...continue as many times as necessary... Update re: maintainability As @drevicko points out, this method will not auto-update with Sublime, and may even cause conflicts in future. @James' answer (editing the Packages/User/Default/Main.sublime-menus) is indeed update-proof, but does, unfortunately, result in a duplicate sub-menu (the duplicate entries appear for me at the very bottom of the menu). The user settings file is merged with the defaults, but in a manner which results in duplicate keys. I find that if I update Packages/Default/Main.sublime-menus, then that file completely replaces the default (delete chunks and see your menus disappear in real time!) - my new file and the defaults are not merged. In order to: a) avoid a duplicate entry, and b) stay current with Sublime updates, I can't see an alternative to tracking changes to the file using git, and when Sublime updates, repeating the Open Resource process (overwriting your edits), then reverting only relevant changes. A: The Default package in Sublime Text 3 on Linux is stored in (assuming you used the .deb installer) /opt/sublime_text/Packages/Default.sublime-package. Default.sublime-package is a ZIP file, if you open it and extract the Main.sublime-menu file from it into ~/.config/sublime-text-3/Packages/Default/Main.sublime-menu, it can then be edited the same way as the linked answer describes. Alternatively run following commands which will create the Default directory and extract the Main.sublime-menu file into it: mkdir ~/.config/sublime-text-3/Packages/Default/ unzip -p /opt/sublime_text/Packages/Default.sublime-package Main.sublime-menu > ~/.config/sublime-text-3/Packages/Default/Main.sublime-menu A: Add this Main.sublime-menu to your %APPDATA%\Sublime Text 3\Packages\User folder. You will see an added File Menu child named Open Recent More, giving you the next same-amount of recent files/folders. (If only I could position it in the menu where I want it, though.) [ { "caption": "File", "mnemonic": "F", "id": "file", "children": [ { "caption": "Open Recent More", "mnemonic": "R", "children": [ { "command": "open_recent_file", "args": {"index": 8 } }, { "command": "open_recent_file", "args": {"index": 9 } }, { "command": "open_recent_file", "args": {"index": 10 } }, { "command": "open_recent_file", "args": {"index": 11 } }, { "command": "open_recent_file", "args": {"index": 12 } }, { "command": "open_recent_file", "args": {"index": 13 } }, { "command": "open_recent_file", "args": {"index": 14 } }, { "command": "open_recent_file", "args": {"index": 15 } }, { "command": "open_recent_file", "args": {"index": 16 } }, { "caption": "-" }, { "command": "open_recent_folder", "args": {"index": 8 } }, { "command": "open_recent_folder", "args": {"index": 9 } }, { "command": "open_recent_folder", "args": {"index": 10 } }, { "command": "open_recent_folder", "args": {"index": 11 } }, { "command": "open_recent_folder", "args": {"index": 12 } }, { "command": "open_recent_folder", "args": {"index": 13 } }, { "command": "open_recent_folder", "args": {"index": 14 } }, { "command": "open_recent_folder", "args": {"index": 15 } }, { "command": "open_recent_folder", "args": {"index": 16 } }, { "caption": "-" } ] } ] } ]
{ "pile_set_name": "StackExchange" }
Q: OS X Web View App - Won't Load Local .html Web Page I have the following code in an AppDelegate.m file that opens Google when I open my app. I am trying to change it to open a .HTML web page I copied into my Xcode project but it is not working. I am using Xcode 4.5.2. The code that works to open Google is: @implementation MDAppDelegate - (void)applicationDidFinishLaunching:(NSNotification *)aNotification { NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.google.com"]]; [self.webView.mainFrame loadRequest:request]; } I tried changing it to (so that it would load my test.html file I put in the project folder but the app just comes up blank now). What am I missing? @implementation MDAppDelegate - (void)applicationDidFinishLaunching:(NSNotification *)aNotification { NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"test.html"]]; [self.webView.mainFrame loadRequest:request]; } A: As long as your test.html is copied at the root of your project (make sure it's also copied to your final app bundle, huh? - check Build Phases) you can load it up your Web View using this code : NSString *path = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"html"]; NSURL* fileURL = [NSURL fileURLWithPath:path]; NSURLRequest* request = [NSURLRequest requestWithURL:fileURL]; [self.webView.mainFrame loadRequest:request];
{ "pile_set_name": "StackExchange" }