pid
int64 2.28k
41.1M
| label
int64 0
1
| text
stringlengths 1
28.3k
|
---|---|---|
23,043,066 | 0 | <p>Apple's MapKit only used Google Maps up to iOS 5.1 as stated in the <a href="https://developer.apple.com/library/ios/documentation/MapKit/Reference/MKMapView_Class/MKMapView/MKMapView.html" rel="nofollow">"Important" note in the <code>MKMapView</code> class reference</a>:</p> <blockquote> <p><strong>Important</strong>: In iOS 5.1 and earlier, the Map Kit framework uses the Google Mobile Maps (GMM) service to provide map data.</p> </blockquote> <p>Since then, and including iOS 7.1, MapKit uses Apple's mapping service instead. </p> <p>However, regardless of iOS version, the developer is not charged for using maps.</p> |
8,640,011 | 0 | What does "visibility" refer to in the Activity Lifecycle? onPause vs onStop? <p>The Activity Lifecycle is giving me headaches. The documentation at <a href="http://developer.android.com/reference/android/app/Activity.html" rel="nofollow">http://developer.android.com/reference/android/app/Activity.html</a> is so darn ambiguous when it describes the concept of visibility, that I can't figure out when <code>onStop()</code> is called vs <code>onPause()</code>.</p> <p>Compare the following two statements from the documentation:</p> <blockquote> <p><em>(taken from right beneath the lifecycle diagram)</em></p> <p>The <code>onStart()</code> and <code>onStop()</code> methods can be called multiple times, as the activity becomes visible and hidden to the user.</p> </blockquote> <p>vs</p> <blockquote> <p><em>(further down in the blue table with the "killable" columns)</em></p> <p><code>onPause()</code> Called when the system is about to start resuming a previous activity.</p> </blockquote> <p>What I'd understand from the first quote, is that <code>onStop()</code> is called on activity <code>A</code> when <code>A</code> is "hidden". "Hidden" I'd guess is referring to when another activity <code>B</code> has been resumed and is completely covering actvity <code>A</code>. But the second quote then states that <code>onPause()</code> is called when another activity is about to start resuming. Wouldn't that completely hide activity A as well? Both cases seem to imply that that activity <code>A</code> becomes "hidden", no? According to my likely faulty interpretation, <code>onPause()</code> and <code>onStop()</code> are called in identical situations.</p> <p>The documentation also seems to differ between being hidden (<code>onStop()</code> gets called) and being partial visibility (<code>onPause()</code> gets called). But when is an activity still partially visible? Do they mean literally? Or can an activity still be deemed "partially visible" when it has started up a new activity (activity calls startActivityForResult and starts a date picker activity) that covers the entire screen? Surely the activity is not going get onStop invoked? Its supposed to receive a result any moment!</p> <p>So I'm trying to figure out what I'm not getting. I understand that a call to onPause is guaranteed. That would be when activity <code>A</code> loses focus (device enters sleep mode, screenlock, etc), a different activity <code>B</code> takes the foreground (where activity <code>B</code> may or may not have been initiated by activity <code>A</code>). But at which point is the <code>onStop()</code> invoked on activity <code>A</code>?</p> <p>Is it matter of how many activities have been piled ontop of activity A on the activity stack? Are there two different definitions of "visiblity" at play?</p> <p>Sorry about the wall of text, but I'm really frustrated :S</p> <p>So the question stands: Precisely in which situations is an activity deemed "hidden" such that <code>onStop()</code> is called on it?</p> <p><strong>EDIT:</strong></p> <p>I inserted Toast notifications in each onX method, and discovered some additional weirdness:</p> <ol> <li>Pressing the Home button will <em>always</em> call onStop(). But starting up the application won't call <code>onRestart()</code>. Instead it calls <code>onCreate()</code>. This seems strange to me, but ok...</li> <li>When the "USB Mass Storage" activity is started on top of the main activity, <code>onStop()</code> is called. And when exiting the usb storage activity, returning to the main activity, <code>onRestart()</code> is called, instead of <code>onCreate()</code>.</li> <li>When the device goes into Sleep mode and is waken up, the activity only goes through the <code>onPause()</code> and <code>onResume()</code> cycle.</li> </ol> <p>The last point was expected (although I can't get it to fit in the lifecycle diagram). But whats up with 1. and 2. ?</p> <p>In the first point, I was expecting a call to <code>onRestart()</code> when starting the activity again. Why did it deallocate the activity and call <code>onCreate()</code> instead?</p> <p>And take a look at point nr 2: According to the documentation: when "another activity comes in front of the activity", <code>onPaused()</code> should be called. Isn't that what happened when the USB Storage activity came up? It didn't call <code>onPause()</code>, it went through the <code>onStop()</code> - <code>OnRestart()</code> cycle! Obviously, the documentation doesn't consider that a case where "another activity comes in front of the activity". So what really happened?</p> |
23,336,248 | 0 | <p>It works for me in my app on Jetty:</p> <p></p> <pre><code><error-page> <error-code>500</error-code> <location>/WEB-INF/jsp/error.jsp</location> </error-page> </code></pre> |
19,392,436 | 0 | Updating many-to-many relations in JayData <p>My OData model contains a pair of entities with many-to-many relationship (Parents-Children). I am trying to add a child entity to a parent's Children navigation property, but calling saveChanges() afterwards has no effect at all. The code looks something like:</p> <pre><code>// both 'parent' and 'child' are attached to the context // both have their navigation properties empty parent.Children.push(child); context.saveChanges(); </code></pre> <p>I have also tried:</p> <pre><code>parent.Children = parent.Children.concat([child]); parent.Children = [child]; </code></pre> <p>But to no avail, it still doesn't work - the saveChanges() call doesn't make any requests to the service, as if there is nothing to update.</p> <p>I'd really appreciate an example of how to work with many-to-many relations using JayData, and some help dealing with the issue described above. Thanks</p> |
3,751,827 | 0 | <p>There are probably a lot of ways, but why not treat direction as a optional argument, which when not set indicates a reset condition.</p> <pre><code>function changestart(direction) { var startElement = $("#startID"); if ( direction ) { var rowsElement = $("#maxrows"); var rowsValue = parseInt(rowsElement.val()); var value = parseInt(startElement.val()); startElement.val(direction == "forward" ? value + rowsValue : direction == "back" ? value - rowsValue : 1); } else { startElement.val( 0 ); } } $("#previous").click(function(){changestart('back');}); $("#next").click(function(){changestart('forward');}); // not working $("#lookup").click(function(){changestart();}); </code></pre> |
39,750,079 | 0 | <p>Process exited with singal 11 (segmentation fault). Typically, it means process unexpectedly crashed because of some error in memory usage, and php just can't handle that error in any way. You will get same error using apache+mod_php, apache+mod_fcgid or any other configuration.</p> <p>In my practice, segfault gives you no useful error message in all cofigurations. The only real way to debug it is <strong>strace</strong>. One-liner to attach strace to all php processes running:</p> <pre><code>strace -f -F -s1000 -t -T `ps aux | grep -E 'apache|php|httpd' | awk '{print "-p" $2}' | xargs` </code></pre> <p>If the error is hard to reproduce, you can use <strong>xdebug</strong> php-module. You need to install it like that:</p> <pre><code>apt-get install php5-xdebug </code></pre> <p>or</p> <pre><code>yum install php-pecl-xdebug </code></pre> <p>for CentOS. For automatic tracing of all processes add to config:</p> <pre><code>xdebug.auto_trace=On </code></pre> <p>And you'll get traces, default path is:</p> <pre><code>xdebug.trace_output_dir => /tmp => /tmp xdebug.trace_output_name => trace.%c => trace.%c </code></pre> <p>So your trace will have name /tmp/trace.$PID.xt</p> <p>There you should be able to see last called fuction before process crash.</p> |
21,132,305 | 0 | why this message come in php:notice undefined offset:2 <p>I want to use the project PHP Weather 2.2.2 but it has many problems here is a code </p> <pre><code>function get_languages($type) { static $output = array(); if (empty($output)) { /* I use dirname(__FILE__) here instead of PHPWEATHER_BASE_DIR * because one might use this function without having included * phpweather.php first. */ require(dirname(__FILE__) . '/languages.php'); $dir = opendir(dirname(__FILE__) . '/output'); while($file = readdir($dir)) { // I got a problem in this line below if (ereg("^pw_${type}_([a-z][a-z])(_[A-Z][A-Z])?\.php$", $file, $regs)) { // After i change it to the line mentioned below i got error undefined offset:2 in line 2 mentioned below // how to correct this error or is there any way to correct this code if(preg_match("#^pw_${type}_([a-z][a-z])(_[A-Z][A-Z])?\.php$#", $file, $regs)) { $output[$regs[1] . $regs[2]] = $languages[$regs[1] . $regs[2]]; } } closedir($dir); } asort($output); return $output; } </code></pre> |
9,903,569 | 0 | <p>You can supply a comparison function to the <code>sort</code> method:</p> <pre><code> theArray.sort(function(a, b){ if (a.Field2 == b.Field2) return 0; if (a.Field2 < b.Field2) return -1; return 1; }); </code></pre> |
3,971,782 | 0 | What to use for a datagrid with a lot of data? <p>Found this interesting interview question:</p> <p>You need to display the sales data for your division for the past 5 years in a DataGrid on a Web Form. Performance is very important. What would be the best strategy to use in retrieving the data?</p> <ul> <li>a)Use a DataReader object to retrieve the data for the DataGrid.</li> <li>b)Use a DataSet object to retrieve the data for the DataGrid.</li> <li>c)Use a simple select statement as the data source for the DataGrid.</li> <li>d)Use a cached XML file as the data source and retrieve the data with a DataSet.</li> </ul> <p>My answer is c) but I am not too sure Can anyone point me to the right answer and explain it to me please Thanks</p> |
32,319,007 | 0 | Multiple FileUploads with Multiple Submit Buttons <p>I have for example 5 fileupload controls and Also I have a submit button for each of them (in front of each fileupload control) which will upload that fileupload's selected file(s).</p> <p>But There is a problem, when I click on (for example) second submit button to upload second fileupload's file(s), we will have a post back and other fileupload's file(s) will reset to empty. How can I manage such situation so when the user click on a submit button, the related fileupload's file(s) upload and the other fileupload's file(s) stay in their states. Hope I'm clear enough.</p> <p>A Picture for better Result:</p> <p><a href="https://i.stack.imgur.com/zrJoC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zrJoC.png" alt="enter image description here"></a></p> |
28,660,442 | 0 | <p>Strictly speaking, this is not exacly a Scalding question but you can use something like <a href="http://commons.apache.org/proper/commons-jexl#A_Brief_Example" rel="nofollow">Apache Commons JeXL</a> to execute formulas dynamically. So you would read the formula from the 2nd file, give it first file record object as a context and execute it.</p> |
36,961,614 | 0 | <p><strong>UPDATE SOLUTION FOUND!</strong> well the solutionin fact deleted some random files so I have taken it off until I figure out why.</p> <p>I leave this important note from before</p> <p><strong>ANYTIME YOU USE CRON</strong> I cannot emphasize enough the importance of specifying completely the full path of all sh files, files in arguments and any files you want to pipe output too such as >> /mydirectorywhereiwantit/output.txt in full in both your crontab file and your sh files script files. </p> <p>As I learned <strong>cron will look for files and write files in whatever directory it happens to be in while bashing</strong> and that can get EXTREMELY confusing if that is a different directory from where you normally type from the terminal. SO FULLY SPECIFY ALL PATHS TO ALL FILES IN BOTH CRONTAB AND IN THE CALLED SH SCRIPT FILES AND IN ARGUMENTS!</p> <p>Thanks to John Mark Mitchell who so kindly offer so many possible solutions.</p> |
40,682,361 | 0 | TFS access rights for revoking some rights to project collection admins <p>I am using Visual Studio Team Services (VSTS). I have to create some Project Collection Administrators only for administrative purpose. At the same time, there will be few projects where all the administrators will not have all rights to those projects. Since rights are inherited, rights cannot be revoked from those administrators and given to some normal users only, few of those users may be project collection administrators also.</p> <p>Is it possible to achieve this?</p> <p>Thanks</p> |
4,424,235 | 0 | <p>In my case i found out it was division by zero</p> |
36,009,744 | 0 | FabricJS export relative to canvas <p>I'm building a authoring tool in FabricJS which is meant to export something for android devices. It's decided that I will support only 6/9 screen ratio (other screens will get black borders). My problem is that I open the page on my pc, add and edit some elements and export ( using the fabricjs serializer ) and then I open on a laptop (different display size), the canvas gets resized correctly (with some js magic) but the elements are still at the same location and same size as on the big display . The problem is that FabricJS does not create elements relative to canvas size.</p> <p>I can write my own export/load functions, but it feels wrong because each element has <em>width</em>, <em>height</em>, <em>scaleX</em> and <em>scaleY</em>. Using the handles changes the scale for some reason. This leads me to think that there is something like a canvas scale, but there is not.</p> <p>Am I missing something? How does one go about exporting and then opening on a different screen, but maintaining the canvas ratio and having elements relative to the canvas size.</p> |
5,422,768 | 0 | <pre><code>$catname = str_replace('-', ' ', $catname); </code></pre> |
30,551,958 | 0 | <p>This may be further off topic than you want to go but <a href="http://nsubstitute.github.io/" rel="nofollow">NSubstitute</a> is a great mocking library that handles this very well. In NSubstitute it's just:</p> <pre><code> var mock = Substitute.For<IInterface>(); var obj = new MyClass(); await obj.Run(); Received.InOrder(() => { mock.MethodOne("foo"); mock.MethodTwo("foo"); }); </code></pre> |
39,796,869 | 0 | <p>Looks like you want the vector product i.e. outer join. But to have a join you need a column with rows matching. A trick here would be to create a new column with just a single value like "1" for all of the rows (use "Insert Calculated Column" - be sure to freeze the column so you can join to it later). Then do a full outer join of that table with a copy of itself (use the "Insert Columns" feature for the join) using the column with that dummy column as the key field. You will then get the combinations you showed above, but it will also have rows where the keys matched.</p> <p>To remove the matches, you can easily create a new column with an expression testing if the primary keys match like:</p> <pre><code>if([Location]=[Location(2)],"Match","NoMatch") </code></pre> <p>Then filter to the matching rows and delete if you don't want them in the data set.</p> <p>You can certainly ask Spotfire questions here, but you can also try the Spotfire section of the TIBCO Community here:</p> <p><a href="https://community.tibco.com/products/spotfire" rel="nofollow">https://community.tibco.com/products/spotfire</a></p> |
1,561,630 | 0 | Optimizing images in a jar-file <p>Is there an advantages to putting all my small widget graphics in one single png-file, which is loaded once, and then creating ImageIcons for buttons and such from sections of this? (Normally I would just use <code>new ImageIcon(aClass.class.getResource("/path/with/image.png"))</code>.) What would be a good way of doing this?</p> |
14,858,674 | 0 | <p>The <code>${userRecords}</code> here</p> <pre><code>${userRecords.user_first_name} ${userRecords.user_middle_name} </code></pre> <p>is a <code>List<User></code>, however you're attempting to access it as if it's a single <code>User</code>. This is not valid. In EL, a <code>List</code> can only be accessed with an integer index, indicating the position of the list item you'd like to access, like so</p> <pre><code>${userRecords[0].user_first_name} ${userRecords[0].user_middle_name} </code></pre> <p>The exception is also basically telling that it expected an integer value instead of a string value. If you look closer at the stack trace, you'll see that a <code>ListELResolver</code> is involved.</p> <p>However, your concrete problem is bigger. You should actually be iterating over the list. Use the <a href="http://stackoverflow.com/tags/jstl/info">JSTL</a> <code><c:forEach></code> for that. E.g. (simplified from your odd code snippet):</p> <pre class="lang-html prettyprint-override"><code><table> <c:forEach items="${userRecords}" var="user"> <tr> <td>${user.user_first_name}</td> <td>${user.user_middle_name}</td> </tr> </c:forEach> </table> </code></pre> <p><em>(note: keep the <a href="http://stackoverflow.com/questions/2658922/xss-prevention-in-java/2658941#2658941">XSS attack hole</a> in mind if you really intend to redisplay them as input values)</em></p> <p>By the way, I'd work on your <a href="http://www.oracle.com/technetwork/java/javase/documentation/codeconvtoc-136057.html">Java code conventions</a>. Those underscores are really not Java-ish.</p> |
38,252,374 | 0 | <p>When used as part of a URL, ? and & represent key value pairs that make up the Query String, which is a set of information sent to the server.</p> <p>The query string starts after the end of the page being requested with a ? and then a key value pair like:</p> <pre><code>?variable1=value1 </code></pre> <p>Any additional key/value pairs need to be prefaced with & like:</p> <pre><code>?variable1=value1&variable2=value2&variable3=value3 </code></pre> |
9,401,370 | 0 | <p>It doesn't work because you're trying to replace the ASCII apostrophe (or single-quote) and quote characters with the empty string, when what's actually in your source string aren't ASCII characters.</p> <pre><code>str.replace(/[“”‘’]/g,''); </code></pre> <p>works.</p> |
27,721,190 | 0 | <p>Add this to your <code>ApplicationController</code>:</p> <pre><code>def search @search ||= Search.new end def galleries @galleries ||= Gallery.all end </code></pre> <p>You then use the function (<code>search</code>) in your views instead if the instance variable <code>@search</code>); the <code>||=</code> makes sure the code is executed only once (thus saving database queries).</p> |
3,723,646 | 0 | How to save data from a DataGridView into database? c# winforms <p>I have this little application, and what it does is a user can add many deductions to a certain employee and save the record.</p> <p><img src="https://i.stack.imgur.com/Y2mVu.png" alt="alt text"></p> <p>What I do in my coding is I pass all the values to a <code>DataTable</code> and loop through each rows and execute a stored procedure that inserts the particular row with the column values. This happens until there are no rows to be inserted from the DataTable. </p> <p>Is there any shortcut? I mean, can I insert the whole value of datatable in one call? I just thought that my current way of inserting data is very resource consuming because it always calls the stored procedure in the server as long as there are rows in the datatable.</p> <p>Any work around or suggestions? I would be very thankful. I hope you understand me,. thanks in advance.</p> |
4,022,463 | 0 | How can I extract non-standard HTTP headers using Perl's LWP? <p>I'm working with a web application that sends some non-standard HTTP headers in its response to a login request. The header in question is:</p> <pre><code>SSO_STATUS: LoginFailed </code></pre> <p>I tried to extract it with LWP::Response as <code>$response->header('SSO_STATUS')</code> but it does not work. It does work for standard headers such as <code>Set-Cookie</code>, <code>Expires</code> etc.</p> <p>Is there a way to work with the raw headers?</p> |
31,635,874 | 0 | gcc with explicit linking <p>I would like with compile C++ code with GCC using command</p> <pre><code>gcc -lstdc++ hello.cpp -o out.a </code></pre> <p>Code:</p> <pre><code>#include <iostream> int main() { std::cout<<"hello"; return 0; } </code></pre> <p>Got output:</p> <pre><code>/tmp/ccgtX1Xs.o: In function `main': hello.cpp:(.text+0xa): undefined reference to `std::cout' hello.cpp:(.text+0xf): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*)' /tmp/ccgtX1Xs.o: In function `__static_initialization_and_destruction_0(int, int)': hello.cpp:(.text+0x3d): undefined reference to `std::ios_base::Init::Init()' hello.cpp:(.text+0x4c): undefined reference to `std::ios_base::Init::~Init()' collect2: error: ld returned 1 exit status g@GME5420:~/cpp$ </code></pre> |
35,503,654 | 0 | <p>Your two larger SELECTS (the first 2) are returning 12 items. The last two SELECTS (the small ones) are returning 13 items. UNION must have matching columns.</p> <p>eg statement should end...</p> <pre><code>SELECT NULL, 0, 'ABC', NULL, NULL, NULL, 'ABC', NULL, NULL, NULL, NULL, NULL FROM DUAL UNION SELECT NULL, 0, 'XYZ', NULL, NULL, NULL, 'XYZ', NULL, NULL, NULL, NULL, NULL FROM DUAL </code></pre> |
39,483,974 | 0 | <p>I'm not sure if I understand your problem correctly, but please check if solution mentioned in <a href="http://stackoverflow.com/questions/4042856/system-out-with-ant">this question</a> suits your needs.</p> |
11,638,724 | 0 | <p>As a function:</p> <pre><code>function printYearsBefore(date,num) { var yr = parseInt(date.getFullYear()), i =0; while(++i <= num){ document.write((yr-i)); } } printYearsBefore(new Date(),18); </code></pre> |
35,418,633 | 0 | <p>use group by for aggregate function (and for this you don0t need distinct )</p> <pre><code>"SELECT Test_ID AS Tcode, COUNT(*) AS Qcount, User_ID FROM user_answers WHERE User_ID = 1 group by Tcode, User_ID ") </code></pre> |
4,881,085 | 0 | php is there a way to transfer Latin letters to english letters? <p>is there a way to transfer Latin letters to english letters with php?</p> <p>Such as: <code>āáǎà</code> transfer to <code>a</code>, </p> <p><code>ēéěè</code> transfer to <code>e</code>,</p> <p><code>īíǐì</code> transfer to <code>i</code>,</p> <p>... // there may be dozens which are main in Germany, French, Italian, Spain...</p> <p>PS: how to transfer punctuation mark use php? I also want to transfer <code>%20</code> to a space, transfer <code>%27</code> to <code>'</code>. Thank u.</p> |
27,129,711 | 0 | <p>Well, my recommendation would be twofold. First, just don't use factors when creating the data.frame; you can factor post-hoc if you really need them. So:</p> <pre><code>GammaShape <- data.frame(Format, Shape, stringsAsFactors = FALSE) </code></pre> <p>Second: for loops are a really inefficient way to modify data.frames, because of how data.frames are stored and modified: every time you tweak a value, you're actually recreating the data.frame in its (new) format and assigning it to the old name, which is computationally expensive with big objects. While this is a very small data.frame, I'd suggest getting into the habit of operating on individual vectors wherever possible, and merging into a data.frame <em>after</em> you've finished iterating. So:</p> <pre><code>Format <- c('10x2', '10x3', '10x7', '17x15', '17x7', '20x2', '20x3', '25x4', '4 column', '5 column', '7x7', 'DPS', 'FP') Shape <- numeric(length(Format)) for(i in seq_along(Shape)){ Shape[i] <- coef(fitdistr(modelset$ETTime[which(modelset$Format == Format[i])]/1000)) } GammaShape <- data.frame(Format, Shape, stringsAsFactors = FALSE) </code></pre> <p>...and then if you want to factor, well, apply <code>as.factor</code>. Note that this solution works <em>to the best of my knowledge</em> - your example doesn't show us modelset.</p> |
33,535,056 | 0 | <p>It looks like this has nothing to do with wallet, but instead is an issue with the version of <code>com.balysv:material-ripple</code> you are using as per <a href="https://github.com/balysv/material-ripple/issues/31" rel="nofollow">this issue</a>.</p> <p>The <a href="https://github.com/balysv/material-ripple" rel="nofollow">library's Github page</a> shows that the latest version (which includes the above fix) is:</p> <pre><code>compile 'com.balysv:material-ripple:1.0.2' </code></pre> |
29,495,239 | 0 | How do you use @Inject with an ejb-jar with (one or more) WAR files? <p>Working with GlassFish, trying to be tidy, I would like to put all of my business logic into a single EJB JAR. I then have 2 WAR files. </p> <ul> <li>app-frontend-war </li> <li>app-backend-war</li> <li>app-logic-ejb</li> </ul> <p>Each of the WAR files need to use the EJBs that are within the app-logic-ejb JAR. This EJB JAR holds the main persistence unit. But I am finding that @Inject of any app-logic-ejb EJB's from any Java within the WAR files are not working.</p> <p>Also, I am trying to avoid using an EAR.</p> |
33,627,536 | 0 | <p>You have just forgotten the <code>new</code> in this line</p> <pre><code>$someclass = someOtherClass(); </code></pre> <p>It should be </p> <pre><code>$someclass = new someOtherClass(); </code></pre> <p>Then everything works. Although this only applies to the second version of your question, not the first!</p> |
39,503,721 | 0 | Perl Regex -?\d+(?:\.\d+)? <p>This regex is supposed to match any numbers (real or integer - no scientific notation). However, I am not sure what is the use of '?:' inside the parentheses. Could anyone explain this along with some examples? Thank you very much.</p> |
17,886,893 | 0 | <p>If the query builder is done in house, and if your query builder returns a the SQL statement in a string, you can parse it either looking for Update statements keyworks or with Regex, if you want to spare the users the trouble of creating an update query then realizing that they can't run it, then you should consider doing this check continiously as they create the query. Alternatively, you can use a third party query builder, like this one: <a href="http://www.activequerybuilder.com/" rel="nofollow">http://www.activequerybuilder.com/</a>, unfortunately i belive it doesn't support anything else but Select statements but it may be worth the shot.</p> |
7,060,185 | 0 | <p>You could break the word into an array of letters, and loop over this using a random number to determining case, after looping the array, simply stick the letters back together using NSMutableString.</p> <p>NSString had a uppercaseString and lowercaseString methods you can use.</p> |
22,937,003 | 0 | HTTP Illegal state exception <p>I have the following code, which in general works without problems:</p> <pre><code>HttpPost post = new HttpPost(sendURL); StringEntity se = new StringEntity( postJSON.toString(), "UTF-8"); se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); post.setEntity(se); response = httpClient.execute(post); </code></pre> <p>When postJSON has the following, I get an IllegalStateException, with the message "Manager is shut down":</p> <pre><code>{"action":"add","items":["61515"],"screen":"display","customer_number":"200001013"} </code></pre> <p>I got a similar message when the items array had malformed content, but I don't see the problem here. Also, the response is immediate, so I am pretty sure that the HTTP library is throwing the exception, not the server. What is wrong with this JSON object?</p> <p>Furthermore, testing the JSON at <a href="http://jsonlint.com/" rel="nofollow">JSONLint</a> shows me that the JSON parses correctly, including the array with "61515", which is the new element in the code.</p> |
13,781,147 | 0 | <p>You are only catching <code>SQLException</code> objects, and <code>NullPointerException</code> is not a subclass of <code>SQLException</code>. You can insert <code>NullPointerException|</code> to catch those also; see <a href="http://docs.oracle.com/javase/7/docs/technotes/guides/language/catch-multiple.html" rel="nofollow">http://docs.oracle.com/javase/7/docs/technotes/guides/language/catch-multiple.html</a>.</p> |
40,702,416 | 0 | <p>Got it working....had to return promise from child parent which is t.none() without catch()</p> |
7,686,048 | 0 | <p>You can use:</p> <pre><code>xhr.timeout = 10000; xhr.ontimeout = timeoutFired; </code></pre> <p>for this purpose</p> |
22,619,826 | 0 | Report Pending Payments with mixed Monthly & Weekly intervals <p>We are working with a database that tracks payment plans for patients. Some patients pay monthly, some weekly, and some every other week.</p> <p>The PaymentsSchedule table fields are Patient, Frequency, NextDueDate, PaymentsRemaining, Amount. Once a payment is processed the NextDueDate and PaymentsRemaining fields are updated so that at any given time there is only one record representing all future payments for a given payment plan.</p> <p>The report we want to generate would show all payments expected within the next month. Something like this:</p> <pre><code>Report Date: 3/1/2014 Patient Frequency Next Date Pmts Left Amount 01 Monthly 3/01/2014 5 $100 02 Weekly 3/02/2014 3 $30 03 Weekly 3/02/2014 7 $25 04 Bi-Weekly 3/03/2014 4 $75 02 Weekly 3/09/2014 2 $30 03 Weekly 3/09/2014 6 $25 02 Weekly 3/16/2014 1 $30 03 Weekly 3/16/2014 5 $25 04 Bi-Weekly 3/17/2014 3 $75 03 Weekly 3/23/2014 4 $25 03 Weekly 3/30/2014 3 $25 </code></pre> <p>I could set up 5 different queries for the 5 date possibilities (weekly) of a payment plan for the next 31 days, pull them together in a UNION and then filter out dates that are not in my time horizon but I would like to find a simpler solution.</p> <p>Your help is much appreciated.</p> <p>Thanks,</p> <p>Jim S</p> |
20,958,023 | 0 | A simple C# Statement works unexpected <p>I've got this line of code: </p> <pre><code>int WStoneCost = PriceMethod.StoneCost / 100 * AP; </code></pre> <p>While PriceMethod.StoneCost is equal to 25 and AP is equal to 70. I've checked it using breakpoints and I can't understand why do I get zero after I run this line. (WStoneCost is equal to zero) Is it just a wrong symbol or am I doing something wrong? Thanks in advance. And how to get a correct double at the end? Like 17.<strong>5</strong></p> |
25,952,788 | 0 | <p>Try this:</p> <pre><code>var result = list.Select(x => new[] { x.Key, x.Value }).ToArray(); </code></pre> |
30,883,823 | 0 | <p>Partial answer:</p> <p>Try all permutations of all subsets of your digits, probably starting with the largest candidates.</p> <p>If your factors contain <code>5</code> the <em>last</em> digit must be <code>0</code>or <code>5</code></p> <p>If your factors contain <code>3</code> or <code>6</code> or <code>9</code> the sum of all candidate digits muts be a multiple of <code>3</code></p> <p>If your factors contain 2 or 4 or 6 or 8 the last digit must be even.</p> <p>And so on.</p> |
13,946,115 | 0 | <p>You must add <code>MessageUI.framework</code> to your Xcode project and include a </p> <p><code>#import <MessageUI/MessageUI.h></code> in your header file.</p> <p>try this code may be its helpful to you..</p> <pre><code>[self presentModalViewController:picker animated:YES]; //[self becomeFirstResponder];//try picker also instead of self </code></pre> <p>Also Refer this bellow tutorial and also check demo..</p> <ol> <li><p><a href="http://coenraets.org/blog/2012/11/new-tutorial-developing-and-architecting-a-phonegap-application/" rel="nofollow">new-tutorial-developing-and-architecting-a-phonegap-application</a></p></li> <li><p><a href="https://github.com/phonegap/phonegap-plugins/tree/master/iPhone/SMSComposer" rel="nofollow">SMSComposer</a></p></li> </ol> <p>i hope this help you...</p> |
36,910,275 | 0 | <p>Do you need to use reflection? If you have control of the classes that you are iterating over, it would be better to create an interface. Reflection is slow and should be avoided where possible.</p> <pre><code>public interface IDocumentCreator { void GenerateDocument(); } </code></pre> <p>Add this interface to your classes:</p> <pre><code>public class YourClass : IDocumentCreator { // ... public void GenerateDocument() { // ... } } </code></pre> <p>And then make a <code>List<IDocumentCreator></code> instead of <code>List<object></code>. You can then call the method in the normal way:</p> <pre><code>List<IDocumentCreator> allClassesINeedList = ... foreach(IDocumentCreator item in allClassesINeedList) { item.GenerateDocument(); } </code></pre> |
2,053,294 | 0 | <p>If I understand what you're trying to do... you can do something like this:</p> <pre><code>// For my benefit, hide all lists except the root items $('ul, li', $('#lesson-sidebar ul li')).hide(); // Show active parents and their siblings $('li a.active').parents('ul, li').each(function() { $(this).siblings().andSelf().show(); }); // Show the active item and its siblings $('li a.active').siblings().andSelf().show(); </code></pre> <p>The <a href="http://docs.jquery.com/Traversing/parents" rel="nofollow noreferrer">parents()</a> and <a href="http://docs.jquery.com/Traversing/siblings#expr" rel="nofollow noreferrer">siblings()</a> methods are both great for this kind of thing.</p> <p>Edit: There was a bug before where it wasn't showing parent siblings. Try this new version.</p> <p>Edit 2: Now it works with class="active" on the anchor instead of the list item.</p> |
5,306,229 | 0 | <p>You've set the variable i in the line <code>var i = document.getElementById('i').innerHTML = (document.getElementById("nine").value);</code>. <code>i</code> refers to the variable i, not to the control with id i.</p> <p>You'll have to do</p> <pre><code>var a = document.getElementById('number').value </code></pre> <p>etc.</p> <p>Edit: Ah I see you've declared a..h inside your methods. Remember that <code>var a</code> only applies within the curly brackets that it's declared inside, so declare them at the start of your script by doing <code>var a=0</code> etc. This is called the 'scope' of your variables.</p> |
13,754,753 | 0 | <p>If the table data is added by JS then you might want to add an on() handler like:</p> <pre><code>$('#area-work-time').on('change','input[type="checkbox"]',function(){ alert("inside change event"); }); </code></pre> <p>This makes the event trigger for dynamically created elements.</p> |
23,725,631 | 0 | C++ inherit template class <p>I've got a peculiar request, hopefully it's not too far fetched and can be done.</p> <p>I've got a template class</p> <pre><code> template<class T> class Packable { public: // Packs a <class T> into a Packet (Packet << T) virtual sf::Packet& operator <<(sf::Packet& p) const = 0; friend sf::Packet& operator <<(sf::Packet& p, const T &t); friend sf::Packet& operator <<(sf::Packet& p, const T *t); // Packs a Packet into a <class T> (T << Packet) virtual T operator <<(sf::Packet& p) const = 0; friend T& operator <<(T &t, sf::Packet& p); friend T* operator <<(T *t, sf::Packet& p); // Unpacks a Packet into a <class T> (Packet >> T) virtual sf::Packet& operator >>(sf::Packet& p) const = 0; friend sf::Packet& operator >>(sf::Packet& p, T &); friend sf::Packet& operator >>(sf::Packet& p, T* t); }; </code></pre> <p>and I want to be able to use it something like</p> <pre><code>class Player : public Packable { //... } </code></pre> <p>Such that Player now has all of those operators overloaded for it.</p> <p>As of now, I get <code>Expected class name</code> as a compile error. Is there a way to accomplish this without needing to specify the class? That is to say; how can <code>Packable</code> pick up <code>Player</code> as <code><class T></code> when I inherit it?</p> |
30,136,090 | 0 | Single <br /> doesn't create a line break instead, requires two <p>I am working on a Wordpress theme and have been using Bootstrap a bit. I put my article excerpt for the homepage in a well, <code>div class='well'</code>. I have edited the well to have straight corners and have changed the border colour. Except those, there aren't any changes. But, when I try to add a linebreak between categories and tags, it doesn't float to extreme left as in the image below. </p> <p>Q1. How to use a single <code><br /></code> to make a line break between the two? Q2. There's a lot of blank space in the well after the category and tags. How to remove it?</p> <p><strong>HTML Code</strong> </p> <pre><code><div class="categories"><?php the_category(' '); ?></div><br /><br /><div class="tags"><?php the_tags('',' '); ?></div> </code></pre> <p><strong>CSS</strong></p> <pre><code>.categories{float:left; margin-right:3px;margin-bottom: 1px;} .categories a { background: #00A1E0; color: #FFFFFF; display: inline-block; margin-bottom: 2px; margin-left: 0px; padding: 1px 7px; text-decoration: none; transition: all 0.3s ease 0s; } .categories a:hover{background: #666; color:#fff;} .tags{float:left; margin-right:1%;margin-bottom:4px;} .tags a { font-size:70%; background:#666666; color: #FFFFFF; display: inline-block; margin-bottom: 3px; margin-left: 0px; padding: 1px 7px; text-decoration: none; transition: all 0.3s ease 0s; } .tags a:hover{color:#FFFFFF;} </code></pre> <p><strong>When I use single <code><br /></code>, this is what happens</strong> <a href="http://i.stack.imgur.com/OIDYt.png" rel="nofollow">http://i.stack.imgur.com/OIDYt.png</a> (Sorry, can't post images due to lack of rep).</p> |
14,425,763 | 0 | <p>Create: app/code/local/Ffdotcom/Helloworld/etc/config.xml</p> <pre><code><?xml version="1.0"?> <config> <modules> <Ffdotcom_Helloworld> <version>1.0.0</version> </Ffdotcom_Helloworld> </modules> <frontend> <routers> <helloworld> <use>standard</use> <args> <module>Ffdotcom_Helloworld</module> <frontName>helloworld</frontName> </args> </helloworld> </routers> </frontend> </config> </code></pre> <p>Create: app/code/local/Ffdotcom/Helloworld/controllers/IndexController.php</p> <pre><code><?php class Ffdotcom_Helloworld_IndexController extends Mage_Core_Controller_Front_Action { public function indexAction(){ echo 'hello world'; } } </code></pre> <p>Create: app/etc/modules/Ffdotcom_Helloworld.xml </p> <pre><code><?xml version="1.0"?> <config> <modules> <Ffdotcom_Helloworld> <active>true</active> <codePool>local</codePool> </Ffdotcom_Helloworld> </modules> </config> </code></pre> |
37,524,896 | 0 | <p>Guava Caches store values in RAM. See <a href="https://github.com/google/guava/wiki/CachesExplained#applicability" rel="nofollow">https://github.com/google/guava/wiki/CachesExplained#applicability</a>.</p> |
33,539,108 | 0 | <p>... and you could use the OpenNTF Domino API that has functions for exactly this. As far as I remember there is an example of this in the demo database. Not sure if it is also in the <a href="http://www.openntf.org/main.nsf/project.xsp?r=project/OpenNTF%20Domino%20API%20Demo%20Database" rel="nofollow">new version of the demo database</a> - but then you may just need to find an older version (e.g. for milestone 4.5 where I saw this).</p> <p>/John</p> |
1,680,681 | 0 | <pre><code>string script = string.Format("alert('this is alert');"); ScriptManager.RegisterClientScriptBlock(Page, typeof(System.Web.UI.Page), "redirect", script, true); </code></pre> |
668,299 | 0 | <p>Not only are continuations monads, but they are a sort of universal monad, in the sense that if you have continuations and state, you can simulate any functional monad. This impressive but highly technical result comes from the impressive and highly technical mind of <a href="http://www.diku.dk/hjemmesider/ansatte/andrzej/" rel="nofollow noreferrer">Andrzej Filinski</a>, who wrote in 1994 or thereabouts:</p> <blockquote> <p>We show that any monad whose unit and extension operations are expressible as purely functional terms can be embedded in a call-by-value language with “composable continuations”.</p> </blockquote> |
35,860,010 | 0 | <p>I also faced same problem, but when I added a space into the empty div, it started positioning properly. i.e.</p> <pre><code>div.innerHTML = &nbsp;&nbsp; </code></pre> |
18,271,791 | 0 | <p>There are many options and they're all very easy to pick up in a couple of days. Which one you choose is completely up to you.</p> <p>Here are a few worth mentioning:</p> <p><strong><a href="http://www.tornadoweb.org/">Tornado</a>: a Python web framework and asynchronous networking library, originally developed at FriendFeed.</strong> </p> <pre><code>import tornado.ioloop import tornado.web class MainHandler(tornado.web.RequestHandler): def get(self): self.write("Hello, world") application = tornado.web.Application([ (r"/", MainHandler), ]) if __name__ == "__main__": application.listen(8888) tornado.ioloop.IOLoop.instance().start() </code></pre> <p><br> <br> <strong><a href="http://bottlepy.org/docs/dev/">Bottle</a>: a fast, simple and lightweight WSGI micro web-framework for Python. It is distributed as a single file module and has no dependencies other than the Python Standard Library.</strong></p> <pre><code>from bottle import route, run, template @route('/hello/<name>') def index(name='World'): return template('<b>Hello {{name}}</b>!', name=name) run(host='localhost', port=8080) </code></pre> <p><br> <br> <strong><a href="http://www.cherrypy.org/">CherryPy</a>: A Minimalist Python Web Framework</strong></p> <pre><code>import cherrypy class HelloWorld(object): def index(self): return "Hello World!" index.exposed = True cherrypy.quickstart(HelloWorld()) </code></pre> <p><br> <br> <strong><a href="http://flask.pocoo.org/">Flask</a>: Flask is a microframework for Python based on Werkzeug, Jinja 2 and good intentions.</strong> </p> <pre><code>from flask import Flask app = Flask(__name__) @app.route("/") def hello(): return "Hello World!" if __name__ == "__main__": app.run() </code></pre> <p><br> <br> <strong><a href="http://webpy.org/">web.py</a>: is a web framework for Python that is as simple as it is powerful.</strong></p> <pre><code>import web urls = ( '/(.*)', 'hello' ) app = web.application(urls, globals()) class hello: def GET(self, name): if not name: name = 'World' return 'Hello, ' + name + '!' if __name__ == "__main__": app.run() </code></pre> |
20,709,676 | 0 | Multiple Select Statements <p>I am trying to create a list of items in which every fourth item in the list is an item that is on from New York and On Sale. The rest of the items in the list are the items that are from New York no matter if they are on sale or not. </p> <p>How can I properly use two select statements to break the list up into the order that I want? Below is what I'm using now. It creates a list of paragraphs but does not understand what the variables <code>$article</code> and <code>$article2</code> are.</p> <pre><code><ul> <? $sort = id; $sql = "SELECT * FROM `Catalog` WHERE state = 'New York' and in_stock = 'yes' ORDER BY $sort"; $result = mysql_query($sql); $sql2 = "SELECT * FROM `Catalog` WHERE state = 'New York' and sale_item = 'yes' ORDER BY $sort "; $result2 = mysql_query($sql2); $i = 0; while ( $article = mysql_fetch_array($result) || $article2 = mysql_fetch_array($result2) ) { if ($i == 0) { echo '<li>This item number is on sale:'.article2[id]. '</li>'; $i++; } else if ($i == 3) { echo '<li>This item number is regular price'.article[id]. '</li>'; $i = 0; } else { echo '<li>This item number is regular price'.article[id].'</li>'; $i++; } } ?> </ul> </code></pre> <p>Based on Dave's suggestion I'm trying it this way. But php still doesn't know how to interpret $itemsOnSale or $items.</p> <pre><code><ul> <? $items = array(); $itemsOnSale = array(); $sql = "SELECT * FROM `Catalog` WHERE state = 'New York' AND in_stock = 'yes' ORDER BY $sort"; $result = mysql_query($sql); while ( $row = mysql_fetch_assoc($result) ) { if ( $row['sale_item'] == 'yes' ) { $itemsOnSale[] = $row; } else { $items[] = $row; } if ($i == 0) { echo '<li>This item number is on sale:'.$itemsOnSale[id]. '</li>'; $i++; } else if ($i == 3) { echo '<li>This item number is regular price'.$items[id]. '</li>'; $i = 0; } else { echo '<li>This item number is regular price'.$items[id].'</li>'; $i++; } } ?> </ul> </code></pre> |
29,785,839 | 0 | <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var url = 'http://website.com/testing/test2/', //URL to convert lastSlash = url.lastIndexOf('/'), //Find the last '/' middleUrl = url.substring(0,lastSlash); //Make a new string without the last '/' lastSlash = middleUrl.lastIndexOf('/'); //Find the last '/' in the new string (the second last '/' in the old string) var newUrl = middleUrl.substring(0,lastSlash); //Make a new string that removes the '/' and everything after it alert(newUrl); //Alert the new URL, ready for use</code></pre> </div> </div> </p> <p>This works.</p> |
24,574,034 | 0 | <p>You can sort the elements before adding them to the DOM and then add them; that should work.</p> <pre><code>var statecontent = ['<option value="Texas" data-code="TX">Texas - TX</option>', '<option value="Washington" data-code="WA">Washington - WA</option>', '<option value="Maryland" data-code="MD">Maryland - MD</option>']; statecontent.sort(function(a,b) { return $(a)[0].text == $(b)[0].text ? 0 : $(a)[0].text < $(b)[0].text ? -1 : 1; }); </code></pre> <p>And you also need to use single quotes for your array elements as you are already using the double quotes for the attributes, or at least escape it in the attributes.</p> <p><a href="http://jsfiddle.net/fiddleyetu/n8bSV/2/" rel="nofollow"><strong>WORKING JSFIDDLE DEMO</strong></a></p> |
12,932,793 | 0 | <blockquote> <p>Why is this the case that an empty class without any values already needs 220 bytes for saving itself?</p> </blockquote> <p>Why ask what you can find out? This code already yields 33 bytes:</p> <pre><code>FileStream fs = new FileStream("Serialized.dat", FileMode.Create); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(fs, "FooString"); </code></pre> <p>Because there's more being serialized than just the string itself. If you serialize an object, its class definition (and the assembly it's in) is also being serialized. Serializing an instance of this class:</p> <pre><code>[Serializable] class Foo { public String FooString { get; set; } } </code></pre> <p>Costs 166 bytes, while the <code>FooString</code> property contains the same data as the raw string serialized earlier.</p> <p>So: write your own serialization (or: load/save) logic. You are the one that reads and writes that data, so you can for example assign specific bytes in the space you have to certain properties of your class.</p> |
7,456,443 | 0 | <p>No. You'd have to expose the static instance to the caller. Reference equality means that it is exactly the same object. Unless there is a way to access that particular object, you can't have another that references the same memory. If you were to use the equality operator, that would be different as <code>string</code> overloads that to do value equality rather than reference equality.</p> <p>Had you, on the other hand, set the static instance value to a constant, you could (by using the constant) have a reference that is equal to the static instance. That is because string literals are interned and shared through out the code, meaning that all string literals that are the same have the same reference.</p> <p>For example,</p> <pre><code>class GuessTheSecret { private static readonly string Secret = "Secret"; public static bool IsCorrect(string token) { return object.ReferenceEquals(token, Secret); } } Console.WriteLine( GuessTheSecret.IsCorrect( "Secret" ) ); </code></pre> <p>would output <code>True</code></p> |
24,570,351 | 0 | <p>If you declare the variable outside of a method, the state is remembered.</p> <p>A solution could be:</p> <pre><code>public class Test { int count = 0; public static void main(String[] args) { Test test1 = new Test(); test1.doMethod(); test1.doMethod(); test1.doMethod(); } public void doMethod () { count++; System.out.println(count); } } </code></pre> <p>This way <code>count</code> is created the moment you call <code>new Test()</code> and will be remembered until the Object is destroyed. Variables have something called a 'scope'. They can only be accessed in their scope and will only exist in that scope. Because you created <code>count</code> inside your <code>void doMethod()</code> method, it did not exist anywhere else. An easy way to look at the scope is by watching the brackets <code>{ }</code> your variables are only stored inside those brackets. In my solution the brackets for <code>count</code> are the brackets for the entire <code>Test</code> class. Thus the variable is stored until the Object is destroyed.</p> <p>More on scope: <a href="http://en.wikipedia.org/wiki/Scope_(computer_science)" rel="nofollow">http://en.wikipedia.org/wiki/Scope_(computer_science)</a></p> <p>I just noticed you mentioned you want the <code>count</code> value to remain after you run the program. You can do this by saving it in a database or file. However, you might have meant that you want the <code>count</code> value to remain after you run the <code>void doMethod()</code> method. I have edited my solution to execute the <code>void doMethod()</code> method three times so you see the value actually remains after running the method.</p> |
9,024,058 | 0 | jQuery time and date <p>I am looking for a time output using jQuery, for example, would be great to know what time it is on the visitor's browser and the current day (friday,saturday,monday, etc...).</p> <p>Is there any way to do it only with jQuery? I don't really like the way javascript handles time issues. </p> <p>If you recommend any plugin, please tell me wich.</p> <p>Thanks so much! Souza.</p> <p>EDIT:</p> <p>I'm looking to avoid substring javascript outputs, or convert the results.</p> <p>Wouldn't be great to use </p> <pre><code>$("#setime").yourtime("day"); </code></pre> <p>and give me the day? or </p> <pre><code> $("#setime").yourtime("hour", 24format); </code></pre> <p>and give you the hour in any format you need?</p> <p>?</p> |
27,081,217 | 0 | Comparing values in a stl list<> that is populated with a class <p>I've been playing around with my code, trying to better it and im stuck a this part.</p> <p>I have the following header</p> <p>Funcionario.h</p> <pre><code>class Funcionario { private: std::string Userid; std::string Nome; std::string Sobrenome; std::string Email; std::string Pass; public: Funcionario(std::string Userid, std::string Nome, std::string Sobrenome, std::string Email, std::string Pass); ~Funcionario(void); string GetUserID() { return Userid; } string GetName() { return Nome; } string GetSName() { return Sobrenome; } string GetEmail() {return Email; } string GetPass() { return Pass; } }; </code></pre> <p>And this is my form, note that it's not the entire form, just the part that matters;</p> <pre><code>#include <list> #include <algorithm> #include "Funcionario.h" Form1(void) { InitializeComponent(); // //TODO: Add the constructor code here // LF = new list<Funcionario>(); } //Button click list<Funcionario>::iterator it1 = find(LF->begin(), LF->end(), ID); //*Searches for ID </code></pre> <p>When i try to run this it says that there is no suitable converter to tipe Funcionario. Any help would be apreciated and thank you very much in advance.</p> |
29,913,138 | 0 | <p>You can use <code>sprintf</code> and then trim the zeros. This is the same idea as @Havenard's answer, but writing spaces over the zeros instead of cutting the string. And my C-style is somewhat different FWIW. My style is that I don't want to count or do any arithmetic in my head; that's what the C optimizer is for :).</p> <pre><code>#include <math.h> #include <stdio.h> #include <string.h> int main() { int kPower; for(kPower=-4; kPower<5; kPower++){ enum { bufsize = 2+5+10+1+4+1+1 }; char buf[bufsize]; int j,n,i; double raisePower = pow(10,kPower); //printf("%2d %10.4f\n",kPower,raisePower); snprintf(buf,bufsize,"%2d %10.4f\n",kPower,raisePower); j=strchr(buf,'.')-buf; j+=1; n=strchr(buf+j,'\n')-buf; for (i=n-1; i>j; i--) if (buf[i]=='0') buf[i]=' '; else break; printf("%s",buf); } return 0; } </code></pre> <p>Output:</p> <pre><code>-4 0.0001 -3 0.001 -2 0.01 -1 0.1 0 1.0 1 10.0 2 100.0 3 1000.0 4 10000.0 </code></pre> |
23,406,407 | 0 | Regex of path not working <p>I need to create reg-ex for path like aaaa/bbb/ccc or aaa-bbb or aaa_bbb_ccc_ddd etc How should I do that ? It can contain only <strong>alpha numeric with hyphen underscore and slash</strong>. Ive tried something like this which is not working</p> <pre><code>@"^((?:/[a-zA-Z0-9]+)+/?|/?(?:[a-zA-Z0-9]+/)+)[a-zA-Z0-9]*$" </code></pre> |
10,522,260 | 0 | <p>If you want to create a new object from a class of which the name is stored in a string, you can use:</p> <pre><code>$object = new $className(); </code></pre> <p>Or in your case:</p> <pre><code>$option = new $_POST['option_name'](); $option->calculated(); $option->create_record_for_database(); </code></pre> <p>However, I personally don't like the idea of using variables like this.</p> |
35,450,932 | 0 | <p>As you want to avoid recursion, you need to reverse the list first. I see some attempt in the original code but it doesn't look correct. Try the following:</p> <pre><code>node *current = head; if (current != NULL) { node *prev = NULL; for (node *next = current->next; ; next = (current = next)->next) { current->next = prev; prev = current; if (next == NULL) break; } } </code></pre> <p>Then <code>current</code> will point to the head of the list and you can traverse using the <code>next</code> link over the list. Note that it will modify your original list but this is expected as I understood the original requirement.</p> |
14,184,695 | 0 | <p>This is a by-product of what Visual C++ refers to as <strong>Identical COMDAT Folding</strong> (ICF). It merges identical functions into a single instance. You can disable it by adding the following switch to the linker commandline: <code>/OPT:NOICF</code> (from the Visual Studio UI it is found under <em>Properties->Linker->Optimization->Enable COMDAT Folding</em>)</p> <p>You can find details at the MSDN article here: <a href="http://msdn.microsoft.com/en-us/library/bxwfs976%28v=vs.110%29.aspx">/OPT (Optimizations)</a></p> <p>The switch is a linker-stage switch, which means you won't be able to enable it just for a specific module or a specific region of code (such as <code>__pragma( optimize() )</code> which is available for compiler-stage optimization).</p> <p>In general, however, it is considered poor practice to rely on either function pointers or literal string pointers (<code>const char*</code>) for testing uniqueness. String folding is widely implemented by almost all C/C++ compilers. Function folding is only available on Visual C++ at this time, though increased widespread use of template<> meta-programming has increased requests for this feature to be added to gcc and clang toolchains.</p> <p>Edit: Starting with binutils 2.19, the included gold linker supposedly also supports ICF, though I have been unable to verify it on my local Ubuntu 12.10 install.</p> |
2,401,438 | 0 | MVC Model Implementation? <p>I am creating a simple application using the MVC design pattern where my model accesses data off the web and makes it available to my controllers for subsequent display. </p> <p>After a little research I have decided that one method would be to implement my model as a singleton so that I can access it as a shared instance from any of my controllers.</p> <p>Having said that the more I read about singletons the more I notice people saying there are few situations where a better solution is not possible.</p> <p>If I don't use a singleton I am confused as to where I might create my model class. I am not over happy about doing it via the appDelegate and it does not seem viable to put it in any of the viewControllers.</p> <p>any comments or pointers would be much appreciated.</p> <p><strong>EDIT_001:</strong></p> <p>TechZen, very much appreciated (fantastic answer as always) can I add one further bit to the question before making it accepted. What are your thoughts on deallocating the singleton when the app exits? I am not sure how important this is as I know quite often that object deallocs are not called on app teardown as they will be cleared when the app exits anyway. Apparently I could register the shared instance with NSApplicationWillTerminateNotification, is that worth doing, just curious?</p> <p>gary</p> |
1,777,744 | 0 | <p>Named Pipes can be used for this. It might be the more acceptable method with .net.You can define a service in the main application that accepts a message from the calling application. Here's a sample of the service, in vb. It calls the main app and passes a string to it, in this case, a filename. It also returns a string, but any parameters can be used here.</p> <pre><code>Public Class PicLoadService : Implements IMainAppPicLoad Public Function LoadPic(ByVal fName As String) As String Implements IMainAppPicLoad.LoadPic ' do some stuff here. LoadPic = "return string" End Function End Class </code></pre> <p>The setup in the calling application is a little more involved. The calling and main application can be the same application.</p> <pre><code>Imports System.Diagnostics Imports System.ServiceModel Imports System.IO Imports vb = Microsoft.VisualBasic Module MainAppLoader Sub Main() Dim epAddress As EndpointAddress Dim Client As picClient Dim s As String Dim loadFile As String Dim procs() As Process Dim processName As String = "MainApp" loadFile = "" ' filename to load procs = Process.GetProcessesByName(processName) If UBound(procs) >= 0 Then epAddress = New EndpointAddress("net.pipe://localhost/MainAppPicLoad") Client = New picClient(New NetNamedPipeBinding, epAddress) s = Client.LoadPic(loadFile) End If End Sub <System.Diagnostics.DebuggerStepThroughAttribute(), _ System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")> _ Partial Public Class picClient Inherits System.ServiceModel.ClientBase(Of IMainAppPicLoad) Implements IMainAppPicLoad Public Sub New(ByVal binding As System.ServiceModel.Channels.Binding, ByVal remoteAddress As System.ServiceModel.EndpointAddress) MyBase.New(binding, remoteAddress) End Sub Public Function LoadPic(ByVal fName As String) As String Implements IMainAppPicLoad.LoadPic Return MyBase.Channel.LoadPic(fName) End Function End Class ' from here down was auto generated by svcutil. ' svcutil.exe /language:vb /out:generatedProxy.vb /config:app.config http://localhost:8000/MainAppPicLoad ' Some has been simplified after auto code generation. <System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0"), _ System.ServiceModel.ServiceContractAttribute(ConfigurationName:="IMainAppPicLoad")> _ Public Interface IMainAppPicLoad <System.ServiceModel.OperationContractAttribute(Action:="http://tempuri.org/IMainAppPicLoad/LoadPic", ReplyAction:="http://tempuri.org/IMainAppPicLoad/LoadPicResponse")> _ Function LoadPic(ByVal fName As String) As String End Interface <System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")> _ Public Interface IMainAppPicLoadChannel Inherits IMainAppPicLoad, System.ServiceModel.IClientChannel End Interface <System.Diagnostics.DebuggerStepThroughAttribute(), _ System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")> _ Partial Public Class IMainAppPicLoadClient Inherits System.ServiceModel.ClientBase(Of IMainAppPicLoad) Implements IMainAppPicLoad Public Sub New(ByVal binding As System.ServiceModel.Channels.Binding, ByVal remoteAddress As System.ServiceModel.EndpointAddress) MyBase.New(binding, remoteAddress) End Sub Public Function LoadPic(ByVal fName As String) As String Implements IMainAppPicLoad.LoadPic Return MyBase.Channel.LoadPic(fName) End Function End Class End Module <ServiceContract()> Public Interface IMainAppPicLoad <OperationContract()> Function LoadPic(ByVal fName As String) As String End Interface </code></pre> |
28,856,611 | 1 | Set a global variable in other function <p>I am trying to set the value of area and perimeter variable that are calculated in "on_button" function and use those in labels. I am confused with using global in the code, because some says its not good. </p> <pre><code>import Tkinter as tk class SampleApp(tk.Tk): def __init__(self): tk.Tk.__init__(self) self.area = 0 self.widthLabel = tk.Label(self, text="Width:") self.widthLabel.grid(row=0, column=0) self.widthEntry = tk.Entry(self) self.widthEntry.grid(row=0, column=1) self.heightLabel = tk.Label(self, text="Height:") self.heightLabel.grid(row=1, column=0) self.heightEntry = tk.Entry(self) self.heightEntry.grid(row=1, column=1) #self.areaValLabel = tk.StringVar() #self.areaValLabel.set(0) self.areaLabel = tk.Label(self, text="Area:").grid(row=3, column=0) self.areaValLabel = tk.Label(self, textvariable=self.area).grid(row=3, column=1) self.PerLabel = tk.Label(self,text="Perimeter:").grid(row=4, column=0) #self.perValLabel =tk.Label(self, text=perimeter).grid(row=4, column=1) self.button = tk.Button(self, text="Calculate", command=self.on_button).grid(row=2, column=0) def on_button(self): print self.widthEntry.get() print self.heightEntry.get() width = self.widthEntry.get() height = self.heightEntry.get() print float(width)*float(height) self.area.set(float(width)*float(height)) app = SampleApp() app.title("HW1") app.mainloop() </code></pre> |
30,163,242 | 0 | <p>If you <em>uninstall</em> packages, then you run the risk of removing things that were already there, but happened to be upgraded. As a rule, you should use <code>yum</code> (or equivalent) for managing packages, which allows you to <em>downgrade</em> a package. This would remove new packages, and downgrade existing ones. See for example <a href="https://access.redhat.com/solutions/158973" rel="nofollow">How to safely downgrade or remove glibc with yum and rpm</a></p> <p>Selecting the names of packages to downgrade can be done using the output of <code>rpm -qa</code>, formatted to allow simple selection of the given date. For instance (see <em><a href="http://unix.stackexchange.com/questions/2291/centos-list-the-installed-rpms-by-date-of-installation-update">CentOS: List the installed RPMs by date of installation/update?</a></em>), you can list packages in the reverse-order of their install date using</p> <pre><code>rpm -qa --last </code></pre> <p>As a more elaborate approach, you can use the <a href="http://www.rpm.org/wiki/Docs/QueryFormat" rel="nofollow"><code>--queryformat</code></a> option with the <code>:date</code> option to format the date exactly as you want (it uses <a href="http://man7.org/linux/man-pages/man3/strftime.3.html" rel="nofollow"><code>strftime</code></a>).</p> <p>In either case, you can make a script to extract the package names from the output of <code>rpm</code>, and use those packages with <code>yum</code> (or even <code>rpm</code>) to manipulate as needed.</p> <p>When doing a downgrade, there is one odd thing to keep in mind: that revises the install-date for packages to be the <em>current date</em> rather than a complete undo, by using the previous date.</p> |
32,893,610 | 0 | <p>To fix the first block issue:</p> <blockquote> <p>Value of type '<code>UIDynamicBehavior</code>' has no member 'items'</p> </blockquote> <pre><code>let attachmentBehavior:UIAttachmentBehavior = behavior as! UIAttachmentBehavior </code></pre> <p>To fix the second issue:</p> <blockquote> <p>Cannot convert return expression of type '<code>[UIDynamicItem]</code>' to return type '<code>[UICollectionViewLayoutAttributes]?</code>'</p> </blockquote> <pre><code>return self.dynamicAnimator.itemsInRect(rect) as? [UICollectionViewLayoutAttributes] </code></pre> |
14,828,872 | 0 | <p>These postfixes commonly says what is the role of the object.</p> <p>For objects intended to transfer data, it is common to add the <strong>TO</strong> suffix, so we have <code>ServerTO</code>, <code>AccountTO</code>, <code>UserTO</code>, <code>CompanyTO</code>, <code>CustomerTO</code>, <code>SaleItemTO</code>, etc. <strong>TO</strong> is an acronym for <em>Transfer Object</em>. A variation of this is the <strong>DTO</strong> suffix which means <em>Data Transfer Object</em>.</p> <p>For objects intended to control the database access we have the <strong>DAO</strong> suffix for <em>Data Access Object</em>, so we have a <code>UserDAO</code>, <code>CustomerDAO</code>, <code>SalesDAO</code>, etc.</p> <p>The <strong>UI</strong> or <strong>GUI</strong> suffix is frequently used for user interface objects. These are acronyms for <em>Graphical User Interface</em> or simply <em>User Interface</em>.</p> <p>Other common uses of this are <strong>VO</strong> for <em>Value Object</em> and <strong>DO</strong> for <em>Domain Object</em>.</p> <p>I once saw <strong>BE</strong> suffix for <em>Business Entity</em>, <strong>SL</strong> for <em>Service Locator</em> and <strong>PB</strong> for <em>Page Bean</em>.</p> <p>Although this is a common practice in lot of places, I weakly recommend against it. A descriptive name is normally much better than a cryptic acronym suffix (or prefix), but if you can't find one that is not too long, use the acronym. Instead of <code>CustomerTO</code> or <code>CustomerDTO</code> you could name it just <code>Customer</code>. Instead of <code>SalesDAO</code> you could name it <code>SalesPersistence</code> or <code>SalesDatabase</code>. This eliminates the problem of trying to understand what the suffix should mean when you get a <code>VendorDSA</code> or a <code>PersonTF</code>.</p> <p>In partcular the <strong>DTO</strong>, <strong>TO</strong>, <strong>DAO</strong>, <strong>UI</strong>, <strong>GUI</strong>, <strong>VO</strong> and <strong>DO</strong> suffix are very common and widespread. Other suffixes are normally obscure.</p> <p>For your case in special, I have no idea of what is <strong>SO</strong> and <strong>RO</strong>, and I can't do anything better than just guess, which again shows that a descriptive name is better than an acronym as a suffix. My best bet is that <strong>SO</strong> is <em>Service Object</em> and <strong>RO</strong> is <em>Resource Object</em>.</p> |
2,452,771 | 0 | <p>So modify the two lines to:</p> <p>movlps QWORD PTR[rdx], xmm7</p> <p>movss dword ptr [rdx+8], xmm6</p> <p>like here: <a href="http://social.msdn.microsoft.com/Forums/en-US/vcgeneral/thread/4f473acb-7b14-4bf4-bed3-e5e87e1f81e7" rel="nofollow noreferrer">http://social.msdn.microsoft.com/Forums/en-US/vcgeneral/thread/4f473acb-7b14-4bf4-bed3-e5e87e1f81e7</a></p> |
39,428,767 | 0 | <p>When</p> <pre class="lang-java prettyprint-override"><code>String sql = "update StudentDatabaseS set RollNo = ?, FullName = ?, FatherName = ?, FatherCNIC = ?, DateOfBirth = ?, Class = ?, Address = ?, City = ?, Province = ? where RollNo = '"+Srollno+"'"; </code></pre> <p>the line</p> <pre class="lang-java prettyprint-override"><code>ResultSet rs = st.executeQuery(sql); </code></pre> <p>makes no sense because </p> <ol> <li>that query does not return a ResultSet, and</li> <li><code>executeQuery</code> has no way of knowing what values correspond to the parameter placeholders (<code>?</code>).</li> </ol> <p>If you omit that line then the "parameter marker not allowed" error will go away and you can carry on with your UPDATE using the PreparedStatement.</p> |
36,900,596 | 0 | <p>I'm struggling with this on IIS right now and in my struggles, stumbled across an excellent guide for Apache: <a href="https://ngmilk.rocks/2015/03/09/angularjs-html5-mode-or-pretty-urls-on-apache-using-htaccess/" rel="nofollow">https://ngmilk.rocks/2015/03/09/angularjs-html5-mode-or-pretty-urls-on-apache-using-htaccess/</a></p> <p>I hope it helps. </p> |
16,982,112 | 0 | jQuery menu acting strangely <p>on click, the div should move up and be mostly hidden, and then on click again, move back down to original position. Yea.... it's so not doing that. I used animate to move the div +100px, and then -100px, but it is not moving up and off the screen to be hidden. Instead, it moves DOWN, and then starts (I think) working.</p> <p><a href="http://jsfiddle.net/laurelrose18/LLdjh/7/" rel="nofollow">http://jsfiddle.net/laurelrose18/LLdjh/7/</a></p> <pre><code>#panel { } .menu { -webkit-border-bottom-left-radius:38px; -webkit-border-bottom-right-radius:38ßpx; border-bottom-left-radius:38px; border-bottom-right-radius:38px; background: $bluejeans; width: 100px; height:300px; padding-bottom: 25px; } .menu li { margin-bottom: .5em; list-style-type: none; } #menubtn { width: 100px; height: auto; max-width: 100px; margin-top: -100px; } .active { padding-top: 100px; } <div class="container"> <div class="row slidemenu"> <div class="span2 offset10"> <div id="panel"> <ul class="menu flexbox"> <li class="smIcon">sk</li> <li class="smIcon">pr</li> <li class="smIcon">tk</li> <li class="hitext">menu</li> </ul> </div> <div id="menulogo"> <a class="slidebtn" href="#"><img src="images/monogram.png" alt="menu button" id="menubtn"></a> </div> </div> </div> </div> <script type="text/javascript" src="js/jquery-1.10.1.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $(".slidebtn").click(function(){ $("#panel").toggleClass("active"); $("#panel").slideToggle("slow"); return false; }); }); </script> </code></pre> |
33,260,317 | 0 | <p>I finally settled on using a file-based lock to ensure that the task doesn't run twice:</p> <pre><code>def get_lock(name): fd = open('/tmp/' + name, 'w') try: flock(fd, LOCK_EX | LOCK_NB) # open for exclusive locking return fd except IOError as e: logger.warn('Could not get the lock for ' + str(name)) fd.close() return None def release_lock(fd): sleep(2) # extend the time a bit longer in the hopes that it blocks the other proc flock(fd, LOCK_UN) fd.close() </code></pre> <p>It's a bit of a hack, but seems to be working...</p> |
30,863,431 | 0 | <p>In oracle, you can use <code>start with connect by</code> to achieve the same result, no need to use nested query</p> <p>Preparation</p> <pre><code>CREATE TABLE EMP ( EMPNO numeric(4,0), ENAME VARCHAR(10 ), JOB VARCHAR(9 ), MGR numeric(4,0), HIREDATE DATE, SAL numeric(7,2), COMM numeric(7,2), DEPTNO numeric(2,0) ); Insert into EMP (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (7369,'SMITH','CLERK',7902,sysdate,800,null,20); Insert into EMP (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (7499,'ALLEN','SALESMAN',7698,sysdate,1600,300,30); Insert into EMP (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (7521,'WARD','SALESMAN',7698,sysdate,1250,500,30); Insert into EMP (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (7566,'JONES','MANAGER',7839,sysdate,2975,null,20); Insert into EMP (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (7654,'MARTIN','SALESMAN',7698,sysdate,1250,1400,30); Insert into EMP (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (7698,'BLAKE','MANAGER',7839,sysdate,2850,null,30); Insert into EMP (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (7782,'CLARK','MANAGER',7839,sysdate,2450,null,10); Insert into EMP (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (7788,'SCOTT','ANALYST',7566,sysdate,3000,null,20); Insert into EMP (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (7839,'KING','PRESIDENT',null,sysdate,5000,null,10); Insert into EMP (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (7844,'TURNER','SALESMAN',7698,sysdate,1500,0,30); Insert into EMP (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (7876,'ADAMS','CLERK',7788,sysdate,1100,null,20); Insert into EMP (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (7900,'JAMES','CLERK',7698,sysdate,950,null,30); Insert into EMP (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (7902,'FORD','ANALYST',7566,sysdate,3000,null,20); Insert into EMP (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (7934,'MILLER','CLERK',7782,sysdate,1300,null,10); </code></pre> <p>Query:</p> <pre><code>select empno, mgr, ename, level - 1 as T from emp start with mgr is null connect by prior empno = mgr; </code></pre> <p>Output:</p> <pre><code>| EMPNO | MGR | ENAME | T | |-------|--------|--------|---| | 7839 | (null) | KING | 0 | | 7566 | 7839 | JONES | 1 | | 7788 | 7566 | SCOTT | 2 | | 7876 | 7788 | ADAMS | 3 | | 7902 | 7566 | FORD | 2 | | 7369 | 7902 | SMITH | 3 | | 7698 | 7839 | BLAKE | 1 | | 7499 | 7698 | ALLEN | 2 | | 7521 | 7698 | WARD | 2 | | 7654 | 7698 | MARTIN | 2 | | 7844 | 7698 | TURNER | 2 | | 7900 | 7698 | JAMES | 2 | | 7782 | 7839 | CLARK | 1 | | 7934 | 7782 | MILLER | 2 | </code></pre> |
34,730,662 | 0 | iOS CoreData fails to fetch data <p>I am developing an application for iOS which has .xcdatamodeld file with a couple of entities, one of which is UserInfo with an attribute "name" of type <code>String</code>. Now that I am on stage of developing I don't always get entities fetched (I rarely do) and therefore I've got a question: Does that mean I have a problem or is it normal for "Test Flights"? This also happens if I open an app, which stays installed after the last test and test its ability to keep data.</p> <p>Here is how I handle data for this particular entity:</p> <pre><code>private func fetchData(){ let fetch = NSFetchRequest(entityName: entityName) var entities = [UserInfo]() do { entities = try moc.executeFetchRequest(fetch) as! [UserInfo] }catch{ delegate.currVC.showSystemMessage("Failed to execute data for \(fetch.entityName!) fetch request", ofType: .ERROR) } if entities.count > 0{ print("Entities found: \(entities.count)") let last = entities.first! name = last.name } } func saveData(){ let fetch = NSFetchRequest(entityName: entityName) var entities = [UserInfo]() do { entities = try moc.executeFetchRequest(fetch) as! [UserInfo] }catch{ delegate.currVC.showSystemMessage("Failed to execute data for \(fetch.entityName!) fetch request", ofType: .ERROR) } if entities.count > 0{ let last = entities[0] last.name = name do{ try moc.save() }catch{ delegate.currVC.showSystemMessage("An error occured while trying to save user data", ofType: .ERROR) } }else{ let entity = NSEntityDescription.insertNewObjectForEntityForName(entityName, inManagedObjectContext: moc) as! UserInfo entity.setValue(name, forKey: "name") do{ try moc.save() }catch{ delegate.currVC.showSystemMessage("Failed to save name to CoreData", ofType: .ERROR) } } } </code></pre> <p>Notes: <code>moc</code> is an <code>NSManagedObjectContext</code> which I keep as a constant in delegate and only initialize once. <code>showSystemMessage</code> is a custom method, which, by the way, is never triggered by this method (which means nothing's caught inside of this whole method).</p> <p>My assumptions are that this might be happening because <code>executeFetchRequest</code> is executed in a new Thread and therefore sometimes fails to fetch data before it's returned, but, yet again, I have no idea if it is so or not. Anyway, I really am looking forward to solving this issue with your help, since it is crucial for my app to have an ability to keep data. Thank you in advance!</p> |
19,684,732 | 0 | Program of consumer Producer <p>I need to make a consumer producer problem for homework. I am stuck repeating the the thread. Only 1 object is produced and only 1 object is consumed. If object is present in array then producer does not produce and wait till consumer consumes it. </p> <pre><code>class PC extends Thread{ static int i=1; static int storage[]=new int[1]; String info; PC(String _info) { this.info=_info; } public synchronized void consume() { if(storage[0]==-1) { try { System.out.println("C: 0" ); wait(); } catch(InterruptedException e) { System.out.println("InterruptedException caught"); } } else { System.out.println("C: " + storage[0]); storage[0]=-1; i++; notify(); } } public synchronized void prod() { if(storage[0]!=-1) { try { System.out.println("P: 0" ); wait(); } catch(InterruptedException e) { System.out.println("InterruptedException caught"); } } else { storage[0]=i; System.out.println("P: " + storage[0]); notify(); } } public void run() { if(info=="producer"){ prod(); } else consume(); } public static void main(String args[]) { storage[0]=-1; PC consumer =new PC("consumer"); PC producer =new PC("producer"); consumer.start(); producer.start(); } </code></pre> <p>}</p> |
24,832,063 | 0 | <p>OK So I have fixed whatever issue was causing it to crash, below is what I changed:</p> <p>Step One: Created entirely new project and completed developer console, published just a simple button to login. It works. I now know that my Unity3d, Android APK and Developer Console procedures are all correct.</p> <p>Step Two: Go to project I am trying to get working and create a new scene, again only adding a login button. It works. So I now now that my Project is fine, something to do with the code.</p> <p>Step Three: I commented out all code and objects and slowly added back one by one.. this was painful. But I located the source of the problem, the issue was that a new player when trying to load from the cloud had no data stored and thus the data array returned was uninitialized, I was accounting for this by doing an if(data.length > 0) however this causes a crash anyways, so a simple try and catch and just use the data returned as if assuming its correct works great.</p> |
13,457,679 | 0 | Mailto link with display name in non-Latin characters doesn't work correctly in Chrome browser <p>I have the following problem in Chrome browser: When I have a mailto link with display name in non-Latin characters and email address the right button->copy email address->paste anywhere doesn’t work correctly. The display name is broken /with escape characters/. </p> <p>For example: </p> <p><code><a href="mailto:нова категория <[email protected]>?Subject=[Enter your subject title here]&body=[Enter your content email here]">нова категория</a></code></p> <p>If you try this in Chrome Copy Email Address doesn’t work correctly. Does anyone know how can I fix this problem or this problem is bug in Chrome? </p> <p>Please help and thanks in advance.</p> |
35,367,363 | 0 | <p>Ok, so I solved it (pretty much). The password and username in my odbc files were being ignored. Because I was calling the DB queries from Asterisk, I was using a file called res_odbc.ini too. This contained my username and password also, and when I run the query from Asterisk, it conencts and returns the correct result.</p> <p>In case it helps, here is my final working configuration.</p> <p>odbc.ini</p> <pre><code>[asterisk-connector] Description = MS SQL connection to asterisk database driver = /usr/lib64/libtdsodbc.so servername = SQL2 Port = 1433 User = MyUsername Password = MyPassword </code></pre> <p>odbcinst.ini</p> <pre><code>[FreeTDS] Description = TDS connection Driver = /usr/lib64/libtdsodbc.so UsageCount = 1 [ODBC] trace = Yes TraceFile = /tmp/sql.log ForceTrace = Yes </code></pre> <p>freetds.conf</p> <pre><code># $Id: freetds.conf,v 1.12 2007/12/25 06:02:36 jklowden Exp $ # # This file is installed by FreeTDS if no file by the same # name is found in the installation directory. # # For information about the layout of this file and its settings, # see the freetds.conf manpage "man freetds.conf". # Global settings are overridden by those in a database # server specific section [global] # TDS protocol version ; tds version = 4.2 # Whether to write a TDSDUMP file for diagnostic purposes # (setting this to /tmp is insecure on a multi-user system) dump file = /tmp/freetds.log ; debug flags = 0xffff # Command and connection timeouts ; timeout = 10 ; connect timeout = 10 # If you get out-of-memory errors, it may mean that your client # is trying to allocate a huge buffer for a TEXT field. # Try setting 'text size' to a more reasonable limit text size = 64512 # A typical Sybase server [egServer50] host = symachine.domain.com port = 5000 tds version = 5.0 # A typical Microsoft server [SQL2] host = 192.168.1.59 port = 1433 tds version = 8.0 </code></pre> <p>res_odbc.conf</p> <pre><code>[asterisk-connector] enabled = yes dsn = asterisk-connector username = MyUsername password = MyPassword pooling = no limit = 1 pre-connect = yes </code></pre> <p>Remember if you are using Centos 64 bit to modify the driver path to lib64. Most of the guides online have the wrong (for 64 bit) paths.</p> <p>Good luck - it's a headache :)</p> |
6,153,297 | 0 | Opening another window in an Appcelerator Titanium-app doesn't work <p>I've got basically 5 windows in my iPad-application (created with Appcelerator Titanium) and want to be able to navigate forth and back (a back and and a next-button for that purpose). The following approach doesn't work. Nothing happens upon clicking the button.</p> <p>The first window is opened in my app.js like this:</p> <pre><code>var window = Titanium.UI.createWindow({ url:'mainwindows.js', modal: true }); window.open(); </code></pre> <p>then in mainwindows.js I've got a button called 'next' which does this:</p> <pre><code>buttonNext.addEventListener('click', function(e){ var newWindow = Titanium.UI.createWindow({ url: "step_1.js", title: "Step 1" }); win.open(newWindow, { animated:true}) }); </code></pre> |
7,009,813 | 0 | <p>Try by using the <a href="http://silverlight.codeplex.com/" rel="nofollow">Silverlight toolkit for Windows Phone 7</a>. If you need to capture the Tap event on the page, you've to use the services of the GestureListner class. </p> <pre><code><phone:PhoneApplicationPage xmlns:toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone" xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" x:Name="phoneApplicationPage" x:Class="XXXXX" > <toolkit:GestureService.GestureListener> <toolkit:GestureListener Tap="Page_Tap" /> </toolkit:GestureService.GestureListener> . . . </code></pre> |
39,862,765 | 0 | How do I get the device given a UUID from libblkid? <p>I know how to get the UUID of a device via libblkid... how do I do the reverse?</p> <p>Given a UUID, I want to find what the device path is.</p> |
15,908,210 | 0 | <p>This is probably because your background image doesn't get repeated (as do the corner images) therefore, it will get covered up by one of the corner pictures. Try to set the first background-image to repeat:</p> <pre><code>background-repeat: repeat, no-repeat, no-repeat, no-repeat, no-repeat; </code></pre> |
17,371,953 | 0 | <p>I think so yes</p> <pre><code>1.9.3-p392 :002 > DateTime.new => Mon, 01 Jan -4712 00:00:00 +0000 1.9.3-p392 :003 > _.cwday => 1 </code></pre> |
26,794,670 | 0 | <p>You must call reader.mark() <em>before</em> the first while loop; reader.mark() essentially saves the current position of the reader so that you can go back to that position when you call reader.reset().</p> <p>You will also not want to pass in 0 to reader.mark(). See the java spec for the parameter below:</p> <p>readAheadLimit - Limit on the number of characters that may be read while still preserving the mark. An attempt to reset the stream after reading characters up to this limit or beyond may fail. A limit value larger than the size of the input buffer will cause a new buffer to be allocated whose size is no smaller than limit. Therefore large values should be used with care.</p> <p>(In other words, passing in 0 will be useless. You need to pass in a number larger than the number of characters read in between mark() and reset()).</p> |
11,446,667 | 0 | <p>Instead of .subproject_thingie1 and .subproject_thingie2 everywhere I usually go for adding a root class or id to differentiate between projects/pages.</p> <p>That way you can have global styling maintained on all pages on the same class names while being able to add specific rules for specific pages.</p> <p>But as always, the best solution depends on how well the existing project is written.</p> |
20,202,989 | 0 | The scientific study of the principles of heredity and the variation of inherited traits among related organisms. |
14,334,909 | 0 | Sprite not showing renderToTexture Map / rendertarget map <p>I am working with three.js and I set up a second scene and camera and added a cylinder to it. Now I setup a rendertarget and I wanted to show this renderedScene on a sprite (HUD-Sprite so to say), but the sprite is not showing up. I added a plane into the original scene and it shows the rendertarget perfectly fine.</p> <p>What I already checked:</p> <p>1) When using the rtTexture as a map for a MeshLambertMaterial, it works perfectly fine</p> <p>2) When loading an image for the sprite with <em>ImageUtils</em> and using this as a map for the SpriteMaterial, it works great and the spline is showing up where it should be!</p> <p>I have the feeling that I overlooked something. Would be cool if someone can help me.</p> <p>OK, guys, i created a jsFiddle, maybe this helps!</p> <p><a href="http://jsfiddle.net/Pk85y/38/" rel="nofollow">My Fiddle for RenderTarget Sprite Problem</a></p> <p>as you can see there, the rendertarget is correctly display on the plane and there is a sprite with screenspace coordinates in there but it does not show the renderTarget.</p> <pre><code>rttMaterial = new THREE.SpriteMaterial( { color: 0xFF0000, map: rtTexture, alignment: THREE.SpriteAlignment.topLeft, useScreenCoordinates: true} ); </code></pre> <p>Thank you in Advance</p> |
38,689,468 | 0 | <p>change the trigger element to button.</p> <pre><code> triggerEl: 'button' </code></pre> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.