Team Ai
Datasetpublic

VishwaSharma84/stack_overflow_data

sourceHugging Faceopenrailupdated 3y agoView on Hugging Face
0likes11downloads
test.tsv7466 linesDownload Raw Back to root
1pid	label	text239424767	0	android studio emulator: WARNING: Increasing RAM size to 1024MB <p>I am trying to build my first android application in Android Studio, following the tutorial <a href="https://developer.android.com/training/basics/firstapp/creating-project.html" rel="nofollow">https://developer.android.com/training/basics/firstapp/creating-project.html</a>, using AndroidStudio 2.1.2. </p> <p>Whenever I run the emulator, I get this error message:</p> <blockquote> <p>Android Emulator could not allocate 1.0 GB of memory for the current AVD configuration. Consider adjusting the RAM size of your AVD in the AVD Manager. Error detail: QEMU 'pc.ram': Cannot allocate memory</p> </blockquote> <p>Decreasing the size of the memory on the Nexus5x emulator has no effect, so the error message still says "could not allocate 1.0 GB", even when I adjust the memory of the AVD to 256MB. The app needs to run on Android 6.0, with a Nexus5x emulator, so I can't try with a different emulator. Any help would be much appreciated :)</p>38991182	0	Difference between different datasources <p>Him Please explain what is the difference between different datasources for SQL (shown in the pic.) </p> <p>I mean difference between Microsoft SQL Server and Microsoft SQL Server Database File</p> <p><img src="https://i.stack.imgur.com/APLoX.jpg" alt="enter image description here"></p>426237094	0	 <p>Use a separate query analyzer with the KeywordTokenizerFactory, thus (using your example):</p> <pre><code> &lt;analyzer type="index"&gt; &lt;tokenizer class="solr.LowerCaseTokenizerFactory"/&gt; &lt;filter class="solr.StopFilterFactory" ignoreCase="true" words="stopwords.txt" enablePositionIncrements="false" /&gt; &lt;filter class="solr.ShingleFilterFactory" maxShingleSize="5" outputUnigrams="false"/&gt; &lt;filter class="solr.RemoveDuplicatesTokenFilterFactory"/&gt; &lt;/analyzer&gt; &lt;analyzer type="query"&gt; &lt;tokenizer class="solr.KeywordTokenizerFactory"/&gt; &lt;filter class="solr.StopFilterFactory" ignoreCase="true" words="stopwords.txt" enablePositionIncrements="false" /&gt; &lt;filter class="solr.LowerCaseFilterFactory"/&gt; &lt;filter class="solr.RemoveDuplicatesTokenFilterFactory"/&gt; &lt;/analyzer&gt; </code></pre>529714091	0	how to save and restore an object into a file in matlab? <p>I have a class like this:</p> <pre><code>classdef my_class properties prop_a prop_b end methods(Static) ... function o = load() ??? end end methods function save(o) ??? end ... end end </code></pre> <p>Please help me to write save and load methods. name of methods is clear and they should save and restore an object from a text file...</p> <p>the properties are quite dynamic and have different row/col number.</p>625989684	0	How to bind an alert message with the controller? <p>Hi guys I've been experimenting with a simple commenting app with AngularJS and I'm stuck on how to get an alert message popup in the view if a user inputs an empty string into an input field.</p> <p><strong>The HTML view and ng-show logic as below</strong>:</p> <pre><code>&lt;div ng-show="alert===true" class="alert alert-warning alert-dismissible inner" role="alert"&gt; &lt;button type="button" class="close" data-dismiss="alert"&gt;&lt;span aria-hidden="true"&gt;&amp;times; &lt;/span&gt;&lt;span class="sr-only"&gt;Close&lt;/span&gt;&lt;/button&gt; &lt;strong&gt;Warning!&lt;/strong&gt; You did not submit a comment. &lt;/div&gt; </code></pre> <p><strong>The controller view and $scope logic as below</strong>: </p> <pre><code>// pushes data back to Firebase Array $scope.addComment = function(){ if ($scope.newComment.text === ''){ $scope.alert = true; } else { $scope.alert = false; } $scope.comments.$add($scope.newComment); $scope.newComment = {text: '', date: ''}; }; </code></pre> <p>The problem is that although I can bind the alert message logic to the HTML view, the alert message only shows up once and cannot be re-used again if the user types in an empty string again.</p> <p>Should I use a while loop or something for this? Any help would be much appreciated!</p> <p><strong>EDIT:</strong></p> <p>Thanks to meriadec's feedback, I have made a fix using a more simple codebase, as follows.</p> <p><strong>The HTML view and ng-show logic as below</strong>:</p> <pre><code>&lt;div ng-show="alert===true" class="alert alert-warning inner" role="alert"&gt; &lt;button type="button" class="btn" ng-click="alert=false"&gt;&lt;span aria-hidden="true"&gt;&amp;times; &lt;/span&gt;&lt;span class="sr-only"&gt;Close&lt;/span&gt;&lt;/button&gt; &lt;strong&gt;Warning!&lt;/strong&gt; You did not submit a comment. &lt;/div&gt; </code></pre> <p><strong>The controller view and $scope logic as below</strong>: </p> <pre><code>// pushes data back to Firebase Array $scope.addComment = function(){ if ($scope.newComment.text === ''){ return $scope.alert = true; }; $scope.comments.$add($scope.newComment); $scope.newComment = {text: '', date: ''}; }; </code></pre>74841203	0	how to create a pam module? <p>Can anyone tell me about this... I want to create a pam module similar to the login module in /etc/pam.d</p>820086791	0	How can I send an email with a layout <p>I am using grails mail plugin. When I submit my form, it will send an email from aaa@example.com to textField name="email successfully but how can I send an email with a layout...not blank like this picture <a href="http://www.4shared.com/photo/uT2YUCfo/Capture__2_.html" rel="nofollow">http://www.4shared.com/photo/uT2YUCfo/Capture__2_.html</a> or maybe some CSS..</p> <p><strong>FORM</strong></p> <pre><code>&lt;g:form action="send"&gt; &lt;table style="width:500px"&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;Your Email Address &lt;/td&gt; &lt;td&gt;&lt;g:textField style="width:250px" name = "email"/&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Your Name&lt;/td&gt; &lt;td&gt;&lt;g:textField style="width:250px" name = "user"/&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;input type="submit"/&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;/g:form&gt; </code></pre> <p><strong>MAIL CLOSURE</strong></p> <pre><code>def send = { sendMail { to params.email from "aaa@yahoo.com" subject "Test Reset Password" body(view:"/user/layoutmail",model:[name:params.user]) } render "Email Terkirim" } </code></pre>930733824	0	 <p>Yes. The code is executed in serial.</p>1025159920	0	 <p>You may start with that base : <a href="http://jsfiddle.net/8r99k/" rel="nofollow">http://jsfiddle.net/8r99k/</a><br> I put sample text and only a few css :</p> <pre><code>html{ margin:0; padding:0; width:calc(100% - 100px); height:calc(100% - 100px); border:solid #eeeeee 50px; overflow:hidden; } body{ margin:0; padding:0; height:100%; overflow:auto; } </code></pre> <p><strong>Update</strong><br> Adding <code>width:100%</code> and <code>padding-right:70px</code> to <code>body</code><br> <a href="http://jsfiddle.net/8r99k/2/" rel="nofollow">http://jsfiddle.net/8r99k/2/</a></p>1111137452	0	 <p>Considering the fact that you want to get "select new " shown ... you still need to send something to the view. Take the entity with the most fields that are present in your new entity.</p> <p>Create a partial class </p> <pre><code>namespace YourDomain.Model { [MetadataType(typeof(EntityWithinXList))] public partial class EntityWithinXList { [DataMember] public string DesiredFieldFromA{ get; set; } [DataMember] public int DesiredFieldFromB{ get; set; } } public class EntityWithinXList { } </code></pre> <p>So you need to add 2 new fields from 2 other tables to your entity:</p> <pre><code> var list = (from x in xList join a in AList on x.commonfield equals a.commonfield join b in BList on x.newCommonField equals b.newCommonField select new { x, a.DesiredFieldFromA, b.DesiredFieldFromB }).ToList(); list.ForEach(el =&gt; { el.x.DesiredFieldFromA= el.DesiredFieldFromA; el.x.DesiredFieldFromB= el.DesiredFieldFromB ; }); return list.Select(p=&gt;p.x); </code></pre> <p>Unless I've misunderstood your question this should do it . And the list that you are sending to the view is <code>List&lt;EntityWithinXList&gt;</code></p>1220357993	0	Creating mobile app in Symfony2 <p>I read that there is an option to create a mobile app in symfony2 and I don't really understand how to create it. As much as I do understand the concepct of emulating HTML5 to native app I don't know HOW to do the same thing with symfony. </p> <p>Lets say that we created the app in html5. We just go through the process with PhoneGap and it creates the native app ( yeah, I know, very simplified ). But how should I do it with Symfony? I mean.. is there any similar emulator for php and...all the files that symfony contains or.. or what? How to make it work on iOS, how on Android, how on Windows Phone and BlackBerry..</p> <p>Sorry for dumb question but I couldn't find proper answer.</p>1333034681	0	 <p>In the <a href="https://github.com/JakeWharton/u2020">Jake Wharton U2020 application</a> it is solved in the next way</p> <p>Add to you gradle.build file</p> <pre><code>configurations.all { resolutionStrategy { force 'com.android.support:support-annotations:23.0.1' } } </code></pre>1440416451	0	Query returing no results codename one <p>Query showing no results and not giving any error .control not entering inside the if block help me out that where is the mistake i am doing ? i have tried many ways to get the result but all in vain. When i tried the following before the if statement </p> <pre><code>int column=cur.getColumnCount(); Row row=cur.getRow(); row.getString(0); </code></pre> <p>then i got the resultset closed exception</p> <pre><code>Database db=null; Cursor cur=null; System.out.print("Printing from accounts class "+Email+Password); String [] param={Email,Password}; System.out.print(param[0]+param[1]); try{ db=Display.getInstance().openOrCreate("UserAccountsDB.db"); cur= db.executeQuery("select * from APPUserInfo WHERE Email=? AND Password=?",(String [])param); int columns=cur.getColumnCount(); if(columns &gt; 0) { boolean next = cur.next(); while(next) { Row currentRow = cur.getRow(); String LoggedUserName=currentRow.getString(0); String LoggedUserPassword=currentRow.getString(1); System.out.println(LoggedUserName); next = cur.next(); } } }catch(IOException ex) { Util.cleanup(db); Util.cleanup(cur); Log.e(ex); } finally{ Util.cleanup(db); Util.cleanup(cur); } </code></pre>155745113	0	 <p>If I understood your question, you want the duplicated row of selects to reset their values.</p> <p>In this case you can just remove this:</p> <pre><code>dropdownclone.find('select').each(function(index, item) { //set new select to value of old select $(item).val( $dropdownSelects.eq(index).val() ); }); </code></pre> <p>and replace it with:</p> <pre><code>dropdownclone.find('option').attr('selected', false); </code></pre>1638242048	0	Expect not accepting negative values <p>I am trying to run <code>expect</code> with negative values. But I'm getting bad flag error.</p> <p>Test File:</p> <pre><code>echo "Enter Number:" read num echo $num </code></pre> <p>Expect File:</p> <pre><code>spawn sh test.sh expect -- "Enter Number:" {send "-342345"} </code></pre> <p>I even tried to escape negative values with <code>\</code> option still it's not working.</p>172230111	0	What to not include in Git repository? <blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="http://stackoverflow.com/questions/1644653/which-files-in-a-visual-c-studio-project-dont-need-to-be-versioned">Which files in a Visual C# Studio project don&rsquo;t need to be versioned?</a> </p> </blockquote> <p>when creating a repository, what do you include in the repository, should folders like Resharper, Debug and Bin folder be included? if not, is it possible to exclude files/folders from the unstaged changes check?</p>1812513218	0	 <p>This will definitely do the task for you.</p> <pre><code>tTable = {} OldIDX, OldIDX2, bSwitched, bSwitched2 = 0, 0, false, false for str in io.lines("txt.txt") do local _, _, iDx, iDex, sIdx, sVal = str:find( "^%| ([%d|%s]?) %| ([%d|%s]?) %| (%S?) %| (%S?) %|$" ) if not tonumber(iDx) then iDx, bSwitched = OldIDX, true end if not tonumber(iDex) then iDex, bSwitched2 = OldIDX2, true end OldIDX, OldIDX2 = iDx, iDex if not bSwitched then tTable[iDx] = {} end if not bSwitched2 then tTable[iDx][iDex] = {} end bSwitched, bSwitched2 = false, false tTable[iDx][iDex][sIdx] = sVal end </code></pre> <h1>NOTE</h1> <p>The only thing you can change in the code is the name of the file. :)</p> <h1>EDIT</h1> <p>Seems like I was wrong, you did need some changes. Made them too.</p>1920801157	0	 <p>Normally it can't. It will complain about libc being too old, for one.</p> <p>If you statically link with libstdc++ and carefully avoid newer glibc features, you may be able to get away with it. The latter is not always possible though. Static linking with libc is not officially supported and may work or not work for you.</p>201221935	0	 <p>I think you can't with the grouped style of the UITableView. You could however use the plain style, and create your own view to show as the cell, just like the grouped view.</p>2122237682	0	 <p>You have to <code>declare</code> the overload in the header and <code>define</code> it in the cpp file. Ex.:</p> <p>MyHeader.h:</p> <pre><code>Fraction&amp; operator+(const Fraction&amp; l, const Fraction&amp; r); </code></pre> <p>MyFile.cpp:</p> <pre><code>Fraction&amp; operator+(const Fraction&amp; l, const Fraction&amp; r){ // ... </code></pre>2240292211	0	 <p><strong>Change the add to cart text on product archives by product types</strong> Here is a <a href="https://docs.woocommerce.com/document/change-add-to-cart-button-text/" rel="nofollow">Complete Example</a> </p> <p><strong>Change this line as per your needed !</strong></p> <pre><code>case 'variable': return __( 'Select options', 'woocommerce' ); </code></pre> <p><strong>Complete code</strong> Add the following to your <code>functions.php</code> file and edit the buttons text.</p> <pre><code>add_filter( 'woocommerce_product_add_to_cart_text' , 'custom_woocommerce_product_add_to_cart_text' ); function custom_woocommerce_product_add_to_cart_text() { global $product; $product_type = $product-&gt;product_type; switch ( $product_type ) { case 'external': return __( 'Buy product', 'woocommerce' ); break; case 'grouped': return __( 'View products', 'woocommerce' ); break; case 'simple': return __( 'Add to cart', 'woocommerce' ); break; case 'variable': return __( 'Select options', 'woocommerce' ); // Change this line break; default: return __( 'Read more', 'woocommerce' ); } } </code></pre>2319292671	0	 <p>Try this:</p> <pre><code>textarea { overflow-x: vertical; } </code></pre>2421975919	0	 <p>That error means that Laravel is trying to write data to your <strong>storage/view</strong> file, but it doesn't have permissions (write access). Storage/view is a folder for caching view files.It is default Laravel behaviour, so change permissions on whole storage folder, becuse there is more files inside, that Laravel will try to use for other purposes. For example, <strong>services.json</strong> is used when you add new service provider, and if it is locked, Laravel will complain.</p>2540545851	0	jQuery - Search on text entry - delay until full term entered <p>I have the following code, which detects any text entered into the <code>#search-box</code> field and then immediately runs the search (if greater than 2 characters):</p> <pre><code>$('#search-box').on('input', function() { var term = $(this).val(); if (term.length &gt; 2) { //execute search and display results } }); </code></pre> <p>This doesn't look pretty though, as if you were to type <code>dollar</code> for example, after 'doll' a load of dolls will appear, which will then be replaced with dollars once <code>dolla</code> is entered. This can happen in a split second.</p> <p>What I'd like to do is determine whether the user has finished the search term. Is it possible to wait for a second or 2 before doing the search? And if in that waiting period the user enters another letter, it resets the clock?</p>263622549	0	Idiomatic way to write .NET interop function <p>I'm looking for a more idiomatic way, if possible, to write the following clojure code:</p> <pre><code>(import '(System.Net HttpWebRequest NetworkCredential) '(System.IO StreamReader)) (defn downloadWebPage "Downloads the webpage at the given url and returns its contents." [^String url ^String user ^String password] (def req (HttpWebRequest/Create url)) (.set_Credentials req (NetworkCredential. user password "")) (.set_UserAgent req ".NET") (def res (.GetResponse req)) (def responsestr (.GetResponseStream res)) (def rdr (StreamReader. responsestr)) (def content (.ReadToEnd rdr)) (.Close rdr) (.Close responsestr) (.Close res) content ) </code></pre> <p>This is on ClojureCLR and works. (the fact that it's the CLR variant doesn't matter much)</p> <p>I'd like to get rid of the defs (replace by lets? can they refer to each other?)</p> <p>How about a better way to get to the stream - keeping in mind that .. chaining won't work because I need to Close the streams later on.</p> <p>EDIT: After the answer, I found a much easier way in .NET to download a web page using the WebClient class. I still used many of Michal's recommended approaches - just wanted to record what I now believe to be the best answer:</p> <pre><code>(defn download-web-page "Downloads the webpage at the given url and returns its contents." [^String url ^String user ^String password] (with-open [client (doto (WebClient.) (.set_Credentials (NetworkCredential. user password "")))] (.DownloadString client url))) </code></pre>276267788	0	Making pre- and post-build event scripts pretty? <p>I have some moderately hefty pre- and post-build event scripts for my Visual Studio 2008 projects (actually it's mainly post-build event scripts). They work OK in that they function correctly and when I <code>exit 0</code> the build succeeds and when I <code>exit 1</code> the build fails with an error. However, that error is enormous, and goes something like this:</p> <pre><code>The command "if Release == Debug goto Foo if Release == Release goto Bar exit 0 :Foo mkdir "abc" copy "$(TargetDir)file.dll" "abc" [...] " exited with code 1. </code></pre> <p>You get the idea. The entire script is always dumped out as part of the error description. The entire script is also dumped out in the Output window while the build is happening, too. So, why have I seen various references on the web to using <code>echo</code> in these scripts? For example, here's part of an example on one particular site:</p> <pre><code>:BuildEventFailed echo POSTBUILDSTEP for $(ProjectName) FAILED exit 1 :BuildEventOK echo POSTBUILDSTEP for $(ProjectName) COMPLETED OK </code></pre> <p>Is there a way to get Visual Studio to suppress all script output apart from what is <code>echo</code>ed (and therefore using <code>echo</code> only to output what you want would make sense), or are these examples just misguided and they don't realize that the whole script is always dumped out?</p>2834633552	0	 <p>There are a few ways to do this:</p> <p>1) PHP: Using PHP, you can simply include an html file into another one</p> <pre><code>&lt;?php include('fileOne.html'); ?&gt; </code></pre> <p>2) jQuery: Using jQuery, you can load an HTML page dynamically into another (this is kind of hacky in my opinion):</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;script src="jquery.js"&gt;&lt;/script&gt; &lt;script&gt; $(function(){ $("#includedContent").load("b.html"); }); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="includedContent"&gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <blockquote> <p>Source: <a href="http://stackoverflow.com/questions/8988855/include-another-html-file-in-a-html-file">Include HTML Page via jQuery</a></p> </blockquote> <p>3) Framework: Using a framework like Python/Django, you can use {% include %} blocks to create standalone html files that can be reused like blocks.</p> <pre><code>&lt;html&gt; {% include 'navbar.html' %} &lt;/html&gt; </code></pre> <p>My honest recommendation is #2 if you have to stay with just raw html, otherwise, if you are using PHP then includes are a no brainer. The last option is the frameworks, and that is really only if you have other heavy-duty functions you would need.</p>292430673	0	 <p>i think you must miss some proper argument which should be a pointer type in your method declaration.</p>3016607326	0	 <p>480 * 800 is a <strong>mdpi</strong> device. You can can put these image resources in <strong>drawable-mdpi</strong> if you want the device to auto adjust for smaller and larger screen sizes. If you want these images to be of maximum size you can put it in <strong>drawable-xhdpi</strong>. If not i.e. if you want same image to be used in all the screen sizes then you can simply put in <strong>drawable</strong> folder in resource. </p> <p>For more information you can check this :<a href="http://developer.android.com/guide/practices/screens_support.html" rel="nofollow">developer link</a></p>3130421058	0	How to tell Faraday to preserve hashbang in site URL? <p>I'm working on a fork of a library that implements Faraday to build URLs.</p> <pre class="lang-rb prettyprint-override"><code>site = "https://example.io/#/" path = "oauth/authorize" connection = Faraday.new(site) resource = Faraday::Utils.URI(path) URL = connection.build_url(resource) </code></pre> <p>Notice that my site URL ends with a hashbang. But when the above code is executed, Faraday strips out the hashbang entirely:</p> <blockquote> <p><strong><a href="https://example.io/oauth/authorize" rel="nofollow">https://example.io/oauth/authorize</a></strong></p> </blockquote> <p>But my application requires it to build this URL (with the hashbang):</p> <blockquote> <p><strong><a href="https://example.io/#/oauth/authorize" rel="nofollow">https://example.io/#/oauth/authorize</a></strong></p> </blockquote> <p>Now before I go ripping out Faraday and monkey-patching something terrible.. can I do this by setting an option on Faraday? </p>325373508	0	 <p>You can simply overload the enqueue class to take both Dates and Integers. In either case, it sounds like you need a method getValue() in CInteger that lets you access the int value.</p> <pre><code>public class CInteger { //constructors, data public void getValue() { return i; } } </code></pre> <p>and then you can have two enqueue() methods in your other class:</p> <pre><code>public void enqueue(Date d) { add(tailIndex, d); } public void enqueue(CInteger i) { add(tailIndex, new Integer(i.getValue()); //access the int value and cast to Integer object } </code></pre> <p>And Java will know which one you are calling automatically based on the parameters.</p>3314994030	0	 <p>To programmatically instantiate the component instead of a declarative implementation, use <code>addElement()</code> to add components to the display list.</p> <p>For example, to add a visual element to a Spark Group named <code>container</code>.</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" creationComplete="creationCompleteHandler(event)"&gt; &lt;fx:Script&gt; &lt;![CDATA[ import mx.core.UIComponent; import mx.events.FlexEvent; protected function creationCompleteHandler(event:FlexEvent):void { var component:UIComponent = new UIComponent(); component.x = 5; component.y = 5; container.addElement(component); } ]]&gt; &lt;/fx:Script&gt; &lt;s:Group id="container" /&gt; &lt;/s:Application&gt; </code></pre> <p>Within script blocks, use package namespaces instead of MXML namespaces.</p> <pre><code>import com.msns.Component; var component:Component = new Component(); component.x = 5 </code></pre>3429693526	0	Are there any Java APIs for for planning or say creating time table <p>Some time back, while Googling, I found a Java API (as I remember it was an Apache project but I am not sure) for creating timetables. By time table I mean simple timetable used in schools and colleges </p> <p>Unfortunately I didn't take note of that API and now I cannot find it.</p> <p>Please tell me if you know any such open source API available in Java.</p>3540956699	0	Hide attributes out of stock on product page PRESTASHOP 1.6 <p>I need help with hiding attributes out of stock on product page when selected some of attributes. Prestashop 1.6.1.9 I did not find ready-made solution. I'm bad at programming in php and java script, I believe I should be the knowledge that would solve this problem.</p> <p>For example.</p> <p>Product combinations should disappear if a certain combo is not currently in stock. For example on one product we might have S M L and 5 color variations, so 15 options. But maybe we only have size M in one color. The customer has to click through each color to find what is available as all colors show up if there is even one size M color available. It's only a problem when combos are partially out of stock. </p> <p>It is necessary to make it work for the block as in the screenshot.</p> <p>I would be very grateful for any help. Thanks in advance. Best Regards. Aleksandrs</p> <p><a href="https://i.stack.imgur.com/tB7hk.png" rel="nofollow noreferrer">Screenshot</a></p>361502685	0	 <p>You can open an interactive shell by right-clicking on the project, selecting <strong>Scala</strong>-> <strong>Create interpreter in XYZ</strong>.</p>379960073	0	 <p>You can use <strong><a href="http://php.net/manual/en/function.mktime.php" rel="nofollow">mktime()</a></strong> or <strong><a href="http://php.net/manual/en/function.strtotime.php" rel="nofollow">strtotime()</a></strong></p> <pre><code>$input_time = mktime(0,0,0,$_POST['m']+1,0,$_POST['y']); if ($input_time &lt; time()){ print '&lt;p class = "error"&gt;Date has elapsed&lt;/p&gt;'; } </code></pre>381769169	0	 <p>Toy can try something like this</p> <pre><code> declare @t table (i int, d datetime) insert into @t (i, d) select 1, '17-Nov-2009 07:22:13' union select 2, '18-Nov-2009 07:22:14' union select 3, '17-Nov-2009 07:23:15' union select 4, '20-Nov-2009 07:22:18' union select 5, '17-Nov-2009 07:22:17' union select 6, '20-Nov-2009 07:22:18' union select 7, '21-Nov-2009 07:22:19' --order that I want select * from @t order by d desc, i declare @currentId int; set @currentId = 4 SELECT TOP 1 t.* FROM @t t INNER JOIN ( SELECT d CurrentDateVal FROM @t WHERE i = @currentId ) currentDate ON t.d &lt;= currentDate.CurrentDateVal AND t.i != @currentId ORDER BY t.d DESC SELECT t.* FROM @t t INNER JOIN ( SELECT d CurrentDateVal FROM @t WHERE i = @currentId ) currentDate ON t.d &gt;= currentDate.CurrentDateVal AND t.i != @currentId ORDER BY t.d </code></pre> <p>You must be carefull, it can seem that 6 should be both prev and next.</p>3919205962	0	 <p>I also get this error sometimes but only on the emulator - seems like an emulator bug to me.</p> <p><a href="http://stackoverflow.com/questions/2437366/android-emulator-internet-access">Android - Emulator internet access</a> helped me a lot. :)</p>403263295	0	 <p>This has worked for me </p> <pre><code>$(window).bind("resize", function(e){ // do something }); </code></pre> <p>You are also missing the closing bracket for the resize function;</p>4140045543	0	Rearrange and save images in gallery using jQuery,php,MySQL <p>I've a dynamic gallery created with php and MySQL. Images are loaded from database tables and are shown according to auto increment id. However I need to sort the images by drag and drop system. I've implemented drag n drop with jquery. I need to rearrange them and their order should be stored in database table.</p> <p><strong>I've used the below drag and drop jquery and is working properly.</strong></p> <pre><code>&lt;script type="text/javascript"&gt; $(function() { $("#dragdiv li,#dropdiv li").draggable({ appendTo: "body", helper: "clone", cursor: "move", revert: "invalid" }); initDroppable($("#dropdiv li,#dragdiv li")); function initDroppable($elements) { $elements.droppable({ activeClass: "ui-state-default", hoverClass: "ui-drop-hover", accept: ":not(.ui-sortable-helper)", over: function(event, ui) { var $this = $(this); }, drop: function(event, ui) { var $this = $(this); var li1 = $('&lt;li&gt;' + ui.draggable.html() + '&lt;/li&gt;') var linew1 = $(this).after(li1); var li2 = $('&lt;li&gt;' + $(this).html() + '&lt;/li&gt;') var linew2 = $(ui.draggable).after(li2); $(ui.draggable).remove(); $(this).remove(); var result = {}; var items = []; $('#allItems').each(function () { var type = $(this).attr('data-type'); $(this).find('li').each(function (index, elem) { items.push(this.innerHTML); }); result[type] = items; }); // alert(items); alert($('.lb').attr('id')); initDroppable($("#dropdiv li,#dragdiv li")); $("#dragdiv li,#dropdiv li").draggable({ appendTo: "body", helper: "clone", cursor: "move", revert: "invalid" }); } }); } }); &lt;/script&gt; </code></pre> <p><strong>The php n MySQL code for display images in gallery is given below</strong></p> <pre><code>&lt;div class="box-content" id="maindiv"&gt; &lt;br&gt; &lt;div id="dragdiv"&gt; &lt;?php $sql1=mysql_query("select bnr_img_id,bnr_img_name,img_cap from xhr_bnr_images where bnr_img_par='$id' order by bnr_img_id desc "); $n1=mysql_num_rows($sql1); if($n1&gt;0) { ?&gt; &lt;ul id="allItems" runat="server" class="col-md-12" &gt; &lt;?php while($row1=mysql_fetch_array($sql1)) { ?&gt; &lt;li&gt; &lt;div class="lb" id="&lt;?php echo $row1['bnr_img_id'];?&gt;"&gt; &lt;img src="banner/&lt;?php echo $row1['bnr_img_name'];?&gt;" width="177px" height="150px"&gt; &lt;br/&gt;&lt;br/&gt; &lt;div&gt;&lt;input id="cap&lt;?php echo $row1['bnr_img_id'];?&gt;" value="&lt;?php echo $row1['img_cap'];?&gt;" onblur="update_caption('&lt;?php echo $row1['bnr_img_id'];?&gt;')" style="font-size:12px;font-weight:normal;width:180px;" type="text"&gt;&lt;/div&gt; &lt;a href="javascript:void(0);" onclick="del_this('&lt;?php echo $row1['bnr_img_id'];?&gt;','&lt;?php echo $row1['bnr_img_name'];?&gt;')"&gt;delete&lt;/a&gt; &lt;/div&gt; &lt;/li&gt; &lt;?php } ?&gt; &lt;/ul&gt; &lt;?php } ?&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p><strong>I need to get the replaced image id and their values should be shuffled when dragged</strong>.</p> <p>Captions of the images updated by <strong>onblur</strong> function and its <strong>id</strong> will be send to another php file via <strong>ajax</strong></p>4220977271	0	 <p>You have to enclose the value of pm in quotation marks too:</p> <pre><code>result = Evaluate({@DBlookup("":"";"":"";"admin";"} &amp; pm &amp; {";1)}) </code></pre> <p>This way it is recognized as a string. </p> <p>Example:</p> <p>If pm has a string value "Domino" then Evaluate string has to look like this:</p> <pre><code>@DBlookup("":"";"":"";"admin";"Domino";1) </code></pre> <p>but in your original formula version it would be </p> <pre><code>@DBlookup("":"";"":"";"admin";Domino;1) </code></pre> <p>BTW, the code would break if pm would contain a quotation mark. If you are sure that can't happen then the code is fine.</p>432778629	0	TLS/SRP in browsers? <p>Is there a plan or existing implementation of RFC 5054 in any of the major browsers yet? </p> <p>If nobody has an implementation yet, then which major browsers have it on their roadmap? Where?</p>4422163107	0	 <p>No it is not equivalent</p> <p>If you want to support only jQuery 1.8+ then you can use .addBack() - <a href="http://jsfiddle.net/arunpjohny/Qa87f/3/" rel="nofollow">Demo</a></p> <pre><code>var foo = $some.find(theCriteria).addBack(theCriteria); </code></pre> <p>else you can use .add</p> <pre><code>var foo = $some.find(theCriteria).add($some.filter(theCriteria)); </code></pre> <p>It is not the same because of 2 reasons Demo: <a href="http://jsfiddle.net/arunpjohny/Qa87f/2/" rel="nofollow">Fiddle</a></p> <ul> <li>andSelf() adds back the previous set of elements in your case there are not previous set of elements - this adds the document object to the element set causing undesired results</li> <li>since you are using .find(), you are not filtering the $some object set</li> </ul>456917637	0	PHP Error only present in Internet Explorer <p>Okay this has baffled me. My script works in Mozilla but not IE. I get this error in IE:</p> <pre><code>Warning: move_uploaded_file(uploads/properties/yh96gapdna8amyhhmgcniskcvk9p0u37/) [function.move-uploaded-file]: failed to open stream: Is a directory in /homepages/19/d375499187/htdocs/sitename/include/session.php on line 602 Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/tmp/phpJkiaF3' to 'uploads/properties/yh96gapdna8amyhhmgcniskcvk9p0u37/' in /homepages/19/d375499187/htdocs/sitename/include/session.php on line 602 </code></pre> <p>my code at Session.php is:</p> <pre><code>function addPhoto($subphotoSize,$subphotoType,$subphotoTmpname,$subphotoDesc,$subfieldID,$subsessionid){ global $database, $form; /* Get random string for directory name */ $randNum = $this-&gt;generateRandStr(10); $maxFileSize = 2500000; // bytes (2 MB) $filerootpath = PHOTOS_DIR.$subsessionid."/"; if($subphotoType == "image/png"){ $filename = $randNum.".png"; } else if ($subphotoType == "image/jpeg"){ $filename = $randNum.".jpg"; } $fullURL = $filerootpath.$filename; /* Image error checking */ $field = "photo"; if(!$subphotoTmpname){ $form-&gt;setError($field, "* No file selected"); } else { if($subphotoSize &gt; $maxFileSize) { $form-&gt;setError($field, "* Your photo is above the maximum of ".$maxFileSize."Kb"); } else if (!is_dir($filerootpath)){ mkdir($filerootpath,0777); chmod($filerootpath,0777); } move_uploaded_file($subphotoTmpname, "$fullURL"); } /* Errors exist, have user correct them */ if($form-&gt;num_errors &gt; 0){ return 1; //Errors with form } else { if($subfieldID == "1"){ // If the first field... $is_main_photo = 1; } else { $is_main_photo = 0; } if(!$database-&gt;addNewPhoto($ownerID,$subphotoDesc,$fullURL,$userSession,$is_main_photo, $subsessionid)){ return 2; // Failed to add to database } } return 0; // Success } </code></pre> <p>It creates the folder no problem but doesnt do anything else. </p>464437653	0	 <p>There is no built-in looping for nested structures (given the depth of nesting could be arbitrary). You have several options.</p> <p>Flatten the 2D vector into a single dimensional vector and iterate over that or, Use something like <code>for_each</code>, e.g.</p> <pre><code>template &lt;typename T&gt; struct do_foo { void operator()(T v) { // Use the v } }; template &lt;typename Handler, typename Container&gt; struct handle_nested { void operator()(Container const&amp; internal) { // inner loop, container type has been abstracted away and the handler type for_each(internal.begin(), internal.end(), Handler()); } }; // outer loop for_each(foo.begin(), foo.end(), handle_nested&lt;do_foo&lt;int&gt;, std::vector&lt;int&gt; &gt;()); </code></pre>4728601530	0	 <p>Change your menthod to</p> <pre><code>private void fadingAnimation() { Animation fadeIn = new AlphaAnimation(0, 1); fadeIn.setInterpolator(new DecelerateInterpolator()); //add this fadeIn.setDuration(2000); AnimationSet animation1 = new AnimationSet(false); //change to false final AnimationSet animation2 = new AnimationSet(false); //change to false final AnimationSet animation3 = new AnimationSet(false); //change to false animation1.addAnimation(fadeIn); animation1.setAnimationListener(new Animation.AnimationListener(){ @Override public void onAnimationStart(Animation arg0) { } @Override public void onAnimationRepeat(Animation arg0) { } @Override public void onAnimationEnd(Animation arg0) { text_1.setVisibility(View.VISIBLE); text_2.startAnimation(animation2); } }); animation2.addAnimation(fadeIn); animation2.setAnimationListener(new Animation.AnimationListener(){ @Override public void onAnimationStart(Animation arg0) { } @Override public void onAnimationRepeat(Animation arg0) { } @Override public void onAnimationEnd(Animation arg0) { text_2.setVisibility(View.VISIBLE); text_3.startAnimation(animation3); } }); animation3.addAnimation(fadeIn); animation3.setAnimationListener(new Animation.AnimationListener(){ @Override public void onAnimationStart(Animation arg0) { } @Override public void onAnimationRepeat(Animation arg0) { } @Override public void onAnimationEnd(Animation arg0) { text_3.setVisibility(View.VISIBLE); } }); text_1.startAnimation(animation1); } </code></pre>4835014427	0	 <p>You can use regex for your copy (under "Artifacts to copy")- </p> <p>dev\downloadAgents\target\dependency\ios***.*</p> <p>** - all folders under ios </p> <p>*.* - all file types</p> <p>You can also specify the target directory, and you also have a flag for "Flatten directories". This will move all the files without the hierarchy of the folders (flat to your target directory) </p> <p>Feel free to look at the plugin's home page: <a href="https://wiki.jenkins-ci.org/display/JENKINS/Copy+Artifact+Plugin" rel="nofollow">https://wiki.jenkins-ci.org/display/JENKINS/Copy+Artifact+Plugin</a></p>4933586292	0	 <p>MSIs can be authored per-user or per-machine. Per-user installs won't ask for elevation by default. Per-machine installs will ask for elevation once they hit the InstallExecuteSequence. </p>5032058029	0	Function returning REF CURSOR <p>I have package like this:</p> <pre><code>CREATE OR REPLACE PACKAGE product_package AS TYPE t_ref_cursor to IS REF CURSOR; FUNCTION get_products_ref_cursor RETURN t_ref_cursor; END product_package; CREATE OR REPLACE PACKAGE BODY product_package AS FUNCTION get_products_ref_cursor is RETURN t_ref_cursor IS products_ref_cursor t_ref_cursor; BEGIN OPEN products_ref_cursor FOR SELECT product_id, name, price FROM Products; RETURN products_ref_cursor; END get_products_ref_cursor; END product_package; </code></pre> <p>My question is, how can I use function <em>get_products_ref_cursor</em> (ref cursor) to get list of products?</p>512974184	0	 <p>Each one is a different type execution.</p> <ul> <li><p><strong>ExecuteScalar</strong> is going to be the type of query which will be returning a single value. </p> <p><em>An example would be returning a generated id after inserting.</em></p> <p><code>INSERT INTO my_profile (Address) VALUES ('123 Fake St.'); SELECT CAST(scope_identity() AS int)</code></p></li> <li><p><strong>ExecuteReader</strong> gives you a data reader back which will allow you to read all of the columns of the results a row at a time. </p> <p><em>An example would be pulling profile information for one or more users.</em></p> <p><code>SELECT * FROM my_profile WHERE id = '123456'</code></p></li> <li><p><strong>ExecuteNonQuery</strong> is any SQL which isn't returning values, but is actually performing some form of work like inserting deleting or modifying something. </p> <p><em>An example would be updating a user's profile in the database.</em></p> <p><code>UPDATE my_profile SET Address = '123 Fake St.' WHERE id = '123456'</code></p></li> </ul>523663001	0	 <p>Check out this book, <a href="http://rads.stackoverflow.com/amzn/click/0262640686" rel="nofollow noreferrer" title="The Elements of Computing Systems: Building a Modern Computer from First Principles">The Elements of Computing Systems: Building a Modern Computer from First Principles</a> it takes you step by step through several aspects of designing a computer language, a compiler, a vm, the assembler, and the computer. I think this could help you answer some of your questions.</p>5313186425	0	 <p>This gives the averages Medians are a pain in SQL. <a href="http://stackoverflow.com/questions/1291152/simple-way-to-calculate-median-with-mysql">Simple way to calculate median with MySQL</a> gives some ideas. The two inner queries give the result sets to median over were there a median aggregate.</p> <pre><code>Select times.eventName, avg(times.timelapse) as avg_to_fail, avg(times2.timelapse) as avg_to_start From ( Select starts.id, starts.eventName, TimestampDiff(SECOND, starts.eventTime, Min(ends.eventTime)) as timelapse From Test as starts, Test as ends Where starts.eventName != 'start' And ends.eventName = 'start' And ends.eventTime &gt; starts.eventTime Group By starts.id ) as times2 Right Outer Join ( Select starts.id, ends.eventName, TimestampDiff(SECOND, starts.eventTime, Min(ends.eventTime)) as timelapse From Test as starts, Test as ends Where starts.eventName = 'start' And ends.eventName != 'start' And ends.eventTime &gt; starts.eventTime Group By starts.id ) as times On times2.EventName = times.EventName Group By Times.eventName </code></pre> <p>To aid understanding I'd first consider</p> <pre><code>Select starts.id, ends.eventName, starts.eventTime, ends.eventTime From Test as starts, Test as ends Where starts.eventName = 'start' And ends.eventName != 'start' And ends.eventTime &gt; starts.eventTime </code></pre> <p>This is the essence of the inner query <code>times</code> without the group by and the min statement. You'll see this has a row combining every start event with every end event where the end event is after the start event. Call this X.</p> <p>The next part is</p> <pre><code>Select X.startid, X.endeventname, TimestampDiff(SECOND, X.starttime, Min(x.endTime)) as timelapse From X Group By X.startid </code></pre> <p>The key here is that Min(x.endTime) combines with the group by. So we're getting the earliest end time after the start time (as X already constrained it to be after). Although I've only picked out the columns we need to use, we have access to start time id, end time id start event, end event, start time, min(end time) here. The reason you can adapt it to find the avg_to_start is because we pick the interesting event name, as we have both.</p> <p>SQL Fiddle: <a href="http://sqlfiddle.com/#!2/90465/6" rel="nofollow">http://sqlfiddle.com/#!2/90465/6</a></p>5434774201	0	 <p>What I ended up having to do for this to work properly was do the logic for if the value was passed or not and then add an attribute manually to my button using Attributes.Add(). </p> <pre><code> 'Logic for button enable If (username Is Nothing) Then eastOpen.Attributes.Add("disabled", "disabled") Else </code></pre>5528750380	0	 <p>An alternative to emmanuel's answer is to add some padding to the <code>a</code> tag:</p> <pre><code>ul { list-style-type:none; } li { float:left; } a { background:grey; color:white; text-decoration:none; padding: 10px 20px 10px 20px; margin-right:1px; } </code></pre> <p>See it in action here: <a href="http://jsfiddle.net/rufneu0w/1/" rel="nofollow">http://jsfiddle.net/rufneu0w/1/</a></p>5638595693	0	 <p>I think the following is a much more natural way to describe your domain</p> <pre><code>class Location { String name static hasMany = [preparedToWork: Assessor] } class Assessor { //Some Properties static belongsTo = [Location] static hasMany = [preparedToWork: Location] } </code></pre> <p>Then you can retrieve all of the assessors who are prepared to work in a certain location with</p> <pre><code>Assessor.executeQuery( "from Assessor a join a.preparedToWork l where l.id = ?", [locationId]) </code></pre>5725722817	0	Solr Qtime difference to real time <p>i am trying to find out what causes the difference between the Qtime and the actual response time in my Solr application. The SolrServer is running on the same maschine as the program generating the queries. I am getting Qtimes in average around 19ms but it takes 30ms to actually get my response. This may sound like it is not much, but i am using Solr for some obscure stuff where every millisecond counts.</p> <p>I figured that the time difference is not caused by Disk I/O since using RAMDirectoryFactory did not speed up anything.</p> <p>Using a SolrEmbeddedServer instead of a SolrHttpServer did not cause a speedup aswell (so it is not Jetty what causes the difference?)</p> <p>Is the data transfer between the query-program and the Solr-instance causing the time difference? And even more important, how can i minimize this time?</p> <p>regards</p>5834903358	0	 <p>You don't need to refresh page.</p> <p>Add callback to load. In callback initialize/apply your js library (for controlling datatable).</p> <pre><code> $("#filebody").load("@Url.Action("Attachments", new {collaborationId = Model.Collaboration.Id})"); </code></pre> <p>to</p> <pre><code>$("#filebody").load("@Url.Action("Attachments", new {collaborationId = Model.Collaboration.Id})", function( response, status, xhr ) { //Apply Datatable js library in here }); </code></pre> <p>Because you are removing elements at #filebody and adding new elements. So you should apply your js library to the new elements.</p>5938223729	0	How to suppress talkback programatically? <p>Is there any way to make talkback to suppress when I open my application and resume when I stop my Application?</p>6022215248	0	Get user Geolocation when user uses modem <p>I have an application that detect user's positions, uses geolocation and show it in map (google maps API)</p> <p>The application work properly when user using wifi, it show user's current positions but if the user using modem,the application show isp's (Internet service provider) position not the current user's position...</p> <p>How i can solved this? anysolutions? thanks before..</p>6120346999	0	 <p>FIM doesn't do authentication. Instead, it does the user management and synchronization piece.</p> <p>You would want to integrate with one of the directories FIM is synchronizing. If your app is within the firewall, you would typically use AD or LDAP (Kerberos-based). If your app is outside of the firewall, you would typically use Azure Active Directory or another SAML-based Identity Provider.</p>629713898	0	 <p>I'm sorry but I don't use makegood but I do know that xdebug has a function you can call from the code to trigger a break.</p> <pre><code>xdebug_break(); </code></pre> <blockquote> <p>bool xdebug_break() </p> <p>Emits a breakpoint to the debug client. This function makes the debugger break on the specific line as if a normal file/line breakpoint was set on this line.</p> </blockquote> <p>I hope this will be of some help.</p>63597703	0	 <p>You could also use Commodore 64 emulator. It start's right from BASIC.</p>6439925635	0	 <p>I think it's actually not need because <strong>WidgetsModule</strong> is same as <strong>FormsModule</strong> (@angular/forms). WidgetsModule is user-defined module and FormsModule provided by angular. That's the only difference. Both of this module are used for doing some functionality. </p> <p>So just think about <em>how we can declare <strong>FormsModule</strong> once and use it in all other module</em>, if you understood that then the problem is solved.</p> <p>Just vist the following link <a href="http://stackoverflow.com/questions/39756178/one-single-ngmodule-versus-multiples-ones-with-angular-2/39756821">One single NgModule versus multiples ones with Angular 2</a></p>652767749	0	 <p>If you have control over both domains, you can try a cross-domain scripting library like <a href="http://easyxdm.net/" rel="nofollow noreferrer">EasyXDM</a>, which wrap cross-browser quirks and provide an easy-to-use API for communicating in client script between different domains using the best available mechanism for that browser (e.g. <a href="https://developer.mozilla.org/en/DOM/window.postMessage" rel="nofollow noreferrer">postMessage</a> if available, other mechanisms if not). </p> <p>Caveat: you need to have control over both domains in order to make it work (where "control" means you can place static files on both of them). But you don't need any server-side code changes.</p> <p>In your case, you'd add javascript into one or both of your pages to look at the location.href, and you'd use the library to call from script in one page into script in the other. </p> <p>Another Caveat: there are security implications here-- make sure you trust the other domain's script!</p>6621012601	0	 <p>I am not sure whether I understand your question correctly or not.</p> <p>We can get the iframe document by calling</p> <p><code>iframeEl.contentWindow.document</code></p> <p>Then we can control the html, css inside it.</p> <p>Be careful about the same origin policy:</p> <p>We can only control the iframe the same origin as the main page. </p>671198893	0	Access to global data in a dll from an exported dll function <p>I am creating a C++ Win32 dll with some global data. There is a std::map defined globally and there are exported functions in the dll that write data into the map (after acquiring a write lock, ofcourse).</p> <p>My problem is, when I call the write function from inside the dll DllMain, it works without any problems. But when I load the dll from another program and call the function that writes data into the global map, it gives me this error:</p> <pre><code>WindowsError: exception: access violation reading 0x00000008 </code></pre> <p>Is there something that can be done about this? The same function when called from DllMain has access to the global data in the dll, but when called from a different process, it doesn't have access to the global data. Please advice.</p> <p>I am using the TDM-MinGW gcc 4.4.0 Compiler.</p> <p><strong>EDIT:</strong> Ok, I've figured out what the problem is, and thanks for the help guys, but the problem was not with a constructor issue or inability to have maps in global space, but an issue in the boost::python that I'm using. I had tested it, but since I was calling the dll from within python or maybe something, the urllib2 module wasn't getting loaded into the dll. Now I have to see how to fix it.</p>6839834204	0	Multiple nested AJAX calls in jQuery: How to do it right, without falling back to synchronous? <p>I know, there already are a lot of questions concerning AJAX and Synchronicity here, but I somehow did not find the right answer to my cause. Please be gentle, I am a noob, so, this might be a duplicate. Still, even hinting to that might help me and others finding an appropriate answer.</p> <p><strong>The Function</strong></p> <pre><code>$.fn.facebookEvents = function(options){ var fbEvents = 'https://graph.facebook.com/'+options.id+'/events/?access_token='+options.access_token+'&amp;since=now&amp;limit=500'; var events = []; $.when($.getJSON(fbEvents)).then(function(json){ $.each(json.data, function(){ $.getJSON('https://graph.facebook.com/'+this.id+'/?access_token='+options.access_token, function(jsonData){ events.push(jsonData); console.log(events); // here array "events" is filled successively }); console.log(events); // here array "events" remains empty }); }).done(function(){ $("#fb_data_live").html( $("#fb_events").render(events) ); }); }; </code></pre> <p>What happens in this function, is an AJAX Call (via jQuerys getJSON shorthand) for the event list of a Facebook Page. This will return a list of JSON objects representing each date. Example of one object as response:</p> <pre><code>{ "end_time": "2017-03-16T23:00:00+0100", "location": "Yuca K\u00f6ln", "name": "K\u00f6rner // G\u00e4nsehaut Tour 2017 // K\u00f6ln", "start_time": "2017-03-16T20:00:00+0100", "timezone": "Europe/Berlin", "id": "985939951529300" }, </code></pre> <p>Unfortunately, these are missing the details we need. They are hidden (nested) and can be found, after making a second getJSON (line 8 in the function), using the individual "id" of each object. Now Facebook replies:</p> <pre><code>{ "description": "http://www.eventim.de/koerner\nTickets ab sofort exklusiv auf eventim.de und ab MI 07.09. \u00fcberall wo es Tickets gibt sowie auf contrapromotion.com.", "end_time": "2017-03-16T23:00:00+0100", "is_date_only": false, "location": "Yuca K\u00f6ln", "name": "K\u00f6rner // G\u00e4nsehaut Tour 2017 // K\u00f6ln", "owner": { "name": "K\u00f6rner", "category": "Musician/Band", "id": "366592010215263" }, "privacy": "OPEN", "start_time": "2017-03-16T20:00:00+0100", "timezone": "Europe/Berlin", "updated_time": "2016-09-28T10:31:47+0000", "venue": { "name": "Yuca K\u00f6ln" }, "id": "985939951529300" } </code></pre> <p>Et voila, the details I was looking for. After making this second (nested) AJAX call, I push the JSON data in the array "events" (line 12). </p> <p><strong>The Problem</strong></p> <p>This should fill up the array with every .each iteration. However, take a look at the two 'console.logs'. The first one returns the filled array, the second one returns an empty array... If the AJAX calls are being made synchronously (which is not how it is supposed to be), e.g. by adding <code>$.ajaxSetup({async: false});</code> prior to the function, it works fine however. The array is filled and can be rendered (line 18).</p> <p><strong>The Question</strong> </p> <p>How can this behaviour be explained and how can this function be done right? I know, there must be a way using deferred and promises? I thought i did, by using .when.then.done... obviously I erred.</p> <p>With best regards, Julius</p>6934653126	0	 <p>If <code>SaveChanges</code> fails, then you will need to rollback your entity's values back to what they originally were.</p> <p>In your <code>DbContext</code> class, you can add a method called <code>Rollback</code>, it'll look something like this:</p> <pre><code>public class MyDbContext : DbContext { //DataSets and what not. //... public void Rollback() { //Get all entities var entries = this.ChangeTracker.Entries().ToList(); var changed = entries.Where(x =&gt; x.State != EntityState.Unchanged).ToList(); var modified = changed.Where(x =&gt; x.State == EntityState.Modified).ToList(); var added = changed.Where(x =&gt; x.State == EntityState.Added).ToList(); var deleted = changed.Where(x =&gt; x.State == EntityState.Deleted).ToList(); //Reset values for modified entries foreach (var entry in modified) { entry.CurrentValues.SetValues(entry.OriginalValues); entry.State = EntityState.Unchanged; } //Remove any added entries foreach (var entry in added) entry.State = EntityState.Detached; //Undo any deleted entries foreach (var entry in deleted) entry.State = EntityState.Unchanged; } } </code></pre> <p>You can simply call this method in your <code>catch</code>:</p> <pre><code>try { dataEntities.SaveChanges(); } catch (Exception oops) { //Rollback all changes dataEntities.Rollback(); } </code></pre> <p>Note that <code>INotifyPropertyChanged</code> will need to be implemented on properties that are bound to the view, this will ensure that any changes that the rollback performs will be pushed back to the view.</p>709478913	0	Determine display mode of sharepoint page <p>I have this question many times and bored while trying to find good solution. Dont understand why microsoft not include method which can easy determine mode of display page: "normal display" or in "design mode". It have many advices of check different variables, but it cant uniquely say that page in design on different type of page(webpart page and wiki page) and on postback or not.</p> <p>Is finally tired me and i write this:</p> <pre><code> public static bool IsDesignTime() { if (SPContext.Current.IsDesignTime) return true; if (HttpContext.Current.Request.QueryString["DisplayMode"] != null) return true; var page = HttpContext.Current.Handler as Page; if(page == null) return false; var inDesign = page.Request.Form["MSOLayout_InDesignMode"]; var dispMode = page.Request.Form["MSOSPWebPartManager_DisplayModeName"]; var wikiMode = page.Request.Form["_wikiPageMode"]; var we = page.Request.Form["ctl00$PlaceHolderMain$btnWikiEdit"]; if (inDesign == null &amp; dispMode == null) return false; //normal display if (we == "edit") return true; //design on wiki pages if (page is WikiEditPage &amp; page.IsPostBack &amp; inDesign == "" &amp; dispMode == "Browse" &amp; wikiMode == "") return false; //display wiki on postback if (inDesign == "" &amp; dispMode == "Browse" &amp; (wikiMode == null | wikiMode == "")) return false; //postback in webpart pages in display mode if (inDesign == "0" &amp; dispMode == "Browse") return false; //exiting design on webpart pages return true; } </code></pre> <p>Does anybody have better solution?</p>7121751558	0	 <p>i think it should be better to have a user skill mapping table with fields user_id &amp; skill_id. Every time when a user adds a skill, enter it with in mapping table so it will be easier to use this data in future</p>7229739501	0	Runtime error: Could not load file or assembly 'Microsoft.Owin, Version=3.0.0.0....Azure mobile services <p>I have downloaded the ToDOService project from the Azure managementprotal after I created a Mobile service. Initially it had a lot of errors as the Nuget packages were outdated. I Uninstalled the <code>Azure mobile services .net backend</code> package and its dependencies. Later I again installed all the packages manually and then I could build the project successfully. Somehow, when I run the service project I get this error:-</p> <pre><code>Could not load file or assembly 'Microsoft.Owin, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.Owin, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified. Source Error: Line 18: Line 19: // Use this class to set WebAPI configuration options Line 20: HttpConfiguration config = ServiceConfig.Initialize(new ConfigBuilder(options)); Line 21: Line 22: // To display errors in the browser during development, uncomment the following Source File: ...\MyProject\MyService\App_Start\WebApiConfig.cs Line: 20 </code></pre> <p>My web.config looks like this</p> <pre><code>&lt;dependentAssembly&gt; &lt;assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" culture="neutral" /&gt; &lt;bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" /&gt; &lt;/dependentAssembly&gt; </code></pre> <p>I also tried to update the assembly to the latest, but could not be updated as Ver 3.0.1 is not compatible with its other dependencies.</p> <p>any help would be appreciated. Thanks</p>731850127	0	 <ol> <li><p>How large of a deployment is this? It might be better to execute the deployment of .net 3.5 as a previous enterprise deployment. And then follow up with your application. For enterprise wide deployments there are tools like Zenworks, and others that deploy applications and other file sets "invisibly" to the user.</p></li> <li><p>Have you confirmed that your application will not function with .net 2.0? </p></li> <li><p>If your application is only files, and does not have registry settings, etc. you may be able to copy the files to the users' computers, and copy a shortcut to their desktop, or startmenu certainly without their intervention, and probably with out their knowledge. If you have admin level credentials that apply to all your PCs and can get a list of all you r PCs' network names, you could "push" the files out through the C$ share, or if they log in to a domain you can have them "pull" them via a login-script.</p></li> </ol> <p>There are actually lots of ways to do this. If you have server admins, they can help you with this.</p>748437176	0	App load screen in Android <p>On iOS you create a load screen for when the app loads, is there a similar thing in Android. When my app loads, I get a black screen until it opens.</p>7526907654	0	 <p>From the <a href="https://skvare.com/blog/non-existent-urls-views-2" rel="nofollow">source</a>:</p> <p>The solution is to edit the view by adding an Argument of Node: Nid. Set it to Display all values, Validator: Node, and Argument type of Node ID. </p> <p>Set Action to take if argument does not validate: Hide view / Page not found (404). Update the Argument and save the view.</p>7616374996	0	mysqldump.exe not taking full backup of mysql database <p>I have a procedure for backing up MySQL database.And also i have different MySQL servers. This procedure works on some of MySQL servers.But on some of servers it won't works proper and create a backup file with the size of 1kb.</p> <h2>Code</h2> <pre><code>public void DatabaseBackup(string ExeLocation, string DBName) { try { string tmestr = ""; tmestr = DBName + "-" + DateTime.Now.ToString("hh.mm.ss.ffffff") + ".sql"; tmestr = tmestr.Replace("/", "-"); tmestr = "c:/" + tmestr; StreamWriter file = new StreamWriter(tmestr); ProcessStartInfo proc = new ProcessStartInfo(); string cmd = string.Format(@"-u{0} -p{1} -h{2} {3}", "uid", "pass", "host", DBName); proc.FileName = ExeLocation; proc.RedirectStandardInput = false; proc.RedirectStandardOutput = true; proc.Arguments = cmd; proc.UseShellExecute = false; proc.CreateNoWindow = true; Process p = Process.Start(proc); string res; res = p.StandardOutput.ReadToEnd(); file.WriteLine(res); p.WaitForExit(); file.Close(); } catch (IOException ex) { } } </code></pre> <p>Can any one tell me what is the problem and how can i solve it.</p>7738627339	0	Is it possible to nest SQL tables? <p>I am wondering if it is possible to nest SQL tables? Or it the best practise to give the id to for example a person in the first table that is the key to the second table?</p>7833402810	0	How can I replace "true" and "false" in java? <p>i need change the values for boolean variables, for example:</p> <p>change this: boolean x = true; System.out.print(x); //console: true for this:</p> <pre><code>boolean x = true; System.out.print(x); //console: 1 </code></pre> <p>Sorry for my bad engish, thanks.</p> <p>This is my code </p> <pre><code>final boolean[] BOOLEAN_VALUES = new boolean [] {true,false}; for (boolean a : BOOLEAN_VALUES) { boolean x = negation(a); String chain = a+"\t"+x; chain.replaceAll("true", "1").replaceAll("false","0"); System.out.println(chain); } negation is a method: public static boolean negation(boolean a){ return !a; } </code></pre> <p>as you can see, i try using .replaceAll, but its not working, when i executed, this is the output:</p> <pre><code> a ¬a ---------------- true false false true </code></pre> <p>i really dont see my error.</p>7920802405	0	 <p>No need to call <code>awk</code> several times. You can do everything with a single <code>awk</code> script. Try the following command:</p> <pre><code>awk -f t.awk GW2.log </code></pre> <p>where <code>t.awk</code> is:</p> <pre><code>NR==5 { RDS_T=$1 } NR==6 { RDS_P=$1" "$2 } NR==8 { RDS_C1=$1" "$2 } NR==9 { RDS_C2=$1" "$2 } NR==16 { ALGN_T=$1 } END { fmt="%-12s %-12s %-18s %-18s %-18s %-18s\n" printf fmt, "File", "Reads", "Paired reads", "Conc reads1", "Conc Reads2", "Total align" printf fmt, "GW2.log", RDS_T, RDS_P, RDS_C1, RDS_C2, ALGN_T } </code></pre> <p>with output:</p> <pre><code>File Reads Paired reads Conc reads1 Conc Reads2 Total align GW2.log 3746112 3746112 (100.00%) 581094 (15.51%) 227387 (6.07%) 28.15% </code></pre>8021458798	0	 <p>I have an idea. If you can get the element in evaluate you can fireEvent on it. So create a function that will fireEvent.</p> <pre><code> function casperFireEvent(element, eventType) { if ("createEvent" in document) { var evt = document.createEvent("HTMLEvents"); evt.initEvent(eventType, false, true); element.dispatchEvent(evt); } else { element.fireEvent("on"+eventType); } } </code></pre> <p>Then on you loop you can do this :</p> <pre><code> this.evaluate(casperFireEvent(document.getElementById('links[i]'), 'click')); </code></pre> <p>I'm not sure it it's conventional but that's a start.</p>816919874	0	 <p>Flymake sets a 1-second timer for each buffer that has flymake-mode enabled, to check to see if the buffer has been modified more than <code>flymake-no-changes-timeout</code> seconds ago.</p> <p>If you have a lot of buffers open (several hundred) in flymake-mode then this can devour a surprisingly large amount of CPU, I've a patched version of flymake that has a single global timer which fixes this, and a few other issues: <a href="https://github.com/illusori/emacs-flymake">https://github.com/illusori/emacs-flymake</a></p> <p>This might not be the same issue for you, but for me it would lock Emacs up when opening in desktop-mode with 600 files open, I'd be lucky to get one keypress processed every 15 minutes.</p>8220602682	0	Background image looks brighter on Safari <p>Background image on Safari looks brighter compare to any other browsers.</p> <p>When I remove <code>background-size: cover</code>, image colors looks like expected.</p> <p>How do I keep normal colors and <code>background-size: cover</code> at the same time?</p> <pre><code>body { background-image: url('https://lh5.googleusercontent.com/-QpCNI9iXEEE/Uq5gxSpxOJI/AAAAAAAAABM/HwVK1nETGPE/I/philadelphia_night_view.jpg'); background-repeat: no-repeat; background-size: cover; } </code></pre> <p><a href="http://jsfiddle.net/xY9wK/" rel="nofollow noreferrer">http://jsfiddle.net/xY9wK/</a></p> <p>OS X Mountain Lion 10.8.3, Safari: 6.0.3</p> <p><img src="https://i.stack.imgur.com/oXYY4.png" alt="enter image description here"></p>8311958008	0	 <p>Do you mean words or characters? If you want to count <strong>words</strong>, a very naïve approach is splitting by whitespace and check the length of the resulting array:</p> <pre><code>if ($("#et_newpost_content").text().split(/\s+/).length &lt; 250) { alert('Message must be at least 250 words.') } </code></pre> <p>If you mean <strong>characters</strong>, then it's much easier:</p> <pre><code>if ($("#et_newpost_content").text().length &lt; 250) { alert('Message must be at least 250 characters.') } </code></pre>8414295380	0	 <p>SmartGWT has extensive built-in support for Selenium. Read about it here:</p> <p><a href="http://www.smartclient.com/smartgwtee-latest/javadoc/com/smartgwt/client/docs/UsingSelenium.html" rel="nofollow">http://www.smartclient.com/smartgwtee-latest/javadoc/com/smartgwt/client/docs/UsingSelenium.html</a></p> <p>Do not attempt to set your own DOM identifiers. This is unnecessary, and is the wrong approach.</p>8535769329	0	Replace month number with month name using current phone format <p>I'm using joda-time to process DateTime. I got date format of phone using this:</p> <pre><code>SimpleDateFormat dateFormat = (SimpleDateFormat) DateFormat.getDateFormat(context); String datePattern = dateFormat.toPattern(); </code></pre> <p>And then I format a DateTime to String using this:</p> <pre><code>DateTimeFormatter dateFormatter = DateTimeFormat.forPattern(datePattern); dateFormatter.print(dateTime) </code></pre> <p>Example, it will show DateTime as String: </p> <blockquote> <p>3/1/2016</p> </blockquote> <p>But i want it displays: </p> <blockquote> <p>March/1/2016</p> </blockquote> <p>or </p> <blockquote> <p>Mar/1/2016</p> </blockquote> <p>How can i do that?</p>8615155844	0	 <p>Sounds like your data might be better suited to being in one index, in which case you could use and/or filters to combine a geo distance filter with a type filter.</p> <p>Another option would be to use the <a href="http://www.elasticsearch.org/guide/reference/query-dsl/indices-query.html" rel="nofollow">indicies</a> query</p>8727709401	0	 <p>It turns out that <a href="http://msdn.microsoft.com/en-us/library/windows/hardware/hh967734(v=vs.85).aspx" rel="nofollow">Microsoft does not support SHA-2 for driver signing on Windows 7</a>.</p> <blockquote> <p>In some cases, you might want to sign a driver package with two different signatures. For example, suppose you want your driver to run on Windows 7 and Windows 8. Windows 8 supports signatures created with the SHA256 hashing algorithm, but Windows 7 does not. For Windows 7, you need a signature created with the SHA1 hashing algorithm.</p> <p>Suppose you want to build and sign a driver package that will run on Windows 7 and Windows 8 on x64 hardware platforms. You can sign your driver package with a primary signature that uses SHA1. Then you can append a secondary signature that uses SHA256. You can use the same certificate for both signatures, or you can use separate certificates. Here are the steps to create the two signatures using Visual Studio.</p> </blockquote>8810278431	0	 <p>As you mentioned, <a href="http://code.google.com/p/mobileterminal/" rel="nofollow">MobileTerminal</a> is probably what you're looking for. This project is open-source and you can start of it. AFAIK now it runs only on jailbroken devices, but you can definitely cut out only the terminal emulation (&amp; screen manipulation, handling input and output, ...) and build your project on it.</p> <p>Building a terminal from scratch is quite complicated and complex, so I suggest you start with this or some other open source project.</p> <p>I am not aware of any ready-to-use component, so you'll probably have to put some work into integrating the terminal into your app.</p>8933427601	0	 <blockquote> <p>When the mouse is dragging a div element over a droppable area, pressing the ESC key should drag the element to an area that is not droppable</p> </blockquote> <p>I´ve created a <a href="http://run.plnkr.co/plunks/JSTWFTFoiz6yLWAQl2vH/"><code>demo</code></a> of a possible solution that you can check in plunker.</p> <p>As stated by <a href="http://stackoverflow.com/users/1272576/ioneyed"><code>@ioneyed</code></a>, you can select the dragged element directly using the selector <code>.ui-draggable-dragging</code>, which should be more efficient if you have lots of draggable elements.</p> <p>The code used is the following, however, apparently it's not working in the snippet section. Use the <code>fullscreen</code> feature on the plunker or reproduce it locally.</p> <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 CANCELLED_CLASS = 'cancelled'; $(function() { $(".draggable").draggable({ revert: function() { // if element has the flag, remove the flag and revert the drop if (this.hasClass(CANCELLED_CLASS)) { this.removeClass(CANCELLED_CLASS); return true; } return false; } }); $("#droppable").droppable(); }); function cancelDrag(e) { if (e.keyCode != 27) return; // ESC = 27 $('.draggable') // get all draggable elements .filter('.ui-draggable-dragging') // filter to remove the ones not being dragged .addClass(CANCELLED_CLASS) // flag the element for a revert .trigger('mouseup'); // trigger the mouseup to emulate the drop &amp; force the revert } $(document).on('keyup', cancelDrag);</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code> .draggable { padding: 10px; margin: 10px; display: inline-block; } #droppable { padding: 25px; margin: 10px; display: inline-block; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="droppable" class="ui-widget-header"&gt; &lt;p&gt;droppable&lt;/p&gt; &lt;/div&gt; &lt;div class="ui-widget-content draggable"&gt; &lt;p&gt;draggable&lt;/p&gt; &lt;/div&gt; &lt;div class="ui-widget-content draggable"&gt; &lt;p&gt;draggable&lt;/p&gt; &lt;/div&gt; &lt;div class="ui-widget-content draggable"&gt; &lt;p&gt;draggable&lt;/p&gt; &lt;/div&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"&gt;&lt;/script&gt; &lt;link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.css"&gt;</code></pre> </div> </div> </p>9015561669	0	Placing multiple Divs (side by side) within a parent Div <p>My goal is to place four divs within a single "container" div. Here's my code so far:</p> <p><strong>HTML</strong></p> <pre><code>&lt;body&gt; &lt;div id="navBar"&gt; &lt;div id="subDiv1"&gt; &lt;/div&gt; &lt;div id="subDiv2"&gt; &lt;/div&gt; &lt;div id="subDiv3"&gt; &lt;/div&gt; &lt;div id="subDiv4"&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; </code></pre> <p><strong>CSS</strong></p> <pre><code>#navBar { width: 75%; height: 75px; margin-left: 25%; margin-right: auto; margin-top: 2%; border-width: 1px; border-style: solid; border-radius: 10px; border-color: #008040; overflow: hidden; } #subDiv1, #subDiv2, #subDiv3, #subDiv4 { width: 25%; height: 75px; border-width: 1px; border-color: #000; border-style: solid; } #subDiv1 { border-top-left-radius: 10px; border-bottom-left-radius: 10px; float: left; margin-left: 0%; } #subDiv2 { float: left; margin-left: 25%; } #subDiv3 { float: left; margin-left: 50%; } #subDiv4 { border-top-right-radius: 10px; border-bottom-right-radius: 10px; float: left; margin-left: 75%; } </code></pre> <p>As far as I know this is the only part of my code that's relevant to my question so I left some other parts out.. Don't mind the width and margin of the navBar, because it's actually within another container as well.</p> <p>P.S I searched Google and StackOverFlow and I could not find an answer that was helpful. There were many questions about placing two divs within a single div, but none for aligning multiple divs within a single div.</p> <p>Thanks for any help in advance!</p>9110566598	0	 <p>No. You can't use VideoView with authenticated RTSP, even with rtsp://User:Password@Server. It won't work. It is possible to use authenticated RTSP on android but it's hard and you will have to do a lot of things by yourself.</p>9216222364	0	 <p>Use <code>Arrays.toString(method.getParameterTypeas())</code> if you want to <em>see</em> the types. Use loop if you want to iterate over them and use them:</p> <pre><code>for (Class&lt;?&gt; type : method.getParameterTypeas()) { // use the type } </code></pre>9325887050	0	 <p>I suppose, you want to <code>INNER JOIN</code> those tables like this:</p> <pre><code> SELECT * FROM ( SELECT pi.FighterId, FName, LName, PaymentDay, PaymentDescr, PaymentAmount, Active, ROW_NUMBER() OVER (PARTITION BY fi.FighterId ORDER BY PaymentDay DESC) rn FROM FightersInfo fi LEFT JOIN PaymentInfo pi ON pi.FighterId = fi.FighterId WHERE NOT EXISTS (SELECT * FROM PaymentInfo WHERE FighterId = fi.FighterId AND DATEDIFF(month, PaymentDay, GETDATE()) = 0 ) AND Active =1) t WHERE rn = 1 </code></pre> <p>All the conditions on amount are removed for readability.</p>9440277883	0	Positioning and then making it responsive <p>Hey I'm currently working on a responsive web design for school and it is a disaster. Currently setting up the website before making it responsive and the text and images aren't going where I need them to go. This is my coding for css so far: </p> <pre><code>body{ background-color: #cd76dd; font-family: 'Raspoutine Medium'; color:white; } #page-wrap{ width: 950px; margin: 0 auto; } #containerIntro h1{ font-family: 'AlphaClouds'; background-color: #7ac8ff; color:white; font-size: 45px; width: 100%; padding-bottom: 10px; position: static; bottom: 0; left: 0; } #containerIntro p{ font-family: 'AlphaClouds'; background-color: #7ac8ff; color:white; text-align: left; font-size: 70px; width: 100%; } h1: hover{ text-shadow: 0px 0px 20px white; } h1 p: hover{ text-shadow: 0px 0px 20px white; } h1{ position: absolute; left: 0; bottom: 0; } p{ background-color:#ffa1ff; color:white; text-align: left; padding-top: 20px; padding-bottom: 20px; padding-left: 10px; font-size: 17px; width: 450px; height: 100%; } h2{ background-color: #ffa1ff; color:white; text-align: left; padding-top: 20px; padding-left: 10px; font-size: 20px; border: 2px #ffa1ff solid; width: 450px; height: 100%; } h3{ background-color: #ffa1ff; color:white; text-align: left; font-size: 20px; padding-left: 10px; border: 2px #ffa1ff solid; width: 450px; height: 100%; } .gummy{ float: right; } .bubble{ float: right; position: relative; right: -130px; padding-top: 15px; } .pink{ float: left; position: relative; top: -145px; } .blue{ float: right; position: relative; top: -145px; } p.select{ background-color: #5d75ed; text-align: right; padding-bottom:10px; padding-top: 10px; font-size: 17px; width: 170px; float: right; margin-top: -850px; } p.archives{ background-color: #f9e075; text-align: right; padding-bottom: 10px; padding-top: 10px; padding-left: 10px; font-size: 17px; width: 170px; float: right; margin-top: -600px; } p.resources{ background-color: #ef5b66; padding-bottom: 10px; padding-top: 10px; font-size: 17px; width: 170px; float:right; margin-top: -500px; } div{ height: 287; width: 198; } </code></pre> <p>mock up for what it will look like</p> <p><a href="https://i.stack.imgur.com/YJLUV.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/YJLUV.jpg" alt="enter image description here"></a></p>9539242333	0	Tensorflow : Implementing gradient for user op in C++? <p>I'd ideally like the operation to be wholly self-contained (gradient and operation defined in same file). The official tutorial only highlights a python implementation. Does anyone know if it's possible to implement the gradient in C++, and how to go about it?</p>967777487	0	 <p>If the file is not opened, the line <code>file = open(filePath, 'w')</code> fails, so nothing gets assigned to <code>file</code>.</p> <p>Then, the <code>except</code> clause runs, but nothing is in file, so <code>file.close()</code> fails.</p> <p>The <code>finally</code> clause always runs, even if there was an exception. And since <code>file</code> is still None you get another exception.</p> <p>You want an <code>else</code> clause instead of <code>finally</code> for things that only happen if there was no exception.</p> <pre><code> try: file = open(filePath, 'w') except IOError: msg = "Unable to create file on disk." return else: file.write("Hello World!") file.close() </code></pre> <hr> <p>Why the <code>else</code>? The <a href="http://docs.python.org/tutorial/errors.html">Python docs</a> say: </p> <blockquote> <p>The use of the else clause is better than adding additional code to the try clause because it avoids accidentally catching an exception that wasn’t raised by the code being protected by the try ... except statement.</p> </blockquote> <p>In other words, this won't catch an <code>IOError</code> from the <code>write</code> or <code>close</code> calls. Which is good, because then reason woudn't have been “Unable to create file on disk.” – it would have been a different error, one that your code wasn't prepared for. It's a good idea not to try to handle such errors.</p>9717126231	0	icefaces project deployment error : org.apache.catalina.LifecycleException: java.lang.NoSuchFieldError: SKIP_ITERATION <p>I'm trying to make new icefaces project which generated using: ICEfaces 3.3.0 project integration for Eclipse. I didn't modify anything on the project. but when i try to run on the server, i got an error:</p> <blockquote> <p>cannot Deploy MyProject</p> <p>Deployment Error for module: MyProject: </p> <p>Exception while loading the app : java.lang.Exception:</p> <p>java.lang.IllegalStateException: ContainerBase.addChild: </p> <p>start: org.apache.catalina.LifecycleException: </p> <p>java.lang.NoSuchFieldError: SKIP_ITERATION</p> </blockquote> <p>before that, I'm using ICEfaces 3.2.0 project integration for Eclipse and no problem.</p> <p>I'm using Eclipse Indigo, GlassFish server 3, Mojarra 2.1.6</p> <p>Thanks before</p>9821263350	0	 <p>On Heroku, gems are installed within the <code>vendor/bundle/ruby/&lt;version&gt;/gems</code> directory. I just checked my Heroku instance and confirmed this.</p>999667115	0	 <p>CML files get rendered as XML from the server because the server is telling Chrome it is XML with header <code>Content-Type:application/xml</code>. When a local file is opened there is no <code>Content-Type</code> header so Chrome guesses off of the file extension and in this case is not aware of CML. You could open a feature request for Chrome to read CML files as XML but I don't know if they will implement it: <a href="http://new.crbug.com" rel="nofollow">http://new.crbug.com</a></p>100447930	0	 <p>I assume you want to implement some sort of a loading screen or interface widget. (Did you know you can set the showBusyCursor on a remote object instance?)</p> <p>There is no way to globally intercept the method calls on your remote objects though. You'll need to solve this by either:</p> <ol> <li>create a subclass of RemoteObject that sets some global flag on the result and fault events.</li> <li>write the same result and fault event handling code on each remote object call that sets a global flag.</li> </ol> <p>Option 1 is a bit more advanced but will save you the boilerplate code that option 2 has.</p>101145227	0	 <p>In my opinion, almost any release number scheme can be made to work more or less sanely. The system I work on uses version numbers such as 11.50.UC3, where the U indicates 32-bit Unix, and the C3 is a minor revision (fix pack) number; other letters are used for other platform types. (I'd not recommend this scheme, but it works.)</p> <p>There are a few golden rules which have not so far been stated, but which are implicit in what people have discussed.</p> <ul> <li>Do not release the same version twice - once version 1.0.0 is released to anyone, it can never be re-released.</li> <li>Release numbers should increase monotonically. That is, the code in version 1.0.1 or 1.1.0 or 2.0.0 should always be later than version 1.0.0, 1.0.9, or 1.4.3 (respectively).</li> </ul> <p>Now, in practice, people do have to release fixes for older versions while newer versions are available -- see GCC, for example:</p> <ul> <li>GCC 3.4.6 was released after 4.0.0, 4.1.0 (and AFAICR 4.2.0), but it continues the functionality of GCC 3.4.x rather than adding the extra features added to GCC 4.x.</li> </ul> <p>So, you have to build your version numbering scheme carefully.</p> <p>One other point which I firmly believe in:</p> <ul> <li>The release version number is unrelated to the CM (VCS) system version numbering, except for trivial programs. Any serious piece of software with more than one main source file will have a version number unrelated to the version of any single file.</li> </ul> <p>With SVN, you could use the SVN version number - but probably wouldn't as it changes too unpredictably.</p> <p>For the stuff I work with, the version number is a purely political decision.</p> <p>Incidentally, I know of software that went through releases from version 1.00 through 9.53, but that then changed to 2.80. That was a gross mistake - dictated by marketing. Granted, version 4.x of the software is/was obsolete, so it didn't immediately make for confusion, but version 5.x of the software is still in use and sold, and the revisions have already reached 3.50. I'm very worried about what my code that has to work with both the 5.x (old style) and 5.x (new style) is going to do when the inevitable conflict occurs. I guess I have to hope that they will dilly-dally on changing to 5.x until the old 5.x really is dead -- but I'm not optimistic. I also use an artificial version number, such as 9.60, to represent the 3.50 code, so that I can do sane <code>if VERSION &gt; 900</code> testing, rather than having to do: <code>if (VERSION &gt;= 900 || (VERSION &gt;= 280 &amp;&amp; VERSION &lt; 400)</code>, where I represent version 9.00 by 900. And then there's the significant change introduced in version 3.00.xC3 -- my scheme fails to detect changes at the minor release level...grumble...grumble...</p> <p><em>NB</em>: Eric Raymond provides <a href="http://en.tldp.org/HOWTO/Software-Release-Practice-HOWTO/naming.html" rel="nofollow noreferrer">Software Release Practice HOWTO</a> including the (linked) section on naming (numbering) releases.</p>1026556981	0	 <p>The <code>using</code> statement is really the preferred solution. It's idiomatic in C#. These classes implement <code>IDisposable</code> explicitly because they already provide a method that has closing semantics: <code>Close</code>. My bet is that <code>Dispose</code> calls <code>Close</code>, or vice-versa. <em>But you shouldn't count on that, and should always call <code>Dispose</code> anyway.</em></p> <p>In the end, all these are equivalent:</p> <ol> <li>Use <code>using</code>, which is preferred;</li> <li><s>Call <code>Close</code> on the <code>finally</code> block, and suppress the static analysis warnings or;</s></li> <li>Call <code>Dispose</code> on the <code>finally</code>: <code>((IDisposable)NewReader).Dispose();</code></li> </ol>1037498755	0	 <p>Try cleaning the project. Also, are you using the google libraries for <a href="http://developer.android.com/guide/tutorials/views/hello-mapview.html" rel="nofollow">maps</a>? You need to add a link to Google API.</p>10430202774	1	Python - remove parts of a string <p>I have many fill-in-the-blank sentences in strings, </p> <p>e.g. <code>"6d) We took no [pains] to hide it ."</code></p> <p>How can I efficiently parse this string (in Python) to be </p> <pre><code>"We took no to hide it"? </code></pre> <p>I also would like to be able to store the word in brackets (e.g. "pains") in a list for use later. I think the regex module could be better than Python string operations like split().</p>10525676448	0	 <p>You want to look at websockets. A good way to do this in PHP is with a library called "Ratchet":</p> <p><a href="http://socketo.me/" rel="nofollow">http://socketo.me/</a></p> <p>Unfortunately websockets don't have very good cross-browser compatibility.</p>106561122	0	 <p>You definitely need some kind of 'in code' element, because a lack of DLL will break things in a worse way than simply disabling the modules you had intended.</p>1079116346	0	 <pre><code>struct C { A a; B b; C(double ta[2], vector&lt;double&gt; tb) { a = A(ta[0],ta[1]); // or a.x = ta[0]; a.y = ta[1] b = tb; } }; </code></pre> <p>then you can initialize with something like</p> <pre><code>C c = C( {0.0, 0.1} , vector&lt;double&gt; bb(0.0,5) ); </code></pre>10824428571	0	Asterisk: How can I filter the Dial event only to my extension <p>I am making a Asterisk Client in C# WinForms using Asterisk.NET. My client is listening to one extension only.We can view the calls, reject or transfer etc to the calls coming to my extensions. I need source channel to transfer the call, and source channel can be got only from Dial Event. Recently, I noticed that The Dial Event happens everytime when any of the extension connected to the server starts dialling. I want to filter it out, only the call coming to my extension only. </p> <pre><code> void manager_Dial(object sender, DialEvent e) { CallingInfo.src_channel = e.Channel; } </code></pre> <p>e.dialString is giving me the Destination Extension number; But I don't know if it become null according to the server status. Moreover, what will happen if some external calls coming to me, I wont get Dial event or Source channel, Then it cannot be transferred. Right ? </p>10916604386	0	what is the function of attribute selected in combo box while fetching data from MYSQL in php <p>Hello i am beginner in PHP. I am trying to fetch data from MYSQL and want to show in combo box but if user does not re selects the item from item list it highlights error that nothing is selected. Is there any php function to do this particular task ? I want that when the data of particular id is loaded in form and if without making any change in combo boxes data user cliks on submit then it must submit but in my case it shows that the fields are empty while data is here. Here is my Code</p> <pre><code>&lt;li id="foli3" class="notranslate "&gt; &lt;label class="desc" id="title3" for="Field3"&gt; what is the current occupation of your guardian? &lt;span id="req_3" class="req"&gt;*&lt;/span&gt; &lt;/label&gt; &lt;span&gt; &lt;select id="Field3" name="occupation" class="field select addr" tabindex="8" required &gt; &lt;option value="" selected="selected"&gt;&lt;?php echo $rows['occupation']; ?&gt;&lt;/option&gt; &lt;option&gt;Private Sector Employee&lt;/option&gt; &lt;option&gt;Social Sector Employee&lt;/option&gt; &lt;option&gt;Agriculturalist&lt;/option&gt; &lt;option&gt;Businessman&lt;/option&gt; &lt;option&gt;Government Employee&lt;/option&gt; &lt;option&gt;Other&lt;/option&gt; &lt;/select&gt; &lt;/span&gt; &lt;/li&gt; </code></pre>11010089327	0	 <p>One method may be to select the appropiate column range using the Visual mode (control+v)</p> <p>Once selected, the search and replace can be done using (<a href="http://stackoverflow.com/questions/773137/find-and-replace-within-selection-in-vi">see this question</a>)</p> <pre><code> %s/\%Vfoo/bar/g </code></pre> <p>A regular expression for not test can be found here: <a href="http://stackoverflow.com/questions/406230/regular-expression-to-match-string-not-containing-a-word">Regular expression to match string not containing a word?</a></p>11139429095	0	materialized view for for a duration with fast refresh such as last ten minutes <p>12015 while creating MV in my 3rd step:</p> <ol> <li><p>create table tab_2 as select * from tab_1; alter table tab_2 add constraint tab_2_pk primary key (col6,col7);</p></li> <li><p>create materialized view log on my_schema.tab_2 with primary key (my_date) including new values;</p></li> <li><p>create materialized view my_schema.ten_minute_data refresh fast as select * from my_schema.tab_2 mt where mt.my_date > sysdate-10/(24*60);</p></li> </ol> <p>I am trying to create mv and mv_log in the same db as replacement of normal view to query and see the the result fast.</p> <p>Please suggest if it such where clause is possible.</p> <p>Thanks</p>1128598171	0	Workaround for DELETE ... LIMIT clause (SQL) <p>I am working on a database query abstraction layer that supports SQLite.</p> <p>Unfortunately, SQLite does not support the <code>LIMIT</code> clause in DELETE (and UPDATE etc.) queries - except if compiled with a special flag in more recent versions.</p> <p>So is there any workaround that I could implement so that that query type can still be supported?</p>1133395055	0	 <p>To store the history of a page, the most popular and full featured/supported way is using hashchanges. This means that say you go from <code>yoursite/page.html#page1</code> to <code>yoursite/page.html#page2</code> you can track that change, and because we are using hashes it can be picked up by bookmarks and back and forward buttons.</p> <p>You can find a great way to bind to hash changes using the jQuery History project <a href="http://www.balupton.com/projects/jquery-history" rel="nofollow noreferrer">http://www.balupton.com/projects/jquery-history</a></p> <p>There is also a full featured AJAX extension for it, allowing you to easily integrate Ajax requests to your states/hashes to transform your website into a full featured Web 2.0 Application: <a href="http://www.balupton.com/projects/jquery-ajaxy" rel="nofollow noreferrer">http://www.balupton.com/projects/jquery-ajaxy</a></p> <p>They both provide great documentation on their demo pages to explain what is happening and what is going on.</p> <p>Here is an example of using jQuery History (as taken from the demo site):</p> <pre><code>// Bind a handler for ALL hash/state changes $.History.bind(function(state){ // Update the current element to indicate which state we are now on $current.text('Our current state is: ['+state+']'); // Update the page"s title with our current state on the end document.title = document_title + ' | ' + state; }); // Bind a handler for state: apricots $.History.bind('/apricots',function(state){ // Update Menu updateMenu(state); // Show apricots tab, hide the other tabs $tabs.hide(); $apricots.stop(true,true).fadeIn(200); }); </code></pre> <p>And an example of jQuery Ajaxy (as taken from the demo site):</p> <pre><code> 'page': { selector: '.ajaxy-page', matches: /^\/pages\/?/, request: function(){ // Log what is happening window.console.debug('$.Ajaxy.configure.Controllers.page.request', [this,arguments]); // Adjust Menu $menu.children('.active').removeClass('active'); // Hide Content $content.stop(true,true).fadeOut(400); // Return true return true; }, response: function(){ // Prepare var Ajaxy = $.Ajaxy; var data = this.State.Response.data; var state = this.state; // Log what is happening window.console.debug('$.Ajaxy.configure.Controllers.page.response', [this,arguments], data, state); // Adjust Menu $menu.children(':has(a[href*="'+state+'"])').addClass('active').siblings('.active').removeClass('active'); // Show Content var Action = this; $content.html(data.content).fadeIn(400,function(){ Action.documentReady($content); }); // Return true return true; </code></pre> <p>And if you ever want to get the querystring params (so <code>yoursite/page.html#page1?a.b=1&amp;a.c=2</code>) you can just use:</p> <pre><code>$.History.bind(function(state){ var params = state.queryStringToJSON(); // would give you back {a:{b:1,c:2}} } </code></pre> <p>So check out those demo links to see them in action, and for all installation and usage details.</p> <hr> <p>Edit: After seeing your code, this is all you would have to do to use it with jQuery History.</p> <p>Change:</p> <pre><code>$('.tabbed_content .tabs li a').live('click', function (e){ e.preventDefault(); switchTab($(this)); }); </code></pre> <p>To:</p> <pre><code>// Bind a handler for ALL hash/state changes $.History.bind(function(state){ switchTab(state); }); </code></pre> <p>Or if you plan to use jQuery History for other areas too, then we would want to ensure that we only call switchTab for our tabs and not all hashes:</p> <pre><code>// Bind a handler for ALL hash/state changes $.History.bind(function(state){ if ( $('.tabbed_content &gt; .content &gt; li[id='+state+']').length ) switchTab(state); }); </code></pre> <p>We no longer use a onclick event, instead we bind to jQuery History as that will detect the hashchange. This is the most important concept to understand, as for instance if we bookmark the site then go back to it, we never clicked it. So instead we change our clicks to bind to the hashchange. As when we click it, bookmark it, back or forward, the hashchange will always fire :-)</p>11412627676	0	Passing Html tag in Update query <p>There is an existing table in database where I want to update one column. If I right click on the table--->select edit 200 rows and try to edit the cell data it says that the cell is read-only. I am using SQL management studio 2008R2. So I was trying to update it using an update Query but I am pretty new to the SQL queries and the whole database thing. Is this the proper way to pass an HTML tag in queries?</p> <pre><code>UPDATE OutputTemplate SET emailText='(&lt;p&gt;Thank you for your gift of {Amount} to the {CommunityName}&lt;/p&gt;&lt;br /&gt;Support &amp; Charity Campaign.&lt;br /&gt; -------------------------------------------- --- Transaction Detail --- -------------------------------------------- &lt;span&gt;Credit Card Details&lt;/span&gt; &lt;span style="text-decoration: underline;"&gt;Personal Info Details &amp; Amount&lt;/span&gt;)' WHERE id='2' </code></pre> <p>It's showing some parsing error, incorrect syntax while executing the query.</p> <p>Sorry to ask such a basic question but I tried to google it, unfortunatelly nothing showed up useful.</p> <p>Thanks </p>11529932443	0	 <p>It is solved. The code works as follows. I made a wrong drill down. Truly thanks, I have learned a lot:</p> <pre><code> class func jsonAsUSDAIdAndNameSearchResults (json: NSDictionary) -&gt; [(name: String, idValue: String)] { var usdaItemsSearchResults: [(name: String, idValue: String)] = [] var searchResult: (name: String, idValue: String) if json["hits"] != nil { let results:[AnyObject] = json["hits"]! as [AnyObject] for itemDictionary in results { let fields: NSDictionary = itemDictionary["fields"]? as NSDictionary let name:String? = fields["item_name"] as? String let idValue:String? = itemDictionary["_id"]? as? String if (name? != nil &amp;&amp; idValue? != nil) { searchResult = (name: name!, idValue: idValue!) usdaItemsSearchResults += [searchResult] } } } return usdaItemsSearchResults } </code></pre>11623401900	0	 <p>Figured it out (don't ask me how). For anyone else looking for the answer, here's what I did.</p> <p>I changed this:</p> <pre><code>// Ajaxify our Internal Links $body.ajaxify(); </code></pre> <p>to this:</p> <pre><code>// Ajaxify our Internal Links $('.menuLeft,.menuRight').ajaxify(); </code></pre> <p>I kept trying to add the menu classes here without the parentheses and single quotes. Once I got those in, everything fell into place. Now, only those menus are ajaxified.</p>11730174087	0	 <p>This solution below was tested and it works fine.</p> <p>First:</p> <p>Remove onkeydown event of digit. It should be like this:</p> <pre><code> &lt;input type="text" name="digit" id="digit" size="50" /&gt; </code></pre> <p>Remove onclick event of the button and set the id property.</p> <pre><code>&lt;button class="btn" id="btnClick" title="send" type="button" &gt; </code></pre> <p>create a input hidden in your html to store $cuser php var</p> <pre><code>&lt;input type="hidden" name="cuser" id="cuser" val="&lt;?php echo $cuser ?&gt;" /&gt; </code></pre> <p>Replace your javascript to the following:</p> <pre><code> $(document).ready(function(){ $("#digit").keydown(function(event){ if (event.keyCode == 13 &amp;&amp; event.shiftKey == 0) { alert("ok1"); filltxtarea($("#digit").val()); } }); $("#btnClick").click(function(){ filltxtarea($("#digit").val()); }); function filltxtarea(desctext) { var uchat = $("#cuser").val(); $(".chatboxcontent").append('&lt;div class=chatboxmessage&gt;&lt;span class="chatboxmessagefrom"&gt;' + uchat + ': &lt;/span&gt;&lt;span class="chatboxmessagecontent"&gt;' + desctext + '&lt;/span&gt;&lt;/div&gt;'); $('#digit').val(''); $('#digit').focus(); alert("ok2"); jQuery.ajax({ type: 'POST', url: 'chat.php', dataType: 'json', data: { "newrow": "desctext" }, success: function(response) { alert(response); } }) } }); </code></pre> <p>Any doubts please let me know.</p> <p>Hope it help.</p>11823975299	0	 <p>Thanks for the responses. Very helpful. I decided to go with a proxy approach for which I found a simple solution here: <a href="http://www.paulund.co.uk/make-cross-domain-ajax-calls-with-jquery-and-php" rel="nofollow">http://www.paulund.co.uk/make-cross-domain-ajax-calls-with-jquery-and-php</a></p> <p>For cut and paste simplicity I've added my code here.</p> <p>I created a file called <strong>crossdomain.html</strong>. Included jquery library. Created the following Javascript function:</p> <pre><code>function requestDataByProxy() { var url = "http://UrlYouWantToAcccess.html"; var data = "url=" + url + "&amp;parameters=1&amp;para=2"; $.ajax({ url: "our_domain_url.php", data: data, type: "POST", success: function(data, textStatus, jqXHR){ console.log('Success ' + data); $('#jsonData').html(data); }, error: function (jqXHR, textStatus, errorThrown){ console.log('Error ' + jqXHR); } }); } </code></pre> <p>I also added a simple button and pre tag in HTML to load results:</p> <pre><code>&lt;button onclick="requestDataByProxy()"&gt;Request Data By Proxy&lt;/button&gt; &lt;h3&gt;Requsted Data&lt;/h3&gt; &lt;pre id="jsonData"&gt;&lt;/pre&gt; </code></pre> <p>And then, the PHP file <strong>our_domain_url.php</strong> which uses cURL (make sure you have this enabled!)</p> <pre><code>&lt;?php //set POST variables $url = $_POST['url']; unset($_POST['url']); $fields_string = ""; //url-ify the data for the POST foreach($_POST as $key=&gt;$value) { $fields_string .= $key.'='.$value.'&amp;'; } $fields_string = rtrim($fields_string,'&amp;'); //open connection $ch = curl_init(); //set the url, number of POST vars, POST data curl_setopt($ch,CURLOPT_URL,$url); curl_setopt($ch,CURLOPT_POST,count($_POST)); curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string); //execute post $result = curl_exec($ch); //close connection curl_close($ch); ?&gt; </code></pre> <p>To me, this was a fairly straight-forward solution.</p> <p>Hope this helps someone else!</p> <p>Rob</p>11937986563	0	 <p>Try to use this gem: <a href="https://github.com/net-ssh/net-ssh-gateway/" rel="nofollow">https://github.com/net-ssh/net-ssh-gateway/</a></p> <pre><code>require 'net/ssh/gateway' gateway = Net::SSH::Gateway.new(@jumpoffIp, @jumpoffUser) gateway.open('ont-db01-vip', 1521, 1521) gateway.open('ont-db02-vip', 1521, 1521) res = %x[sqlplus #{@sqlUsername}/#{@sqlPassword}@'#{@sqlUrl}' @scripts/populateASDB.sql &gt; output.txt] puts "populateDb output #{res}" gateway.shutdown! </code></pre>12018745200	0	 <p>We did an htaccess edit for it.</p> <pre><code> &lt;FilesMatch "\.(ttf|otf|eot)$"&gt; &lt;IfModule mod_headers.c&gt; Header set Access-Control-Allow-Origin "*" &lt;/IfModule&gt; &lt;/FilesMatch&gt; </code></pre>12117152024	0	 <p>Instead of looping through all your messages and calling the method that displays an alert for each of them, which results in the multiple alerts being displayed to the user, while looping, add all the 'priority' messages in an array. Then, check the number of alerts in your array and you can show one alert that reflects this information: e.g. for one message you could display the title of the message and some other information as title and message of the alertView, while, when you have multiple messages, you could have a title stating something like "You have x new messages with high priority" where x is the number of messages and some other description.</p>12234829930	1	Is there a way to get function parameter names, including bound-methods excluding `self`? <p>I can use <code>inspect.getargspec</code> to get the parameter names of any function, including bound methods:</p> <pre><code>&gt;&gt;&gt; import inspect &gt;&gt;&gt; class C(object): ... def f(self, a, b): ... pass ... &gt;&gt;&gt; c = C() &gt;&gt;&gt; inspect.getargspec(c.f) ArgSpec(args=['self', 'a', 'b'], varargs=None, keywords=None, defaults=None) &gt;&gt;&gt; </code></pre> <p>However, <code>getargspec</code> includes <code>self</code> in the argument list.</p> <p>Is there a universal way to get the parameter list of any function (and preferably, any callable at all), excluding <code>self</code> if it's a method?</p> <p>EDIT: Please note, I would like a solution which would on both Python 2 and 3.</p>12323673818	0	 <p>Remove <code>()</code> near values</p> <pre><code>INSERT INTO evraklar(evrak_tipi_grubu, evrak_tipi, evrak_konu, evrak_subeye_gelis_tarihi, evrak_gonderen, evrak_alici, evrak_tarihi, evrak_sayisi, evrak_aciklama, evrak_kurum_icindenmi, gelen_evrak_tarihi, gelen_evrak_sayi, gelen_evrak_etakip, evrak_kaydeden_ybs_kullanici_id,kaydeden_kullanici_birim_id) VALUES (6,43,'Test amaçlı girilen konu',STR_TO_DATE('12/12/2012', '%d/%m/%Y'),0,566,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555','YBS:110 nolu evrağa cevaben yazılan yazıdır. Alıcısı:Antalya Valiliği - İl Sağlık Müdürlüğü',0,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555',777777777,1,685), (6,43,'Test amaçlı girilen konu',STR_TO_DATE('12/12/2012', '%d/%m/%Y'),0,612,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555','YBS:110 nolu evrağa cevaben yazılan yazıdır. Alıcısı:Mersin Valiliği - İl Sağlık Müdürlüğü',0,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555',777777777,1,685), (6,43,'Test amaçlı girilen konu',STR_TO_DATE('12/12/2012', '%d/%m/%Y'),0,616,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555','YBS:110 nolu evrağa cevaben yazılan yazıdır. Alıcısı:Niğde Valiliği - İl Sağlık Müdürlüğü',0,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555',777777777,1,685), (6,43,'Test amaçlı girilen konu',STR_TO_DATE('12/12/2012', '%d/%m/%Y'),0,616,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555','YBS:110 nolu evrağa cevaben yazılan yazıdır. Alıcısı:Niğde Valiliği - İl Sağlık Müdürlüğü',0,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555',777777777,1,685), (6,43,'Test amaçlı girilen konu',STR_TO_DATE('12/12/2012', '%d/%m/%Y'),0,616,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555','YBS:110 nolu evrağa cevaben yazılan yazıdır. Alıcısı:Niğde Valiliği - İl Sağlık Müdürlüğü',0,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555',777777777,1,685); </code></pre>12441067535	0	 <p>You can use <code>sum</code> function:</p> <pre><code>In [52]: m = np.random.randint(0,9,(4,4)) In [53]: m Out[53]: array([[8, 8, 2, 1], [2, 7, 1, 2], [8, 6, 8, 7], [5, 2, 5, 2]]) In [56]: np.sum(m == 8) Out[56]: 4 </code></pre> <p><code>m == 8</code> will return a boolean array contains True for each 8 then since python evaluates the True as 1 you can sum up the array items in order to get the number of intended items. </p>1255381004	0	 <p>Thanks Equiso, I didn't find the question you refered to. So this is an exact duplicate of <a href="http://stackoverflow.com/questions/295593/linq-query-built-in-foreach-loop-always-takes-parameter-value-from-last-iteration">Linq query built in foreach loop always takes parameter value from last iteration</a>.</p>12614876110	0	 <p>Considering that all your filters are set to <code>required=false</code> I'll assume the PRO version is paid and guess an answer here:</p> <p>There're 2496 - 2263 devices in the world that were only released in countries that does not accept the paid area of the Play Store.</p>1275073928	0	 <p><a href="http://developer.android.com/guide/topics/data/data-storage.html#db" rel="nofollow">http://developer.android.com/guide/topics/data/data-storage.html#db</a></p>1284787264	0	 <p>I can't speak for all RDBMS systems, but Postgres specifically uses estimated table sizes as part of its efforts to construct query plans. As an example, if a table has two rows, it may choose a sequential table scan for the portion of the JOIN that uses that table, whereas if it has 10000+ rows, it may choose to use an index or hash scan (if either of those are available.) Incidentally, it used to be possible to trigger poor query plans in Postgres by joining VIEWs instead of actual tables, since there were no estimated sizes for VIEWs.</p> <p>Part of how Postgres constructs its query plans depend on tunable parameters in its configuration file. More information on how Postgres constructs its query plans can be found on the Postgres website.</p>12919356791	0	 <p>You want to use an unnamed form. Here is the correct syntax :</p> <pre><code># List the forms that are in the page for form in br.forms(): print "Form name:", form.name print form # To go on the mechanize browser object must have a form selected br.select_form(nd = "form1") # works when form has a name br.form = list(br.forms())[0] # use when form is unnamed </code></pre> <p>Python for beginners has a great cheat sheet about mechanize : <a href="http://www.pythonforbeginners.com/cheatsheet/python-mechanize-cheat-sheet/" rel="nofollow">http://www.pythonforbeginners.com/cheatsheet/python-mechanize-cheat-sheet/</a></p>13033357067	0	 <p>Based on your case, I think you can try to use shellCommandActivity in data pipeline. It will launch a ec2 instance and execute the command you give to data pipeline on your schedule. After finishing the task, pipeline will terminate ec2 instance. </p> <p>Here is doc:</p> <p><a href="http://docs.aws.amazon.com/datapipeline/latest/DeveloperGuide/dp-object-shellcommandactivity.html" rel="nofollow">http://docs.aws.amazon.com/datapipeline/latest/DeveloperGuide/dp-object-shellcommandactivity.html</a></p> <p><a href="http://docs.aws.amazon.com/datapipeline/latest/DeveloperGuide/dp-object-ec2resource.html" rel="nofollow">http://docs.aws.amazon.com/datapipeline/latest/DeveloperGuide/dp-object-ec2resource.html</a></p>13136848540	0	 <p>You can always use <code>std::enable_if</code>:</p> <pre><code>template &lt;typename T, typename ... ARGS&gt; std::enable_if_t&lt;(sizeof...(ARGS)&gt;0)&gt; func(...) { ... } </code></pre> <p>In this case, <code>func</code> will only appear as part of the overload set if the size of <code>ARGS...</code> is greater than 0. However, if the size is zero, you will be missing a function from your overload set. Maybe that's want you want, though.</p>13211232507	0	 <p>Since you're using percentages for both <code>top</code> and <code>margin-top</code>, you can combine them, and simply use <code>top: 10%</code>.</p> <p>See this demo: <a href="http://jsfiddle.net/jackwanders/DEn6r/3/" rel="nofollow">http://jsfiddle.net/jackwanders/DEn6r/3/</a></p> <p>Also, if you'd like to drop the negative left margin, you can use this trick to center the div horizontally:</p> <pre><code>#inside { position: absolute; width: 300px; height: 80%; top: 10%; left: 0; right: 0; // set left and right to 0 margin: 0 auto; // set left and right margins to auto background: white; } </code></pre>1335180846	0	 <p>This looks like a case of reference versus value comparison. If you have two different instances of objects with the same property values, by default they will never be 'equal' using default comparisons. You have to compare the <em>values</em> of the objects. Try writing code to compare the values of each instance.</p>1343553540	0	 <p>The documentation has this line of code:</p> <pre><code>user_db=${user_www}/${filename}-db.sqlite3 </code></pre> <p>Is the <code>filename</code> variable defined? Does the database exist in that location?</p>13519422892	0	 <p>The convoluted way :</p> <pre><code>var t = setTimeout((function(that){ return function(){ jQuery(that).find("ul.topnavsub").hide(); console.log(that); } })(this), 1000); </code></pre> <p>The less-cool-but-still-works-(-and-is-probably-more-readable-) way :</p> <pre><code>var that = this; var t = setTimeout(function(){ jQuery(that).find("ul.topnavsub").hide(); console.log(that); }, 1000); </code></pre>13627330540	0	How to use OperaChromiumDriver for opera version >12.X <p>I understand that to work on opera versions > 12.X, Operachromiumdriver has been developed. At the same time I couldn't get this to work. I downloaded the windows version of operachromiumdriver.exe from <a href="https://github.com/operasoftware/operachromiumdriver/releases" rel="nofollow">https://github.com/operasoftware/operachromiumdriver/releases</a> but to no avail. Can someone help me with this . Please tell me if my understanding is right.</p> <p>Thanks</p>13720222305	0	 <p>There is a particular line-height property for <code>h3</code> tag with bootstrap. </p> <pre><code>h1, h2, h3 { line-height: 40px;//line 760 } </code></pre> <p>So you will have to add style to negotiate this additional height. </p> <p>Also another set for your ul as : </p> <pre><code>ul, ol { margin: 0 0 10px 25px; //line 812 } </code></pre> <p>Solution : </p> <ol> <li><p>Over-ride the ul margin as follows : </p> <pre><code>.pull-right ul{ margin: 0; } </code></pre></li> <li><p>Over-ride the line-height for the h3 as follows : </p> <pre><code>.pull-left h3{ line-height:20px; } </code></pre></li> </ol> <p>First one is pretty straight forward and gives you correct alignment straighaway. Second solution will need you to work some more with tweaking the negative-margins for <code>.pull-right</code>. </p> <p>Debugging URL : <a href="http://jsbin.com/oToRixUp/1/edit?html,css,output" rel="nofollow">http://jsbin.com/oToRixUp/1/edit?html,css,output</a></p> <p>Hope this helps.</p>13831494182	0	 <p><code>Scanner</code> has a <code>nextFloat()</code> for getting <code>float</code>s fashion to <code>nextInt()</code>. Just call it in its own loop:</p> <pre><code>System.out.print("Enter " + c.length + " float values: "); for(int index1 = 0; index1 &lt; c.length; index1++) { c[index1] = input.nextFloat(); } </code></pre> <p>Unfortunately, there is no <code>nextChar()</code> method, so you'd have to emulate it with <code>next(String)</code>'s variant that accepts a pattern:</p> <pre><code>System.out.print("Enter " + b.length + " char values: "); for(int index1 = 0; index1 &lt; b.length; index1++) { b[index1] = input.next(".").charAt(0); } </code></pre>13919070557	0	 <p>Try <code>(35 &gt;= strlen($line)</code> rather than <code>(35 &lt;= strlen($line)</code> if you want lines 35 chars <em>or less</em>. Personally, I prefer to order comparisons like that the other way around, e.g. <code>strlen($line) &lt;= 35</code>, which I think is more readable and avoids mistakes like the one you just made :)</p>14017962433	0	 <p>First of all your UI will hang on button 2 click because it's stuck on the while(true) loop so use BeginAcceptSocket(IAsyncResult r, Object state) for async.</p> <p>Second you must use the loopback address or otherwise the firewall should block the port 10 assuming that it's not open. Also the TcpListener(int port) is obsolote and its better to use the TcpListener(IPAddress localddr, int port) and use both the loopback address.</p>14126381810	0	Calculate 1 line value using 2 or more other lines <p>I have the following query.</p> <p>How this works my client sells kits. Each kit can contains 3 to 5 lines. </p> <pre><code>LINTYP = 6 - Kit Item LINTYP = 7 - Components </code></pre> <p>The sequence should always be 6-7-7 where 6 represents the start of an new kit. There will always be 1 line that would contain an gross price. In the sample below there is 2 kits each containing 2 lines with an line status of 7</p> <p>So what needs to happen is I need to calculate the missing GROSPRI using LINTYP 6 and deducting all my LINTYP 7 lines</p> <p>eq. </p> <pre><code>Grosprice on line 1 (Product 550412) = R1 795 Grosprice on line 3 (Product 501301) = R 185 Grosprice on line 2 (Product 650412) should be R 1795-185 = R1 610 ---------------------------------------------------------------- | Invoice No| Product| Line No| Line Type| Gross Price ---------------------------------------------------------------- |SI141000008| 550412| 1000| 6| 1795.00 ---------------------------------------------------------------- |SI141000008| 650412| 2000| 7| 0.00 | This needs to be R1610 ---------------------------------------------------------------- |SI141000008| 501301| 3000| 7| 185.00 --------------------------------------------------------------- |SI141000008| 550413| 4000| 6| 1855.00 -------------------------------------------------------------- |SI141000008| 650413| 5000| 7| 0.00 | This needs to be R1670 --------------------------------------------------------------- |SI141000008| 501301| 6000| 7| 185.00 ---------------------------------------------------------------- </code></pre>14233820507	0	Could not open ServletContext resource [/WEB-INF/mvc-dispatcher-servlet.xml] <p>I am having this error when I run my code. Any help will be appreciated. Thanks.</p> <p>Here is my dispatcher servlet.</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"&gt; &lt;context:component-scan base-package="tutorial.mvc"/&gt; &lt;mvc:annotation-driven/&gt; &lt;bean id="HandlerMapping" class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/&gt; &lt;bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"&gt; &lt;property name="prefix" value="/WEB-INF/" /&gt; &lt;property name="suffix" value=".jsp" /&gt; &lt;/bean&gt; &lt;/beans&gt; </code></pre> <p>Here is my web.xml</p> <pre><code>&lt;servlet&gt; &lt;servlet-name&gt;mvc-dispatcher&lt;/servlet-name&gt; &lt;servlet-class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt; &lt;/servlet&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;mvc-dispatcher&lt;/servlet-name&gt; &lt;url-pattern&gt;/&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt;/web-app&gt; </code></pre> <p>Here is the error that I end up getting.</p> <pre><code> Nov 20, 2015 1:39:45 AM org.apache.catalina.core.ApplicationContext log SEVERE: StandardWrapper.Throwable org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from ServletContext resource [/WEB-INF/mvc-dispatcher-servlet.xml]; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/mvc-dispatcher-servlet.xml] at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:343) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:303) at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:180) at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:216) at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:187) at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:125) at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:94) at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:129) at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:540) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:454) at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:658) at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:624) at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:672) at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:543) at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:484) at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136) at javax.servlet.GenericServlet.init(GenericServlet.java:158) at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1284) at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1197) at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:864) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:134) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611) at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2462) at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2451) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:745) Caused by: java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/mvc-dispatcher-servlet.xml] at org.springframework.web.context.support.ServletContextResource.getInputStream(ServletContextResource.java:141) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:329) ... 35 more </code></pre>1433410674	0	 <p>The builtin method you are looking for is <a href="http://ruby-doc.org/core-2.0/Array.html#method-i-transpose" rel="nofollow noreferrer">Array#transpose</a></p>14421259556	0	 <p>I believe I've come up with an alternate solution to this problem. There are certain circumstances with the other solution proposed where the label colours appear incorrect (using the system default instead of the overridden colour). This happens while scrolling the list of items.</p> <p>In order to prevent this from happening, we can make use of method swizzling to fix the label colours at their source (rather than patching them after they're already created).</p> <p>The <code>UIWebSelectSinglePicker</code> is shown (as you've stated) which implements the UIPickerViewDelegate protocol. This protocol takes care of providing the NSAttributedString instances which are shown in the picker view via the <code>- (NSAttributedString *)pickerView:(UIPickerView *)pickerView attributedTitleForRow:(NSInteger)row forComponent:(NSInteger)component</code> method. By swizzling the implementation with our own, we can override what the labels look like.</p> <p>To do this, I defined a category on UIPickerView:</p> <pre><code>@implementation UIPickerView (LabelColourOverride) - (NSAttributedString *)overridePickerView:(UIPickerView *)pickerView attributedTitleForRow:(NSInteger)row forComponent:(NSInteger)component { // Get the original title NSMutableAttributedString* title = (NSMutableAttributedString*)[self overridePickerView:pickerView attributedTitleForRow:row forComponent:component]; // Modify any attributes you like. The following changes the text colour. [title setAttributes:@{NSForegroundColorAttributeName : [UIColor redColor]} range:NSMakeRange(0, title.length)]; // You can also conveniently change the background of the picker as well. // Multiple calls to set backgroundColor doesn't seem to slow the use of // the picker, but you could just as easily do a check before setting the // colour to see if it's needed. pickerView.backgroundColor = [UIColor yellowColor]; return title; } @end </code></pre> <p>Then using method swizzling (<a href="http://stackoverflow.com/a/5372042/1270148">see this answer for reference</a>) we swap the implementations:</p> <pre><code>[Swizzle swizzleClass:NSClassFromString(@"UIWebSelectSinglePicker") method:@selector(pickerView:attributedTitleForRow:forComponent:) forClass:[UIPickerView class] method:@selector(overridePickerView:attributedTitleForRow:forComponent:)]; </code></pre> <p>This is the Swizzle implementation I developed based off the link above.</p> <pre><code>@implementation Swizzle + (void)swizzleClass:(Class)originalClass method:(SEL)originalSelector forClass:(Class)overrideClass method:(SEL)overrideSelector { Method originalMethod = class_getInstanceMethod(originalClass, originalSelector); Method overrideMethod = class_getInstanceMethod(overrideClass, overrideSelector); if (class_addMethod(originalClass, originalSelector, method_getImplementation(overrideMethod), method_getTypeEncoding(overrideMethod))) { class_replaceMethod(originalClass, overrideSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod)); } else { method_exchangeImplementations(originalMethod, overrideMethod); } } @end </code></pre> <p>The result of this is that when a label is requested, our override function is called, which calls the original function, which conveniently happens to return us a mutable NSAttributedString that we can modify in anyway we want. We could completely replace the return value if we wanted to and just keep the text. <a href="https://developer.apple.com/library/mac/documentation/cocoa/Reference/ApplicationKit/Classes/NSAttributedString_AppKitAdditions/Reference/Reference.html#//apple_ref/doc/uid/20000167-10585" rel="nofollow">Find the list of attributes you can change here</a>.</p> <p>This solution allows you to globally change all the Picker views in the app with a single call removing the need to register notifications for every view controller where this code is needed (or defining a base class to do the same).</p>14535777586	0	 <p>One solution is to use a <code>Lookup</code> expression, with the minimum price as the value to match. This expression should give each vendor if there is a tie for the cheapest:</p> <pre><code>=Join(LookupSet(Min(Fields!PRICE.Value), Fields!PRICE.Value, Fields!VENDOR.Value, "pv"), " / ") </code></pre> <p>There may be a more elegant solution out there, but is the first one I found.</p>14626670693	0	 <pre><code>&lt;input type="name[]" value="1"&gt; //row1 &lt;input type="name[]" value="2"&gt; //row2 &lt;input type="name[]" value="3"&gt; // row3 </code></pre> <p>this is wrong i think you are looking for this </p> <pre><code>&lt;input type="text" name="name[]" value="1"&gt; //row1 &lt;input type="text" name="name[]" value="2"&gt; //row2 &lt;input type="text" name="name[]" value="3"&gt; // row3 </code></pre>14729094706	0	jQuery - If first element has class then Function <p>I'm looking to add a piece of code sitewide to affect all of my pages.</p> <p>Right now, it goes something like this.</p> <pre><code>if($('#container &gt; div:first').attr('id') == 'filterOptions') { $('#container').prepend('&lt;div class="banner"&gt;&lt;/div&gt;'); } </code></pre> <p><strong>The output:</strong></p> <pre><code>&lt;div id="container"&gt; &lt;div class="banner"&gt;&lt;/div&gt; &lt;div id="filterOptions"&gt;&lt;div&gt; &lt;/div&gt; </code></pre> <p><strong>Example</strong>, if the container looked like this:</p> <pre><code>&lt;div id="container"&gt; &lt;div class="existingBanner"&gt;&lt;/div&gt; &lt;div id="filterOptions"&gt;&lt;div&gt; &lt;/div&gt; </code></pre> <p>Nothing would happen as the first div doesn't have the filterOptions ID.</p> <p>Now I've hit a bump as I also have something that looks like this that the banner DOES get added to</p> <pre><code>&lt;div id="container"&gt; &lt;a class="existingBanner" href="#"&gt;&lt;/a&gt; &lt;div id="filterOptions"&gt;&lt;div&gt; &lt;/div&gt; </code></pre> <p>This will essentially have a double banner which is something I want to avoid. because it's an anchor instead of a div.</p> <p>So my question is. instead of targeting <strong>div:first</strong> how would I target ALL elements?</p> <p><strong>Something like...</strong></p> <p><code>if($('#container &gt;</code> <strong>any</strong><code>:first').attr('id') == 'filterOptions') { ... }</code></p>14837589976	0	How to iterate array in json <p>How to iterate array in json:</p> <pre><code>$(document).ready(function(){ $('#wardno').change(function(){ //any select change on the dropdown with id country trigger this code $("#wardname &gt; option").remove(); //first of all clear select items var ward_id = $('#wardno').val(); $.ajax({ type: "POST", cache: false, url:"get_wardname/"+ward_id, //here we are calling our user controller and get_cities method with the country_id success: function(cities) { try { $.each(cities,function(id,city) { var opt = $('&lt;option /&gt;'); // here we're creating a new select option with for each city opt.val(id[0]); opt.text(id[1]); $('#wardname').append(opt); var opt1 = $('&lt;option /&gt;'); // here we're creating a new select option with for each city opt1.val(city[0]); opt1.text(city[1]); $('#koottaymaname').append(opt1); }); //here we will append these new select options to a dropdown with the id 'cities' } catch(e) { alert(e); } }, error: function (jqXHR, textStatus, errorThrown) { alert("jqXHR: " + jqXHR.status + "\ntextStatus: " + textStatus + "\nerrorThrown: " + errorThrown); } }); }); }); </code></pre> <p>The output from the code is:</p> <pre><code>[{"1":"St. Sebastian"},{"1":"kudumbakoottayma1","2":"kudumbakoottayma2"}] </code></pre> <p>How to iterate into two different drop down list?</p>149459747	0	 <p>There is still a good reason for a template system to use, however not Smarty, but <a href="http://phptal.org/" rel="nofollow noreferrer">PHPTAL</a>. PHPTAL templates are valid XML (and hence XHTML) files. You can farther use dummy content in PHPTAL and so get valid XHTML file with the final appearance, that can be processed and tested with standard tools. Here is a small example:</p> <pre><code>&lt;table&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;First Name&lt;/th&gt; &lt;th&gt;Last Name&lt;/th&gt; &lt;th&gt;Age&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr tal:repeat="users user"&gt; &lt;td tal:content="user/first_name"&gt;Max&lt;/td&gt; &lt;td tal:content="user/last_name"&gt;Mustermann&lt;/td&gt; &lt;td tal:content="user/age"&gt;29&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; </code></pre> <p>PHPTAL template engine will automatically insert all values from users array and replace our dummy values. Nevertheless, the table is already valid XHTML that can be displayed in a browser of your choice.</p>15025610893	0	 <p>If you want to avoid using valid values of <code>float</code>, you could use a NAN:</p> <pre><code>#include &lt;limits&gt; .... float min = std::numeric_limits&lt;float&gt;::quiet_NaN(); </code></pre> <p>You can then use <code>std::isnan</code> to check:</p> <pre><code>#include &lt;cmath&gt; .... bool not_cool = std::isnan(min); </code></pre>1519297352	0	 <p>You receive null at the end of the stream. The client correctly starts, sends Ready, and the the ends, so the stream ends.</p> <p>Totally correct behaviour. If the client would end itself (but instead do something else like reading server messages on stdin), the server would never receive a null.</p> <p>Edit: NEVER EVER (!!!!!) do this:</p> <pre><code>catch(IOException e){} </code></pre> <p>At least write:</p> <pre><code>catch(IOException e){ e.printStackTrace() } </code></pre> <p>This will show you your error!</p> <p>In my company, this is one of the elementary rules of code style!</p>15210412684	0	compiling your own glibc <p>I am trying to compile my own glibc. I have a directory <code>glibc</code>, which contain the <code>glibc</code> source code I downloaded from the internet. From that directory I typed <code>mkdir ../build-glibc</code>. Now from the <code>build-glibc</code> directory I typed <code>../glibc/configure</code>, which performed the configuration. Now I'm not sure how to call <code>make</code>. I can't call it from <code>glibc</code> directory since it doesn't have the configuration set, neither I can call it from <code>build-glibc</code>, since makefile is not in that directory. How do I solve this problem?</p>15339624683	0	 <pre><code>var stuff= ["uyuuyu", "76gyuhj***", "uiyghj", "56tyg", "juijjujh***"]; for(var i = 0; i &lt; stuff.length; i++) { if(stuff[i].indexOf('***') != -1) { stuff[i] = stuff[i].replace('***','0') // this is where i guess the replacing would go } console.log(stuff[i]); } </code></pre>1544920668	0	 <p>Yes there's a standard method for creating these symbols known as <a href="http://en.wikipedia.org/wiki/Name_mangling" rel="nofollow">name mangling.</a></p>15511372530	0	 <p>I can't think of a good way to do this with qsub as there are no programmatic interfaces into the -o and -e options. There is, however, a way to accomplish what you want.</p> <p>Run your qsub with -o and -e pointing to /dev/null. Make the command you run be some type of wrapper that redirects it's own stdout and stderr to files in whatever fashion you want (i.e., your broken down directory structure) before it execs the real job.</p>15632902868	0	Swift set variable to another ViewController <p>I have two tabs. And i want to set data from one tab to another. For example i have a code that switch to another tab:</p> <pre><code>func foundCode(code: String) { print("Code has been found: \(code)") // MySecondViewController.codeSetter(code); self.tabBarController?.selectedIndex = 1; } </code></pre> <p>What is the best way to set it? Or maybe delegate this variable... But how ?</p>15710575459	0	 <p>For what you want this is not the best way of doing it. However what you're talking about requires knowledge of one of the fundamental tennets of PHP and programming in general aka scope, namely what the global scope is.</p> <p>So, if you declare this in the global scope:</p> <pre><code> $uom = new UOM_Class(); </code></pre> <p>Then in any file afterwards you write:</p> <pre><code>global $uom; $uom-&gt;something(); </code></pre> <p>it will work.</p> <p>This is all wasteful however, instead you would be better with static methods, and something more like a singleton pattern e.g.:</p> <pre><code>UOM::Something(); </code></pre> <p>I leave it as a task for you to learn what a singleton is, and what scope is, these are fundamental tennets of PHP, and you should not claim to know PHP without knowing about scope. The best way of putting it is when in everyday conversation, it is called <em>context</em>, the global scope is tantamount to shouting in everyones ear at the same time. Everyone can access it, and its not something you want to pollute</p> <p>I'm sorry if I seem a bit harsh, here's some articles that should help, they talk about scope, singletons and some other methods of doing it, like object factories</p> <p><a href="http://php.net/manual/en/language.variables.scope.php" rel="nofollow">http://php.net/manual/en/language.variables.scope.php</a> http://www.homeandlearn.co.uk/php/php8p2.html</p> <p><a href="http://php.net/manual/en/language.oop5.patterns.php" rel="nofollow">http://php.net/manual/en/language.oop5.patterns.php</a></p>15839795421	0	Show in view only object with specified id <p>i am woking on a project about a restaurant and i need to show on my staff view only the Chef and Su-Chef which has id (Chef-2, Su-Chef 4). I need to show on my view all the Chefs and all the Su-Chefs. The view is organised at the form that is the number is odd (i have the image on left and text on right), if the number is even i have (i have the image on right and text on left) Here is my Controller </p> <pre><code>public function index() { $staff = Staff::where('visible','yes')-&gt;where('delete','no')-&gt;orderBy('name','DESC')-&gt;get(); return view('staff.staff', ['staff' =&gt; $staff]); } </code></pre> <p>And this is my View </p> <pre><code>&lt;section class="bg-deep-yellow"&gt; &lt;div class="container"&gt; &lt;div class="row"&gt; &lt;!-- section title --&gt; &lt;div class="col-md-12 text-center"&gt; &lt;span class="title-small black-text text-uppercase letter-spacing-3 font-weight-600"&gt;I NOSTRI CHEF&lt;/span&gt; &lt;div class="separator-line-thick bg-black no-margin-bottom margin-one xs-margin-top-five"&gt;&lt;/div&gt; &lt;/div&gt; &lt;!-- end section title --&gt; &lt;/div&gt; &lt;div class="row margin-ten no-margin-bottom"&gt; &lt;!-- chef --&gt; &lt;div class="col-md-12 sm-margin-bottom-ten"&gt; &lt;div class="col-md-5 chef-img cover-background" style="background-image:url({{URL::asset('external_assets/assets/images/images_downloaded/chef.jpg') }});"&gt; &lt;div class="img-border"&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="col-md-7 chef-text bg-white text-center"&gt; &lt;img src="{{URL::asset('external_assets/assets/images/images_downloaded/kapele.png') }}" alt=""/&gt;&lt;br&gt; &lt;span class="text-large black-text text-uppercase letter-spacing-3 font-weight-600 margin-ten display-block no-margin-bottom"&gt;Patrick Smith&lt;/span&gt; &lt;span class="text-small text-uppercase letter-spacing-3"&gt;Chef, Co-Founder&lt;/span&gt; &lt;p class="text-med margin-ten width-90 center-col" style="text-align: justify"&gt;Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- end chef --&gt; &lt;!-- chef --&gt; &lt;div class="col-md-12"&gt; &lt;div class="col-md-7 chef-text bg-white text-center"&gt; &lt;img src="{{URL::asset('external_assets/assets/images/images_downloaded/bari.png') }}" alt=""/&gt;&lt;br&gt; &lt;span class="text-large black-text text-uppercase letter-spacing-3 font-weight-600 margin-ten display-block no-margin-bottom"&gt;Sancho Pansa&lt;/span&gt; &lt;span class="text-small text-uppercase letter-spacing-3"&gt;Bartender&lt;/span&gt; &lt;p class="text-med margin-ten width-90 center-col" style="text-align: justify" &gt;Lorem Ipsum is simply dummy text of the printing and typesetting industry.&lt;/p&gt; &lt;/div&gt; &lt;div class="col-md-5 chef-img cover-background" style="background-image:url({{URL::asset('external_assets/assets/images/images_downloaded/chef2.jpg') }});"&gt; &lt;div class="img-border"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- end chef --&gt; &lt;/div&gt; &lt;/div&gt; &lt;/section&gt; </code></pre> <p><a href="http://i.stack.imgur.com/O6FEw.png" rel="nofollow">This is an image of my view</a></p>1592480835	0	NHibernate paging for Telerik Extensions for ASP.NET MVC <p>How can I integrate Telerik Grid paging for ASP.NET MVC (<a href="http://demos.telerik.com/aspnet-mvc/Grid" rel="nofollow noreferrer">http://demos.telerik.com/aspnet-mvc/Grid</a>) with my NHibernate data access with minimal coding?</p>16039010768	0	 <p>You cantry it this way, it should work:</p> <pre><code>$.ajax({ type: "GET", url: "/grafana/dashboard", contentType: "application/json", beforeSend: function(xhr, settings){ xhr.setRequestHeader("some_custom_header", "foo");}, success: function(data){ $("#output_iframe_id").attr('src',"data:text/html;charset=utf-8," + escape(data)) } }); </code></pre>16133492944	0	 <p>Yes, you can do it in single query. Combine those condition in one query then sort YMonth <em>DESC</em> and limit by <em>ROWNUM</em></p> <pre><code>SELECT COUNT(*) FROM ( SELECT XXX,YMONTH FROM MyTable WHERE XXX AND YMONTH IN( TO_CHAR(add_months(SYSDATE,0),'YYYYMM'), TO_CHAR(add_months(SYSDATE,-1),'YYYYMM'), TO_CHAR(add_months(SYSDATE,-2),'YYYYMM'), TO_CHAR(add_months(SYSDATE,-3),'YYYYMM'), TO_CHAR(add_months(SYSDATE,-4),'YYYYMM') ) ORDER BY YMONTH DESC ) WHERE ROWNUM &lt;= 3 </code></pre> <p>Please try the query above, and let see if it works.</p>16240562875	0	 <p>You need to specify the inheritance with extends the base class <a href="http://php.net/manual/en/keyword.extends.php" rel="nofollow noreferrer">http://php.net/manual/en/keyword.extends.php</a></p> <p>Try this for your child class</p> <pre><code>//Child View Class class ChildView extends View{ public function html(){ //I get a fatal error here: calling img_cache on a non-object. //But it should have inherited this from the parent class surely? return '&lt;img src="'.$this-&gt;img_cache-&gt;thumb($this-&gt;data['img-src']).'"/&gt;'; } } </code></pre> <p>Also as @ferdynator says, you are instantiating the parent, not the child, so your <code>Main</code> class also needs to be changed to instantiate <code>ChildView</code>, not the parent <code>View</code></p> <pre><code>//Main class: class Main{ //construct public function Main(){ //get data from model $data = $model-&gt;getData(); //Get the view $view = new ChildView(); //Init view $view-&gt;init( $data ); //Get html $view-&gt;getHTML(); } } </code></pre>16318099453	0	Why the data retrieved isn't shown <p>I would to retrieve the data from <a href="http://api.eventful.com/rest/events/search?app_key=42t54cX7RbrDFczc&amp;location=singapore" rel="nofollow">http://api.eventful.com/rest/events/search?app_key=42t54cX7RbrDFczc&amp;location=singapore</a> . The tag under "title", "start_time", "longitude", "latitude". But I not sure why it couldn't be display out after I added the longitude and latitude.</p> <p>This is from logcat: </p> <pre><code>08-07 17:17:44.190: E/AndroidRuntime(23734): FATAL EXCEPTION: main 08-07 17:17:44.190: E/AndroidRuntime(23734): java.lang.NullPointerException 08-07 17:17:44.190: E/AndroidRuntime(23734): at com.example.eventfulmaptry.MainActivity$ItemAdapter.getView(MainActivity.java:147) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.widget.AbsListView.obtainView(AbsListView.java:1618) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.widget.ListView.measureHeightOfChildren(ListView.java:1241) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.widget.ListView.onMeasure(ListView.java:1152) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.view.View.measure(View.java:8513) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3143) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1017) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.widget.LinearLayout.measureVertical(LinearLayout.java:386) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.widget.LinearLayout.onMeasure(LinearLayout.java:309) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.view.View.measure(View.java:8513) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3143) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.widget.FrameLayout.onMeasure(FrameLayout.java:250) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.view.View.measure(View.java:8513) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.widget.LinearLayout.measureVertical(LinearLayout.java:531) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.widget.LinearLayout.onMeasure(LinearLayout.java:309) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.view.View.measure(View.java:8513) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3143) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.widget.FrameLayout.onMeasure(FrameLayout.java:250) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.view.View.measure(View.java:8513) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.view.ViewRoot.performTraversals(ViewRoot.java:857) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.view.ViewRoot.handleMessage(ViewRoot.java:1878) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.os.Handler.dispatchMessage(Handler.java:99) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.os.Looper.loop(Looper.java:130) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.app.ActivityThread.main(ActivityThread.java:3691) 08-07 17:17:44.190: E/AndroidRuntime(23734): at java.lang.reflect.Method.invokeNative(Native Method) 08-07 17:17:44.190: E/AndroidRuntime(23734): at java.lang.reflect.Method.invoke(Method.java:507) 08-07 17:17:44.190: E/AndroidRuntime(23734): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:912) 08-07 17:17:44.190: E/AndroidRuntime(23734): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:670) 08-07 17:17:44.190: E/AndroidRuntime(23734): at dalvik.system.NativeStart.main(Native Method) </code></pre> <p>This is my code :</p> <pre><code>public class MainActivity extends Activity { ArrayList&lt;String&gt; title; ArrayList&lt;String&gt; start_time; ArrayList&lt;String&gt; latitude; ArrayList&lt;String&gt; longitude; ItemAdapter adapter1; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ListView list = (ListView) findViewById(R.id.list); title = new ArrayList&lt;String&gt;(); latitude = new ArrayList&lt;String&gt;(); longitude = new ArrayList&lt;String&gt;(); try { URL url = new URL( "http://api.eventful.com/rest/events/search?app_key=42t54cX7RbrDFczc&amp;location=singapore"); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(new InputSource(url.openStream())); doc.getDocumentElement().normalize(); NodeList nodeList = doc.getElementsByTagName("event"); for (int i = 0; i &lt; nodeList.getLength(); i++) { Node node = nodeList.item(i); Element fstElmnt = (Element) node; NodeList nameList = fstElmnt.getElementsByTagName("title"); Element nameElement = (Element) nameList.item(0); nameList = nameElement.getChildNodes(); title.add(""+ ((Node) nameList.item(0)).getNodeValue()); NodeList websiteList = fstElmnt.getElementsByTagName("start_time"); Element websiteElement = (Element) websiteList.item(0); websiteList = websiteElement.getChildNodes(); start_time.add(""+ ((Node) websiteList.item(0)).getNodeValue()); NodeList websiteList1 = fstElmnt.getElementsByTagName("latitude"); Element websiteElement1 = (Element) websiteList1.item(0); websiteList1 = websiteElement1.getChildNodes(); latitude.add(""+ ((Node) websiteList1.item(0)).getNodeValue()); NodeList websiteList2 = fstElmnt.getElementsByTagName("longitude"); Element websiteElement2 = (Element) websiteList2.item(0); websiteList2 = websiteElement2.getChildNodes(); longitude.add(""+ ((Node) websiteList2.item(0)).getNodeValue()); } } catch (Exception e) { System.out.println("XML Pasing Excpetion = " + e); } adapter1 = new ItemAdapter(this); list.setAdapter(adapter1); } class ItemAdapter extends BaseAdapter { final LayoutInflater mInflater; private class ViewHolder { public TextView title_text; public TextView des_text; public TextView lat_text; public TextView long_text; } public ItemAdapter(Context context) { // TODO Auto-generated constructor stub super(); mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } //@Override public int getCount() { return title.size(); } //@Override public Object getItem(int position) { return position; } //@Override public long getItemId(int position) { return position; } //@Override public View getView(final int position, View convertView, ViewGroup parent) { View view = convertView; final ViewHolder holder; if (convertView == null) { view = mInflater.inflate(R.layout.mainpage_list,parent, false); holder = new ViewHolder(); holder.title_text = (TextView) view.findViewById(R.id.title_text); holder.des_text = (TextView) view.findViewById(R.id.des_text); holder.lat_text = (TextView) view.findViewById(R.id.lat_text); holder.long_text = (TextView) view.findViewById(R.id.long_text); view.setTag(holder); } else { holder = (ViewHolder) view.getTag(); } holder.title_text.setText(""+title.get(position)); holder.des_text.setText(""+Html.fromHtml(start_time.get(position))); holder.lat_text.setText(""+Html.fromHtml(latitude.get(position))); holder.long_text.setText(""+Html.fromHtml(longitude.get(position))); return view; } } } </code></pre>16415404711	0	 <p>in the javascript function. Then it will not postback.</p> <pre><code> $j(".colorBoxLink").click((function () { $j("div#popup").show(); var editor = new wysihtml5.Editor("wysihtml5_textarea", { // id of textarea element toolbar: "wysihtml5-toolbar", // id of toolbar element parserRules: wysihtml5ParserRules, // defined in parser rules set stylesheets: ["Styles/wysihtml5.css", "Styles/wysihtml5.css"] }); $j.colorbox({ inline: true, href: "#popup", modal: true, scrolling: false, onCleanup: function () { $j("div#popup").hide(); } }); return false; })); </code></pre>16511773518	0	 <p>Could it be because you want to measure the font before it's been fully loaded ?</p> <p>In my example it seems to be working fine : <a href="http://jsfiddle.net/VkyMV/1/" rel="nofollow">Font example</a></p>16610176059	0	 <p>The images you are using might be too large for an animation. How large are they? In an animation, Android loads all of the images into memory and uncompresses them meaning that every pixel will take 4 bytes. So 50k would mean that your image is 111px x 111px. It seems from the error each frame is about 480 x 640, which is really large. Try using smaller images.</p>16728839887	0	number bytes read from gpio input is zero <p>I have some strange behaviour when trying to read gpio output pin. I get that the first read return 1 (1 bytes read), but all next read from same gpio return 0. I would assume that it should always read 1, because there is always something to read from input pin.</p> <pre><code>gpio = 8; fd = open("/sys/class/gpio/export", O_WRONLY); sprintf(buf, "%d", gpio); rc = write(fd, buf, strlen(buf)); if (rc == -1) printf("failed in write 17\n"); close(fd); sprintf(buf, "/sys/class/gpio/gpio%d/direction", gpio); fd = open(buf, O_WRONLY); rc = write(fd, "in", 2); if (rc == -1) printf("failed in write 18\n"); close(fd); sprintf(buf, "/sys/class/gpio/gpio%d/value", gpio); gpio_tdo = open(buf, O_RDWR); rc = read(gpio_tdo, &amp;value, 1); &lt;-- rc here is 1 rc = read(gpio_tdo, &amp;value, 1); &lt;-- rc here is 0 rc = read(gpio_tdo, &amp;value, 1); &lt;-- rc here is 0 </code></pre> <p>Should the read of one byte from the gpio input always return 1 ?</p>16829310107	0	 <p>You want to use <a href="http://dev.mysql.com/doc/refman/5.0/en/join.html" rel="nofollow">Mysql Join</a> to join the two tables together which reference the user id.</p> <p>Account Table</p> <pre><code>CREATE TABLE `account` ( `id` INT UNSIGNED AUTO_INCREMENT, `username` VARCHAR(10) NOT NULL, PRIMARY KEY(`id`) ); </code></pre> <p>Suspension Table</p> <pre><code>CREATE TABLE `suspension` ( `user_id` INT UNSIGNED DEFAULT NULL, FOREIGN KEY (`user_id`) REFERENCES account(`id`) ON DELETE CASCADE ON UPDATE CASCADE ); </code></pre> <p>Query</p> <pre><code>SELECT A.username, A.id FROM `account` AS A LEFT JOIN `suspension` AS S ON S.user_id = A.id WHERE A.id = 5 AND S.user_id IS NULL; </code></pre> <p>If the user appears in Suspension, no results are returned. If the user isn't suspended then the user result is returned. To return the user and their suspension status, you can use the below query.</p> <pre><code>SELECT A.username, A.id, (S.user_id IS NOT NULL) AS `suspended` FROM `account` AS A LEFT JOIN `suspension` AS S ON S.user_id = A.id WHERE A.id = 5; </code></pre>16935814790	0	 <ul> <li>Using <code>stack.top()</code> is illegal if the <code>stack</code> is empty.<br> Change <code>while((!highPrecedence(stack.top(),c)) &amp;&amp; (stack.size()!=0)){</code><br> to <code>while((!stack.empty()) &amp;&amp; (!highPrecedence(stack.top(),c))){</code></li> <li>The initiali value of <code>i</code> is not good and you are printing uninitialized variable, which has indeterminate value.<br> Change <code>int i=0;</code> to <code>int i=-1;</code></li> </ul>1708285825	0	How to change text or background color in a Windows console application <p>Which C++ function changes text or background color (MS Visual studio)? For example <code>cout&lt;&lt;"This text";</code> how to make "This text" red color.</p>17119047053	0	having a powers of 2 questions <pre><code> import acm.program.*; public class Practice3 extends ConsoleProgram { public static int powersOf2(int k) { int x = 0; while (k &lt; 1000) { x = k; k *= 2; } return x; } public void run() { println(powersOf2(1)); println(powersOf2(0)); println(powersOf2(2)); println(powersOf2(-1)); println(powersOf2(3000)); } </code></pre> <p>I don't think I really get right values from <code>powersOf2</code>. Only 512 is displayed when I run program. And if I run it by each <code>println</code>, it gives me:</p> <pre><code>512 none 512 none 0 </code></pre> <p>Is there something wrong? or values are correct?</p>17218961158	0	Formatting data based on string or number - google visualization <p>I have database in PHPMyAdmin, Excel and CSV format (all the same just different formats). To put this data in a table in google visualization numbers are written as they are but string values need to have a ' either side of the text. For example:</p> <pre><code>['MESSI','FC BARCELONA','ARGENTINA',169,67,25,'Left foot','SS',98,99,38,74,9855704866], </code></pre> <p>My database has over 2000 rows so manually doing this isn't an option. Is there a way in any of these formats to make all string variables have the ' either side and all numbers to be written by themselves. The CSV format already splits cells using a comma which I need but it would also be useful if each row started with [ and ended with ] . Anyone know how to do this using any of these formats?</p>1733193062	0	 <p>You can make C++ callable from C by using the <code>extern "C"</code> construct.</p>17434803298	0	 <p>You are forgetting an AND in this line.</p> <pre><code>SELECT * FROM users WHERE id ='" . $_SESSION['UserRow'] . "' AND note='$noteSequence'", $connection </code></pre>17517293590	0	How efficient is .clone()? <p>I have a page with a canvas area (nothing to do wth HTML5) where people can create "art" by dragging in photos, creating divs that they can drag, stretch, color, etc. etc. etc. The canvas div is inside a canvasContainer div. Now I'd like to implement an UNDO option. My thought was to do a</p> <pre><code> canvasBackup$ = $('#canvas').clone(); </code></pre> <p>when an operation began, say at every dragStart event, and at the end of the operation an UNDO, if asked for with Ctrl-Z, would execute</p> <pre><code> $('#canvas').remove(); canvasBackup$.appendTo($('#canvasContainer'); </code></pre> <p>My concern is that the clone, and perhaps the append, might be a bit compute intensive as the page grows and start slowing down the page's responsiveness. I suppose it depends on how jQuery does the clone. If it just breaks off the section from the DOM and does a straight memory copy, it shouldn't be bad. But if there's a lot of calculation and building going on it could be a problem.</p> <p>Does anyone have a feel for whether this is a reasonable approach to implementing UNDO?</p> <p>Thanks</p>1764024056	0	Threads vs. Async <p>I have been reading up on the threaded model of programming versus the asynchronous model from this really good article. <a href="http://krondo.com/blog/?p=1209">http://krondo.com/blog/?p=1209</a></p> <p>However, the article mentions the following points.</p> <ol> <li>An async program will simply outperform a sync program by switching between tasks whenever there is a I/O.</li> <li>Threads are managed by the operating system.</li> </ol> <p>I remember reading that threads are managed by the operating system by moving around TCBs between the Ready-Queue and the Waiting-Queue(amongst other queues). In this case, threads don't waste time on waiting either do they?</p> <p>In light of the above mentioned, what are the advantages of async programs over threaded programs?</p>17732481778	0	 <p>Quick answer:</p> <p>First af all you are starting from x=0 and then increasing it which is not the best solution since you are looking for the maximum value and not the first one. So for that I would go from an upperbound that can be</p> <p>x=abs((b)^(1/4))</p> <p>than decrease from that value, and as soon you find an element &lt;=b you are done. </p> <p>You can even think in this way:</p> <pre><code>for y=b to 1 solve(x^4+x^3+x^2+x+1=y) if has an integer solution then return solution </code></pre> <p>See <a href="https://en.wikipedia.org/wiki/Quartic_function#Solving_a_quartic_equation" rel="nofollow">this</a></p> <p>This is a super quick answer I hope I didn't write too many stupid things, and sorry I don't know yet how to write math here.</p>1785167035	0	Excutereader is very slow when taking data by oledbcommand object <p>I am fetching data from dBase4 database by using object of oledbcommand and load it into datatable. but it is taking too much time to fetch 160 records around 5-10 minutes. Please Help me Out.</p> <p>Code:</p> <pre><code> using (OleDbConnection cn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;" + @"Data Source=" + TrendFilePath + "\\" + Pathname + ";" + @"Extended Properties=dBASE III;")) using (OleDbCommand cm = cn.CreateCommand()) { cn.Open(); for (int L = 0; L &lt;= months; L++) { DataTable dt_Dbf = new DataTable(); From_Date = DateTime.ParseExact(frmdate, dateFormat2, provider); From_Date = From_Date.AddMonths(L); int month = From_Date.Month; string year = "1" + From_Date.Year.ToString().Substring(2, 2); if (L == 0) { cm.CommandText = @"SELECT * FROM 128.DBF where DATE_Y =" + year + " and DATE_M = " + month + " and DATE_D&gt;=" + From_Day + ""; dt_Dbf.Load(cm.ExecuteReader(CommandBehavior.CloseConnection)); } } } </code></pre>17920116797	0	 <p>Scala has implemented also the async/await paradigm, which can simplify some algorithms.</p> <p>Here is the proposal: <a href="http://docs.scala-lang.org/sips/pending/async.html" rel="nofollow">http://docs.scala-lang.org/sips/pending/async.html</a></p> <p>Here is the implementation: <a href="https://github.com/scala/async" rel="nofollow">https://github.com/scala/async</a></p>18023311182	0	Convert JSON String to Object - jquery <p>I have a JSON String like this.</p> <pre><code>{"label":"label","label1":"67041","label2":"745","label3":"45191","label4":"11‌​464"} </code></pre> <p>I wanted to convert it to object like this</p> <pre><code>[{"label":"label","label1":"67041","label2":"745","label3":"45191","label4":"11‌​464"}] </code></pre> <p>I did figure that out like this.</p> <pre><code>'[' + {"label":"label","label1":"67041","label2":"745","label3":"45191","label4":"11‌​464"} + ']' </code></pre> <p>And using <code>$.parseJSON()</code> to make it a JSON.</p> <p>But instead of concatenating. Is there any elegant way to do it?</p> <p>If so please do share me.</p> <p>Thanks in advance.</p>18125766028	0	 <p>What you want to do is not called "instantiation." You can instantiate a universally quantified hypothesis and you can instantiate an existentially quantified conclusion, but not vice versa. I'm thinking the proper name is "introduction". You can introduce existential quantification in a hypothesis and you can introduce universal quantification in the conclusion. If it seems like you're "eliminating" instead, that's because, when proving something, you start at the bottom of a sequent calculus deriviation, and work your way backwards to the top.</p> <p>Anyway, use the tactic <code>firstorder</code>. Also, use the command <code>Set Firstorder Depth 0</code> to turn off proof search if you only want to simplify your goal.</p> <p>If your goal has higher order elements though, you'll probably get an error message. In that case, you can use something like <code>simplify</code>.</p> <pre><code>Ltac simplify := repeat match goal with | h1 : False |- _ =&gt; destruct h1 | |- True =&gt; constructor | h1 : True |- _ =&gt; clear h1 | |- ~ _ =&gt; intro | h1 : ~ ?p1, h2 : ?p1 |- _ =&gt; destruct (h1 h2) | h1 : _ \/ _ |- _ =&gt; destruct h1 | |- _ /\ _ =&gt; constructor | h1 : _ /\ _ |- _ =&gt; destruct h1 | h1 : exists _, _ |- _ =&gt; destruct h1 | |- forall _, _ =&gt; intro | _ : ?x1 = ?x2 |- _ =&gt; subst x2 || subst x1 end. </code></pre>1829885459	0	 <p>In my case (label on a panel) I set <code>label.AutoSize = false</code> and <code>label.Dock = Fill</code>. And the label text is wrapped automatically.</p>18322554399	0	 <p>You should set your categories in beforeFilter() of appController for that because navigation will be included in every page .</p> <pre><code> function beforeFilter() { parent::beforeFilter(); ///set your categories here $this-&gt;set('Categories',$Categories); } </code></pre>18421777508	0	 <p>I am not sure you are asking for this.</p> <p>If the path of the folders are same you can use <code>-or</code> with <code>find</code></p> <p><code>find $CATALINA_HOME/webapps/myapp/WEB-INF/lib/ -name "*.jar" -or -type d</code></p> <p><code>-type d</code> will also find directories</p>1853505889	0	Can I set the size attribute of StructLayout at runtime? <p>Im trying to use SendInput to simulate keyboard presses in my app and want to support both 32-bit and 64-bit.</p> <p>I've determined that for this to work, I need to have 2 different INPUT structs as such</p> <pre><code> [StructLayout(LayoutKind.Sequential)] public struct KEYBDINPUT { public ushort wVk; // Virtual Key Code public ushort wScan; // Scan Code public uint dwFlags; public uint time; public IntPtr dwExtraInfo; } [StructLayout(LayoutKind.Explicit, Size = 28)] public struct INPUT32 { [FieldOffset(0)] public uint type; // eg. INPUT_KEYBOARD [FieldOffset(4)] public KEYBDINPUT ki; } [StructLayout(LayoutKind.Explicit, Size = 40)] public struct INPUT64 { [FieldOffset(0)] public uint type; // eg. INPUT_KEYBOARD [FieldOffset(8)] public KEYBDINPUT ki; } </code></pre> <p>I wanted to know if there was a way to set the <code>StructLayout</code> size and <code>FieldOffsets</code> at runtime so I could use just one <code>INPUT</code> struct and determine the size and fieldoffset depending on the machine.</p> <p>I have tried the code below but I would like to know if the same is possible at runtime instead of compile time. </p> <pre><code>#if _M_IX86 [StructLayout(LayoutKind.Explicit, Size = 28)] #else [StructLayout(LayoutKind.Explicit, Size = 40)] #endif public struct INPUT { [FieldOffset(0)] public uint type; // eg. INPUT_KEYBOARD #if _M_IX86 [FieldOffset(4)] #else [FieldOffset(8)] #endif public KEYBDINPUT ki; } </code></pre>18627625701	0	 <p>You did not even use a search engine to look for the error message.</p> <p>In google, the first result is the <a href="http://pear.php.net/manual/en/package.database.mdb2.faq.php" rel="nofollow">MDB2 FAQ page</a> which explains the error and the reason for it.</p>1871673178	0	cvs2svn changes binary files <p>I'm using cvs2svn to migrate from <a href="http://en.wikipedia.org/wiki/Concurrent_Versions_System" rel="nofollow noreferrer">CVS</a> to <a href="http://en.wikipedia.org/wiki/Subversion_%28software%29" rel="nofollow noreferrer">SVN</a>.</p> <p>I've noticed a problem with my binary file after the conversion was completed.</p> <p>I'm using auto-props file, which is very helpful.</p> <p>After the conversion I took the file from CVS and compared it to the same file from SVN. The file is binary. Using <a href="http://en.wikipedia.org/wiki/WinMerge" rel="nofollow noreferrer">WinMerge</a>, I see that there is a difference between the files.</p> <p>What can be the problem? </p>18828022612	0	 <p>This might hepls you</p> <pre><code>declare @t table(a date,b time) insert into @t values (getdate(),'7:00:00 AM') select * from @t where a&gt;'2015/01/19' or (a=getdate() and a&gt;'6:00:00 AM') </code></pre>189314693	0	 <pre><code>select * from canonical_list_of_tags where tag not in (select tag from used_tags) </code></pre> <p>At least that works in T-SQL for SQL Server ... </p> <p><strong>Edit:</strong> Assuming that the table <code>canonical_list_of_tags</code> is populated with the result of "<em>Given a collection of user specified tags</em>"</p>19029112595	0	I want to copy files from one folder to another in my dedicated server <p>I placed files in my root folder and copy when user try to download the files like </p> <blockquote> <p>/root/filelocation/file.mp3</p> </blockquote> <p>when user on download page</p> <pre><code>copy("/root/filelocation/file.mp3","download/file.mp3"); </code></pre> <p>i use this command but it takes too much load time</p> <p>i have ffmpeg installed in server also</p>19118265414	0	PHP login with PDO, doesnt seem to work <p>There aren't any errors given, but for some reason the code doesnt seem to work..</p> <p>Here is the code:</p> <pre><code>&lt;?php session_start(); require_once('inc/db.php'); if(isset($_SESSION['username'])) { header("location: index.php"); } else { try { $username = mysql_real_escape_string($_POST['username']); $password = mysql_real_escape_string($_POST['password']); $SQL = $dbh-&gt;prepare('SELECT * FROM users WHERE username =:username AND password =:password'); $SQL-&gt;bindParam(':username', $username); $SQL-&gt;bindParam(':password', $password); $SQL-&gt;execute(); $total = $SQL-&gt;rowCount(); $row = $SQL-&gt;fetch(); if($total &gt; 0) { if($row['verified'] &gt; 0) { $_SESSION['username'] = $username; } else { echo "Unverified"; } } else { echo "Incorrect"; } } catch(PDOException $e) { } } ?&gt; </code></pre> <p>Can anyone help me see what's wrong? Thank you a lot in advance :)</p> <p>EDIT::::</p> <p>Here is my db.php</p> <pre><code>&lt;?php try { $DB_NAME = 'users'; $DB_USER = 'root'; $DB_PASS = ''; $dbh = new PDO('mysql:host=localhost;dbname='.$DB_NAME, $DB_USER, $DB_PASS, array(PDO::MYSQL_ATTR_INIT_COMMAND =&gt; "SET NAMES utf8")); $dbh-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch(PDOException $e) { echo "Error?"; } ?&gt; </code></pre>19237164244	0	Do we need a second thread to process time-consuming jobs with inotify? <p>Referenc: <a href="http://stackoverflow.com/questions/9067175/how-to-monitor-a-folder-with-all-subfolders-and-files-inside">How to monitor a folder with all subfolders and files inside?</a></p> <p>I need to monitor a directory for any file with extension of *.log. If a new file is created or is moved in, I will process the file. it takes variable time to process each file.</p> <p>Question> Do I need to create one thread to listen the inotify event and push the new file name into queue and use another thread to process the queue? My concern is that if I don't use separate threads, then the inotify may fail to track changes caused by some large files.</p> <p>I have simulated the problem with <code>sleep</code> while processing each log file without any multi-thread code. It seems to me that inotify always corrects get all created/moved files in the directory.</p> <p>Here is my simulation.</p> <p><strong>Terminate 1</strong>: I run the app and listen the inotify event within the main. Whenever processing one log file, I will sleep for 10 second then print the file name to console.</p> <p><strong>Terminte 2</strong>: I will copy multiple files at time T1 to the monitored directory. Before the app finishing processing all previous files, I will move multiple files at time T2. Then again time T3, I will copy multiple files to the directory before the app finishes.</p> <p>Observation: The app processed all log files as I expected.</p> <p>Question> Is this expected behavior of inotify or I just run lucky this morning? In other words, will inotify cache unprocessed events in case of simulation as above?</p> <p>FYI: the code snippet I used:</p> <pre><code>#define EVENT_SIZE ( sizeof (struct inotify_event) ) #define BUFFER_LEN ( 1024 * ( EVENT_SIZE + NAME_MAX + 1) ) wd = inotify_add_watch( fd, root.string().c_str(), IN_CREATE | IN_MOVED_TO ); while ( true ) { length = read( fd, buffer, BUFFER_LEN ); for ( int i = 0; i &lt; length; ) { const inotify_event *ptrEvent = reinterpret_cast&lt;inotify_event *&gt;(&amp;buffer[i]); ... // processing the event sleep(10); // to simulate the long work i += INO_EVENT_SIZE + ptrEvent-&gt;len; } } </code></pre>19313701479	0	 <p>You can simply extend your code: </p> <pre><code>if ( (str[i] == '-' &amp;&amp; minus) || (str[i] &gt;= '0' &amp;&amp; str[i] &lt;= '9') || (str[i] == 'e' || str[i] == 'E') ) </code></pre> <p>to </p> <pre><code>char separator = ','; //or whatever you want int have_separator = 0; if ( (str[i] == '-' &amp;&amp; minus) || (str[i] &gt;= '0' &amp;&amp; str[i] &lt;= '9') || (str[i] == 'e' || str[i] == 'E') || str[i] == separator ) { if (str[i] == separator &amp;&amp; have_separator == 0) { have_separator = 1; str_dbl[j++] = str[i]; continue; } ... </code></pre> <p>Please note that this is only some try to show the idea - not the real working code (but it could work anyway). You can use similar concept. </p>19427301946	0	 <p>As <strong>Jake Wharton</strong> said</p> <pre><code>You can use a "@FieldMap Map&lt;String, String&gt;" for that. </code></pre> <p>Looks like Robospice Retrofit module is out of date.</p>19518907389	0	 <p>For MySQL 5.7:</p> <pre><code>ALTER TABLE tbl_name RENAME INDEX old_index_name TO new_index_name </code></pre> <p>For MySQL older versions:</p> <pre><code>ALTER TABLE tbl_name DROP INDEX old_index_name, ADD INDEX new_index_name (...) </code></pre> <p>See <a href="http://dev.mysql.com/doc/refman/5.7/en/alter-table.html">http://dev.mysql.com/doc/refman/5.7/en/alter-table.html</a></p>19611654411	0	Single criteria query with two separate sets of restrictions <p>I'm wondering if you can create a single criteria query then somehow create two separate sets of restrictions with two completely different sets of results without having to issue a second query?</p>19735723634	0	 <p>Simplest way would be to use a wild card character (<strong>*</strong>) and add the <code>wildcarded</code> option</p> <pre><code>cts:search(fn:doc(),cts:word-query("*226", ('wildcarded'))) </code></pre> <p><strong>EDIT:</strong> </p> <p>Although this matches the example documents, as Kishan points out in the comments, <strong>the wildcard also matches unwanted documents</strong> (e.g. containing "226226"). </p> <p>Since range indexes are not an option in this case because the data is mixed, here is an alternative hack:</p> <pre><code>cts:search( fn:doc(), cts:word-query( for $lead in ('', '0', '00', '000') return $lead || "226")) </code></pre> <p>Obviously, this depends on how many leading zeros there can be and will only work if this is known and limited.</p>19824274151	0	 <p>The "enhanced for loop" as you call it (it's actually called the <code>foreach</code> loop) internally uses an iterator for any iterable - including linked lists.</p> <p>In other words it is O(n)</p> <p>It does handle looping over arrays by using an integer and iterating over it that way but that's fine as it performs well in an array.</p> <p>The only advantages of using an iterator manually are if you need to remove some or all of the elements as you iterate.</p>19921697697	0	 <p>Yes, performing method calls like this is perfectly fine. They're marked as <code>private</code> so they remain encapsulated within your class and unexposed to the outside world.</p> <p>If these method calls started to cause the class/object to deviate its main purpose, breaking <a href="http://en.wikipedia.org/wiki/Single_responsibility_principle" rel="nofollow">single responsibility principle</a>, then it would be worth looking at breaking the class into finer units and injecting this new dependency via <a href="http://stackoverflow.com/questions/130794/what-is-dependency-injection">dependency injection</a>. An example of this would be if the <code>checkBaz</code> method was performing a database look-up.</p> <p>In terms of unit testing, what you really want to do is <a href="http://stackoverflow.com/questions/383947/what-does-it-mean-to-program-to-an-interface">program to an interface not implementation</a> by creating an interface for your foo class and implementing it. This means whenever you program to it you're programming to a contract - allowing you to easily mock your <code>IFoo</code> implementation.</p> <p>eg:</p> <pre><code>class Foo implements IFoo { } </code></pre> <p>Your interface will look like this:</p> <pre><code>interface IFoo { public function setBaz($baz) public function setBar($bar) } </code></pre> <p>I would also recommend following the <a href="http://pear.php.net/manual/en/standards.php" rel="nofollow">PEAR coding standard</a> and make your class names uppercase first. Though if this is a decision made by you or your team then that's entirely your call.</p>2002674853	0	How to delete a string inside a file (.txt) in Java Programming <p>I would like to delete a string or a line inside a ".txt" file (for example filen.txt). For example, I have these lines in the file:</p> <blockquote> <p>1JUAN DELACRUZ<br/> 2jUan dela Cruz<br/> 3Juan Dela Cruz<br/></p> </blockquote> <p>Then delete the 2nd line (<code>2jUan dela Cruz</code>), so the ".txt" file will look like:</p> <blockquote> <p>1JUAN DELACRUZ<br/> 3Juan Dela Cruz<br/></p> </blockquote> <p>How can I do this?</p>20136784340	0	Finding the last row with data using vba <p><strong>I am creating a program in which everytime it generates, the generated data will appear in a specific sheet and arranged in specific date order . It looks like this.</strong></p> <p><a href="https://i.stack.imgur.com/1vUeq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1vUeq.png" alt="Generated data"></a></p> <p>But when I generate again, the existing data will be replaced/covered by the new data generated. Looks like this.</p> <p><a href="https://i.stack.imgur.com/KM55r.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KM55r.png" alt="enter image description here"></a></p> <p>Now my idea is, before I am going to paste another data, I want to find out first what is the last used cell with value so that in the next generation of data, it wont be replaced/covered by the new one. Can someone help me with this. The output should look like this.</p> <p><a href="https://i.stack.imgur.com/YLXnq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YLXnq.png" alt="enter image description here"></a></p> <p>Any help everyone? Thanks! </p>20223514209	0	 <p>One of the first things you need to learn about SQL (and relational databases) is that you shouldn't store multiple values in a single field.</p> <p>You should create another table and store one value per row.</p> <p>This will make your querying easier, and your database structure better.</p> <pre><code>select case when exists (select countryname from itemcountries where yourtable.id=itemcountries.id and countryname = @country) then 'national' else 'regional' end from yourtable </code></pre>20322104970	0	 <p>Looking at the source of <a href="http://www.ruby-doc.org/stdlib-2.1.1/libdoc/set/rdoc/Set.html#method-c-new" rel="nofollow"><code>Set::new</code></a>:</p> <pre><code># File set.rb, line 80 def initialize(enum = nil, &amp;block) # :yields: o @hash ||= Hash.new enum.nil? and return if block do_with_enum(enum) { |o| add(block[o]) } else # you did not supply any block, when you called `new` # thus else part will be executed here merge(enum) end end </code></pre> <p>it seems that <code>Set.new</code> calls method <code>#add</code> internally. In the OP's example, <code>block</code> is <code>nil</code>, thus <a href="http://www.ruby-doc.org/stdlib-2.1.1/libdoc/set/rdoc/Set.html#method-i-merge" rel="nofollow"><code>#merge</code></a> is called:</p> <pre><code># File set.rb, line 351 def merge(enum) if enum.instance_of?(self.class) @hash.update(enum.instance_variable_get(:@hash)) else # in your case this else part will be executed. do_with_enum(enum) { |o| add(o) } end self end </code></pre> <p>Hence <code>add</code> is called for each element of <code>enum</code> (<code>[1,2]</code>). Here, you overrode the original <code>#add</code> method, and within that method, you are calling the old <code>#add</code> method with the argument <code>5</code>.</p> <p>Set implements a collection of <strong>unordered values with no duplicates</strong>. Thus even if you added <code>5</code> twice, you are getting only one <code>5</code>. This is the reason you are not getting <code>#&lt;Set: {1,2}&gt;</code>, but <code>#&lt;Set: {5}&gt;</code>. As below, when you call <code>Set.new</code>, the object <code>#&lt;Set: {5}&gt;</code> is created just as I explained above:</p> <pre><code>require 'set' class Set alias :old_add :add def add(arg) arg = 5 old_add arg end end s = Set.new ([1,2]) s # =&gt; #&lt;Set: {5}&gt; </code></pre> <p>When you called <code>s.add(3)</code>, your overridden <code>add</code> method was called, and it again passed the <code>5</code> to the old <code>add</code> method. As I said earlier, <code>Set</code> doesn't contain duplicate values, thus the object will still be the same as the earlier <code>#&lt;Set: {5}&gt;</code>.</p>20425561125	1	Parsing and Storing HTML Tags Along With Text <p>I'm looking for a way to parse unicode strings of html and essentially split all of the elements of the string (html elements as well as individual tokens) and store them in a list. <code>BeautifulSoup</code> obviously has some nice functionality for parsing html, such as the <code>.get_text</code> method, but this doesn't preserve the tags themselves.</p> <p>What I need is something like this. Given an html unicode string such as </p> <p><code>s = u'&lt;b&gt;This is some important text!&lt;/b&gt;</code>, </p> <p>what I would like to have as a result is a list like this:</p> <p><code>['&lt;b&gt;', 'This', 'is', 'some', 'important', 'text!', '&lt;/b&gt;']</code></p> <p>There must be an easy way to do this with BeautifulSoup that I'm just not seeing in SO searches. Thanks for reading.</p> <p><b>EDIT:</b> since this has been getting some questions as to the purpose of storing the tags, I'm interested in using the tags as features for a project in text classification. I'm experimenting with using different structural features from an online discussion forum in addition to the n-grams present within forum posts.</p>20513795206	0	Strange output from Java typecast <p>I am playing around with simple encryption using RSA algorithms and found a strange bug.</p> <pre><code>private static Integer testEnc(Integer value){ Integer val = (int)Math.pow(value, 37); return val % 437; } private static Integer testDec(Integer value){ Integer val = new Integer((int)Math.pow(value, 289)); return val % 437; } public static void main(String[] args) { System.out.print("Encode 55 = "); Integer encoded = testEnc(2); System.out.println(encoded + "\n"); System.out.print(encoded + " decoded = "); Integer decoded = testDec(3977645); System.out.println(decoded + "n"); } </code></pre> <p>Both of the following functions return 97 regardless of input. If I comment out the modulus and just return val, the returned value is 2147483647.</p> <p>Type casting double to int seems to be the issue but I am not sure why this is. These methods are static only because I was calling them from a main method.</p>20626871943	0	 <p>You're looking for the <code>extend</code> method.</p> <pre><code>&gt;&gt;&gt; l = [1, 2, 3] &gt;&gt;&gt; l.extend([4, 5, 6]) &gt;&gt;&gt; print l [1, 2, 3, 4, 5, 6] </code></pre>20723109791	0	 <p>I had a similar problem recently, specifically making the width match the parent div and also respond. I couldn't work out why Trust Pilot thought it appropriate to set something to make the height of the frame dynamic and not the width, but anyway.</p> <p>Firstly, I had some CSS for the parent div, like:</p> <pre><code>&lt;style type="text/css"&gt; div.trust-pilot{ width: 100% !important; height: auto; } &lt;/style&gt; </code></pre> <p>This may not actually be necessary, but I put it there anyway.</p> <p>These are the 'trustbox' settings I used (see <a href="http://trustpilot.github.io/developers/#trustbox" rel="nofollow">http://trustpilot.github.io/developers/#trustbox</a>):</p> <pre><code>&lt;div id="trust-pilot" class="trust-pilot"&gt; &lt;div class="tp_-_box" data-tp-settings="domainId: xxxxxxx, bgColor: F5F5F5, showRatingText: False, showComplementaryText: False, showUserImage: False, showDate: False, width: -1, numOfReviews: 6, useDynamicHeight: False, height: 348 "&gt; &lt;/div&gt; &lt;script type="text/javascript"&gt; (function () { var a = "https:" == document.location.protocol ? "https://ssl.trustpilot.com" : "http://s.trustpilot.com", b = document.createElement("script"); b.type = "text/javascript"; b.async = true; b.src = a + "/tpelements/tp_elements_all.js"; var c = document.getElementsByTagName("script")[0]; c.parentNode.insertBefore(b, c) })(); &lt;/script&gt; &lt;/div&gt; </code></pre> <p>Replace the domainId with something valid (in the case of this question, it's 3660907). Note that the width: -1 parameter might work already for you except if you want the page to be responsive (that is below).</p> <p>Firstly, to make the width match the parent div, I used:</p> <pre><code>&lt;script type="text/javascript"&gt; jQuery( window ).load(function() { _width = jQuery('#trust-pilot').innerWidth(); jQuery('#tpiframe-box0').attr('width',_width); }); &lt;/script&gt; </code></pre> <p>And then to make the box respond, I used:</p> <pre><code>&lt;script type="text/javascript"&gt; jQuery( window ).resize(function() { _width = jQuery('#trust-pilot').innerWidth(); jQuery('#tpiframe-box0').attr('width',_width); }); &lt;/script&gt; </code></pre> <p>I hope that this helps. Shaun.</p>20816341343	0	Exactly which content-inserting block helpers have changed behaviour in Rails 3? <p>The <a href="http://guides.rubyonrails.org/3_0_release_notes.html#helpers-with-blocks" rel="nofollow">release notes for Rails 3.0</a> include this change:</p> <blockquote> <p><strong>7.4.2 Helpers with Blocks</strong></p> <p>Helpers like <code>form_for</code> or <code>div_for</code> that insert content from a block use <code>&lt;%=</code> now:</p> <pre><code>&lt;%= form_for @post do |f| %&gt; ... &lt;% end %&gt; </code></pre> <p>Your own helpers of that kind are expected to return a string, rather than appending to the output buffer by hand.</p> <p>Helpers that do something else, like <code>cache</code> or <code>content_for</code>, are not affected by this change, they need <code>&lt;%</code> as before.</p> </blockquote> <p>We're in the process of migrating a web application from Rails 2.3.18 to Rails 3.1.12, and it would be very useful to have a complete list of such helpers that have changed, so that we can check all of their occurrences in our source code, but I'm having trouble finding an authoritative list of this kind.</p> <p>I've tried looking through the git history of the <a href="https://github.com/rails/rails" rel="nofollow">rails project</a>, but there seem to be many commits with related changes, and they're not obviously grouped on particular branch. For example, it seems to be clear that this list includes:</p> <ul> <li><code>form_for</code></li> <li><code>form_tag</code></li> <li><code>fields_for</code></li> <li><code>field_set_tag</code></li> </ul> <p>... from <a href="https://github.com/rails/rails/commit/7b622786fcc5046a06989ec7a" rel="nofollow">7b622786f</a>,</p> <ul> <li><code>link_to</code></li> </ul> <p>... alluded to in <a href="https://github.com/rails/rails/commit/e98474096a6a514b2a5c299" rel="nofollow">e98474096</a> and:</p> <ul> <li><code>div_for</code></li> <li><code>content_tag_for</code></li> </ul> <p>... alluded to in <a href="https://github.com/rails/rails/commit/e8d2f48cff858728280eef575e95c3b82ecd69d9" rel="nofollow">e8d2f48cff</a></p> <ul> <li><code>remote_form_for</code></li> </ul> <p>.... alluded to in <a href="https://github.com/rails/rails/commit/4f0982db91f4e67b36aec7f1e7445655e7bce8ce" rel="nofollow">0982db91f</a>, although it's removed in Rails 3.</p> <p>However, I'm sure that's not complete - can anyone supply a complete list?</p>20920669873	0	 <p>This cannot be done using only CSS3. CSS3 does not allow you to reference parent elements based on a hover of the child element. You'll need to use JavaScript for this.</p> <p>Hopefully browsers will soon support the parent selector that is featured in the new CSS4 documentation</p>21038444485	0	Use std::bind to remove arguments <p>I'm currently coding against a library that uses an event system to signify user interface interactions. Each listener can either be a pointer to an object and a function to call, or a std::function. For example, the MenuItem object defines an OnClick event that will call a function that takes a MenuItem*:</p> <pre><code>someMenuItem-&gt;OnClick.addListener( this, &amp;myObj.doSomeAction ); ... void myObj::doSomeAction( MenuItem* menuItem ) {} </code></pre> <p>or</p> <pre><code>someMenuItem-&gt;OnClick.addListener( []( MenuItem* menuItem ) {} ); </code></pre> <p>It's often the case that doSomeAction is part of the public API of the class that we might want to call for some reason other than the user selecting the menu item. Is it possible to use std::bind to throw away the MenuItem* argument so that <code>doSomeAction( MenuItem* menuItem )</code> could be defined as simply <code>doSomeAction()</code>?</p> <p>PS - I do realize that I could use lambdas to do the same thing, but if bind can do the same thing then it might be more stylistically pleasing to some.</p>21123350686	0	 <p><a href="http://projects.spring.io/spring-social-facebook/" rel="nofollow">Spring Social Facebook</a> is a module within the <a href="http://projects.spring.io/spring-social/" rel="nofollow">Spring Social</a> family of projects that enables you to connect your <a href="http://spring.io/" rel="nofollow">Spring</a> application with the <a href="https://developers.facebook.com/docs/graph-api" rel="nofollow">Facebook Graph API</a>.</p> <h2>Features:</h2> <ul> <li>A service provider and connection factory for use with Spring Social's connection framework</li> <li>A Java API binding for Facebook's Graph API</li> <li>A real-time update controller for handling real-time update callbacks from Facebook</li> <li>A disconnect controller to handle disconnect callbacks from Facebook</li> <li>Much more...</li> </ul> <h2>More Information:</h2> <ul> <li><a href="http://projects.spring.io/spring-social-facebook/" rel="nofollow">Project Page</a></li> <li><a href="https://github.com/spring-projects/spring-social-facebook" rel="nofollow">Source (GitHub)</a></li> <li><a href="https://github.com/spring-projects/spring-social-samples" rel="nofollow">Sample Applications (GitHub)</a></li> <li><a href="http://docs.spring.io/spring-social-facebook/docs/current/apidocs/" rel="nofollow">API Documentation (Javadoc)</a></li> <li><a href="http://docs.spring.io/spring-social-facebook/docs/current/reference/htmlsingle/" rel="nofollow">Reference Documentation</a></li> <li><a href="https://jira.spring.io/browse/SOCIALFB/" rel="nofollow">Issue Tracker (JIRA)</a></li> <li><a href="http://spring.io/blog" rel="nofollow">The Spring Blog</a></li> </ul> <h2>Getting Started Guides:</h2> <ul> <li><a href="http://spring.io/guides/gs/accessing-facebook/" rel="nofollow">Accessing Facebook Data</a></li> <li><a href="http://spring.io/guides/gs/register-facebook-app/" rel="nofollow">Registering an Application with Facebook</a></li> </ul> <h2>Related Tags:</h2> <ul> <li><a href="/questions/tagged/spring-framework" class="post-tag" title="show questions tagged &#39;spring-framework&#39;" rel="tag">spring-framework</a></li> <li><a href="/questions/tagged/spring-social" class="post-tag" title="show questions tagged &#39;spring-social&#39;" rel="tag">spring-social</a></li> <li><a href="/questions/tagged/spring-social-twitter" class="post-tag" title="show questions tagged &#39;spring-social-twitter&#39;" rel="tag">spring-social-twitter</a></li> <li><a href="/questions/tagged/spring-social-linkedin" class="post-tag" title="show questions tagged &#39;spring-social-linkedin&#39;" rel="tag">spring-social-linkedin</a></li> <li><a href="/questions/tagged/facebook-oauth" class="post-tag" title="show questions tagged &#39;facebook-oauth&#39;" rel="tag">facebook-oauth</a></li> <li><a href="/questions/tagged/oauth" class="post-tag" title="show questions tagged &#39;oauth&#39;" rel="tag">oauth</a></li> <li><a href="/questions/tagged/oauth-2.0" class="post-tag" title="show questions tagged &#39;oauth-2.0&#39;" rel="tag">oauth-2.0</a></li> </ul>21217179304	0	 <p>You invoke the nextToken() method 3 times. That will get you 3 different tokens</p> <pre><code>int pos = productsTokenizer .nextToken().indexOf("-"); String product = productsTokenizer .nextToken().substring(0, pos+1); String count= productsTokenizer .nextToken().substring(pos, pos+1); </code></pre> <p>Instead you should do something like:</p> <pre><code>String token = productsTokenizer .nextToken(); int pos = token.indexOf("-"); String product = token.substring(...); String count= token.substring(...); </code></pre> <p>I'll let you figure out the proper indexes for the substring() method.</p> <p>Also instead of using a do/while structure it is better to just use a while loop:</p> <pre><code>while(productsTokenizer .hasMoreTokens()) { // add your code here } </code></pre> <p>That is don't assume there is a token.</p>21333224978	0	Is there a way to a prevent a String from being interpolated in Swift? <p>I'm experimenting around the idea of a simple logger that would look like this:</p> <pre><code>log(constant: String, _ variable: [String: AnyObject]? = nil) </code></pre> <p>Which would be used like this:</p> <pre><code>log("Something happened", ["error": error]) </code></pre> <p>However I want to prevent misuse of the constant/variable pattern like the following:</p> <pre><code>log("Something happened: \(error)") // `error` should be passed in the `variable` argument </code></pre> <p>Is there a way to make sure that <code>constant</code> wasn't constructed with a string interpolation?</p>21430851800	0	 <p>You can add directly the content string</p> <p><a href="http://jsfiddle.net/0m5axpxx/" rel="nofollow">http://jsfiddle.net/0m5axpxx/</a></p> <pre><code>var iframe = document.createElement('iframe'); var html = '&lt;body&gt;&lt;scr'+ 'ipt&gt;alert(1)&lt;/s' + 'cript&gt;Content&lt;/body&gt;'; iframe.src = 'data:text/html;charset=utf-8,' + encodeURI(html); document.body.appendChild(iframe); </code></pre>21510710677	0	Login in JSF 2.0 with Glassfish 3.1.2 and JAAS <p>I'm having problems when I try to login with JSF 2. I am getting the following message:</p> <blockquote> <p>WEB9102: Web Login Failed: com.sun.enterprise.security.auth.login.common.LoginException: Login failed: Security Exception</p> </blockquote> <p>This is my login page:</p> <pre><code>&lt;?xml version='1.0' encoding='UTF-8' ?&gt; &lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;ui:composition xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" template="./modeloLogin.xhtml" xmlns:p="http://primefaces.prime.com.tr/ui" xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html"&gt; &lt;ui:define name="content"&gt; &lt;p:growl id="growl" showDetail="true" life="3000" /&gt; &lt;div id="formulario"&gt; &lt;p:panel id="pnl" header="Login"&gt; &lt;h:form&gt; &lt;h:panelGrid columns="2" cellpadding="5"&gt; &lt;h:outputLabel for="username" value="Usuário:" /&gt; &lt;p:inputText value="#{beanLogin.username}" id="username" required="true" label="username" /&gt; &lt;h:outputLabel for="password" value="Senha:" /&gt; &lt;p:password value="#{beanLogin.password}" feedback="false" minLength="" id="password" label="password" /&gt; &lt;p:commandButton id="loginButton" value="Efetuar Login" update=":growl" action="#{beanLogin.login()}" ajax="false"/&gt; &lt;p:commandLink value="Esqueceu a senha?" &gt;&lt;/p:commandLink&gt; &lt;/h:panelGrid&gt; &lt;/h:form&gt; &lt;/p:panel&gt; &lt;/div&gt; &lt;/ui:define&gt; &lt;/ui:composition&gt; </code></pre> <p>And this is my BeanLogin:</p> <pre><code>/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package sonic.action.login; import java.security.Principal; import javax.ejb.Stateless; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import javax.faces.context.FacesContext; import javax.inject.Named; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; /** * * @author 081315620876 */ @ManagedBean @SessionScoped public class BeanLogin { private String username; private String password; public BeanLogin() { } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String login() { FacesContext context = FacesContext.getCurrentInstance(); HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest(); System.out.println(context == null); System.out.println(request == null); try { request.login(this.username, this.password); if(request.isUserInRole("admin")) { return "/pages/protected/admin/index.xhtml?faces-redirect=true"; } else if(request.isUserInRole("professor")){ return "/pages/protected/professor/index.xhtml?faces-redirect=true"; } } catch (ServletException e) { context.addMessage(null, new FacesMessage("Login failed.")); return "error"; } return "login.xhtml"; } public void logout() { FacesContext context = FacesContext.getCurrentInstance(); HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest(); try { request.logout(); } catch (ServletException e) { context.addMessage(null, new FacesMessage("Logout failed.")); } } } </code></pre> <p>Thanks in advance for help :)</p>21630001286	0	 <p>It is because the whitespace between the <code>&lt;li&gt;</code> elements is significant. If you remove all whitespace, the elements will be right next to each other. Either you just do this:</p> <pre><code>&lt;li class="orange start"&gt;&lt;a href=""&gt;Home&lt;/a&gt;&lt;/li&gt;&lt;li class="orange center"&gt;&lt;a href=""&gt;Forum&lt;/a&gt;&lt;/li&gt; </code></pre> <p>Or, if you want to keep the line breaks in code, which I usually think is a good thing, you can insert an HTML comment like this:</p> <pre><code>&lt;li class="orange start"&gt;&lt;a href=""&gt;Home&lt;/a&gt;&lt;/li&gt;&lt;!-- --&gt;&lt;li class="orange center"&gt;&lt;a href=""&gt;Forum&lt;/a&gt;&lt;/li&gt; </code></pre> <p>It's a matter of taste, but I tend to favor the latter because I find it more readable.</p>2171653217	0	How do I figure out the smtp_port for my localhost? <p>I am using a script that is sending out emails and I am receiving the following error:</p> <p><strong>Warning: mail() [function.mail]: Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set() in C:\wamp\bin\php\php5.3.0\PEAR\Mail\mail.php on line 125</strong></p> <p>How to i figure out the stmp_port for my localhost?</p> <p>EDIT:</p> <p>I am sorry. I don't have my own server on my computer and I don't think I want to set one up either. I didn't realiza that it what it takes. I do have a hosting provider though and would like to figure out how to use their smtp information to send my mail though if anyone knows how to do that.</p> <p>According to the reply by Nathan Adams, I can use my hosting provider's smtp information. What exactly do I need to find out where do I put that information in my php.ini file?</p>21835382289	1	Controlling pygame animation through text input <p>I need to create a fighting game that gives prompts and accepts input through text, such as a raw input and then performs the animation, while still have the characters animated, e.g. moving back and forth in a ready to fight stance. How would I go about this?</p>21918016725	0	Update specific object in array <p>I have a DataTable and an array of objects that I loop through.</p> <p>For each row in a data table, I search through my collection of objects with Linq, and if found, that object needs to be updated. But how do I refresh my collection without reloading it from the database?</p> <pre><code>Car[] mycars = Cars.RetrieveCars(); //This is my collection of objects //Iterate through Cars and find a match using (DataTable dt = data.ExecuteDataSet(@"SELECT * FROM aTable").Tables[0]) { foreach (DataRow dr in dt.Rows) //Iterate through Data Table { var found = (from item in mycars where item.colour == dr["colour"].ToString() &amp;&amp; item.updated == false select item).First(); if (found == null) //Do something else { found.updated = true; Cars.SaveCar(found); //HERE: Now here I would like to refresh my collection (mycars) so that the LINQ searches on updated data. //Something like mycars[found].updated = true //But obviously mycars can only accept int, and preferably I do not want to reload from the database for performance reasons. } </code></pre> <p>How else can I search and update a single item in the array?</p>2205004015	0	 <pre><code>&lt;s:HGroup gap="0"&gt; &lt;s:Label text="234 cm" fontSize="14"/&gt; &lt;s:Label text="2" baselineShift="4" fontSize="10"/&gt; &lt;/s:HGroup&gt; </code></pre> <p>The HGroup might not actually be needed, depending on context.</p>2218711744	0	 <pre><code>function displaymessage() { $("select").each(function() { this.selectedIndex = 0 }); } </code></pre> <p>this selects the first option (not necessarily having value = 0)</p>22216891837	0	Restrict a user to visit a particular page only certain number of times <p>How to restrict a user (role) to visit a particular page only certain number of times? </p> <p>I am using drupal 6. It's for premium content, I just want to give 5 premium content free.</p>2231545284	0	 <p>i found this problem earlier and the work around was to use the builder directly</p> <pre><code>def test = { def sw = new StringWriter() def b = new MarkupBuilder(sw) b.html(contentType: "text/html") { div(id: "myDiv") { p "somess text inside the div" b.form(action: 'get') { p "inside form" } } } render sw } </code></pre> <p>will render the following HTML</p> <pre><code>&lt;html contentType='text/html'&gt; &lt;div id='myDiv'&gt; &lt;p&gt;somess text inside the div&lt;/p&gt; &lt;form action='get'&gt; &lt;p&gt;inside form&lt;/p&gt; &lt;/form&gt; &lt;/div&gt; &lt;/html&gt; </code></pre>22423445517	0	calculate expected cost of final product using atleast k out of n items in c <p>Suppose I have 4 items and i have to pick at least 1 item to make a product out of them. I have cost corresponding to each item as Item1 -> 4 , Item2 -> 7 , Item3 -> 2 , Item4 -> 5.I have to to find expected cost of the final product means an average of all possible combinations Item used like if I use only 1 item then cost may be 4 , 7 , 2 , 5 and if if i use 2 items the cost would be 4+7 , 4+2 , 4+5 , 7+2 , 7+5 , 2+5 and similarly all combinations for using three items and 4+2+7+5 for using four items.Adding those all combinations and dividng them with no. of combination gives me expected cost of the final product.So I want to find sum of all these combinations then how can I go for it??</p> <p>I think recursion will be used for calculating these combination but unable to apply ???</p>22536428352	0	 <p>To make it works, you can use <code>padding-left</code> instead of <code>margin-left</code> and also adapt the width of the <code>td</code></p> <p><a href="https://jsfiddle.net/3hamc4b0/1/" rel="nofollow">See it here</a></p> <pre><code>.modules-table &gt; tbody &gt; tr &gt; td:nth-child(2) { width:256px; padding-left:80px; } </code></pre>22618184897	0	 <p>HTML5 solution, min 5, max 10 characters</p> <p><strong><a href="http://jsfiddle.net/xhqsB/102/" rel="nofollow">http://jsfiddle.net/xhqsB/102/</a></strong></p> <pre><code>&lt;form&gt; &lt;input pattern=".{5,10}"&gt; &lt;input type="submit" value="Check"&gt;&lt;/input&gt; &lt;/form&gt; </code></pre>22722970292	0	 <p>A problem I ran into was related to the ordering in Application_Start(). Note the order of Web API configuraton below:</p> <p>This does NOT work</p> <pre class="lang-cs prettyprint-override"><code>protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); GlobalConfiguration.Configure(WebApiConfig.Register); } </code></pre> <p>This does work </p> <pre class="lang-cs prettyprint-override"><code>protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } </code></pre>22811785670	0	Closing generic handlers before logging and other functionalities <p>I am working on a high volumne API that needs to provide substantial logging for reporting purposes. In order to limit the effect of this logging functionality to the api users, I would like to finish the request, and then start logging all the stuff that needs to be logged. </p> <p>Will flush, then close cause this to occur or will the client system wait until all the "Business Stuff " (BS for short) is complete?</p>22928901933	0	 <p>Ok, i found a way to do that. </p> <p>Basically i changed <code>trigger()</code> function to <code>debugEmail()</code>, and inside the <code>class-wc-email-customer-invoice.php</code> file, copied the <code>trigger()</code> into <code>debugEmail()</code> and removed the this line to avoid the send of the email: </p> <pre><code>$this-&gt;send( $this-&gt;get_recipient(), $this-&gt;get_subject(), $this-&gt;get_content(), $this-&gt;get_headers(), $this-&gt;get_attachments() ); </code></pre>23012958793	0	onclick to clear form fields JavaScript <p>I hope this question isn't duplicating something in the archives; I've looked but can't find an answer that solves my problem because I seem to be following the advice given.</p> <p>I am making a dynamic form with JavaScript and would like to clear the prompts in each field when a user clicks in it. Here is part of what I have for one of the form fields. I can't figure out why onlick="this.value=' '"; isn't working. Any help would be much appreciated.</p> <pre><code> var VMake1 = document.createElement("input"); VMake1.name = "veh_1_make"; VMake1.type = "text"; VMake1.value= "Please enter the make of vehicle 1"; if (VMake1.value=="Please enter the make of vehicle 1") { onclick="this.value=''"; } placeVeh1Make.parentNode.insertBefore(VMake1,placeVeh1Make); </code></pre> <p>Thank you in advance for your help.</p>23134448066	0	Time the execution of batch file commands of VB scripts without using WScript.sleep <p>I have a batch file which starts telnet server and stops telnet server with sleep time in between. </p> <p><strong>Script:</strong></p> <pre><code>set OBJECT=WScript.CreateObject("WScript.Shell") WScript.sleep 5000 OBJECT.SendKeys "net stop TlntSvr{ENTER}" WScript.sleep 30000 OBJECT.SendKeys "net start TlntSvr{ENTER}" WScript.sleep 30000 OBJECT.SendKeys "exit" </code></pre> <p>Like you see the above code stops <em>telnet services</em> using <code>net stop TlntSvr</code> and then starts telnet services using <code>net start TlntSvr</code> with a sleep time in between like <code>WScript.sleep 3000</code>. </p> <p><strong>Issue:</strong> Now I need to run <strong>this batch file</strong> in multiple systems PCs/laptop and in each execution cases, the time taken to start/stop <em>telnet services/telnet service installation</em> varies and hence I had to <strong>modify the sleep time every time</strong> when I am running the script in different systems. </p> <p><strong>Question:</strong> Is there a way to time the next execution such that as soon as the first execution completes only then it will start the next execution? Meaning I don't need to configure the sleep time for each laptops/PCS, the next execution will start only when the first execution is over according to each PC's own execution behavior. </p>2327460474	0	 <p>Look at <a href="http://stackoverflow.com/questions/672032/fluent-nhibernate-working-with-interfaces/683364#683364">this post</a>. It seems that the problem may be in the mapping of IUser in NH</p>23332997838	0	Number of times one string occurs within another in C <p>I have written a function that uses the strstr() function to determine if string2 has any matches in string1. This works fine (I also convert both strings to lower case so that I can do a case-insensitive match.). However, strstr() only finds the <em>first</em> time the match occurs. Is there a way to use it to find <em>each</em> time a match occurs? For example:</p> <pre><code>string1[] = "ABCDEFABC"; string2[] = "ABC"; </code></pre> <p>Would return 0 as a match is found in position 0, and 6 as it's found again in position 6?</p> <p>Here's the original function as written (including call to function in main):</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &lt;stdlib.h&gt; char *strstrnc(const char *str1, const char *str2); int main() { char buf1[80],buf2[80]; printf("Enter the first string to be compared: "); gets(buf1); printf("Enter the second string to be compared: "); gets(buf2); strstrnc(buf1,buf2); return 0; } char *strstrnc(const char *buf1, const char *buf2) { char *p1, *ptr1, *p2, *ptr2, *loc; int ctr; ptr1 = malloc(80 * sizeof(char)); ptr2 = malloc(80 * sizeof(char)); p1 = ptr1; p2 = ptr2; for (ctr = 0; ctr &lt; strlen(buf1);ctr++) { *p1++ = tolower(buf1[ctr]); } *p1 = '\0'; for (ctr = 0; ctr &lt; strlen(buf2);ctr++) { *p2++ = tolower(buf2[ctr]); } *p2 = '\0'; printf("The new first string is %s.\n", ptr1); printf("The new first string is %s.\n", ptr2); loc = strstr(ptr1,ptr2); if (loc == NULL) { printf("No match was found!\n"); } else { printf("%s was found at position %ld.\n", ptr2, loc-ptr1); } return loc; } </code></pre>23435177242	0	 <p>Try to checkout your branch to a different folder than your original work folder, git will not delete the existing folders (from the different folder structure) to this new one - so you would still have folders in Tests\x-test and Tests\y-test.</p> <p>However, <code>git clean -fd</code> could be used to remove untracked directories.</p>23528406619	0	Which languages are required to learn animation designing? <p>I want to design animations, short animated video clips but even after Googling a little I got no clue about it.</p> <p>I want ways that include programming rather than mouse clicks.</p>23624368496	0	 <p>You, of course, could do this. You should loop all existing htmlElement instances with current class</p> <pre><code>$(".sel_region").each(function(index, element) { element.prototype.yourFunction = function() { console.log("exists!"); }; }); </code></pre> <p>You should call this loop on Dom load</p>23719572181	0	 CSS Generated Content allows us to insert and move content around a document. We can use this to create footnotes, endnotes, and section notes, as well as counters and strings, which can be used for running headers and footers, section numbering, and lists.23830758924	0	 <blockquote> <ol> <li>Do I really need to use a mutex in a thread each time I access the data from the read-only array? If so could you explain why?</li> </ol> </blockquote> <p>No. Because the data is never modified, there cannot be synchronization problem.</p> <blockquote> <ol start="2"> <li>Do I need to use a mutex in a thread when it writes to the result array even though this will be the only thread that ever writes to this element?</li> </ol> </blockquote> <p>Depends.</p> <ol> <li>If any other thread is going to read the element, you need synchronization.</li> <li>If any thread may modify the size of the vector, you need synchronization.</li> </ol> <p>In any case, take care of not writing into adjacent memory locations by different threads a lot. That could destroy the performance. See "false sharing". Considering, you probably don't have a lot of cores and therefore not a lot of threads and you say write is done only once, this is probably not going to be a significant problem though.</p> <blockquote> <ol start="3"> <li>Should I use atomic data types and will there be any significant time over head if I do?</li> </ol> </blockquote> <p>If you use locks (mutex), atomic variables are not necessary (and they do have overhead). If you need no synchronization, atomic variables are not necessary. If you need synchronization, then atomic variables can be used to avoid locks in some cases. In which cases can you use atomics instead of locks... is more complicated and beyond the scope of this question I think.</p> <p>Given the description of your situation in the comments, it seems that no synchronization is required at all and therefore no atomics nor locks.</p> <blockquote> <ol start="4"> <li>...Would my array elements in this example be aligned, or is there some way to ensure they are?</li> </ol> </blockquote> <p>As pointed out by Arvid, you can request specific alignment using the <a href="http://en.cppreference.com/w/cpp/language/alignas" rel="nofollow">alginas</a> keyword which was introduced in c++11. Pre c++11, you may resort to compiler specific extensions: <a href="https://gcc.gnu.org/onlinedocs/gcc-5.1.0/gcc/Variable-Attributes.html" rel="nofollow">https://gcc.gnu.org/onlinedocs/gcc-5.1.0/gcc/Variable-Attributes.html</a></p>23924873633	0	 <p>Here's one possible way of reading a file and getting just the "chunks":</p> <pre><code>import java.io.*; import java.util.Scanner; public class ScanXan { public static void main(String[] args) throws IOException { Scanner s = null; try { s = new Scanner(new BufferedReader(new FileReader("xanadu.txt"))); while (s.hasNext()) { System.out.println(s.next()); } } finally { if (s != null) { s.close(); } } } } </code></pre> <p>You can take a look at the <a href="http://docs.oracle.com/javase/tutorial/essential/io/scanning.html" rel="nofollow">Java Scanner Tutorial</a> for other ideas.</p>24020391612	0	 <p>Note: its not a tested code. but it tries to solve your problem. Please give it a try</p> <pre><code>import csv with open(file_name, 'rb') as csvfile: marksReader = csv.reader(csvfile) for row in marksReader: if len(row) &lt; 8: # 8 is the number of columns in your file. # row has some missing columns or empty continue # Unpack columns of row; you can also do like fname = row[0] and lname = row[1] and so on ... (fname,lname,subj1,marks1,subj2,marks2,subj3,marks3) = *row # you can use float in place of int if marks contains decimals totalMarks = int(marks1) + int(marks2) + int(marks3) print '%s %s scored: %s'%(fname, lname, totalMarks) print 'End.' </code></pre>24115237073	0	D3.js: "Uncaught SyntaxError: Unexpected token ILLEGAL"? <p>I've just <a href="http://d3js.org/d3.v3.zip">downloaded D3.js from d3js.org</a> (link to zip file), unzipped it, and referenced it in the following HTML page: </p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;D3 Sandbox&lt;/title&gt; &lt;style&gt; &lt;/head&gt; &lt;body&gt; &lt;script src="/d3.v3.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>But when I load this page, my console (in Chrome) is giving me this error: </p> <pre><code>Uncaught SyntaxError: Unexpected token ILLEGAL: line 2 </code></pre> <p>It doesn't like the <a href="https://github.com/mbostock/d3/blob/master/d3.js#L2">pi and e symbols at the start of the file</a>. Errrr... what can I do about this? I am serving the file with python's SimpleHTTPServer.</p> <p>Update: yes I know I can just link to a CDN version, but I would prefer to serve the file locally. </p>24230795069	0	 <p>While you could use AntiSamy to do it, I don't know how sensible that would be. Kinda defeats the purpose of it's flexibility, I think. I'd be curious about the overhead, even if minimal, to running that as a filter over just a regex.</p> <p>Personally I'd probably opt for the regex route in this scenario. Your example appears to only strip the brackets. Is that acceptable in your situation? (understandable if it was just an example) Perhaps use something like this:</p> <pre><code>reReplace(string, "&lt;[^&gt;]*&gt;", "", "ALL"); </code></pre>2431143722	0	 <p>Does the machine running IE 6 have its security settings set to reject cookies? Alternatively, if you are using one of the various techniques that supposedly allow you to run multiple versions of IE on the same machine, be aware that the results are not perfect, and often cause subtle aspects of the browser to break on one or more of the versions: for example, see <a href="http://tredosoft.com/Multiple_IE#comment-1843" rel="nofollow noreferrer">this comment on Tredosoft's Multiple IE page</a> about cookies failing in IE 6.</p>2442218937	0	HAS-A, IS-A terminology in object oriented language <p>I was just reading through the book and it had the terms, "HAS-A" and "IS-A" in it. Anyone know what they mean specifically? Tried searching in the book, but the book is 600 pages long. Thanks!</p>24524947366	0	Ruby on Rails: How to change the Foriegn Key values on a collection_select drop down? <p>I have a drop down on my form which is a foreign key to another table:</p> <pre><code>&lt;div class="field"&gt; &lt;td&gt;&lt;%= f.label "#{column_name}" %&gt;&lt;/td&gt; &lt;td&gt;&lt;%= f.collection_select "#{column_name}", Table.all, :id, :message_id %&gt;&lt;/td&gt; &lt;/div&gt; </code></pre> <p>"Table" has a column "message_id" which is a foreign_key to a different table "Messages".</p> <p>The "Messages" table contains all the text/strings in my application.</p> <p>When I load this code on my page it will give me a drop down list of all records but it will only show foreign key ID numbers pointing to the "Messages" table.</p> <p>How can I change the foreign key ID numbers in the drop down to switch with message content I have on my Messages table?</p>24628332602	0	 <p>The code you've shared seems very close. See below to output the first child <code>&lt;tr&gt;</code> of the table, if an <code>&lt;a&gt;</code> element is found, then stop looping through additional <code>&lt;a&gt;</code> elements. What specific problems are you having with your code?</p> <pre><code>foreach ($html-&gt;find('table') as $name) { foreach ($name-&gt;find('a') as $elem) { echo $name-&gt;find('tr', 0)-&gt;plaintext; // echo first TR element echo $elem-&gt;plaintext.'&lt;br&gt;'; // echo A element break 1; // skip to the next table } } </code></pre>2471383277	0	Using preprocessor directives in BlackBerry JDE plugin for eclipse? <p>How to use preprocessor directives in BlackBerry JDE plugin for eclipse? </p>24829945137	0	Should I add the sass source map to my git repo? <p>I had added <code>style.css.map</code> to my <code>.gitignore</code> file thinking that this was some kind of internal file that was not needed for public consumption.</p> <p>Now I'm seeing that when Chrome (not Firefox) loads my page, it is looking for <code>style.css.map</code> and returning a 404. I'm not explicitly asking it to load that file, but it seems to be getting called automatically. </p> <ol> <li>Why is Chrome looking for that file?</li> <li>Should I have included the .map file to the repo?</li> </ol> <p>For further context, this is a Wordpress site and I <em>am</em> including the <code>style.scss</code> file in the repo.</p>24941069932	0	 <p>I had a similar request from a client. but instead of an "x" to close the pop up it was to make it fade after x number of seconds.</p> <p>see the see this link: <a href="http://ausauraair.com.au/product/ausaura-air/" rel="nofollow noreferrer">http://ausauraair.com.au/product/ausaura-air/</a></p> <p>by adding some jQuery i was able to make the box fade.</p> <pre><code>jQuery(document).ready(function( $ ) { $('.woocommerce-message').fadeTo(7000,1).fadeOut(2000); }); </code></pre> <p>you could possibly use a similar technique but add a "x" button and then an on-click function to make the box close on click.</p>2505077413	0	 <p>Try this:</p> <pre><code>DateTime dt = DateTime.ParseExact(strDate, "MMM dd, yyyy", CultureInfo.InvariantCulture); </code></pre>2515873725	0	 25212103872	0	 <p>The slaveOk property is now known as ReadPreference (.SECONDARY in this case) in newer Mongo Java driver versions. This can be set at the Mongo/DB/Collection level. Note that when you set ReadPreference at these levels, it applies for all callers (i.e. these objects are shared across threads).</p> <p>Another approach is to try the ReadPreference.SECONDARY and if it fails, try without it and go to the master. This logic can be isolated to your repository layer, so the service layer doesn't have to deal with it. If you are doing this, you may want to set the ReadPreference at the DBQuery object, which is on a per-use basis.</p>25338287434	0	 <p>If you run</p> <pre><code>getAnywhere("complete") </code></pre> <p>where is the package providing that function located? Is that package loaded in your <code>.Rmd</code> file?</p>254183197	0	 <p>Just like Perl,</p> <pre><code>loop1: for (var i in set1) { loop2: for (var j in set2) { loop3: for (var k in set3) { break loop2; // breaks out of loop3 and loop2 } } } </code></pre> <p>as defined in EMCA-262 section 12.12. <a href="https://developer.mozilla.org/en/JavaScript/Reference/Statements/label" rel="nofollow noreferrer">[MDN Docs]</a></p> <p>Unlike C, these labels can only be used for <a href="https://developer.mozilla.org/en/JavaScript/Reference/Statements/continue" rel="nofollow noreferrer"><code>continue</code></a> and <a href="https://developer.mozilla.org/en/JavaScript/Reference/Statements/break" rel="nofollow noreferrer"><code>break</code></a>, as Javascript does not have <code>goto</code> (without hacks like <a href="http://www.summerofgoto.com/" rel="nofollow noreferrer">this</a>).</p>25536170192	0	 <p>You can find the extra braces by making use of stack as below:</p> <pre><code>public static void main(final String[] args) { Stack&lt;String&gt; stack = new Stack&lt;String&gt;(); File file = new File("InputFile"); int lineCount = 0; try (BufferedReader br = new BufferedReader(new FileReader(file))) { String line; while ((line = br.readLine()) != null) { lineCount++; for (int i = 0; i &lt; line.length(); i++) { if (line.charAt(i) == '{') { stack.push("{"); } else if (line.charAt(i) == '}') { if (!stack.isEmpty()) { stack.pop(); } else { System.out.println("Extra brace found at line number : " + lineCount); } } } } if (!stack.isEmpty()) { System.out.println(stack.size() + " braces are opend but not closed "); } } catch (Exception e) { e.printStackTrace(); } } </code></pre>25638113933	0	 <p>Plivo Sales Engineer here.</p> <p>Pavan is correct. You need to specify the <code>Content-Type</code> header as <code>application/json</code> for Parse to make a JSON string of the body: </p> <pre><code> headers: { "Content-Type": "application/json" }, </code></pre> <p>You also should <code>console.log(httpResponse)</code> (aka the Plivo API response) which will tell if you are doing something wrong (sending the wrong data, not authenticating correctly) or if you do something right. Either way it will show you an <code>api_id</code> which you can use to look in your <a href="https://manage.plivo.com/logs/debug/" rel="nofollow">Plivo account dashboard debug logs</a> and figure out what need to be changed. You can also go directly to the debug logs for a specific <code>api_id</code> by making a url like this: <code>https://manage.plivo.com/logs/debug/api/e58b26e5-3db5-11e6-a069-22000afa135b/</code> and replacing <code>e58b26e5-3db5-11e6-a069-22000afa135b</code> with the <code>api_id</code> returned by your <code>Parse.Cloud.httpRequest</code></p>2574187709	0	 <p>I've been using <code>&lt;div&gt;&lt;jsp:text/&gt;&lt;/div&gt;</code></p>25811981535	0	 <p>It is very simple</p> <p>Let me make you understand</p> <p>first</p> <pre><code>public MyClass() { } </code></pre> <p>is simply a default public constructor</p> <p>But when you write this</p> <pre><code>public MyClass() { this(); } </code></pre> <p>that means you are applying constructor chaining. Constructor Chaining is simply calling another constructor of the same class. This must be the first statement of the Constructor. But in your scenario you are passing nothing in <code>this();</code> that means you are again calling the same constructor which will result in infinite loop. your class may have another constructor like this</p> <pre><code>public MyClass(int a) { } </code></pre> <p>then you may have called this</p> <pre><code>public MyClass(){ this(10); } </code></pre> <p>the above statement will make you to jump to the constructor receiving the same arguments that you have passed</p> <p>Now,</p> <pre><code>public Myclass(){ super(); } </code></pre> <p>signifies that you are calling the constructor of the super class which is inherited by the class <code>MyClass</code>. the same scenario occurs here, you have passed nothing in the <code>super();</code> which will call the default constructor of the Super class.</p>25938354587	0	IONIC2: Content Appearing Pushed To The Right <p>I am having a problem on my Ionic2 application when deployed to an <code>android 4.2.2</code> device, all the content appears heavily padded to the right as shown in the image attachment.</p> <p><a href="https://i.stack.imgur.com/1aXYJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1aXYJ.png" alt="enter image description here"></a></p> <p>Your help will be greatly appreciated.</p>2603614420	0	I need an easy way to extract data from a few thousand emails (apple mail) <p>I have about 2000 emails from a web contest my company did. All the emails are arranged in the following fashion:</p> <pre><code>You have received a new contest submission. Here are the details: Name: Bob Jones Email: bobjones@internet.com Location: Springfield, MA Age: 83 Mailinglist: true </code></pre> <p>All of these emails are saved in apple mail, is there any way I can extract this data into a text file, excel sheet, or something else more useable?</p>2616153541	0	 <p>I found the problem/solution!</p> <p>The problem is that in my Controller_Website I had this in my <code>action_before()</code>:</p> <pre><code>// Create a new DM_Nav object to hold our page info // Make this page info available to all views as well $this-&gt;page_info = new DM_Nav; View::bind_global('page_info', $this-&gt;page_info); </code></pre> <p>The problem is the <code>bind_global</code> – which is actually <em>working as it's supposed to</em> by letting you change the value of this variable after the fact... <em>(A very neat feature indeed.)</em></p> <p>The workaround/solution was to force the template to use only the original <code>page_info</code> by detecting if it was an initial/main request. So at the very end of the <code>action_before()</code> method of <code>Controller_Website</code> where it says:</p> <pre><code>// Only if auto_render is still TRUE (Default) if ($this-&gt;auto_render === TRUE AND $this-&gt;request-&gt;is_initial()) { </code></pre> <p>I added this line to the end of that <code>if</code> statement:</p> <pre><code> $this-&gt;template-&gt;page_info = $this-&gt;page_info; } </code></pre> <p>This line is redundant on initial/main requests, but it means that any additional sub-requests can still have access to their own <code>page_info</code> values without affecting the values used in the template. It appears, then, that if you assign a property to a view and then attempt to <code>bind_global()</code> the same property with new values, it doesn't overwrite it and uses the original values instead... <em>(Which is why this solution works.)</em> Interesting.</p>26240495193	0	Passing Datomic console options via file <p>Someone noticed that on one of our Datomic transactor boxes, our process running the Datomic console is exposing database credentials. </p> <p>Here is what our we get back when running <code>ps aux | grep datomic</code> (linebreaks added for readability):</p> <pre><code>[ian@testtransactor ~]$ ps aux | grep datomic datomic 18372 0.8 55.7 6898068 4495820 ? Sl Nov01 31:20 java -server -cp lib/*:datomic-transactor-pro-0.9.5394.jar:samples/clj:bin:resources -Xmx4g -Xms4g -Ddatomic.printConnectionInfo=false -Doracle.net.tns_admin=/usr/lib/oracle/11.2/client64/network/admin -Dgraphite.host=graphite -Dgraphite.port=2003 -Dgraphite.prefix=datomic.testransactor clojure.main --main datomic.launcher /opt/datomic-pro-0.9.5394/config/transactor.properties root 18821 0.2 10.2 3503992 826664 ? Sl May20 504:04 java -server -Xmx1g -Doracle.net.tns_admin=/usr/lib/oracle/11.2/client64/network/admin -cp lib/console/*:lib/*:datomic-transactor-pro-0.9.5327.jar:samples/clj:bin:resources clojure.main -i bin/bridge.clj --main datomic.console -p 3035 dev datomic:sql://?jdbc:oracle:thin:USERNAME/PASSWORD@DB_SID </code></pre> <p>Our security team would prefer that the password be passed to the console process via a properties file, like we do with the transactor. Unfortunately, just mirroring it with <code>clojure.main -i bin/bridge.clj --main datomic.console /opt/datomic-pro-0.9.5394/config/console.properties</code> doesn't work. Does anyone have suggestions on how to set this up?</p>26322144512	0	 <p>There are some different matters in your question. First of all:</p> <p>1: I don't really understand what you do in your query, but the limit clause must be at the end of a query, so you could try </p> <pre><code>select * from A join B on A.id = B.id limit 10 </code></pre> <p>And this should work. More info on:</p> <p><a href="https://dev.mysql.com/doc/refman/5.0/en/select.html" rel="nofollow">https://dev.mysql.com/doc/refman/5.0/en/select.html</a></p> <p>2: Join vs. IN clause: the IN clause should always perform worse than the join. Imagine something like:</p> <pre><code>select * from A where A.id in (select id from B) </code></pre> <p>This will do a full scan on B table (<code>select id from B</code> subquery) and then another full scan on A to try match the results.</p> <p>However, </p> <pre><code>select * from A join B on A.id = B.id </code></pre> <p>should do a hash join between both tables, and if you have planned it right, id will be an index column, so it should be quite faster (and do no full scans on neither of them)</p>26413245470	1	Python: What is zip doing in this list comprehension <p>I am trying to understand this:</p> <pre><code>a = "hello" b = "world" [chr(ord(x) ^ ord(y)) for (x, y) in zip(a[:len(b)], b)] </code></pre> <p>I understand the <code>XOR</code> part but I don't get what zip is doing.</p>2653673509	0	 <p>Some CSS :</p> <pre class="lang-css prettyprint-override"><code>table td, table td * { vertical-align: top; } </code></pre>26626091260	0	 <p>you have to add pull-left to the h1 too.. to have both of them floated..</p> <p>also add a .cleafix class to the page-header div</p> <pre><code>&lt;div class="container"&gt; &lt;div class="page-header clearfix"&gt; &lt;h1 class="pull-left"&gt; &lt;img src="logo.png"&gt; Page title &lt;/h1&gt; &lt;div class="panel panel-primary pull-right"&gt; ...content... &lt;/div&gt; &lt;/div&gt; ... &lt;/div&gt; </code></pre>2672233408	0	 <p>The "redundant include guard", as you call it, speeds up compilation.</p> <p>Without the redundant guard, the compiler will iterate the entire foo.h file, looking for some code that might be outside the <code>#ifndef</code> block. If it's a long file, and this is done many places, the compiler might waste a lot of time. But with the redundant guard, it can skip the entire <code>#include</code> statement and not even reopen that file.</p> <p>Of course, you'd have to experiment and see the actual amount of time wasted by the compiler iterating through foo.h and not actually compiling anything; and perhaps modern compilers actually look for this pattern and automatically know not to bother opening the file at all, I don't know.</p> <p>(Begin edit by 280Z28)</p> <p>The following header structure is recognized by <em>at least</em> GCC and MSVC. Using this pattern negates virtually all benefits you could gain with guards in the including files. Note that comments are ignored when the compiler examines the structure.</p> <pre><code>// GCC will recognize this structure and not reopen the file #ifndef SOMEHEADER_H_INCLUDED #define SOMEHEADER_H_INCLUDED // Visual C++ uses #pragma once to mark headers that shouldn't be reopened #if defined(_MSC_VER) &amp;&amp; (_MSC_VER &gt;= 1020) # pragma once #endif // header text goes here. #endif </code></pre> <p>(End edit)</p>2685668801	0	Entity framework code-first null foreign key <p>I have a <code>User</code> &lt; <code>Country</code> model. A user belongs to a country, but may not belong to any (null foreign key).</p> <p>How do I set this up? When I try to insert a user with a null country, it tells me that it cannot be null.</p> <p>The model is as follows:</p> <pre><code> public class User{ public int CountryId { get; set; } public Country Country { get; set; } } public class Country{ public List&lt;User&gt; Users {get; set;} public int CountryId {get; set;} } </code></pre> <p>Error: <code>A foreign key value cannot be inserted because a corresponding primary key value does not exist. [ Foreign key constraint name = Country_Users ]"}</code></p>26933369903	0	 <p>What version of Opentaps are you running ? did you clone from the master git repository ? </p> <p>are you trying to compile the code in the ide? I suggest you run ./ant inside the project and don't use the ide to compile </p>2704619893	0	Form submission in rails 3 <p>I decided to start a little project in rails 3 and I am a little bit stuck on a form... Where can I specified the f.submit action should go to a special controller / action ?</p> <p>The code in the form is:</p> <pre><code>&lt;%= form_for @user, :url =&gt; { :action =&gt; "login" } do |f| %&gt; &lt;div class="field"&gt; &lt;%= f.text_field :email %&gt;&lt;br /&gt; &lt;%= f.text_field :password %&gt; &lt;/div&gt; &lt;div class="actions"&gt; &lt;%= f.submit %&gt; &lt;/div&gt; &lt;% end %&gt; </code></pre> <p>User is defined as @user = User.new in "index" method of "home_controller".</p> <p>but I have the error:</p> <pre><code>No route matches {:controller=&gt;"home", :action=&gt;"login"} </code></pre> <p>as soon as I run <a href="http://0.0.0.0:3000" rel="nofollow">http://0.0.0.0:3000</a></p> <p>I am very sorry for this newbee question but I cannot find the routing details (I worked a little bit with rails a couple of years ago but...)</p> <p>Thanks, Luc</p>27126211646	0	Include Bootstrap form css alone <p>I have site created already which is not bootstrap, and now i need to implement the bootstrapValidator for the validation purpose, if i include bootstrap css then my site style also changing,</p> <p>Is there any way to include bootstrap form styles alone in html, apart from cut copy in bootstrap css file? </p>27224274017	0	 <p>This is the solution, I didn't change anything in the original code and script:</p> <pre><code>&lt;div id="content"&gt; &lt;div id="tab1"&gt;@{ Html.RenderAction("TabbedIndex", "Stuff", new { claimed = false }); }&lt;/div&gt; &lt;div id="tab2"&gt;@{ Html.RenderAction("TabbedIndex", "Stuff", new { claimed = true }); }&lt;/div&gt; &lt;/div&gt; </code></pre>2735255938	0	 <p>as someone who spent time looking for such a solution for my company's product--I can tell you that you are not going to find one. It does not exist. Sorry, dude. :(</p>27438048090	0	 <p>It's a bug in <code>iex</code>. I've tracked down and fixed it: <a href="https://github.com/elixir-lang/elixir/pull/4895" rel="nofollow">https://github.com/elixir-lang/elixir/pull/4895</a></p>27534014365	0	Mybatis how to dynamic create table sql in xml <p>Before,I use </p> <pre><code>&lt;select id="queryUser" parameterType="userInfo"&gt; select * from uc_login_${tableSuffix} &lt;/select&gt; userInfo:{ private String tableSuffix; } </code></pre> <p>and I create userInfo with tableSuffix like </p> <pre><code>new DateTime().getYear() + "_" + new DateTime().getMonthOfYear(); </code></pre> <p>and now I select from uc_login_nowYear_nowMonth(uc_login_2015_12). Now,I don't want create tabkeSuffix by myself,I want Mybatis help me to dynamic create sql in xml. How can I do that?</p>2765092644	0	 <p>In the end I canned the joined DataTable idea and just read the data straight into a List of my objects with a DataReader. So this whole question is now pretty redundant for me. Hopefully someone else will find it useful.</p>27712711873	0	Excel VBA Dynamic Ranges/Index selections <p>I'm trying to create a talent calculator for myself, and the entire first sheet calls to a Data sheet that does all the background work. On the excel sheet itself, everything calls to INDEX(TableName,Row,Column) because it's much easy to keep track of and I find I often have to move data around while working on it so handling Names is easier than handling cell references.</p> <p>However, I also use VBA on this sheet, and I'm rather new to it. Instead of, for example, using Range("C1"), if C1 was part of table TableOne, would there be a way to reference it like in the Excel formulas such as INDEX(TableOne,1)?</p>27826522897	0	 <blockquote> <p>Usually using <code>lxml</code> and xpath is a common approach in Python. </p> </blockquote> <p>As you want to use <code>minidom</code> explicitly, you can use the following method to get all HTML elements of a particular tag.</p> <pre><code>matches = dom.getElementsByTagName("foo") for e in matches: print(e.firstChild.nodeValue) </code></pre>279840421	0	 <p>You can check if its a digit:</p> <pre><code>char c; scanf( "%c", &amp;c ); if( isdigit(c) ) printf( "You entered the digit %c\n", c ); </code></pre>28011020766	0	 <p>I really liked Phaxmohdem solution, so I added a bit more to it. I hope others continue to improve this. =)</p> <pre><code>&lt;NotepadPlus&gt; &lt;UserLang name="X12" ext=""&gt; &lt;Settings&gt; &lt;Global caseIgnored="no" /&gt; &lt;TreatAsSymbol comment="no" commentLine="no" /&gt; &lt;Prefix words1="no" words2="no" words3="no" words4="no" /&gt; &lt;/Settings&gt; &lt;KeywordLists&gt; &lt;Keywords name="Delimiters"&gt;000000&lt;/Keywords&gt; &lt;Keywords name="Folder+"&gt;&lt;/Keywords&gt; &lt;Keywords name="Folder-"&gt;&lt;/Keywords&gt; &lt;Keywords name="Operators"&gt;* : ^ ~ +&lt;/Keywords&gt; &lt;Keywords name="Comment"&gt;&lt;/Keywords&gt; &lt;Keywords name="Words1"&gt;ISA IEA GS GE ST SE&lt;/Keywords&gt; &lt;Keywords name="Words2"&gt;AAA ACT ADX AK1 AK2 AK3 AK4 AK5 AK6 AK7 AK8 AK9 AMT AT1 AT2 AT3 AT4 AT5 AT6 AT7 AT8 AT9 AT8 AT9 B2 B2A BEG BGN BHT BPR CAS CL1 CLM CLP CN1 COB CR1 CR2 CL3 CL4 CR5 CR6 CRC CTX CUR DMG DN1 DN2 DSB DTM DTP EB EC ENT EQ FRM G61 G62 HCP HCR HD HI HL HLH HSD ICM IDC III IK3 IK4 IK5 INS IT1 K1 K2 K3 L3 L11 LIN LQ LUI LX MEA MIA MOA MPI MSG N1 N2 N3 N4 NM1 NTE NX OI PAT PER PLA PLB PO1 PRV PS1 PWK QTY RDM REF RMR S5 SAC SBR SLN STC SV1 SV2 SV3 SV4 SV5 SVC SVD TA1 TOO TRN TS2 TS3 UM&lt;/Keywords&gt; &lt;Keywords name="Words3"&gt;LS LE&lt;/Keywords&gt; &lt;Keywords name="Words4"&gt;00 000 0007 001 0010 0019 002 0022 003 004 00401 004010 004010X061 004010X061A1 004010X091 004010X091A1 004010X092 004010X092A1 004010X093 004010X093A1 004010X094 004010X094A1 004010X095 004010X095A1 004010X096 004010X096A1 004010X098 004010X098A1 005 00501 005010 005010X212 005010X217 005010X218 005010X220 005010X220A1 005010X221 005010X221A1 005010X222 005010X222A1 005010X223 005010X223A1 005010X223A2 005010X224 005010X224A1 005010X224A2 005010X230 005010X231 005010X279 005010X279A1 006 007 0078 008 009 01 010 011 012 013 014 015 016 017 018 019 02 020 021 022 023 024 025 026 027 028 029 03 030 031 032 035 036 04 05 050 06 07 08 09 090 091 096 097 0B 0F 0K 102 119 139 150 151 152 18 193 194 196 198 1A 1B 1C 1D 1E 1G 1H 1I 1J 1K 1L 1O 1P 1Q 1R 1S 1T 1U 1V 1W 1X 1Y 1Z 200 232 233 270 271 276 277 278 286 290 291 292 295 296 297 2A 2B 2C 2D 2E 2F 2I 2J 2K 2L 2P 2Q 2S 2U 2Z 30 300 301 303 304 307 31 314 318 330 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 356 357 36 360 361 374 382 383 385 386 388 393 394 3A 3C 3D 3E 3F 3G 3H 3I 3J 3K 3L 3M 3N 3O 3P 3Q 3R 3S 3T 3U 3V 3W 3X 3Y 3Z 40 405 41 417 431 434 435 438 439 441 442 444 446 45 452 453 454 455 456 458 46 461 463 471 472 473 474 480 481 484 492 4A 4B 4C 4D 4E 4F 4G 4H 4I 4J 4K 4L 4M 4N 4O 4P 4Q 4R 4S 4U 4V 4W 4X 4Y 4Z 539 540 543 573 580 581 582 598 5A 5B 5C 5D 5E 5F 5G 5H 5I 5J 5K 5L 5M 5N 5O 5P 5Q 5R 5S 5T 5U 5V 5W 5X 5Y 5Z 607 636 695 6A 6B 6C 6D 6E 6F 6G 6H 6I 6J 6K 6L 6M 6N 6O 6P 6Q 6R 6S 6U 6V 6W 6X 6Y 70 71 72 738 739 74 77 771 7C 82 820 831 834 835 837 85 850 866 87 8H 8U 8W 938 997 999 9A 9B 9C 9D 9E 9F 9H 9J 9K 9V 9X A0 A1 A172 A2 A3 A4 A5 A6 A7 A8 A9 AA AAE AAG AAH AAJ AB ABB ABC ABF ABJ ABK ABN AC ACH AD ADD ADM AE AF AG AH AI AJ AK AL ALC ALG ALS AM AN AO AP APC APR AQ AR AS AT AU AV AX AY AZ B1 B2 B3 B4 B6 B680 B7 B9 BA BB BBQ BBR BC BD BE BF BG BH BI BJ BK BL BLT BM BN BO BOP BP BPD BQ BR BS BT BTD BU BV BW BX BY BZ C1 C2 C3 C4 C5 C6 C7 C8 C9 CA CAD CB CC CCP CD CE CER CF CG CH CHD CHK CI CJ CK CL CLI CLM01 CM CN CNJ CO CON CP CQ CR CS CT CV CW CX CY CZ D2 D3 D8 D9 D940 DA DB DCP DD DEN DEP DG DGN DH DI DJ DK DM DME DN DO DP DQ DR DS DT DX DY E1 E1D E2 E2D E3 E3D E5D E6D E7 E7D E8 E8D E9 E9D EA EAF EBA ECH ED EI EJ EL EM EMP EN ENT01 EO EP EPO ER ES ESP ET EV EW EX EXS EY F1 F2 F3 F4 F5 F6 F8 FA FAC FAM FB FC FD FE FF FH FI FJ FK FL FM FO FS FT FWT FX FY G0 G1 G2 G3 G4 G5 G740 G8 G9 GB GD GF GH GI GJ GK GM GN GO GP GR GW GT GY H1 H6 HC HE HF HH HJ HLT HM HMO HN HO HP HPI HR HS HT I10 I11 I12 I13 I3 I4 I5 I6 I7 I8 I9 IA IAT IC ID IE IF IG IH II IJ IK IL IN IND IP IR IS IV J1 J3 J6 JD JP KG KH KW L1 L2 L3 L4 L5 L6 LA LB LC LD LI LM LOI LR LT LU LTC LTD M1 M2 M3 M4 M5 M6 M7 M8 MA MB MC MD ME MED MH MI MJ ML MM MN MO MOD MP MR MRC MS MSC MT N5 N6 N7 N8 NA ND NE NF NH NI NM109 NL NN NON NQ NR NS NT NTR NU OA OB OC OD ODT OE OF OG OL ON OP OR OT OU OX OZ P0 P1 P2 P3 P4 P5 P6 P7 PA PB PC PD PDG PE PI PID PL PN PO POS PP PPO PQ PR PRA PRP PS PT PU PV PW PXC PY PZ Q4 QA QB QC QD QE QH QK QL QM QN QO QQ QR QS QV QY R1 R2 R3 R4 RA RB RC RD8 RE REC RET RF RGA RHB RLH RM RN RNH RP RR RT RU RW RX S1 S2 S3 S4 S5 S6 S7 S8 S9 SA SB SC SD SEP SET SFM SG SJ SK SL SP SPC SPO SPT SS STD SU SV SWT SX SY SZ T1 T10 T11 T12 T2 T3 T4 T5 T6 T7 T8 T9 TC TD TE TF TJ TL TM TN TNJ TO TPO TQ TR TRN02 TS TT TTP TU TV TWO TZ UC UH UI UK UN UP UPI UR UT V1 V5 VA VER VIS VN VO VS VV VY W1 WA WC WK WO WP WR WU WW X12 X3 X4 X5 X9 XM XN XP XT XV XX XX1 XX2 XZ Y2 Y4 YR YT YY Z6 ZB ZH ZK ZL ZM ZN ZO ZV ZX ZZ&lt;/Keywords&gt; &lt;/KeywordLists&gt; &lt;Styles&gt; &lt;WordsStyle name="DEFAULT" styleID="11" fgColor="000000" bgColor="FFFFFF" fontName="" fontStyle="0" /&gt; &lt;WordsStyle name="FOLDEROPEN" styleID="12" fgColor="000000" bgColor="FFFFFF" fontName="" fontStyle="0" /&gt; &lt;WordsStyle name="FOLDERCLOSE" styleID="13" fgColor="000000" bgColor="FFFFFF" fontName="" fontStyle="0" /&gt; &lt;WordsStyle name="KEYWORD1" styleID="5" fgColor="0000FF" bgColor="FFFFFF" fontName="" fontStyle="1" /&gt; &lt;WordsStyle name="KEYWORD2" styleID="6" fgColor="800000" bgColor="FFFFFF" fontName="" fontStyle="1" /&gt; &lt;WordsStyle name="KEYWORD3" styleID="7" fgColor="00FF00" bgColor="FFFFFF" fontName="" fontStyle="1" /&gt; &lt;WordsStyle name="KEYWORD4" styleID="8" fgColor="8000FF" bgColor="FFFFFF" fontName="" fontStyle="0" /&gt; &lt;WordsStyle name="COMMENT" styleID="1" fgColor="000000" bgColor="FFFFFF" fontName="" fontStyle="0" /&gt; &lt;WordsStyle name="COMMENT LINE" styleID="2" fgColor="000000" bgColor="FFFFFF" fontName="" fontStyle="0" /&gt; &lt;WordsStyle name="NUMBER" styleID="4" fgColor="000000" bgColor="FFFFFF" fontName="" fontStyle="0" /&gt; &lt;WordsStyle name="OPERATOR" styleID="10" fgColor="FF00FF" bgColor="FFFFFF" fontName="" fontStyle="0" /&gt; &lt;WordsStyle name="DELIMINER1" styleID="14" fgColor="000000" bgColor="FFFFFF" fontName="" fontStyle="0" /&gt; &lt;WordsStyle name="DELIMINER2" styleID="15" fgColor="000000" bgColor="FFFFFF" fontName="" fontStyle="0" /&gt; &lt;WordsStyle name="DELIMINER3" styleID="16" fgColor="000000" bgColor="FFFFFF" fontName="" fontStyle="0" /&gt; &lt;/Styles&gt; &lt;/UserLang&gt; &lt;/NotepadPlus&gt; </code></pre>281971828	0	 <p>There is also garbage collection to consider - if you are using new() a lot, then that will create lots of objects on the heap that will have to be garbage collected, but Clear() won't create any new heap objects (although this is only really an issue if you're doing this thousands of times)</p>28213026080	0	 <p>If you want to <strong>AUTOMATICALLY</strong> redirect from <code>www.google.com</code> to <code>www.google.com#something</code> you can use firefox's redirector addon.<br/> Whenever you load www.google.com, the addon will automatically change the URL in the location bar to www.google.com#something (or whatever you specify.) <br/><br/> Alternately, you could use firefox addon, called greasemonkey, to write the 1 line script given by Jacob. That will also serve the purpose.</p> <p>Off course, both these solutions are specific to firefox.</p>28331940324	0	vb.net to pull data from Excel Data GridView <p>I have <strong>78</strong> excel columns and I have <strong>5</strong> datagridviews.</p> <p>How do I make connection?</p>28418114495	0	Imagemagick position and size of a sub-image <h3>Problem description:</h3> <p>In imagemagick, it is very easy to diff two images using compare, which produces an image with the same size as the two images being diff'd, with the diff data. <strong>I would like to use the diff data and crop that part from the original image, while maintaining the image size by filling the rest of the space with alpha</strong>.</p> <h3>The approach I am taking:</h3> <p>I am now trying to figure the bounding box of the diff, without luck. For example, below is the script I am using to produce the diff image, see below. Now, I need to find the bounding box of the red color part of the image. The bounding box is demonstrated below, too. Note that the numbers in the image are arbitrary and not the actual values I am seeking.</p> <pre><code>compare -density 300 -metric AE -fuzz 10% ${image} ${otherImage} -compose src ${OUTPUT_DIR}/diff${i}-${j}.png </code></pre> <p><img src="https://i.stack.imgur.com/edPdf.png" alt="enter image description here"> <img src="https://i.stack.imgur.com/AZkdz.png" alt="enter image description here"></p>28537239427	0	Delete Method's return value in Excel VBA <p>According to Microsoft Developer Network, both <code>Range.Delete</code> and <code>Worksheet.Delete</code> method will return a value. However, by using the <code>MsgBox</code> function I can only view the return value for the <code>Worksheet.Delete</code> method but have no luck with the <code>Range.Delete</code> method. The code I used is <code>MsgBox Worksheets("Sheet1").Delete</code></p> <p>Here are the two articles from MSDN for your information: <a href="https://msdn.microsoft.com/en-us/library/office/ff837404.aspx" rel="nofollow">https://msdn.microsoft.com/en-us/library/office/ff837404.aspx</a> <a href="https://msdn.microsoft.com/en-us/library/office/ff834641.aspx" rel="nofollow">https://msdn.microsoft.com/en-us/library/office/ff834641.aspx</a></p>2869514715	0	 <p>It might be possible, try setting the window background color to clear, as well as the view controller's view background color.</p> <p>I say it might be possible because I've seen my home screen while using some apps, for example, the Facebook app sometimes shows it during a transition (it might be a bug on either Facebook or the OS).</p> <p>Anyway, I'm pretty sure that kind of app would be rejected from the App Store, so be advised.</p>28721366036	0	Correctly serializing objects in java <p>can anyone help me to spot the mistake? I am trying to pass certain information (min/max/avg ages) from file people.txt (which consists of 200 lines like 'Christel ; MacKay ; 4"2' ; 38'), to another file, by serializing. Here's the first class, where I process some info about these people:</p> <pre><code>import java.io.Serializable; @SuppressWarnings("serial") public class Person implements Serializable { private String firstname; private String lastname; private int age; public Person (String PersonFN, String PersonLN, int PersonA) { firstname = PersonFN; lastname = PersonLN; age = PersonA; } public String toString() { return "Name: "+firstname+" "+lastname+" Age: "+age; } public int getAge() { return age; } } </code></pre> <p>And another one, which does all the job:</p> <pre><code>import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.*; public class Collection { int min; int max; int total; private static ArrayList&lt;Person&gt; people; public Collection() { people = new ArrayList&lt;Person&gt;(); min = 100; max = 1; total = 0; } BufferedReader fr = null; BufferedWriter fw = null; public void readFromFile() throws IOException { fr = new BufferedReader (new FileReader("people.txt")); String line = null; StringTokenizer st; while (fr.ready()) { line = fr.readLine(); st = new StringTokenizer(line); String name = st.nextToken(";"); String surname = st.nextToken(";").toUpperCase(); String height = st.nextToken(";"); int age = Integer.parseInt(st.nextToken(";").trim()); Person p = new Person (name, surname, age); p.toString(); people.add(p); //for the 2nd part if(age &lt; min) min = age; if (age &gt; max) max = age; total = total + age; } } public int minAge() { int minA = 100; for (int i = 0; i &lt; people.size(); i++) { Person p = people.get(i); int age = p.getAge(); if (age &lt; minA) { minA = age; } } System.out.print(minA+"; "); return minA; } public int maxAge() { int maxA = 1; for (int i = 0; i &lt; people.size(); i++) { Person p = people.get(i); int age = p.getAge(); if (age &gt; maxA) { maxA = age; } } System.out.print(maxA+"; "); return maxA; } public float avgAge() { int sum = 0; for (int i = 0; i &lt; people.size(); i++) { Person p = people.get(i); int age = p.getAge(); sum = sum + age; } float avgA = sum / people.size(); System.out.print(avgA); return avgA; } public int fastMinAge() { //System.out.print("Minimum age: " + min); return min; } public int fastMaxAge() { return max; } public float fastAvgAge() { return total / people.size(); } public void writeToFile(String filename) throws IOException { StringBuffer val = new StringBuffer ("Minimum age: "); val.append(fastMinAge()); val.append("\n Maximum age: "); val.append(fastMaxAge()); val.append("\n Average age: "); val.append(fastAvgAge()); BufferedWriter out = new BufferedWriter(new FileWriter(filename)); String outText = val.toString(); out.write(outText); out.close(); } public static void main(String[] args) throws IOException, ClassNotFoundException { Collection c = new Collection(); c.readFromFile(); for(Person d: people) { System.out.println(d); } c.minAge(); c.maxAge(); c.avgAge(); c.fastMinAge(); c.fastMaxAge(); c.fastAvgAge(); c.writeToFile("RESULTS.txt"); String filename = "people.txt"; //FileOutputStream fos = new FileOutputStream(filename); ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(filename)); os.writeObject(c); os.close(); String filename1 = "results1.txt"; FileInputStream fis = new FileInputStream(filename1); ObjectInputStream ois = new ObjectInputStream(fis); Collection p = (Collection) ois.readObject(); ois.close(); } } </code></pre> <p>When I run the code, it creates the RESULTS.txt file and adds the correct information there. I'm sure there's something wrong with this exact part of code:</p> <pre><code> String filename = "people.txt"; //FileOutputStream fos = new FileOutputStream(filename); ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(filename)); os.writeObject(c); os.close(); String filename1 = "results1.txt"; FileInputStream fis = new FileInputStream(filename1); ObjectInputStream ois = new ObjectInputStream(fis); Collection p = (Collection) ois.readObject(); ois.close(); </code></pre> <p>By the way, my people.txt file changes into "¬ķ {sr java.io.NotSerializableException(Vx ē†5 xr java.io.ObjectStreamExceptiondĆäk¨9ūß xr java.io.IOExceptionl€sde%š« xr java.lang.ExceptionŠż>;Ä xr java.lang.ThrowableÕĘ5'9wøĖ L causet Ljava/lang/Throwable;L detailMessaget Ljava/lang/String;[ stackTracet [Ljava/lang/StackTraceElement;L suppressedExceptionst Ljava/util/List;xpq ~ t SD3lab1.Collectionur [Ljava.lang.StackTraceElement;F*&lt;&lt;ż"9 xp sr java.lang.StackTraceElementa Å&amp;6Ż… I lineNumberL declaringClassq ~ L fileNameq ~ L methodNameq ~ xp˙˙˙˙t java.io.ObjectOutputStreampt writeObject0sq ~ ˙˙˙˙q ~ pt writeObjectsq ~ ©q ~ t Collection.javat mainsr &amp;java.util.Collections$UnmodifiableListü%1µģˇ L listq ~ xr ,java.util.Collections$UnmodifiableCollectionB €Ė^÷ L ct Ljava/util/Collection;xpsr java.util.ArrayListxŅ™Ēa¯ I sizexp w xq ~ x", and I get these errors on the console:</p> <pre><code>Exception in thread "main" java.io.NotSerializableException: SD3lab1.Collection at java.io.ObjectOutputStream.writeObject0(Unknown Source) at java.io.ObjectOutputStream.writeObject(Unknown Source) at SD3lab1.Collection.main(Collection.java:169) </code></pre> <p>MANY THANKS FOR ANY HELP</p>2885724765	0	 <p>You can check for the license for the first time, then cache it. The next time when your app runs, read the license from the cache, and also start a Thread that gets the license from your server. If the license that you got from the server is now invalid. You can pop up a dialog box to tell the user that the license is invalid, remove the cached license, and quit the app.</p>28938156646	0	Using @RequestParam for multipartfile is a right way? <p>I'm developing a spring mvc application and I want to handle multipart request in my controller. In the request I'm passing <code>MultiPartFile</code> also, currently I'm using <code>@RequestParam</code> to get the file paramaeter, the method look like,</p> <pre><code>@RequestMapping(method = RequestMethod.POST) public def save( @ModelAttribute @Valid Product product, @RequestParam(value = "image", required = false) MultipartFile file) { ..... } </code></pre> <p>Above code works well in my service and the file is getting on the server side. Now somewhere I seen that in case of file need to use <code>@RequestPart</code> annotation instead of <code>@RequestParam</code>. Is there anything wrong to use <code>@RequestParam</code> for file ? Or it may cause any kind of error in future?</p>2904225379	0	 <p>You can do like this (note that I have moved some of your generic parameters and constraints around).</p> <pre><code>public class MyType { public void doStuff(int i){} } public abstract class ABase&lt;T&gt;where T : class, new() { public abstract T method(int arg); } public class AChild : ABase&lt;MyType&gt; { override public MyType method(int arg) { MyType e = new MyType(); e.doStuff(arg); // no more error here return e; } } </code></pre>2912579588	0	Incorrect emacs indentation in a C++ class with DLL export specification <p>I often write classes with a DLL export/import specification, but this seems to confuse emacs' syntax parser. I end up with something like:</p> <pre><code>class myDllSpec Foo { public: Foo( void ); }; </code></pre> <p>Notice that the "public:" access spec is indented incorrectly, as well as everything that follows it.</p> <p>When I ask emacs to describe the syntax at the beginning of the line containing public, I get a return of:</p> <pre><code>((label 352)) </code></pre> <p>If I remove the myDllSpec, the indentation is correct, and emacs tells me that the syntax there is:</p> <pre><code>((inclass 352) (access-label 352)) </code></pre> <p>Which seems correct and reasonable. So I conclude that the syntax parser is not able to handle the DLL export spec, and that this is what's causing my indentation trouble.</p> <p>Unfortunately, I don't know how to teach the parser about my labels. Seems that this is pretty common practice, so I'm hoping there's a way around it.</p>29223893046	0	How to add timestamp to the existing mysql table <p>I am updatng my application from standard php into laravel and i am creating two new field in each of my table which is created_at and updated_at.</p> <p>The problem is both field has being set as null for the existing data. How to make a query to set the created_at and updated_at to the current date time??</p>29332405642	0	 <p>I need to see the full query, but at a guess it is going to be:</p> <pre><code>LEFT JOIN adcfvc ON adcfvc.advert_id = $table.id </code></pre> <p>Where $table is the tablename of the first table.</p>29434273628	0	 <p>You have to tell the server that your body is in a JSON format by adding the right request header:</p> <pre><code>... request.HTTPBody = [newNewString dataUsingEncoding:NSUTF8StringEncoding]; request.HTTPMethod = @"POST"; [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; ... </code></pre>2955625589	0	Javac erroring out when compiling Servlet libraries <p>I am using ubuntu and I have set my paths to be the following:</p> <pre><code>JAVA_HOME=/usr/local/jdk1.6.0_24 export CLASSPATH=/usr/local/tomcat/lib export JAVA_HOME </code></pre> <p>I thought that would put the servlet libraries in the compile path, but I am still getting compile errors like this:</p> <pre><code>package javax.servlet does not exist [javac] import javax.servlet.ServletException; </code></pre> <p>Any ideas how to fix this or what I am doing wrong? The general Java libraries seem to be working fine.</p>2966356792	0	 <p>I thought I'd answer this one since it has a few votes, although based on Christina's other questions I don't think this will be a usable answer for her since a 50,000-word language model almost certainly won't have an acceptable word error rate or recognition speed (or most likely even function for long) with in-app recognition systems for iOS that use this format of language model currently, due to hardware constraints. I figured it was worth documenting it because I think it may be helpful to others who are using a platform where keeping a vocabulary this size in memory is more of a viable thing, and maybe it will be a possibility for future device models as well.</p> <p>There is no web-based tool I'm aware of like the Sphinx Knowledge Base Tool that will munge a 50,000-word plaintext corpus and return an ARPA language model. But, you can obtain an already-complete 64,000-word DMP language model (which can be used with Sphinx at the command line or in other platform implementations in the same way as an ARPA .lm file) with the following steps:</p> <ol> <li>Download this language model from the CMU speech site:</li> </ol> <p><a href="http://sourceforge.net/projects/cmusphinx/files/Acoustic%20and%20Language%20Models/US%20English%20HUB4%20Language%20Model/HUB4_trigram_lm.zip">http://sourceforge.net/projects/cmusphinx/files/Acoustic%20and%20Language%20Models/US%20English%20HUB4%20Language%20Model/HUB4_trigram_lm.zip</a></p> <p>In that folder is a file called language_model.arpaformat.DMP which will be your language model.</p> <ol> <li>Download this file from the CMU speech site, which will become your pronunciation dictionary:</li> </ol> <p><a href="https://cmusphinx.svn.sourceforge.net/svnroot/cmusphinx/trunk/pocketsphinx/model/lm/en_US/cmu07a.dic">https://cmusphinx.svn.sourceforge.net/svnroot/cmusphinx/trunk/pocketsphinx/model/lm/en_US/cmu07a.dic</a></p> <p>Convert the contents of cmu07a.dic to all uppercase letters. </p> <p>If you want, you could also trim down the pronunciation dictionary by removing any words from it which aren't found in the corpus language_model.vocabulary (this would be a regex problem). These files are intended for use with one of the Sphinx English-language acoustic models.</p> <p>If the desire to use a 50,000-word English language model is driven by the idea of doing some kind of generalized large vocabulary speech recognition and not by the need to use a very specific 50,000 words (for instance, something specialized like a medical dictionary or 50,000-entry contact list), this approach should give those results if the hardware can handle it. There are probably going to be some Sphinx or Pocketsphinx settings that will need to be changed which will optimize searches through this size of model.</p>29734835581	0	Buy Google search result data? <p>Wanted to use GoogleAPI to search the Internet and return the results in JSON.<br> Google API allows this to search within a specific website, but I could not find this to the entire web. Is this possible? Thanks</p>29832230557	0	Create new row based on column value SQL Server <p>I have data like this</p> <pre><code>DECLARE @Employee TABLE (EmployeeName NVARCHAR(50), EmployeeAddress NVARCHAR(50), WorkedLocations NVARCHAR(50), IdNumbers NVARCHAR(50), UpdatedOn Date ) Insert into @Employee Values ('Alex',' Alex address','Cisco','12345',GETDATE()), ('John','John Address','Microsoft','23456',GETDATE()), ('Bob','Bob Address','CiscoMicrosoft','78903,89067',GETDATE()), ('Bill','Bill Address','Microsoft','54652',GETDATE()) select * from @Employee </code></pre> <p>In 3rd row based on the 3rd column value a row has to be created and 4th row value should be split and assigned to respective 3rd column. Please see below required output</p> <pre><code>DECLARE @Employee TABLE ( EmployeeName NVARCHAR(50) , EmployeeAddress NVARCHAR(50) , WorkedLocations NVARCHAR(50) , IdNumbers NVARCHAR(50) ,UpdatedOn Date) Insert into @Employee Values ('Alex',' Alex address','Cisco','12345',GETDATE()), ('John','John Address','Microsoft','23456',GETDATE()), ('Bob','Bob Address','Cisco','78903',GETDATE()), ('Bob','Bob Address','Microsoft','89067',GETDATE()), ('Bill','Bill Address','Microsoft','54652',GETDATE()) select * from @Employee </code></pre> <p>Thanks in advance!</p>29931613403	0	 <p>I was seing this same issue today, and I didn't have any code changes. Twitter just suddenly stopped authorizing and told me it couldn't get request token.</p> <p>I just had to restart my emulator and it started working again.</p>30035776087	0	 <p>You need to modify web.xml to use the special role ** as indicated here: <a href="http://www.eclipse.org/jetty/documentation/current/configuring-security-authentication.html#d0e5942" rel="nofollow">Authorization section for Jetty Authentication</a>:</p> <blockquote> <p>access granted to any user who is authenticated, regardless of roles. This is indicated by the special value of "**" for the &lt;role-name&gt; of a &lt;auth-constraint&gt; in the &lt;security-constraint&gt;</p> </blockquote> <p>So, this is what my security-constraint looks like:</p> <pre><code>&lt;security-constraint&gt; &lt;web-resource-collection&gt; &lt;web-resource-name&gt;Secured Solr Admin User Interface&lt;/web-resource-name&gt; &lt;url-pattern&gt;/*&lt;/url-pattern&gt; &lt;/web-resource-collection&gt; &lt;auth-constraint&gt; &lt;role-name&gt;**&lt;/role-name&gt; &lt;/auth-constraint&gt; &lt;/security-constraint&gt; </code></pre>30121756702	0	WCF service Endpoint X509 certificate Identity <p>I have service on one machine which I would like to access from another machine. So I need a help with setting the identity of the endpoints because i am getting </p> <pre><code>The identity check failed for the outgoing message. The expected identity is 'identity(http://schemas.xmlsoap.org/ws/2005/05/identity/right/possessproperty:http://schemas.xmlsoap.org/ws/2005/05/identity/claims/thumbprint)' (http://schemas.xmlsoap.org/ws/2005/05/identity/claims/thumbprint%29%27) for the 'net.tcp:...' target endpoint. </code></pre> <p>My service is configured to use certificate for transport security and validation mode is set to ChainTrust.</p> <p>What type of identity should I set on the client of this service since I am accessing the service using the ip address of the machine hosting it and not the dns name? More precisely what EndpointIdentity setting should I set to the EndpointAddress when I am setting the service host and what should I use on the client when I am setting the EndpointAddress?</p> <p>On both client and the service machine the issuer of the certificates used to secure the transport is in the trusted authorities.</p>30223987241	0	I'm trying to sort an NSMutableArray of objects by a field of type double <p>the code I'm currently trying doesn't give any errors but after it runs nothing is sorted. This is my first time in objective-c so I'm hoping there's something obvious here that I'm missing.</p> <pre><code>NSSortDescriptor * sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"distanceOfPlace" ascending:true] ; [surroundingRestaurants sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]]; </code></pre>30310165928	0	 <p>Yes, set the <code>proxy_max_temp_file_size</code> to zero, or some other reasonably small value. Another option (which might be a better choice) is to set the <code>proxy_temp_path</code> to faster storage so that nginx can do a slightly better job of insulating the application from buggy or malicious hosts. </p>30414460134	0	 <p>One way is to wait until the infinite loop shows up, then use <a href="http://docs.oracle.com/javase/7/docs/technotes/tools/share/jstack.html" rel="nofollow"><code>jstack -l &lt;pid&gt;</code></a> to get a stack dump, and analyze that.</p> <p>With a modicum of luck, this should suggest some lines of further inquiry.</p>30528945990	0	MVC 4: Create HTML textboxes dynamically with JQUERY and PartialViewResult. How to fill the model if the code is added dynamically? <p>I am creating form input fields with JQUERY like</p> <pre><code>$('#students').live('change', function () { var value = $(this).val(); if (value) { $.ajax({ type: "GET", timeout: 10000, url: "@Url.Action(MVC.Company.ManageWorkReport.GetStudent())", data: { studentId: value }, cache: false, success: function (data) { if (data) { $("#students tbody").html(data); } }, error: function (xhr, status, error) { alert(xhr.responseText); } }); } return false; }); </code></pre> <p>HTML code to insert data is</p> <pre><code>@using (Html.BeginDefaultForm(MVC.Company.ManageWorkReport.Create())) { &lt;table class="table table-striped table-bordered bootstrap-datatable datatable" id="students"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;Ime in Priimek&lt;/th&gt; &lt;th&gt;Vrsta&lt;/th&gt; &lt;th&gt;Začetek dela&lt;/th&gt; &lt;th&gt;Konec dela&lt;/th&gt; &lt;th&gt;Enota&lt;/th&gt; &lt;th&gt;Cena za enoto&lt;/th&gt; &lt;th&gt;Količina&lt;/th&gt; &lt;th&gt;Neto znesek&lt;/th&gt; &lt;th&gt;Bruto znesek&lt;/th&gt; &lt;th&gt;&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td colspan="11"&gt;Podatek še ne obstaja&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; @Html.SimpleSubmitAndCancelButton(Translations.Global.SAVE, Translations.Global.CANCEL) } </code></pre> <p>and C#</p> <pre><code>[HttpGet] public virtual PartialViewResult GetStudent(int studentId) { StudentsWorksReportsFormModel studentsWorksReportsFormModel = new StudentsWorksReportsFormModel(); ..... var view = PartialView("StudentWorkReportResult", studentsWorksReportsFormModel); return view; </code></pre> <p>}</p> <p>Problem is that when I enter data in form and click SUBMIT button model is always empty. Why model is empty if I fill page with JQUERY and later enter data in text fields? How to fill the model also that I can insert data in DB.</p>30620837913	0	 <p>The approach will not succeed, as you can search, but you cannot sort by a multivalued field. This pointed out in <a href="http://stackoverflow.com/questions/7845337/sorting-with-multivalued-field-in-solr">Sorting with Multivalued Field in Solr</a> and <a href="http://wiki.apache.org/solr/CommonQueryParameters#sort" rel="nofollow">written in Solr's Wiki</a></p> <blockquote> <p>Sorting can be done on the "score" of the document, or on any multiValued="false" indexed="true" field provided that field is either non-tokenized (ie: has no Analyzer) or uses an Analyzer that only produces a single Term (ie: uses the KeywordTokenizer)</p> </blockquote> <p><strong>Update</strong></p> <p>About the alternatives, as you point out that you need to find similar documents for one given ID, why not create a second core with a schema like</p> <pre class="lang-xml prettyprint-override"><code>&lt;fields&gt; &lt;field name="doc_id" type="int" indexed="true" stored="true" /&gt; &lt;field name="similar_to_id" type="int" indexed="true" stored="true" /&gt; &lt;field name="similarity" type="string" indexed="true" stored="true" /&gt; &lt;/fields&gt; &lt;types&gt; &lt;fieldType name="int" class="solr.TrieIntField"/&gt; &lt;fieldType name="string" class="solr.StrField" /&gt; &lt;/types&gt; </code></pre> <p>Then you could do a second query, after performing the actual search</p> <blockquote> <p>q=similar_to_id=42&amp;sort=similarity</p> </blockquote>30716130137	0	 <p>Notes :</p> <ol> <li>Query optimization and indexing the search traget tables</li> <li>datagrids are complex objects and get time in updating and filling its ordinary( spcially when have more column ) </li> <li>your System hardware (Ram , CPU ,VGA, ... ) that must be considered</li> <li><p>i think best approach is sort your query result and paging your result by Last code accessed and use this :</p> <p>void NextPage()<br> {<br> Qr="select Top N from tbl where Code>LastCode order by Code asc";<br> //reading data<br> FirstCode=Drr["Code"];//for first record result<br> LastCode=Drr["Code"];//for last record result<br> }<br> void PreviousPage()<br> {<br> Qr="select Top N from tbl where Code &lt; FirstCode order by Code asc"; </p> <p>//reading data </p> <p>FirstCode=Drr["Code"];//for first record result<br> LastCode=Drr["Code"];//for last record result<br> }</p></li> </ol> <p>Hope this Help</p>30823503635	0	 <p>This statement, for instance, </p> <pre><code>String studAnswers[][] = answerArray[rowIndex][1].replace(" ", "S"); </code></pre> <p>gives the compilation error</p> <pre><code>Type mismatch: cannot convert from String to String[][] </code></pre> <p>because</p> <p><code>answerArray[rowIndex][1].replace(" ", "S");</code> returns a <code>String</code>. </p> <ul> <li><code>answerArray</code> is a 2D <code>String</code> array.</li> <li><code>answerArray[rowIndex][1]</code> gets a element from the array which is a string </li> <li><code>answerArray[rowIndex][1].replace...</code> replaces a character in that<br> <code>String</code> with another character, ending up as another <code>String</code> (with the replaced character)</li> </ul> <p>You are trying to assign it to a <code>String</code> array.</p> <p>Also, you cannot use <code>equals</code> on primitives (<code>int</code>, <code>char</code>...). You need to use <code>==</code> for comparison.</p>3094982879	0	 <p>Here's another way. Of course this is just for int but the code could easily be altered for other datatypes.</p> <p><strong>AOMatrix.h:</strong></p> <pre><code>#import &lt;Cocoa/Cocoa.h&gt; @interface AOMatrix : NSObject { @private int* matrix_; uint columnCount_; uint rowCount_; } - (id)initWithRows:(uint)rowCount Columns:(uint)columnCount; - (uint)rowCount; - (uint)columnCount; - (int)valueAtRow:(uint)rowIndex Column:(uint)columnIndex; - (void)setValue:(int)value atRow:(uint)rowIndex Column:(uint)columnIndex; @end </code></pre> <p><strong>AOMatrix.m</strong></p> <pre><code>#import "AOMatrix.h" #define INITIAL_MATRIX_VALUE 0 #define DEFAULT_ROW_COUNT 4 #define DEFAULT_COLUMN_COUNT 4 /**************************************************************************** * BIG NOTE: * Access values in the matrix_ by matrix_[rowIndex*columnCount+columnIndex] ****************************************************************************/ @implementation AOMatrix - (id)init { return [self initWithRows:DEFAULT_ROW_COUNT Columns:DEFAULT_COLUMN_COUNT]; } - (id)initWithRows:(uint)initRowCount Columns:(uint)initColumnCount { self = [super init]; if(self) { rowCount_ = initRowCount; columnCount_ = initColumnCount; matrix_ = malloc(sizeof(int)*rowCount_*columnCount_); uint i; for(i = 0; i &lt; rowCount_*columnCount_; ++i) { matrix_[i] = INITIAL_MATRIX_VALUE; } // NSLog(@"matrix_ is %ux%u", rowCount_, columnCount_); // NSLog(@"matrix_[0] is at %p", &amp;(matrix_[0])); // NSLog(@"matrix_[%u] is at %p", i-1, &amp;(matrix_[i-1])); } return self; } - (void)dealloc { free(matrix_); [super dealloc]; } - (uint)rowCount { return rowCount_; } - (uint)columnCount { return columnCount_; } - (int)valueAtRow:(uint)rowIndex Column:(uint)columnIndex { // NSLog(@"matrix_[%u](%u,%u) is at %p with value %d", rowIndex*columnCount_+columnIndex, rowIndex, columnIndex, &amp;(matrix_[rowIndex*columnCount_+columnIndex]), matrix_[rowIndex*columnCount+columnIndex]); return matrix_[rowIndex*columnCount_+columnIndex]; } - (void)setValue:(int)value atRow:(uint)rowIndex Column:(uint)columnIndex { matrix_[rowIndex*columnCount_+columnIndex] = value; } @end </code></pre>31015692210	0	What's the difference between 301 and 302 in HTTP for Search engine <p>I read this <a href="http://serverfault.com/questions/110227/whats-the-difference-between-301-and-302-in-http">question</a> and know What's the difference between 301 and 302 in HTTP but my question is What's the difference between 301 and 302 in HTTP for Search engine?</p>31117532229	1	What does "Cannot have more than on screen object" error mean? <p>I'm working on a timer template for use in my games that I create. This is the code I have for a timer module (haven't put it into a class yet)</p> <pre><code>import time import math import pygame from livewires import games, color timer = 0 games.init(screen_width = 640, screen_height = 480, fps = 50) gamefont = pygame.font.Font(None, 30) timertext = gamefont.render('Timer: ' +str(timer), 1, [255,0,0]) screen.blit(timertext, [scoreXpos,20]) </code></pre> <p>Eventually, I'm going to have a live timer which is why I use the the render and blit methods, but for now, I just have a static variable called timer set equal to 0. When I run this program however, I get an error that says "Cannot have more than on screen object." I'm really confused because I don't think I've ever seen this error before, and definitely don't know what it means, or how to fix it. If someone could help me understand what's happening, I would very much appreciate it. Also, the reason I've imported games and color from livewires, is to use it for another purpose later on in the code.</p>3124309378	0	Association Extensions no longer working in Rails 2.3.10 <p>I have an app that we just upgrade from 2.1.0 to 2.3.10. After the upgrade, an Association Extension that previously worked causes a failure. Here is the code on the model for the extension:</p> <pre><code>Class Classroom has_many :registrations has_many :students, :through =&gt; :registrations, :uniq =&gt; true do def in_group(a_group) if a_driver scoped(:conditions =&gt; ['registrations.group_id = ?', a_group]) else in_no_group end end def in_no_group scoped(:conditions =&gt; 'registrations.group_id is null') end end end </code></pre> <p>This is a simplified model of my actual issue, but basically I used to be able to do</p> <pre><code>classroom.students.in_group(honor_students) </code></pre> <p>This no longer works, with the following output: </p> <pre><code>classroom.students.in_group(honor_students) ActiveRecord::StatementInvalid: Mysql::Error: Unknown column 'registrations.group_id' in 'where clause': SELECT * FROM `students` WHERE (registrations.group_id = 1234) </code></pre> <p>When I just grab the list of students, the SQL has all the expected join syntax there thats missing from the above version:</p> <pre><code>SELECT DISTINCT `students`.* FROM `students` INNER JOIN `registrations` ON `students`.id = `registrations`.student_id WHERE ((`registrations`.classroom_id = 9876)) </code></pre> <p>Why is the association extension missing all the join SQL?</p>31318094751	0	 <p>Use <code>e.Cancel = true;</code> to cancel back navigation.</p> <p>Please correct me if I'm wrong. Your code is looking messed up. I think you last page/back page is <code>mainpage.xaml</code> and in <code>OK</code> you are again navigating to this page. If this is the case then there is no need of navigating again you can use below code.</p> <pre><code>protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e) { MessageBoxResult res = MessageBox.Show("Are you sure that you want to exit?", "", MessageBoxButton.OKCancel); if (res != MessageBoxResult.OK) { e.Cancel = true; //when pressed cancel don't go back } } </code></pre>31431244421	0	 <p>You have the following <strong>errors</strong>:</p> <ol> <li>You cannot nest anything like form elements inside <code>&lt;p&gt;</code> tag. Replace it with a <code>&lt;div&gt;</code> tag.</li> <li>You haven't closed the <code>&lt;input /&gt;</code>.</li> </ol> <p>Use this <strong>snippet</strong>:</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;li&gt; &lt;div&gt; &lt;label for="request" id="officallabel"&gt;Purpose&lt;/label&gt; &lt;input type = "radio" name = "approvalbuttons" id = "approved" value = "Approved" /&gt; &lt;label for = "approved"&gt;Approved&lt;/label&gt; &lt;input type = "radio" name = "approvalbuttons" id = "denied" checked = "checked" value = "denied" /&gt; &lt;label for = "denied"&gt;Denied&lt;/label&gt; &lt;/div&gt; &lt;/li&gt;</code></pre> </div> </div> </p>31534394842	0	 <p>I guess you mean the category tree, And this should give you category tree. you can see the various filters being applied. (You can always do according to your need.)</p> <pre><code>&lt;?php $rootCatId = Mage::app()-&gt;getStore()-&gt;getRootCategoryId(); $catlistHtml = getTreeCategories($rootCatId, false); echo $catlistHtml; function getTreeCategories($parentId, $isChild){ $allCats = Mage::getModel('catalog/category')-&gt;getCollection() -&gt;addAttributeToSelect('*') -&gt;addAttributeToFilter('is_active','1') -&gt;addAttributeToFilter('include_in_menu','1') -&gt;addAttributeToFilter('parent_id',array('eq' =&gt; $parentId)) -&gt;addAttributeToSort('position', 'asc'); $class = ($isChild) ? "sub-cat-list" : "cat-list"; $html .= '&lt;ul class="'.$class.'"&gt;'; foreach($allCats as $category) { $html .= '&lt;li&gt;&lt;span&gt;'.$category-&gt;getName()."&lt;/span&gt;"; $subcats = $category-&gt;getChildren(); if($subcats != ''){ $html .= getTreeCategories($category-&gt;getId(), true); } $html .= '&lt;/li&gt;'; } $html .= '&lt;/ul&gt;'; return $html; } ?&gt; </code></pre> <blockquote> <p>EDIT: getting all parent category using an id/current category id..</p> </blockquote> <pre><code>$id = Mage::registry('current_category'); //or if you are retrieving other way around $category = Mage::getModel('catalog/category')-&gt;load($id); $categorynames = array(); foreach ($category-&gt;getParentCategories() as $parent) { $categorynames[] = $parent-&gt;getName(); } print_r($categorynames); //dumping category names for eg. </code></pre>31614371345	1	Get field value within Flask-MongoAlchemy Document <p>I've looked at documentation, and have searched Google extensively, and haven't found a solution to my problem.<br> This is my <code>readRSS</code> function (note that 'get' is a method of Kenneth Reitz's requests module):</p> <pre><code>def readRSS(name, loc): linkList = [] linkTitles = list(ElementTree.fromstring(get(loc).content).iter('title')) linkLocs = list(ElementTree.fromstring(get(loc).content).iter('link')) for title, loc in zip(linkTitles, linkLocs): linkList.append((title.text, loc.text)) return {name: linkList} </code></pre> <p>This is one of my MongoAlchemy classes:</p> <pre><code>class Feed(db.Document): feedname = db.StringField(max_length=80) location = db.StringField(max_length=240) lastupdated = datetime.utcnow() def __dict__(self): return readRSS(self.feedname, self.location) </code></pre> <p>As you can see, I had to call the <code>readRSS</code> function within a function of the class, so I could pass <code>self</code>, because it's dependent on the fields <code>feedname</code> and <code>location</code>.<br> I want to know if there's a different way of doing this, so I can save the <code>readRSS</code> return value to a field in the <code>Feed</code> document. I've tried assigning the <code>readRSS</code> function's return value to a variable within the function <code>__dict__</code> -- that didn't work either. </p> <p>I have the functionality working in my app, but I want to save the results to the Document to lessen the load on the server (the one I am getting my RSS feed from). </p> <p>Is there a way of doing what I intend to do or am I going about this all wrong?</p>31711968366	0	cURL loop memory growth <p>I have this problem with a loop using cURL where memory grows exponentially. In this example script, it starts using approximately 14MB of memory and ends with 28MB, with my original script and repeating to 1.000.000, memory grows to 800MB, which is bad.</p> <p>PHP 5.4.5<br/> cURL 7.21.0</p> <pre><code>for ($n = 1; $n &lt;= 1000; $n++){ $apiCall = 'https://api.instagram.com/v1/users/' . $n . '?access_token=5600913.47c8437.358fc525ccb94a5cb33c7d1e246ef772'; $options = Array(CURLOPT_URL =&gt; $apiCall, CURLOPT_RETURNTRANSFER =&gt; true, CURLOPT_FRESH_CONNECT =&gt; true ); $ch = curl_init(); curl_setopt_array($ch, $options); $response = curl_exec($ch); curl_close($ch); unset($ch); } </code></pre>31825353469	0	Two issues while trying to update wordpress user meta <p>I have a form that is submitting data to a php script. Here is some of the code in the script.</p> <pre><code>foreach ($newuser_values as $key =&gt; $value) { echo $key; echo $value; switch ($key) { case "show_name": echo "1"; switch ($value) { case "first": $update_val = $current_user-&gt;user_firstname; break; case "first_initial": echo "HI"; $update_val = $current_user-&gt;user_firstname . " " . substr($current_user-&gt;user_lastname,0,0) . "."; break; case "first_last": $update_val = $current_user-&gt;user_firstname . " " . $current_user-&gt;user_lastname; break; default: echo "HELLO"; $update_val = $user_identity; } echo $update_val; update_user_meta($user_ID, $show_name, $update_val); echo get_user_meta($user_ID, $show_name); ... } } </code></pre> <p>$newuser_values is an array of form info. I get it like this:</p> <pre><code>$newuser_values = $_POST['edit-profile']; </code></pre> <p>I have two issues here. They can both be seen from the beginning of the script output (from echo statements). The script output is:</p> <p>show_namefirst_intital1HELLOtestuser1Array</p> <p>Problem 1: As you can see, the script prints a 1 which means that it is entering the case titled "show_name" of the switch on $key. However, it does not enter the case entitled "first_intial" of the switch on $value. Why is this?</p> <p>Problem 2: Anyway the script enters the default case of the switch on $value and prints HELLO. Then, it prints the $update_val which is the testuser1. However, that value is not getting assigned to the user_meta because it is printing "Array". Why is this?</p> <p>Thanks in advance. I apologize if these questions are simplistic. I am pretty new to wordpress and web development.</p>31918138512	0	 <p>The correct thing to do is to set an execution policy on your machine (a one-time action), at which point you won't need to bypass it every time, and the Jenkins plugin should "just work". Are you unable to?</p> <p>A reasonable starting setting would be RemoteSigned, which will allow you to execute local scripts fine but would still disallow scripts downloaded from the internet.</p> <p>From an elevated PowerShell prompt, you would run:</p> <pre><code>Set-ExecutionPolicy RemoteSigned </code></pre> <p>See also: <a href="http://technet.microsoft.com/library/hh849812.aspx" rel="nofollow">http://technet.microsoft.com/library/hh849812.aspx</a></p> <p>UPDATE: excerpt from Help on applying policy and how it's supposed to behave:</p> <blockquote> <p>If you set the execution policy for the local computer (the default) or the current user, the change is saved in the registry and remains effective until you change it again.</p> </blockquote> <p>Of course, if your machine is on a Domain, then Group Policy could revert this.</p>32017133620	0	Setting timeout on blocking I/O ops with ServerSocketChannel doesn't work as expected <p>I'm working on a small group conversation server in Java and I'm currently hacking network code, but it seems like I cannot set right timeout on blocking I/O ops: chances are I've been bitten by some Java weirdness (or, simply, I misinterpret javadoc).</p> <p>So, this is the pertinent code from <code>ConversationServer</code> class (with all security checks and logging stripped for simplicity):</p> <pre><code>class ConversationServer { // ... public int setup() throws IOException { ServerSocketChannel server = ServerSocketChannel.open(); server.bind(new InetSocketAddress(port), Settings.MAX_NUMBER_OF_PLAYERS + 1); server.socket().setSoTimeout((int) Settings.AWAIT_PLAYERS_MS); int numberOfPlayers; for (numberOfPlayers = 0; numberOfPlayers &lt; Settings.MAX_NUMBER_OF_PLAYERS; ++numberOfPlayers) { SocketChannel clientSocket; try { clientSocket = server.accept(); } catch (SocketTimeoutException timeout) { break; } clients.add(messageStreamFactory.create(clientSocket)); } return numberOfPlayers; } // ... } </code></pre> <p>The expected behaviour is to let connect <code>Settings.MAX_NUMBER_OF_PLAYERS</code> clients at most, or terminate setup anyway after <code>Settings.AWAIT_PLAYER_MS</code> milliseconds (currently, <code>30000L</code>).</p> <p>What happens, is that if I connect <code>Settings.MAX_NUMBER_OF_PLAYERS</code> clients, everything is fine (exit because of <code>for</code> condition), but if I don't, the <code>SocketTimeoutException</code> I'd expect is never thrown and the server hangs forever.</p> <p>If I understand right, <code>server.socket().setSoTimeout((int) Settings.AWAIT_PLAYERS_MS);</code> should be sufficient, but it doesn't give the expected behaviour.</p> <p>So, can anyone spot the error here?</p>32137428778	0	 <p>just try with adding this piece of code </p> <pre><code>&lt;supports-screens android:anyDensity="true" android:largeScreens="true" android:normalScreens="true" android:resizeable="true" android:smallScreens="true" android:xlargeScreens="true" /&gt; </code></pre> <p></p> <pre><code>&lt;!-- all normal size screens --&gt; &lt;screen android:screenDensity="ldpi" android:screenSize="normal" /&gt; &lt;screen android:screenDensity="mdpi" android:screenSize="normal" /&gt; &lt;screen android:screenDensity="hdpi" android:screenSize="normal" /&gt; &lt;screen android:screenDensity="xhdpi" android:screenSize="normal" /&gt; </code></pre> <p></p> <p>This code involves everything even tablets <a href="https://developer.android.com/guide/topics/manifest/supports-screens-element.html" rel="nofollow">refer this</a> to exclude tablets </p>32233217783	0	Optimizing opencl kernel <p>I am trying to optimize this kernel. The CPU version of this kernel is 4 times faster than the GPU version. I would expect that the GPU version would be faster. It might be that we have a lot of memory accesses and that is why we have a low performance. I am using an Intel HD 2500 and OpenCL 1.2. </p> <p>The GPU kernel is: </p> <pre><code>__kernel void mykernel(__global unsigned char *inp1, __global unsigned char *inp2, __global unsigned char *inp3, __global unsigned char *inp4, __global unsigned char *outp1, __global unsigned char *outp2, __global unsigned char *outp3, __global unsigned char *outp4, __global unsigned char *lut, uint size ) { unsigned char x1, x2, x3, x4; unsigned char y1, y2, y3, y4; const int x = get_global_id(0); const int y = get_global_id(1); const int width = get_global_size(0); const uint id = y * width + x; x1 = inp1[id]; x2 = inp2[id]; x3 = inp3[id]; x4 = inp4[id]; y1 = (x1 &amp; 0xff) | (x2&gt;&gt;2 &amp; 0xaa) | (x3&gt;&gt;4 &amp; 0x0d) | (x4&gt;&gt;6 &amp; 0x02); y2 = (x1&lt;&lt;2 &amp; 0xff) | (x2 &amp; 0xaa) | (x3&gt;&gt;2 &amp; 0x0d) | (x4&gt;&gt;4 &amp; 0x02); y3 = (x1&lt;&lt;4 &amp; 0xff) | (x2&lt;&lt;2 &amp; 0xaa) | (x3 &amp; 0x0d) | (x4&gt;&gt;2 &amp; 0x02); y4 = (x1&lt;&lt;6 &amp; 0xff) | (x2&lt;&lt;4 &amp; 0xaa) | (x3&lt;&lt;2 &amp; 0x0d) | (x4 &amp; 0x02); // lookup table y1 = lut[y1]; y2 = lut[y2]; y3 = lut[y3]; y4 = lut[y4]; outp1[id] = (y1 &amp; 0xc0) | ((y2 &amp; 0xc0) &gt;&gt; 2) | ((y3 &amp; 0xc0) &gt;&gt; 4) | ((y4 &amp; 0xc0) &gt;&gt; 6); outp2[id] = ((y1 &amp; 0x30) &lt;&lt; 2) | (y2 &amp; 0x30) | ((y3 &amp; 0x30) &gt;&gt; 2) | ((y4 &amp; 0x30) &gt;&gt; 4); outp3[id] = ((y1 &amp; 0x0c) &lt;&lt; 4) | ((y2 &amp; 0x0c) &lt;&lt; 2) | (y3 &amp; 0x0c) | ((y4 &amp; 0x0c) &gt;&gt; 2); outp4[id] = ((y1 &amp; 0x03) &lt;&lt; 6) | ((y2 &amp; 0x03) &lt;&lt; 4) | ((y3 &amp; 0x03) &lt;&lt; 2) | (y4 &amp; 0x03); } </code></pre> <p>I use :</p> <pre><code> size_t localWorkSize[1], globalWorkSize[1]; localWorkSize[0] = 1; globalWorkSize[0] = X*Y; // X,Y define a data space of 15 - 20 MB </code></pre> <p>LocalWorkSize can vary between 1 - 256. </p> <pre><code>for LocalWorkSize = 1 I have CPU = 0.067Sec GPU = 0.20Sec for LocalWorkSize = 256 I have CPU = 0.067Sec GPU = 0.34Sec </code></pre> <p>Which is really weird. Can you give me some ideas why I get these strange numbers? and do you have any tips on how I can optimize this kernel?</p> <p>My main looks like this: </p> <pre><code>int main(int argc, char** argv) { int err,err1,j,i; // error code returned from api calls and other clock_t start, end; // measuring performance variables cl_device_id device_id; // compute device id cl_context context; // compute context cl_command_queue commands; // compute command queue cl_program program_ms_naive; // compute program cl_kernel kernel_ms_naive; // compute kernel // ... dynamically allocate arrays // ... initialize arrays cl_uint dev_cnt = 0; clGetPlatformIDs(0, 0, &amp;dev_cnt); cl_platform_id platform_ids[100]; clGetPlatformIDs(dev_cnt, platform_ids, NULL); // Connect to a compute device err = clGetDeviceIDs(platform_ids[0], CL_DEVICE_TYPE_GPU, 1, &amp;device_id, NULL); // Create a compute context context = clCreateContext(0, 1, &amp;device_id, NULL, NULL, &amp;err); // Create a command queue commands = clCreateCommandQueue(context, device_id, 0, &amp;err); // Create the compute programs from the source file program_ms_naive = clCreateProgramWithSource(context, 1, (const char **) &amp;kernelSource_ms, NULL, &amp;err); // Build the programs executable err = clBuildProgram(program_ms_naive, 0, NULL, NULL, NULL, NULL); // Create the compute kernel in the program we wish to run kernel_ms_naive = clCreateKernel(program_ms_naive, "ms_naive", &amp;err); d_A1 = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, mem_size_cpy/4, h_A1, &amp;err); d_A2 = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, mem_size_cpy/4, h_A2, &amp;err); d_A3 = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, mem_size_cpy/4, h_A3, &amp;err); d_A4 = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, mem_size_cpy/4, h_A4, &amp;err); d_lut = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, 256, h_ltable, &amp;err); d_B1 = clCreateBuffer(context, CL_MEM_WRITE_ONLY, mem_size_cpy/4, NULL, &amp;err); d_B2 = clCreateBuffer(context, CL_MEM_WRITE_ONLY, mem_size_cpy/4, NULL, &amp;err); d_B3 = clCreateBuffer(context, CL_MEM_WRITE_ONLY, mem_size_cpy/4, NULL, &amp;err); d_B4 = clCreateBuffer(context, CL_MEM_WRITE_ONLY, mem_size_cpy/4, NULL, &amp;err); int size = YCOLUMNS*XROWS/4; int size_b = size * 4; err = clSetKernelArg(kernel_ms_naive, 0, sizeof(cl_mem), (void *)&amp;(d_A1)); err |= clSetKernelArg(kernel_ms_naive, 1, sizeof(cl_mem), (void *)&amp;(d_A2)); err |= clSetKernelArg(kernel_ms_naive, 2, sizeof(cl_mem), (void *)&amp;(d_A3)); err |= clSetKernelArg(kernel_ms_naive, 3, sizeof(cl_mem), (void *)&amp;(d_A4)); err |= clSetKernelArg(kernel_ms_naive, 4, sizeof(cl_mem), (void *)&amp;d_B1); err |= clSetKernelArg(kernel_ms_naive, 5, sizeof(cl_mem), (void *)&amp;(d_B2)); err |= clSetKernelArg(kernel_ms_naive, 6, sizeof(cl_mem), (void *)&amp;(d_B3)); err |= clSetKernelArg(kernel_ms_naive, 7, sizeof(cl_mem), (void *)&amp;(d_B4)); err |= clSetKernelArg(kernel_ms_naive, 8, sizeof(cl_mem), (void *)&amp;d_lut); //__global err |= clSetKernelArg(kernel_ms_naive, 9, sizeof(cl_uint), (void *)&amp;size_b); size_t localWorkSize[1], globalWorkSize[1]; localWorkSize[0] = 256; globalWorkSize[0] = XROWS*YCOLUMNS; start = clock(); for (i=0;i&lt; EXECUTION_TIMES;i++) { err1 = clEnqueueNDRangeKernel(commands, kernel_ms_naive, 1, NULL, globalWorkSize, localWorkSize, 0, NULL, NULL); err = clFinish(commands); } end = clock(); return 0; } </code></pre>32337501223	0	I can not print correctly mysql to xml <p>I do not know where I went wrong. I want to this.</p> <pre><code> &lt;mekan&gt; &lt;Soguk Icecekler&gt; &lt;yemek&gt; &lt;urunismi&gt;Kola&lt;/urunismi&gt; &lt;fiyat&gt;2&lt;/fiyat&gt; &lt;efiyat&gt;0&lt;/efiyat&gt; &lt;/yemek&gt; &lt;yemek&gt; &lt;urunismi&gt;Kola&lt;/urunismi&gt; &lt;fiyat&gt;2&lt;/fiyat&gt; &lt;efiyat&gt;0&lt;/efiyat&gt; &lt;/yemek&gt; &lt;/Soguk Icecekler&gt; &lt;Sicak Icecekler&gt; &lt;yemek&gt; &lt;urunismi&gt;cay&lt;/urunismi&gt; &lt;fiyat&gt;2&lt;/fiyat&gt; &lt;efiyat&gt;0&lt;/efiyat&gt; &lt;/yemek&gt; &lt;yemek&gt; &lt;urunismi&gt;kahve&lt;/urunismi&gt; &lt;fiyat&gt;2&lt;/fiyat&gt; &lt;efiyat&gt;0&lt;/efiyat&gt; &lt;/yemek&gt; &lt;/Sicak Icecekler&gt; &lt;/mekan&gt; </code></pre> <p>What is my mistake?</p> <pre><code>$xml = new SimpleXMLElement('&lt;mekan/&gt;'); while($data = mysql_fetch_array($resultID)) { $kategori=$xml-&gt;addChild('Kategori'); $kategori-&gt;addChild('kategori_adi', $data["kategoriadi"]); $kategori-&gt;addChild('urunismi', $data["urunadi"]); $kategori-&gt;addChild('fiyat', $data["fiyat"]); $kategori-&gt;addChild('efiyat', $data["eskifiyat"]); } Header('Content-type: text/xml'); echo $xml-&gt;asXML(); </code></pre> <p>XML is read, but I get mistaken result.</p>32424100405	0	How to dynamically configure DataSource in Spring based on application mode? <p>We have an application which runs both as standalone Spring application and as Webservice in Weblogic. The standalone application creates the database DataSource as show below by reading the properties file.</p> <p>However for the Webservices part, I'd like to use the DataSource configured in Weblogic via JNDI. I'm not sure how to make that dynamic DataSource switch based on the mode my application runs. Any help here please? </p> <pre><code>@Configuration @PropertySources(value = {@PropertySource("classpath:app.properties")}) public class DAOConfig { @Autowired Environment env; @Bean(destroyMethod = "close") public DataSource dataSource() { return new DataSources.Builder() .host(env.getProperty("dbhost")) .port(env.getProperty("dbport", Integer.class)) .service(env.getProperty("dbservice")) .user(env.getProperty("dbuser")) .pwd(env.getProperty("dbpwd")) .initialConnectionsInPool(env.getProperty("dbinitialConnectionsInPool", Integer.class)) .maxConnectionsInPool(env.getProperty("dbmaxConnectionsInPool", Integer.class)) .build(); } } </code></pre>32532739558	0	Media Foundation EVR no video displaying <p>I've been trying in vain to come up with a no frills example of displaying video using Microsoft's Media Foundation Enhanced Video Renderer (EVR). I'm testing on Windows 7 with Visual Studio 2013.</p> <p>I'm pretty sure I've got the media types configured correctly as I can export and save the buffer from the IMFSample in my read loop to a bitmap. I can also get the video to render IF I get MF to automatically generate the topology but in this case I need to wire up the source reader and sink writer manually so I can get access to the different parts of the pipeline.</p> <p>I have used mftrace to see if I can spot anything different between the automatically generated topology and the manually wired up example but nothing obvious jumps out.</p> <p>The code is below (full sample project at <a href="https://github.com/sipsorcery/mediafoundationsamples/tree/master/MFVideoEVR" rel="nofollow">https://github.com/sipsorcery/mediafoundationsamples/tree/master/MFVideoEVR</a>).</p> <p>Is there a step I've missed to get the IMFSample from the SinkWriter to display on the video window? I've been looking at a few examples that go deeper into the DirectX pipeline but should that be necessary or is the EVR meant to abstract those mechanics aways?</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;tchar.h&gt; #include &lt;evr.h&gt; #include &lt;mfapi.h&gt; #include &lt;mfplay.h&gt; #include &lt;mfreadwrite.h&gt; #include &lt;mferror.h&gt; #include "..\Common\MFUtility.h" #include &lt;windows.h&gt; #include &lt;windowsx.h&gt; #pragma comment(lib, "mf.lib") #pragma comment(lib, "evr.lib") #pragma comment(lib, "mfplat.lib") #pragma comment(lib, "mfplay.lib") #pragma comment(lib, "mfreadwrite.lib") #pragma comment(lib, "mfuuid.lib") #pragma comment(lib, "Strmiids") #pragma comment(lib, "wmcodecdspuuid.lib") #define CHECK_HR(hr, msg) if (hr != S_OK) { printf(msg); printf("Error: %.2X.\n", hr); goto done; } void InitializeWindow(); // Constants const WCHAR CLASS_NAME[] = L"MFVideoEVR Window Class"; const WCHAR WINDOW_NAME[] = L"MFVideoEVR"; // Globals. HWND _hwnd; using namespace System::Threading::Tasks; int main() { CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE); MFStartup(MF_VERSION); IMFMediaSource *videoSource = NULL; UINT32 videoDeviceCount = 0; IMFAttributes *videoConfig = NULL; IMFActivate **videoDevices = NULL; IMFSourceReader *videoReader = NULL; WCHAR *webcamFriendlyName; IMFMediaType *videoSourceOutputType = NULL, *pvideoSourceModType = NULL, *pSrcOutMediaType = NULL; IMFSourceResolver *pSourceResolver = NULL; IUnknown* uSource = NULL; IMFMediaSource *mediaFileSource = NULL; IMFAttributes *pVideoReaderAttributes = NULL; IMFMediaType *pVideoOutType = NULL; MF_OBJECT_TYPE ObjectType = MF_OBJECT_INVALID; IMFMediaSink *pVideoSink = NULL; IMFStreamSink *pStreamSink = NULL; IMFMediaTypeHandler *pMediaTypeHandler = NULL; IMFMediaType *pMediaType = NULL; IMFMediaType *pSinkMediaType = NULL; IMFSinkWriter *pSinkWriter = NULL; IMFVideoRenderer *pVideoRenderer = NULL; IMFVideoPresenter *pVideoPresenter = nullptr; IMFVideoDisplayControl *pVideoDisplayControl = nullptr; IMFGetService *pService = nullptr; IMFActivate* pActive = NULL; MFVideoNormalizedRect nrcDest = { 0.5f, 0.5f, 1.0f, 1.0f }; IMFPresentationTimeSource *pSystemTimeSource = nullptr; IMFMediaType *sinkPreferredType = nullptr; IMFPresentationClock *pClock = NULL; IMFPresentationTimeSource *pTimeSource = NULL; CHECK_HR(MFTRegisterLocalByCLSID( __uuidof(CColorConvertDMO), MFT_CATEGORY_VIDEO_PROCESSOR, L"", MFT_ENUM_FLAG_SYNCMFT, 0, NULL, 0, NULL ), "Error registering colour converter DSP.\n"); Task::Factory-&gt;StartNew(gcnew Action(InitializeWindow)); Sleep(1000); if (_hwnd == nullptr) { printf("Failed to initialise video window.\n"); goto done; } // Set up the reader for the file. CHECK_HR(MFCreateSourceResolver(&amp;pSourceResolver), "MFCreateSourceResolver failed.\n"); CHECK_HR(pSourceResolver-&gt;CreateObjectFromURL( L"..\\..\\MediaFiles\\big_buck_bunny.mp4", // URL of the source. MF_RESOLUTION_MEDIASOURCE, // Create a source object. NULL, // Optional property store. &amp;ObjectType, // Receives the created object type. &amp;uSource // Receives a pointer to the media source. ), "Failed to create media source resolver for file.\n"); CHECK_HR(uSource-&gt;QueryInterface(IID_PPV_ARGS(&amp;mediaFileSource)), "Failed to create media file source.\n"); CHECK_HR(MFCreateAttributes(&amp;pVideoReaderAttributes, 2), "Failed to create attributes object for video reader.\n"); CHECK_HR(pVideoReaderAttributes-&gt;SetGUID(MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE, MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_GUID), "Failed to set dev source attribute type for reader config.\n"); CHECK_HR(pVideoReaderAttributes-&gt;SetUINT32(MF_SOURCE_READER_ENABLE_VIDEO_PROCESSING, 1), "Failed to set enable video processing attribute type for reader config.\n"); CHECK_HR(MFCreateSourceReaderFromMediaSource(mediaFileSource, pVideoReaderAttributes, &amp;videoReader), "Error creating media source reader.\n"); CHECK_HR(videoReader-&gt;GetCurrentMediaType((DWORD)MF_SOURCE_READER_FIRST_VIDEO_STREAM, &amp;videoSourceOutputType), "Error retrieving current media type from first video stream.\n"); Console::WriteLine("Default output media type for source reader:"); Console::WriteLine(GetMediaTypeDescription(videoSourceOutputType)); Console::WriteLine(); // Set the video output type on the source reader. CHECK_HR(MFCreateMediaType(&amp;pvideoSourceModType), "Failed to create video output media type.\n"); CHECK_HR(pvideoSourceModType-&gt;SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Video), "Failed to set video output media major type.\n"); CHECK_HR(pvideoSourceModType-&gt;SetGUID(MF_MT_SUBTYPE, MFVideoFormat_RGB32), "Failed to set video sub-type attribute on EVR input media type.\n"); CHECK_HR(pvideoSourceModType-&gt;SetUINT32(MF_MT_INTERLACE_MODE, MFVideoInterlace_Progressive), "Failed to set interlace mode attribute on EVR input media type.\n"); CHECK_HR(pvideoSourceModType-&gt;SetUINT32(MF_MT_ALL_SAMPLES_INDEPENDENT, TRUE), "Failed to set independent samples attribute on EVR input media type.\n"); CHECK_HR(MFSetAttributeRatio(pvideoSourceModType, MF_MT_PIXEL_ASPECT_RATIO, 1, 1), "Failed to set pixel aspect ratio attribute on EVR input media type.\n"); CHECK_HR(CopyAttribute(videoSourceOutputType, pvideoSourceModType, MF_MT_FRAME_SIZE), "Failed to copy video frame size attribute from input file to output sink.\n"); CHECK_HR(CopyAttribute(videoSourceOutputType, pvideoSourceModType, MF_MT_FRAME_RATE), "Failed to copy video frame rate attribute from input file to output sink.\n"); CHECK_HR(videoReader-&gt;SetCurrentMediaType((DWORD)MF_SOURCE_READER_FIRST_VIDEO_STREAM, NULL, pvideoSourceModType), "Failed to set media type on source reader.\n"); Console::WriteLine("Output media type set on source reader:"); Console::WriteLine(GetMediaTypeDescription(pvideoSourceModType)); Console::WriteLine(); // Create EVR sink . //CHECK_HR(MFCreateVideoRenderer(__uuidof(IMFMediaSink), (void**)&amp;pVideoSink), "Failed to create video sink.\n"); CHECK_HR(MFCreateVideoRendererActivate(_hwnd, &amp;pActive), "Failed to created video rendered activation context.\n"); CHECK_HR(pActive-&gt;ActivateObject(IID_IMFMediaSink, (void**)&amp;pVideoSink), "Failed to activate IMFMediaSink interface on video sink.\n"); // Initialize the renderer before doing anything else including querying for other interfaces (https://msdn.microsoft.com/en-us/library/windows/desktop/ms704667(v=vs.85).aspx). CHECK_HR(pVideoSink-&gt;QueryInterface(__uuidof(IMFVideoRenderer), (void**)&amp;pVideoRenderer), "Failed to get video Renderer interface from EVR media sink.\n"); CHECK_HR(pVideoRenderer-&gt;InitializeRenderer(NULL, NULL), "Failed to initialise the video renderer.\n"); CHECK_HR(pVideoSink-&gt;QueryInterface(__uuidof(IMFGetService), (void**)&amp;pService), "Failed to get service interface from EVR media sink.\n"); CHECK_HR(pService-&gt;GetService(MR_VIDEO_RENDER_SERVICE, __uuidof(IMFVideoDisplayControl), (void**)&amp;pVideoDisplayControl), "Failed to get video display control interface from service interface.\n"); CHECK_HR(pVideoSink-&gt;GetStreamSinkByIndex(0, &amp;pStreamSink), "Failed to get video renderer stream by index.\n"); CHECK_HR(pStreamSink-&gt;GetMediaTypeHandler(&amp;pMediaTypeHandler), "Failed to get media type handler.\n"); // Set the video output type on the source reader. CHECK_HR(MFCreateMediaType(&amp;pVideoOutType), "Failed to create video output media type.\n"); CHECK_HR(pVideoOutType-&gt;SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Video), "Failed to set video output media major type.\n"); CHECK_HR(pVideoOutType-&gt;SetGUID(MF_MT_SUBTYPE, MFVideoFormat_RGB32), "Failed to set video sub-type attribute on EVR input media type.\n"); CHECK_HR(pVideoOutType-&gt;SetUINT32(MF_MT_INTERLACE_MODE, MFVideoInterlace_Progressive), "Failed to set interlace mode attribute on EVR input media type.\n"); CHECK_HR(pVideoOutType-&gt;SetUINT32(MF_MT_ALL_SAMPLES_INDEPENDENT, TRUE), "Failed to set independent samples attribute on EVR input media type.\n"); CHECK_HR(MFSetAttributeRatio(pVideoOutType, MF_MT_PIXEL_ASPECT_RATIO, 1, 1), "Failed to set pixel aspect ratio attribute on EVR input media type.\n"); CHECK_HR(CopyAttribute(videoSourceOutputType, pVideoOutType, MF_MT_FRAME_SIZE), "Failed to copy video frame size attribute from input file to output sink.\n"); CHECK_HR(CopyAttribute(videoSourceOutputType, pVideoOutType, MF_MT_FRAME_RATE), "Failed to copy video frame rate attribute from input file to output sink.\n"); //CHECK_HR(pMediaTypeHandler-&gt;GetMediaTypeByIndex(0, &amp;pSinkMediaType), "Failed to get sink media type.\n"); CHECK_HR(pMediaTypeHandler-&gt;SetCurrentMediaType(pVideoOutType), "Failed to set current media type.\n"); Console::WriteLine("Input media type set on EVR:"); Console::WriteLine(GetMediaTypeDescription(pVideoOutType)); Console::WriteLine(); CHECK_HR(MFCreatePresentationClock(&amp;pClock), "Failed to create presentation clock.\n"); CHECK_HR(MFCreateSystemTimeSource(&amp;pTimeSource), "Failed to create system time source.\n"); CHECK_HR(pClock-&gt;SetTimeSource(pTimeSource), "Failed to set time source.\n"); //CHECK_HR(pClock-&gt;Start(0), "Error starting presentation clock.\n"); CHECK_HR(pVideoSink-&gt;SetPresentationClock(pClock), "Failed to set presentation clock on video sink.\n"); Console::WriteLine("Press any key to start video sampling..."); Console::ReadLine(); IMFSample *videoSample = NULL; DWORD streamIndex, flags; LONGLONG llTimeStamp; while (true) { CHECK_HR(videoReader-&gt;ReadSample( MF_SOURCE_READER_FIRST_VIDEO_STREAM, 0, // Flags. &amp;streamIndex, // Receives the actual stream index. &amp;flags, // Receives status flags. &amp;llTimeStamp, // Receives the time stamp. &amp;videoSample // Receives the sample or NULL. ), "Error reading video sample."); if (flags &amp; MF_SOURCE_READERF_ENDOFSTREAM) { printf("End of stream.\n"); break; } if (flags &amp; MF_SOURCE_READERF_STREAMTICK) { printf("Stream tick.\n"); } if (!videoSample) { printf("Null video sample.\n"); } else { printf("Attempting to write sample to stream sink.\n"); CHECK_HR(videoSample-&gt;SetSampleTime(llTimeStamp), "Error setting the video sample time.\n"); //CHECK_HR(videoSample-&gt;SetSampleDuration(41000000), "Error setting the video sample duration.\n"); CHECK_HR(pStreamSink-&gt;ProcessSample(videoSample), "Streamsink process sample failed.\n"); } SafeRelease(&amp;videoSample); } done: printf("finished.\n"); getchar(); return 0; } LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { return DefWindowProc(hwnd, uMsg, wParam, lParam); } void InitializeWindow() { WNDCLASS wc = { 0 }; wc.lpfnWndProc = WindowProc; wc.hInstance = GetModuleHandle(NULL); wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.lpszClassName = CLASS_NAME; if (RegisterClass(&amp;wc)) { _hwnd = CreateWindow( CLASS_NAME, WINDOW_NAME, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 640, 480, NULL, NULL, GetModuleHandle(NULL), NULL ); if (_hwnd) { ShowWindow(_hwnd, SW_SHOWDEFAULT); MSG msg = { 0 }; while (true) { if (PeekMessage(&amp;msg, NULL, 0, 0, PM_REMOVE)) { TranslateMessage(&amp;msg); DispatchMessage(&amp;msg); } else { Sleep(1); } } } } } </code></pre>32615481263	0	 <p>The short answer is <strong>no, there isn't.</strong> You always should write the access specifier in front of your field/method.</p> <pre><code>public int var1; public char var2; </code></pre> <p>Note that <code>private</code> is the default specifier. It is a question of design, but I would always explicitly designate the modifier. (And even if it is just for the consistent indentation!)</p> <p>Read more on <a href="http://msdn.microsoft.com/en-us/library/ba0a1yw2%28v=vs.71%29.aspx" rel="nofollow">Accessibility Levels (C#)</a> at msdn.</p>32734390276	0	 <p>Just do it, like this:</p> <pre><code>Update TableTest SET COL3 = newdata Where Col1= D11 </code></pre>3289401392	0	 <p>You can add panels to a form at runtime the same way the designer does - construct the Panel, and add it to the form (via <code>this.Controls.Add(thePanel);</code>).</p> <p>The easiest way to see the appropriate code is to add a panel to the form using the designer, then open up the "YourForm.designer.cs" file. The designer just generates the required code for you - but you can see the exact code required to duplicate what the designer would create.</p> <p>As for the layout, I'd recommend watching the <a href="http://windowsclient.net/learn/video.aspx?v=324332" rel="nofollow">Layout Techniques for Windows Forms Developers</a> video. It may give you some good clues as to the various options available for layout. There is nothing exactly like Java's GridLayout, though there are some <a href="http://sourceforge.net/projects/dnetgridlayout/" rel="nofollow">open source projects that attempt to duplicate this functionality</a>.</p>32922980802	0	 <p><a href="http://msdn.microsoft.com/en-us/library/hh193922%28v=vs.110%29.aspx" rel="nofollow">SendMailAsync</a> and all methods that use the Task Parallel Library execute in a threadpool thread, although you can make them use a new thread if you need to. This means that instead of creating a new thread, an available thread is picked from the pool and returned there when the method finishes.</p> <p>The number of threads in the pool varies with the version of .NET and the OS, the number of cores etc. It can go from 25 threads per core in .NET 4 to hundreds or per core in .NET 4.5 on a server OS.</p> <p>An additional optimization for IO-bound (disk, network) tasks is that instead of using a thread, an IO completion port is used. Roughly, this is a callback from the IO stack when an IO operation (disk or network) finishes. This way the framework doesn't waste a thread waiting for an IO call to finish.</p> <p>When you start an asynchronous network operation, .NET make the network call, registers for the callback and releases the threadpool thread. When the call finishes, the framework gets notified and schedules the rest of the asynchronous method (essentially what comes after the <code>await</code> or <code>ContinueWith</code>) on a threadpool thread. </p> <p>Submitting a 100 asynchronous operations doesn't mean that 100 threads will be used nor that all 100 of them will execute in parallel. Rather, the framework will take into account the number of cores, the load and the number of available threads to execute as many of them as possible, without hurting overall performance. Waiting on the network calls may not even use a thread at all, while processing the messages themselves will execute on threadpool threads</p>33020908161	0	Special character in concatenated sql script causing error <p>I save stored procedure code as files and then execute them in several different databases. I am trying to concatenate multiple files (100's). Every utility I use seems to create some special characters in the file that cause an error when i execute the script in sql.</p> <p>Currently, i used</p> <pre><code>type *.sql &gt; script.sql </code></pre> <p>in DOS. I am getting the following error in many places.</p> <pre><code>Msg 102, Level 15, State 1, Line 1 Incorrect syntax near ''. </code></pre> <p>How can I find this character so I can do a find/replace? Thanks!</p>33136973295	0	Balloon synopsis - jQuery plugin - which file specifically? <p>I have downloaded what seems to be a handy tool called Balloon Synopsis (homepage: <a href="http://schlegel.github.io/balloon/index.html" rel="nofollow">http://schlegel.github.io/balloon/index.html</a> GitHub: <a href="https://github.com/balloonLD/balloon-synopsis" rel="nofollow">https://github.com/balloonLD/balloon-synopsis</a>) and ran the Gruntfile. All there is however is bunch of .js files (/src/js) and I am not sure which one (or several) are the jQuery plugin. Alternatively, have I been misled completely? There is no documentation or how-to whatsoever, so any help or advice would be great :) Thanks!</p>33224777375	0	 <p>This is not a cross-domain issue. You are mixing the <em>dynamic proxy</em> and <em>proxyless</em> approaches. <code>$.hubConnection</code> and <code>createHubProxy</code> are from the proxyless API, but <code>.client</code> is available only with dynamic proxies. Check <a href="http://www.asp.net/signalr/overview/signalr-20/hubs-api/hubs-api-guide-javascript-client#establishconnection" rel="nofollow">the documentation about both</a> and you will be able to fix it (I don't go further with code because I do not know which approach you really want to use). </p>33334815913	0	 <p>You can also do it in pure xaml, just use trigger action:</p> <pre><code> &lt;Button&gt; &lt;Button.Triggers&gt; &lt;EventTrigger RoutedEvent="PreviewMouseDown"&gt; &lt;BeginStoryboard Storyboard="{DynamicResource BotRotation}"/&gt; &lt;/EventTrigger&gt; &lt;/Button.Triggers&gt; &lt;/Button&gt; </code></pre>3345605025	0	 <p>The system NAND flash for the emulator has run out of space. Your host system D: is not the issue, but for some reason the system.img file that represents a NAND flash for the emulator is full. You can try creating a new emulator, or doing a factory default reset in the emulator to clean it up. To do this, either issue a Factory Data Reset inside Android under Settings -> Privacy, or start the emulator from the command-line:</p> <pre><code>android list avd emulator -avd My_Avd_Name -wipe-data </code></pre> <p>The first command list all Android Virtual Devices. You need the name for the second command. The emulator should not already be running. A third option would be to delete the disk images located under your Windows profile. Under your profiles, it's <code>.android/avd/My_Avd_Name.avd</code> You should only need to delete <code>userdata-qemu.img</code> and maybe <code>cache.img</code>. You can try deleting other image files if necessarily, but note, <code>sdcard.img</code> won't be re-created automatically. You need to run <code>mksdcard</code> from the command-line.</p>33513156139	0	 <p>If you could change your student class properties to match the Xml element names and/or decorate the properties with attributes indicating what XML value goes to what class property, then you could use the .Net to deserialise the XML into a List Students in one line.</p> <p>Then just persist to the DB as you normally would.</p> <p><a href="http://stackoverflow.com/questions/364253/how-to-deserialize-xml-document">Here's an example</a></p>33639297430	0	 <p>you should use a <code>table</code> as grid </p> <p>Try this </p> <pre><code>&lt;table&gt; &lt;tr&gt; &lt;?php $numbers_per_row = 5; $rowi= 0; $numbers_limit = 25; for($b=1; $b&lt;=$numbers_limit ; $b++) { echo '&lt;td&gt;&lt;a href="index.php?page='.$b.'"&gt;'.$b.'&lt;/td&gt;'; if($rowi&lt;=$numbers_per_row) { $rowi++; } else { echo '&lt;/tr&gt;&lt;tr style="margin-top:10px;"&gt;'; /* &lt;-- change it ^ to what you want */ /* Reset counter */ $rowi = 0; } } ?&gt; &lt;/table&gt; </code></pre>3376971446	0	distribution provisioning and code signing issues <p>I just generated a ad hoc distribution provisioning. I dragged this into xcode and then set my ad hoc build to be iphone distribution. Followed every single step in this <a href="http://support.testflightapp.com/kb/tutorials/how-to-create-an-ipa-xcode-4" rel="nofollow noreferrer">tutorial</a>. The issue is that when I follow this instruction to see my list of devices it doesn't even have a ProvisionedDevices key in the embedded.mobileprovison. The key goes something like this:</p> <pre><code>&lt;key&gt;Entitlements&lt;/key&gt; &lt;dict&gt; &lt;key&gt;application-identifier&lt;/key&gt; &lt;string&gt;8CH38P5X6X.*&lt;/string&gt; &lt;key&gt;get-task-allow&lt;/key&gt; &lt;false/&gt; &lt;key&gt;keychain-access-groups&lt;/key&gt; &lt;array&gt; &lt;string&gt;8CH38P5X6X.*&lt;/string&gt; &lt;/array&gt; &lt;/dict&gt; &lt;key&gt;ExpirationDate&lt;/key&gt; &lt;date&gt;2012-03-17T00:31:45Z&lt;/date&gt; &lt;key&gt;Name&lt;/key&gt; &lt;string&gt;Fever&lt;/string&gt; //this is not my app name, how come it's here &lt;key&gt;TimeToLive&lt;/key&gt; &lt;integer&gt;291&lt;/integer&gt; &lt;key&gt;UUID&lt;/key&gt; &lt;string&gt;101F3A06-B33C-411A-8173-A4CEAFF5E673&lt;/string&gt; &lt;key&gt;Version&lt;/key&gt; &lt;string&gt;101F3A06-B33C-411A-8173-A4CEAFF5E673&lt;/string&gt; &lt;key&gt;Version&lt;/key&gt; &lt;integer&gt;1&lt;/integer&gt; &lt;/dict&gt; &lt;/plist&gt; </code></pre> <p>The weirdest issue is that it has an app name in the , which is not my app name!! How is this even possible? Something is messed up..</p> <p>This 8CH38P5X6X is also the App ID of my other app called Fever... how.. how is this possible. I've code signed adhoc using iphone distribution and it clearly says this:</p> <p><img src="https://i.stack.imgur.com/icqfU.png" alt="enter image description here"></p> <p><strong>UPDATE:</strong></p> <p>I removed/clear the provisioning profile that I have for the Fever app, restart xcode, and tried to build the archive again and it works! Anyone ever have issues with multiple provisioning profile on your xcode being mixed up like this?</p>33832798837	0	 <p><a href="http://guides.rubyonrails.org/active_record_validations.html#uniqueness" rel="nofollow">Why not use a validation</a>:</p> <pre><code>#app/models/review.rb class Review &lt; ActiveRecord::Base validates :movie_id, uniqueness: { scope: :user_id, message: "You've reviewed this movie!" } end </code></pre> <p>This is considering your <code>review</code> model <code>belongs_to :movie</code></p> <hr> <p>You could also use an ActiveRecord callback:</p> <pre><code>#app/models/review.rb class Review &lt; ActiveRecord::Base before_create :has_review? belongs_to :user, inverse_of: :reviews belongs_to :movie def has_review? return if Review.exists?(user: user, movie_id: movie_id) end end #app/models/user.rb class User &lt; ActiveRecord::Base has_many :reviews, inverse_of: :user end </code></pre> <hr> <blockquote> <p>Is there any way to improve the lookup in my has_reviewed? method?</p> </blockquote> <pre><code> def has_reviewed? redirect_to album_reviews_path, notice: "You've already written a review for this album." if current_user.reviews.exists?(movie: @movie) end </code></pre>33921572016	1	List connected Bluetooth LE devices to Windows 8 with python <p>I want to be able to read out information about connected Bluetooth Low Energy HID devices in Windows 8. My main application uses Qt, but I thought it could be much easier to get help from a Python script. Since Windows 8.1 supports Bluetooth Low Energy natively, I connect my mouse to it and tried using the <a href="https://pypi.python.org/pypi/pywinusb/" rel="nofollow">pywinusb</a> package, but it doesn't seem to be able to read out this wirelessly connected device, only connected HID devices. </p> <p>How can I read out information about my BLE device with Python? </p>34039388527	0	 <p>All answers are creating NEW arrays before projecting the final result : (<code>filter</code> and <code>map</code> creates a new array each) so basically it's creating <strong>twice</strong>.</p> <p>Another approach is <em>only to yield expected values</em> : </p> <p>Using iterator functions</p> <pre><code>function* foo(g) { for (let i = 0; i &lt; g.length; i++) { if (g[i]['images'] &amp;&amp; g[i]["images"].length) yield g[i]['images'][0]["name"]; } } var iterator = foo(data1) ; var result = iterator.next(); while (!result.done) { console.log(result.value) result = iterator.next(); } </code></pre> <p>This will <strong>not</strong> create any additional array and only return the expected values !</p> <p>However if you must return an array , rather than to do something with the actual values , then use other solutions suggested here.</p> <p><a href="https://jsfiddle.net/remenyLx/7/" rel="nofollow">https://jsfiddle.net/remenyLx/7/</a></p>34127845377	0	Issues connecting to mySql database on target machine <p>I'm using <code>hostgator</code> for hosting my website and I have added my <code>IP</code> address as remote access host. And then I connected with mySql workbench and tested the connection and I get the message that all parameters are correct. On <strong>hostgator</strong>, I added myself as a the admin user granting myself all privileges. Now I want to manipulate the database via a PHP script using PDO but this is the error I'm getting in my browser when I try to run the PHP file:</p> <p>Connection failed: <code>SQLSTATE[28000] [1045] Access denied for user 'user'@'host' (using password: YES)</code></p> <p>On mySQL workbench Users and Privileges tab, I get this:</p> <p>"<code>The account you are currently using does not have sufficient privileges to make changes to MySQL users and privileges.</code>"</p> <p>I'm not sure whats going wrong here and I'm quiet new to this. Can somebody please help?</p> <p>edit:</p> <p>php code below: </p> <pre><code>&lt;?php ini_set('display_errors',1); error_reporting(E_ALL); //this block tries to connect to the database //if there's an error connecting, the code under catch will //and the program will end $host="host"; $port="3306"; $user="xxx"; $password="xxx"; $dbname="database"; try { $conn = new PDO("mysql:host=$host;dbname=$dbname;", $user, $password); // set the PDO error mode to exception $conn-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); echo "Connected successfully"; } catch(PDOException $e) { echo "Connection failed: " . $e-&gt;getMessage(); } //$con-&gt;close(); ?&gt; </code></pre>34220081748	0	Drawing layers with jcanvas: performance optimization <p>)</p> <p>I have a small web-application which uses jquery and jcanvas (<a href="http://calebevans.me/projects/jcanvas/" rel="nofollow">http://calebevans.me/projects/jcanvas/</a>) to print some shapes onto a canvas.</p> <p>It's basically a map. The user can zoom into it and drag it around and whenever he does so everything has to be drawn again.</p> <p>As you may see in the code below I remove and recreate layers pretty often (whenever the user drags the map, zooms or resizes his window). I need the layers to handle hover- and click-events. My question is whether there is a big performance impact of this way to handle events in comparison to other solutions. If this is the case, how could I optimize my performance?</p> <pre><code>var posX = 0, posY = 0; var zoom = 100; var points = []; //array of up to 1000 points retrieved by ajax function draw(){ $("canvas").removeLayers(); $("canvas").clearCanvas(); var xp, yp, ra; var name; $.each(points, function(index) { xp = (this["x"]-posX)/zoom; yp = (this["y"]-posY)/zoom; ra = 1000/zoom; $("#map").drawArc({ layer:true, fillStyle: "black", x: xp, y: yp, radius: ra, mouseover: function(layer) { $(this).animateLayer(layer, { fillStyle: "#c33", scale: 1.0 },200); }, mouseout: function(layer) { $(this).animateLayer(layer, { fillStyle: "black", scale: 1.0 },200); }, mouseup: function(layer){ context(index,layer.x,layer.y); } }); }); } </code></pre> <p>Thank you for your time :-)</p>3433991107	0	 <p>You should not be using HTML Entities in XML. Using normal UTF-8 characters should be fine.</p> <p>The occurrence of <code>Osnabrück</code> means that at some point, most likely, the city name is processed as ISO-8859-1 instead of UTF-8. It is not <code>htmlentities()</code>'s fault. You need to find that point and fix it.</p>3448772833	0	 <p>You are just passing that function a string. For it to make any sense of that, it would have to parse the string to split up the key/value pairs. I'm not saying it's the best approach, but if you want to do that, you should use <a href="http://php.net/manual/en/function.parse-str.php" rel="nofollow"><code>parse_str()</code></a>.</p> <p>Note that this is <em>not</em> by any means a language feature of PHP, but I am just providing a means to handle what you've shown.</p>3459716871	0	 <p>Try this </p> <pre><code> return Fluently.Configure().Database(MsSqlConfiguration.MsSql2008 .ConnectionString(@"Data Source=CHRIS-PC\\SQLEXPRESS;Initial Catalog=TestDB;User ID=test")) .Mappings(m =&gt; m.AutoMappings.Add(model)) .ExposeConfiguration(BuildSchema) .BuildSessionFactory(); </code></pre> <p>or use this let <strong>mymodel</strong> be a sample <strong>model</strong></p> <pre><code> Fluently.Configure() .Database(MsSqlConfiguration.MsSql2008 .ConnectionString(ConfigurationManager.ConnectionStrings["CHRIS-PC\\SQLEXPRESS"].ConnectionString)) .Mappings(m =&gt; m.FluentMappings.AddFromAssemblyOf&lt;mymodel&gt;().Add&lt;UsersMap&gt;()) .ExposeConfiguration(cfg =&gt; { new SchemaExport(cfg).Execute(false, true, false); // new SchemaUpdate(cfg).Execute(true, true); }).BuildSessionFactory(); </code></pre>34616583017	0	 <p>For formatting options, see <a href="http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx" rel="nofollow">this</a> </p> <pre><code>Dim v1 as Double = Val(txtD.Text) / Val(txtC.Text) * Val(txtF.Text) / Val(txtE.Text) txtA.text = v1.ToString("N2"); </code></pre>34711855579	0	 <p>STL containers in VS Debug are notoriously slow. Game programmers forums are rife with complaints about this. Often people choose alternative implementations. However, from what I've read, you can get a performance boost up front by disabling iterator debugging/checking:</p> <pre><code>#define _HAS_ITERATOR_DEBUGGING 0 #define _SECURE_SCL 0 </code></pre> <p>Other things that can affect debug performance are excessive calls to new and delete. Memory pools can help with that. You haven't provided details for <code>PropMsg::add_v_var_repeated()</code> or <code>PropMsg::~PropMsg()</code>, so I can't comment. But I assume there's a vector or other STL container inside that class?</p>34828081273	0	How do I change only background color of ProgressDialog without affecting border in Android? <p>I used the following code to change the background of Progress Dialog. But the color changes on the outside frame too as below. I want to change only inside the dialog.</p> <pre><code>&lt;style name="StyledDialog" parent="@android:style/Theme.Panel"&gt; &lt;item name="android:background"&gt;#083044&lt;/item&gt; &lt;/style&gt; </code></pre> <p><img src="https://i.stack.imgur.com/ZuITn.png" alt="enter image description here"></p> <p>As per the answer given at this question <a href="http://stackoverflow.com/questions/13347539/change-background-of-progressdialog">Change background of ProgressDialog</a></p> <pre><code>&lt;style name="StyledDialog" parent="@android:style/Theme.Dialog"&gt; &lt;item name="android:alertDialogStyle"&gt;@style/CustomAlertDialogStyle&lt;/item&gt; &lt;item name="android:textColorPrimary"&gt;#000000&lt;/item&gt; &lt;/style&gt; &lt;style name="CustomAlertDialogStyle"&gt; &lt;item name="android:bottomBright"&gt;@color/background&lt;/item&gt; &lt;item name="android:bottomDark"&gt;@color/background&lt;/item&gt; &lt;item name="android:bottomMedium"&gt;@color/background&lt;/item&gt; &lt;item name="android:centerBright"&gt;@color/background&lt;/item&gt; &lt;item name="android:centerDark"&gt;@color/background&lt;/item&gt; &lt;item name="android:centerMedium"&gt;@color/background&lt;/item&gt; &lt;item name="android:fullBright"&gt;@color/background&lt;/item&gt; &lt;item name="android:fullDark"&gt;@color/background&lt;/item&gt; &lt;item name="android:topBright"&gt;@color/background&lt;/item&gt; &lt;item name="android:topDark"&gt;@color/background&lt;/item&gt; &lt;/style&gt; </code></pre> <p>This code gives background color perfect. But since, dialog color and activity's background color is same. It appears <strong>like transparent with no border. I want some border as before.</strong></p> <p><img src="https://i.stack.imgur.com/saW53.png" alt="enter image description here"></p>3494010166	0	prevent url tampering in php <p>This is a test engine application with 5 papers set by me..as 5 php pages</p> <p>Flow of the application </p> <p>Login.html </p> <p>check.php // to check whether credentials r right</p> <p>if correct then </p> <p>main.php //user clicks on "take test" in this page which displays him 1 of the 5 papers...</p> <p>but once i am logged in i can just change the url to the url of the test paper i want..the paper names r 1.php 2.php....</p> <p>how do i stop this...??</p> <pre><code>if(!isset($_SESSION['page'])//Tp continue; //Tp else { header('Location:login.php'); exit; } //Tp $_SESSION['page']=$_SERVER['SCRIPT_NAME'];//tp </code></pre> <p>is this correct...as i said there are 5 pages....</p> <p>in eac page i have this code....</p> <p>i check whether the Session variable is set....if it is set...it means it already has visited the page.....but this code doesnt work...did i use the variable _SESSION['page'] before declaring it???</p>35040054572	0	 <p>When you avoid of using the <code>with_message</code> method on the matcher then <a href="https://github.com/thoughtbot/shoulda-matchers/blob/d1e9a41fca001b6d89455aff49f1f03ac272ee08/lib/shoulda/matchers/active_model/validation_matcher.rb#L143" rel="nofollow">it uses default message</a>. </p> <p>To make your test works you should override the <a href="https://github.com/thoughtbot/shoulda-matchers/blob/d1e9a41fca001b6d89455aff49f1f03ac272ee08/lib/shoulda/matchers/active_record/validate_uniqueness_of_matcher.rb#L265" rel="nofollow">matcher's default message</a>:</p> <pre><code>it { should validate_uniqueness_of(:name).with_message("has already been taken") } </code></pre>35113240740	0	 <p>Microsoft's documentation is of limited use, once you move off Windows. Their discussion of the ODBC APIs is fine -- but anything about Visual Studio or other Windows-specific components should generally be ignored.</p> <p>iODBC.org can provide some pointers -- especially if you look into the source for iODBC Demo.app and/or iODBC Test.command, which ship with the <a href="http://www.iodbc.org/dataspace/iodbc/wiki/iODBC/Downloads#Mac_OS_X" rel="nofollow">free and open source iODBC SDK</a>.</p> <p>You may also benefit from developing and testing with a commercially-supported ODBC driver, such as <a href="http://uda.openlinksw.com/odbc-sqlserver-st/" rel="nofollow">my employer's offering</a>.</p>3522206099	0	 <p>I've found a solution.</p> <p>I can apply system theme for that single element in the resource, something like this:</p> <pre><code>&lt;ResourceDictionary&gt; &lt;ResourceDictionary.MergedDictionaries&gt; &lt;ResourceDictionary Source="/PresentationFramework.Aero;V3.0.0.0;31bf3856ad364e35;component\themes/aero.normalcolor.xaml" /&gt; &lt;/ResourceDictionary.MergedDictionaries&gt; &lt;/ResourceDictionary&gt; </code></pre>35328839744	1	Convert XML to string to find length <p>I am trying to find the length of an XML document and would like to know how to convert an XML document into a string so that I can find its length.</p>3544804176	0	 <p>You could use a <code>not exists</code> clause to ensure the combination has not been voted on:</p> <pre><code>select a.itemId , b.itemId from Items a join Items b on a.ItemId &lt; b.ItemId where not exists ( select * from Vote where userId = 42 and ((betterItemId = a.ItemId and worseItemId = b.ItemId) or (worseItemId = a.ItemId and betterItemId = b.ItemId)) ) order by rand() limit 2 </code></pre>35512284347	0	 <p>In the CMSButton you set <strong>base</strong>.BackColor, but in CMSLabel you set <strong>this</strong>.BackColor, which has no code in the setter.</p>35619137295	0	 <p>Strictly by the standard <em>type-punning</em> expect in narrow circumstances is <a href="http://en.wikipedia.org/wiki/Undefined_behavior" rel="nofollow">undefined behavior</a> but in practice many compilers support it for example <a href="http://gcc.gnu.org/onlinedocs/gcc-4.7.1/gcc/Optimize-Options.html#Type-punning" rel="nofollow">gcc manual points here for type-punning</a> and under <em>-fstrict-aliasing</em> section is says:</p> <blockquote> <p>The practice of reading from a different union member than the one most recently written to (called “type-punning”) is common. Even with -fstrict-aliasing, type-punning is allowed, provided the memory is accessed through the union type.</p> </blockquote> <p>I would recommend reading <a href="http://cellperformance.beyond3d.com/articles/2006/06/understanding-strict-aliasing.html" rel="nofollow">Understanding Strict Aliasing</a> if you plan on using <em>type-punning</em> a lot.</p> <p><code>y.b</code> has the value <code>b</code> since all the elements of the union share memory and you initialized <code>y</code> with <code>100</code> which in <em>ASCII</em> is <code>b</code>. This is the same reason why the other fields of <code>x</code> change when you modify one including the case of <code>strcpy</code> and depending on your compiler this may be undefined or well defined(<em>in the case of gcc it is defined</em>).</p> <p>For completeness sake the C++ draft standard section <code>9.5</code> <em>Unions</em> paragraph <em>1</em> says(<em>emphasis mine</em>):</p> <blockquote> <p>In a union, <strong>at most one of the non-static data members can be active at any time</strong>, that is, the value of at most one of the non-static data members can be stored in a union at any time. [ Note: One special guarantee is made in order to simplify the use of unions: If a standard-layout union contains several standard-layout structs that share a common initial sequence (9.2), and <strong>if an object of this standard-layout union type contains one of the standard-layout structs, it is permitted to inspect the common initial sequence of any of standard-layout struct members</strong>; see 9.2. —end note ] The size of a union is sufficient to contain the largest of its non-static data members. Each non-static data member is allocated as if it were the sole member of a struct.</p> </blockquote>35729624392	0	 <p>What you could do is, use the <a href="http://coding4fun.codeplex.com/releases/view/109917" rel="nofollow noreferrer">Coding4Fun Toolkit</a> and use the control to display the current memory use and peak memory while developing your app. So download the Toolkit and add the correct dlls to your project. You can also use NuGet.</p> <p>Now you can add this to your layout:</p> <pre><code>&lt;coding4fun:MemoryCounter xmlns:coding4fun="clr-namespace:Coding4Fun.Phone.Controls;assembly=Coding4Fun.Phone.Controls"/&gt; </code></pre> <p>Or declare it in C#:</p> <pre><code>public MainPage() { InitializeComponent(); MemoryCounter counter = new MemoryCounter(); this.ContentPanel.Children.Add(counter); } </code></pre> <p>Now you should see two numbers on the top of your screen when you launch it.</p> <p><img src="https://i.stack.imgur.com/eSvYH.png" alt="enter image description here"></p> <p>You can see the MemoryCounter results only in DEBUG mode!</p> <p>Otherwise check the DeviceStatus class out, it has some useful things in it:</p> <pre><code>namespace Microsoft.Phone.Info { public static class DeviceStatus { public static long ApplicationCurrentMemoryUsage { get; } public static long ApplicationPeakMemoryUsage { get; } public static long ApplicationMemoryUsageLimit { get; } public static long DeviceTotalMemory { get; } } } </code></pre> <p>To see how to use it check <a href="https://msdn.microsoft.com/en-us/library/windows/apps/hh394037(v=vs.105).aspx" rel="nofollow noreferrer">this</a> out!</p> <p>Hope it helps!</p>3587753989	0	 <p>Yes, you have to create the product id for every product you wish to put on the app store. Apple checks each and every purchase made by the user on the basis of the product id you create on iTunes Connect.</p>35918155087	0	intellij Debugger is not able to connect with Remote VM <p>I am working on a JNLP based application which is hosted on JBOSS server. My IDE is intellij . When I tried to do the remote debug on the port defined for that the on Debug console of intellij this message is written</p> <pre><code>Connected to the target VM, address: 'camelot-dev.kwcorp.com:8787', transport: 'socket' </code></pre> <p>from this message, I thought that I am connected with the Remote VM and I jumped into the workspace for debugging but nothing seems to be working for me. When I clicked on F6 and respective buttons for debugging nothing seems to working (no debug happened). I checked the debug port and it is correct. I am not sure that whether I am doing the correct thing or not.</p>36037712436	0	 <p>Your plunkr wasn't working because your script tag was pointing to a not existing <code>app.js</code> in <code>index.html</code> after re-naming <code>script.js</code> to <code>app.js</code> the plunkr is working.</p> <p>Your JSON mock seems a bit complicated. You can easily add a json file to the plunkr and load it with a <code>$http.get()</code> request.</p> <p>Please have a look at the demo below and this <a href="http://plnkr.co/edit/klCx13NmuHFJC7B6fv00?p=preview" rel="nofollow">updated plunkr</a>.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>// Code goes here /* var mockDataForThisTest = "json=" + encodeURI( JSON.stringify([ { name: "Dave", email: "dave@gmail.com", option: "Home", number: "1234567890" }, { name: "John", email: "jon@gmail.com", option: "Home", number: "1234567890" } ]));*/ var app = angular.module('angularApp', []); app.controller('MainCtrl', function($scope, $http) { $scope.choices = []; loadChoices(); function loadChoices() { var httpRequest = $http({ method: 'GET', url: 'https://www.mocky.io/v2/5758817a130000f82d896c76' //url: './example.json' //data: mockDataForThisTest }).then(function(response) { //success(function(data, status) { // use then --&gt; newer syntax console.log(response.data); $scope.choices = response.data; }); }; $scope.addNewChoice = function() { var newItemNo = $scope.choices.length + 1; $scope.choices.push({ 'id': 'choice' + newItemNo }); }; $scope.removeChoice = function(index) { //var lastItem = $scope.choices.length - 1; $scope.choices.splice(index, 1); //lastItem); }; });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"&gt;&lt;/script&gt; &lt;link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/&gt; &lt;div ng-app="angularApp" ng-controller="MainCtrl"&gt; &lt;fieldset data-ng-repeat="choice in choices"&gt; &lt;input type="text" ng-model="choice.name" name="" placeholder="Enter name"&gt; &lt;input type="text" ng-model="choice.email" name="" placeholder="Enter email"&gt; &lt;input type="text" ng-model="choice.number" name="" placeholder="Enter mobile number"&gt; &lt;select ng-model="choice.option"&gt; &lt;option value&gt;Select&lt;/option&gt; &lt;option value="Mobile"&gt;Mobile&lt;/option&gt; &lt;option value="Office"&gt;Office&lt;/option&gt; &lt;option value="Home"&gt;Home&lt;/option&gt; &lt;/select&gt; &lt;button class="remove" ng-click="removeChoice($index)"&gt;-&lt;/button&gt; &lt;/fieldset&gt; &lt;button class="addfields" ng-click="addNewChoice()"&gt;Add fields&lt;/button&gt; &lt;div id="choicesDisplay"&gt; {{ choices }} &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>36111566417	0	 <p>The problem is that the browser is downloading the image when you first reference it, and not before.</p> <p>I'd simply have two image elements and hide/show them instead of changing the <code>src</code> attribute of a single element.</p>36232030396	0	 <p>The <a href="https://developer.apple.com/library/ios/documentation/CoreBluetooth/Reference/CBCharacteristic_Class/#//apple_ref/c/tdef/CBCharacteristicProperties" rel="nofollow">documentation</a> is pretty clear. You cannot use this property on characteristics you publish. The purpose of this value is to enable you to interpret the properties of characteristics that are discovered from other peripherals. </p> <p>If you want to advise centralised that your value has changed then <code>notify</code> is the appropriate method. </p>3638334450	0	 <blockquote> <p>Note: This method is automatically called by JavaScript whenever a Date object needs to be displayed as a string.</p> </blockquote> <p>So <code>d+''</code> is the same as <code>d.toString()</code>.</p>3644092645	0	Store metadata "CurrentBind" is not valid. Error <p>In the context of a click-once application that is being debugged locally with exception breaking on "Thrown" turned on in VS2010, I am experiencing the following error:</p> <pre><code>Deployment Exception: "Store metadata "CurrentBind" is not valid." at System.Deployment.Application.ComponentStore.GetPropertyString(DefinitionAppId appId, String propName) </code></pre> <p>when I execute the following line of code:</p> <pre><code>if (System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed) </code></pre> <p>This exception is being caught and handled by .net code, and the application will not crash after experiencing this error. Unfortunately, this error is followed up by:</p> <pre><code>InvalidDeploymentException: "Application is not installed" at System.Deployment.Application.ApplicationDeployment..ctor(String fullAppId) </code></pre> <p>If I continue to wade through the exceptions, I get another error:</p> <pre><code>SynchronizationLockException: "Object synchronization method was called from an unsynchronized block of code" at Microsoft.Practices.Unity.SynchronizedLifetimeManager.TryExit() @ ProvidedContainer.RegisterInstance(LoggerFacade); </code></pre> <p>and finally:</p> <pre><code>ConfigurationErrorsException: "This element is not currently associated with any context" at System.Configuration.ConfigurationElement.get_EvaluationContext() </code></pre> <p>in the constructor of </p> <pre><code>[System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] public partial class InfrastructureDataServiceClient : System.ServiceModel.ClientBase&lt;Infrastructure.DataServices.IInfrastructureDataService&gt;, Infrastructure.DataServices.IInfrastructureDataService { public InfrastructureDataServiceClient() { } } </code></pre> <p>These errors are all handled by the .net framework code and don't ripple into the application, but as long as I have the option to break on exception "Thrown" I continue to go through these errors until I lose patience and choose to break only on unhandled exceptions, at which point the app fully loads.</p> <p>This has happened to me in the past, and at that time I had to completely re-install visual studio, but it worked fine after that. I'd rather not do that, as it is time consuming and my VS installation is pretty customized. Also, my co-workers are not experiencing the same error, so that tells me that there is something unique about my environment.</p> <p>I experienced a visual studio hang recently when debugging, and had to kill the devenv process, that might play a role, but it's hard to say because I recently turned on the break on thrown option. I've already tried to delete the suo files, but that had no effect.</p> <p>I have the following addons installed: Resharper, .Net Reflector, Team Explorer, TFS Power Tools, Theme Manager</p>3655684415	0	 <blockquote> <p>(1) <em>The stack is actually only local to expressionParser so I KNOW I can remove the new keyword</em></p> </blockquote> <p><strong>correct</strong></p> <blockquote> <p>(2) <em>Do I HAVE To create a pointer to the queue in this case. If I need to create the pointer, then I should call a delete output in my query function to properly get rid of the queue?</em></p> </blockquote> <p><strong>correct. Here, "creating pointer" doesn't mean again using <code>new</code> and copy all contents. Just assign a pointer to the already created <code>queue&lt;string&gt;</code>. Simply <code>delete output;</code> when you are done with it in your <code>query()</code>.</strong></p> <blockquote> <p>(3) <em>vector being returned by query. Should that be left as I have it or should it be a pointer and what's the difference between them?</em></p> </blockquote> <p><strong>I would suggest either you pass the <code>vector&lt;Line*&gt;</code> by non-const reference to your <code>query()</code> and use it or return a <code>vector&lt;Line*&gt;*</code> from your function. Because difference is, if the vector is huge and return by value then it might copy all its content (considering the worst case without optimization)</strong></p> <blockquote> <p>(4) <em>Once I consume that vector (display the information in it) I need it to be removed from memory, however, the pointers contained in the vector are still good and the items being pointed to by them should not be deleted. What's the best approach in this case?</em></p> </blockquote> <p><strong>Pass the <code>vector&lt;Line*&gt;</code> into the function by reference. And retain it in scope until you need it. Once you are done with pointer members 'Line*<code>inside it, just</code>delete` them</strong></p> <blockquote> <p>(5) <em>What happens to the contents of containers when you call delete on the container? If the container held pointers?</em></p> </blockquote> <p><strong>Nothing happens to the pointer members of the container when it's deleted. You have to explicitly call <code>delete</code> on every member. By the way in your case, you can't <code>delete</code> your <code>vector&lt;Line*&gt;</code> because it's an object not a pointer &amp; when you <code>delete output;</code>, you don't have to worry about contents of <code>queue&lt;&gt;</code> because they are not pointers.</strong></p> <blockquote> <p>(6) <em>Those pointers are deleted won't that affect other areas of my program?</em></p> </blockquote> <p><strong>Deleting a valid pointer (i.e. allocated on heap) doesn't affect your program in any way.</strong></p>3668588334	0	 <p>The <code>center</code> of a view is expressed in it's superview's coordinate system. So you are centering your image view in the wrong coordinate system. (dynamic view's superview as opposed to dynamic view)</p> <p>To centre view A within view B, the centre point of view A has to be the centre of the <code>bounds</code> rectangle of view B. You can get this using (from memory!) <code>CGRectGetMidX</code> and <code>CGRectGetMidY</code>.</p>3679625734	0	 <p>You are trying to do too much in the main method. You need to break this up into more manageable parts. Write a method <code>boolean isPrime(int n)</code> that returns true if a number is prime, and false otherwise. Then modify the main method to use isPrime.</p>36837425524	0	Problems in building a gradle project on Intellij Idea <p>I'm having problems when trying to build a proyect on Intellij Idea. There are 2 problems:</p> <ul> <li><p>When creating a gradle project on Intellij Idea, and I select "Use default gradle wrapper (recommended)", Intellij Idea can't let me set the Gradle Home. Then, when I go to Build -> Make project, Intellij Idea tells me that is downloading Gradle, when actually I have already downloaded Gradle 2.12 (I'm using gradle in another projects).</p></li> <li><p>The second thing I'm doing is to create a project and when setting gradle (in the New Project Wizard) and set "Use local gradle distribution". When doing this, and building the project, Intellij Idea tells me that is refreshing gradle project and stays there(I have been waiting 1 hour and nothing..)</p></li> </ul> <p>So, which is the best way to create a gradle project, or, how can I solve this problems?</p> <p>Thanks</p>36930769109	0	 <p>If using uWSGI, there is a command line option which allows you to say you are providing it with a module path instead of a file path. For standard Apache with mod_wsgi, or with uWSGI defaults, you can create a WSGI script file which imports the WSGI application from your module by its path into the WSGI script file and then refer to that WSGI script file. If using mod_wsgi-express, then it has an option like uWSGI which allows you to say you are providing it with a module path instead.</p>37038539650	0	Google map not load completely and rending error <p>I have one problem with google map, I used <a href="https://ngmap.github.io/#/!places-auto-complete.html" rel="nofollow noreferrer">https://ngmap.github.io/#/!places-auto-complete.html</a>.</p> <p>I split my web app into multiple tabs and turn catch it by <code>ng-if</code>.</p> <p>Currently in the main tab, I can google map fully loaded, but in others, it fails tab as shown below. The first image is the main tab, it's okay. But the 2nd picture is faulty, somebody please tell me why and how to fix me, please In tab Dashboard, google map is okay, but in tab Manage it does not load completely.</p> <p><a href="https://i.stack.imgur.com/1kSuM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1kSuM.png" alt="enter image description here"></a></p>37130409981	0	How to allow access to a file for a specific domain and block for other domain in Apache2.conf? <p>I have blocked the access to a file in apache configuration by editing the .conf file. For now, only localhost can access the files. Is there a way where i can access the files if it requested from a specific domain name or if requested by query string parameters.</p> <p>Apache.conf - </p> <blockquote> <p> Order allow,deny Allow from 127.0.0.1 </p> </blockquote>37213279307	0	 <p>Cast the <code>obj</code> to type of the return. </p> <p>For example if your expected return type is <code>PdsLongAttrImpl</code></p> <p>Then, it would be:</p> <pre><code>PdsLongAttrImpl pdsObj = (PdsLongAttrImpl)obj; </code></pre> <p>//Then perform operation on <code>pdsObj</code>.</p> <p>NOTE: If obj is not of the type you are casting to, you will end up with <code>ClassCastException</code>.</p>37329589230	0	Why wont my loop within a loop in Javascript work? <p>This is suppose to store the chosen answer for multiple questions. When I use this code, it only checks the first question and disregards the other questions.</p> <pre><code> for(i = 0; i &lt; questions.length-1; i++){ radios = document.getElementsByName(questions[i]); for (var t = 0; length &lt; radios.length; t++) { if (radios[t].checked) { var qResults = JSON.parse(localStorage["qResults"]); num = radios[t].value; checked = num.toString(); var temp = (id[0] + ";" + questions[i] + ";" + checked); alert(temp); qResults.push(temp); localStorage["qResults"] = JSON.stringify(qResults); } } alert("question finished"); } </code></pre>37413264230	0	What is the difference between named and optional parameters in Dart? <p>Dart supports both named optional parameters and positional optional parameters. What are the differences between the two?</p> <p>Also, how can you tell if an optional parameter was actually specified?</p>37525979649	0	dgrid editor with a dijit.form.Select <p>I have a column in my dgrid that uses a digit.form.Select.</p> <pre><code>var gl = {}; gl.coverTypeEditorData = [{label: "C", value: "C"}, {label: "F", value: "F"}, {label: "G", value: "G"}, {label: "S", value: "S"}, {label: "P", value: "P"}]; ... ,editor({ 'label': 'Type', 'field': 'TYPE', 'editor': Select, 'editorArgs': { options: gl.coverTypeEditorData } } ) </code></pre> <p>The select drop down displays the correct value, but when it closes the value in the cell gets changed to whatever value was last chosen.</p> <p>Row 1: Change the value to S.<br/> Row 2: Has value C. I select the dd but do not change the value. Display changes to S. Change row event does not fire. The cell has a S displaying but its actual value is C, which will be the selected value if I open the drop down again.</p> <p>What do I need to add to get the cell to display the correct value?</p>37636282002	0	Handling option groups in Access form- runtime error 2427 <p>I have an option group on a form. I want the form to process code based on which button is selected. The snippet I have for now is:</p> <pre><code>If Me.Option18.Value = True Then DoCmd.OpenQuery "Logbook Query all available" End If </code></pre> <p>Option 18 is the radio button on the form.<br> On the If line, I get 'run time error 2427: You entered an expression that has no value'</p> <p>I tried different uses of me.option 18, and get the same error. I also tried replacing 'true' with 1, same result.</p> <p>Is there a better way to execute code based on an option group selection. or is this simply a syntax error?</p>37719122892	0	 <p>If you want to know if an object property exists, regardless of its value, you can use <code>property_exists</code>.</p> <pre><code>if (property_exists($model, $column) { ... } </code></pre>37836524426	0	 <p>I think that the best way to do it is to <a href="http://symfony.com/doc/current/cookbook/controller/error_pages.html#overriding-the-default-exceptioncontroller" rel="nofollow">overriding the default ExceptionController</a>. Just extend it, and override the <code>findTemplate</code> method. Check from the request's attribute if there's <code>_route</code> or <code>_controller</code> set, and do something with it.</p> <pre><code>namespace AppBundle\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Bundle\TwigBundle\Controller\ExceptionController as BaseExceptionController; class ExceptionController extends BaseExceptionController { protected function findTemplate(Request $request, $format, $code, $showException) { $routeName = $request-&gt;attributes-&gt;get('_route'); // You can inject these routes in the construct of the controller // so that you can manage them from the configuration file instead of hardcode them here $routesAdminSection = ['admin', 'admin_ban', 'admin_list']; // This is a poor implementation with in_array. // You can implement more advanced options using regex // so that if you pass "^admin" you can match all the routes that starts with admin. // If the route name match, then we want use a different template: admin_error_CODE.FORMAT.twig // example: admin_error_404.html.twig if (!$showException &amp;&amp; in_array($routeName, $routesAdminSection, true)) { $template = sprintf('@AppBundle/Exception/admin_error_%s.%s.twig', $code, format); if ($this-&gt;templateExists($template)) { return $template; } // What you want to do if the template doesn't exist? // Just use a generic HTML template: admin_error.html.twig $request-&gt;setRequestFormat('html'); return sprintf('@AppBundle/Exception/admin_error.html.twig'); } // Use the default findTemplate method return parent::findTemplate($request, $format, $code, $showException); } } </code></pre> <p>Then configure <code>twig.exception_controller</code>:</p> <pre><code># app/config/services.yml services: app.exception_controller: class: AppBundle\Controller\ExceptionController arguments: ['@twig', '%kernel.debug%'] </code></pre> <p> <pre><code># app/config/config.yml twig: exception_controller: app.exception_controller:showAction </code></pre> <p>You can then override the template in the same way:</p> <ul> <li>Resources/AppBundle/views/Exceptions/ <ul> <li>admin_error.html.twig</li> <li>admin_error_404.html.twig</li> <li>admin_error_500.html.twig</li> <li>...</li> </ul></li> </ul> <h2>UPDATE</h2> <p>A simpler way to do this is to specify the section of the website inside the <code>defaults</code> collection of your routes. Example:</p> <pre><code># app/config/routing.yml home: path: / defaults: _controller: AppBundle:Main:index section: web blog: path: /blog/{page} defaults: _controller: AppBundle:Main:blog section: web dashboard: path: /admin defaults: _controller: AppBundle:Admin:dashboard section: admin stats: path: /admin/stats defaults: _controller: AppBundle:Admin:stats section: admin </code></pre> <p>then your controller become something like this:</p> <pre><code>namespace AppBundle\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Bundle\TwigBundle\Controller\ExceptionController as BaseExceptionController; class ExceptionController extends BaseExceptionController { protected function findTemplate(Request $request, $format, $code, $showException) { $section = $request-&gt;attributes-&gt;get('section'); $template = sprintf('@AppBundle/Exception/%s_error_%s.%s.twig', $section, $code, format); if ($this-&gt;templateExists($template)) { return $template; } return parent::findTemplate($request, $format, $code, $showException); } } </code></pre> <p>And configure <code>twig.exception_controller</code> in the same way as described above. Now you just need to define a template for each section, code and format.</p> <ul> <li>web_error_404.html.twig</li> <li>web_error_500.html.twig</li> <li>admin_error_404.html.twig</li> <li>admin_error_500.html.twig</li> <li>and so on...</li> </ul>37911499101	0	Open a text file with vb.net , and if it exists delete that file <p>I am writing code for a windows application using vb.net. I want to open a text file under <code>c:\</code>. If the file already exists I want to delete that file.</p> <pre><code>my code ------- Dim file As String = "C:\test.txt" If System.IO.File.Exists(file) Then file.Remove(file) Else System.Diagnostics.Process.Start(file) End If </code></pre> <p>I am getting the following error when I try to open that file.</p> <pre><code>error ----- The system cannot find the file specified </code></pre>38034577849	1	Getting value of an HiddenField inserting it from template - Flask <p>I'm a newbie in Python/Flask programmation and I'm having some problems to return the value of my HiddenField inserting it from my template.</p> <p>This my Form Class:</p> <pre><code>class DownloadForm(Form): link = HiddenField() download = SubmitField('Download') </code></pre> <p>And this is my template "Material" with a table in which I put my materials from DB and where I'm trying to put the value of the HiddenField:</p> <pre><code> &lt;tbody&gt; {% for mat in materials %} &lt;tr&gt; &lt;td&gt;{{ mat.author }}&lt;/td&gt; &lt;td&gt;{{ mat.title }}&lt;/td&gt; &lt;td&gt;{{ mat.subject }}&lt;/td&gt; &lt;td&gt;{{ mat.description }}&lt;/td&gt; &lt;td&gt;{{ mat.faculty }}&lt;/td&gt; &lt;td&gt;{{ mat.professor }}&lt;/td&gt; &lt;td&gt; &lt;select class="form-control"&gt; &lt;option&gt;1&lt;/option&gt; &lt;option&gt;2&lt;/option&gt; &lt;option&gt;3&lt;/option&gt; &lt;option&gt;4&lt;/option&gt; &lt;option&gt;5&lt;/option&gt; &lt;/select&gt; &lt;/td&gt; &lt;form method="POST" enctype="multipart/form-data" action={{url_for('download')}}&gt; {{ formDownload.link(value = '{{mat.link}}')}} &lt;td&gt;{{ formDownload.download }}&lt;/td&gt; &lt;/form&gt; &lt;td&gt;{{ formDelete.delete }}&lt;/td&gt; &lt;/tr&gt; {% endfor %} &lt;/tbody&gt; &lt;/table&gt; </code></pre> <p>The problem is in this line of code where I would like to insert the HiddenField value. </p> <pre><code>{{ formDownload.link(value = '{{mat.link}}')}} </code></pre> <p>I want to insert the value here because every SubmitField is linked with a specific row of the table. The variable <strong>mat.link</strong> contains the url of the material that users want to download but I can't get this value with the function form.request['link'].</p> <p>Here there's my function download when form is submitted:</p> <pre><code>@app.route('/download', methods=['GET', 'POST']) def download(): form = DownloadForm(csrf_enabled=False) if form.validate_on_submit(): link = request.form['link'] return redirect(url_for('download', filename=link)) </code></pre> <p>I've tried to debug my application and the <em>variable link</em> results equal to <em>"mat.link"</em> as a string . Can someone help me please ? Thanks</p>38131093166	0	Polymer 1.0 Dom-Repeat Bind Array <p>In my try to update to Polymer 1.0 I got the following problem with Data-Binding:</p> <p>My Polymer 0.5 Webapp uses a Repeat-Template to generate Checkboxes for some Categories. All <code>checked</code> values are bound to an array (<code>sortedCatsArray</code>) with the category-ids as key. Here is my first attempt to update that part to Polymer 1.0, but it doesn't work...</p> <pre><code> &lt;template is="dom-repeat" items="{{sortedCatsArray}}" as="category"&gt; &lt;paper-checkbox for category$="{{category.id}}" checked="{{filterChkboxes[category.id]}}"&gt;&lt;/paper-checkbox&gt; &lt;/template&gt; </code></pre> <p>As you may read in the <a href="https://www.polymer-project.org/1.0/docs/devguide/data-binding.html#path-binding" rel="nofollow">docs</a>, it is no longer possible to bind to Array-Properties with square-brackets (now that way: <code>object.property</code>). May anybody tell me if it's still possible to bind all generated checkbox-values in one array? </p> <p><strong>Update #1</strong></p> <p>As you may read in the <a href="https://www.polymer-project.org/1.0/docs/devguide/data-binding.html#array-binding" rel="nofollow">docs</a>, Array-Binding by index is not supported. So I tried to use that example from the docs for my case and wrote the following code. If I run this code, it seems to work as expected: the first and third checkbox is checked. But I also want the array to be changed if I manual check/uncheck a checkbox. That does not happen, only if I change the array (in the <code>ready</code>-function) the checkbox gets checked...</p> <pre><code>&lt;dom-module id="my-index"&gt; &lt;link rel="import" type="css" href="/css/index.css"&gt; &lt;template&gt; &lt;template is="dom-repeat" items="{{sortedCatsArray}}" as="category"&gt; &lt;paper-checkbox for category$="{{category.id}}" checked="{{arrayItem(filterChkboxes.*,category.id)}}" on-change="test"&gt;&lt;/paper-checkbox&gt; &lt;/template&gt; &lt;/template&gt; &lt;/dom-module&gt; &lt;script&gt; Polymer({ is: "my-index", properties: { filterChkboxes: { type: Array, notify: true, observer: "filterChkboxesChanged", value: function(){return[true,false,true,false];} }, sortedCatsArray: { type: Array, value: function(){return[{id: 0}, {id: 1},{id: 2},{id: 3}]}, notify: true }, }, ready: function(){ this.set('filterChkboxes.1',true); }, test: function(){ console.log(this.filterChkboxes); }, observers: [ 'filterChkboxesChanged(filterChkboxes.*)' ], arrayItem: function(array, key){ return this.get(key, array.base); }, filterChkboxesChanged: function(changes){ console.log(changes); }, }); &lt;/script&gt; </code></pre>38231041329	0	Kendo combobox not show the Text corresponding to value from modal <p>I have a partial view with a combobox. When try to render partial view with modal(contains data from database), it shows only the value field. i want to show the text field of that value field. Help me please.</p> <pre><code>@(Html.Kendo().ComboBoxFor(m =&gt; m.divCode) .DataTextField("Name") .DataValueField("ID") .HtmlAttributes(new { style = "width:160px" }) .SelectedIndex(0) .AutoBind(false) .Placeholder("Select Div Code") .Filter(FilterType.Contains) .DataSource(source =&gt; { source.Read(read =&gt; { read.Action("GetDivision", "AssetTransaction"); }); }) ) </code></pre>38336286882	0	need to create one sample app using google app engine <p>I need to integrate Google app engine to use as back end for iOS app .</p> <p>I have tried following the <a href="https://cloud.google.com/appengine/docs/python/endpoints/consume_ios" rel="nofollow">Link</a> But I wasnt able to complete it .</p> <p>Can AnyOne Please guide me the step to convert the Parse database back end to Google App Engine as back end .</p> <p>Kindly guide the proper way .</p> <p>Thanks </p>38438872477	0	 <p>Then you can't use a form-level setting.</p> <p>If this is constant (the fields are <strong>always</strong> locked), simply set all other controls to <code>Locked = True</code>.</p> <p>If it's dynamic, use a procedure like this:</p> <pre><code>Private Sub SetEditable(EnableEdit As Boolean) Dim ctl As Control For Each ctl In Me.Controls ' The main editable control types (add more if they occur on your form) If ctl.ControlType = acTextBox Or ctl.ControlType = acComboBox Or _ ctl.ControlType = acCheckBox Or ctl.ControlType = acSubform Then If ctl.Name = "MySpecialDateField" Then ' Always editable ctl.Locked = False Else ctl.Locked = Not EnableEdit ' If you want to provide a visual feedback: ' 0 = Flat (locked), 2 = Sunken (editable) ctl.SpecialEffect = IIf(EnableEdit, 2, 0) End If End If End If Next ctl End Sub </code></pre>38522534739	0	 <p>The panel's <a href="http://docs-origin.sencha.com/extjs/4.1.3/#!/api/Ext.panel.Panel-method-update" rel="nofollow">update</a> function expects a HTML string instead of a DOM object:</p> <pre><code>// using a HTML string Ext.getCmp('treeContainer').update("&lt;div class='NodeContent'&gt;" + node.displayText + "&lt;/div&gt;"); // using a DOM object Ext.getCmp('treeContainer').update(nodeDiv.outerHTML); </code></pre> <p>Note, that using this function will always replace all existing HTML content in the panel.</p> <hr> <p>If you really want to <strong>append</strong> HTML (i.e. preserve existing HTML content), you need to get a target element to append your HTML/DOM node to.</p> <p>This could be the panel's default render target element:</p> <pre><code>var panel = Ext.getCmp('treeContainer'), renderEl = panel.isContainer ? panel.layout.getRenderTarget() : panel.getTargetEl(); // using a DOM node renderEl.appendChild(nodeDiv); // using a HTML string renderEl.insertHtml('beforeEnd', "&lt;div class='NodeContent'&gt;" + node.displayText + "&lt;/div&gt;"); </code></pre> <p>Or - as this may change depending on your panel's layout - you just create a containg element in your initial <a href="http://docs-origin.sencha.com/extjs/4.1.3/#!/api/Ext.panel.Panel-cfg-html" rel="nofollow">html</a> config:</p> <pre><code>{ xtype: 'panel', id: 'treeContainer', html: '&lt;div class="html-content"&gt;&lt;/div&gt;' } </code></pre> <p>and append your content there:</p> <pre><code>Ext.getCmp('treeContainer').getEl().down('.html-content').appendChild(nodeDiv); </code></pre> <p>In any of the latter two cases, you should update the panel's layout afterwards, as you changed it's content manually:</p> <pre><code>Ext.getCmp('treeContainer').updateLayout(); </code></pre>38623576794	0	When pasting into the console, spaces after command are causing issue <p>I have a simple line of code, with multiple readline commands that works just fine if I type it into the console directly, or paste it in from an existing R document without any excess spaces after the last bracket.</p> <pre><code>{ v1 &lt;- readline("Choose 1: "); v2 &lt;- readline("Choose 2: "); v3&lt;- readline("Choose 2: ")} </code></pre> <p>If I run the above line I will be asked to Choose 1, then Choose 2, then Choose 3. This example is simple, but it is how I like to enter a lot of my data.</p> <p>But if I inadvertently copy some empty spacing after the line of code when copying from an R document, or the above line is included with other code like so:</p> <pre><code>X&lt;-c(1,2,3,4,5) { v1 &lt;- readline("Choose 1: "); v2 &lt;- readline("Choose 2: "); v3&lt;- readline("Choose 2: ")} Y&lt;-c(1,2,3,4) </code></pre> <p>All three readline commands will be printed at once, so that I can't enter my data in.</p> <p>I've tried including the readline statements in a function, but I run into the same kind of problem with pasting spaces after the function call, causing the readline statements to all be printed out at once.</p> <pre><code>fun&lt;-function(){ v1 &lt;- readline("Choose 1: "); v2 &lt;- readline("Choose 2: "); v3&lt;- readline("Choose 2: ") } fun() Y&lt;-c(1,2,3,4) </code></pre> <p>The only luck I've had is to use source() to call a function from a separate R document, but I'm trying to avoid using source and keep everything in one R document. Ideally I'd like to be able to run multiple readline (or some other way to be asked to enter data), from a piece of code sandwiched in other code.</p>3873123951	0	SQLite: How to calculate age from birth date <p>What is the best way to calculate the age in years from a birth date in sqlite3?</p>38810693076	0	 <p>It is possible to "Publish" the results of the job. The response from the HTTP request can be written to the file server, and that will have the values of the last run job.</p> <pre><code>&lt;cfschedule action = "update" task = "TaskName" operation = "HTTPRequest" url = "/index.cfm?action=task" startDate = "#STARTDATE#" startTime = "12:00:00 AM" interval = "Daily" resolveURL = "NO" requestTimeOut = "600" publish = "yes" path = "#PATH#" file = "log_file.log"&gt; </code></pre> <p>Then you can verify the log against the database if you wanted. Since it is the response from the page, you can get and store errors and warnings here as well.</p>3896183877	0	 <p>Javascript Patterns is a good book to learn object oriented programming and advanced concepts in javascript.</p>3904981227	0	 <p>This is on mac, I'm guessing? I'm not very familiar with compiling on mac. </p> <p>Can you tell us how you're compiling (i.e. what compile flags, etc). And perhaps add an example which is compilable).</p> <p>Also, can you compile this code using your environment?</p> <pre><code>#include "CLucene.h" int main(){ lucene::analysis::SimpleAnalyzer *sanalyzer = new lucene::analysis::SimpleAnalyzer(); } </code></pre> <p>I compiled the above code with the following command with no problems. (-fPIC because i'm on an 64 bit machine).</p> <blockquote> <p>g++ test.cpp -lclucene -I/usr/lib -fPIC</p> </blockquote>39138905683	0	JSON DECODE using PHP <p>I am doing some JSON decodes - I followed this tutorial well explained - <a href="http://webtutsdepot.com/2009/08/31/how-to-read-json-data-with-php/" rel="nofollow">How To Parse JSON With PHP</a></p> <p>and the PHP code, I used </p> <pre><code> &lt;?php $string='{"person":[ { "name":{"first":"John","last":"Adams"}, "age":"40" }, { "name":{"first":"Thomas","last":"Jefferson"}, "age":"35" } ]}'; $json_a=json_decode($string,true); $json_o=json_decode($string); // array method foreach($json_a[person] as $p) { echo ' Name: '.$p[name][first].' '.$p[name][last].' Age: '.$p[age].' '; } // object method foreach($json_o-&gt;person as $p) { echo ' &lt;br/&gt; Name: '.$p-&gt;name-&gt;first.' '.$p-&gt;name-&gt;last.' Age: '.$p-&gt;age.' '; } ?&gt; </code></pre> <p>It is working correctly... But my concern I need only details of Thomas' last name and age. I need to handle this to extract only certain features, not all the objects. </p>39238442568	0	Problems with NSTokenView (again) - using objectvalue <p>In my Swift Application for Mac OS X, I'm using a <a href="https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ApplicationKit/Classes/NSTokenField_Class/" rel="nofollow">NSTokenField</a>. I'm using, among others, the delegate methods <code>tokenField(tokenField: NSTokenField, representedObjectForEditingString editingString: String) -&gt; AnyObject</code> and <code>tokenField(tokenField: NSTokenField, displayStringForRepresentedObject representedObject: AnyObject) -&gt; String?</code> to work with represented objects. My represented objects are instances of a custom class.</p> <p>From the <a href="https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/TokenField_Guide/GetSetTokenFields/GetSetTokenFields.html#//apple_ref/doc/uid/TP40006555-CH9-SW2" rel="nofollow">Apple Documentation</a>, I know that <code>objectValue</code> can be used to access the represented objects of a <code>NSTokenView</code> as a <code>NSArray</code>:</p> <blockquote> <p>To retrieve the objects represented by the tokens in a token field, send the token field an <code>objectValue</code> message. Although this method is declared by <code>NSControl</code>, <code>NSTokenField</code> implements it to return an array of represented objects. If the token field simply contains a series of strings, <code>objectValue</code> returns an array of strings. To set the represented objects of a token field, use the <code>setObjectValue</code>: method, passing in an array of represented objects. If these objects aren’t strings, <code>NSTokenField</code> then queries its delegate for the display strings to use for each token.</p> </blockquote> <p>However, this doesn't seem to work for me. <code>let tokenArray = self.tokenField.objectValue! as! NSArray</code> does return a NSArray, but it is empty, even though the delegate method required to return a represented object has been called the appropriate amount of times before.</p> <p><code>NSTokenView</code> doesn't seem like a particularly strong tool to work with tokenization, but, lacking an alternative, I hope that you guys can help me making my implementation work.</p> <p>Thanks in advance!</p>39321929870	0	Error 410:gone (codenameone) <p>So I tried the tutorial Codenameone provided on JSON parsing, but now when i try it out it gives me a 410:gone error.</p> <p>I did google the error but didn't find anything in combination with java or codenameone and i don't really understand the meaning of this error.</p> <p>This error is not only in netbeans as i expected but even the on android it gives this error.</p> <p>Code below is the action performed after clicking the "get twitter"-button:</p> <pre><code>public void actionPerformed(ActionEvent evt) { ConnectionRequest request = new ConnectionRequest() { @Override protected void readResponse(InputStream input) throws IOException { JSONParser parser = new JSONParser(); System.out.println(parser.parse(new InputStreamReader(input))); } }; request.setUrl("http://search.twitter.com/search.json"); request.setPost(false); request.addArgument("q", "@codenameone"); NetworkManager manager = NetworkManager.getInstance(); manager.start(); manager.addToQueue(request); } }); </code></pre>39433373890	0	 <p>MySQLi is not a driver for PDO. It is a standalone class. PDO has the following drivers:</p> <ul> <li>CUBRID (PDO)</li> <li>MS SQL Server (PDO)</li> <li>Firebird (PDO)</li> <li>IBM (PDO)</li> <li>Informix (PDO)</li> <li>MySQL (PDO)</li> <li>MS SQL Server (PDO)</li> <li>Oracle (PDO)</li> <li>ODBC and DB2 (PDO)</li> <li>PostgreSQL (PDO)</li> <li>SQLite (PDO)</li> <li>4D (PDO)</li> </ul> <p>More information you can find here: <a href="http://php.net/manual/de/pdo.drivers.php" rel="nofollow">http://php.net/manual/de/pdo.drivers.php</a><br> You have to remove the <code>i</code> from the dsn: <code>mysql:host=127.0.0.1;dbname=app</code></p>39513648622	0	 <p>You will need to identify what makes that data unique in the table. If it's a customer table, then it's probably the customerid of 13029. However if it's a customer order table, then maybe it's the combination of CustomerId and OrderDate (and maybe not, I have placed two unique orders on the same date). You will know the answer to that based on your table's design.</p> <p>Armed with that knowledge, you will want to write a query to pull back the keys from the target table <code>SELECT CO.CustomerId, CO.OrderId FROM dbo.CustomerOrder CO</code> If you know the process only transfers data from the current year, add a filter to the above query to restrict the number of rows returned. The reason for this is memory conservation-you want SSIS to run fast, don't bring back extraneous columns or rows it will never need.</p> <p>Inside your dataflow, add a <a href="http://msdn.microsoft.com/en-us/library/ms141821.aspx" rel="nofollow">Lookup Transformation</a> with that query. You don't specify 2005, 2008 or 2012 as your SSIS version and they have different behaviours associated with the Lookup Transformation. Generally speaking, what you are looking to do is identify the unmatched rows. By definition, unmatched means they don't exist in the target database so those are the rows that are <em>new</em>. 2005 assumes every row is going to match or it errors. You will need to click the Configure Error Output... button and select "Redirect Rows". 2008+ has an option under "Specify how to handle rows with no matching entries" and there you'll want "Redirect rows to no match output."</p> <p>Now take the No match output branch (2008+) or the error output branch (2005) and plumb that into your destination.</p> <p>What this approach doesn't cover is detecting and handling when the source system reports $56.82 and the target system has $22.38 (updates). If you need to handle that, then you need to look at some change detection system. Look at Andy Leonard's <a href="http://www.sqlservercentral.com/articles/Stairway+Series/76390/" rel="nofollow">Stairway to Integration Services</a> series of articles to learn about options for detecting and handling changes.</p>39638004053	0	 <pre><code>function dividedByArray(data,low,high) { for (i=low; i&lt;=high; i++) { var passed = 0; for(var curr in data) { if(i % data[curr] === 0) { passed++; } } switch(passed) { case data.length : console.log(i + 'all_match'); break; case 0 : console.log(i) break; default: console.log(i + " one_match"); } } } </code></pre>39729969185	0	 <p>Found the solution. The problem was the <code>labelunderscore</code> div that was created in the page. This "confuses" the jquery library as whilst it applying the slide in effect, it has to apply the slide out effect <strong>on the same div</strong>.</p> <p>The problem has been sorted by creating the <code>labelunderscore</code> div in the function at runtime and assigning it a unique id based on the id of the hovered element. Code as follows:</p> <pre><code>// Slide in effect for hover on class=head labels $(".head").hover(function () { //alert($(this).attr('id')) $('#main').append('&lt;div id="labelunderscore_' + $(this).attr("id") + '" class="labelunderscore"&gt;&lt;/div&gt;'); // Set width to hovering element width: $('#labelunderscore_' + $(this).attr("id")).css("width", $(this).width() + 20); // Set position on labelunderscore to current element left value $('#labelunderscore_' + $(this).attr("id")).css("left", $(this).offset().left); // Check where are we hovering. Left side slide from left right from right if ($(this).offset().left &gt; $(window).width()/2) { // We are on the right side $('#labelunderscore_' + $(this).attr("id")).show('slide', {direction: 'right'}, 200); } else { // Left side $('#labelunderscore_' + $(this).attr("id") ).show('slide', {direction: 'left'}, 200); } }, function () { $('#labelunderscore_' + $(this).attr("id")).hide('slide', {direction: 'left'}, 200); }) </code></pre>3981680067	0	 <p>I would recommend that you create another column in the database for arranging your items instead of using the OrderID - which is, I'm assuming here, may be used as a row identifier/ primary key for your database.</p> <p>I'll give you a scenario.</p> <p>Say you have the following items:</p> <ul> <li>Order ID 1- Orange</li> <li>Order ID 2 - Banana</li> <li>Order ID 3 - Apple</li> </ul> <p>And you have added another item:</p> <ul> <li>Order ID 4 - Grapes</li> </ul> <p>What if the user deletes Order ID 2 - Banana, and would want Order ID 4- Grapes to replace the deleted item in your list, how are you going to sort it by then? At least if you add another column, then you can preserve the sorting order for your items without touching your Order ID.</p> <p>On the other hand, if the Order ID is not the primary key for your table and you have a different primary key, then by all means use the Order ID as your sorting column. Make sure that you implement unique index for the sorting column so that it could enhance your db as well as application performance.</p> <p>To make your sorting a lot easier in .NET, you can use the classes in <a href="http://msdn.microsoft.com/en-us/library/system.collections.specialized.aspx" rel="nofollow noreferrer">System.Collections.Specialized Namespace</a> to sort your lists and want it for strongly-typed collections, i.e. Dictionary, OrderedDictionary, etc. because you will be using a key/value pair if you are implementing a sort order column.</p> <p>Hope this helps!</p>39926231138	0	Error in update ADT in Eclipse and IBM Worklight Studio <p>After update Android SDK I found this error message in Eclipse:</p> <blockquote> <p>This Android SDK requires Android Developer Toolkit version 23.0.0 or above. Current version is 22.6.3.v201404151837-1123206. Please update ADT to the latest version.</p> </blockquote> <p>In Stackoverflow are several very complete answer to this problem like <a href="http://stackoverflow.com/questions/24437564/update-eclipse-with-android-development-tools-v-23">here</a> and <a href="http://stackoverflow.com/questions/24583267/android-cannot-complete-the-install-because-of-a-conflicting-dependency/24583769#24583769">here</a>.<br> But I'm Working with Eclipse Kepler because is a requirement of IBM Worklight Studio.</p> <p>Have I to update ADT to the latest version? <br>IBM Worklight still working afterwards?</p>40024406553	0	Automatically send SCORM data to LMS <p>I have this code so far...</p> <pre><code>function sendData() { // this work out where I am and construct the 'cmi.core.lesson.location' variable computeTime(); var a = "" + (course.length - 1) + "|"; for (i = 1; i &lt; course.length; i++) { a = a + qbin2hex(course[i].pages).join("") + "|"; if (iLP == 1) { a = a + course[i].duration + "|"; a = a + course[i].timecompleted + "|" } } SetQuizDetails(); a = a + course[0].quiz_score_running + "|0|0|0|0|0|0|"; objAPI.LMSSetValue("cmi.core.lesson_location", "LP_AT7|" + a); bFinishDone = (objAPI.LMSCommit("") == "true"); objAPI.LMSCommit(""); console.log("Data Sent!"); } setTimeout(sendData(), 1000); </code></pre> <p>However, it doesn't seem to work as intented. Data should be sent off to the server every 1000ms, but that's not happening. What am I missing here?</p> <p>As I side note, this is SCORM 1.2.</p>4016673450	0	 <p>This is an example of an <a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Core_Language_Features#Object_Literals" rel="nofollow"><em>object literal</em></a>.</p> <p>It creates a normal object with two properties.</p>4025411974	0	 <p>Check if the proc belongs to a different schema than expexted.</p> <p>Something like myaccount.MyProc if it is expected to be dbo.MyProc </p>40325664859	0	 <p>Do not do that: <code>new FormInt64Control()</code>. Just don't. Only create form controls using <code>addControl</code>. </p> <p>To answer your question you need access to the C++ source code implementing the control. I do not have that access, nor do you.</p>40412479124	0	 <p>No, there aren't any changes in respect to custom action filters. Assuming you have controller/actions decorated with this attribute the <code>OnAuthorization</code> will always be called.</p>4059641029	0	 <p>You <em>might</em> be able to implement a <a href="http://developer.android.com/reference/android/app/admin/DeviceAdminReceiver.html#onPasswordFailed%28android.content.Context,%20android.content.Intent%29" rel="nofollow">DeviceAdminReceiver</a></p> <p>From it's description it should be notified of failed password attempts but it's not really clear from the description if that includes lock screen attempts.</p> <p>If that did work from a service or something you might be able to launch a toast though.</p> <hr> <p>[Edit] Found a better <a href="http://developer.android.com/guide/topics/admin/device-admin.html" rel="nofollow">resource</a></p>40627854464	0	Unable to change label text after presenting the view controller programmatically in swift <p>I am presenting the a view programmatically in if else statement using this code:</p> <pre><code>if (Condition) { ..... } else { var vc = self.storyboard?.instantiateViewControllerWithIdentifier("gameover") as UIViewController self.presentViewController(vc, animated: true, completion: nil) finalMsg.text="Thank you" } </code></pre> <p>So the view is getting changed but I am not able to change the text of label finalMsg which belongs to the view that I changed programmatically (gameover). </p> <p>I am getting error "fatal error: unexpectedly found nil while unwrapping an Optional value"</p> <p>Can someone help me on this? </p>40719797247	0	 <p>Have a look at this article: <a href="http://support.microsoft.com/kb/316871" rel="nofollow">HOW TO: Control Authorization Permissions in an ASP.NET Application</a></p> <p>In short you can set folder permissions like this:</p> <pre><code>&lt;configuration&gt; &lt;location path="images"&gt; &lt;system.web&gt; &lt;authorization&gt; &lt;deny users ="?" /&gt; &lt;/authorization&gt; &lt;/system.web&gt; &lt;/location&gt; &lt;/configuration&gt; </code></pre>40824999421	0	 <p>You can find source code in Appendix E of <a href="http://usir.salford.ac.uk/30721/1/Riadi_Thesis_2014_jan.pdf" rel="nofollow">this paper</a> explaining how to proceed for a variety of problems.</p> <p>The code is reproduced below in case the paper becomes lost to the Internet:</p> <pre><code>function result = acorPTcg() %Archive table is initialized by uniform random % clear all nVar = 10; nSize = 50; %size nAnts = 2; fopt = 0; %Apriori optimal q=0.1; qk=q*nSize; xi = 0.85; maxiter = 25000; errormin = 1e-04; %Stopping criteria %Paramaeter range Up = 0.5*ones(1,nVar); %range for dp function Lo = 1.5*ones(1,nVar); %Initialize archive table with uniform random and sort the result from %the lowest objective function to largest one. S = zeros(nSize,nVar+1,1); Solution = zeros(nSize,nVar+2,1); for k=1:nSize Srand = zeros(nVar); for j = 1:nAnts for i=1:nVar Srand(j,i) = (Up(i) - Lo(i))* rand(1) + Lo(i); %uniform distribution end ffbest(j)=dp(Srand(j,:)); %dp test function end [fbest kbest] = min(ffbest); S(k,:)=[Srand(kbest,:) fbest]; end %Rank the archive table from the best (the lowest) S = sortrows(S,nVar+1); %Select the best one as the best %Calculate the weight,w %the parameter q determine which solution will be chosen as a guide to %the next solution, if q is small, we prefer the higher rank %qk is the standard deviation % mean = 1, the best on w = zeros(1,nSize); for i=1:nSize w(i) = pdf('Normal',i,1.0,qk); end Solution=S; %end of archive table initialization stag = 0; % Iterative process for iteration = 1: maxiter %phase one is to choose the candidate base one probability %the higher the weight the larger probable to be chosen %value of function of each pheromone p=w/sum(w); ref_point = mean(Solution(:,nVar+1)); for i=1:nSize pw(i) = weight_prob(p(i),0.6); objv(i)= valuefunction(0.8,0.8, 2.25, ref_point-Solution(i, nVar+1)); prospect(i) = pw(i)*objv(i); end [max_prospect ix_prospect]=max(prospect); selection = ix_prospect; %phase two, calculate Gi %first calculate standard deviation delta_sum =zeros(1,nVar); for i=1:nVar for j=1:nSize delta_sum(i) = delta_sum(i) + abs(Solution(j,i)- ... Solution(selection,i)); %selection end delta(i)=xi /(nSize - 1) * delta_sum(i); end % xi has the same as pheromone evaporation rate. Higher xi, the lower % convergence speed of algorithm % do sampling from PDF continuous with mean chosen from phase one and % standard deviation calculated above % standard devation * randn(1,) + mean , randn = random normal generator Stemp = zeros(nAnts,nVar); for k=1:nAnts for i=1:nVar Stemp(k,i) = delta(i) * randn(1) + Solution(selection,i); %selection if Stemp(k,i)&gt; Up(i) Stemp(k,i) = Up(i); elseif Stemp(k,i) &lt; Lo(i); Stemp(k,i) = Lo(i); end end ffeval(k) =dp(Stemp(k,:)); %dp test function end Ssample = [Stemp ffeval']; %put weight zero %insert this solution to archive, all solution from ants Solution_temp = [Solution; Ssample]; %sort the solution Solution_temp = sortrows(Solution_temp,nVar+1); %remove the worst Solution_temp(nSize+1:nSize+nAnts,:)=[]; Solution = Solution_temp; best_par(iteration,:) = Solution(1,1:nVar); best_obj(iteration) = Solution(1,nVar+1); %check stopping criteria if iteration &gt; 1 dis = best_obj(iteration-1) - best_obj(iteration); if dis &lt;=1e-04 stag = stag + 1; else stag = 0; end end ftest = Solution(1,nVar+1); if abs(ftest - fopt) &lt; errormin || stag &gt;=5000 break end end plot(1:iteration,best_obj); clc title (['ACOR6 ','best obj = ', num2str(best_obj(iteration))]); disp('number of function eveluation') result = nAnts*iteration; %%------------------------------------------------------------- function value = valuefunction(alpha, beta, lambda, xinput) value =[]; n = length(xinput); for i=1:n if xinput(1,i) &gt;= 0 value(1,i) = xinput(1,i) ^ alpha; else value(1,i) = -lambda * (-xinput(1,i))^ beta; end end function prob = weight_prob(x, gamma) % weighted the probability % gamma is weighted parameter prob=[]; for i=1:length(x) if x(i) &lt; 1 prob(i) = (x(i)^(gamma))/((x(i)^(gamma) + (1-x(i))^(gamma))^(1/gamma)); %prob(i) = (x(i)^(1/gamma))/((x(i)^(1/gamma) + (1-x(i))^(1/gamma))^(1/gamma)); else prob(i) = 1.0; end end function y = dp(x) % Diagonal plane % n is the number of parameter n = length(x); s = 0; for j = 1: n s = s + x(j); end y = 1/n * s; </code></pre>40924336551	0	Charts in zend framework2 <p>I am working with zend framework 2 and i want to display charts in some views but it doesn't work!! This is my Action:</p> <pre><code>public function statvehAction(){ $data = [ 'labels' =&gt; ["January","February","March","April","May","June","July"], 'data' =&gt; [18,99,30,81,28,55,30] ]; json_encode($data); $viewModel = new ViewModel(array('data' =&gt; $data)); return $viewModel; } </code></pre> <p>this is my view:</p> <p> </p> <pre><code>&lt;script src="../../../../jquery.min.js"&gt;&lt;/script&gt; &lt;script src="../../../../chart.min.js"&gt;&lt;/script&gt; &lt;script&gt; (function($){ var ctx = document.getElementById("chart").getContext("2d"); $.ajax({ type: "POST", url: "VehiculesController.php", dataType: "json" }) .success(function(data) { var d = { labels: $data.labels, datasets : [ { fillColor: "rgba(220,220,220,0.5)", strokeColor: "rgba(220,220,220,1)", data: data.data }] }; var barChart = new Chart(ctx).Bar(d); }); })(jQuery); &lt;/script&gt; </code></pre> <p>But when i want to diplay my chart i got a white page whith no error !! Please can you help me to solve this problem.</p>41022814123	0	How to correctly affect multiple css properties in jquery <p>Below is an example of how I currently would affect two css properties for the same div in jquery:</p> <pre><code>$('#mydiv').css("width",myvar+"px"); $('#mydiv').css("margin-left",myvar+"px"); </code></pre> <p>I don't believe this to be the most efficient method as it requires two lines of code for one div, can somebody please show me a more susinct (tidier) method of writing the same thing?</p>41138263641	0	 <p>It may be model update problem try this.</p> <pre><code>$scope.$apply(); </code></pre>412900136	0	 <p>One way is to just have a copy of your database file (mdf) available for pushing onto a new server. This similiar to what microsoft does with it's Model database. Whenever you create a new database it starts by making a copy of that one.</p> <p>Your button click could copy the database file to the desired location, rename it as appropriate, then attach it to the running sql server instance. Whenever you need to update the database with a new schema, just copy the mdf to your deployment directory.</p>41317935206	0	How to layout correctly <p>I just try to create my own layout. I used <code>UITableView</code> for my <code>UIViewController</code>. I have some JSON response from server. This is like detailed publication. Also i calculate my <code>UITableViewCell</code> height because my publication contain mix of images and text. I wrote own layout and recalculate when device in rotation. </p> <pre><code>for (UIView * sub in contentSubviews) { if([sub isKindOfClass:[PaddingLabel class]]) { PaddingLabel *textPart = (PaddingLabel *)sub; reusableFrame = textPart.frame; reusableFrame.origin.y = partHeight; partHeight += textPart.frame.size.height; [textPart setFrame:reusableFrame]; } else if([sub isKindOfClass:[UIImageView class]]) { UIImageView * imagePart = (UIImageView *)sub; reusableFrame = imagePart.frame; reusableFrame.origin.y = partHeight; reusableFrame.origin.x = screenWidth/2 - imageSize.width/2; reusableFrame.size.width = imageSize.width; reusableFrame.size.height = imageSize.height; [imagePart setFrame:reusableFrame]; partHeight += imagePart.frame.size.height; } } </code></pre> <p>But I have some issue. When device change orientation state <code>UIScrollView</code> offset is same as was. I don't know how to change it. Before rotation:</p> <p><img src="https://i.stack.imgur.com/Is9aW.png" alt="enter image description here"></p> <p>After rotation:</p> <p><img src="https://i.stack.imgur.com/UiRf8.png" alt="enter image description here"></p> <p>I want to save visible elements in rect. Suggest pls.</p>4147389510	0	 <p>I also started to look at the <a href="http://mvcmusicstore.codeplex.com/" rel="nofollow">MVC Music Store</a> example.</p>41540953020	0	 <p>You don't have an instance of elasticsearch running failing to get to server at localhost:9200 indicates that.</p>41616297052	0	Replace a text with a variable (sed) <p>How can I do this?</p> <pre><code>sed -i 's/wiki_host/$host_name/g' /root/bin/sync </code></pre> <p>It will replace wiki_host with the text $host_name. But i want to replace it with the content of the variable..</p> <p>I tried it with</p> <pre><code>sed -i 's/wiki_host/${host_name}/g' /root/bin/sync </code></pre> <p>It doesnt work too..</p>41730050115	0	 <p>Use word boundaries:</p> <pre><code>Pattern p=Pattern.compile("\\b(1[0-9]|[0-9])\\b"); </code></pre>41814768853	0	 <p>If you take a look into the Android.mk file of OpenSSH you'll find the following line:</p> <pre><code>LOCAL_MODULE_TAGS := optional </code></pre> <p>This means that the module will be include into a build if the module name is listed in the appropriate make file (for instance, in a <code>build/target/product/core.mk</code>) </p>41935942849	0	 <p>If you want to use just 1 transaction and more then one EJB method call, then 1., use the session facade design pattern. Create a facae bean with CMT (Container Managed Transaction) to call the other beans within its own transaction. 2., Use BMT (Bean Managed Transaction)</p>42018281403	0	 <p>Try to use the "new" keyword instead of "override" and remove the "virtual" keyword from methods;)</p>4212512863	0	Have you been in cases where TDD increased development time? <p>I was reading <a href="http://stackoverflow.com/questions/2512504/tdd-how-to-start-really-thinking-tdd">TDD - How to start really thinking TDD?</a> and I noticed many of the answers indicate that tests + application should take less time than just writing the application. In my experience, this is not true. My problem though is that some 90% of the code I write has a TON of operating system calls. The time spent to actually mock these up takes <em>much</em> longer than just writing the code in the first place. Sometimes 4 or 5 times as long to write the test as to write the actual code.</p> <p>I'm curious if there are other developers in this kind of a scenario.</p>42234537143	0	SharedPreferences variable always returns false <p>I am using a Preference Fragments following the step by step guide on <a href="http://developer.android.com/intl/es/guide/topics/ui/settings.html#Fragment" rel="nofollow">Android guide</a>. </p> <p>I am trying to set some preferences using this fragment, so later on the code I can check the value of each variable to perform actions accordingle. </p> <p>Mi Preference fragment is working fine. However, when I try to recover the value of a CheckedBoxPreference somewhere else on the code, it always returns false.</p> <p>This is the preference xml file :</p> <pre><code>&lt;PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" android:persistent="true" &gt; &lt;PreferenceCategory android:title="NOTIFICACIONES" android:key="pref_key_storage_settings"&gt; &lt;CheckBoxPreference android:key="sendMail" android:defaultValue="false" android:persistent="true" android:summary="Send emails to contacts" android:title="E-mail"/&gt; &lt;/PreferenceCategory&gt; &lt;/PreferenceScreen&gt; </code></pre> <p>This is the class I've done to use SharedPReferences</p> <pre><code>public class Prefs{ private static Prefs myPreference; private SharedPreferences sharedPreferences; private static final String NOMBRE_PREFERENCIAS = "MisPreferencias"; public static Prefs getInstance(Context context) { if (myPreference == null) { myPreference = new Prefs(context); } return myPreference; } private Prefs(Context context) { sharedPreferences = context.getSharedPreferences(NOMBRE_PREFERENCIAS,context.MODE_PRIVATE); } public Boolean getBoolean(String key) { boolean returned = false; if (sharedPreferences!= null) { returned = sharedPreferences.getBoolean(key,false); } return returned; } } </code></pre> <p>And this is how I check if the options is selected, so I can send/or not emails to clients</p> <pre><code>Prefs preferences = Prefs.getInstance(getApplicationContext()); if(preferences.getBoolean("sendMail") { // .... send email } </code></pre> <p>As I said, what is strange is that It is persistent on the settings fragment ( if I select the option sendEmmail, it is selected even if I close the app and reopen it. However, when I check the value using my method, it always returns false.</p> <p>What am I doing wrong?</p> <p>Thank you</p>42314857267	0	VS regex search: Find Try..Finally with no Catch <p>I want to use the Regular Expression search in Visual Studio to find all instances of a Try/Finally block without a Catch.</p> <p>After reading the <a href="http://msdn.microsoft.com/en-us/library/2k3te2cs%28v=vs.80%29.aspx" rel="nofollow">help file</a>, I started with this which returns a match of <strong>Try</strong> without matching <strong>End Try</strong>.</p> <pre><code>~(End )Try\n </code></pre> <p>Then, I wanted to get a match where there was <strong>Finally</strong>:</p> <pre><code>~(End )Try\n*Finally\n </code></pre> <p>This actually doesn't work. </p> <p>The full, working Regex, I assume would look something like this:</p> <pre><code>~(End )(Sub|Function)*~(End )Try\n*~(Catch*\n)*Finally\n*End (Sub|Function) </code></pre> <p>That's try trying to say, within a Sub Or Function, return matches that have <strong>Try/Finally</strong> but no <strong>Catch</strong>.</p> <p>Am I in the ballpark for accomplishing this search?</p>4243998271	0	 <p>There is no difference in reading standard input from threads except if more than one thread is trying to read it at the same time. Most likely your threads are not all calling functions to read standard input all the time, though.</p> <p>If you regularly need to read input from the user you might want to have one thread that just reads this input and then sets flags or posts events to other threads based on this input.</p> <p>If the kill character is the only thing you want or if this is just going to be used for debugging then what you probably want to do is occasionally poll for new data on standard input. You can do this either by setting up standard input as non-blocking and try to read from it occasionally. If reads return 0 characters read then no keys were pressed. This method has some problems, though. I've never used <em>stdio.h</em> functions on a <code>FILE *</code> after having set the underlying file descriptor (an int) to non-blocking, but suspect that they may act odd. You could avoid the use of the <em>stdio</em> functions and use <code>read</code> to avoid this. There is still an issue I read about once where the block/non-block flag could be changed by another process if you forked and exec-ed a new program that had access to a version of that file descriptor. I'm not sure if this is a problem on all systems. Nonblocking mode can be set or cleared with a 'fcntl' call.</p> <p>But you could use one of the polling functions with a very small (0) timeout to see if there is data ready. The <code>poll</code> system call is probably the simplest, but there is also <code>select</code>. Various operating systems have other polling functions.</p> <pre><code>#include &lt;poll.h&gt; ... /* return 0 if no data is available on stdin. &gt; 0 if there is data ready &lt; 0 if there is an error */ int poll_stdin(void) { struct pollfd pfd = { .fd = 0, .events = POLLIN }; /* Since we only ask for POLLIN we assume that that was the only thing that * the kernel would have put in pfd.revents */ return = poll(&amp;pfd, 1, 0); } </code></pre> <p>You can call this function within one of your threads until and as long as it retuns 0 you just keep on going. When it returns a positive number then you need to read a character from stdin to see what that was. Note that if you are using the <em>stdio</em> functions on <code>stdin</code> elsewhere there could actually be other characters already buffered up in front of the new character. <code>poll</code> tells you that the operating system has something new for you, not what C's <em>stdio</em> has.</p> <p>If you are regularly reading from standard input in other threads then things just get messy. I'm assuming you aren't doing that (because if you are and it works correctly you probably wouldn't be asking this question).</p>4256659250	0	 <p>protobuf.net has to maintain compatibility with the protobuf binary format, which is designed for the Java date/time datatypes. No <code>Kind</code> field in Java -> No <code>Kind</code> support in the protobuf binary format -> <code>Kind</code> not transferred across the network. Or something along those lines.</p> <p>As it turns out, protobuf.net encodes the <code>Ticks</code> field (only), you'll find the code in <a href="http://code.google.com/p/protobuf-net/source/browse/trunk/protobuf-net/BclHelpers.cs#135" rel="nofollow"><code>BclHelpers.cs</code></a>.</p> <p>But feel free to add another field in your protobuf message definition for this value.</p>4269369592	0	 <p>Given that a family tree application has more to do with relationships between entities than the entities themselves, modeling this in a relational database would be the better fit.</p> <p>I release this does not answer your question, but at the end of the day we need to choose the most appropriate tool for the task.</p>42732066748	0	 <p>The statement <code>$scope.messages = messageOptions.slice(0, messageOptions.length);</code> create a clone/copy of array and assigning it to <code>$scope.messages</code></p> <p>You can also achieve same using</p> <pre><code> $scope.messages = messageOptions.slice(); </code></pre> <p><em>Code to demonstrate</em> </p> <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 messageOptions = [1, 2]; var messages = messageOptions.slice(0, messageOptions.length); //Update messageOptions[0] = 100; snippet.log("messages: " + JSON.stringify(messages)); snippet.log("messageOptions: " + JSON.stringify(messageOptions));</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --&gt; &lt;script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"&gt;&lt;/script&gt;</code></pre> </div> </div> </p>42834338418	0	 <p>Here's what I would do, making use of a <code>Person</code> class. It may not seem necessary right now given the scope of your project, but if the scope ever grows, using classes and instances will pay off. Plus, this way, you have the names to match the ages you're seeking which is probably going to be necessary at some point anyway.</p> <pre><code>public static List&lt;Person&gt; GetResults(string[] text) { var results = new List&lt;Person&gt;(); foreach(var line in text) { results.Add(Person.Parse(line)); } return results; } public class Person { public string Name { get; private set; } public int Age { get; private set; } public Person(string name, int age) { Name = name; Age = age; } public static Person Parse(string fromInputLine) { ValidateInput(fromInputLine); var delimPosition = fromInputLine.LastIndexOf(' '); var name = fromInputLine.Substring(0, delimPosition); var age = Convert.ToInt32(fromInputLine.Substring(delimPosition + 1)); return new Person(name, age); } private static void ValidateInput(string toValidate) { if (!System.Text.RegularExpressions.Regex.IsMatch(toValidate, @"^.+\s+\d+$")) throw new ArgumentException(string.Format(@"The provided input ""{0}"" is not valid.", toValidate)); } } </code></pre>42910090013	0	 <p><a href="http://www.iosdevnotes.com/2011/03/uiscrollview-paging/#comment-14154" rel="nofollow">This</a> is a relly good tutorial about UIScrollView&amp;IPageControl combination. But I my self look for a tutorail for more dynamic designs(like main page of ios applications-i increments-decrements automatically)</p>4304108113	0	php fopen: failed to open stream: HTTP request failed! HTTP/1.0 403 <p>I am receiving an error message in PHP 5 when I try to open a file of a different website. So the line</p> <pre><code>fopen("http://www.domain.com/somef­ile.php", r) </code></pre> <p>returns an error</p> <blockquote> <p>Warning: fopen(www.domain.com/somefile.php) [function.fopen]: failed to open stream: HTTP request failed! HTTP/1.1 403 Forbidden in D:\xampp\htdocs\destroyfiles\index.php on line 2</p> </blockquote>43130911184	0	Running use ant in java <p>Both compilation and JAR file creation is sucessful.</p> <p>Running java file through ant file is producing error.</p> <pre><code>&lt;project&gt; &lt;target name="clean"&gt; &lt;delete dir="build"/&gt; &lt;/target&gt; &lt;target name="compile"&gt; &lt;mkdir dir="build/classes"/&gt; &lt;javac srcdir="src" destdir="build/classes"/&gt; &lt;/target&gt; &lt;target name="jar"&gt; &lt;mkdir dir="build/jar"/&gt; &lt;jar destfile="build/jar/Helloworld" basedir="build/classes"&gt; &lt;manifest&gt; &lt;attribute name="Main-Class" value="Helloworld"/&gt; &lt;/manifest&gt; &lt;/jar&gt; &lt;/target&gt; &lt;target name="run"&gt; &lt;java jar="build/jar/Helloworld" fork="true"/&gt; &lt;/target&gt; &lt;/project&gt; </code></pre> <p>Buildfile: <code>C:\Workspace\anttest\build.xml</code></p> <pre><code>run: [java] java.lang.NoClassDefFoundError: Helloworld [java] Caused by: java.lang.ClassNotFoundException: Helloworld [java] at java.net.URLClassLoader$1.run(URLClassLoader.java:202) [java] at java.security.AccessController.doPrivileged(Native Method) [java] at java.net.URLClassLoader.findClass(URLClassLoader.java:190) [java] at java.lang.ClassLoader.loadClass(ClassLoader.java:306) [java] at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301) [java] at java.lang.ClassLoader.loadClass(ClassLoader.java:247) [java] Could not find the main class: Helloworld. Program will exit. [java] Exception in thread "main" [java] Java Result: 1 </code></pre> <p>BUILD SUCCESSFUL</p>4324645070	0	 <p>This is happening because the user 'sarin' is the actual owner of the database "dbemployee" - as such, they can <em>only</em> have db_owner, and cannot be assigned any further database roles.</p> <p>Nor do they need to be. If they're the DB owner, they already have permission to do anything they want to within this database.</p> <p>(To see the owner of the database, open the properties of the database. The Owner is listed on the general tab).</p> <p>To change the owner of the database, you can use <a href="http://msdn.microsoft.com/en-us/library/ms178630.aspx">sp_changedbowner</a> or <a href="http://msdn.microsoft.com/en-us/library/ms187359.aspx">ALTER AUTHORIZATION</a> (the latter being apparently the preferred way for future development, but since this kind of thing tends to be a one off...)</p>43317732610	0	 <p>This is just the way it is. <code>first</code> and <code>last</code> are not a complementary pair of operations. <code>last</code> is more closely related to <code>rest</code> and <code>nthcdr</code>. There is also <code>butlast</code> which constructs a new list that omits the last item from the given list.</p> <p><code>first</code> versus <code>last</code> is nothing compared to how <code>get</code> and <code>getf</code> have nothing to do with <code>set</code> and <code>setf</code>.</p>43431892188	0	 <p>You can overcome this easily by using the <code>ChoiceMode</code> option <code>CHOICE_MODE_MULTIPLE</code> for the <code>ListView</code> as used in the <a href="https://android.googlesource.com/platform/development/+/master/samples/ApiDemos/src/com/example/android/apis/view/List11.java?autodive=0%2F%2F" rel="nofollow">API Demo</a> -</p> <pre><code>public class List11 extends ListActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setListAdapter(new ArrayAdapter&lt;String&gt;(this, android.R.layout.simple_list_item_multiple_choice, GENRES)); final ListView listView = getListView(); listView.setItemsCanFocus(false); listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); } private static final String[] GENRES = new String[] { "Action", "Adventure", "Animation", "Children", "Comedy", "Documentary", "Drama", "Foreign", "History", "Independent", "Romance", "Sci-Fi", "Television", "Thriller" }; } </code></pre> <p><strong>EDIT</strong> Alternate for your context- Have an extra boolean object with your <code>HashMap&lt;String, Object&gt;</code> <code>isChecked</code> and initialize it to false when you populate your <code>list</code>.</p> <p>Set your <code>CheckBox</code> in <code>getView()</code> method as- </p> <pre><code>check.setChecked(Boolean.parseBoolean(dataMap.get("isChecked")); </code></pre> <p>Now in the listener <code>OnCheckedChangeListener()</code> set the value of your <code>dataMap</code> true or false accordingly.</p>43529351130	0	 <p>JSON string values should be quoted and so should parameter expansions. You can achieve this by using double quotes around the entire JSON string and escaping the inner double quotes, like this:</p> <pre><code>curl -i -H "Content-Type: application/json" -X POST -d "{\"mountpoint\":\"$final\"}" http://127.0.0.1:5000/connect </code></pre>4361784093	0	Get Application Pool Uptime in c# <p>Is there a way I can determine how long an application pool (in IIS7) has been up (time since started, or last restart) in c#?</p>4377790366	0	 <p>If you run your regex snippet in a C# program, I have the solution for you:</p> <pre class="lang-cs prettyprint-override"><code>Regex regex = new Regex(@"(?&lt;=\{{1}[\s\r\n]*)((?&lt;Attribute&gt;[^}:\n\r\s]+):\s+(?&lt;Value&gt;[^;]*);[\s\r\n]*)*(?=\})"); regex.Replace(input, match =&gt; { var replacement = string.Empty; for (var i = 0; i &lt; match.Groups["Attribute"].Captures.Count; i++) { replacement += string.Format(CultureInfo.InvariantCulture, "{0}: {1}\r\n", match.Groups["Attibute"].Captures[i], match.Groups["Value"].Captures[i]); } return replacement; }); </code></pre>43839913248	0	 <p>OpenCV uses by default the now very uncommon BGR (blue, green, red) ordering of the color channels. Normal is RGB. </p> <p><a href="http://stackoverflow.com/questions/14556545/why-opencv-using-bgr-colour-space-instead-of-rgb">Why OpenCV Using BGR Colour Space Instead of RGB</a></p> <p>This could explain the bad performance of the model.</p>43929143825	0	No SCM URL was provided to perform the release from <p>I am trying to use maven release plugin and after that automate this using nexus.</p> <p>Here is my pom.xml:</p> <pre><code>&lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;groupId&gt;com.ozge.net&lt;/groupId&gt; &lt;artifactId&gt;com.ozge.net&lt;/artifactId&gt; &lt;version&gt;1.1- snapshot&lt;/version&gt; &lt;build&gt; &lt;pluginManagement&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-release-plugin&lt;/artifactId&gt; &lt;version&gt;2.5.1&lt;/version&gt; &lt;configuration&gt; &lt;tagBase&gt;svn://local/exekuce/com.ozge.net&lt;/tagBase&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/pluginManagement&gt; &lt;/build&gt; &lt;scm&gt; &lt;tag&gt;HEAD&lt;/tag&gt; &lt;connection&gt;scm:svn:svn://[svnusername]:[svn password]@local/exekuce/com.ozge.net&lt;/connection&gt; &lt;developerConnection&gt;scm:svn:svn://[svnusername]:[svn password]@local/exekuce/com.ozge.net&lt;/developerConnection&gt; &lt;url&gt;scm:svn:svn://[svnusername]:[svn password]@local/exekuce/com.ozge.net&lt;/url&gt; &lt;/scm&gt; &lt;distributionManagement&gt; &lt;repository&gt; &lt;id&gt;OzgeRelease&lt;/id&gt; &lt;url&gt;http://localhost:8081/nexus/content/repositories/OzgeRelease&lt;/url&gt; &lt;/repository&gt; &lt;/distributionManagement&gt; &lt;/project&gt; </code></pre> <p>after I ran the command <code>mvn release:perform</code> on command prompt</p> <p>it says </p> <blockquote> <p>No SCM URL was provided to perform the release from</p> </blockquote> <p>I believe I provided.</p> <p>Anybody here tried to maven-subversion-nexus-hudson for automating builds?</p>4408087446	0	 <p>here you are</p> <pre><code>$("#bxs").on('click', 'li',function() { var exists = false for(var i=0;i&lt;result.length;i++) { var item = result[i]; if(item.id == $(this).prop("id")) { exists = true; break; } } if(exists) { alert("exists"); } else { alert("doesn't exists"); } }); </code></pre>44122901149	0	 <pre><code>if ($contract['Contract']['contract_maandag'] = 1){ if ($contract['Contract']['contract_dinsdag'] = 1){ </code></pre> <p>This won't work. You're doing an assignment (=), so it's always true. But you want a comparison (===). It is recommended to do always (except required otherwise) to use strict (===) comparison. </p>44248508	0	 <p>I can only once again point to <a href="http://www.research.att.com/~bs/new_learning.pdf" rel="nofollow noreferrer">Stroustrup</a> and preach: Don't teach the C subset! It's important, but not for beginners! C++ is complex enough as it is and the standard library classes, especially the STL, is much more important and (at least superficially) easier to understand than the C subset of C++.</p> <p>Same goes for pointers and heap memory allocation, incidentally. Of course they're important but only after having taught the STL containers.</p> <p>Another important concept that new students have to get their head around is the concept of different compilation units, the One Definition Rule (because if you don't know it you won't be able to decypher error messages) and headers. This is actually quite a barrier and one that has to be breached early on.</p> <p>Apart from the language features the most important thing to be taught is how to understand the C++ compiler and how to get help. Getting help (i.e. knowing how to search for the right information) in my experience is the single most important thing that has to be taught about C++.</p> <p>I've had quite good experiences with this order of teaching in the past.</p> <p>/EDIT: If you happen to know any German, take a look at <a href="http://madrat.net/coding/cpp/skript" rel="nofollow noreferrer">http://madrat.net/coding/cpp/skript</a>, part of a <em>very</em> short introduction used in one of my courses.</p>4436675225	0	Advantages of using Passenger + Apache over Webrick <p>I want to convince my management that using Apache + passenger setup is way to go on production rather than having webrick or mongrel</p> <p>I have found some points from the net. </p> <p>It would be great help if you could add your thoughts as that will defiantly help me to present my points. (technical details are welcome)</p> <p>and It will great if you could send some links if you have any</p> <p>thanks in advance</p> <p>cheers</p> <p>sameera</p>44436609262	0	 <p>You have two class attributes on each of your menu items. The second one is being ignored by jQuery.</p> <pre><code>&lt;a class="list-group-item allnotif" href="#allnotif"&gt;&lt;strong&gt;Alle Notificaties&lt;/strong&gt;&lt;/a&gt; </code></pre> <p><strong><a href="https://jsfiddle.net/3puygh7h/" rel="nofollow">Working demo</a></strong></p>44533999562	0	 <p>You should use <code>ArrayList</code> rather than <code>Vector</code>. There is no simple way to convert though. One way is</p> <pre><code>ArrayList&lt;String&gt; list = new ArrayList&lt;String&gt;(); for (char a : x) list.add(String.valueOf(a)); </code></pre> <p><code>Arrays.asList</code> works for arrays of object references, not arrays of primitives like <code>char</code>.</p> <p>If you are using Java 8, another way is</p> <pre><code>List&lt;String&gt; list = IntStream.range(0, x.length) .mapToObj(i -&gt; String.valueOf(x[i])) .collect(Collectors.toList()); </code></pre>4465093338	0	 <p>Thinking in high level, this is what I'd do:</p> <p>Develop a decorator function, with which I'd decorate every event-handling functions.</p> <p>This decorator functions would take note of thee function called, and its parameters (and possibly returning values) in a unified data-structure - taking care, on this data structure, to mark Widget and Control instances as a special type of object. That is because in other runs these widgets won't be the same instances - ah, you can't even serialize a toolkit widget instances, be it Qt or otherwise.</p> <p>When the time comes to play a macro, you fill-in the gaps replacing the widget-representating object with the instances of the actually running objects, and simply call the original functions with the remaining parameters.</p> <p>In toolkits that have an specialized "event" parameter that is passed down to event-handling functions, you will have to take care of serializing and de-serializing this event as well.</p> <p>I hope this can help. I could come up with some proof of concept code for that (although I am in a mood to use tkinter today - would have to read a lot to come up with a Qt4 example).</p>44715875144	0	 <p>use</p> <pre><code> $this-&gt;m_user-&gt;delete($user_id); </code></pre> <p>Instead </p> <pre><code> $this-&gt;m_user-&gt;delete_user($user_id); </code></pre>4489779994	0	I just need someone to help me with a tiny actionscript error <p>I've made the hourly wages calculator, but there is one problem: I can't get it to calculate anything, so if you were to use this program; you would add your name, hours worked and wages. once you click the button, at the bottom with have your results. </p> <p>i'm trying to get it to say hi, "the person's name" you have this much... something like that.</p> <p>can anyone help me?</p> <p>thanks</p> <p>here is my code: </p> <pre><code>button.mouseChildren = false button.addEventListener(MouseEvent.CLICK, onClick); } private function onClick(event:MouseEvent):void { this.results.text = "Hi, " } } } </code></pre>4499628155	0	 <p>What i would do is look at it in an Object Oriented Perspective, which is what Java is all about. When i get stuck on a piece of code then i write it down. Think of what the objective of the code is. </p> <ul> <li><p>You probably have a class called Level. In this level class you could have a property called "unlocked" or the opposite "locked". Then when the user goes to your "play a level" screen or what have you, then only allow the user to see the levels that are unlocked. </p></li> <li><p>You also probably have a Player class of some sort so you could have a property called "unlockedLevels" which is of the type Level[]. So then all of the unlocked levels would be in this array of Levels.</p></li> </ul> <p>It is all about how your code is structured, structure and true Object Orientation are the most important things in Java. When you stray from Object Oriented Design then you can run into problems that should never have existed.</p>450978043	0	 <p>A module in the Python natural language toolkit (nltk) does naïve Bayesian classification: <a href="http://nltk.googlecode.com/svn/trunk/doc/api/nltk.classify.naivebayes-module.html" rel="nofollow noreferrer"><code>nltk.classify.naivebayes</code></a>.</p> <p><em>Disclaimer:</em> I know crap all about Bayesian classification, naïve or worldly.</p>45120799086	0	 <p>I finally chose to use <strong>websockets</strong> to solve my problem (with Ratchet). Like this, I can invoke my script from my browser passing the arguments I need to the executable file.</p> <p>PHP in CLI doesn't seem to have any problem with exec() on .exe files.</p>45232746403	0	Groovy script to transform xml to json <p>I have the following groovy script that transforms an xml into json.</p> <p><a href="http://stackoverflow.com/a/24647389/2165673">http://stackoverflow.com/a/24647389/2165673</a></p> <p>Here is my xml</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;Response xmlns=""&gt; &lt;ProgressResult xmlns:i="http://www.w3.org/2001/XMLSchema-instance"&gt; &lt;ErrorMessage&gt;error &lt;/ErrorMessage&gt; &lt;IsSuccessful&gt;false&lt;/IsSuccessful&gt; &lt;/ProgressResult&gt; &lt;/ProgressResponse&gt; </code></pre> <p>The JSON result i need is </p> <pre><code>{ "IsSuccessful" : "false", "ErrorMessage" : "Something Happened" } </code></pre> <p>but i am getting the following <a href="http://www.tiikoni.com/tis/view/?id=b4ce664" rel="nofollow">http://www.tiikoni.com/tis/view/?id=b4ce664</a></p> <p>I am trying to improve my groovy script but i just started using it and it has a steep learning curve. Can someone help direct me to the right direction?</p> <p>Thanks!!</p>45320498360	0	Android logcat errors on project <p>I'm trying to run a project in Android but it crashes upon trying to execute it: I don't really understand the logCat messages I get so I wanted to see if someone could help me out in understanding them.</p> <p>Here are some of my errors:</p> <pre><code>FATAL EXCEPTION: MAIN java.lang.RunTimeException: Unable to start activity componentInfo (com.example.logger/com.example.logger.ThirdActivity):java.lang.RuntimeException: your content must have a ListView whose id attribe is 'android.R.id.list'; Caused by: java.lang.RuntimeException: your content must have a ListView whose id attribute is 'android.R.id.list'; at.com.example.logger.ThirdActivity.onCreate (ThirdActivity:java:18) </code></pre> <p><strong>Android Manifest</strong></p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.logger" android:versionCode="1" android:versionName="1.0" &gt; &lt;uses-sdk android:minSdkVersion="8" android:targetSdkVersion="18" /&gt; &lt;application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" &gt; &lt;activity android:name="com.example.logger.MainActivity" android:label="@string/app_name" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.LAUNCHER" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;activity android:name="com.example.logger.SecondActivity" android:label="@string/title_activity_second" &gt;&lt;/activity&gt; &lt;activity android:name="com.example.logger.ThirdActivity" android:label="@string/title_activity_third" &gt; &lt;/activity&gt; &lt;/application&gt; &lt;/manifest&gt; </code></pre> <p><strong>End manifest</strong></p> <p><strong>Main Activity</strong></p> <pre><code>package com.example.logger; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; public class MainActivity extends Activity implements OnClickListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); attachHandlers(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } private void attachHandlers() { findViewById(R.id.login).setOnClickListener(this); } @Override public void onClick(View arg0) { if(arg0.getId() == R.id.login) { Intent i = new Intent(this, SecondActivity.class); startActivity(i); } } </code></pre> <p>}</p> <p><strong>End Main Activity</strong></p> <p><strong>SecondActivity</strong></p> <pre><code>package com.example.logger; import android.os.Bundle; import android.annotation.SuppressLint; import android.app.Activity; import android.app.Fragment; import android.app.FragmentManager; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.support.v4.app.FragmentStatePagerAdapter; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.Menu; import android.view.View; import android.widget.ImageView; import android.view.ViewGroup; public class SecondActivity extends Activity { private static final int NUM_PAGES = 10; private ViewPager mpager; private MyPagerAdapter mPagerAdapter; private int [] pics = {R.drawable.android_interfaz_layout_estructura_final, R.drawable.baixa, R.drawable.baixada, R.drawable.greenprogressbar, R.drawable.layout_keyboard, R.drawable.linerlay, R.drawable.merge1, R.drawable.o2zds, R.drawable.regbd, R.drawable.s7qrs}; @SuppressLint("NewApi") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); mPagerAdapter = new MyPagerAdapter(null); mpager = (ViewPager) findViewById(R.id.viewer); mpager.setAdapter (mPagerAdapter); } public void showImage (int position, View view) { //View is your view that you returned from instantiateItem //and position is it's position in array you can get the image resource id //using this position and set it to the ImageView } private class MyPagerAdapter extends PagerAdapter { SecondActivity activity; public MyPagerAdapter (SecondActivity activity){ this.activity=activity; } @Override public int getCount() { // TODO Auto-generated method stub return pics.length; } @Override public boolean isViewFromObject(View arg0, Object arg1) { // TODO Auto-generated method stub return false; } @Override public Object instantiateItem(View collection, int position) { ImageView view = new ImageView (SecondActivity.this); view.setImageResource (pics[position]); ((ViewPager) collection).addView(view, 0); return view; } @Override public void setPrimaryItem (ViewGroup container, int position, Object object) { super.setPrimaryItem (container, position, object); activity.showImage(position,(View)object); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.second, menu); return true; } private OnClickListener mPageClickListener = new OnClickListener() { public void onClick (View v) { // TODO Auto-generated method stub //aquí anirà la funció per traslladar la image de la gallery a la pantalla Integer picId = (Integer) v.getTag(); mpager.setVisibility(View.VISIBLE); mpager.setCurrentItem(v.getId()); } @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub } }; </code></pre> <p>}</p> <p><strong>End Second Activity</strong></p> <p><strong>Third Activity</strong></p> <pre><code>package com.example.logger; import android.os.Bundle; import android.app.Activity; import android.app.ListActivity; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; public class ThirdActivity extends ListActivity implements OnClickListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_third); final ListView listview = (ListView) findViewById(android.R.id.list); String[] values = new String[] {"One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen", "Twenty"}; ArrayAdapter&lt;String&gt; adapter = new ArrayAdapter&lt;String&gt;(this, R.layout.activity_third, android.R.id.list, values); setListAdapter(adapter); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.third, menu); return true; } public void attachButton() { findViewById(R.id.add).setOnClickListener(this); } @Override public void onClick(View v) { // TODO Auto-generated method stub } </code></pre> <p>}</p> <p><strong>End Third Activity</strong></p> <p><strong>Activity_Main.xml</strong></p> <pre><code>&lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:orientation="vertical" tools:context=".MainActivity" &gt; &lt;Button android:id="@+id/login" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/Login" android:layout_alignParentBottom="true" android:background="@drawable/shapes" android:textColor="@color/text" /&gt; &lt;EditText android:id="@+id/username" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/input_u" android:layout_marginTop="10dp" android:textColor="@color/text" /&gt; &lt;EditText android:id="@+id/password" android:layout_below="@+id/username" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/input_p" android:layout_marginTop="10dp" android:textColor="@color/text" /&gt; &lt;/RelativeLayout&gt; </code></pre> <p><strong>End Activity_Main.xml</strong></p> <p><strong>Activity_Second.xml</strong></p> <pre><code>&lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".SecondActivity" &gt; &lt;android.support.v4.view.ViewPager android:padding="16dp" android:id="@+id/viewer" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:layout_weight="0.70" /&gt; &lt;ImageView android:id="@+id/big_image" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:layout_below="@+id/viewer" android:layout_weight="0.30" /&gt; &lt;/RelativeLayout&gt; </code></pre> <p><strong>End Activity_Second.xml</strong></p> <pre><code>**Activity_Third.xml** &lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".ThirdActivity" &gt; &lt;Button android:id="@+id/add" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:text="@string/add" /&gt; &lt;ListView android:id="@+id/list" android:layout_width="match_parent" android:layout_below="@+id/add" android:layout_height="wrap_content" &gt;&lt;/ListView&gt; &lt;/RelativeLayout&gt; </code></pre> <p><strong>End Activity_Third.xml</strong></p> <p>I'd very grateful if someone could help me figure out what I'm doing wrong on this project.</p> <p>Yours sincerely,</p> <p>Mauro.</p>4545198155	0	Not all tiles redrawn after CATiledLayer -setNeedsDisplay <p>My view has a <code>CATiledLayer</code>. The view controller has custom zooming behavior, so on <code>-scrollViewDidEndZooming</code> every tile needs to be redrawn. But, even though <code>-setNeedsDisplay</code> is being called on the layer after every zoom, not all tiles are being redrawn. This is causing the view to sometimes look wrong after a zoom. (Things that should appear in just 1 tile are appearing in multiple places). It often corrects itself after another zoom. </p> <p>Here's the relevant code. <code>updatedRects</code> is for testing -- it stores the unique rectangles requested to be drawn by <code>-drawLayer</code>. </p> <p>CanvasView.h: </p> <pre><code>@interface CanvasView : UIView @property (nonatomic, retain) NSMutableSet *updatedRects; @end </code></pre> <p>CanvasView.m: </p> <pre><code>@implementation CanvasView @synthesize updatedRects; + (Class)layerClass { return [CATiledLayer class]; } - (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)context { CGRect rect = CGContextGetClipBoundingBox(context); [updatedRects addObject:[NSValue valueWithCGRect:rect]]; CGContextSaveGState(context); CGContextTranslateCTM(context, rect.origin.x, rect.origin.y); // ...draw into context... CGContextRestoreGState(context); } @end </code></pre> <p>MyViewController.m: </p> <pre><code>@implementation MyViewController - (void)viewDidLoad { [super viewDidLoad]; canvasView.updatedRects = [NSMutableSet set]; } - (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(float)scale { canvasView.transform = CGAffineTransformIdentity; canvasView.frame = CGRectMake(0, 0, canvasView.frame.size.width * scale, canvasView.frame.size.height); [self updateCanvas]; } - (void)updateCanvas { NSLog(@"# rects updated: %d", [canvasView.updatedRects count]); [canvasView.updatedRects removeAllObjects]; canvasView.frame = CGRectMake(canvasView.frame.origin.x, canvasView.frame.origin.y, canvasView.frame.size.width, myHeight); CGFloat tileSize = 256; NSLog(@"next # rects updated will be: %f", [canvasView.layer bounds].size.width / tileSize); [canvasView.layer setNeedsDisplay]; } @end </code></pre> <p>When testing this, I always scrolled all the way across the view after zooming to make sure every tile was seen. Whenever the view looked wrong, the predicted "next # of rects updated" was greater than the actual "# of rects updated" on the next call to <code>-updateCanvas</code>. What would cause this? </p> <p><strong>Edit:</strong> </p> <p>Here's a better way to visualize the problem. Each time <code>updateCanvas</code> is called, I've made it change the background color for drawing tiles and record the time it was called -- the color and time are stored in <code>canvasView</code>. On each tile is drawn the tile's rectangle, the tile's index along the x axis, the time (sec.) when the background color was set, and the time (sec.) when the tile was drawn. If everything is working correctly, all tiles should be the same color. Instead, here's what I'm sometimes seeing: </p> <p><img src="https://i.stack.imgur.com/k2BjY.png" alt="Screenshot of tiles with mismatched colors"> <img src="https://i.stack.imgur.com/6GzNS.png" alt="Screenshot of tiles with mismatched colors"></p> <p>I only seem to see wrong results after zooming out. <strike>The problem might be related to the fact that <code>scrollViewDidEndZooming</code>, and therefore <code>updateCanvas</code>, can get called multiple times per zoom-out.</strike> (<strong>Edit</strong>: No-- not called multiple times.) </p>455661733	0	 <p>If you are running Time Machine on Leopard (OS X 10.5) then you have a chance that the files are in the backup. By default Time Machine backs up every hour so unless the files were created and deleted between backups then you should have something.</p>45628711174	0	Showing message after customer is redirected to logout page magento <p>I have a problem here. I want to show a message to the customer after his/her session is out. Let me explain in detail. I have a case, at first the customer is logged in when the customer clicks the "My Account" he/she is redirected to customer login page.Here i want to show the message that "your session is out please log in again".</p> <p>One method i tried is to check the customer session in indexAction() in AcountController.php but this redirection is not taking place from this indexAction().</p> <p>I am guessing that this redirection is taking somewhere from the block because "My Account" link is added through the xml file using "addLink" method.But i couldn't figure it out.</p> <p>Has anyone faced such problem and has solved it. Can anyone provide me with some insights so i can fix it.</p>45720752692	0	 <p><strong>HTML</strong></p> <pre><code>&lt;div id='mydiv'&gt;Lorem&lt;span&gt; ipsum&lt;/span&gt; dolor amet&lt;/div&gt; </code></pre> <p><strong>JS/Jquery</strong></p> <pre><code>var elm = $('#mydiv'); highlite(elm, 2, 28); //specify the start and end position // if you know the word you can find the index of word using indexOf/lastIndexOf function highlite(element, startpos, endpos) { var rgxp = elm.html().substr(startpos,endpos) var repl = '&lt;span class="myClass"&gt;' + rgxp + '&lt;/span&gt;'; elm.html(elm.html().replace(rgxp, repl)); } </code></pre> <p><strong>Demo</strong></p> <p><a href="http://jsfiddle.net/raunakkathuria/sD2pX/" rel="nofollow">http://jsfiddle.net/raunakkathuria/sD2pX/</a></p>45822358491	0	 <p>HANDLE_MSG macro is defined in Windowsx.h header.</p> <p>Note: To use message cracker for WM_NOTIFY you must use HANDLE_WM_NOTIFY macro defined in commctrl.h header.</p>45932731041	0	 <p>You should create a variable containing the \n:</p> <pre><code>(bind ?newline " ") </code></pre> <p>and then use it in str-cat or sym-car or other places.</p> <pre><code>(bind ?a (sym-cat ?a ?newline)) </code></pre>46032560451	0	 <p>Maybe what you want is like this : </p> <pre><code>public void startApp(){ primaryStage.show(); new Thread(new Runnable(){ @Override public void run() { try { Thread.sleep(20000);//2 seconds } catch (InterruptedException e) { e.printStackTrace(); } //do something......... System.out.println("all things done"); } }).run(); } </code></pre> <p>You need to implement the method <code>run()</code> of <code>Runnable</code></p>46113594906	0	Executing an API call in Android <p>I am trying to make an API call to the address: apps.smilemachine.com/smilefactory/api/v1.0/speedup. I just want to execute the url (above) so that it increments the machine and changes the speed value stored at Smilemachine.com? Nothing special I just need to execute the url as if you were typing it into the address bar in any browser?</p> <p>Has anyone got any advice for this or code snippets?</p> <p>My current code just opens the browser, please find below:</p> <pre><code>increasespeed.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { Intent increasespeed = new Intent(null, Uri.parse("http://apps.smilemachine.com/smilefactory/api/v1.0/speedup")); startActivity(increasespeed); } }); </code></pre>4622935604	0	Qt cross thread call <p>I have a Qt/C++ application, with the usual GUI thread, and a network thread. The network thread is using an external library, which has its own select() based event loop... so the network thread isn't using Qt's event system.</p> <p>At the moment, the network thread just emit()s signals when various events occur, such as a successful connection. I think this works okay, as the signals/slots mechanism posts the signals correctly for the GUI thread.</p> <p>Now, I need for the network thread to be able to call the GUI thread to ask questions. For example, the network thread may require the GUI thread to request put up a dialog, to request a password.</p> <p>Does anyone know a suitable mechanism for doing this?</p> <p>My current best idea is to have the network thread wait using a QWaitCondition, after emitting an object (<code>emit passwordRequestedEvent(passwordRequest);</code>. The passwordRequest object would have a handle on the particular QWaitCondition, and so can signal it when a decision has been made..</p> <p>Is this sort of thing sensible? or is there another option?</p>4636362068	0	 <p>This website is answer to my question: <a href="http://embed.ly/" rel="nofollow">http://embed.ly/</a> :)</p>46415532242	0	error while installing WindowBuilder Pro Update Site - http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7 <p>I faced this error while installing <a href="http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7" rel="nofollow">http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7</a> on eclipse Juno Service Release 1 </p> <pre><code>An error occurred while collecting items to be installed session context was:(profile=epp.package.jee, phase=org.eclipse.equinox.internal.p2.engine.phases.Collect, operand=, action=). Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/com.google.gdt.eclipse.designer_2.6.0.r37x201206111227.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/com.google.gdt.eclipse.designer.GWTExt_2.6.0.r37x201206111253.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/com.google.gdt.eclipse.designer.GXT_2.6.0.r37x201206111253.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/com.google.gdt.eclipse.designer.GXT.databinding_2.6.0.r37x201206111253.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/com.google.gdt.eclipse.designer.SmartGWT_2.6.0.r37x201206111253.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/com.google.gdt.eclipse.designer.UiBinder_2.6.0.r37x201206111227.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/com.google.gdt.eclipse.designer.UiBinder.wizards_2.6.0.r37x201206111253.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/com.google.gdt.eclipse.designer.doc.user_2.6.0.r37x201206111253.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/features/com.google.gdt.eclipse.designer.editor.feature_2.6.0.r37x201206111227.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/features/com.google.gdt.eclipse.designer.feature_2.6.0.r37x201206111253.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/com.google.gdt.eclipse.designer.hosted_2.6.0.r37x201206111222.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/com.google.gdt.eclipse.designer.hosted.2_0_2.6.0.r37x201206111222.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/com.google.gdt.eclipse.designer.hosted.2_0.super_2.6.0.r37x201206111222.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/com.google.gdt.eclipse.designer.hosted.2_0.webkit_2.6.0.r37x201206111222.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/com.google.gdt.eclipse.designer.hosted.2_0.webkit_win32x64_2.6.0.r37x201206111222.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/com.google.gdt.eclipse.designer.hosted.2_2_2.6.0.r37x201206111222.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/com.google.gdt.eclipse.designer.hosted.2_2.webkit_2.6.0.r37x201206111222.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/features/com.google.gdt.eclipse.designer.hosted.feature_2.6.0.r37x201206111222.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/com.google.gdt.eclipse.designer.hosted.lib_2.6.0.r37x201206111222.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/com.google.gdt.eclipse.designer.launch_2.6.0.r37x201206111253.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/com.google.gdt.eclipse.designer.preferences_2.6.0.r37x201206111253.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/com.google.gdt.eclipse.designer.wizards_2.6.0.r37x201206111253.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/org.eclipse.wb.rcp_1.5.0.r37x201206111317.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/org.eclipse.wb.rcp.GroupLayout_1.5.0.r37x201206111330.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/features/org.eclipse.wb.rcp.GroupLayout_support.feature_1.5.0.r37x201206111330.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/org.eclipse.wb.rcp.SWT_AWT_1.5.0.r37x201206111333.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/features/org.eclipse.wb.rcp.SWT_AWT_support_1.5.0.r37x201206111333.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/org.eclipse.wb.rcp.databinding_1.5.0.r37x201206111317.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/org.eclipse.wb.rcp.databinding.emf_1.5.0.r37x201206111317.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/org.eclipse.wb.rcp.databinding.xwt_1.5.0.r37x201206111323.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/org.eclipse.wb.rcp.doc.user_1.5.0.r37x201206111236.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/features/org.eclipse.wb.rcp.doc.user.feature_1.5.0.r37x201206111236.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/features/org.eclipse.wb.rcp.feature_1.5.0.r37x201206111317.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/org.eclipse.wb.rcp.nebula_1.5.0.r37x201206111317.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/org.eclipse.wb.rcp.swing2swt_1.5.0.r37x201206111317.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/org.eclipse.wb.swt_1.5.0.r37x201206111304.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/features/org.eclipse.wb.swt.feature_1.5.0.r37x201206111304.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/org.eclipse.wb.swt.layout.grouplayout_1.5.0.r37x201206111330.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/org.eclipse.wb.swt.widgets.baseline_1.5.0.r37x201206111317.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/org.eclipse.wb.xwt_1.5.0.r37x201206111323.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/features/org.eclipse.wb.xwt.feature_1.5.0.r37x201206111323.jar dl.google.com </code></pre>46537482250	0	Dropdown menu isn't working <p>I'm doing a Menu where it has four dropdown buttons that aren't working. The following image shows how it is supposed to work: "<em>Bijutaria</em>=(perfumes+fios)"<br> "<em>Inserir</em>=(<em>Perfumes</em>=homem+mulher)+<em>Bijutaria</em>=fios+pulseiras)"</p> <p><img src="https://i.imgur.com/Qh5oYDm.png?1" alt=""></p> <p>I think the problem is located in my CSS code, but I'm not being able to figure out what the problem is.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>ul { margin: 0; padding: 0; list-style: none; width: 150px; } ul li { position: relative; } li ul { position: absolute; left: 120px; top: 0; display: none; } ul li a { display: block; text-decoration: none; color: #E2144A; background: #fff; padding: 5px; border: 1px solid #ccc; } li:hover ul { display: block; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;ul id="left" class='column'&gt; &lt;li&gt;&lt;a href="ver.php"&gt;Home&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Bijutaria&lt;/a&gt;&lt;/li&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="pulseiras.php"&gt;Pulseiras&lt;/a&gt; &lt;/li&gt; &lt;li&gt;&lt;a href="fios.php"&gt;Fios&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;li&gt;&lt;a href="#"&gt;Perfumes&lt;/a&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="prfh.php"&gt;Homem&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="prfm.php"&gt;Mulher&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;li&gt;&lt;a href="#"&gt;Inserir&lt;/a&gt;&lt;/li&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="#"&gt;Perfumes&lt;/a&gt;&lt;/li&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="insrph.php"&gt;Homem&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="insrpm.php"&gt;Mulher&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;li&gt;&lt;a href="#"&gt;Bijutaria&lt;/a&gt;&lt;/li&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="insrp.php"&gt;Pulseiras&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="insrf.php"&gt;Fios&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt;</code></pre> </div> </div> </p>46629019976	0	 <p>Where you will have a problem is when find descends into subdirectories, and it tries to exec something like <code>cp ./foo/bar.txt /new/path/./foo/bar.txt</code> and "/new/path" has no subdirectory "foo" -- you might want to:</p> <ul> <li><p>specify <code>-maxdepth 1</code> so you do not descend into subdirs</p> <pre><code>find . -maxdepth 1 -type f -exec cp {} /new/path/{} \; </code></pre></li> <li><p>just use a directory destination for <code>cp</code>, so the files end up in a single dir (will suffer from collisions if you have "./foo/bar.txt" and "./qux/bar.txt")</p> <pre><code>find . -type f -exec cp -t /new/path {} + </code></pre></li> <li><p>use <code>tar</code> to copy the whole tree: this will preserve directory structure</p> <pre><code>tar cf - . | ( cd /new/path &amp;&amp; tar xvf - ) </code></pre></li> </ul>4673917587	0	 <p>Have you tried <a href="http://developers.facebook.com/docs/reference/fql/" rel="nofollow">FQL</a>? Using this I was able to get users display pictures on any site I wanted by simply constructing a simple SQL like query.</p>4682228489	0	image thumb list with opacity changes and add class/remove class on click <p>I got the script from another post on here, but for some reason it isn't working quite correctly on my implementation of it. Everything works fine except for stripping of the "selected" class, therefore the thumbnails all stay highlighted after being clicked. Easiest way is to show in context:</p> <p><a href="http://www.studioimbrue.com/beta" rel="nofollow noreferrer">http://www.studioimbrue.com/beta</a></p> <p>I changed it around a bit trying to figure out the problem but I couldn't find anything.</p>469663380	0	 <p>This is going to sound strange, but does the view/table have a column named "1"?</p>47012896034	0	 <p>LESS provides the ability to use previously defined classes as mixins in other contexts. Try this:</p> <pre><code>.theme-dark { .navbar { .navbar-inverse; } } </code></pre>47126383784	0	View not refreshing following post in Razor MVC using datatable <p>As per subject. The view looks like this.</p> <pre><code>@using System.Globalization @model IEnumerable&lt;TaskEngine.WebUI.Models.TaskViewModel&gt; &lt;script src="../../Scripts/progress-task.js" type="text/javascript"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; $(document).ready(function () { $.ajax({ url: '@Url.Action("Index", "Home")', data: { from: "10/01/2014", to: "10/14/2014" }, dataType: "html", success: function () { alert('Success'); }, error: function (request) { alert(request.responseText); } }); }); &lt;/script&gt; &lt;div class="container"&gt; &lt;div class="row"&gt; &lt;div class="span16"&gt; &lt;div id="sitename"&gt; &lt;a href="/" id="logo"&gt;xxxxxxxx&lt;/a&gt; &lt;span class="name"&gt;Workbasket&lt;/span&gt; &lt;/div&gt; &lt;div class="row"&gt; &lt;div class="span16"&gt; &lt;table class="table table-striped table-condensed" id="task-table"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th class="left"&gt;Client&lt;/th&gt; &lt;th class="left"&gt;Task&lt;/th&gt; &lt;th class="left"&gt;State&lt;/th&gt; &lt;th class="left"&gt;Assigned By&lt;/th&gt; &lt;th class="left"&gt;Assigned To&lt;/th&gt; &lt;th class="left"&gt;Date Opened&lt;/th&gt; &lt;th class="left"&gt;Date Due&lt;/th&gt; @* &lt;th class="left"&gt;Date Closed&lt;/th&gt;*@ &lt;th class="left"&gt;Outcomes&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; @foreach (var task in Model) { &lt;tr&gt; &lt;td&gt;&lt;span&gt;@task.ClientId&lt;/span&gt;&lt;/td&gt; &lt;td&gt;&lt;span class="nowrap"&gt;@task.TaskDescription&lt;/span&gt;&lt;/td&gt; &lt;td&gt;&lt;span class="nowrap"&gt;@task.CurrentState&lt;/span&gt;&lt;/td&gt; &lt;td&gt;&lt;span &gt;@task.AssignedBy.Replace("CORPORATE\\", "").Replace(@".", " ")&lt;/span&gt;&lt;/td&gt; &lt;td&gt;&lt;span&gt;@task.AssignedTo.Replace("CORPORATE\\", "").Replace(@".", " ")&lt;/span&gt;&lt;/td&gt; &lt;td&gt;&lt;span&gt;@task.DateOpened.ToString("dd/MM/yyyy HH:mm")&lt;/span&gt;&lt;/td&gt; &lt;td&gt;&lt;span&gt;@task.DateDue.ToString("dd/MM/yyyy HH:mm")&lt;/span&gt;&lt;/td&gt; @* &lt;td&gt;&lt;span&gt;@(task.DateClosed.HasValue ? task.DateClosed.Value.ToShortDateString() : " - ")&lt;/span&gt;&lt;/td&gt;*@ &lt;td&gt; &lt;span class="nowrap"&gt; @Html.DropDownList( "Outcomes", new SelectList(task.Outcomes, "Id", "Name"), "---Please Select ---", new Dictionary&lt;string, object&gt; { {"data-case-id", @task.CaseId }, {"data-task-log-id", @task.TaskLogId}, {"data-client-id", @task.ClientId} }) &lt;/span&gt; &lt;/td&gt; &lt;/tr&gt; } &lt;/tbody&gt; &lt;/table&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="modal hide span8" id="complete-task-modal" tabindex="-1" role="dialog" aria-labelledby="complete-task-header" aria-hidden="true"&gt; &lt;div class="modal-header"&gt; &lt;button type="button" class="close" data-dismiss="modal" aria-hidden="true"&gt;×&lt;/button&gt; &lt;h3 id="complete-task-header"&gt;Complete Task&lt;/h3&gt; &lt;/div&gt; &lt;div class="modal-body"&gt; &lt;div class="row"&gt; &lt;div class="span8"&gt; &lt;div class="alert alert-info"&gt; &lt;label id="CurrentState"&gt;&lt;/label&gt; &lt;label id="NewState"&gt;&lt;/label&gt; &lt;label&gt;Generated Tasks&lt;/label&gt; &lt;ul id="task-list"&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;form id="form"&gt; &lt;input type="hidden" id="task-log-id" name="taskLogId" /&gt; &lt;input type="hidden" id="case-id" name="caseId" /&gt; &lt;input type="hidden" id="outcome-id" name="triggerId" /&gt; &lt;input type="hidden" id="client-id" name="clientId" /&gt; &lt;div id="popup"&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt; &lt;div class="modal-footer"&gt; &lt;button class="btn" id="close" data-dismiss="modal" aria-hidden="true"&gt;Go Back&lt;/button&gt; &lt;button class="btn btn-primary" id="confirm-task"&gt;Confirm&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>This is the controller method.</p> <pre><code> public ActionResult Index(DateTime? from, DateTime? to) { var usergroups = GetGroups(HttpContext.User.Identity.Name); var model = _taskLogger.GetTasks(from, to) .Select(task =&gt; new TaskViewModel { TaskLogId = task.TaskLogId, CaseId = task.CaseId, ClientId = task.ClientId, TaskDescription = task.Description, AssignedBy = task.AssignedBy, AssignedTo = task.AssignedTo.Trim(), DateOpened = task.DateCreated, DateClosed = task.DateClosed, DateDue = task.DateDue }).ToList() .Where(x =&gt; IsAvailableToUser(x.AssignedTo, usergroups)) .OrderBy(x =&gt; x.DateDue); foreach (var task in model) { var workflow = _workflowEngine.GetCase(task.CaseId); task.CurrentState = workflow.State.ToNonPascalString(); task.Outcomes = workflow.GetPermittedTriggers().OrderBy(x =&gt; x.Name).ToList(); } ModelState.Clear(); return View(model); } </code></pre> <p>When the model is returned following the ajax post, the dataset is different, as expected, however, within the datatable in the view it still displays the old data.</p> <p>Having done some googling on this issue, I've tried clearing the modelstate but that makes no difference and from what I've read, it only seems to affect HTMLHelpers anyway.</p> <p>I'm not sure if this is an issue with the datatable or just a refresh issue with the view itself. Any input would be appreciated.</p>4721328836	0	How can I include line numbers in a stack trace without a pdb? <p>We are currently distributing a WinForms app without .pdb files to conserve space on client machines and download bandwidth. When we get stack traces, we are getting method names but not line numbers. Is there any way to get the line numbers without resorting to distributing the .pdb files?</p>47321550489	0	 <p>Does it read the file while omitting the format argument?</p> <pre><code>x=read('g:\Work\WD\Debug\wd.txt',100,4) </code></pre> <p>I am suspecting it has something to do with your formatting string.</p> <pre><code>(5x,a2,3(5x,e12.4)) </code></pre> <p>Maybe have a look <a href="http://fortranwiki.org/fortran/show/Edit+descriptors" rel="nofollow">here</a> to learn more about Fortran format edit descriptors.</p>47429986258	0	How to render QuickBlox VideoStream into opponentVideoView and ownVideoView? <p>I have to accept video call(QuickBlox) anywhere from the application. for this I have create a singleton class in which I have implemented few Quick Blox delegate method for receiving call. after receiving call i present user to VideoCallController. But I am unable to render VideoStream into opponanenVideoView and myVideoView. Can anyone suggest me where I have to set VideoChat Property either in Singleton or VideoCallController.</p> <pre><code>self.videoChat.viewToRenderOpponentVideoStream = opponentVideoView; self.videoChat.viewToRenderOwnVideoStream = myVideoView; </code></pre>47528283134	0	 <p>Sounds easy enough. You just need to use jquery selectors to slice and dice to get the li into the correct position.</p> <p>Take a look at <a href="http://api.jquery.com/nth-child-selector/" rel="nofollow">nth-child() selector</a>.</p>47640950774	0	 <p>Remedy User Tool <strong>macro</strong> language is proprietary.</p> <p>Since Remedy User Tool is not supported anymore, I'd encourage you to use updated technologies, like SOAP or REST (for everything back-end), or AngularJS (for everything front-end)</p> <p>Another solution would be to use tools created by the Remedy Community, like the one appearing on <a href="https://communities.bmc.com/message/437693#437693" rel="nofollow noreferrer">https://communities.bmc.com/message/437693#437693</a></p>47731361842	0	Why layoutIfNeeded() allows to perform animation when updating constraints? <p>I have two states of <code>UIView</code>:</p> <p><img src="https://i.stack.imgur.com/iL91d.png" alt="enter image description here"> <img src="https://i.stack.imgur.com/xbnHn.png" alt="enter image description here"></p> <p>I have animation between them using <code>@IBaction</code> for <code>button</code>:</p> <pre><code>@IBAction func tapped(sender: UIButton) { flag = !flag UIView.animateWithDuration(1.0) { if self.flag { NSLayoutConstraint.activateConstraints([self.myConstraint]) } else { NSLayoutConstraint.deactivateConstraints([self.myConstraint]) } self.view.layoutIfNeeded() //additional line } } </code></pre> <p>Animation is working <strong>only when I add additional line</strong>:</p> <p>But when I remove that line, then my <code>UIView</code> is updated but without any animation, it happens immediately.</p> <p>Why this line makes such difference? How is it working?</p>47810864824	0	Organizing my papers in org-mode <p>I've just started using org-mode, and so far find it quite useful. I have a <em>very</em> large collection of technical papers in a directory tree, and I'd like to go through them and index them through org-mode. What I'd like is to have a way of going through them and look at the unannotated ones, and annotate them one by one. I imagine doing this by first making up a file of links like [[xxx.pdf][not done yet]], and then being presented with the not done ones, glancing at them and deciding how what annotations to put in. In addition I'd like to add tags. What I'd really like is to be able to make up new tags on the fly. Has anyone done anything like this in org-mode?</p> <p>Victor</p>47924588828	0	 <pre><code>request.update("growl"); </code></pre> <p>This is the wrong part.</p> <p>Put an id to your form, then reference it like</p> <p>i.e</p> <pre><code>request.update("your_for_mid:growl"); </code></pre> <p>Alternatively you could activate the auto-update feature of the growl with the attribute <code>autoUpdate="true"</code> of the growl component, and remove the <code>request.update()</code> method call in your backing bean.</p>48028371485	0	No debug option in VBA runtime error <p>I am using excel 2013. I do not get any debug option when there is a runtime error. How can I get a debug option during runtime errors?</p> <p>Edit - I have realized that I have this problem only in the following instance. Normally I am getting the debug option (except for this case). What is especially painful is that it doesn't even tell me which line the error is on.</p> <p>screenshot of error -</p> <p>Code is as follows -</p> <pre><code>Option Explicit Option Base 1 Sub doit() Dim intRowCounter As Long Dim intColCounter As Long Dim parentFormula As String Dim resultantFormulas As String For intRowCounter = 1 To 100 For intColCounter = 1 To 200 'This is the line giving the error parentFormula = Right(parentFormula, Len(parentFormula) - 1) Next intColCounter Next intRowCounter End Sub </code></pre> <p>Screenshot of the error <a href="https://imgur.com/gC32z74" rel="nofollow noreferrer">http://imgur.com/gC32z74</a></p> <p><img src="https://i.stack.imgur.com/fwXVf.png" alt="enter image description here"></p>48132392463	0	 <p>well, you want to hide the fields in the gridfield detail form? that cannot be done in your pages <code>getCMSFields()</code>, as the grid is responsible for generating the detail form. Two possible solutions:</p> <p>1) tell the grid to hide that fields with a custom component. I dunno how to do it</p> <p>2) tell your Rotator class to show the fields ONLY if the related page is a homepage:</p> <pre><code>public function getCMSFields() { $fields = parent::getCMSFields(); //...other stuff.... $isOnHomePage = ($this-&gt;Page() &amp;&amp; $this-&gt;Page()-&gt;ClassName == 'HomePage'); //put in your own classname or conditions if(!$isOnHomePage) { //remove the fields if you're not on the HomePage $fields-&gt;removeByName('Body'); //we need to suffix with "ID" when we have a has_one relation! $fields-&gt;removeByName('BackGroundImageID'); } return $fields; } </code></pre>48231238631	0	Refreshing html table using Jquery Java built on Codeigniter <p>Guys I have a data coming from an outsource table which I'm presenting in table. The original data coming in Json which I'm decoding using PHP function and displaying.</p> <p>I have been googling for auto refreshing that data and found this <a href="http://stackoverflow.com/questions/8128877/auto-refresh-table-without-refreshing-page-php-mysql">Auto refresh table without refreshing page PHP MySQL</a></p> <p>I have managed to built what is suggested in the Ticked answers and seems like working for the first time but it doesn't refresh. So when page is loaded</p> <p>I'm calling this </p> <pre><code>$(document).ready (function () { var updater = setTimeout (function () { $('div#user_table').load ('get_new_data', 'update=true'); /* location.reload(); */ }, 1000); }); </code></pre> <p>Which loads a function named get_new_data from controller file and loads on to</p> <pre><code> &lt;div class="container-fluid" id="user_table"&gt; &lt;/div&gt; </code></pre> <p>Codeigniter controller function is</p> <pre><code> public function get_new_data(){ $url = 'https://gocleanlaundry.herokuapp.com/api/users/'; $result = $this-&gt;scripts-&gt;get_data_api($url); $data_row = $result; $tbl = ''; $tbl .= '&lt;table class="table table-striped table-responsive" id="tableSortableRes"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;Name&lt;/th&gt; &lt;th&gt;Email Address&lt;/th&gt; &lt;th&gt;Role&lt;/th&gt; &lt;th&gt;Status&lt;/th&gt; &lt;th&gt;Action&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt;'; foreach($data_row as $row){ $tbl .= '&lt;tr class="gradeX"&gt; &lt;td&gt;' . $row-&gt;name . '&lt;/td&gt; &lt;td&gt;' . $row-&gt;email . '&lt;/td&gt; &lt;td&gt;' . $row-&gt;role . '&lt;/td&gt; &lt;td&gt;&lt;p id="' . $row-&gt;_id. '_status"&gt;'.( $row-&gt;alive == true ? 'Active' : 'Banned').' &lt;/p&gt;&lt;/td&gt; &lt;input id="' . $row-&gt;_id . 'status_val" value="' . $row-&gt;alive . '" type="hidden"&gt; &lt;td class="center"&gt; &lt;a href="#" id="' . $row-&gt;_id . '_rec" onclick="UpdateStatus(' . $row-&gt;_id . ')" class="btn btn-mini "&gt;' . ($row-&gt;alive == '1' ? '&lt;i class="fa fa-thumbs-o-up fa-fw"&gt;&lt;/i&gt;' : '&lt;i class="fa fa-thumbs-o-down fa-fw"&gt;&lt;/i&gt;' ) . '&lt;/a&gt; &lt;/td&gt; &lt;/tr&gt; '; } $tbl .= '&lt;/tbody&gt; &lt;/table&gt;'; echo $tbl; } </code></pre> <p>As I said when page loads is showing data so something is working but when I add new data to the database is doesn't automatically show up. I want function to call and refresh the data. Sorry I'm very new to javascript and jQuery so please go easy on me :)</p> <p>Thank you guys</p>4839816460	0	Loop Design: Counting & Subsequent Code Duplication <p>Exercise 3-3 in Accelerated C++ has led me to two broader questions about loop design. The exercise's challenge is to read an arbitrary number of words into a vector, then output the number of times a given word appears in that input. I've included my relevant code below:</p> <pre><code>string currentWord = words[0]; words_sz currentWordCount = 1; // invariant: we have counted i of the current words in the vector for (words_sz i = 1; i &lt; size; ++i) { if (currentWord != words[i]) { cout &lt;&lt; currentWord &lt;&lt; ": " &lt;&lt; currentWordCount &lt;&lt; endl; currentWord = words[i]; currentWordCount = 0; } ++currentWordCount; } cout &lt;&lt; currentWord &lt;&lt; ": " &lt;&lt; currentWordCount &lt;&lt; endl; </code></pre> <p>Note that the output code has to occur again outside the loop to deal with the last word. I realize I could move it to a function and simply call <em>the function</em> twice if I was worried about the complexity of duplicated code.</p> <p><strong>Question 1:</strong> Is this sort of workaround is common? Is there a typical way to refactor the loop to avoid such duplication?</p> <p><strong>Question 2:</strong> While my solution is straightforward, I'm used to counting from zero. Is there a more-acceptable way to write the loop respecting that? Or is this the optimal implementation?</p>48413754000	0	 <p>Is there a reason you were using <code>Request.Form</code>? You should use</p> <pre><code>Guid myGuid = Guid.Parse(GuidToken.Value); </code></pre> <p>If you still want to use Request.Form which I would not recommend, the name of the hidden field control has been changed by asp.net so the collection does not contain exactly what you specified because it has some autogenerated naming convention added to it. It now looks like this</p> <pre><code>Request.Form["ctl00$MainContent$GuidToken"] </code></pre> <p>Debug mode</p> <p><img src="https://i.stack.imgur.com/1ywh4.png" alt="enter image description here"></p>48538638442	0	 <p>As a workaround, download data per day and define weeks in alignment with your measurements from the other dataset. Now Aggregate the Trends data. In case you are dealing with more than 3 months worth of data, consider to rescale your segments beforehand as described here: <a href="http://erikjohansson.blogspot.de/2014/12/creating-daily-search-volume-data-from.html" rel="nofollow">http://erikjohansson.blogspot.de/2014/12/creating-daily-search-volume-data-from.html</a> <a href="http://erikjohansson.blogspot.de/2014/05/daily-google-trends-data-using-r.html" rel="nofollow">http://erikjohansson.blogspot.de/2014/05/daily-google-trends-data-using-r.html</a></p>48613914974	0	 <p>I recommend you read about CSS a little, here is a good example of centering anything.</p> <p><a href="http://www.w3.org/Style/Examples/007/center.en.html" rel="nofollow">http://www.w3.org/Style/Examples/007/center.en.html</a></p>48736159118	0	Guava EventBus - FIFO or LIFO? <p>This is a very generic question on EventBus. Does the EventBus exhibit a FIFO or LIFO behavior? I am using the EventBus as a Java event "queuing" mechanism and seeing LIFO behavior when a single publisher publishes events to the EventBus faster than the Subscriber can handle. </p>48834755958	0	 <p>The difference is caused by <code>doSomeY</code> yielding a number in the first case vs. yielding a function in the second case when applied to one argument.</p> <p>Given</p> <pre><code>doSomeX x = if x==7 then True else False doSomeY x y = x+y+1 </code></pre> <p>we can infer the types (these aren't the most generic types possible, but they'll do for our purposes):</p> <pre><code>doSomeX :: Int -&gt; Bool doSomeY :: Int -&gt; Int -&gt; Int </code></pre> <p>Remember that <code>-&gt;</code> in type signature associates to the right, so the type of <code>doSomeY</code> is equivalent to</p> <pre><code>doSomeY :: Int -&gt; (Int -&gt; Int) </code></pre> <p>With this in mind, consider the type of <code>(.)</code>:</p> <pre><code>(.) :: (b -&gt; c) -&gt; (a -&gt; b) -&gt; a -&gt; c </code></pre> <p>If you define</p> <pre><code>doSomeXY = doSomeX.doSomeY </code></pre> <p>...which is equivalent to <code>(.) doSomeX doSomeY</code>, it means that the first argument to <code>(.)</code> is <code>doSomeX</code> and the second argument is <code>doSomeY</code>. Hence, the type <code>b -&gt; c</code> (the first argument to <code>(.)</code>) must match the type <code>Int -&gt; Bool</code> (the type of <code>doSomeX</code>). So</p> <pre><code>b ~ Int c ~ Bool </code></pre> <p>Hence,</p> <pre><code>(.) doSomeX :: (a -&gt; Int) -&gt; a -&gt; Bool </code></pre> <p>Now, applying this to <code>doSomeY</code> causes a type error. As mentioned above,</p> <pre><code>doSomeY :: Int -&gt; (Int -&gt; Int) </code></pre> <p>So when inferring a type for <code>(.) doSomeX doSomeY</code> the compiler has to unify <code>a -&gt; Int</code> (the first argument of <code>(.) doSomeX</code>) with <code>Int -&gt; (Int -&gt; Int)</code> (the type of <code>doSomeY</code>). <code>a</code> can be unified with <code>Int</code>, but the second half won't work. Hence the compiler barfs.</p>48935189371	0	MVN archetype generate a sub project structure (grunt and package.json) <p>I'm adding to the adobe aem archetype <a href="https://github.com/Adobe-Marketing-Cloud/aem-project-archetype" rel="nofollow">https://github.com/Adobe-Marketing-Cloud/aem-project-archetype</a> . I'm trying to have the archetype create a directory directory call ui.resources with a Gruntfile and package.json in it. I place those files in a ui.resources directory in src/main/archetype. When I run mvn archetype:generate and point to it, there's a gruntfile placed under ui.resource/{packageName} . What am I missing in the archetype-metadata? </p>49027370203	0	 <p>You need be superuser for the Process in Java, see my example: <a href="https://github.com/adouggy/MyRecorder" rel="nofollow">https://github.com/adouggy/MyRecorder</a></p>49114778756	0	 <p>There are several ways to achieve that, see <a href="http://ant.apache.org/faq.html#propertyvalue-as-name-for-property" rel="nofollow">Ant FAQ</a><br> One possible solution via macrodef simulates the antcontrib / propertycopy task but doesn't need any external library.</p>4925532679	0	 <p>What version of Django are you using? </p> <p>Can you post the generated HTML code? if the URL works when you copy and paste in the browser, it might be an html issue as well.</p> <p>Have you looked at this page yet?</p> <p><a href="http://docs.djangoproject.com/en/dev/howto/static-files/" rel="nofollow">http://docs.djangoproject.com/en/dev/howto/static-files/</a></p> <p><strong>Update:</strong></p> <p>Can you post the model for a? is a.picture an image field? If so, then you don't need to put the MEDIA_URL in your img src, since it is already an absolute url and it should include the MEDIA_URL already. try removing that and see if it works.</p> <pre><code>&lt;img src='{{a.picture.url}}' /&gt; </code></pre> <p>For more info see this page.</p> <p><a href="http://docs.djangoproject.com/en/1.3/ref/models/fields/#django.db.models.FileField.storage" rel="nofollow">http://docs.djangoproject.com/en/1.3/ref/models/fields/#django.db.models.FileField.storage</a></p>4934442587	0	Simple jQuery problem <p>This one should be easy</p> <p>I've got this HTML</p> <pre><code>&lt;table class="PageNumbers"&gt; &lt;tr&gt; &lt;td colspan="3"&gt;text3 &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td colspan="2"&gt;text &lt;/td&gt; &lt;td&gt;text2 &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;moretext &lt;/td&gt; &lt;td&gt;moretext2 &lt;/td&gt; &lt;td&gt;moretext3 &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p>I need to change the colspan of the first rows first column to one</p> <p>This is what i've got</p> <pre><code>$('.PageNumbers tr:first td:first').attr('colspan') = '1' </code></pre> <p>Doesn't seem to work though</p> <p>Any ideas?</p> <p>Thanks</p>4949780858	0	Understanding the MVC design pattern in Cocoa Touch <p>Usually I just put together an app in any random way, as long as it works, but this means I don't pay any attention to any design patterns. My application currently makes extensive use of global variables (I carry an instance of my <code>AppDelegate</code> in every view controller to access properties I declared in my <code>AppDelegate.h</code>). Although it does what I want it to do, I've read this is not a good design practice. </p> <p>So I want to start making my code "legit". However, I can't imagine my app right now without global variables. They are so important to the well-being of the app, but this must mean I'm doing something wrong, right? I just can't imagine how else I'd do some things. Take for example this:</p> <p><img src="https://i.stack.imgur.com/DlH1e.png" alt="enter image description here"></p> <p>You have two view controllers here, a <code>SideViewController</code> and a <code>MainViewController</code>. Using global variables, such as say if the entire application had one shared instance of <code>SideViewController</code> and <code>MainViewController</code> (<code>appDelegate.sideViewController</code> and <code>appDelegate.mainViewController</code>), I can easily communicate between the two view controllers, so that if I press "News Feed" in my <code>SideViewController</code>, I can tell my <code>MainViewController</code> to reload it's view. </p> <p>I can't imagine, however, how this would be done if these were not global variables? If an event occurs in my <code>SideViewController</code>, how would I notify my <code>MainViewController</code>, in a way that is in accordance with design standards?</p>49535071799	0	Dynamically enumerate keys in libconfig <p>in <code>libconfig</code> - is it possible to dymanically enumerate keys?</p> <p>As an example, in this <a href="https://github.com/hyperrealm/libconfig/blob/master/examples/c/example.cfg" rel="nofollow">example</a> config file from their repo - if someone invented more days in the <code>hours</code> section, could the code dynamically enumerate them and print them out?</p> <p>Looking at the docs, I see lots of code to get a specific string, or list out an array, but I can't find an example where it enumerates the keys of a config section. </p> <p><strong>Edit</strong></p> <p>Received some downvotes, so thought I'd have another crack at being more specific. </p> <p>I'd like to use libconfig to track some state in my application, read in the last known state when the app starts, and write it out again when it exits. My app stores things in a tree (of depth 2) - so this could be niceley represented as an associative array in a libconfig compatible file as below. The point is that the list of Ids (<code>1234/4567</code>) can change. I could track them in another array, but if I could just enumerate the 'keys' in the <code>ids</code> array below - that would be neater.</p> <p>so </p> <pre><code>ids = { "1234" = [1,2,3] "4567" = [9,10,11,23] } </code></pre> <p>e.g (psuedocode)</p> <pre><code>foreach $key(config_get_keys_under(&amp;configroot)){ config_get_String($key) } </code></pre> <p>I can't see anything obvious in the header file. </p>4962663579	0	 <p>You probably have an ancient version of xerces on the classpath. Definitely check xerces versions.</p>49732054793	0	Are there other means of obtaining the properties of a target in cmake? <p>I have created a C++ static library, and in order to make it searchable easily, I create the following cmake files:</p> <p><strong>lib.cmake</strong></p> <pre><code># The installation prefix configured by this project. set(_IMPORT_PREFIX "C:/------/install/win32") # Create imported target boost add_library(lib STATIC IMPORTED) set_target_properties(lib PROPERTIES INTERFACE_COMPILE_DEFINITIONS "lib_define1;lib_define2" INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/../include" ) # Load information for each installed configuration. get_filename_component(_DIR "${CMAKE_CURRENT_LIST_FILE}" PATH) file(GLOB CONFIG_FILES "${_DIR}/lib-*.cmake") foreach(f ${CONFIG_FILES}) include(${f}) endforeach() </code></pre> <p><strong>lib-debug.cmake</strong></p> <pre><code># Import target "boost" for configuration "Debug" set_property(TARGET lib APPEND PROPERTY IMPORTED_CONFIGURATIONS DEBUG) set_target_properties(boost PROPERTIES IMPORTED_LINK_INTERFACE_LANGUAGES_DEBUG "CXX" IMPORTED_LOCATION_DEBUG "${_IMPORT_PREFIX}/Debug/staticlib/lib.lib" ) </code></pre> <p>When I want to use this library in an executable, I can simply invoke it by calling find_package command:</p> <pre><code>find_package(lib REQUIRED) if(lib_FOUND) message("lib has been found") else() message("lib cannot be found") endif(boost_FOUND) </code></pre> <p>It works and if I want to know the head file directory of the library, I will have to call it this way:</p> <pre><code> get_target_property(lib_dir lib INTERFACE_INCLUDE_DIRECTORIES) </code></pre> <p>I was just wondering whether there are other ways of obtaining the properties of an target. In this case I expect some variable like <code>lib_INCLUDE_DIRECTORIES</code> will exist. </p>49839932643	0	Log level Client side <p>I need to know a strategy to overwrite the log level server side by a unique client session. I mean, I don't want to let all client to write more than needed in order to debug errors only for a specific client. So I'm trying to drive the log level client side instead of server side.</p>4991651061	0	 <p>You might want to set these session options in your vimrc. Especially options is annoying when you've changed your vimrc after you've saved the session.</p> <pre><code>set ssop-=options " do not store global and local values in a session set ssop-=folds " do not store folds </code></pre>50040768802	0	Reload linechart only <p>I have this chart element</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;canvas class="main-chart" id="line-chart" height="200" width="600"&gt;&lt;/canvas&gt;</code></pre> </div> </div> </p> <p>and i have this script to insert the data</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>&lt;script&gt; function hour(){ return a=["00:00","01:00","02:00","03:00","04:00","05:00","06:00","07:00","08:00","09:00","10:00", "11:00","12:00","13:00","14:00","15:00","16:00","17:00","18:00", "19:00","20:00","21:00","22:00","23:00"]; }; var data_visitors_present=&lt;?php echo json_encode(visitorsPresentDay()[0]);?&gt;; var data_visitors_previous=&lt;?php echo json_encode(visitorPreviousDay()[0]);?&gt;; var lineChartData = { labels : hour(), datasets : [ { label: "My First dataset", fillColor : "rgba(220,220,220,0.2)", strokeColor : "rgba(220,220,220,1)", pointColor : "rgba(220,220,220,1)", pointStrokeColor : "#fff", pointHighlightFill : "#fff", pointHighlightStroke : "rgba(220,220,220,1)", data : data_visitors_previous }, { label: "My Second dataset", fillColor : "rgba(48, 164, 255, 0.2)", strokeColor : "rgba(48, 164, 255, 1)", pointColor : "rgba(48, 164, 255, 1)", pointStrokeColor : "#fff", pointHighlightFill : "#fff", pointHighlightStroke : "rgba(48, 164, 255, 1)", data : data_visitors_present } ] } &lt;/script&gt;</code></pre> </div> </div> </p> <p>The final result is this <a href="https://i.stack.imgur.com/1EI0e.png" rel="nofollow noreferrer">enter image description here</a></p> <p>I want every 10 seconds to reload only the chart element; I wrote this without effect..</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>&lt;script&gt; var chart=document.getElementById('#line-chart'); setInterval(chart){( function hour(){ return a=["00:00","01:00","02:00","03:00","04:00","05:00","06:00","07:00","08:00","09:00","10:00", "11:00","12:00","13:00","14:00","15:00","16:00","17:00","18:00", "19:00","20:00","21:00","22:00","23:00"]; }; var data_visitors_present=&lt;?php echo json_encode(visitorsPresentDay()[0]);?&gt;; var data_visitors_previous=&lt;?php echo json_encode(visitorPreviousDay()[0]);?&gt;; var lineChartData = { labels : hour(), datasets : [ { label: "My First dataset", fillColor : "rgba(220,220,220,0.2)", strokeColor : "rgba(220,220,220,1)", pointColor : "rgba(220,220,220,1)", pointStrokeColor : "#fff", pointHighlightFill : "#fff", pointHighlightStroke : "rgba(220,220,220,1)", data : data_visitors_previous }, { label: "My Second dataset", fillColor : "rgba(48, 164, 255, 0.2)", strokeColor : "rgba(48, 164, 255, 1)", pointColor : "rgba(48, 164, 255, 1)", pointStrokeColor : "#fff", pointHighlightFill : "#fff", pointHighlightStroke : "rgba(48, 164, 255, 1)", data : data_visitors_present } ] } }1000); &lt;/script&gt;</code></pre> </div> </div> </p> <p>how i can fix it?</p>50126956433	1	Python - non-English characters don't work in one case <p>Despite the fact I tried to find a solution to my problem both on english and my native-language sites I was unable to find a solution. I'm querying an online dictionary to get translated words, however non-English characters are displayed as e.g. <code>x86</code> or <code>x84</code>. However, if I just do <code>print(the_same_non-english_character)</code> the letter is displayed in a proper form. I use Python 3.3.2 and the HTML source of the site I extract the words from has <code>charset=UTF-8</code> set. Morever, if I use e.g. <code>replace("x86", "non-english_character")</code>, I don't get anything replaced, but replacing of normal characters works.</p>50239113806	0	How to send a value in Database to Google analytics? <p>I manage web application which is made by Symfony2(PHP). I measure some value in Database (for example, register User per a day) on management screen made by myself.</p> <p>But I want to compare this value with data on Google analytics. so I want to know how to send a value in database to Google analytics.</p>50314089825	0	 <p>I usually select a base color and change the hue in 5-6 step (=changing main color) If I need more colors, I'd change saturation (strength or grayish) or luminosity.</p> <p>The problem here is that you should avoid two adjacent colors (on your drawing) to be close together in terms of 'distance' of the three values H,S,L.</p> <p>This is quite easy to implement and gives acceptable results.</p> <p>e.g. (use the windows color editor)<br> (S=140, L=160): H=0,40,80,120,160,200<br> (S=90 , L=180); H=20,60,100,140, 180</p> <p>Please don't use too many colors. Play with fill patterns as well.</p>50423295562	0	 <pre><code>el = document.getElementsByName("invoice_line[0][vat]") el.options[[el.selectedIndex]].attributes["data-id"].value </code></pre>50537505779	0	 <p>I use following code fix:</p> <pre><code>require 'nokogiri' d = Nokogiri::HTML(%Q(&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;/head&gt; &lt;body&gt; &lt;/body&gt; &lt;/html&gt; )) d.css('body')[0].add_child(Nokogiri::XML::Comment.new(d, "doc")) puts d.to_s </code></pre>50640195101	0	 <p>To store inside your program multiple instances of the same class you need an object called List (<a href="https://msdn.microsoft.com/en-us/library/6sh2ey19(v=vs.110).aspx" rel="nofollow">here</a> the MSDN reference and <a href="https://www.dotnetperls.com/list" rel="nofollow">here</a> a fast tutorial). To store the List you have multiple choice: serialize and deserialize using <a href="https://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer(v=vs.110).aspx" rel="nofollow">xml</a>, <a href="http://json.net" rel="nofollow">json</a>, <a href="https://github.com/mgravell/protobuf-net" rel="nofollow">protobuf protocol</a> and much more, it's you choice.</p>5078075116	0	Database Login Failed, Mysql, html, and php <p>I am trying to work on getting better at making HTML forms using PHP and Mysql databases so I decided to make a little mock-up website to do some experiments and things like that. </p> <p>I decided that the first thing I would need to do was to create a login and register page for users who want to sign on to the website. I had no idea how to do this so I did a little research online and I found some pre-built scripts that would do exactly what I wanted to do. In the end I decided to go with this script: <a href="http://www.html-form-guide.com/php-form/php-registration-form.html" rel="nofollow">http://www.html-form-guide.com/php-form/php-registration-form.html</a></p> <p>On my website (hosted with hostgator using cPanel) I set up a Mysql database called ljbaumer_gifts (website is a gift website) and I added a table with 2 columns. The first one a login column which was set to int with auto increment and 25 characters. The second one is a password one which was set to var_char and 25 characters. </p> <p>I filled in all of the information on the setup scripts from the website I linked to earlier completely correctly but every single time I try to register I get this error code: </p> <blockquote> <p>Database Login failed! Please make sure that the DB login credentials provided are correct mysqlerror:Access denied for user 'ljbamer_root'@'my_server_adress' (using password: YES) Database login failed!</p> </blockquote> <p>I used an account that has complete privileges on my server but it still doesn't work!</p>50831562696	0	 <p>It appears that in case of using impersonated async http calls via httpWebRequest</p> <pre><code>HttpWebResponse webResponse; using (identity.Impersonate()) { var webRequest = (HttpWebRequest)WebRequest.Create(url); webResponse = (HttpWebResponse)(await webRequest.GetResponseAsync()); } </code></pre> <p>the setting <code>&lt;legacyImpersonationPolicy enabled="false"/&gt;</code> needs also be set in aspnet.config. Otherwise the HttpWebRequest will send on behalf of app pool user and not impersonated user.</p>509901893	0	 <p>Try doing</p> <pre><code>GridView1.DataSource = users.ToList(); </code></pre> <p>or </p> <pre><code>GridView1.DataSource = users.ToArray(); </code></pre> <p>Is possibly that the query isn't executing at all, because of deferred execution.</p>51031651332	0	Google+ Sign In Button not functioning Android Studio <p>Hi so I am currently integrating a Google Sign In into my app. Lately this has been my only concern that for some reason Android Studio not recognizing the Plus_Login scope (which is necessary for the app to access basic profile info, etc). My current error is this</p> <pre><code>Error:(40, 17) error: method addScope in class Builder cannot be applied to given types; required: Scope found: String reason: actual argument String cannot be converted to Scope by method invocation conversion </code></pre> <p>and here is my onCreate file where the Error is found</p> <p><strong>EDIT 1 - Added import statement and variable declarations</strong></p> <pre><code>package com.instigate.aggregator06; import android.content.Intent; import android.content.IntentSender; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks; import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener; import com.google.android.gms.common.Scopes; import com.google.android.gms.common.api.Scope; import com.google.android.gms.plus.Plus; public class SocialNetworkActivity extends AppCompatActivity implements ConnectionCallbacks, OnConnectionFailedListener, View.OnClickListener { private static final String TAG = "Social Network Activity"; /* Request code used to invoke sign in user interactions. */ private static final int RC_SIGN_IN = 0; /* Client used to interact with Google APIs. */ private GoogleApiClient mGoogleApiClient; /* A flag indicating that a PendingIntent is in progress and prevents * us from starting further intents. */ private boolean mIntentInProgress; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(Plus.API) .addScope(Scopes.PLUS_LOGIN) // &lt;----- This is where the error is found .addScope(Scopes.PLUS_ME) .build(); findViewById(R.id.sign_in_button).setOnClickListener(this); } </code></pre> <p>I have searched a while to find a solution for this error (seeing as the Plus_Login scope should be functioning) yet have found no solution.</p> <p><strong>EDIT 2 - Errors after solving</strong> I found the answer to this. Apparently instead of:</p> <pre><code>.addScope(Scopes.PLUS_LOGIN) .addScope(Scopes.PLUS_ME) </code></pre> <p>we write this</p> <pre><code>.addScope(new Scope(Scopes.PLUS_LOGIN)) .addScope(new Scope(Scopes.PLUS_ME)) </code></pre> <p>which solved my problem.</p> <p>However, it revealed a new problem:</p> <pre><code> findViewById(R.id.sign_in_button).setOnClickListener(this); </code></pre> <p>where logcat points out that there is a NullPointerException at that point.</p> <p><strong>EDIT 3 - Solved NullPointerException</strong> I have solved the NullPointer Exception Problem, however my Google+ Sign In Button will still not function.</p> <p>here is the overall class (continuation of the code snippet mentioned above)</p> <pre><code>package com.instigate.aggregator06; import android.content.Intent; import android.content.IntentSender; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks; import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener; import com.google.android.gms.common.Scopes; import com.google.android.gms.common.api.Scope; import com.google.android.gms.plus.Plus; public class SocialNetworkActivity extends AppCompatActivity implements ConnectionCallbacks, OnConnectionFailedListener, View.OnClickListener { private static final String TAG = "Social Network Activity"; /* Request code used to invoke sign in user interactions. */ private static final int RC_SIGN_IN = 0; /* Client used to interact with Google APIs. */ private GoogleApiClient mGoogleApiClient; /* A flag indicating that a PendingIntent is in progress and prevents * us from starting further intents. */ private boolean mIntentInProgress; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_social_network); mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(Plus.API) //.addScope(Scopes.PLUS_LOGIN) //.addScope(Scopes.PLUS_ME) .addScope(new Scope(Scopes.PLUS_ME)) .addScope(new Scope(Scopes.PLUS_LOGIN)) .build(); this.findViewById(R.id.sign_in_button).setOnClickListener(this); } protected void onStart() { super.onStart(); mGoogleApiClient.connect(); } protected void onStop() { super.onStop(); if (mGoogleApiClient.isConnected()) { mGoogleApiClient.disconnect(); } } /* Code in case second one doesn't work @Override public void onConnectionFailed(ConnectionResult connectionResult) { // Could not connect to Google Play Services. The user needs to select an account, // grant permissions or resolve an error in order to sign in. Refer to the javadoc for // ConnectionResult to see possible error codes. Log.d(TAG, "onConnectionFailed:" + connectionResult); if (!mIsResolving &amp;&amp; mShouldResolve) { if (connectionResult.hasResolution()) { try { connectionResult.startResolutionForResult(this, RC_SIGN_IN); mIsResolving = true; } catch (IntentSender.SendIntentException e) { Log.e(TAG, "Could not resolve ConnectionResult.", e); mIsResolving = false; mGoogleApiClient.connect(); } } else { // Could not resolve the connection result, show the user an // error dialog. showErrorDialog(connectionResult); } } }*/ public void onConnectionFailed(ConnectionResult result) { if (!mIntentInProgress &amp;&amp; result.hasResolution()) { try { mIntentInProgress = true; startIntentSenderForResult(result.getResolution().getIntentSender(), RC_SIGN_IN, null, 0, 0, 0); } catch (IntentSender.SendIntentException e) { // The intent was canceled before it was sent. Return to the default // state and attempt to connect to get an updated ConnectionResult. mIntentInProgress = false; mGoogleApiClient.connect(); } } } public void onConnected(Bundle connectionHint) { // We've resolved any connection errors. mGoogleApiClient can be used to // access Google APIs on behalf of the user. Log.d(TAG, "onConnected:" + connectionHint); Intent j = new Intent(SocialNetworkActivity.this, AccountPageActivity.class); startActivity(j); } protected void onActivityResult(int requestCode, int responseCode, Intent intent) { if (requestCode == RC_SIGN_IN) { mIntentInProgress = false; if (!mGoogleApiClient.isConnecting()) { mGoogleApiClient.connect(); } } } public void onConnectionSuspended(int cause) { mGoogleApiClient.connect(); } @Override public void onClick(View v) { if (v.getId() == R.id.sign_in_button) { //onSignInClicked(); mGoogleApiClient.connect(); } // ... } /* I find this unnecesary private void onSignInClicked() { // User clicked the sign-in button, so begin the sign-in process and automatically // attempt to resolve any errors that occur. //mShouldResolve = true; mGoogleApiClient.connect(); // Show a message to the user that we are signing in. //mStatusTextView.setText(R.string.signing_in); }*/ public void backToMainPage(View view) { Intent j = new Intent(SocialNetworkActivity.this, MainActivity.class); startActivity(j); } } </code></pre> <p>and here is my xml for that class file</p> <pre><code>&lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context="com.instigate.aggregator06.SelectSNActivity" android:orientation="vertical" android:id="@+id/SelectSNActivity" android:weightSum="1"&gt; &lt;Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/backbtn2" android:id="@+id/backbtntest" android:layout_gravity="right" android:layout_alignParentBottom="true" android:layout_alignParentRight="true" android:layout_alignParentEnd="true" android:layout_marginBottom="43dp" android:onClick="backToMainPage"/&gt; &lt;TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:text="@string/selectSocialNetwork" android:id="@+id/selectSocialNetworkHeader" android:textStyle="bold" android:textSize="36sp" android:layout_gravity="center_horizontal" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" /&gt; &lt;com.google.android.gms.common.SignInButton android:id="@+id/sign_in_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/selectSocialNetworkHeader" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_marginTop="52dp" /&gt; &lt;/RelativeLayout&gt; </code></pre> <p>Any help is much appreciated, thank you.</p>51114212199	0	 <p>The other answers seem to have missed the source-control history side of things.</p> <p>From <a href="http://forums.perforce.com/index.php?/topic/359-how-many-lines-of-code-have-i-written/" rel="nofollow">http://forums.perforce.com/index.php?/topic/359-how-many-lines-of-code-have-i-written/</a></p> <p>Calculate the answer in multiple steps:</p> <p>1) Added files:</p> <pre><code>p4 filelog ... | grep ' add on .* by &lt;username&gt;' p4 print -q foo#1 | wc -l </code></pre> <p>2) Changed files:</p> <pre><code>p4 describe &lt;changelist&gt; | grep "^&gt;" | wc -l </code></pre> <p>Combine all the counts together (scripting...), and you'll have a total.</p> <p>You might also want to get rid of whitespace lines, or lines without alphanumeric chars, with a grep?</p> <p>Also if you are doing it regularly, it would be more efficient to code the thing in P4Python and do it incrementally - keeping history and looking at only new commits.</p>51235512272	0	 <p>It looks like your datanodes are full. Could you please check disk space?</p>51334677900	0	 <p>That's because <code>getPerson()</code> returns nothing. You are missing a <code>return</code> keyword. </p> <p>Correct structure is:</p> <pre><code>getPerson() { return addressService.get() .then(...) .then(...); } </code></pre> <hr> <p>Side note: There are also several other typos/minor errors to fix:</p> <pre><code>class PersonService { getPerson() { return addressService.get().then(({address}) =&gt; { // &lt;== Added return at beginning of line return `http://localhost/${address}`; // &lt;== Use ` (backtick), not ', for template strings }).then(url =&gt; { // &lt;== Fixed typo return new es6Promise.Promise(function(resolve, reject) { ApiUtils.get(url, {}, {}, { success: resolve, error: reject }); }); }); // &lt;== Fixed typo } } </code></pre>5148394380	0	 <p>If the parent has <code>display:none;</code> then you'll need to show it before trying to slideUp the child. You can do this with the <code>show</code> function.</p> <pre><code>$(divToSlide).parent().show(); $(divToSlide).slideUp(); </code></pre> <p>Per the comment, you could alternatively, you could just set the display property to 'block'</p> <pre><code>$(divToSlide).parent().css("display", "block"); $(divToSlide).slideUp(); </code></pre>51537023081	0	 <p>The Recycle View supports AutofitRecycleView.</p> <p>You need to add <code>android:numColumns="auto_fit"</code> in your xml file.</p> <p>You can refer to this <a href="http://blog.sqisland.com/2014/12/recyclerview-autofit-grid.html" rel="nofollow">AutofitRecycleViewLink</a></p>51615723806	0	 <p>Basic mechanics for this is very simple. Just toggle a class on list container. In CSS set a set of rules for items that are descendent of that class to change floats or columns or css table properties . Also use that main list class to determine what you want displayed within the items, or how you want them displayed</p> <p>Once class is removed they go back to block elements and default css </p> <p>Simple example:</p> <p>HTML:</p> <pre><code>&lt;ul id="itemList"&gt; &lt;li&gt; &lt;h3 class="title"&gt;Item # 1&lt;/h3&gt; &lt;div class="details"&gt;Detals # 1&lt;/div&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre> <p>CSS:</p> <pre><code>.grid li{ float:left; width:30%;margin-right:5px} .grid .details{display:none} </code></pre> <p>JS:</p> <pre><code>$('button').click(function(){ var txt=$(this).text(); txt= txt=='Grid view'? 'List view' : 'Grid view'; $(this).text( txt); $('#itemList').toggleClass('grid') }); </code></pre> <p>DEMO: <a href="http://jsfiddle.net/kzDNe/" rel="nofollow">http://jsfiddle.net/kzDNe/</a></p>51715341673	0	 <p>DataStax provides a Community Edition AMI for Amazon EC2, detailed instructions <a href="http://www.datastax.com/docs/1.2/install/install_ami" rel="nofollow" title="here">here</a>.</p>5189253056	0	 <p>Yes. It's possible. Use plpython for example. Use this in trigger.</p> <pre><code>CREATE OR REPLACE FUNCTION move_file(old_path text, new_path text) RETURNS boolean AS $$ import shutil try: shutil.move(old_path, new_path) return True except: return False $$ LANGUAGE 'plpythonu' VOLATILE; </code></pre>51924402847	0	non-static variable s cannot be referenced from a static context <p>I'm trying to write a piece of code that when I check one of the two checkboxes, it will change the message that appears when I then select the button. </p> <pre><code>import javax.swing.*; import java.awt.*; import java.awt.event.*; public class FirstWindow extends JFrame{ String message; public static void main(String[] args){ //the string to show the message for button 1 message = "goodjob \n"; //all of the main window JFrame frame = new JFrame("heading"); frame.setVisible(true); frame.setSize(600,400); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLocationRelativeTo(null); //makes seperate panels JPanel panel1 = new JPanel(); JPanel panel2 = new JPanel(); JPanel panel3 = new JPanel(new GridBagLayout()); //set of buttons JButton button1 = new JButton("Button 1"); JButton button2 = new JButton("Button 2"); //makes an ACTION LISTENER, which tells the button what to do when //it is pressed. button1.addActionListener(new ActionListener(){ //the command to button @Override public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(null, message); } }); //for panel adds buttons panel1.add(button1); panel1.add(button2); //set of checkboxes JCheckBox checkBox = new JCheckBox("Option1"); JCheckBox checkBox2 = new JCheckBox("Option2"); //adds text if the box is checked if (checkBox.isSelected()) { message += "you picked option 1"; } if (checkBox2.isSelected()) { message += "you picked option 2"; } //for panel2 adds checkboxes panel2.add(checkBox); panel2.add(checkBox2); //makes a new label, text area and field JLabel label = new JLabel("This is a label"); JTextArea textArea = new JTextArea("this is a text area"); JTextField textField = new JTextField("text field"); //makes an invisible grid GridBagConstraints grid = new GridBagConstraints(); grid.insets = new Insets(15, 15, 15, 15); //sets the the coordinates 0,0. adds the label, and sets position grid.gridx = 0; grid.gridy = 0; panel3.add(label, grid); //sets the the coordinates 0,1. adds the textArea, and sets position grid.gridx = 0; grid.gridy = 1; panel3.add(textArea, grid); //sets the the coordinates 0,2. adds the text field, and sets position grid.gridx = 0; grid.gridy = 2; panel3.add(textField, grid); //adds each PANEL to the FRAME and positions it frame.add(panel1, BorderLayout.SOUTH); frame.add(panel3, BorderLayout.CENTER); frame.add(panel2, BorderLayout.NORTH); } } </code></pre> <p>The error message I'm receiving is:</p> <p>"FirstWindow.java:12: error: non-static variable message cannot be referenced from a static context message = "goodjob \n";"</p> <p>for lines 12, 37, 53, 57. I've tried declaring the String variable in the main but then I will just receive the error:</p> <p>"FirstWindow.java:38: error: local variables referenced from an inner class must be final or effectively final JOptionPane.showMessageDialog(null, message);"</p> <p>How to solve this problem?</p>52016481898	0	 <p>From <a href="http://stackoverflow.com/questions/4072260/how-to-change-java-version-used-by-tomcat">here</a>:</p> <p>When you open catalina.sh / catalina.bat, you can see :</p> <pre><code>Environment Variable Prequisites JAVA_HOME Must point at your Java Development Kit installation. </code></pre> <p>So, set your environment variable JAVA_HOME to point to Java 7. Also make sure JRE_HOME is pointing to the same target, if it is set.</p> <p>You may not have this same issue, but if you do, it could be helpful to know ; )</p>52137791208	0	Knockout JS - How to initialize a complex object as observable? <p>I have a ViewModel and have an observable property that will have a complex object after an edit link is clicked. This is a basic example of managing a set of Groups. User can click on the 'edit' link and I want to capture that Group in SelectedGroup property.</p> <p>But I'm not sure how should I initialize the SelectedGroup and make every peoperty in this object as observable to begin with. </p> <pre><code>function ManageGroupsViewModel() { var self = this; self.Groups = ko.observableArray(); self.IsLoading = ko.observable(false); self.SelectedGroup = ko.observable(); } </code></pre>5224431992	0	as3: Error: Implicit coercion of a value of type void to an unrelated type <p>I'm attempting to set up a Metadata object like so:</p> <pre><code>public function myFunction(event:MediaFactoryEvent):void { var resource:URLResource = new URLResource("http://mediapm.edgesuite.net/osmf/content/test/logo_animated.flv"); var media:MediaElement = factory.createMediaElement(resource); // Add Metadata for the URLResource var MediaParams:Object = { mfg:"Ford", year:"2008", model:"F150", } media.addMetadata("MediaParams", (new Metadata()).addValue("MediaParams", MediaParams) ); </code></pre> <p>When I attempt this, I get:</p> <blockquote> <p>Implicit coercion of a value of type void to an unrelated type org.osmf.metadata:Metadata. (new Metadata()).addValue("MediaParams", MediaParams) ); I actually need the metadata at a couple of levels of depth there, because the metadata gets passed and another function expects the Metadata that way. </p> </blockquote> <p>How do I get the Metadata added to my URLResource the way I want? Thanks!</p>52320895184	0	Identical template for many functions <h1>Hello guys (and happy new year!)</h1> <p>I'm writing a (not really) simple project in C++ (my first, coming from plain C). I was wondering if there is a way to simplify the definition for multiple functions having the same template pattern. I think an example would be better to explain the problem.</p> <h2>The context</h2> <p>Let's assume I have a "Set" class which represents a list of numbers, defined as</p> <pre><code>template &lt;class T&gt; class Set { static_assert(std::is_arithmetic&lt;T&gt;(), "Template argument must be an arithmetic type."); T *_address; ... } </code></pre> <p>So if I have an instance (say <code>Set&lt;double&gt;</code>) and an array <code>U array[N]</code>, where <code>U</code> is another arithmetic type and <code>N</code> is an integer, I would like to be able to perform some operations such as assigning the values of the array to those of the <code>Set</code>. Thus I create the function template inside the class</p> <pre><code>template &lt;class U, int N&gt; void assign(U (&amp;s)[N]) { static_assert(std::is_arithmetic&lt;U&gt;(), "Template argument must be an arithmetic type."); errlog(E_BAD_ARRAY_SIZE, N == _size); idx_t i = 0; do { _address[i] = value[i]; } while (++i &lt; size); } </code></pre> <h2>The problem</h2> <p>As far as my tests went the code above works perfectly fine. However I find it REALLY REALLY ugly to see since I need the <code>static_assert</code> to ensure that only arithmetic types are taken as arguments (parameter <code>U</code>) and I need a way to be sure about the array size (parameter <code>N</code>). Also, I'm not done with the <code>assign</code> function but I need so many other functions such as <code>add</code>, <code>multiply</code>, <code>scalar_product</code> etc. etc.!</p> <h2>The first solution</h2> <p>I was wondering then if there is a prettier way to write this kind of class. After some work I've come up with a preprocessor directive:</p> <pre><code>#define arithmetic_v(_U_, _N_, _DECL_, ...) \ template &lt;class U, idx_t N&gt; _DECL_ \ { \ static_assert(std::is_arithmetic&lt;U&gt;(),"Rvalue is not an arithmetic type."); \ errlog(E_BAD_ARRAY_SIZE, N == _size); \ __VA_ARGS__ \ } </code></pre> <p>thus defining my function as</p> <pre><code>arithmetic_v(U, N, void assign(U (&amp;value)[N]), idx_t i = 0; do { _address[i] = value[i]; } while (++i &lt; _size); ) </code></pre> <p>This is somehow cleaner but still isn't the best since I'm forced to lose the brackets wrapping the function's body (having to include the <code>static_assert</code> INSIDE the function itself for the template parameter <code>U</code> to be in scope).</p> <h2>The question</h2> <p>The solution I've found seems to work pretty well and the code is much more readable than before, but... Can't I use another construct allowing me to build an even cleaner definition of all the functions and still preserving the <code>static_assert</code> piece and the info about the array size? It would be really ugly to repeat the template code once for each function I need...</p> <h2>The thanks</h2> <p>I'm just trying to learn about the language, thus ANY additional information about this argument will be really appreciated. I've searched as much as I could stand but couldn't find anything (maybe I just couldn't think of the appropriate keywords to ask Google in order to find something relevant). Thanks in advance for your help, and <strong>happy new year to you all</strong>!</p> <p>Gianluca</p>52426027094	0	 <p><strong>Use this:</strong></p> <pre><code>(?s)&lt;Device(?:(?!&lt;\/Device).)*&lt;Block[^&gt;]+Name="ZG123CZ123".*?&lt;\/Device&gt; </code></pre> <p><sub><a href="http://regex101.com/r/bU5zC1/1" rel="nofollow"><em>Demo</em></a></sub></p> <hr> <p><strong>Explanation:</strong></p> <ul> <li><code>(?s)</code> is the single-line modifier, which makes <code>.</code> include newline characters.</li> <li><code>&lt;Device</code> looks for the beginning of a <code>Device</code> element.</li> <li><code>(?:(?!&lt;\/Device).)*</code> is essentially <code>.*</code>, but each time we try to match a character we make sure we aren't matching the end of a <code>Device</code> element (<code>&lt;\/Device</code>) by using a negative lookahead. Note that you can't just make this a lazy match, since it would continue until if found the <code>&lt;Block Name="ZG123CZ123"&gt;</code> (that is the next chunk).</li> <li><code>&lt;Block[^&gt;]+Name="ZG123CZ123"</code> will look for the beginning of a <code>Block</code> element, followed by non <code>&gt;</code> character(s), followed by the <code>Name</code> attribute equaling <code>ZG123CZ123</code>.</li> <li><code>.*?</code> is a lazy match to eat up the rest of the <code>Device</code> element.</li> <li><code>&lt;\/Device&gt;</code> we've made it to the end!</li> </ul>52538363122	0	 <p>Yeah there's a matches pseudo class, but if you're hoping it will save you some typing it still needs vendor prefixes you'd have to duplicate and the support isn't great. </p> <pre><code>:matches(#header, #footer) button active:hover { color: purple; } :-webkit-any(#header, #footer) button active:hover { color: purple; } :-moz-any(#header, #footer) button active:hover { color: purple; } </code></pre> <p>So as you can see it ends up being more verbose than just adding the comma and another selector at the moment. </p>52627665172	0	 <pre><code>list_a = list_b = [0 for k in range(10)] </code></pre> <p>Because list_a equal to list_b. So if list_b is changed, then list_a will change.</p>52734990373	0	 <p>You could use <code>ngModel</code> to do this automatically</p> <pre><code>&lt;li *ngFor="#hero of heroes"&gt; &lt;input type="text" [(ngModel)]="hero.name"/&gt; &lt;/li&gt; </code></pre>52822297215	0	 <p>don't look for bug free query here because you haven' provided enough info and sample data. So start pointing out one be one,</p> <pre><code>Declare @i varchar='Jan-13' declare @upto int=11 Declare @FromDate date=convert(varchar(12),'1-'+'Jan-13',120) Declare @Todate date =dateadd(month,@upto,@FromDate) select convert(char(6),@FromDate,107) ,@ToDate Declare @StringDate varchar(2000)='' select @StringDate= stuff((select ','+'['+convert(char(6),ODLN.DocDate ,107)DocDate+']' from ODLN inner join DLN1 on odln.DocEntry = ODLN.DocEntry where ODLN.DocDate between between @FromDate and @Todate for xml path('')),1,1,'') --@StringDate will have value like [Jan-13],[Dec-12] and so on Declare @qry varchar(max)='' set @qry='select CardName,'+@StringDate+' from (select CardName,CardCode ,DLN1.Quantity,convert(char(6),ODLN.DocDate ,107)DocDate from ODLN inner join DLN1 on odln.DocEntry = ODLN.DocEntry where ODLN.DocDate between between '+@FromDate+' and '+@Todate+')tbl pivot( max(Quantity) for DocDate in('+@StringDate+'))pvt' exec @qry </code></pre>52932282831	1	Unable to log Flask exceptions with SMTP handler <p>I am attempting to get an email sent to me any time an error occurs in my Flask application. The email is not being sent despite the handler being registered. I used <code>smtplib</code> to verify that my SMTP login details are correct. The error is displayed in Werkzeug's debugger, but no emails are sent. How do I log exceptions that occur in my app?</p> <pre><code>import logging from logging.handlers import SMTPHandler from flask import Flask app = Flask(__name__) app.debug = True app.config['PROPAGATE_EXCEPTIONS'] = True if app.debug: logging.basicConfig(level=logging.INFO) # all of the $ names have actual values handler = SMTPHandler( mailhost = 'smtp.mailgun.org', fromaddr = 'Application Bug Reporter &lt;$mailgun_email_here&gt;', toaddrs = ['$personal_email_here'], subject = 'Test Application Logging Email', credentials = ('$mailgun_email_here', '$mailgun_password_here') ) handler.setLevel(logging.ERROR) app.logger.addHandler(handler) @app.route('/') def index(): raise Exception('Hello, World!') # should trigger an email app.run() </code></pre>53032090894	0	Maven - Debug - Can not find symbol <p>During using mvn install or mvn compile i got error that maven can not find symbol with different methods and variables in mozilla rhino classes. I made exclusions everywhere where it is possible and said to use 7r5 build for rhino. Also i decompiled jar and got sure that mentioned classes and methods in maven were in that classes. I had pom deps and i couldnt exclude all 3d libraries. So in classpath i saw also path to rhino 6r5 library. I thought that problem was there. So i also decompiled that jar but i saw that methods in the error were also there. My question is how i can debug maven and see what library or class it is using for compiling class. All mozilla rhino libraries which are set in classpath have that methods. PS: I wanted to mention that mvn eclipse:eclipse works fine and i have no errors in eclipse.</p> <pre><code>[ERROR] ...path_to_class...:[264,65] cannot find symbol [ERROR] symbol: method getLength() [ERROR] location: class org.mozilla.javascript.NativeArray [ERROR] ...path_to_class...:[288,18] cannot find symbol [ERROR] symbol: method getWrapFactory() [ERROR] location: variable cx of type org.mozilla.javascript.Context [ERROR] ...path_to_class...:[322,49] cannot find symbol [ERROR] symbol: method getLength() [ERROR] location: variable array of type org.mozilla.javascript.NativeArray </code></pre>53138124350	0	Does Setting Session in Model is bad practice? <p>I do some database transaction and the set <strong>$new_user = TRUE</strong> like this</p> <p>Model Code:</p> <pre><code>$data_insert = array ( 'username' =&gt; $username_post, 'password'=&gt;$username_post, ); $this-&gt;db-&gt;insert('Tenant', $data_insert); $new_tenant_id = $this-&gt;db-&gt;insert_id(); //CREATE TABLE FOR THAT DISTRIBUTOR $this-&gt;dbforge-&gt;add_field( array( 'id' =&gt; array( 'type' =&gt; 'INT', 'constraint' =&gt; 10, 'unsigned' =&gt; TRUE, 'auto_increment' =&gt; TRUE ), 'site_key' =&gt; array( 'type' =&gt; 'VARCHAR', 'constraint' =&gt; '100', ), 'display_name' =&gt; array( 'type' =&gt; 'VARCHAR', 'constraint' =&gt; '100', 'null' =&gt; TRUE ), 'ext' =&gt; array( 'type' =&gt; 'VARCHAR', 'constraint' =&gt; '50', 'null' =&gt; TRUE ), 'auth_user' =&gt; array( 'type' =&gt; 'VARCHAR', 'constraint' =&gt; '100', 'null' =&gt; TRUE ), 'password' =&gt; array( 'type' =&gt; 'VARCHAR', 'constraint' =&gt; '128', 'null' =&gt; TRUE, ), 'base_ini_id' =&gt; array( 'type' =&gt; 'VARCHAR', 'constraint' =&gt; '50', 'null' =&gt; TRUE ), 'md_user' =&gt; array( 'type' =&gt; 'VARCHAR', 'constraint' =&gt; '128', 'null' =&gt; TRUE ), 'uc_user' =&gt; array( 'type' =&gt; 'VARCHAR', 'constraint' =&gt; '50', 'null' =&gt; TRUE ), 'uc_password' =&gt; array( 'type' =&gt; 'VARCHAR', 'constraint' =&gt; '100', 'null' =&gt; TRUE ), 'comments' =&gt; array( 'type' =&gt; 'VARCHAR', 'constraint' =&gt; '200', 'null' =&gt; TRUE ), 'custom_ini_filename' =&gt; array( 'type' =&gt; 'VARCHAR', 'constraint' =&gt; '100', 'null' =&gt; TRUE ), 'email' =&gt; array( 'type' =&gt; 'VARCHAR', 'constraint' =&gt; '100', 'null' =&gt; TRUE ), )); $this-&gt;dbforge-&gt;add_key('id', TRUE); if (!$this-&gt;db-&gt;table_exists('table_name')) { $this-&gt;dbforge-&gt;create_table($usertable); } //TABLE CREATED NOW ADD SOME DATA $insert_data = array ( 'site_key' =&gt;$site_post, 'tenant_id'=&gt;$new_tenant_id ); //TENANT CREATED AND THE SITE BY HIM IS ADDED TO DATABASE $query = $this-&gt;db-&gt;insert('MLCSites',$insert_data); $new_user = TRUE; </code></pre> <p>Now if i have the user in database then $validate is set to TRUE if not i check if $new_user == TRUE then I set loggedin = TRUE in my session like this:</p> <pre><code>if(!empty($validate)) { if ($validate == TRUE) { // Log in user $data = array( 'site' =&gt; $site-&gt;site_post, 'id' =&gt;$tenant_id, 'username'=&gt;$username_post, 'user_table'=&gt;$usertable, 'nec_distributor'=&gt;TRUE, 'loggedin' =&gt; TRUE, ); $this-&gt;session-&gt;set_userdata($data); return TRUE; } elseif ($new_user == TRUE) { // Log in user $data = array( 'site' =&gt; $site-&gt;site_post, 'id' =&gt;$new_tenant_id, 'username'=&gt;$username_post, 'user_table'=&gt;$usertable, 'nec_distributor'=&gt;TRUE, 'loggedin' =&gt; TRUE, ); $this-&gt;session-&gt;set_userdata($data); return TRUE; } return FALSE; } </code></pre> <p>Now in my controller i Check like this:</p> <pre><code>$dashboard ='customer/dashboard'; $rules = $this-&gt;distributor_m-&gt;rules; $this-&gt;form_validation-&gt;set_rules($rules); if ($this-&gt;distributor_m-&gt;login() == TRUE) { var_dump($this-&gt;session-&gt;all_userdata()); $this-&gt;distributor_m-&gt;loggedin() == FALSE || redirect($dashboard); redirect($dashboard); } else { $this-&gt;session-&gt;set_flashdata('error', 'That email/password combination does not exist'); //redirect('secure/login', 'refresh'); } </code></pre> <p>But when i submit username and key, all the database transaction are done as per the code successfully. But there is nothing in my session, if I resend the form information then i see the SESSION data. So where I am going wrong?</p>53226407526	0	 <p>No answer yet has explained why NASM reports</p> <pre><code>Mach-O 64-bit format does not support 32-bit absolute addresses </code></pre> <p>The reason NASM won't do this is explained in <a href="http://agner.org/optimize/optimizing_assembly.pdf" rel="nofollow">Agner Fog's Optimizing Assembly</a> manual in section <em>3.3 Addressing modes</em> under the subsection titled <em>32-bit absolute addressing in 64 bit mode</em> he writes</p> <blockquote> <p>32-bit absolute addresses cannot be used in Mac OS X, where addresses are above 2^32 by default.</p> </blockquote> <p>This is not a problem on Linux or Windows. In fact I already showed this works at <a href="http://stackoverflow.com/questions/26358119/static-linkage-with-glibc-without-calling-main">static-linkage-with-glibc-without-calling-main</a>. That hello world code uses 32-bit absolute addressing with elf64 and runs fine.</p> <p>@HristoIliev suggested using rip relative addressing but did not explain that 32-bit absolute addressing in Linux would work as well. In fact if you change <code>lea rdi, [rel msg]</code> to <code>lea rdi, [msg]</code> it assembles and runs fine with <code>nasm -efl64</code> but fails with <code>nasm -macho64</code></p> <p>Like this:</p> <pre><code>section .data msg db 'This is a test', 10, 0 ; something stupid here section .text global _main extern _printf _main: push rbp mov rbp, rsp xor al, al lea rdi, [msg] call _printf mov rsp, rbp pop rbp ret </code></pre> <p>You can check that this is an absolute 32-bit address and not rip relative with <code>objdump</code>. However, it's important to point out that the preferred method is still rip relative addressing. Agner in the same manual writes:</p> <blockquote> <p>There is absolutely no reason to use absolute addresses for simple memory operands. Rip- relative addresses make instructions shorter, they eliminate the need for relocation at load time, and they are safe to use in all systems.</p> </blockquote> <p>So when would use use 32-bit absolute addresses in 64-bit mode? Static arrays is a good candidate. See the following subsection <em>Addressing static arrays in 64 bit mode</em>. The simple case would be e.g:</p> <pre><code>mov eax, [A+rcx*4] </code></pre> <p>where A is the absolute 32-bit address of the static array. This works fine with Linux but once again you can't do this with Mac OS X because the image base is larger than 2^32 by default. To to this on Mac OS X see example 3.11c and 3.11d in Agner's manual. In example 3.11c you could do</p> <pre><code>mov eax, [(imagerel A) + rbx + rcx*4] </code></pre> <p>Where you use the extern reference from Mach O <code>__mh_execute_header</code> to get the image base. In example 3.11c you use rip relative addressing and load the address like this</p> <pre><code>lea rbx, [rel A]; rel tells nasm to do [rip + A] mov eax, [rbx + 4*rcx] ; A[i] </code></pre>5331315826	0	Sharing objects between C# and C++ code <p>Is it possible to share references to C# objects between C# and C++ code without massive complexity? Or is this generally considered a bad idea? </p>53416525056	0	remove multiple line using str_replace <p>I want to remove this multi line with str_replace</p> <pre><code>&lt;div&gt;&lt;i&gt;Hello&lt;/i&gt;&lt;br/&gt; &lt;!-- Begin: Hello.text --&gt; &lt;script src="http://site.com/hello.php?id=12345" type="text/javascript"&gt; &lt;/script&gt; &lt;!-- End: Hello.text --&gt;&lt;/div&gt; </code></pre> <p>12345 = random number</p>53537551018	0	how to check longitude latitude database sql server <p>i have longitude and latitude in geofence table how to check longitude and latitude in database level. if car longitude latitude are in Zone, update geofance column zones = 'car in zone area'</p> <pre><code>CREATE TRIGGER Tr_CheckGeoFance ON CheckGeoFance AFTER INSERT AS BEGIN Update tblgeofencing Set CarZone ='Car In Zone Area' END GO ShapesString ={"shapes":[{"type":"rectangle","color":"#1E90FF","bounds":{"northEast":{"lat":"32.379961464357315","lon":"70.99365234375"},"southWest":{"lat":"31.840232667909362","lon":"70.2685546875"}}}]} </code></pre> <p><a href="https://i.stack.imgur.com/wHj9e.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wHj9e.png" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/1LYTA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1LYTA.png" alt="enter image description here"></a></p>53636487261	0	 <p>Instead of <code>TStringGrid</code> use <code>TGrid</code> with <code>TColumn</code> columns. Then use the <code>OnGetValue</code> event to fetch values for display in the grid. This is closest to the <code>VCL</code>s <code>TDrawGrid</code>.</p> <pre><code>procedure TForm1.Grid1GetValue(Sender: TObject; const Col, Row: Integer; var Value: TValue); begin Value := inttostr(col)+', '+inttostr(row); end; </code></pre> <p>Sample result of grid with 10 mio rows:</p> <p><a href="https://i.stack.imgur.com/NHQK0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NHQK0.png" alt="enter image description here"></a></p>53714716668	0	quicker WiFi scan rate to obtain rssi changes android <p>I am trying to increase the wifi scan rate but with the method wifi.startscan and getting the info of the list result returned, i dont see that the rssi change each 2 seconds. My question is if it is possible to get a low rate scan of the rssi and if it is possible how could i do it.</p>53820710003	0	 <p>You can use GridBagLayout in netBeans . this layout is stable way for complex form and panel . </p> <p><a href="https://netbeans.org/kb/docs/java/gbcustomizer-basic.html" rel="nofollow">tutorial for Netbeans</a> </p>5393519222	0	 <pre><code>&gt;gawk -F"/" "{ split($5,a,\".\"); print a[1]}" 1.t PRX01 PRX02 PRX03 PRX04 </code></pre>54025004136	0	 <p>I got this after more trial and error: <code>'/table/tbody/tr[preceding-sibling::tr[th/text()="First header"] = preceding-sibling::tr[th][1]]'</code> Which translates to English: get all rows preceded by the "First header" row where that row is also the first preceding row that contains a header.</p>54136072122	0	 <p>According to documentation for <a href="https://developer.mozilla.org/ru/docs/Web/API/CanvasRenderingContext2D/drawImage" rel="nofollow">CanvasRenderingContext2D.drawImage()</a> function:</p> <blockquote> <p>ctx.drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight);</p> </blockquote> <p><em>sx, sy, sWidth, sHeight</em> are parameters of the <strong>sub-rectangle</strong> of the source image <br>In your case: parameters <strong><em>sx, sy, sWidth, sHeight</em></strong> should coincide with parameters <strong><em>dx, dy, dWidth, dHeight</em></strong> (in most simple case)<br> Change your <code>imageObj.onload</code> handler as shown below:</p> <pre><code>... imageObj.onload = function() { context.drawImage(imageObj, x, y, width, height, x, y, width, height); callback(canvas.toDataURL()) }; ... </code></pre>54215720869	0	Connect to database in android <p>I used the login code to login through simple android application , I've created mydatabase also created the whole java classes needed and the xml files, the result always gives me "Invalid username or password" even though the username and the password are correct as inserted in the DB ,, the app runs with no errors</p> <p>this is the MainActivity java class:</p> <pre><code>package com.logintest.fh; import java.io.IOException; public class MainActivity extends Activity { /** Called when the activity is first created. */ Button login; String name="",pass=""; EditText username,password; TextView tv; byte[] data; HttpPost httppost; StringBuffer buffer; HttpResponse response; HttpClient httpclient; InputStream inputStream; SharedPreferences app_preferences ; List&lt;NameValuePair&gt; nameValuePairs; CheckBox check; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); app_preferences = PreferenceManager.getDefaultSharedPreferences(this); username = (EditText) findViewById(R.id.username); password = (EditText) findViewById(R.id.password); login = (Button) findViewById(R.id.login); check = (CheckBox) findViewById(R.id.check); String Str_user = app_preferences.getString("username","0" ); String Str_pass = app_preferences.getString("password", "0"); String Str_check = app_preferences.getString("checked", "no"); if(Str_check.equals("yes")) { username.setText(Str_user); password.setText(Str_pass); check.setChecked(true); } login.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { name = username.getText().toString(); pass = password.getText().toString(); String Str_check2 = app_preferences.getString("checked", "no"); if(Str_check2.equals("yes")) { SharedPreferences.Editor editor = app_preferences.edit(); editor.putString("username", name); editor.putString("password", pass); editor.commit(); } if(name.equals("") || pass.equals("")) { Toast.makeText(MainActivity.this, "Blank Field..Please Enter", Toast.LENGTH_LONG).show(); } else { try { httpclient = new DefaultHttpClient(); httppost = new HttpPost("http://10.0.0.1/my_folder_inside_htdocs/check.php"); // Add your data nameValuePairs = new ArrayList&lt;NameValuePair&gt;(2); nameValuePairs.add(new BasicNameValuePair("username", name.trim())); nameValuePairs.add(new BasicNameValuePair("password", pass.trim())); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); // Execute HTTP Post Request response=httpclient.execute(httppost); ResponseHandler&lt;String&gt; responseHandler = new BasicResponseHandler(); final String response = httpclient.execute(httppost, responseHandler); System.out.println("Response : " + response); if(response.equalsIgnoreCase("User Found")){ runOnUiThread(new Runnable() { public void run() { Toast.makeText(MainActivity.this,"Login Successfull", Toast.LENGTH_SHORT).show(); } }); //startActivity(new Intent(MainActivity.this, UserPage.class)); Move_to_next(); }else{ Toast.makeText(MainActivity.this, "Invalid Username or password", Toast.LENGTH_LONG).show(); } } catch (Exception e) { Toast.makeText(MainActivity.this, "error"+e.toString(), Toast.LENGTH_LONG).show(); } } } }); check.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // Perform action on clicks, depending on whether it's now checked SharedPreferences.Editor editor = app_preferences.edit(); if (((CheckBox) v).isChecked()) { editor.putString("checked", "yes"); editor.commit(); } else { editor.putString("checked", "no"); editor.commit(); } } }); } public void Move_to_next() { startActivity(new Intent(MainActivity.this, UserPage.class)); } } </code></pre> <p>the UserPage an empty page I want the user to go to after logging in</p> <p>this is my php file : <pre><code>try { $db = new PDO("mysql:host=$hostname_localhost;dbname=mydatabase", $username_localhost, $password_localhost); echo "Connected to database"; // check for connection $username = $_POST['myusername']; $password = $_POST['mypassword']; $db-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); $sql = "select * from mydatabase.tbl_user where username = '".$username."' AND password = '".$password. "'"; $result = $db-&gt;query($sql); foreach ($result as $row) { echo "&lt;br/&gt; success"; } $db = null; // close the database connection } catch(PDOException $e) { echo $e-&gt;getMessage(); } ?&gt; </code></pre> <p>any ideas of what the problem might be ?</p>54318988050	0	 <p>If the form is posting a field with a parameter of <code>name</code>, a 404 will result. </p>54430678371	0	 <p>You can try this:judge the parameter wether is a file, then according to the type of parameter execute the operation respectively</p>54530322733	0	 <p>try this, if Z axis is your forward direction:</p> <pre><code>for(var i=0;i&lt;10;i++) { gun.transform.position += gun.transform.forward; yield return 0; } for(var i=0;i&lt;10;i++) { gun.transform.position -= gun.transform.forward; yield return 0; } </code></pre> <p>this will move the gun in the forward direction of the gun</p> <p>if you turn, the forward direction is not (0,0,1)</p> <p>you can also use this if X axis is your forward direction:</p> <pre><code>for(var i=0;i&lt;10;i++) { gun.transform.position += gun.transform.right; yield return 0; } for(var i=0;i&lt;10;i++) { gun.transform.position -= gun.transform.right; yield return 0; } </code></pre>546930920	0	 <p>If you are able to use LINQ,</p> <pre><code> void Main() { Dictionary d1 = new Dictionary&lt;int, string&gt;(); Dictionary d2 = new Dictionary&lt;int, string&gt;(); d1.Add(1, "1"); d1.Add(2, "2"); d1.Add(3, "3"); d2.Add(2, "2"); d2.Add(1, "1"); d2.Add(3, "3"); Console.WriteLine(d1.Keys.Except(d2.Keys).ToArray().Length); } </code> </pre> <p>This prints 0 to the console. Except tries to find the difference between two lists in the above example. </p> <p>You can compare this with 0 to find if there is any difference.</p> <p>EDIT: You could add the check for comparing the length of 2 dictionaries before doing this.<br> i.e. You can use Except, <strong><em>only</em></strong> if the length differs.</p>5474518512	0	 <ul> <li><p><strong>Card Number</strong> (aka <strong>PAN</strong>, Primary Account Number)<br> Don't take any advice as gospel. The card number is comprised of a 6 digit Issuer Identification Number (IIN), an account number and a luhn check digit. The IIN ranges are constantly changing and industry sectors that rely on this information (such as Payment Processors) will generally be updated as changes occur. It's reasonably safe to assume that the card number should be between 16 and 19 digits, and start with 3, 4, 5 or 6. Beyond that trying to identify the card type from the IIN is prone to error unless you are frequently updated.</p></li> <li><p><strong>Luhn / Mod10 check digit</strong>.<br> The last digit of the card number is a check digit to pick up transposition errors which may have occured when an operator has keyed in the card number. The <a href="http://en.wikipedia.org/wiki/Luhn_algorithm">wikipedia article</a> is a good source for more info and code samples.</p></li> <li><p><strong>Magnetic stripe</strong><br> If you have physical access to the card, and a magstripe reader, then track 2 contains banking card info. Amongst the details are card number, expiry date, LRC (check digit) and a Service Code. The service code (only available on mag stripe) informs how the card may be used, eg only for national payments, only for use at an ATM (not as a payment card), whether cash back should be offered etc.</p></li> <li><p><strong>CCV / CSC / CV2</strong><br> Security digits are never embossed onto the card, or recorded on the magstripe. Should be three digits on all except Amex (always 4 digits)</p></li> <li><p><strong>Issue date</strong><br> Used for manual (sanity) check only. Not sent during the authorization request</p></li> <li><p><strong>Expiry date</strong><br> A common misconception is that expired cards cannot be used. They frequently can, but they must go through online authorization first (so that the acquiring bank has final say on whether it is permitted or not). Expiry dates can be up to 20 years in the future (and even further in some rare cases)</p></li> <li><p><strong>Issue number</strong><br> Only available on certain card types. Should be captured and used in the authorization request.</p></li> </ul>54816410142	0	 <p>If you're using the standard Android binding, whose Javadoc is at <a href="http://developer.android.com/reference/android/database/sqlite/package-summary.html" rel="nofollow">http://developer.android.com/reference/android/database/sqlite/package-summary.html</a>, then you can find the right code to call by looking at the Javadoc for an overload of <code>execSQL</code>. See http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#execSQL(java.lang.String,%20java.lang.Object[]).</p> <p>Now, the Javadoc says that <code>execSQL</code> is not to be used for <code>SELECT/INSERT/UPDATE/DELETE</code>. Instead, there are three <code>insertXXX</code> methods, each of which takes additional data in a <code>ContentValues</code> object. So, you construct that object, which looks like a <code>Map</code>, with the new row's data.</p>54917195288	0	remove "+" or "0" from a telephone number string <p>i need in php a regular expression to remove from a string of telephone numbers the + or the 0 at the beginning of a number</p> <p>i have this function to remove every not-number characters</p> <pre><code>ereg_replace("[^0-9]", "", $sPhoneNumber) </code></pre> <p>but i need something better, all these examples should be...</p> <pre><code>$sPhoneNumber = "+3999999999999" $sPhoneNumber = "003999999999999" $sPhoneNumber = "3999999999999" $sPhoneNumber = "39 99999999999" $sPhoneNumber = "+ 39 999 99999999" $sPhoneNumber = "0039 99999999999" </code></pre> <p>... like this</p> <pre><code>$sPhoneNumber = "3999999999999" </code></pre> <p>any suggestions, thank you very much!</p>55016218085	0	 <p>Here, check this out! This is what you need! </p> <p>This tut explains everything you need -> <a href="http://www.learningjquery.com/2009/02/slide-elements-in-different-directions" rel="nofollow"><strong>Slide Elements in Different Directions</strong></a></p>5518307372	0	Diagnostics not available in Insights <p>I have a couple of apps on Facebook. I would like to be able to see how many wallposts per user I am allowed to make. I know I can see this on insights (http://www.facebook.com/insights) by opening an app and clicking on "diagnostics" in the left column under "App insights".</p> <p>However: for a couple of my apps there is no "diagnostics" link under "App insights". There is only a button that says "Open graph".</p> <p>I have no idea what the difference is between the apps that have and don't have the "diagnostics" button. Can anyone give me some insight (har har) on this?</p>55216822317	0	getText between tags with Selenium <p>I'm trying to parse the following XML file so that I can get some attributes. One thing I need to do is verify that the content between tags is not empty. To do this, I though I would be able to use the getText method provided for web elements.</p> <p>The XML file:</p> <pre><code>&lt;results&gt; &lt;result index="1"&gt; &lt;track&gt; &lt;creator&gt;Cool&lt;/creator&gt; &lt;album&gt;Amazing&lt;/album&gt; &lt;title&gt;Awesome and Fun&lt;/title&gt; &lt;/track&gt; &lt;/result&gt; &lt;/results&gt; </code></pre> <p>My code for parsing through and getting what I want is as follows (keep in mind there is more than one result):</p> <pre><code>boolean result = false; driver.get(url); List&lt;WebElement&gt; result_list = driver.findElements(By.xpath(".//result")); if (result_list.size() == num_results) { try { for (int i = 0; i &lt; result_list.size(); i++) { WebElement track = result_list.get(i).findElement(By.xpath(".//track")); WebElement creator = track.findElement(By.xpath(".//creator")); System.out.println(creator.getText()); track.findElement(By.xpath(".//album")); track.findElement(By.xpath(".//title")); } result = true; } catch (Exception e) { result = false; } } return result; </code></pre> <p>The problem is that the System.out.println call returns an empty string when there is clearly text between the creator tags. Any help would be greatly appreciated!</p>55318342913	0	 <p>Make sure your zoom is at 100%. Also in <strong>Internet Options > security</strong> you need to make sure that 'Enable protected mode' is selected on all 4 zones. </p>55432863649	0	How to add an action to notifications in Swift 2 iOS 9 <p>I'm trying to get a button in my notifications send with PHP Apns <a href="http://immobiliare.github.io/ApnsPHP/html/" rel="nofollow">http://immobiliare.github.io/ApnsPHP/html/</a></p> <p>Following this documentation from Apple: <a href="https://developer.apple.com/library/ios/documentation/General/Conceptual/WatchKitProgrammingGuide/BasicSupport.html#//apple_ref/doc/uid/TP40014969-CH18-SW5" rel="nofollow">https://developer.apple.com/library/ios/documentation/General/Conceptual/WatchKitProgrammingGuide/BasicSupport.html#//apple_ref/doc/uid/TP40014969-CH18-SW5</a></p> <p>But the buttons never show..</p> <p>My code:</p> <pre><code> var categories = NSMutableSet() var acceptAction = UIMutableUserNotificationAction() acceptAction.title = NSLocalizedString("Accept", comment: "Accept") acceptAction.identifier = "accept" acceptAction.activationMode = UIUserNotificationActivationMode.Background acceptAction.authenticationRequired = false var declineAction = UIMutableUserNotificationAction() declineAction.title = NSLocalizedString("Decline", comment: "Decline") declineAction.identifier = "decline" declineAction.activationMode = UIUserNotificationActivationMode.Background declineAction.authenticationRequired = false var inviteCategory = UIMutableUserNotificationCategory() inviteCategory.setActions([acceptAction, declineAction], forContext: UIUserNotificationActionContext.Default) inviteCategory.identifier = "cat1" categories.addObject(inviteCategory) let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: (NSSet(array: [categories])) as? Set&lt;UIUserNotificationCategory&gt;) UIApplication.sharedApplication().registerUserNotificationSettings(settings) UIApplication.sharedApplication().registerForRemoteNotifications() </code></pre> <p>My APNS code:</p> <pre><code>$push = new ApnsPHP_Push(ApnsPHP_Abstract::ENVIRONMENT_PRODUCTION, 'dict_prod.pem'); $push-&gt;setProviderCertificatePassphrase('XXXXXXX'); $push-&gt;setRootCertificationAuthority('entrust_root_certification_authority.pem'); $push-&gt;connect(); $message = new ApnsPHP_Message("THE TOKEN"); $message-&gt;setText("Test"); $message-&gt;setSound('default'); $message-&gt;setExpiry(30); $message-&gt;setCategory('cat1'); $push-&gt;add($message); $push-&gt;send(); $push-&gt;disconnect(); $aErrorQueue = $push-&gt;getErrors(); if (!empty($aErrorQueue)) { var_dump($aErrorQueue); } </code></pre>55516229840	0	android - required layout_attribute is missing <pre><code>&lt;shape xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" &gt; &lt;gradient android:layout_width="match_parent" android:angle="270" android:centerColor="#4ccbff" android:endColor="#24b2eb" android:startColor="#24b2eb" /&gt; &lt;corners android:radius="5dp" /&gt; &lt;/shape&gt; </code></pre> <p>The above code shows " required <code>layout_height</code> attribute is missing" on the line no <strong>4</strong> </p> <p>&amp; </p> <p>"required <code>layout_height</code> and <code>layout_width</code> attribute is missing" on the line no <strong>11</strong>.</p>55698081	0	 <p>I've used <a href="http://pmock.sourceforge.net/" rel="nofollow noreferrer">pMock</a> in the past, and didn't mind it, it had pretty decent docs too. However, Foord's Mock as mentioned above is also nice.</p>55721023322	0	 <p>try adding </p> <pre><code>div.myClass{ position: absolute; bottom:0; width:100%; } </code></pre> <p>to the div.</p> <p><strong>Example with the div positioned only on td bottom.</strong> </p> <p><a href="http://jsfiddle.net/chin/T3TqE/" rel="nofollow">JSFiddle</a> </p>55810818756	0	 <p>Your selectors are incorrect, you're using the hash to indicate and <strong>id</strong>. Also you're prefixing your classes with an element notation that is not correct.</p> <p>This </p> <pre><code>if($('#tr').hasClass('tr_group')) </code></pre> <p>should be:</p> <pre><code>if($('tr').hasClass('group')) </code></pre>55925618368	0	 <p>The "Micro" version of Cloud Foundry is not available for Cloud Foundry V2 users onward. Check those options to run Cloud Foundry V2 locally: <a href="http://docs.cloudfoundry.org/deploying/run-local.html" rel="nofollow">http://docs.cloudfoundry.org/deploying/run-local.html</a> </p> <p>This currently includes bosh-lite and cf_nise_installer.</p>56024510945	0	 <p>Save is meant to insert one document. Update can be used over several documents that match the criteria in the first parameter.</p> <p>Under certain circumstances (specifying a unique id as the criteria, upsert:true, and not using multi: true) both can serve the same purpose.</p>5619400307	0	 <p>Browser configuration settings are available in <a href="http://sdllivecontent.sdl.com/LiveContent/web/ui.xql?action=html&amp;resource=login.html&amp;destination=/LiveContent/web/pub.xql?action=home&amp;pub=SDL_Tridion_2011&amp;lang=en-US#url=http://sdllivecontent.sdl.com:80/LiveContent/web/search.xql;jsessionid=124ke8dtvh9ur?id=124ke8dtvh9ur&amp;pub=SDL_Tridion_2011&amp;lang=en-US&amp;action=search&amp;query=events&amp;sid=lcSearch.runSearch1309417963999&amp;eventType=lcContent.loadDocet_concept_382BF5DCD4BF401ABDE0B58D28E1B11C&amp;query=events&amp;scope=&amp;resource=08e288f2-faef-470d-b26e-7f98d85e9595.xml&amp;filename=EventTriggers.xml&amp;docid=et_concept_382BF5DCD4BF401ABDE0B58D28E1B11C&amp;inner_id=&amp;tid=29213774-9889-4628-b74a-2e8c645ea8fb&amp;addHistory=true">online documenation</a>, I suggest adding as a "Trusted Site"</p>56228559864	0	Comparing values of two promises <p>I wish to achieve the following:</p> <pre><code>var textPromise1 = element(by.id('id1')).getText(); var textPromise2 = element(by.id('id2')).getText(); if(textPromise1.SOMELOGIC == textPromise2.SOMELOGIC ) console.log('These are equal') </code></pre> <p>I know the promise is resolved using .then(). However, I want to know if there exists some way with which above can be achieved!</p> <p>Thanks,</p>56310692147	0	Error while installing caldecott <p>I am getting this error while running this command on windows <code>prompt&gt; gem insatll caldecott</code>. I have downloaded the development kit but the error is still the same.</p> <p>Please update your PATH to include build tools or download the DevKit from 'http://rubyinstaller.org/downloads' and follow the instructions at 'http://github.com/oneclick/rubyinstaller/wiki/Development-Kit'</p>5646300010	0	 <p>All of your questions can be solved very easy if you use a DFS for each relationship and then use your function calculate() again if you want it more detailed.</p>5656487736	0	 <p>Try:</p> <pre><code>$('.btn-reply').click(function(){ $(this).parents('.roar').siblings('.newreply').toggleClass('show'); return false; }); </code></pre> <p>However, I agree with <code>Francisc</code> that a better approach would be to modify the <code>HTML</code> and assign a unique <code>id</code> to each message set. That way you can grab the <code>.newreply</code> to show based on a shared unique <code>id</code> which would be agnostic regarding the positioning of the <code>HTML</code> layout.</p> <p>E.g.</p> <pre><code>&lt;div class="roar" rel="msg0"&gt;...&lt;/div&gt; ... &lt;button class="btn-reply" rel="msg0"&gt;&lt;/button&gt; ... &lt;div class="newreply" rel="msg0"&gt;...&lt;/div&gt; ... </code></pre> <p>Then your jQuery becomes:</p> <pre><code>$('.btn-reply').click(function(){ var id = $(this).attr('rel'); var selector = '.newreply[rel=' + id + ']'; $(selector).toggleClass('show'); return false; }); </code></pre>56623782945	0	 <p>Thanx cs 1088,</p> <p>I basically used casting a List to an array List as you correctly proposed and I finally after much mucking about realised I needed to use this structure below to cast the IList back to a BIC after retrieving the array from the Schema.</p> <p>userCheckedbuiltInCategory = retrievedData.Cast().ToList();</p>56716059073	1	How to change file_extension internally in Blender 2.65 <p>I am writing a python script for Blender and I am quite new. I want to change output file format in render option internally. For example, <code>context.scene.render.file_extension = "PNG"</code> . But it is a read-only variable so I get an error. Is there a way to change it in code? </p> <p>I am using Blender-2.65.</p>56836256047	0	 <p>Your <code>codeResult()</code> method throws <code>Exception</code></p> <pre><code>public int coderesult (String urlstring) throws Exception { </code></pre> <p>Therefore, you must either catch it specifically <code>catch(Exception ex)</code> , or declare that your throw it from your method.</p> <p>When catching exceptions, you either catch a specific exception type, or a more generic parent exception type. You could combine all catches into one catch, because all built in java exceptions extend from Exception</p> <pre><code>catch(Exception ex){ ex.printStackTrace(); } </code></pre>56928818282	0	 <p>You can make regular expression groups by using <code>(</code> and <code>)</code> and reference then in replace using <code>$N</code>, which will access <code>N-th</code> group.</p> <p>So in your case, you can do this regex: <code>([^: ]+:[^:]+:([^:]+):[^:]+:[^:]+)(:[^: ]+)</code> replace: <code>\1&lt;\2&gt;\3</code> or on some implementation <code>$1&lt;$2&gt;$3</code></p> <p>You can try it yourself here: <a href="https://www.regex101.com/r/hY8pY9/1" rel="nofollow">https://www.regex101.com/r/hY8pY9/1</a></p>57032955667	0	 <p>I think I have an answer for you. In this you do not have to flip the y-axis, and I can get the names in the x-axis, but I still use a hierarchy. I'm not sure it's more efficient, but here goes.</p> <p>First, I created a Hierarchy defined as:</p> <pre><code>CREATE NESTED HIERARCHY [New hierarchy (2)] [yearsOfExp] AS [yearsOfExp], [name] AS [name] </code></pre> <p>This allowed me to order the category axis by years of experience.</p> <p>Secondly, I created a calculated column defined as: </p> <pre><code>Sum([yearsOfExp]]) over (AllNext([yearsOfExp]])) </code></pre> <p>I then created a line chart. The hierarchy is the x axis and the calculated column is the y axis. When setting the x axis, be sure to "reverse scale". <a href="https://i.stack.imgur.com/9RL8C.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9RL8C.png" alt="enter image description here"></a></p> <p>I hope this does what you're looking for. Good luck. Any questions, just ask.</p>57138428541	0	How to erase rows in a data frame R <p>I have a data frame that look like this:</p> <pre><code>Quality Data Name 1 667 green 3 647 white 1 626 Blue 2 345 yellow 1 550 Blue 5 730 green </code></pre> <p>i want a code that goes through a for loop and takes the one less the 600 and greater than 700 and delete the row &amp;&amp; all the ones with the same name and saves the ones that were deleted in another data frame<br> example </p> <pre><code> for i in nrow(df){ if (df$Data[i]&lt;=600 || df$Data[i]&gt;=700){ Subset_by_name=subset(df,df$Name==df$Name[i]) (saves bad samples) (delete from data) Subset_by_name=data.frame(Subset_by_name) bad_sample=rbind(Subset_by_name) (saves all the bad data in a data frame) } } </code></pre> <p>result<br> bad_sample</p> <pre><code>Quality Data Name 1 667 green 1 626 Blue 2 345 yellow 1 550 Blue 5 730 green </code></pre> <p>data</p> <pre><code>Quality Data Name 3 647 white </code></pre> <p>help please????</p>57220856099	0	Meteor Js , Store images to mongoDB <p>I want to store an image browsed by a file input to database. I am browing the image using redactor plugin using this code </p> <pre><code>$('.editor').redactor({ imageUpload:"/uploads" }); </code></pre> <p>Using this when i select or browse an image i am directly sending that image to server using meteor HTTP-methods </p> <pre><code>HTTP.methods({ '/uploads': function(data) { console.log(data) Meteor.call("uploadImage",data) return JSON.stringify({'Hello':"hello"}); } }); </code></pre> <p>Here when i am doing console.log data I am getting the 64bit binary code for the image. Now i want to save this data to the mongodb database.<br> I am using meteor-collection 2 for defining fields and their types. But i couldn't get which data type i have to use to store image to the mongo db.<br> I am trying to use mongodb gridfs to store the image. Tell me how can i store image in mongodb ? Thanx </p>57330157519	0	 <p>Use $user->profile() ->save(new UserProfile($params)); </p>57437706079	0	Prevent HTML Removing Successive spaces <p>I have an issue in a JSP page where I have to display a generated message onscreen based on a string. It all works fine until one of the account numbers contains two spaces.</p> <p>So, I have this HTML:</p> <pre><code> &lt;logic:notEqual name="migrationsMessage" value=""&gt; &lt;div style="color:Red;font-weight:bold"&gt; &lt;bean:write name="solasDetailsForm" property="migrationsMessage"/&gt; &lt;/div&gt; &lt;/logic:notEqual&gt; </code></pre> <p>When the field migrationsMessage contains this:</p> <pre><code>&lt;input type="hidden" name="migrationsMessage" value="A 123456W has migrated to A 123456."&gt; </code></pre> <p>The output on the screen is this:</p> <pre><code>“A 123456W has migrated to A 123456.” </code></pre> <p>The second space after the first A is removed. I tried to alter the style to be this but it didn't help:</p> <pre><code> &lt;logic:notEqual name="migrationsMessage" value=""&gt; &lt;div style="color:Red;font-weight:bold;white-space:pre"&gt; &lt;bean:write name="solasDetailsForm" property="migrationsMessage"/&gt; &lt;/div&gt; &lt;/logic:notEqual&gt; </code></pre> <p>Any ideas what is going wrong?</p>5758018632	0	 <p>It is not possible to <em>reliably</em> get sorted results without explicitly using <code>ORDER BY</code>.</p> <p>Sources:</p> <p><a href="http://sqlblog.com/blogs/hugo_kornelis/archive/2006/12/31/Beatles-vs-Stones.aspx" rel="nofollow">The Beatles versus the Stones</a> </p> <p><a href="http://sqlblog.com/blogs/alexander_kuznetsov/archive/2009/05/20/without-order-by-there-is-no-default-sort-order.aspx" rel="nofollow">Without ORDER BY, there is no default sort order</a> </p>57640370122	0	Best way to index a SQL table to find best matching string <p>Let's say I have a SQL table with an <code>int</code> PK column and an <code>nvarchar(max)</code>. In the the <code>nvarchar(max)</code> column, I have a bunch of table entries that are all like this:</p> <pre><code>SOME_PEOPLE_LIKE_APPLES SOME_PEOPLE_LIKE_APPLES_ON_TUESDAY SOME_PEOPLE_LIKE_APPLES_ON_THE_MOON SOME_PEOPLE_LIKE_APPLES_ON_THE_MOON_CAFE SOME_PEOPLE_LIKE_APPLES_ON_THE_RIVER . . . SOME_ANTS_HATE_SYRUP SOME_ANTS_HATE_SYRUP_WITH_STRAWBERRIES </code></pre> <p>There's millions of these rows - Then let's say my goal is to find the row with the most overlap for an input <code>searchTerm</code> - So in this case, if I input <code>SOME PEOPLE_LIKE_APPLES_ON_THE_MOON_MOUNTAIN</code>, the returned entry would be the third entry from the table above, <code>SOME_PEOPLE_LIKE_APPLES_ON_THE_MOON</code></p> <p>I have a SPROC that does this very naively, it goes through the entire table as follows:</p> <pre><code>SELECT DISTINCT phrase, len(phrase) l, [id] FROM X WHERE searchTerm LIKE phrase + '%' -- phrase is the row entry being searched against -- searchTerm is the phrase we're searching for </code></pre> <p>I then <code>ORDER BY</code> length and pick the <code>TOP</code> only</p> <p>Would there be a way to speed this up, perhaps by doing some indexing?</p> <p>If this is confusing, think of it as <code>tableRowEntry + wildcard = searchTerm</code></p> <p>I'm on MSSQL 2008 if that makes any difference</p>57729924627	0	 <p>You could look into <a href="http://developer.android.com/reference/android/app/Application.html#registerActivityLifecycleCallbacks%28android.app.Application.ActivityLifecycleCallbacks%29" rel="nofollow"><code>Application.registerActivityLifecycleCallbacks()</code></a> &amp;c.</p>5787313818	0	 <p>As mentioned in the comments by HK1, here's what can be done (although it's workaround):</p> <p>Use a continuous form instead of the datasheet.</p>57929392005	0	Generate a unique number that is formed from 2 numbers and vice versa? <p>I am not sure if this is possible but,</p> <p>I have 2 numbers, a 32-bit int x and a 64-bit long y.</p> <p>Given that 'y' is ALWAYS unique.</p> <p>Given these numbers, I want to generate a unique identifier which is a 32-bit int. I should also be able to construct the individual numbers back from the unique identifier. Is this possible? I apologize if this is the wrong forum to ask, but this is related to C# programming on a project i am working on.</p> <p>Basically, 'x' refers to a categoryID and 'y' refers to a unique 'categoryItemId' in my database, a single category can have a million of catalogItems.</p> <p>Thanks!</p>58020207798	0	 <p>Your using <code>WriteString</code> to display a string. <code>WriteString</code> uses <code>edx</code> to hold the address of the string to print.</p> <p>You call <code>DisplayPrompt</code> and move the address of <code>vHexPrompt</code> into <code>edx</code>, then you call <code>DisplayString</code> and in that function, you call <code>WriteString</code>. <code>edx</code> still contains the address of <code>vHexPrompt</code> which is why you are getting a double prompt.</p> <p>Until you write more code to utilize <code>DisplayString</code>, either comment out the call to writestring in that function, or just add <code>xor edx, edx</code> right before your call to <code>WriteString</code> in <code>DisplayString</code></p>58117387295	0	 <p>You don't need to use Regex, you can just use .length to search for the longest string.</p> <p>i.e.</p> <pre><code>function longestWord(string) { var str = string.replace(/[\.,-\/#!$%\^&amp;\*;:{}=\-_`~()]/g,"").split(" "); longest = str[0].length; longestWord = str[0]; for (var i = 1; i &lt; str.length; i++) { if (longest &lt; str[i].length) { longest = str[i].length; longestWord= str[i]; } } return longestWord; } </code></pre> <p>EDIT: You do have to use some Regex...</p>5824382442	0	 <p>(Before the longer discussion: it looks like you're typing <code>myButton</code> one line 2, and <code>eventButton</code> on line 3. Make sure these match!)</p> <p>You're correct in thinking that you're creating a new instance of <code>mainViewController</code>. To get at the one you want, You'll either need to pass a reference to <code>mainViewController</code> into the new view controller when you create it, writing a method like:</p> <pre><code>@synthesize mainViewController; -(void) initWithMainVC:(MainViewController *)mainVC { if ((self = [super init])) { self.mainViewController = mainVC; } return self; } </code></pre> <p>to override <code>init</code>, or, if you've got a reference to <code>mainViewController</code> in your App Delegate, you can get it using:</p> <pre><code>MainViewController *mainVC = [(YourAppDelegate *)[[UIApplication sharedApplication] delegate] mainViewController]; </code></pre> <p>Either way you choose, you'll want to read up on object oriented programming and pointers in objective C. When you call <code>alloc</code>, you're manufacturing a new copy of that class. All copies sit in different chunks of memory, so any new one you make (as in your code above) is actually a totally different entity, like two Priuses, or something like that.</p> <p>A pointer is like a nametag that identifies, or points the way, to that block of memory. In my <code>init</code> code example above, we're attaching a new nametag to a <code>mainViewController</code> instance with the same guts. Same thing with the second line -- we make a new pointer (see the star?) tell it it's going to be pointing to a <code>MainViewController</code> instance, and slap that nametag, or pointer, on to an instance.</p> <p>(The second one is a little more complicated, as you're plucking <code>mainViewController</code> from an object called a singleton, or an object that you can get at from anywhere... read more about those and the App Delegate at <a href="http://cocoawithlove.com/2008/11/singletons-appdelegates-and-top-level.html" rel="nofollow">this post</a> from Cocoa with Love.)</p> <p>Anyway, I get nervous expounding on this stuff on Stack! Check out Apple's <a href="http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ObjectiveC/ObjC.pdf" rel="nofollow">Objective C</a> reference for some more of the basics. The sample code on the <a href="http://developer.apple.com/devcenter/ios/index.action" rel="nofollow">iOS Dev Center</a> is really, really good to check out. Download a project that looks nice, or, better yet, just create a project from an Xcode template, and go try to figure out how it's stitched together. Good luck!</p>58310514710	0	 <p>If you want anything starting with page1 to be rewritten, this will work:</p> <pre><code> RewriteRule ^page1.* http://www.example.com/newpage.htm [R=301,L] </code></pre> <p>If you want only page1 and page1.htm to be rewritten, but not e.g. page1whatever, this should work:</p> <pre><code> RewriteRule ^page1(.htm)? http://www.example.com/newpage.htm [R=301,L] </code></pre>58412911179	0	 <p>You must specify the following property</p> <pre><code>sonar.host.url=http://localhost:9100 </code></pre> <p>, if you want Sonar batch to connect to the correct URL.</p> <p>You can set it either as a property in your Ant script or a JVM parameter.</p>5854666017	0	 <p>You can access faster to local vars, also you can shorten the variable name "window" (and even "document") with something like:</p> <pre><code>(function(w, d)(){ // use w and d var })(window, document) </code></pre>58632518542	0	How to set up dc.js x axis for dates <p>I have a CSV file with 2 columns, in the first I have got some dates, in the second there are some values. </p> <p>How do I initialize the x axis to show dates?</p>58721929808	0	 <p><code>c_str</code> is a method on a string, so you need to call it like <code>cell.c_str()</code> to tell the compiler is a method, not a class member</p>58834587113	0	 <p>My opinion is that you can remove the <code>george_holiday_passengers</code> and add the <code>type,age,gender</code> columns to the <code>george_holiday_users</code> as looking to it; its only a extended data of the <code>holiday_users</code> table and build query with your new database tables.</p> <pre><code>$query = $this-&gt;db-&gt;select('u.*, p.package_name, p.description') -&gt;from('george_holiday_users u') -&gt;join('george_packges p', 'u.package_id = p.id', 'left') -&gt;get(); return $query-&gt;result(); </code></pre> <p>anyway, you can achieved the result using this query.</p> <pre><code>$query = $this-&gt;db-&gt;select('u.*, hp.type, hp.name AS passengers_name, hp.age, hp.gender, p.package_name, p.description') -&gt;from('george_holiday_users u') -&gt;join('george_holiday_passengers hp', 'hp.user_id = u.id', 'left') -&gt;join('george_packges p', 'u.package_id = p.id', 'left') -&gt;get(); return $query-&gt;result(); </code></pre> <p>you should be careful about the column names because on your database there are a lot of columns with the same names, It might affect your query when your using joins, etc.</p> <p>Hope that helps.</p>58923446458	0	 <p>Do you really use command <code>dir</code> in your batch file or another command, a command which itself is enclosed in double quotes because of a space in path or has a parameter in double quotes?</p> <p>If the output of a command should be processed within the loop and the command itself must be specified in double quotes or at least one of its parameters, the following syntax using back quotes is required:</p> <pre><code>for /f "usebackq delims=" %%a in (`"command to run" "command parameter"`) do echo %%a </code></pre> <p>An example:</p> <pre><code>for /f "usebackq delims=" %%a in (`dir "%CommonProgramFiles%"`) do echo %%a </code></pre> <p><code>%CommonProgramFiles%</code> references the value of environment variable <strong>CommonProgramFiles</strong> which is a directory path containing usually spaces. Therefore it is necessary to enclose the parameter of command <code>dir</code> in double quotes which requires the usage of <code>usebackq</code> and back quotes after the opening and before the closing round bracket.</p> <p>Further I suggest to look on value of environment variable <strong>PATH</strong>. There are applications which add their program files directory to <strong>PATH</strong> during installation, but not by appending the directory to end of the list of directories, but by inserting them at beginning. That is of course a bad behavior of the installer of those applications.</p> <p>If you call in your batch file standard Windows commands not located in cmd.exe, but in Windows system directory which is usually the first directory in <strong>PATH</strong>, like the command <code>find</code>, and the installed application by chance has also an executable with same name in the program files directory of the application, the batch file might not work on this computer because of running the wrong command.</p> <p>It is safer to use instead of just <code>find</code> in a batch file <code>%SystemRoot%\system32\find.exe</code> to avoid problems caused by bad written installer scripts of applications modifying the <code>PATH</code> list on wrong end.</p>59016002801	0	Find if any element is present in System.Array or not and if exists remove from the original <p>I have three System.Array where I store basically phone numbers with 10 characters. The definition is this:</p> <pre><code>private static System.Array objRowAValues; private static System.Array objRowBValues; private static System.Array objRowCValues; </code></pre> <p>I do this because I read a huge Excel file with many cells (around 1 000 000) and process with <code>List&lt;string&gt;</code> is a bit slow. Later in my code I change the System.Array to a <code>List&lt;string&gt;</code> mainly because I fill a ListBox elements. These are the definition for the List</p> <pre><code>private List&lt;string&gt; bd = new List&lt;string&gt;(); private List&lt;string&gt; bl = new List&lt;string&gt;(); private List&lt;string&gt; cm = new List&lt;string&gt;(); </code></pre> <p>I want to check if any values in objRowAValues exists in objRowBValues or in objRowCValues and if exists then remove the existent value, how can I do this? I'm newbiew with C# and this is my first steps.</p> <p><strong>EDIT: here is the code (relevant parts only) of what I'm doing:</strong></p> <pre><code>private List&lt;string&gt; bd = new List&lt;string&gt;(); private static System.Array objRowAValues; private List&lt;string&gt; bl = new List&lt;string&gt;(); private static System.Array objRowBValues; private List&lt;string&gt; cm = new List&lt;string&gt;(); private static System.Array objRowCValues; private List&lt;string&gt; pl = new List&lt;string&gt;(); private static Microsoft.Office.Interop.Excel.Application appExcel; Excel.Application xlApp; Excel.Workbook xlWorkBook; Excel.Worksheet xlWorkSheet; Excel.Range rngARowLast, rngBRowLast, rngCRowLast; long lastACell, lastBCell, lastCCell, fullRow; // this is the main method I use to load all three Excel files and fill System.Array and then convert to List&lt;string&gt; private void btnCargarExcel_Click(object sender, EventArgs e) { if (this.openFileDialog1.ShowDialog() == DialogResult.OK) { if (System.IO.File.Exists(openFileDialog1.FileName)) { Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); Thread.Sleep(10000); filePath.Text = openFileDialog1.FileName.ToString(); xlApp = new Microsoft.Office.Interop.Excel.Application(); xlWorkBook = xlApp.Workbooks.Open(openFileDialog1.FileName, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0); xlWorkSheet = (Excel.Worksheet) xlWorkBook.Worksheets.get_Item(1); fullRow = xlWorkSheet.Rows.Count; lastACell = xlWorkSheet.Cells[fullRow, 1].End(Excel.XlDirection.xlUp).Row; rngARowLast = xlWorkSheet.get_Range("A1", "A" + lastACell); objRowAValues = (System.Array) rngARowLast.Cells.Value; foreach (object elem in objRowAValues) { bd.Add(cleanString(elem.ToString(), 10)); } nrosProcesados.Text = bd.Count().ToString(); listBox1.DataSource = bd; xlWorkBook.Close(true, null, null); xlApp.Quit(); releaseObject(xlWorkSheet); releaseObject(xlWorkBook); releaseObject(xlApp); stopWatch.Stop(); TimeSpan ts = stopWatch.Elapsed; executiontime.Text = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds/10).ToString(); } else { MessageBox.Show("No se pudo abrir el fichero!"); System.Runtime.InteropServices.Marshal.ReleaseComObject(appExcel); appExcel = null; System.Windows.Forms.Application.Exit(); } } } // This is the method where I clean the existent values from bd (the List where I should remove existent values on bl and existent values on cm private void btnClean_Click(object sender, EventArgs e) { pl = bd; Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); Thread.Sleep(10000); pl.RemoveAll(element =&gt; bl.Contains((element))); pl.RemoveAll(element =&gt; cm.Contains((element))); textBox2.Text = pl.Count.ToString(); listBox4.DataSource = pl; stopWatch.Stop(); TimeSpan ts = stopWatch.Elapsed; textBox6.Text = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10).ToString(); } </code></pre>59129205252	0	Android: java.lang.StringIndexOutOfBoundsException: on copy to clipboard selected text on long press event <p>In my app I would like to give copy to clipboard selected text functionality on long press event.foo is a text view foo = (TextView) findViewById(R.id.single_string);. I am using the below code to implement this functionality.</p> <pre><code> protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); activateToolbar(); text = parseSourceCode(text); foo = (TextView) findViewById(R.id.single_string); foo.setTextSize(mRatio + 14); foo.setText(Html.fromHtml(text,imgGetter, null)); foo.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { String stringYouExtracted = foo.getText().toString(); int startIndex = foo.getSelectionStart(); int endIndex = foo.getSelectionEnd(); stringYouExtracted = stringYouExtracted.substring(startIndex, endIndex); if(android.os.Build.VERSION.SDK_INT &lt; android.os.Build.VERSION_CODES.HONEYCOMB) { android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); clipboard.setText(stringYouExtracted); } else { android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); android.content.ClipData clip = android.content.ClipData.newPlainText("Copied Text", stringYouExtracted); clipboard.setPrimaryClip(clip); } // TODO Auto-generated method stub return false; } }); </code></pre> <p>I am able to set the text but my code is getting crashed when I press long on the screen to copy the selected text. Error I am getting is : </p> <pre><code>java.lang.StringIndexOutOfBoundsException: length=3704; regionStart=-1; regionLength=0 at java.lang.String.startEndAndLength(String.java:504) at java.lang.String.substring(String.java:1333) at java.lang.String.subSequence(String.java:1671) – </code></pre>59221501160	0	 <p>addGestureRecognizer is a method on UIView, not UIViewController.</p> <p>Try </p> <pre><code> [self.view addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(isTapped:)]]; </code></pre>59335397885	0	 <p>I encountered this issue as you did. I got an error that's something like "couldn't find package Emacs-24.4". This inspired me to install <code>Emacs-24.4</code> on my Ubuntu, instead of older version <code>24.3</code> which is the newest I can get from <code>apt-get</code>. (A convincing fact is that the newer version <code>24.5</code> provided by <code>Homebrew</code> works well with Purcell's package on my Mac.) </p> <p>Under <code>Emacs 24.4</code>, <code>slime</code> proved to run well with Purcell's <code>.emacs.d/</code>. But it really costs me a lot of time to install <code>Emacs-24.4</code> on my Ubuntu. First, I had to solve the problems of dependencies. Using <code>aptitude</code>, I get rid of the problem which <code>apt-get</code> failed to solve:</p> <pre><code>sudo apt-get install aptitude sudo aptitude install build-essential sudo aptitude build-dep emacs24 </code></pre> <p>When the dependency issue pops out, <code>aptitude</code> will give you some suggestions including downgrading your current packages. I chose solutions of downgrade without leaving over any unsolved dependency problem (select 'no' until you find an acceptable one). During reinstalling build packages, Ubuntu iso cdrom may be required. </p> <p>Then install <code>Emacs 24.4</code>:</p> <pre><code>wget http://open-source-box.org/emacs/emacs-24.4.tar.xz tar xvf emacs-24.4.tar.xz cd emacs-24.4 ./configure --prefix=$HOME/.local LDFLAGS=-L$HOME/.local/lib --without-pop --without-kerberos --without-mmdf --without-sound --without-wide-int --without-xpm --without-jpeg --without-tiff --without-gif --without-png --without-rsvg --without-xml2 --without-imagemagick --without-xft --without-libotf --without-m17n-flt --without-xaw3d --without-xim --without-ns --without-gpm --without-dbus --without-gconf --without-gsettings --without-selinux --without-gnutls --without-x make &amp;&amp; make install </code></pre> <p>References: </p> <p><a href="https://gist.github.com/tnarihi/6054dfa7b4ad2564819b" rel="nofollow">https://gist.github.com/tnarihi/6054dfa7b4ad2564819b</a></p> <p><a href="http://linuxg.net/how-to-install-emacs-24-4-on-ubuntu-14-10-ubuntu-14-04-and-derivative-systems/" rel="nofollow">http://linuxg.net/how-to-install-emacs-24-4-on-ubuntu-14-10-ubuntu-14-04-and-derivative-systems/</a></p>59426217398	0	Cannot get div element by id to display gif in internet explorer <p>I am trying to make a .gif image display in a loading window to alert my user that loading is underway, quite simple. I was doing it using only css and <code>background</code> property like this:</p> <p>/<em>background: url(ajax-loader.gif) no-repeat center #fff;</em>/</p> <p>but my .gif was not loading in internet explorer. So I've made a research and found <a href="http://stackoverflow.com/questions/780560/animated-gif-in-ie-stopping">this</a> and, based on J.Davies's solution, I have implemented this instead in my js file:</p> <pre><code>function ShowProgress() { if (!spinnerVisible) { $('div#layer').fadeIn("fast"); $('div#spinner').fadeIn("fast"); spinnerVisible = true; var pb = $('#spinner'); pb.innerHTML = '&lt;img src="./ajax-loader.gif" width=200 height=40/&gt;'; pb.style.display = ""; } } </code></pre> <p>My problem is that it works still in chrome, but I get a crash in internet explorer saying that it pb is undefined. Is there a specificity on how to work with jquery and internet explorer? For information, here's my display:</p> <pre><code>&lt;div id="body"&gt; @RenderSection("featured", false) &lt;section class="content-wrapper main-content clear-fix"&gt; &lt;section&gt; @Html.Partial("MessageDisplay") &lt;/section&gt; &lt;div id="layer"&gt;&lt;/div&gt; &lt;div id="spinner"&gt; Loading, please wait... &lt;/div&gt; @RenderBody() &lt;/section&gt; &lt;/div&gt; </code></pre> <p>And the css saying that spinner and layer div are hidden:</p> <pre><code>div#spinner { display: none; width: 300px; height: 300px; position: fixed; top: 40%; left: 45%; /*background: url(ajax-loader.gif) no-repeat center #fff;*/ text-align: center; padding: 10px; font: normal 16px Tahoma, Geneva, sans-serif; border: 1px solid #666; margin-left: -50px; margin-top: -50px; z-index: 2; overflow: auto; } div#layer { display: none; width: 100%; height: 100%; position: fixed; top: 0; left: 0; background-color: #a4a3a3; background-color: rgba(164, 163, 163, 0.5); z-index: 1; overflow: auto; -moz-opacity: 0.5 } </code></pre>59512810133	0	link static library in c++ visual studio <p>can someone please help me to understand the process.</p> <p>in c++ visual studio 2010 </p> <p>i have a visual studio solution (lets call it mysol)</p> <p>i have a project built as a static library (let's call it staticprj) staticprj needs to use a library from outside (lets call it ext.lib)</p> <p>in the body of the source code of staticprj i include outside library header file with # include extlib.h and make calls to some of its functions (let call them extfunctions()) i also include the the path to the header files location of the ext.lib.</p> <p>the staticprj compiles okay without errors</p> <p>the mysol also has another project which is a dynamic library (dynprj) and which depends on the staticprj. </p> <p>also in the source files of the dynprj uses functions from outside library.</p> <p>i have included #include extlib.h in the source code of dynprj. i have included the path of the header files i have attached extlib.h directly to the dynprj i have also added ext.lib to the linker input (along with the path where the ext.lib resides).</p> <p>i still get a lnk2001 error stating that extfunctions() where not found.</p> <p>the whole structure (the mysol solution) compiles okay if i do not use ext.lib at all. </p> <p>my question is how does the linking process works and what can i do to correct this linking error.</p> <p>(note that without the presence of ext.lib my linking of the staticprj and dynprj is fine. my compilation works okay and my code works. i only get the linking error when i try to link another ext.lib to staticprj and dynprj and use functions from ext.lib)</p> <p>thanks in advance.</p>59615570462	0	 <p>I don't know about <em>that other editor</em>, but for Vim syntax highlighting, this is definitely not possible. Why?</p> <ul> <li>Vim syntax definitions are written in Vimscript; it would require a complete interpreter.</li> <li>Most definitions use regular expressions; no other engine implements exactly the same flavor; some atoms are unique to Vim.</li> </ul> <p>If you just want similar colors in Eclipse, you can certainly re-create your Vim <em>colorscheme</em> in another editor. The output of <code>:highlight</code> gives you all defined groups and their color values.</p>59711933191	0	 <p>Please, try this query (also on <a href="http://www.sqlfiddle.com/#!2/48b44/3" rel="nofollow">SQL Fiddle</a>): </p> <pre><code>SELECT p.id, p.user_id, m.username, m.privacy, searcher.username "Searcher", p.status_msg FROM posts p JOIN members m ON m.id = p.user_id LEFT JOIN following f ON p.user_id = f.user_id JOIN members searcher ON searcher.username = 'userA' WHERE (m.privacy = 0 OR (m.privacy = 1 AND f.follower_id = searcher.id) OR m.id = searcher.id) AND p.status_msg LIKE '%New%' ORDER BY p.id LIMIT 5; </code></pre> <p>I removed <code>username</code> field from <code>posts</code> table, as it is redundant. Also, I named tables and columns slightly different, so query might need cosmetic changes for your schema.</p> <p>The first line in the <code>WHERE</code> clause is the one that you're looking for, it selects posts in the following order:</p> <ol> <li>First posts from members without privacy;</li> <li>Then posts from members that are followed by the current <code>searcher</code>;</li> <li>Finally, posts of the member himself.</li> </ol> <hr> <p><strong>EDIT:</strong></p> <p>This query is using original identifiers: </p> <pre><code>SELECT p.id, p.`userID`, m.username, m.privacy, searcher.username "Searcher", p.`statusMsg` FROM posts p JOIN `myMembers` m ON m.id = p.`userID` LEFT JOIN following f ON p.`userID` = f.user_id JOIN `myMembers` searcher ON searcher.username = 'userD' WHERE (m.privacy = 0 OR f.follower_id = searcher.id OR m.id = searcher.id) AND p.`statusMsg` LIKE '%New%' ORDER BY p.id LIMIT 5; </code></pre> <hr> <p><strong>EDIT 2:</strong></p> <p>To avoid duplicates in case there're several followers for the user from the <code>posts</code> table, join and filtering conditions should be changed the following way (on <a href="http://www.sqlfiddle.com/#!2/a6262/31" rel="nofollow">SQL Fiddle</a>): </p> <pre><code>SELECT p.id, p.user_id, m.username, m.privacy, searcher.username "Searcher", p.status_msg FROM posts p JOIN members m ON m.id = p.user_id JOIN members searcher ON searcher.username = 'userC' LEFT JOIN following f ON p.user_id = f.user_id AND follower_id = searcher.id WHERE (m.privacy = 0 OR (m.privacy = 1 AND f.id IS NOT NULL) OR m.id = searcher.id) ORDER BY p.id LIMIT 5; </code></pre>59827549500	0	 <p>I think msmq's answer is valid, but you should be a little careful about using the main info.plist this way. Doing that suggests that all your versions of info.plist are almost identical, except for a couple of differences. That's a recipe for divergence, and then hard-to-debug issues when you want to add a new URI handler or background mode or any of the other things that might modify info.plist.</p> <p>Instead, I recommend you take the keys that vary out of the main info.plist. Create another plist (say "Config.plist") to store them. Add a Run Script build phase to copy the correct one over. See the <a href="https://developer.apple.com/library/ios/documentation/DeveloperTools/Reference/XcodeBuildSettingRef/1-Build_Setting_Reference/build_setting_ref.html" rel="nofollow">Build Settings Reference</a> for a list of variables you can substitute. An example script might be:</p> <pre><code>cp ${SOURCE_ROOT}/Resources/Config-${CONFIGURATION}.plist ${UNLOCALIZED_RESOURCES_FOLDER_PATH}/Config.plist </code></pre> <p>Then you can read the file using something like this (based on <a href="https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/PropertyLists/QuickStartPlist/QuickStartPlist.html#//apple_ref/doc/uid/10000048i-CH4-SW6" rel="nofollow">Read in the Property List</a>):</p> <pre><code>NSString *baseURL; NSString *path = [[NSBundle mainBundle] pathForResource:@"Config" ofType:@"plist"]; NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:plistPath]; NSString *errorDesc = nil; NSDictionary *dict = (NSDictionary *)[NSPropertyListSerialization propertyListFromData:plistXML mutabilityOption:NSPropertyListImmutable format:NULL errorDescription:&amp;errorDesc]; if (dict != nil) { baseUrl = dict[@"baseURL"]; } else { NSAssert(@"Could not read plist: %@", errorDesc); // FIXME: Return error } </code></pre> <p>There are other solutions of course. I personally generally use the preprocessor for this kind of problem. In my build configuration, I would set <code>GCC_PREPROCESSOR_DEFINITIONS</code> to include <code>BaseURL=...</code> for each build configuration and then in some header I would have:</p> <pre><code>#ifndef BaseURL #define BaseURL @"http://default.example.com" #endif </code></pre> <p>The plist way is probably clearer and easier if you have several things to set, especially if they're long or complicated (and definitely if they would need quoting). The preprocessor solution takes less code to process and has fewer failure modes (since the strings are embedded in the binary at compile time rather than read at runtime). But both are good solutions.</p>59920617512	0	 <p>You are trying to connect to a local instance of RabbitMQ.</p> <blockquote> <p>BROKER_URL = 'amqp://guest:guest@localhost:5672/'</p> </blockquote> <p>in your settings.py). If you are working currently on development, you could avoid setting up Rabbit and all the mess around it, and just use a development-version of a Message Queue with the Django Database. </p> <p>Do this by replacing your previous configuration with</p> <blockquote> <p>BROKER_URL = 'django://' and add this app:</p> <p>INSTALLED_APPS += ('kombu.transport.django', )</p> </blockquote> <p>Finally, launch the worker with</p> <blockquote> <p>./manage.py celery worker --loglevel=info</p> </blockquote> <p>Source: <a href="http://docs.celeryproject.org/en/latest/getting-started/brokers/django.html">http://docs.celeryproject.org/en/latest/getting-started/brokers/django.html</a></p>60010737118	0	 <p>The easiest way to go about it is to offload it to separate process using <a href="https://github.com/dmgctrl/django-ztask" rel="nofollow">ztask</a>.</p> <pre><code>from django_ztask.decorators import task @task() def delayed_save(obj): obj.save() ... your_object.something = "something" delayed_save.async(your_object) </code></pre>60114476479	0	Using mail() to send an attachment AND text/html in an email in PHP4 <p>To make life difficult, the client I'm working for is using a really large yet old system which runs on PHP4.0 and they're not wanting any additional libraries added.</p> <p>I'm trying to send out an email through PHP with both an attachment and accompanying text/html content but I'm unable to send both in one email.</p> <p><strong>This sends the attachment:</strong></p> <pre><code>$headers = "Content-Type: text/csv;\r\n name=\"result.csv\"\r\n Content-Transfer-Encoding: base64\r\n Content-Disposition: attachment\r\n boundary=\"PHP-mixed-".$random_hash."\""; $output = $attachment; mail($emailTo, $emailSubject, $output, $headers); </code></pre> <p><strong>This sends text/html:</strong></p> <pre><code>$headers = "Content-Type: text/html; charset='iso-8859-1'\r\n"; $output = $emailBody; // $emailBody contains the HTML code. </code></pre> <p><strong>This sends an attachment containing the text/html along with the attachment contents:</strong></p> <pre><code>$headers = "Content-Type: text/html; charset='iso-8859-1'\r\n".$emailBody."\r\n"; $headers = "Content-Type: text/csv;\r\n name=\"result.csv\"\r\n Content-Transfer-Encoding: base64\r\n Content-Disposition: attachment\r\n boundary=\"PHP-mixed-".$random_hash."\""; $output = $attachment; </code></pre> <p>What I need to know is how can I send an email with text/html in the email body and also add an attachment to it. I'm sure I'm missing something really simple here!</p> <p>Thanks in advance.</p>60237484024	0	 <p>Here is your code converted to PDO. </p> <pre><code>// Make sure the email address is available: $q = $dbc-&gt;query("SELECT user_id FROM users WHERE email=?"); $q-&gt;execute(array($e)); $r = $q-&gt;fetchColumn(); if (!$r) { // Available. // Create the activation code: $a = md5(uniqid(rand(), true)); </code></pre> <p>Three things has been corrected</p> <ol> <li>You have to always use a placeholder tp represent a variable in the query.</li> <li>To get a single value from the result, <code>fetchColumn</code> have to be used instead of <code>fetchAll</code></li> <li>No need for the manual reporting, as PDO can report its errors automatically, if confugired properly, as described in <a href="https://phpdelusions.net/pdo#errors" rel="nofollow">this tutorial</a> I wrote</li> </ol>60328096069	0	 <pre><code>Def recadd(lis): If lis[0] + lis[1] - lis[2]] = lis[3]: return lis Else: recadd(lis[3] + lis[0:2]) recadd(lis[0] + lis[3] + lis[1:2]) recadd(lis[0:1] + lis[3]. + lis[2]) </code></pre> <p>Quick and dirty hack on my mobile, could be elegantly expanded for k numbers, untested but it should work. </p> <p>Edit: realized this won't work if there is no solution.infinite recursion...</p>60423916553	0	 <p>try this</p> <pre><code>def bookList() = { val res = resource.getAssets.open("demo.png") val image = Drawable.createFromStream(res, "demo.png") val map = Map[String, Drawable]() for (i &lt;- 1 to 100) { map += (s"test book$i" -&gt; image) } map } </code></pre>6056471481	0	 <p>This may be useful:<br> <a href="http://gcc.gnu.org/onlinedocs/gcc-4.1.1/cpp/Search-Path.html#Search-Path" rel="nofollow">http://gcc.gnu.org/onlinedocs/gcc-4.1.1/cpp/Search-Path.html#Search-Path</a></p>60627315459	0	My application does not save data to the database <p>I have tried to create a C# application that saves data to an existing local SQL database. I created a local database called <code>AccountDatabase.mdf</code> which has a table called <code>AccountTable</code> in it. I first started with an empty table. I then used the code below to get the application to save the input data to the database.</p> <pre><code>private void FPAccountNotExist_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { //Make forgot password page invisible and create new account page visible ForgotPassword.Visible = false; CreateNewAccount.Visible = true; //Set text content of labels on create new account page CreateNewAccountTitle.Text = "Create New Account"; CNAConfirmLabel.Text = "Confirm Password"; CNAEmailLabel.Text = "Email"; CNAInstruction.Text = "Please fill in the following details."; CNAOpenAccount.Text = "Submit new account"; CNAPasswordLabel.Text = "Password"; CNAUsernameLabel.Text = "Username"; OpenManual.Text = "Start with Manual"; CNAConfirmTextBox.UseSystemPasswordChar = true; CNAPasswordTextBox.UseSystemPasswordChar = true; </code></pre> <p>}</p> <pre><code>private void CNAOpenAccount_Click(object sender, EventArgs e) { AccountVariables.ConfirmedPassword = CNAConfirmTextBox.Text; AccountVariables.Email = CNAEmailTextBox.Text; AccountVariables.Password = CNAPasswordTextBox.Text; AccountVariables.Username = CNAUsernameTextBox.Text; //GeneralVariables.ManualOption = OpenManual.Checked; var CreateNewAccountStrings = new List&lt;string&gt; { AccountVariables.ConfirmedPassword, AccountVariables.Password, AccountVariables.Email, AccountVariables.Username }; if (CreateNewAccountStrings.Contains("")) { MessageBox.Show("All textboxes should be filled"); } else { if ((AccountVariables.ConfirmedPassword == AccountVariables.Password) &amp;&amp; (AccountVariables.Password.Length &gt;= 8)) { accountTableTableAdapter.Fill(accountDatabaseDataSet.AccountTable); AccountVariables.defaultAccountRow = AccountVariables.defaultAccountRow + 1; AccountVariables.newAccountTableRow = accountDatabaseDataSet.AccountTable.NewAccountTableRow(); AccountVariables.newAccountTableRow.UserId = AccountVariables.defaultAccountRow; AccountVariables.newAccountTableRow.Username = AccountVariables.Username; AccountVariables.newAccountTableRow.Email = AccountVariables.Email; AccountVariables.newAccountTableRow.Password = AccountVariables.Password; accountDatabaseDataSet.AccountTable.AddAccountTableRow(AccountVariables.newAccountTableRow); accountTableTableAdapter.Update(accountDatabaseDataSet.AccountTable); accountDatabaseDataSet.AccountTable.AcceptChanges(); AccountVariables.AccountDatabaseConnection.Close(); } } } </code></pre> <p>However, when I closed the program after running the application, I looked in the database and saw that the rows had not been saved, even after I have saved it. Please can you help me solve this problem.</p>60713341544	0	 <p>I would first try to optimze your query. Is it slow in SSMS? Do you use proper indices? Do you need all columns. Most important: do you need all 50000 rows to be displayed?</p> <p>50000 records are not many records, but it's unusual to show all in a web application since that means you have to generate the HTML for all records and display it in the client's browser(maybe even using <code>ViewState</code>). So i would suggest to use database paging(f.e. via <a href="http://msdn.microsoft.com/en-us/library/ms186734.aspx" rel="nofollow"><code>ROW_NUMBER</code></a> function) to partition your resultset and query only the data you want to show(f.e. 100 rows per page in a <code>GridView</code>). </p> <p><a href="http://www.asp.net/web-forms/tutorials/data-access/paging-and-sorting/efficiently-paging-through-large-amounts-of-data-vb" rel="nofollow">Efficiently Paging Through Large Amounts of Data</a> </p>60839130085	0	 <pre><code>Object json = mapper.readValue(input, Object.class); String indented = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json); </code></pre>60913966814	0	 <p>You can merge all of your string in one string by <a href="http://developer.android.com/reference/java/lang/StringBuilder.html" rel="nofollow"><code>StringBuilder</code></a> and apply it to the <code>TextView</code>.</p> <p>I've implemented my own TextView with scrolling by wrapping textview (and maybe some other views) </p> <pre><code>private Runnable scrollRight = new Runnable() { @Override public void run() { // can control scrolling speed in on tick topScroll.smoothScrollBy(1, 0); } }; </code></pre> <p>and in new Thread I invoke:</p> <pre><code>while (!interruptScroll){ try{ Thread.sleep(50); // control ticking speed } catch (InterruptedException e){ e.printStackTrace(); } topScroll.post(scrollRight); } </code></pre> <p>and by manually scrolling the scrollView i interrupt the scrolling (such an automatic scrolling while not interrupted by user).</p>61029392238	0	 <p>Using HtmlAgilityPack (HAP) and XPath function <code>name()</code> didn't work for me, but replacing <code>name()</code> with <code>local-name()</code> did the trick :</p> <pre><code>//*/@*[starts-with(local-name(), 'on')] </code></pre> <p>However, both <code>SelectSingleNode()</code> and <code>SelectNodes()</code> only able to return <code>HtmlNode</code>(s). When the XPath expression selects an attribute instead of node, the attribute's owner node would be returned. So in the end you still need to get the attribute through some options besides XPath, for example :</p> <pre class="lang-cs prettyprint-override"><code>HtmlDocument doc; ...... var link = doc.DocumentNode .SelectSingleNode("//*/@*[starts-with(local-name(), 'on')]"); var onclick = link.Attributes .First(o =&gt; o.Name.StartsWith("on")); </code></pre>61123678485	0	Adding parameters to URL in ZF2 <p><br> I am trying to construct url which looks like this:</p> <pre><code> abc.com/folder?user_id=1&amp;category=v </code></pre> <p>Followed the suggestion given in this link:</p> <p><a href="http://stackoverflow.com/questions/12785190/how-can-you-add-query-parameters-in-the-zf2-url-view-helper">How can you add query parameters in the ZF2 url view helper</a></p> <p>Initially, it throws up this error</p> <pre><code> Query route deprecated as of ZF 2.1.4; use the "query" option of the HTTP router\'s assembling method instead </code></pre> <p>Following suggestion, I used similar to </p> <pre><code> $name = 'index/article'; $params = ['article_id' =&gt; $articleId]; $options = [ 'query' =&gt; ['param' =&gt; 'value'], ]; $this-&gt;url($name, $params, $options); </code></pre> <p>Now, I am getting syntax error saying, </p> <pre><code> Parse error: syntax error, unexpected '[' in /var/www/test/module/Dashboard/view/dashboard/dashboard/product.phtml on line 3 </code></pre> <p>My module.config.php is configured like this:</p> <pre><code> 'browse_test_case' =&gt; array( 'type' =&gt; 'Literal', 'options' =&gt; array( 'route' =&gt; '/browse-case[/:productId]', 'defaults' =&gt; array( 'controller' =&gt; 'Test\Controller\Browse', 'action' =&gt; 'browse-test-case', ), ), 'may_terminate' =&gt; true, 'child_routes' =&gt; array( 'query' =&gt; array( 'type' =&gt; 'Query', ), ), ), </code></pre> <p>Any Idea, please help!</p>612119732	0	How to initialize Hibernate entities fetched by a remote method call? <p>When calling a remote service (e.g. over RMI) to load a list of entities from a database using Hibernate, how do you manage it to initialize all the fields and references the client needs?</p> <p>Example: The client calls a remote method to load all customers. With each customer the client wants the reference to the customer's list of bought articles to be initialized.</p> <p>I can imagine the following solutions:</p> <ol> <li><p>Write a remote method for each special query, which initializes the required fields (e.g. Hibernate.initialize()) and returns the domain objects to the client.</p></li> <li><p>Like 1. but create DTOs</p></li> <li><p>Split the query up into multiple queries, e.g. one for the customers, a second for the customers' articles, and let the client manage the results</p></li> <li><p>The remote method takes a DetachedCriteria, which is created by the client and executed by the server</p></li> <li><p>Develop a custom "Preload-Pattern", i.e. a way for the client to specify explicitly which properties to preload.</p></li> </ol>6139353661	0	Storing ABRecordRef in Core Data <p>I would like to store a ABRecordRef in a 'Client' entity in core data. </p> <p>I have read in apples documentation that ABRecordRef is a primitive C data type. As far as I am aware, you can only insert objects in core data. With this in mind, what is the best way to store it in core data?</p> <p>I thought about converting it into a NSNumber for storage, but dont know how to convert it back to ABRecordRef for use.</p> <p>I also thought I could just put it in a NSArray/NSSet/NSDictionary on its own just acting as a wrapper but didnt know if this was silly/inefficient/would even work.</p> <p>Thoughts appreciated.</p> <p>Many thanks</p>61422052735	0	Trace a curve with two colors? <p>is there a way to have a curve with two colors, well i have many curves in my plot. But I like to add a specific characteristic, i want the curve 1 to be <strong>simple line</strong> in[a,b] interval, and <strong>dotted line</strong> in interval [b,c].</p> <p>an example of my graph:</p> <p>plot exp(-x**2 / 2), sin(x)</p> <p>can we make sin(x) plotted in dotted line from[0,5]</p> <p>thanks in advance.</p>61531312465	0	How to avoid duplicate insert of ToolbarItem in Xamarin.forms? <pre><code>protected override void OnAppearing(){ ToolbarItem itemStudy = new ToolbarItem { Name = "Study", Order = ToolbarItemOrder.Primary, Command = new Command (() =&gt; Navigation.PushAsync (studyPage)) }; if (ToolbarItems.Count &gt; 0) { ToolbarItems.RemoveAt(0); } ToolbarItems.Add (itemStudy); } </code></pre> <p>This is my Code snipped on Xamarin.forms for adding Toolbaritem. Anyhow I don't think this is an elegant way and looking for better solution. Can anyone help? Thanks.</p>61634020483	0	Where is PFFile saved? <p>I save UIImage as PFFile:</p> <pre><code>let imageFile = PFFile(data: imageData) imageFile?.saveInBackgroundWithBlock({}) </code></pre> <p>This file is not referenced with any PFObject, so what happens to him?</p> <ol> <li><p>This file is saved on my reserved storage (20GB)? </p></li> <li><p>Is there any tool for clean non-referenced files?</p></li> <li><p>If I assign some PFFile to object and replace it by other PFFile after that, first object will be deleted?</p></li> </ol>61713503068	0	 <p>I think what you will see is just differences in coding practice.</p> <p>If all child classes have the same exact <code>init()</code> method, there is no reason to even have the method declared within the child classes.</p> <p>In some cases, however I have seen developers do exactly what you have shown. In a lot of cases this may because the eventual intent may be to somehow augment the parent method behavior in a way specific to the class. In other cases, I have seen some collection of children classes override the functionality, so the developer puts a method like this in all child classes just so the intent (execute parent method as is for this child class) is clear to other developers.</p>61815086294	0	 <p>You can also do it like tihs:</p> <pre><code>public static function generateCode($length = 6) { $az = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $azr = rand(0, 51); $azs = substr($az, $azr, 10); $stamp = hash('sha256', time()); $mt = hash('sha256', mt_rand(5, 20)); $alpha = hash('sha256', $azs); $hash = str_shuffle($stamp . $mt . $alpha); $code = ucfirst(substr($hash, $azr, $length)); return $code; } </code></pre>6198972776	0	 <p>Yes - you or have to introduce date_of_entry field or some other vector field like <code>IDENTITY</code>. For example if column <code>Id</code> is your <code>INT IDENTITY</code>, then your query will look like this:</p> <pre><code> ;WITH cte AS (SELECT ROW_NUMBER() OVER (PARTITION BY person_id, date_work, hours ORDER BY ( SELECT Id DESC)) RN FROM work_hours) DELETE FROM cte WHERE RN &gt; 1 </code></pre> <p><strong>Of course</strong> it is valid if nobody changes the values in <code>IDENTITY</code> column</p> <p>And if your conditions suits - then you may want to use column <code>Hours</code> as your vector field within grouping range of <code>person_id, date_work</code></p> <p><strong>And even better way</strong> is to have an <code>UNIQUE INDEX</code> over columns <code>person_id, date_work, hours</code>, then there will no any ability to add duplicates.</p>6202192006	0	Failed to Map Path '/doc'. server.map path <p>If I run the site using the internal Visual Studio web server, I get the failed to map path error.</p>62135561493	0	 <p>There's a few ways to clean this up in Ruby that I'll demonstrate here:</p> <pre><code>puts 'Hello mate what is thy first name?' name1 = gets.chomp # Inline string interpolation using #{...} inside double quotes puts "Your name is #{name1} eh? What is thy middle name?" name2 = gets.chomp # Interpolating a single string argument using the String#% method puts 'What is your last name then %s?' % name1 name3 = gets.chomp # Interpolating with an expression that includes code puts "Oh! So your full name is #{ [ name1, name2, name3 ].join(' ') }?" puts 'That is lovey!' # Combining the strings and taking their aggregate length puts 'Did you know there are %d letters in your full name?' % [ (name1 + name2 + name3).length ] # Using collect and inject to convert to length, then sum. puts 'Did you know there are %d letters in your full name?' % [ [ name1, name2, name3 ].collect(&amp;:length).inject(:+) ] </code></pre> <p>The <a href="http://ruby-doc.org/core-2.2.0/String.html#method-i-25" rel="nofollow"><code>String#%</code></a> method is a variant of <a href="http://ruby-doc.org/core-2.2.0/Kernel.html#method-i-sprintf" rel="nofollow"><code>sprintf</code></a> that's very convenient for this sort of formatting. It gives you a lot of control over presentation.</p> <p>That last one might look a bit mind-bending but one of the powerful features of Ruby is being able to string together a series of simple transformations into something that does a lot of work.</p> <p>That part would look even more concise if you used an array to store the name instead of three independent variables:</p> <pre><code>name = [ ] name &lt;&lt; gets.chomp name &lt;&lt; gets.chomp name &lt;&lt; gets.chomp # Name components are name[0], name[1], and name[2] # Using collect -&gt; inject name.collect(&amp;:length).inject(:+) # Using join -&gt; length name.join.length </code></pre> <p>It's generally a good idea to organize things in structures that lend themselves to easy manipulation, exchange with other methods, and are easy to persist and restore, such as from a database or a file.</p>6222773791	0	 <p>I finally got the solution. The problem was with the field's verbose name - it was str instead of unicode. Moving to unicode helped. </p> <p>Thanks :-)</p>62339429247	0	 <p>you can use the <code>all</code> method.</p> <pre><code>Book.all </code></pre> <p>This will return all of the books on record. </p>62425918441	0	Creating links relative to localhost <p>I'm trying to create a custom menu in drupal 7 by coding it in a custom code block, but I'm running into the issue that the links I create aren't lined up to the way my local site is setup. Is there php code or a drupal setting of some sort that can create a link relative to the local machine setup?</p> <p>To give more context: My friend and I are working on creating a drupal site and have individually setup our local files differently (we are sharing the database which is on a remote server). When browsing to the site, his URL shows up: <code>localhost/content/page</code>. Whereas how I have it setup is: <code>localhost/sitename/content/page</code>.</p> <p>When I create an internal link in the nav menu, I have to create it using a relative path /content/page, otherwise the link wont work on my coworkers localhost. This, in turn, makes it so that the link doesn't work on my locahost.</p> <p>Is there a way I can create these links relative to the localhost so that it works on both machines? When creating a navigation menu using my Drupal theme this is not an issue, but since the link list I'm creating is custom coded, I can't seem to figure out how to mimic this same functionality.</p> <p>Any ideas? Thanks!</p>6255588023	0	ASP.NET MVC - How to re-run jQuery tabs script after getJSON call? <p>I have some data wrapped in 3 divs, each div represents a 'tab', and a jQuery script to create the tab effect. The 3 tabs include hours of operation, contact info, location info.</p> <p>Pretty standard, nothing special. When the page loads, the following script is run, creating the 'tab' effect.</p> <pre><code> $(document).ready(function () { tabs({ block: "#branch" }); }); </code></pre> <p>I have a drop down list that triggers a call to an action that returns a JsonResult, and the following code to handle the change:</p> <pre><code> $("#branches").change(function () { $("#branches option:selected").each(function () { $.getJSON("/Branch/JsonBranch/" + $(this)[0].value, null, function (data) { $("#branchinfo").html(data); }); }); }); </code></pre> <p>The action is a variation on the post <a href="http://stackoverflow.com/questions/1181849/asp-net-mvc-combine-json-result-with-viewresult">ASP.NET MVC - Combine Json result with ViewResult</a></p> <p>The action code isn't relevant. The problem is that, since I'm not reloading the whole page, the 'tab' script is never run again. So, once the html code is replaced, ALL the data shows, the tabs are not created.</p> <p>Is there a way to run the tab script again after just reloading that one portion of the page? I tried adding the call to tabs() in the .change() function call, but that didn't work.</p> <p>Any help would be appreciated! Thanks!</p>62622077268	0	 <p>The above code will only run once only which will add information to head only once. If you want to add more information in case of second run then add code for else condition. Example:-</p> <pre><code>if ( head == NULL ) { // code to insert data in case of first run }else{ // code to insert data for second run and so..... } </code></pre>62732280035	0	Prevent IE caching AngularJS/Restangular <p>In IE, when I make an update to or destroy an item in a list, the action is successful, but the updated list/data is not returned from the server, thus the list is not being updated in the view.</p> <p>I've tried the following to no avail:</p> <pre><code>angular.module('casemanagerApp') .config(function($stateProvider, $urlRouterProvider, RestangularProvider) { if (!RestangularProvider.setDefaultHeaders) { RestangularProvider.setDefaultHeaders({}); } RestangularProvider.setDefaultHeaders({'If-Modified-Since': 'Mon, 26 Jul 1997 05:00:00 GMT'}); RestangularProvider.setDefaultHeaders({'Cache-Control': 'no-cache'}); RestangularProvider.setDefaultHeaders({'Pragma': 'no-cache'}); $stateProvider ... }); </code></pre> <p>Can anyone point me in the right direction for a solution to this?</p>62837733893	0	Squash git commits from topic branch <p>I have a topic branch (macaroni), and I have submitted a pull request. I had to make a change after feedback. It was requested that I squash the two commits into a single commit. This is what I have done:</p> <pre><code>git status On branch macaroni git log commit def feedback fixes commit abc fix cheddar flavor git rebase -i origin/master .. go through screen where I pick commit to squash .. .. go through screen where I update commit message .. git log commit abc fix cheddar flavor, squashing done! </code></pre> <p>at this point I believe I have to push my topic branch using the -force flag, because I have changed history:</p> <pre><code>git push -f </code></pre> <p>I am using the second answer from this question:</p> <p><a href="http://stackoverflow.com/questions/7947322/preferred-github-workflow-for-updating-a-pull-request-after-code-review">Preferred Github workflow for updating a pull request after code review</a></p> <p>with subtitle "Optional - Cleaning commit history". The author mentions at the end that you should be using topic branches, not sure if I should have changed any of the commands since I'm already on a topic branch.</p> <p>I am also concerned with accidentally force-pushing something onto the master branch with the above since I'm using -f, but since I'm on the topic branch, only that branch should be affected, right?</p> <p>Thanks</p>62938084853	0	how to show a window only one time? <p>I want display a window only one time. When the user click on this button:</p> <pre><code>private void Notification_Click(object sender, RoutedEventArgs e) { NotificationSettings notifications = new NotificationSettings(); notifications.ShowDialog(); } </code></pre> <p>this will create a new window, I want that if there is already a window opened the user can't open a new one. There is an option in xaml for tell to compiler this? I remember the vb.net with windows form that allow to set the option to show only one windows at time. </p> <p>Thanks.</p>63010302647	0	 <p>If you want to pass the whole list in a single parameter, use array datatype:</p> <pre><code>SELECT * FROM word_weight WHERE word = ANY('{a,steeple,the}'); -- or ANY('{a,steeple,the}'::TEXT[]) to make explicit array conversion </code></pre>6315108964	0	Attached databases in Honeycomb <p>Has anyone ran into attached database issues with Honeycomb yet? My application uses attached databases (working on 1.5 through 2.3) using the statements:</p> <p>...</p> <pre><code>String newDb = "/data/data/com.stuff.app/databases/mydata.db"; db.execSQL("attach database ? as newDb", new String[] {newDb}); String[] columns = MY_COL_NAMES; String orderBy = DEFAULT_SORT_ORDER; Cursor cursor = db.query("newDb.mydata", columns, null, null, null, null, orderBy); </code></pre> <p>...</p> <p>This is working (1.5 through 2.3) regardless of the actual location of the sqlite database file (local or SD Card)...However, in Honeycomb, the db.query statement results in a "I/SqliteDatabaseCpp( 628): sqlite returned: error code = 1, msg = no such table: newDb.mydata ..."</p> <p>I can manually attach the database from within sqlit3 by issuing the statement:</p> <p>sqlite3>attach database '/data/data/com.stuff.app/databases/mydata.db' as newDb;</p> <p>Any help resolving this would be greatly appreciated.</p>6329047001	0	 <p>If your receiver must know the concrete type, then you're not using Interfaces properly.</p> <p>If you're returning a page, there's really no reason for anything to know what kind of page it is. I would add a <code>Render</code> method to the <code>IPage</code> interface so that all the receiver has to do is call <code>Render()</code> and the page will handle the rest.</p>6337167976	0	 <p>The collection is a reference type, so other holding code onto that will see the old data. </p> <p>Two possible solutions:</p> <p>Instead of data = temp use data.Clear(); data.AddRange(temp) which will change the contents of the data field. </p> <p>Or better delete the MyCollection property and make class implement IEnumerable. This results in much better encapsulation. </p>63418949117	0	 <p><strong>Assuming a dash following a space or vice versa is ok:</strong></p> <pre><code>^( -?|- ?)?(\d( -?|- ?)?){9,13}$ </code></pre> <p><strong>Explanation:</strong></p> <p><code>( -?|- ?)</code> - this is equivalent to <code>( | -|-|- )</code>. Note that there can't be 2 consecutive dashes or spaces here, and this can only appear at the start or directly after a digit, so this prevents 2 consecutive dashes or spaces in the string.</p> <p>And there clearly must be exactly one digit in <code>(\d( -?|- ?)?)</code>, thus the <code>{9,13}</code> enforces 9-13 digits.</p> <p><strong>Assuming a dash following a space or vice versa is NOT ok:</strong></p> <pre><code>^[ -]?(\d[ -]?){9,13}$ </code></pre> <p>Explanation similar to the above.</p> <p>Both of the above allows the string to start or end with a digit, dash or space.</p>63537299020	0	 <p>Instance types are cached in the browser's local storage. You can explicitly refresh the cache via the 'Refresh all caches' link:<a href="https://i.stack.imgur.com/QOdbN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QOdbN.png" alt="enter image description here"></a></p> <p>If you show the network tab of your browser's console (prior to clicking 'Refresh all caches'), you should see a request to <a href="http://localhost:8084/instanceTypes" rel="nofollow noreferrer">http://localhost:8084/instanceTypes</a>.</p> <p>If the response contains your instance types, you should be good to go.</p>63615978379	0	 <p>This command does two main things: create a mask with that torn-paper effect, apply the mask to the image. It does them, fancily, in one line, by using +clone and the parentheses. It's less confusing to do it as two commmands though:</p> <pre><code>convert thumbnail.gif \ -alpha extract \ -virtual-pixel black \ -spread 10 \ -blur 0x3 \ -threshold 50% \ -spread 1 \ -blur 0x.7 \ mask.png convert thumbnail.gif mask.png \ -alpha off \ -compose Copy_Opacity \ -composite torn_paper.png </code></pre> <p>The first command is fairly complex. But you can find decent explanations of each of the component commands in the ImageMagick docs:</p> <ul> <li><a href="http://www.imagemagick.org/Usage/masking/#alpha_extract" rel="nofollow">http://www.imagemagick.org/Usage/masking/#alpha_extract</a></li> <li><a href="http://www.imagemagick.org/Usage/misc/#virtual_examples" rel="nofollow">http://www.imagemagick.org/Usage/misc/#virtual_examples</a></li> <li><a href="http://www.imagemagick.org/script/command-line-options.php#blur" rel="nofollow">http://www.imagemagick.org/script/command-line-options.php#blur</a></li> </ul> <p>Also, by splitting the command into these two pieces, you can see what the mask looks like on its own. It's basically the inverse of the paper effect. White throughout the middle of the images, fading to black around the "torn edges". </p> <p>The second command is a lot more straightforward. Copy_Opacity, as described in the <a href="http://www.imagemagick.org/Usage/compose/#copyopacity" rel="nofollow">ImageMagick docs</a>, is a way of making parts of an image transparent or not. Anything that's black in the mask will be made transparent in the resulting image. In effect, the second command uses the mask to "erase" the edges of the original thumbnail in a stylistically interesting way.</p>63718597835	0	Placing a TextView below two ImageViews and in middle - Android <p>Please share code to achieve the layout of the screen shown in the below link. The text should be in center of the two images and all these components can be dynamic.</p> <p>(<a href="https://docs.google.com/file/d/0B9n2IhVep_QeNDFKaWFHVERQOVk/edit?usp=sharing" rel="nofollow">https://docs.google.com/file/d/0B9n2IhVep_QeNDFKaWFHVERQOVk/edit?usp=sharing</a>)</p> <p><a href="https://www.dropbox.com/s/2j4bpwdmv0wgesg/Untitled%20Diagram.png" rel="nofollow">https://www.dropbox.com/s/2j4bpwdmv0wgesg/Untitled%20Diagram.png</a></p>63830757002	0	 <p>pboedker and ChrisKo answers are both good. A couple of extra warnings are needed.</p> <p>A scan (or the scan time) can be shorter than your code's execution time. In most PLC's there is a "watchdog" to detect this, and warn you that it is happening. You often need to set this "watchdog" up, and set up a alarm/event handler for it.</p> <p>Know how your PLC executes I/O. Some (Such as ControlLogix) are Asynchronous, I/O gets read into your controllers memory based on the RPI (request packet interval), and gets written out (same RPI) when you make a change to the I/O point with code. Others (Such as AutomationDirect's Productivity 2000 series) only write the outputs upon a COMPLETE scan of your code. I'm sure you can picture the pro's and cons of each scenario, especially if your controller is not completing your code before restarting a scan.</p> <p>PLC's that allow you to have different scan rates for different pieces of code give you powerful tools for I/O and program flow management. Slow processes can be scanned slowly, allowing you more PLC time for other things.</p>6399814937	0	 <p>Follow this guide: <a href="http://weblogs.asp.net/psheriff/archive/2009/12/01/load-resource-dictionaries-at-runtime-in-wpf.aspx" rel="nofollow">http://weblogs.asp.net/psheriff/archive/2009/12/01/load-resource-dictionaries-at-runtime-in-wpf.aspx</a></p> <ol> <li>Create various xaml resource files, but make sure the file does not compile and copies into the bin directory instead.</li> <li>Decorate your xaml controls with <code>DynamicResource</code>s.</li> <li>Load in your resources through code.</li> </ol> <p>Basically, you are looking to "skin" your application. The code that loads in your resource file can take advantage of the <code>TimeOfDay</code> enumeration.</p> <p>If you want it automated you can even have some static class that has a timer to automatically attempt to change the resource and set the timer on the application startup. :)</p>64040354505	0	 <p>You can manually bootstrap angular after receive data from server.</p> <p>Example on <a href="https://jsfiddle.net/Stepan_Kasyanenko/dkhf29ej/1/" rel="nofollow">jsfiddle</a>:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var app = angular.module("myApp", []); app.controller("myController", function($scope, servicesConfig) { console.log(servicesConfig); $scope.model = servicesConfig.host; $scope.reset = function() { $scope.model = ''; }; }); angular.element(document).ready(function() { //Simulate AJAX call to server setTimeout(function() { app.constant('servicesConfig', { host: "appdev" }); angular.bootstrap(document, ['myApp']); }, 2000); });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"&gt;&lt;/script&gt; &lt;div ng-cloak&gt; &lt;div ng-controller="myController"&gt; &lt;input type="text" ng-model="model" /&gt; {{model}} &lt;button ng-click="reset()"&gt;Reset&lt;/button&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>64130815407	0	YARN log aggregation on a per job basis <p>Can properties such as yarn.log-aggregation-enable and yarn.log-aggregation.retain-seconds applied on a per job basis? I would not like this to be enabled at a cluster-wide scale but only for a few tasks. </p>6425286116	0	 <p>If you like to <em>learn by doing</em> then <em>learn by doing it</em> in <strong><a href="http://php.net/manual/en/book.pdo.php" rel="nofollow">PDO</a></strong> and <a href="http://www.php.net/manual/en/pdostatement.bindparam.php" rel="nofollow">bind</a> the parameters. This is the safe and correct way to <strong>do it</strong> these days.</p>6434193721	0	 <p>If you want to implement server side sorting then it does not matter what technology you are using in the front end. </p> <p>On a conceptual level you can do the following things:</p> <ol> <li>Write a SortingServlet which takes your grid and sorts it according to the request parameters passed to it and renders the output in the form of json(not strictly required but good to have)</li> <li>Use jQuery to make a Ajax call to this servlet and then format the response when you get it back. </li> </ol>64425744475	0	 <p>EDIT: Updated with <code>resize</code> event listener. Updated <a href="http://jsfiddle.net/flowstoneknight/2xt9t8pg/" rel="nofollow">fiddle</a>.</p> <p>As I understand it, you want the text to be as large as possible while still fitting inside the containing <code>&lt;div&gt;</code>, correct? My solution is to put a <code>&lt;span&gt;</code> around the text, which conforms to the text's normal size. Then calculate the ratios between the container's dimensions and the <code>&lt;span&gt;</code>'s dimensions. Whichever is the smaller ratio (either width or height), use that ratio to enlarge the text.</p> <p>HTML:</p> <pre><code>&lt;div class="container"&gt; &lt;span class="text-fitter"&gt; text here &lt;/span&gt; &lt;/div&gt; </code></pre> <p>JS (jQuery):</p> <pre><code>textfit(); $(window).on('resize', textfit); function textfit() { $('.text-fitter').css('font-size', 'medium'); var w1 = $('.container').width()-10; var w2 = $('.text-fitter').width(); var wRatio = Math.round(w1 / w2 * 10) / 10; var h1 = $('.container').height()-10; var h2 = $('.text-fitter').height(); var hRatio = Math.round(h1 / h2 * 10) / 10; var constraint = Math.min(wRatio, hRatio); $('.text-fitter').css('font-size', constraint + 'em'); } </code></pre> <p>Here's a <a href="http://jsfiddle.net/flowstoneknight/2xt9t8pg/" rel="nofollow">fiddle</a>. Adjust the <code>.container</code> dimensions in the CSS to see it in action.</p>64513793935	0	 <p>I'm only marking this as the answer to close the case, what the actual answer was to the problem we will never know. The solution: automatic updates. After much hassles with getting automatic updates to actually go through, my machine is now working well.</p>6464969681	0	 <p>in case you want both containers to float besides each other, you can rather use a span instead of a div. That might bring the problem to an end.</p>64733093272	0	 <p>It's related with thread not killed after use, not related with logging module, it's solved now, thanks for attention. </p>64823032838	0	 <p>If you are looking to just "preload" the images so that you can use them later (in your app/page), then you can use the following HTML 5 code:</p> <pre><code>&lt;link rel="prefetch" href="http://davidwalsh.name/wp-content/themes/walshbook3/images/sprite.png" /&gt; </code></pre> <p>See: Link prefetching is a browser mechanism, which utilizes browser idle time to download or prefetch documents that the user might visit in the near future. A web page provides a set of prefetching hints to the browser, and after the browser is finished loading the page, it begins silently prefetching specified documents and stores them in its cache. When the user visits one of the prefetched documents, it can be served up quickly out of the browser's cache. URL, then description, then title, keywords.. and finally body.</p> <p>If for gallery, then @Santosh is correct. Or <a href="http://code.msdn.microsoft.com/Infinite-Scroll-Like-Bing-bc05262b" rel="nofollow">http://code.msdn.microsoft.com/Infinite-Scroll-Like-Bing-bc05262b</a></p>64932792841	0	 <pre><code>self.printfunc = weakref.ref(printfunc)() </code></pre> <p>isn't actually using <code>weakref</code>s to solve your problem; the line is effectively a noop. You create a <code>weakref</code> with <code>weakref.ref(printfunc)</code>, but you follow it up with call parens, which converts back from <code>weakref</code> to a strong ref which you store (and the <code>weakref</code> object promptly disappears). Apparently it's not possible to store a <code>weakref</code> to the bound method itself (because the bound method is its own object created each time it's referenced on <code>self</code>, not a cached object whose lifetime is tied to <code>self</code>), so you have to get a bit hacky, unbinding the method so you can take a <code>weakref</code> on the object itself. Python 3.4 introduced <a href="https://docs.python.org/3/library/weakref.html#weakref.WeakMethod" rel="nofollow"><code>WeakMethod</code></a> to simplify this, but if you can't use that, then you're stuck doing it by hand.</p> <p>Try changing it to (on Python 2.7, and you must <code>import inspect</code>):</p> <pre><code># Must special case printfunc=None, since None is not weakref-able if printfunc is None: # Nothing provided self.printobjref = self.printfuncref = None elif inspect.ismethod(printfunc) and printfunc.im_self is not None: # Handling bound method self.printobjref = weakref.ref(printfunc.im_self) self.printfuncref = weakref.ref(printfunc.im_func) else: self.printobjref = None self.printfuncref = weakref.ref(printfunc) </code></pre> <p>and change <code>myprint</code> to:</p> <pre><code>def myprint(self,text): if self.printfuncref is not None: printfunc = self.printfuncref() if printfunc is None: self.printfuncref = self.printobjref = None # Ref died, so clear it to avoid rechecking later elif self.printobjref is not None: # Bound method not known to have disappeared printobj = self.printobjref() if printobj is not None: print ("ExtenalFUNC:%s" %text) # To call it instead of just saying you have it, do printfunc(printobj, text) return self.printobjref = self.printfuncref = None # Ref died, so clear it to avoid rechecking later else: print ("ExtenalFUNC:%s" %text) # To call it instead of just saying you have it, do printfunc(text) return print ("JustPrint:%s" %text) </code></pre> <p>Yeah, it's ugly. You could factor out the ugly if you like (borrowing <a href="https://hg.python.org/cpython/file/tip/Lib/weakref.py" rel="nofollow">the implementation of <code>WeakMethod</code> from Python 3.4's source code</a> would make sense, but names would have to change; <code>__self__</code> is <code>im_self</code> in Py2, <code>__func__</code> is <code>im_func</code>), but it's unpleasant even so. It's definitely not thread safe if the <code>weakref</code>s could actually go dark, since the checks and clears of the <code>weakref</code> members aren't protected.</p>65040363768	0	runjags trouble locating JAGS - error "'where' not found" even after setting jagspath <p>Seems that runjags suddenly (after update to version 2.0.3-2) has trouble finding JAGS binary, issuing an error: </p> <pre><code>[1] "Error in system(\"where jags\", intern = TRUE) : 'where' not found\n" attr(,"class") [1] "try-error" attr(,"condition") &lt;simpleError in system("where jags", intern = TRUE): 'where' not found </code></pre> <p>I fixed this by putting this line to my <code>Rprofile</code>:</p> <pre><code>.runjags.options &lt;- list(jagspath = "c:/Program Files/JAGS/JAGS-4.2.0/i386/bin/jags-terminal.exe") </code></pre> <p>This pretty much fixes the problem (although it is not ideal - previous versions of runjags could find the binary automatically).</p> <p>However, when the Rgui (in Windows XP) is launched by opening an .Rdata file, which is associated to it, it stops working:</p> <pre><code>&gt; .runjags.options # it was set in the Rprofile $jagspath [1] "c:/Program Files/JAGS/JAGS-4.2.0/i386/bin/jags-terminal.exe" &gt; require(runjags) Loading required package: runjags Warning message: package ‘runjags’ was built under R version 3.1.3 &gt; runjags.getOption("jagspath") [1] "Error in system(\"where jags\", intern = TRUE) : 'where' not found\n" attr(,"class") [1] "try-error" attr(,"condition") &lt;simpleError in system("where jags", intern = TRUE): 'where' not found </code></pre> <p>Is this a bug? How to fix this?</p> <p>I am currently calling <code>runjags.options(jagspath = "c:/Program Files/JAGS/JAGS-4.2.0/i386/bin/jags-terminal.exe")</code> in my source after <code>require(runjags)</code>, but I would like to avoid this as much as possible!</p>6517470318	0	Setting parameter of layout of android programmatically <p>I am new to android. I want to know how to set the parameters or attributes to layout x and layout y width and height from the program for any layouts like absolute.</p>6529671918	0	Disable submit if inputs empty jquery <p>Disclaimer: I know there are quite a few questions out there with this topic and it has been highly addressed, though I need assistance in my particular case.</p> <p>I am trying to check if the input values are empty on keyup then disable the submit button.</p> <p>My HTML snippet:</p> <pre><code>&lt;div class='form'&gt; &lt;form&gt; &lt;div class='field'&gt; &lt;label for="username"&gt;Username&lt;/label&gt; &lt;input id="username" type="text" /&gt; &lt;/div&gt; &lt;div class='field'&gt; &lt;label for="password"&gt;Password&lt;/label&gt; &lt;input id="password" type="password" /&gt; &lt;/div&gt; &lt;div class='actions'&gt; &lt;input type="submit" value="Login" /&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt; </code></pre> <p>I have used the example answer from <a href="http://stackoverflow.com/questions/5614399/disabling-submit-button-until-all-fields-have-values">here</a> with some modifications:</p> <pre><code>(function() { $('.field input').keyup(function() { var empty = false; $('.field input').each(function() { if ($(this).val() == '') { empty = true; } }); if (empty) { $('.actions input').attr('disabled', true); } else { $('.actions input').attr('disabled', false); } }); })() </code></pre> <p>Any help would be greatly appreciated!</p>65338587336	0	 <p><code>mysqli_real_escape_string</code> is good, but not always safe as prepared statement.</p> <p><code>mysql_real_escape_string()</code> prone to the same kind of issues affecting <code>addslashes()</code>.</p> <p>So use of <strong><em>prepared statement</em></strong> is much better.</p>65426567465	0	GeckoInputElement.Click returns System.NullReferenceException <p>I am making use of the GeckoWebbrowser control in a C# Windows forms app environment. </p> <p>I am wanting to call the click event on a button on the browser page, from a code event behind.</p> <p>When I try an access a specific button I can find it by making use of the GetElementById command, however after assigning this information to the GeckoInputElement to call the click event, there is a null reference exception visible with this.</p> <p>My code call to get the element looks like this:</p> <pre><code>GeckoInputElement betbt = new GeckoInputElement(wBrowser.Document.GetElementById("bet-bt").DomObject); </code></pre> <p>If I assign it like this I can access the element but still cannot click it with the GeckoElement object:</p> <pre><code>GeckoElement g1 = (GeckoElement)wBrowser.Document.GetElementById("bet-bt"); </code></pre> <p>The HTML for the button looks as follows:</p> <pre><code>&lt;button data-action="bet" id="bet-bt" class="action"&gt;Bet&lt;/button&gt; </code></pre>65536754439	0	 <p>Use <code>background-size: cover;</code> or <code>background-size: contain;</code> as per your necessity. That should fix it.</p>65629024997	0	 <p>The PowerPivot tab is a COM Add-In. To view the progID of it and other COM Add-Ins use:</p> <pre><code>Sub ListCOMAddins() Dim lngRow As Long, objCOMAddin As COMAddIn lngRow = 1 With ActiveSheet For Each objCOMAddin In Application.COMAddIns .Cells(lngRow, "A").Value = objCOMAddin.Description .Cells(lngRow, "B").Value = objCOMAddin.Connect .Cells(lngRow, "C").Value = objCOMAddin.progID lngRow = lngRow + 1 Next objCOMAddin End With End Sub` </code></pre> <p>In my case the progID of the PowerPivot tab is "Microsoft.AnalysisServices.Modeler.FieldList". So to close the tab use:</p> <pre><code>Private Sub Workbook_Open() Application.COMAddIns("Microsoft.AnalysisServices.Modeler.FieldList").Connect = False End Sub </code></pre>65733940429	0	 <p>In order to define an <code>ArrayList</code> with <code>CheckBoxes</code> please refer to following example:</p> <pre><code>List&lt;JCheckBox&gt; chkBoxes = new ArrayList&lt;JCheckBox&gt;(); </code></pre> <p>Add your <code>JCheckBox</code> elements to the <code>ArrayList</code> using standard approach, for example:</p> <pre><code>JCheckBox chkBox1 = new JCheckBox(); chkBoxes.add(chkBox1); </code></pre> <p>Interatve over the list and carry out check if selected using <code>JCheckBox</code> method <code>#.isSelected()</code> as follows:</p> <pre><code>for(JCheckBox chkBox : chkBoxes){ chkBox.isSelected(); // do something with this! } </code></pre>65813315966	0	 <p>There's another angle to this one. If you have SQL Server 2008 already installed, you need to select the upgrade option. If you don't, then in your installation of SQL Server 2008 R2 your "management tools - complete" will be grayed out when you get to the install items choice screen. Hover over it and it will tell you as much. Hope this helps someone.</p>65924004362	0	 <p>I think that you can change the <code>new</code> resource to <code>newVisit</code> like this:</p> <pre><code>App.Router.map () -&gt; @resource 'visits', -&gt; @resource 'visit', { path: '/:visit_id' } @resource 'newVisit', -&gt; @route 'welcome' @route 'directory' @route 'thanks' </code></pre> <p>Now you will have a <code>NewVisitRoute</code> where you can create a new <code>Visit</code> model to use in each of the child routes.</p> <p>And you will be able to make a transition to this routes with the route names: <code>newVisit.welcome</code>, <code>newVisit.directory</code> and <code>newVisit.thanks</code>. You can use this route names in a <code>link-to</code> helper link this:</p> <pre><code>{{link-to "Welcome", "newVisit.welcome"}} </code></pre>66015040416	0	 <p>I use LaTeX to create the DOM representation.</p> <p>Here is a minimal working example:</p> <pre><code>\documentclass{scrreprt} \usepackage{tikz-qtree} \begin{document} \Tree[.table [.thead [.tr [.th [.\textit{Vorname} ] ] [.th [.\textit{Nachname} ] ] ] ] [.tbody [.tr [.td [.\textit{Donald} ] ] [.td [.\textit{Duck} ] ] ] ] ] \end{document} </code></pre> <p>Which gives:</p> <p><img src="https://i.stack.imgur.com/Q1MXq.png" alt="enter image description here"></p>6618414219	0	 <p><strong>Q</strong>: How can I have DNS name resolving running while other protocols seem to be down?</p> <p><strong>A</strong>: Your local DNS resolver (<code>bind</code> is another possibility besides <code>ncsd</code>) <em>might</em> be caching the first response. <code>dig</code> will tell you where you are getting the response from:</p> <pre><code>[mpenning@Bucksnort ~]$ dig cisco.com ; &lt;&lt;&gt;&gt; DiG 9.6-ESV-R4 &lt;&lt;&gt;&gt; +all cisco.com ;; global options: +cmd ;; Got answer: ;; -&gt;&gt;HEADER&lt;&lt;- opcode: QUERY, status: NOERROR, id: 22106 ;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 2, ADDITIONAL: 0 ;; QUESTION SECTION: ;cisco.com. IN A ;; ANSWER SECTION: cisco.com. 86367 IN A 198.133.219.25 ;; AUTHORITY SECTION: cisco.com. 86367 IN NS ns2.cisco.com. cisco.com. 86367 IN NS ns1.cisco.com. ;; Query time: 1 msec &lt;----------------------- 1msec is usually cached ;; SERVER: 127.0.0.1#53(127.0.0.1) &lt;--------------- Answered by localhost ;; WHEN: Wed Dec 7 04:41:21 2011 ;; MSG SIZE rcvd: 79 [mpenning@Bucksnort ~]$ </code></pre> <p>If you are getting a very quick (low milliseconds) answer from <code>127.0.0.1</code>, then it's very likely that you're getting a locally cached answer from a prior query of the same DNS name (and it's quite common for people to use caching DNS resolvers on a <code>ppp</code> connection to reduce connection time, as well as achieving a small load reduction on the ppp link).</p> <p>If you suspect a cached answer, do a <code>dig</code> on some other DNS name to see whether it can resolve too.</p> <ul> <li>If random DNS names continue resolution and you still cannot make a TCP connection to a certain host, this is worthy of noting when you edit the question after this investigation.</li> <li>If random DNS names don't resolve, then this is indicative of something like the loss of your default route, or the <code>ppp</code> connection going down.</li> </ul> <h2>Other diagnostic information</h2> <p>If you find yourself in either of the last situations I described, you need to do some IP and ppp-level debugs before this can be isolated further. As someone mentioned, <code>tcpdump</code> is quite valuable at this point, but it sounds like you don't have it available.</p> <p>I assume you are not making a TCP connection to the same IP address of your DNS server. There are many possibilities at this point... If you can still resolve random DNS names, but TCP connections are failing, it is possible that the problem you are seeing is on the other side of the ppp connection, that the kernel routing cache (which holds a little TCP state information like <code>MSS</code>) is getting messed up, you have too much packet loss for <code>tcp</code>, or any number of things.</p> <p>Let's assume your topology is like this:</p> <pre><code> 10.1.1.2/30 10.1.1.1/30 [ppp0] [pppX] uCLinux----------------------AccessServer----&gt;[To the reset of the network] </code></pre> <p>When you initiate your ppp connection, take note of your IP address and the address of your default gateway:</p> <pre><code>ip link show ppp0 # display the link status of your ppp0 intf (is it up?) ip addr show ppp0 # display the IP address of your ppp0 interface ip route show # display your routing table route -Cevn # display the kernel's routing cache </code></pre> <p>Similar results can be found if you don't have the <code>iproute2</code> package as part of your distro (<code>iproute2</code> provides the <code>ip</code> utility):</p> <pre><code>ifconfig ppp0 # display link status and addresses on ppp0 netstat -rn # display routing table route -Cevn # display kernel routing table </code></pre> <p>For those with the <code>iproute2</code> utilities (which is almost everybody these days), <code>ifconfig</code> has been deprecated and replaced by the <code>ip</code> commands; however, if you have an older 2.2 or 2.4-based system you may still need to use <code>ifconfig</code>.</p> <p><strong>Troubleshooting steps</strong>:</p> <ol> <li><p>When you start having the problem, first check whether you can ping the address of <code>pppX</code> on your access server.</p> <ul> <li>If you can not ping the ip address of <code>pppX</code> on the other side, then it is highly unlikely your DNS is getting resolved by anything other than a cached response on your uCLinux machine.</li> <li>If you can ping <code>pppX</code>, then try to <code>ping</code> the ip address of your TCP peer and the IP address of the DNS (if it is not on <code>localhost</code>). Unless there is a firewall involved, you must be able to <code>ping</code> it successfully for any of this to work.</li> </ul></li> <li><p>If you can <code>ping</code> the ip address of <code>pppX</code> but you cannot <code>ping</code> your TCP peer's ip address, check your routing table to see whether your default route is still pointing out <code>ppp0</code></p></li> <li><p>If your default route points through <code>ppp0</code>, check whether you can still ping the ip address of the default route.</p></li> <li><p>If you can <code>ping</code> your default route and you can <code>ping</code> the remote host that you're trying to connect to, check the kernel's routing cache for the IP address of the remote TCP host.... look for anything odd or suspicious</p></li> <li><p>If you <em>can</em> <code>ping</code> the remote TCP host (and you need to do about 200 <code>pings</code> to be sure... <code>tcp</code> is sensitive to significant packet loss &amp; GPRS is notoriously lossy), try making a successful <code>telnet &lt;remote_host&gt; &lt;remote_port&gt;</code>. If both are successful, then it's time to start looking inside your software for clues.</p></li> </ol> <p>If you still can't untangle what is happening, please include the output of the aforementioned commands when you come back... as well as how you're starting the <code>ppp</code> connection.</p>6624521403	0	How to ad a title on a section of my wordpress blog <p>I want to ad a title "Instant Independent" to the center "featured" section of my wordpress blog. Directly above where the "fee increase coming soon for lake mohave" story. <a href="http://www2.az-independent.com/" rel="nofollow">http://www2.az-independent.com/</a></p> <p>How do I do this?</p>66327392016	0	Incorrectly parsed ReturnJSON method <p>This method</p> <pre><code>var fListItems = db.FListItems.Include(f =&gt; f.FList) .Include(f =&gt; f.Item) .GroupBy(g =&gt; new { g.Item.Name, g.FList.Title }) .Select(lg =&gt; new FListItemsViewModel { Title = lg.Key.Title, ItemStat = new ItemStat { Name = lg.Key.Name, NameCount = lg.Count(), NameSum = lg.Sum(w =&gt; w.Score), NameAverage = lg.Average(w =&gt; w.Score) } }); </code></pre> <p>returns this JSON</p> <pre><code>[ { Title: "Animals", ItemStat: { Name: "Cat", NameCount: 2, NameSum: 8, NameAverage: 4 } }, { Title: "Animals", ItemStat: { Name: "Dog", NameCount: 1, NameSum: 5, NameAverage: 5 } } ] </code></pre> <p>but I'd like it to return this JSON:</p> <pre><code>[ { Title: "Animals", ItemStats: [ { Name: "Cat", NameCount: 2, NameSum: 8, NameAverage: 4 }, { Name: "Dog", NameCount: 1, NameSum: 5, NameAverage: 5 } ] } ] </code></pre> <p>Can anybody suggest how to do this? Here's the viewmodel:</p> <pre><code>public class FListItemsViewModel { public string Title { get; set; } public ItemStat ItemStat { get; set; } } public class ItemStat { public string Name { get; set; } public int NameCount { get; set; } public int NameSum { get; set; } public double NameAverage { get; set; } } </code></pre> <p>Rather than <code>GroupBy</code> <code>Title</code> and <code>Name</code> in the same clause, could it be better to re-write my query with two seperate <code>GroupBy</code>s?</p> <p>Progress based on Rahul's answer:</p> <pre><code>[ { Title: "Animals", ItemStat: [ { Name: "Cat", NameCount: 2, NameSum: 8, NameAverage: 4 }, { Name: "Cat", NameCount: 2, NameSum: 8, NameAverage: 4 } ] }, { Title: "Animals", ItemStat: [ { Name: "Dog", NameCount: 1, NameSum: 5, NameAverage: 5 } ] } ] </code></pre>6647172537	0	 <p>If you accept to recycle the random numbers, why do you want to wait for the exhaustion of the combinations before recycling?</p> <ul> <li>This makes the numbers less and less random when going to the end of the combination set</li> <li>This forces you to maintain some database to know which numbers have already been used and which haven't.</li> </ul> <p>I would just generate random numbers, without caring if they've been used already.</p> <p>If you really really want to keep it like you asked, here's how you could do it:</p> <ul> <li>Generate all the combinations and put them into a database table</li> <li>Store the size of this table in some variable</li> <li>Generate a random number R between 1 and the size of the table</li> <li>Fetch the combination stored at the Rth row of the table</li> <li>Delete the Rth row from the table, and decrement the size variable</li> <li>when the table is empty (and the size variable is 0), start again</li> </ul> <p>You could improve it by moving the used numbers from one table to another, and use the second table instead of the first one when the first table is empty.</p> <p>You could also do that in memory, if you have enough of it.</p>6655613804	0	 <p>Assuming you've made sure your application doesn't persist anything, all you have left to do is add <code>UIApplicationExitsOnSuspend</code> and set it to true in your application's <code>Info.plist</code>. The moment the user leaves your application, its process will terminate. When the user starts your application again it won't remember anything; it'll just start from the beginning. This includes displaying the launch image.</p>66615455247	0	Smallest number in array and it position <p>What I am trying to achieve is to find smallest number in array and it initial position. Here's an example what it should do:</p> <pre><code>temp = new Array(); temp[0] = 43; temp[1] = 3; temp[2] = 23; </code></pre> <p>So in the end I should know number 3 and position 1. I also had a look here: <a href="http://stackoverflow.com/questions/8934877/obtain-smallest-value-from-array-in-javascript">Obtain smallest value from array in Javascript?</a> , but this way does not gives me a number position in array. Any tips, or code snippets are appreciated. Thanks.</p>66726963227	0	 <p>Your recursive predicate isConnected/2 misses the base case:</p> <pre><code>isConnected(X,Y) :- graph1(X,Y). </code></pre> <p>(assuming we are checking graph1, of course).</p> <p>Anyway, you cannot use isConnected/2, since Prolog will loop on cyclic graphs.</p>66827267854	0	Rounded Corner images <p>I've been trying to do perfectly shaped circular images with non-square images. I tried to make it with </p> <pre><code>[self.photoView.layer setCornerRadius:50.0f]; [self.photoView.layer setMasksToBounds:YES]; </code></pre> <p>It becomes something like this:</p> <p><img src="https://i.stack.imgur.com/ftyrj.png" alt="Not so perfectly rounded"></p> <p>I want to make it full perfect circular. </p> <p>PhotoView's content mode is setted to Aspect Fill, It's height and width fixed to 80x80 with autolayout. I could not figure it out.</p> <p>I made circular images with cropping and scaling them, but also want to add a border to it, in this way i need to recreate new uiimage to draw borders in it. It's expensive thing. I want to use photoView's layer to do this. </p> <p>Any help is appreciated.</p>66911979894	0	 <p>You are accessing <code>getResources()</code> without a reference to a <code>Context</code>. Because this is a static method, you can only access other static methods within that class without providing a reference.</p> <p>Instead, you must pass the <code>Context</code> as an argument:</p> <pre><code>// the 34th button Button tf = (Button) findViewById(R.id.tFour); tf.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Apply.applyBitmap(v.getContext(), R.drawable.tFour); // Pass your context to the static method } }); </code></pre> <p>Then, you must reference it for <code>getResources()</code>:</p> <pre><code>public static void applyBitmap(Context context, int resourceID) { BitmapFactory.Options opt = new BitmapFactory.Options(); opt.inScaled = true; opt.inPurgeable = true; opt.inInputShareable = true; Bitmap brightBitmap = BitmapFactory.decodeResource(context.getResources(), resourceID, opt); // Use the passed context to access resources brightBitmap = Bitmap.createScaledBitmap(brightBitmap, 100, 100, false); MyBitmap = brightBitmap; } </code></pre>6709489652	0	 <p>the warnings are caused by the maven tar archiver. By default, it warns for tar entries with path length > 100 chars. Considering this is an ancient tar format limitation, I changed the default to "gnu" for tycho 0.17.0-SNAPSHOT so you should no longer get these warnings:</p> <p><a href="https://github.com/eclipse/tycho/commit/5db5cc2b76bdba8526cfc4acb66b3e4674f23f03" rel="nofollow">https://github.com/eclipse/tycho/commit/5db5cc2b76bdba8526cfc4acb66b3e4674f23f03</a></p>67138432502	0	PayPal iOS Network Connection Was Lost <p>I actually posted this question on <a href="https://github.com/paypal/PayPal-iOS-SDK/issues/435" rel="nofollow">PayPal Repository GitHub</a>, but no one was answering me.</p> <p>The PayPal SDK works so fine when using a PayPal Account, but when I try to use Pay with card, I can't connect to the PayPal Server, and there is no debug logs, only this: </p> <blockquote> <p>2016-07-18 10:00:03.447 UPlant[23489:265771] NSScanner: nil string argument 2016-07-18 10:00:04.036 UPlant[23489:265771] Can't find keyplane that supports type 4 for keyboard iPhone-Portrait-NumberPad; using 563160167_Portrait_iPhone-Simple-Pad_Default 2016-07-18 10:00:04.077 UPlant[23489:265771] NSScanner: nil string argument 2016-07-18 10:00:04.077 UPlant[23489:265771] NSScanner: nil string argument 2016-07-18 10:00:04.077 UPlant[23489:265771] NSScanner: nil string argument 2016-07-18 10:00:08.415 UPlant[23489:265771] Can't find keyplane that supports type 4 for keyboard iPhone-Portrait-NumberPad; using 563160167_Portrait_iPhone-Simple-Pad_Default 2016-07-18 10:00:10.070 UPlant[23489:265771] Can't find keyplane that supports type 4 for keyboard iPhone-Portrait-NumberPad; using 563160167_Portrait_iPhone-Simple-Pad_Default</p> </blockquote> <p><strong>Additional Information</strong></p> <p><strong>Mode (Mock/Sandbox/Live)</strong>: Sandbox</p> <p><strong>PayPal iOS SDK Version:</strong> sandbox, PayPal iOS SDK 2.14.2</p> <p><strong>iOS Version and Device (iOS 8.x, iOS 9.3 on an iPhone 6s, etc.):</strong> iOS 9.3 iPhone 5 Simulator</p> <p><strong>PayPal-Debug-ID(s) (from any logs):</strong> No debug logs</p> <p>After attempting the PayPal to do the transaction with Card, it pops up an alert saying </p> <blockquote> <p>The Network Connection Was Lost.</p> </blockquote> <p>Any idea on this why is this happening and how to solve it?</p>67231597735	0	 <p>After playing around with it a bit I came to this conclusion. I changed the HTML a bit because I wanted to use the Bootstrap alert boxes.</p> <pre><code>public static string MyValidationSummary(this HtmlHelper helper, string validationMessage = "") { string retVal = ""; string errorList = ""; foreach (var key in helper.ViewData.ModelState.Keys) { retVal = ""; foreach (var err in helper.ViewData.ModelState[key].Errors) { retVal += "&lt;div class='alert alert-danger'&gt;"; retVal += "&lt;button type='button' class='close' data-dismiss='alert' aria-hidden='true'&gt;×&lt;/button&gt;"; retVal += "&lt;i class='icon-remove-sign'&gt;&lt;/i&gt;"; retVal += helper.Encode(err.ErrorMessage); retVal += "&lt;/div&gt;"; errorList += retVal; } } return errorList.ToString(); } </code></pre>6734488211	0	 <p>Observe that:</p> <ul> <li>For the number XY you have 11X + 2Y.</li> <li>For the number XYZ you have 111X + 22Y + 3Z.</li> <li>For WXYZ, you have 1111W + 222X + 33Y + 4Z.</li> </ul> <p>Here's my C# implementation, though it should be trivial to port to Java:</p> <pre><code>static long SumSubtring(String s) { long sum = 0, mult = 1; for (int i = s.Length; i &gt; 0; i--, mult = mult * 10 + 1) sum += (s[i - 1] - '0') * mult * i; return sum; } </code></pre> <p>Note that it is effectively O(n).</p>67432227126	0	CentOs Magento files created as directories? <p>I noticed a few days ago that a few files that belong to a certain Magento extension were in fact created as directories and not in fact the .png .css and .js files that they were supposed to be. When updating the extension there are errors as the files are unable to overwrite the existing directories. I mainly noticed this due to the icons being missing from the Magento admin panel. Although baffling, no big deal, I deleted the directories (x4) and copied the correct files from the original distribution. Problem solved.</p> <p>I used find . -type d "<em>.</em>" and also the 'empty' option to identify directories which should be files. This fixes the symptom but not the cause. There were around 10 files, mostly images but some .js and .css affected.</p> <p>I've just run an update of M2e via Magento connect, 'successfully', but having noticed some missing icons/graphics in admin I checked the code and have identified 17 empty directories that should have been image files (.png and .gif).</p> <p>I guess my questions are how and why is this happening? How can I stop it happening again?</p> <p>I have a dedicated CentOS server running Apache. Installs are done via Filezilla FTP upload or Magento Connect, it seems most likely that it's Connect causing the problem, both extensions have been updated by Connect at least once in their lifetime.</p> <p>Hoping someone can enlighten me, though not a huge problem in itself, it is a concern that critical files (rather than images) may be prone to the same problems...Anyone seen this before??</p> <p>Cheers RobH</p>6753294365	0	 <p>The destination anchor for a link in an HTML page may be any element with an <code>id</code> attribute. See <a href="http://www.w3.org/TR/html401/struct/links.html" rel="nofollow noreferrer">Links</a> on the W3C site. Here's a quote from the relevant section:</p> <blockquote> <p>Destination anchors in HTML documents may be specified either by the A element (naming it with the name attribute), or by any other element (naming with the id attribute).</p> </blockquote> <p>Markdown treats HTML as HTML (see <a href="http://daringfireball.net/projects/markdown/syntax#html" rel="nofollow noreferrer">Inline HTML</a>), so you can create your fragment identifiers from any element you like. If, for example, you want to link to a paragraph, just wrap the paragraph in a paragraph tag, and include an id:</p> <pre><code>&lt;p id="mylink"&gt;Lorem ipsum dolor sit amet...&lt;/p&gt; </code></pre> <p>Then use your standard Markdown <code>[My link](#mylink)</code> to create a link to fragment anchor. This will help to keep your HTML clean, as there's no need for extra markup.</p>67624453451	0	Autoencoders: Papers and Books regarding algorithms for Training <p>Which are some of the famous research papers and/or books which concern Autoencoders and the various different training algorithms for Autoencoders? I'm talking about research papers and/or books which lay the foundation for the different training algorithms used to train autoencoders. </p>67734564942	0	 <p>Am assuming you know javascript array and few method</p> <hr> <p>Use the <strong><em>window.location.href</em></strong></p> <p>var url = 'site.com/seach?a=val0&amp;b=val1'</p> <p>split the '?' </p> <p>var someArray = url.split('?');</p> <p>The someArray looks like this ['site.com/seach', 'a=1000&amp;b=c'] index 0 is the window.location and index 1 is queryString</p> <p>var queryString = someArray[1];</p> <p>Go futher a split '&amp;' so u get a key=value</p> <p>var keyValue = queryString.split('&amp;');</p> <p>keyVal looks like this ['a=val0', 'b=val1'];</p> <p>Now lets get keys and values.</p> <p>var keyArray=[], valArray=[];</p> <p>Loop through the keyValue array and split '=' the update keyArray and valArray</p> <p>for(var i = 0; i &lt; keyValue.length; i++){</p> <p>key = keyValue[i].split('=')[0];</p> <p>val = keyValue[i].split('=')[1];</p> <p>keyArray.push(key);</p> <p>valArray.push(val);</p> <p>}</p> <p>Finally we have</p> <p>keyArray = ['a', 'b'];</p> <p>valArray = ['val0', 'val1'];</p> <p>Our full codes looks like this.</p> <p>var url = 'site.com/seach?a=val0&amp;b=val1';</p> <p>var someArray = url.split('?');</p> <p>var queryString = someArray[1];</p> <p>var keyValue = queryString.split('&amp;');</p> <p>var keyArray=[], valArray=[];</p> <p>for(var i = 0; i &lt; keyValue.length; i++){</p> <p>key = keyValue[i].split('=')[0];</p> <p>val = keyValue[i].split('=')[1];</p> <p>keyArray.push(key);</p> <p>valArray.push(val);</p> <p>}</p> <p>DONE!</p>67818217302	0	 <p>You might need to change </p> <pre><code>-lopencv_core244 \ -lopencv_highgui244 \ -lopencv_imgproc244 </code></pre> <p>to</p> <pre><code>-lopencv_core244d \ -lopencv_highgui244d \ -lopencv_imgproc244d </code></pre> <ul> <li>note 'd' at the end of each lib (if you are to build in debug)</li> </ul>67937747592	0	 <p>Do not set any <code>IBOutlet</code> of your <code>UIViewController</code> before it is displayed. </p> <p>The <code>IBOutlet</code> is probably not initialised yet. I would suggest making a string property, setting it when you initialise your <code>UIViewController</code> and setting that text to your <code>UILabel</code> in the <code>viewDidLoad</code> or <code>viewWillAppear</code> method.</p> <p>Hope this helped!</p>6809449562	0	How to remove Scrollbar in ChromeDriver, how to change http-agent? <p>I use <code>IWebDriver driver = new ChromeDriver(options)</code> in C#</p> <p>When I take <code>.GetScreenshot();</code>, often see scrollbar, is there a way to remove it?</p> <p>2nd question, how to mock/change <code>http_agent</code> in ChromeDriver?</p>68111141718	0	 <p>I will take it from the silence that there is no such feature. So here is the macro for it:</p> <pre><code>Sub StopDebugAndKillProcesses() Dim dbg As EnvDTE80.Debugger2 = DTE.Debugger dbg.Stop() Dim shell_string As String shell_string = "taskkill /F /IM TheProcessToKill.exe" Shell(shell_string) End Sub </code></pre> <p>Assign it to a button, put it next to the original "Stop" button and your done.</p>68224771191	0	 <p>The local file system is declared to be cross-origin and will taint the canvas. This is a good declaration given that your most sensitive information is probably on a local file system.</p> <p>Here are some ways to be compliant with CORS security:</p> <ul> <li><p>Install a web server on your local computer and serve both your images and .html/.css/.js files on that server. PHP &amp; IIS both have excellent local editions.</p></li> <li><p>Put your images on a CORS compliant hosting service (imagur.com is one among others)</p></li> <li><p>For small projects, it sometimes works to put both the image and webpage files all on the desktop.</p></li> </ul>68327585390	0	 <p>It's equivalent to</p> <pre><code>least = Math.min(least, k); </code></pre> <p>or</p> <pre><code>if (!(least &lt; k)) { least = k } </code></pre> <p>See also: <a href="http://docs.oracle.com/javase/tutorial/java/nutsandbolts/op2.html">the Java documentation on the ternary operator</a> (scroll to the "The Conditional Operators" section).</p>68430244323	0	PHP - Cast type from variable <p>I was asking myself if it's possible to cast a string to become another type defined before</p> <p>e.g.</p> <pre><code>$type = "int"; $foo = "5"; $bar = ($type) $foo; </code></pre> <p>and where $bar === 5</p>685319672	0	GetWindowLong vs GetWindowLongPtr in C# <p>I was using GetWindowLong like this:</p> <pre><code>[DllImport("user32.dll")] private static extern IntPtr GetWindowLong(IntPtr hWnd, int nIndex); </code></pre> <p>But according to the MSDN docs I am supposed to be using GetWindowLongPtr to be 64bit compatible. <a href="http://msdn.microsoft.com/en-us/library/ms633584(VS.85).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms633584(VS.85).aspx</a></p> <p>The MSDN docs for GetWindowLongPtr say that I should define it like this (in C++):</p> <pre><code>LONG_PTR GetWindowLongPtr(HWND hWnd, int nIndex); </code></pre> <p>I used to be using IntPtr as the return type, but what the heck would I use for an equivalent for LONG_PTR? I have also seen GetWindowLong defined as this in C#:</p> <pre><code>[DllImport("user32.dll")] private static extern long GetWindowLong(IntPtr hWnd, int nIndex); </code></pre> <p>What is right, and how can I ensure proper 64bit compatibility?</p>68617641209	0	 <p>Your app crashing because the variable <code>maxInt</code> in plus1 is undefined. <code>maxInt</code>'s scope is local to <code>onCreate</code>. Also <code>final</code> variables are like <code>constant</code> variables in C. They can only get a value when you initialize them, meaning you can't change their value.</p> <p>Your maxInt should not be final and should be a global variable:</p> <pre><code>public class ScoreActivity extends Activity { int maxInt; protected void onCreate(Bundle savedInstanceState) { ... maxInt = Integer.parseInt(max); ... } public void plus1 (View V) { maxInt ++; } ... } </code></pre>6871641232	0	 <p>Python has limited support for private identifiers, through a feature that automatically prepends the class name to any identifiers starting with two underscores. This is transparent to the programmer, for the most part, but the net effect is that any variables named this way can be used as private variables.</p> <p>See <a href="http://docs.python.org/tutorial/classes.html#private-variables" rel="nofollow noreferrer">here</a> for more on that.</p> <p>In general, Python's implementation of object orientation is a bit primitive compared to other languages. But I enjoy this, actually. It's a very conceptually simple implementation and fits well with the dynamic style of the language.</p>6884759726	0	.NET - Multiple libraries with the same namespace - referencing <p>Today I am faced with a curious challenge...</p> <p>This challenge involves two .NET libraries that I need to reference from my application. Both of which I have no control over and have the same namespace within them.</p> <p>So...</p> <p>I have <code>foo.dll</code> that contains a <code>Widget</code> class that is located on the <code>Blue.Red.Orange</code> namespace.</p> <p>I have <code>bar.dll</code> that also contains a <code>Widget</code> class that is also located on the <code>Blue.Red.Orange</code> namespace.</p> <p>Finally I have my application that needs to reference both <code>foo.dll</code> and <code>bar.dll</code>. This is needed as within my application I need to use the <code>Widget</code> class from <code>foo</code> and also the <code>Widget</code> class from <code>bar</code></p> <p>So, the question is how can I manage these references so that I can be certain I am using the correct <code>Widget</code> class?</p> <p>As mentioned, I have no control over the <code>foo</code> or <code>bar</code> libraries, they are what they are and cannot be changed. I do however have full control over my application.</p>68918714240	0	 <p>Add a hidden field to your aspx page.</p> <pre><code> &lt;asp:HiddenField ID="hfrecordID" runat="server" /&gt; </code></pre> <p>And assign the recodId to it in the ItemDataBound event and use it in the aspx page.</p> <pre><code> &lt;telerik:RadCodeBlock ID="RadCodeBlock1" runat="server"&gt; &lt;script type="text/javascript"&gt; function ViewCheck(filename) { var targetfile = "Allegati/" + &lt;%= hfrecordID.value %&gt; + filename; var openWnd = radopen(targetfile, "RadWindowDetails"); } &lt;/script&gt; protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e) { if (e.Item is GridEditableItem &amp;&amp; e.Item.IsInEditMode) { GridEditableItem editedItem = e.Item as GridEditableItem; hfrecordID= editedItem.GetDataKeyValue("TransazioneID").ToString(); } } </code></pre>69018151503	0	 <p>It looks from your code like you're trying to run some php code (tradeformresult.php). Loading it this way isn't going to work as expected-that require_once will be run as the page is being built in PHP, not in the browser.</p> <p>For sending a form without refreshing the page, you should look into AJAX (<a href="http://en.wikipedia.org/wiki/Ajax_(programming)" rel="nofollow">http://en.wikipedia.org/wiki/Ajax_(programming)</a>)</p> <p>JQuery has a good AJAX method. Here is a simple example of how to use it:</p> <pre><code>$.ajax({url:"http://www.someserver.com/api/path", data:{val1:"value",val2:"value"}) .success(function(returnData) { console.log(returnData); }); </code></pre> <p>The above will call the given URL with the given data as parameters, then, if successful, will return whatever data the server gave back into the <code>returnData</code> variable.</p> <p>If you're using AJAX, you don't really even have to use a <code>&lt;form&gt;</code> tag, since you'll be building the query string manually. You can have the function that makes the AJAX call be triggered from the <code>onClick</code> event of a button.</p>69132064508	0	 <p>There is a wordpress plugin CC Circle Progress Bar which will work for you. Here is the link: <a href="https://wordpress.org/plugins/cc-circle-progress-bar/" rel="nofollow">https://wordpress.org/plugins/cc-circle-progress-bar/</a></p>69232958703	0	 <p>You need to create a resources folder in your eclipse project. and then add that folder to your project sources. application.properties file (which contains IP/Port of RTSP server) should be located there. </p> <p><a href="https://i.stack.imgur.com/wssvQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wssvQ.png" alt="It should look something like this"></a></p>69320176778	0	Is it good to make function in function using 'return'? <p>While I was investigating functions, I realised that I can create embedded functions. Firstly, I thought it may be useful for structuring code. But now I suppose it isn't good style of coding. Am I right? Here is an example.</p> <pre><code>function show () { return function a() { alert('a'); return function b() { alert('b'); } } } </code></pre> <p>And I can call <code>alert('b')</code> using this string: <code>show()()</code>;</p> <p><strong>In what</strong> situations is better to use this method and in what not?</p>69416930087	0	 <p>The error is in this line of code.</p> <pre><code>if (sqlite3_prepare_v2(contactDB, query_stmt, 1, &amp;statement, NULL) == SQLITE_OK) { </code></pre> <p>The <code>1</code> is wrong. From the SQLite docs:</p> <pre><code>int sqlite3_prepare_v2( sqlite3 *db, /* Database handle */ const char *zSql, /* SQL statement, UTF-8 encoded */ int nByte, /* Maximum length of zSql in bytes. */ sqlite3_stmt **ppStmt, /* OUT: Statement handle */ const char **pzTail /* OUT: Pointer to unused portion of zSql */ ); If the nByte argument is less than zero, then zSql is read up to the first zero terminator. If nByte is non-negative, then it is the maximum number of bytes read from zSql. </code></pre> <p>So you are forcing SQLite to only read the first byte from the statement. Of course this is invalid.</p>69522399218	0	 <p>Maybe you could use <a href="https://api.jquery.com/promise/" rel="nofollow"><code>.promise()</code></a> for this. </p> <p>You can add a promise to the upload function. This way you could run functions like <code>upload.done(function(e) { /* do stuff */ });</code> </p> <p>The <a href="https://api.jquery.com/jQuery.ajax/" rel="nofollow"><code>$.ajax()</code></a> in jQuery has its build-in promise. You can check if an ajax call succeeded with <code>xhr.done(function(e) { /* do stuff */ });</code></p>69611117515	0	JqueryUI slider handle stuck on the div border and handle donot reaches max value <p>Hi guys I'm a Jquery noob ,I'm using jqueryUI slider but the slider handle always stucks on div border (left side) and after clicking on the slider bar it moves forward but doesn't reaches max limit and stucks in between.</p> <p>Check the <strong><a href="http://jsfiddle.net/VaMJ2/1/" rel="nofollow noreferrer">JsFiddle</a></strong> the snapshot is from the browser (where you can see the slider handle) ,I have put all the code on fiddle ,but can't make jsFiddle work.</p> <p><img src="https://i.stack.imgur.com/k2Ri7.jpg" alt="enter image description here"> <br/> <em>Slider:</em><br/> 1. Slider handle sticks to the div border.<br/> 2. Slider handle doesnt move towards the max value and stucks at some value in between.</p>69731997082	0	 <p>You can of course use a regexp, but there are libraries which will do the job quicker and easier. Try using a HTML dom parser, or <a href="http://code.google.com/p/phpquery/" rel="nofollow">phquery</a> which is an implementation of jquery lib in php. It's also <a href="https://packagist.org/packages/electrolinux/phpquery" rel="nofollow">available for Composer</a>. So if you're familiar with jquery syntax, you can find it very neat.</p> <p>Get the html you need using this: $html = pq('.modal.ww')->html();</p>69818818456	0	center site content on all devices <p>This is the site I am referring to: <a href="http://heattreatforum.flyten.net/" rel="nofollow">http://heattreatforum.flyten.net/</a></p> <p>It was built as a child-site to the twenty-twelve theme.</p> <p>I can't seem to get the content to center on every screen, and I am seeing a strange wide margin on the right that I just can't seem to locate in my css.</p> <p>Any help would be much appreciated - thanks for looking!</p>69923659948	0	WCF binding over HTTPS an security at message level <p>I have a WCF Service over HTTP with the following binding:</p> <pre><code>&lt;basicHttpBinding&gt; &lt;binding name="RegistreReferenciaBinding"&gt; &lt;security mode="Message"&gt; &lt;message clientCredentialType="Certificate" /&gt; &lt;/security&gt; &lt;/binding&gt; &lt;/basicHttpBinding&gt; </code></pre> <p>A third party service is connecting to this Service and now this third party is requiring an HTTPS connection.</p> <p>The problem is that I need to maintain the security at message level in order to be compatible with the third party Service.</p> <p>To resume the situation what I need to do is configure the service to be HTTPS compatible, without client certificate while maintaining the security at message level.</p> <p>What is the configuration needed to get this Service working with the same configuration but over HTTPS?</p> <p><strong>UPDATE:</strong></p> <p>I tried to use the following configuration:</p> <pre><code>&lt;basicHttpBinding&gt; &lt;binding name="RegistreReferenciaBinding"&gt; &lt;security mode="Transport" /&gt; &lt;/binding&gt; &lt;/basicHttpBinding&gt; </code></pre> <p>But with this configuration the third party Service could not connect because there was no security at message level.</p> <p>From what I viewed in captured messages with Wireshark, the third party Service is using SOAP 1</p> <p>The error message with this configuration was:</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"&gt; &lt;s:Body&gt; &lt;s:Fault&gt; &lt;faultcode&gt;s:MustUnderstand&lt;/faultcode&gt; &lt;faultstring xml:lang="es-ES"&gt;El destinatario de este mensaje no entendió el encabezado 'Security' del espacio de nombres 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd', por lo que el mensaje no se procesó. Este error suele indicar que el remitente del mensaje habilitó un protocolo de comunicación que el destinatario no puede procesar. Asegúrese de que la configuración del enlace del cliente es coherente con el enlace del servicio. &lt;/faultstring&gt; &lt;/s:Fault&gt; &lt;/s:Body&gt; &lt;/s:Envelope&gt; </code></pre> <p><strong>UPDATE 2</strong></p> <p>I also tried with the following configuration:</p> <pre><code>&lt;basicHttpBinding&gt; &lt;binding name="RegistreReferenciaBinding"&gt; &lt;security mode="TransportWithMessageCredentials"&gt; &lt;message clientCredentialType="Certificate" /&gt; &lt;/security&gt; &lt;/binding&gt; &lt;/basicHttpBinding&gt; </code></pre> <p>And it failed again.</p>70013617138	0	php validation is incorrect for drop down menu <p>I have a code below where it displays students details in a drop down menu, and then it does a php validation to see if a student is selected from the drop down menu or not:</p> <pre><code>$sql = "SELECT StudentUsername, StudentForename, StudentSurname FROM Student ORDER BY StudentUsername"; $sqlstmt = $mysqli-&gt;prepare($sql); $sqlstmt-&gt;execute(); $sqlstmt-&gt;bind_result($dbStudentUsername, $dbStudentForename, $dbStudentSurname); $students = array(); // easier if you don't use generic names for data $studentHTML = ""; $studentHTML .= '&lt;select name="students" id="studentsDrop"&gt;'.PHP_EOL; $studentHTML .= '&lt;option value=""&gt;Please Select&lt;/option&gt;'.PHP_EOL; $outputstudent = ""; while($sqlstmt-&gt;fetch()) { $student = $dbStudentUsername; $firstname = $dbStudentForename; $surname = $dbStudentSurname; $studentHTML .= "&lt;option value='" . $student . "'&gt;" . $student . " - " . $firstname . " " . $surname . "&lt;/option&gt;" . PHP_EOL; } $studentHTML .= '&lt;/select&gt;'; $errormsg = (isset($errormsg)) ? $errormsg : ''; if(isset($_POST['resetpass'])) { //get the form data $studentdrop = (isset($_POST['students'])) ? $_POST['students'] : ''; if($studentdrop = "") { $errormsg = "Student is Selected"; } else{ $errormsg = "You must Select a Student"; } } </code></pre> <p>The problem I have though is that even though I have selected a student from the drop down menu, it still displays a message stating that "You Must select a Student".</p> <p>What is suppose to happen is that if the user has not selected a student or in other words when they have submitted the form and the drop down menu is still on the "Please Select" option, then it displays the message stating that user must select a student, else if the user does select a student from the drop down menu then display the message that a student has been selected.</p>7013207102	0	 <p>Make sure you have the exact same service pack levels on the test and production servers. Also make sure you have the same version of all the assemblies of the third party library.</p>70239528057	0	 <p>It is usually a bad idea to use a <code>python</code> <code>for</code> loop to iterate over a large <code>pandas.DataFrame</code> or a <code>numpy.ndarray</code>. You should rather use the available build in functions on them as they are optimized and in many cases actually not written in python but in a compiled language. In your case you should use the methods <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.max.html" rel="nofollow">pandas.DataFrame.max</a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.min.html" rel="nofollow">pandas.DataFrame.min</a> that both give you an option <code>skipna</code> to skip <code>nan</code> values in your <code>DataFrame</code> without the need to actually drop them manually. Furthermore, you can choose a <code>axis</code> to minimize along. So you can specifiy <code>axis=1</code> to get the minimum along columns.</p> <p>This will add up to something similar as what @EdChum just mentioned in the comments:</p> <pre><code>data.max(axis=1, skipna=True) - data.min(axis=1, skipna=True) </code></pre>70331202407	0	 <p>Even though not specifically mentioned in the API description, the <a href="http://www.google.com/support/enterprise/static/gsa/docs/admin/72/gsa_doc_set/xml_reference/request_format.html#1076971" rel="nofollow">Google GSA Search Protocol Reference</a> is pretty explicit about this limitation:</p> <blockquote> <p>The maximum number of results available for a query is 1,000, i.e., the value of the start parameter added to the value of the num parameter cannot exceed 1,000.</p> </blockquote> <p>However, if all you need is more than 1,000 records (as you indicated) you can structure your query to return a well-defined non-overlapping subset of potential results, then piece together the overall result.</p> <p>A simple example would segment results by date. For the custom query you posted, appending something like <code>&amp;sort=date:r:20100101:20101231</code> would return 1,000 results from the year 2010. If you repeat this for 2011, you would have a total of 2,000 results.</p>70419262634	0	 <p>This might be something you can try: <a href="http://www.krautcomputing.com/blog/2012/03/27/how-to-compile-custom-sass-stylesheets-dynamically-during-runtime/" rel="nofollow">http://www.krautcomputing.com/blog/2012/03/27/how-to-compile-custom-sass-stylesheets-dynamically-during-runtime/</a>.</p> <p>I've used this in a Rails 3.2x project and it works fine, but I'm having difficulties getting it working in a different (somewhat modified Rails 4 project).</p> <p>It's older article about compiling css on the fly using the Sprockets::StaticCompiler class.</p>7057704031	0	jquery sliding menu opening/closing animations issue <p>I'm testing this on local : <a href="http://jsfiddle.net/fYkMk/1/" rel="nofollow noreferrer">http://jsfiddle.net/fYkMk/1/</a> This is a booking form that opens up on mouse over (booking-mask) and closes when mouse leaves it. It has 4 fields : </p> <ul> <li>datepicker</li> <li>number of guests </li> <li>number rooms</li> <li>number of nights</li> </ul> <p>the last three fields are sliding menus that open up with a click on the relative icon.</p> <p>These sliding animations work until The user decide to "mouseover" then "mouseleave" and "mouseover" again over the booking-mask div before the oprning/closing animations are finished yet.</p> <p>So it happens the lists are broken and I can only see a piece of them.[see image below]</p> <p><img src="https://i.stack.imgur.com/LxhK8.jpg" alt="enter image description here"></p> <p>Hope you can help me out with this. Thanks</p> <p>Luca</p>7069416950	0	 <p>I would first fetch the title tag and then process the title further. The other answers contain perfectly valid solutions for this task.</p> <h2>Some further notes:</h2> <ul> <li>Please use DOMDocument for such things, since it is much safer (your regular expression might break on some specific HTML pages)</li> <li><p><strong>Please use the non-greedy version of <code>.*</code>: <code>.*?</code></strong>, otherwise you will run into funny things like:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;a&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;title&gt;test&lt;/title&gt; &lt;!-- not allowed in HTML, but since when does the web pages online actually care about that? --&gt; &lt;/body&gt; &lt;/html&gt; </code></pre></li> </ul> <p>You will now match everything between <code>&lt;title&gt;a&lt;/title&gt;...</code> up to <code>&lt;title&gt;test&lt;/title&gt;</code>, including everything in between.</p>70717278865	0	Connection to a web service in Android Virtual Device <p>I have a web service with a WS-security. I can have access to this web service only with my machine IP address and only if I make the right WS configuration.</p> <p>So when testing it in Soap-ui, I get responses! and when testing connection in browser of my emulator, I get the wsdl page!</p> <p>But when implemented in my application, I can not call the web service! I'm making something really wrong and didn't get it!</p> <p>Is the URL I'm using for calling my web service right? Have I to configure the DNS server in the emulator? What have I to do ?</p> <p>Here is my SOAP request:</p> <pre><code> POST http://172.xxx.xxx.xxx:8080/wbb HTTP/1.1 Accept-Encoding: gzip,deflate Content-Type: text/xml;charset=UTF-8 SOAPAction: "" Content-Length: 1146 Host: 172.xxx.xxx.xxx:8080 Connection: Keep-Alive User-Agent: Apache-HttpClient/4.1.1 (java 1.5) &lt;soapenv:Envelope xmlns:ser="http://www.''''.com/wbb/service" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"&gt; &lt;soapenv:Header&gt;&lt;wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"&gt; &lt;wsse:UsernameToken wsu:Id="UsernameToken-11"&gt; &lt;wsse:Username&gt;whatever2&lt;/wsse:Username&gt; &lt;wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText"&gt;whatever3&lt;/wsse:Password&gt; &lt;wsse:Nonce EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary"&gt;whatever4&lt;/wsse:Nonce&gt; &lt;wsu:Created&gt;whatever5&lt;/wsu:Created&gt; &lt;/wsse:UsernameToken&gt;&lt;/wsse:Security&gt;&lt;/soapenv:Header&gt; &lt;soapenv:Body&gt; &lt;ser:RechargeRequest&gt; &lt;ser:value1&gt;?&lt;/ser:value1&gt; &lt;ser:value2&gt;?&lt;/ser:value2&gt; &lt;!--Optional:--&gt; &lt;ser:value3&gt;?&lt;/ser:value3&gt; &lt;/ser:RechargeRequest&gt; </code></pre> <p> </p> <p>and my android code:</p> <pre><code> protected String doInBackground(String... params) { private static final String SOAP_ACTION = ""; private static final String NAMESPACE"http://www.'''''.com/wbb/ws"; private static final String METHOD_NAME="Recharge"; private static final String URL = "http://172.xxx.xxx.xxx:8080/wbb/wbb.wsdl"; SoapPrimitive response = null; String xml=""; SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); PropertyInfo p1 =new PropertyInfo(); p1.name = "value1"; p1.setValue(params[0]); request.addProperty(p1); PropertyInfo p2 =new PropertyInfo(); p2.name = "value2"; p2.setValue(params[1]); request.addProperty(p2); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER12); // create header Element[] header = new Element[1]; header[0] = new Element().createElement("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd","Security"); Element usernametoken = new Element().createElement("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "UsernameToken"); usernametoken.setAttribute(null, "Id", "UsernameToken-1"); header[0].addChild(Node.ELEMENT,usernametoken); Element username = new Element().createElement(null, "n0:Username"); username.addChild(Node.IGNORABLE_WHITESPACE,"whatever2"); usernametoken.addChild(Node.ELEMENT,username); Element pass = new Element().createElement(null,"n0:Password"); pass.setAttribute(null, "Type", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText"); pass.addChild(Node.TEXT, "whatever3"); usernametoken.addChild(Node.ELEMENT, pass); Element nonce = new Element().createElement(null, "n0:Nonce"); nonce.setAttribute(null, "EncodingType","http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary"); nonce.addChild(Node.TEXT, "whatever3"); usernametoken.addChild(Node.ELEMENT, nonce); Element created = new Element().createElement(null, "n0:Created"); created.addChild(Node.TEXT, "whatever4"); usernametoken.addChild(Node.ELEMENT, created); // add header to envelope envelope.headerOut = header; Log.i("header", "" + envelope.headerOut.toString()); envelope.dotNet = false; envelope.bodyOut = request; envelope.setOutputSoapObject(request); //HttpTransportSE androidHttpTransport = new HttpTransportSE(URL); URL url = null; try { url = new URL(URL); } catch (MalformedURLException e1) { e1.printStackTrace(); } HttpTransportSE androidHttpTransport = null; String host = url.getHost(); int port = url.getPort(); String file = url.getPath(); Log.d("Exception d", "host -&gt; " + host); Log.d("Exception d", "port -&gt; " + port); Log.d("Exception d", "file -&gt; " + file); androidHttpTransport = new KeepAliveHttpsTransportSE(host, port, file, 25000); Log.i("bodyout", "" + envelope.bodyOut.toString()); try { androidHttpTransport.debug = true; androidHttpTransport.call(SOAP_ACTION, envelope); xml = androidHttpTransport.responseDump; response = (SoapPrimitive)envelope.getResponse(); Log.i("myApp", response.toString()); } catch (SoapFault e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); Log.d("Exception Generated", ""+e.getMessage()); } return response; } </code></pre> <p>Sorry for my bad english and for the mistakes! </p>70821502773	0	 <p>As others have said, you update properties of an immutable object by creating a new object with updated properties. But let me try to illustrate how this might work with some code.</p> <p>For simplicity, let's say you are modelling a particle system, where each particle moves accordingly to it's velocity.</p> <p>Your model comprises of a set of particles that are updated and then rendered to the screen each frame.</p> <p>In C#, your model implementation might look like this:</p> <pre><code>public class Model { public class Particle { public double X { get; set; } public double Y { get; set; } public double Vx { get; set; } public double Vy { get; set; } } public Model() { this.particles = /* ... initialize a set of particles ... */ } public void Update() { foreach (var p in this.particles) { p.X += p.Vx; p.Y += p.Vy; } } public void Render() { /* ... clear video buffer, init something, etc ... */ foreach (var p in this.particles) { this.RenderParticle(p); } } } </code></pre> <p>Pretty straightforward. As you can see, each frame we go over entire set of particles and update coordinates of each one according to it's velocity.</p> <p>Now, if the particle was immutable, there'd be no way to change it's properties, but as been said, we just create a new one with updated values. But hold on a second, doesn't that mean we'd have to replace the original particle object with an updated one in our set? Yes it does. And doesn't that mean that the <strong>set</strong> now has to be <strong>mutable</strong>? Looks like we just transfered the mutability from one place to another...</p> <p>Well, we could refactor to rebuild the entire set of particles each frame. But then, the property that stores the set would have to be mutable... Hmmm. Do you follow?</p> <p>It appears that at some point you'll have to lose immutability in order to cause effects, and depending on <em>where</em> that point is, your program will or will not have some (arguably) useful properties.</p> <p>In our case (we're making a video game), we technically can postpone the mutability all the way until we get to drawing on the screen. It's good that the screen is mutable, otherwise we'd have to create a new display each frame :)</p> <p>Now, let's see how this could be implemented in F#:</p> <pre><code>type Particle = { X : double Y : double Vx : double Vy : double } type Model = { Particles : Particle seq } module Game = let update model = let updateParticle p = { p with X = p.X + p.Vx; Y = p.Y + p.Vy } { model with Particles = seq { for p in model.Particles do yield updateParticle p } } let render model = for p in model.Particles do Graphics.drawParticle p </code></pre> <p>Note that in order to preserve immutability, we had to make the <code>Update</code> method a function that takes a model object and returns it updated. The <code>Render</code> now also takes the model object as an argument, as we don't keep it in memory anymore because it is immutable.</p> <p>Hope this helps!</p>70930605081	0	 <p>OK the answer to my 2 questions are: Yes and No.</p> <p>I <strong><em>was</em></strong> missing something and there is <strong><em>nothing</em></strong> wrong with my approach.</p> <p>What was worrying me was that the instantiate approach might be causing the problem as it isn't the method described in the documentation. It turns out that this was not the problem.</p> <p>What was the problem was lazy copying and pasting. When I copied the tracking code from the GA website I accidentally also copied the line below. When this was copied into the single line textbox for the variable in the inspector the tracking code showed as expected but there was a hidden line that was also part of the string variable that couldn't be seen.</p> <p>Slap me.</p> <p>Hopefully this lesson learned helps another careless idiot avoid the same or similar mistake.</p>71037710071	0	Could someone tell me why this code isn't working? <p>So I have been stuck with this for a long time now, unable to figure why it isn't working. This is a registration page which, after submitting information, should upload the information (the one I choose, not all the registration options enter the database) into a table (called tbl) inside the database (known as Database2.mdf). This is through Visual Studio 2010. There is also a java phase that checks the information but I don't think that is what is causing the problem so I'll just post the SQL code and the HTML code, along with the names of the table lines.</p> <p>The SQL bit:</p> <pre><code>&lt;%@ Page Language="C#" %&gt; &lt;%@ Import Namespace="System.Data.SqlClient" %&gt; &lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;script runat="server"&gt; protected void Page_Load(object sender, EventArgs e) { if (Request.Form["sub"] != null) { string fName = Request.Form["FName"]; string lName = Request.Form["LName"]; string uName = Request.Form["UName"]; string Street = Request.Form["Street"]; string City = Request.Form["City"]; string Pass = Request.Form["Password"]; string PassCon = Request.Form["PasswordConf"]; string Email = Request.Form["Email"]; string Comments = Request.Form["Comment"]; int ID = int.Parse(Request.Form["ID"]); string conStr = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database2.mdf;Integrated Security=True;User Instance=True"; string cmdStr = string.Format("INSERT INTO tbl (FirstName, LastName, UserName, Street, City, Password, PasswordConfirm, Email, Comments, IdentificationNumber) VALUES (N'{0}', N'{1}', N'{2}', N'{3}', N'{4}', N'{5}', N'{6}', N'{7}', N'{8}', {9})", fName, lName, uName, Street, City, Pass, PassCon, Email, Comments, ID); SqlConnection conObj = new SqlConnection(conStr); SqlCommand cmdObj = new SqlCommand(cmdStr, conObj); conObj.Open(); cmdObj.ExecuteNonQuery(); conObj.Close(); } } &lt;/script&gt; </code></pre> <p>The HTML bit: (CheckForm is the name of the Javassript action that checks if the form matches the requirements, also Registration.aspx is the registration page obviously, and it is not linked to a master page)</p> <pre><code>&lt;form action="Registration.aspx" method="post" name="ContactForm" onsubmit="return CheckForm()"&gt; First Name: &lt;input type="text" size="65" name="FName" /&gt; &lt;br /&gt; Last Name: &lt;input type="text" size="65" name="LName" /&gt; &lt;br /&gt; Username: &lt;input type="text" size="65" name="UName" /&gt; &lt;br /&gt; Street: &lt;input type="text" size="65" name="Street" /&gt; &lt;br /&gt; City: &lt;input type="text" size="65" name="City" /&gt; &lt;br /&gt; Password: &lt;input type="password" size="65" name="Password" /&gt; &lt;br /&gt; Password Confimration: &lt;input type="password" size="65" name="PasswordConf" /&gt; &lt;br /&gt; E-mail Address: &lt;input type="text" size="65" name="Email" /&gt; &lt;br /&gt; Comments: &lt;input type="text" size="100" name="Comment" /&gt; &lt;br /&gt; Identification Number: &lt;input type="password" size="65" name="ID" /&gt; &lt;br /&gt; Mobile : &lt;input type="text" id="mobile" name="mobile" style="width: 40px;" maxlength="3" /&gt; - &lt;input type="text" name="mobile1" maxlength="7" /&gt; &lt;br /&gt; Gender: Male&lt;input type="radio" name="gender" id="gender_Male" value="Male" checked /&gt; Female&lt;input type="radio" name="gender" id="gender_Female" value="Female" /&gt; &lt;br /&gt; Which countries would you like to recieve political news for?: &lt;br /&gt; &lt;input type='checkbox' name='files[]' id='1' value='1' /&gt; Israel &lt;input type='checkbox' name='files[]' id='2' value='2' /&gt; Russia &lt;input type='checkbox' name='files[]' id='3' value='3' /&gt; Canada &lt;br /&gt; How often do you read the newspaper? &lt;br /&gt; &lt;select id="cardtype" name="sel"&gt; &lt;option value=""&gt;&lt;/option&gt; &lt;option value="1"&gt;Never&lt;/option&gt; &lt;option value="2"&gt;Everyday&lt;/option&gt; &lt;option value="3"&gt;Once a week&lt;/option&gt; &lt;option value="4"&gt;Once a year&lt;/option&gt; &lt;/select&gt; &lt;br /&gt; What can we help you with? &lt;select type="text" value="" name="Subject"&gt; &lt;option&gt;&lt;/option&gt; &lt;option&gt;Customer Service&lt;/option&gt; &lt;option&gt;Question&lt;/option&gt; &lt;option&gt;Comment&lt;/option&gt; &lt;option&gt;Consultation&lt;/option&gt; &lt;option&gt;Other&lt;/option&gt; &lt;/select&gt; &lt;br /&gt; &lt;input type="submit" value="Send" name="submit" /&gt; &lt;input type="reset" value="Reset" name="reset" /&gt; &lt;/form&gt; </code></pre> <p>The table lines are as follows:</p> <ul> <li>FirstName - nvarchar(50)</li> <li>LastName - nvarchar(50)</li> <li>UserName - nvarchar(50)</li> <li>Street - nvarchar(50)</li> <li>City - nvarchar(50)</li> <li>Password - nvarchar(50)</li> <li>PasswordConfirm - nvarchar(50)</li> <li>Email - nvarchar(50)</li> <li>Comments - nvarchar(50) - Only one that allows nulls</li> <li>IdentificationNumber - int</li> </ul> <p>I know this is A LOT to sift through but I have been stuck with it for so long and I must get it fixed very quickly, I would VERY much appreciate any help provided! Thanks in advance!</p>71124779469	0	Implement rollback in Nested stored procedure <p>I am using TRY CATCH block to capture error and do rollback</p> <pre><code>ALTER PROCEDURE sp_first /* parameters */ BEGIN TRY BEGIN TRANSACTION /* statements */ COMMIT END TRY BEGIN CATCH IF(@@TRANCOUNT&gt;0) ROLLBACK END CATCH </code></pre> <p>Will the above approach work if there is another stored procedure <code>sp_inner</code> being called inside <code>sp_first</code> which also performs DML statements INSERT , DELETE , UPDATE etc.</p> <pre><code>ALTER PROCEDURE sp_first /* parameters */ BEGIN TRY BEGIN TRANSACTION /* statements of sp_first */ -- stored procedure sp_inner also requires rollback if error occurs. EXEC sp_inner @paramaterList COMMIT END TRY BEGIN CATCH IF(@@TRANCOUNT&gt;0) ROLLBACK END CATCH </code></pre> <p>How to implement roll back if nested stored procedure is used?</p>71235751448	0	Disabling"Synchronous XMLHttpRequest on the main thread is deprecated" <p>I'm using Chrome to debug a web page, and while debugging I get frequent warnings and stops with the message "Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check <a href="https://xhr.spec.whatwg.org/" rel="nofollow">https://xhr.spec.whatwg.org/</a>."</p> <p>I understand what is causing these, but they are in code over which I have no control. But their existence is making it hard to debug my code, as I have to click past twenty or so of these warnings to reach my code, and sometimes others are thrown during the execution of my code.</p> <p>My question is: <strong>How do I prevent the Chrome debugger from stopping on these warnings?</strong></p>71323276302	0	 <p>Assuming your adapter is based off some class, and this class has the methods to set and get the switch value, you should be able to do something like this in your adapter:</p> <pre><code>public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(R.layout.some_layout, null); } Switch switch_temp = (Switch) v.findViewById(R.id.item_pers_ajout_op_switch); switch_temp.setChecked(getItem(position).getTousCoches()); return convertView; } public void switchAll(boolean mySwitch) { for (int i=0; i&lt;getCount(); i++) { getItem(i).setTousCoches(mySwitch); } notifyDataSetChanged(); } </code></pre>7148174516	0	 <p>You should use strtod; it checks double overflow/underflow also like:</p> <pre><code>#include &lt;errno.h&gt; #include &lt;stdio.h&gt; #include &lt;math.h&gt; #include &lt;stdlib.h&gt; double d; char *e,s[100]; fgets(s,100,stdin); if( s[strlen(s)-1]=='\n' ) s[strlen(s)-1]=0; errno=0; d=strtod(s,&amp;e); if( *e || errno==EINVAL || errno==ERANGE ) puts("error"); else printf("d=%f\n",d); </code></pre>71522043342	0	 <p>Any decent JPA docs would tell you that a 1-N bidir relation needs <em>mappedBy</em> on the side with the collection. The error message is pretty clear too</p>71612870896	0	Google Analytics Traffic Sources issue with mobile traffic redirected to m. site <p>A big chunk of my traffic is mobile. My server identifies this traffic by regex on the user agent and redirects (301) from www.mydomain.com to m.mydomain.com</p> <p>My site has different sources I want to get insights on (ads, Facebook, referrer sites etc)</p> <p>In the traffic sources report in Google Analytics I see a big chunk of visits originate from mydomain.com. That chunk size is similar to my mobile traffic, though a little lower.</p> <p>Does it make sense that the traffic source issue is related to mobile?</p> <p>If so:</p> <ul> <li>Is there a way to overcome this and have Google Analytics report the true traffic origin?</li> </ul> <p>One option I saw was faking a Google campaign by having the server add fake parameters to the query. This way I can use Google Analytics advertising-related reports to track origin. </p> <p>I'm looking for something more straightforward if possible.</p> <p>Will HTTP 302 work better?</p> <ul> <li>Why would the traffic source chunk be smaller than the mobile chunk?</li> </ul>71722061093	0	 <p>I write one function which will convert date as per my requirement as given below </p> <pre><code>var getRequiredDate = function(date) { var monthList = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; var day = date.getDate(); var month = date.getMonth(); var year = date.getFullYear(); // Use standard date methods var newdate = monthList[month] + ' ' + day + ", " + year; Ti.API.info("Date :" + newdate); </code></pre> <p>};</p> <p>Hope this helps you.</p>71839908486	0	Django attachment and custom data in response <p>Could someone please let me know if I can add custom message in HTTP response along with a attachment in Django</p> <p>Here is my django response with file attachment. </p> <pre><code>data = key[0] response = HttpResponse(data, content_type='text/plain') response['Content-Disposition'] = 'filename=license.txt' </code></pre> <p>I also want to send additional data with response (not part of attachment) like employee id '2343'. Can it be done? Is it a good idea to add data to header ?</p> <p>thanks in advance!</p>71910669832	0	How to customize the full page of a listpicker? <blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="http://stackoverflow.com/questions/9738204/listpicker-fullmode-selected-item-color">ListPicker FullMode Selected Item Color</a> </p> </blockquote> <p>I've a long list of things loading from a listpicker, mostly "useless".</p> <p>Is there the possibility to add a button on top of the full page opened when I click the listpicker (so when I click on it I only show the most useful things?</p> <p>Thanks a lot!</p>72014098246	0	 <p>If you are hoping to do a random choice using strings you need to put them in an array and do Array shuffle.</p> <pre><code>shuffle($array_of_filenames); echo $array_of_filenames[0]; </code></pre> <p>More examples: <a href="http://php.net/manual/en/function.shuffle.php" rel="nofollow">http://php.net/manual/en/function.shuffle.php</a></p>72138301548	0	 <p>I think you did not connect the label with xib or storyboard properly.Kindly again connect the label with xib or storyboard correctly with the following screenshots and coding. </p> <p><strong>FIRST : I drag and drop the Label from the Object Library</strong> <a href="https://i.stack.imgur.com/3xc3D.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3xc3D.png" alt="I drag and drop the Label from the Object Library"></a></p> <p><strong>SECOND : CLICK control + mouse on label and drag that label to ViewController.h</strong> <a href="https://i.stack.imgur.com/bOWaN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bOWaN.png" alt="enter image description here"></a></p> <p><strong>THIRD : Now BOX shows with default cursor in Name field</strong> <a href="https://i.stack.imgur.com/Xo3MB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Xo3MB.png" alt="enter image description here"></a></p> <p><strong>FOUR : Finally give the Label Name in Name Field of BOX</strong> <a href="https://i.stack.imgur.com/U0hmV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/U0hmV.png" alt="enter image description here"></a></p> <p>Once I did that Now the View Controller.h</p> <pre><code>#import &lt;UIKit/UIKit.h&gt; @interface ViewController : UIViewController @property (strong, nonatomic) IBOutlet UILabel *labelStringText; @end </code></pre> <p>Then in ViewController.m</p> <pre><code>#import "ViewController.h" @interface ViewController () @end @implementation ViewController @synthesize labelStringText; - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. labelStringText.text = @""; NSString *strLabelText = [NSString stringWithFormat:@"%@",labelStringText.text]; //OR NSString *strLabelText = labelStringText.text; } </code></pre> <p>for your simple understanding I set the label.text to string in viewDidLoad.You just set the string where you want.</p>72240689117	0	 <p>Seems you set inappropriate maximum nested level in style checks which provided by compiler switch "-gnatyL" and then set up the compiler to treat all warnings and style checks as errors by "-gnatwe" switch.</p>7232473340	0	 <p>Why are you making this generic? Just overload the method.</p> <pre><code> void bar(A a) { a.Foo(); } void bar(B b) { b.Foo(); } </code></pre> <p>Generics are there so that you can make potentially infinite <code>bar()</code> methods.</p>72440157074	0	Multiple docker images run from docker file <p>I am trying to execute multiple docker images run from single docker file with different ports. Please advise How to execute multiple "docker run" commands from single docker file with different ports.</p>72514085145	0	 <p>Tobias Ternstrom at Microsoft has a workaround that works for sql server2005 and higher: Consider the following example using the AdventureWorks microsoft sample database:</p> <pre><code> SELECT soh.OrderDate ,( SELECT p.Name + ', ' FROM Production.Product AS p INNER JOIN Sales.SalesOrderDetail AS sod ON p.ProductID = sod.ProductID WHERE sod.SalesOrderID = soh.SalesOrderID FOR XML PATH(''), TYPE ).value('/', 'NVARCHAR(max)') AS ProductsOrdered FROM Sales.SalesOrderHeader AS soh </code></pre> <p>See where they discuss the same problem here: <a href="https://connect.microsoft.com/SQLServer/feedback/details/389883/string-aggregate-function-something-like-sum-for-numbers" rel="nofollow">string aggregate function, something like SUM for numbers</a></p>72617070179	0	Deleting a file in Java <p>I want to delete a file, and sometimes I can, sometimes I don't. I'm doing this:</p> <pre><code>String filePath = "C:\\Users\\User\\Desktop\\temp.xml"; File f = new File(filePath); if (f.exists()) { if(f.delete()) System.out.println("deleted"); else System.out.println("not deleted"); } </code></pre> <p>I think that when I can't delete it is because it is still open somewhere in the Application. But how can I can I close it, if I don't use the <code>FileInputStream</code> or the <code>BufferedReader</code>? Because if I use those classes, I can't see if the file exists. Or can I?</p> <p><strong>Edit:</strong> I just found my error. I was doing this:</p> <pre><code>XMLEventWriter eventWriter = outputFactory.createXMLEventWriter(new FileOutputStream(filePath)); </code></pre> <p>and then, closing just the <code>eventWriter</code> .</p> <p>And I have to do this:</p> <pre><code>FileOutputStream fos = new FileOutputStream(filePath); XMLEventWriter eventWriter = outputFactory.createXMLEventWriter(fos); </code></pre> <p>and then:</p> <pre><code> eventWriter.close(); fos.close(); </code></pre>72710876559	0	 <pre><code>char * bytes = [SomeData bytes]; </code></pre>72814547761	0	 <p>Your code looks correct. The most likely problem is that it's being built incorrectly, but to address this we need to see your Makefile.</p> <p>At the link below (wouldn't let me post the link so you have to copy/paste it yourself) is a post by someone who had a very similar problem to yours. It turned out that he was not running his compiled object file through the linker, with the result that some essential library was missing which caused the PIC to loop endlessly, trying to execute an invalid opcode (instruction).</p> <p>efreedom dot com/Question/E-27081/Using-Avr-Gcc-Delay-Ms-Causes-Chip-Freeze</p> <p>If this doesn't fix it, try posting your Makefile.</p> <p>Also, there is no reason to call _delay_ms(10) 100 times, you can just call _delay_ms(1000) directly. It will use a lower resolution.</p> <p><strong>Edit:</strong> After seeing your Makefile it looks like your clock speed might be set incorrectly. The CLOCK setting specifies what speed you are running your AVR at, if it's set to something way off (like 8MHz and your PIC is running at 1MHz), the delay loop will take 8 seconds when you expect it to take one - if that's the problem your LED's will appear frozen but if you wait long enough they will actually change. Try removing the -DF_CPU=$(CLOCK) statement and see if it makes a difference.</p> <p>Apart from that your Makefile has a lot of unused/unnecessary stuff, and since I don't have a working avr-gcc setup at the moment, it's hard to follow, so it will help if you try simplifying the Makefile like the following, and see if it works - it will be close, please comment below if you get any problems!</p> <pre><code>DEVICE = attiny2313 CLOCK = 8000000 OBJECTS = main.o # Tune the lines below only if you know what you are doing: AVRDUDE = avrdude $(PROGRAMMER) -p $(DEVICE) COMPILE = avr-gcc -Wall -Os -DF_CPU=$(CLOCK) -mmcu=$(DEVICE) # symbolic targets: all: main.hex flash: all $(AVRDUDE) -U flash:w:main.hex:i clean: rm -f main.hex main.elf $(OBJECTS) main.elf: $(OBJECTS) $(COMPILE) -o main.elf $(OBJECTS) main.hex: main.elf rm -f main.hex avr-objcopy -j .text -j .data -O ihex main.elf main.hex avr-size --format=avr --mcu=$(DEVICE) main.elf </code></pre>72923849929	0	how to make uitextview scroll in iOS Storyboards <p>I have a uitextview with more text that can fit in the view. I enabled "scrolling enabled" on the textview, however the scrollview does not scroll.</p> <p>Here is how I populate the textview in <code>viewDidLoad</code>:</p> <pre><code> PFQuery *query = [MyObject query]; [query whereKey:@"cycleNumber" equalTo:_cycleNumber]; [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) { if([objects count] &gt; 0){ NSString *description = objects[0]; _lessonDescriptionTextView.text = description; } }]; </code></pre> <p>How can I make the textview scroll to show all content?</p>73027820074	0	 <p>If you change</p> <pre><code>&lt;xsl:template match="order"&gt; &lt;order job_id="{job_id}" site_code="{site_code}" replace="{replace}"&gt; &lt;xsl:apply-templates/&gt; &lt;/order&gt; &lt;/xsl:template&gt; </code></pre> <p>to</p> <pre><code>&lt;xsl:template match="order"&gt; &lt;order job_id="{job_id}" site_code="{site_code}" replace="{replace}"&gt; &lt;xsl:apply-templates select="node()[not(self::job_id|self::site_code|self::replace)"/&gt; &lt;xsl:copy-of select="following-sibling::master_version[1]"/&gt; &lt;/order&gt; &lt;/xsl:template&gt; </code></pre> <p>and then add <code>&lt;xsl:template match="master_version"/&gt;</code> you get the nesting, assuming it should be done for the following sibling <code>master_version</code> element and not based on some reference value.</p>73127181986	0	 <pre><code>void *multiply() </code></pre> <p>The values of struct variables <code>a</code> and <code>b</code> are not initialized within this function you should be passing the scanned values in <code>main()</code> to this function as well as <code>divide()</code></p> <p>There is no reason here I see why you are returning <code>void *</code>. Pass parameters by reference or by value.</p>73210358488	0	 <p>Template value must be compile-time constant, that is literal, <code>constexpr</code> or <code>static const</code> variable.</p>73326536604	0	Loading state for ApplicationRoute <p>Using: ember 1.7.0</p> <p>I have some server-side data that I want to load up in my ember app before any routes are transitioned to. Multiple (but not all) of my other routes / controllers need this data. I was thinking that I could just load up this data in the ApplicationRoute <code>model</code> method. It works fine, but does not display a loading state.</p> <p>Is it possible to have the ApplicationRoute display a loading state until it's <code>model</code> promise gets resolved.</p> <p>Here's a jsbin illustrating the problem: <a href="http://jsbin.com/soqivo/1/" rel="nofollow">http://jsbin.com/soqivo/1/</a></p> <p>Thanks for the help!</p>7347237488	0	 <p>Value property of NumericUpDown is Decimal - that is perhaps why you are having issues. In your if block, I would consider casting the Value Property of NumericUpDown object into an integer in the true part and use integer value 3 in its else part. There after, I would avoid parsing again and give it to Substring as is.</p>73517839560	0	 <p><strong>To answer your question directly:</strong></p> <p>Configuration > Content Authoring > Configure (the format) </p> <p>At the bottom under "Filter settings" there should be a list of allowable HTML tags. Just add in </p> <p><strong>For a better solution:</strong></p> <p>Create an image field and display that above the text. The advantage is that Drupal will handle the uploading and storing of the image.</p> <p>or install the following modules.</p> <ul> <li><a href="http://drupal.org/project/wysiwyg" rel="nofollow">http://drupal.org/project/wysiwyg</a></li> <li><a href="http://drupal.org/project/media" rel="nofollow">http://drupal.org/project/media</a></li> </ul>73623868607	0	 <p>Please see this example that I made for you: <a href="http://jsfiddle.net/972ak/" rel="nofollow">http://jsfiddle.net/972ak/</a></p> <pre><code>$('form .close').click(function(event) { Boxy.confirm("Are you sure ?", function() { alert('ok'); }); return false; }); </code></pre> <p>Boxy documentation says:</p> <p>Boxy.confirm(message, callback, options) Displays a modal, non-closeable dialog displaying a message with OK and Cancel buttons. Callback will only be fired if user selects OK.</p> <p><a href="http://onehackoranother.com/projects/jquery/boxy/" rel="nofollow">http://onehackoranother.com/projects/jquery/boxy/</a></p>73737124233	0	 <p>In your <code>__init__</code> method and in some other places you refer to <code>self.__speed</code>. However, in your <code>accelerate</code> and <code>brake</code> methods you refer to <code>self.speed</code>, which is not the same thing. Make all the references the same and your problem should be resolved.</p>73832004919	1	time.gmtime() causes OverflowError on armhf platform <p>I have a webserver (CherryPy) running with on a Cubox (armhf platform) and upon starting the wever i get the following error:</p> <pre><code>[14/Aug/2015:09:33:40] HTTP Traceback (most recent call last): File "(...)/lib/python3.4/site-packages/cherrypy/_cprequest.py", line 661, in respond self.hooks.run('before_request_body') File "(...)/lib/python3.4/site-packages/cherrypy/_cprequest.py", line 114, in run raise exc File "(...)/lib/python3.4/site-packages/cherrypy/_cprequest.py", line 104, in run hook() File "(...)/lib/python3.4/site-packages/cherrypy/_cprequest.py", line 63, in __call__ return self.callback(**self.kwargs) File "(...)/lib/python3.4/site-packages/cherrypy/lib/sessions.py", line 901, in init httponly=httponly) File "(...)/lib/python3.4/site-packages/cherrypy/lib/sessions.py", line 951, in set_response_cookie cookie[name]['expires'] = httputil.HTTPDate(e) File "(...)/lib/python3.4/site-packages/cherrypy/_cpcompat.py", line 278, in HTTPDate return formatdate(timeval, usegmt=True) File "/usr/lib/python3.4/email/utils.py", line 177, in formatdate now = time.gmtime(timeval) OverflowError: timestamp out of range for platform time_t </code></pre> <p>I'm not sure whether I understand the problem correctly and I am not sure if it can be fixed by me. As far as I can tell by the Traceback it is caused by CherryPy. This error causes a <code>500 Internal Server Error</code> and won't load the page.</p> <p>As asked in the comments I inserted a print. I don't see any thing special. This is the output of starting the server and once trying to load the page:</p> <pre><code>1439551125.1483066 1439551132.639804 4593151132.6458025 1439551132.723468 1439551132.7210276 1439551132.7268708 1439551132.7359934 1439551132.741787 1439551132.7452564 4593151132.750907 4593151132.762612 4593151132.749376 4593151132.731232 4593151132.754474 4593151132.763546 1439551132.8183882 4593151132.828029 1439551132.8379567 4593151132.856025 1439551132.8734775 1439551132.8554301 1439551132.879614 4593151132.884698 4593151132.890394 1439551132.8971672 4593151132.902081 4593151132.908171 1439551132.931757 4593151132.944052 1439551132.9759347 1439551132.9714596 4593151132.987068 4593151132.985899 1439551132.9926524 1439551133.0088623 4593151133.013047 1439551133.0280995 4593151133.040709 4593151133.029601 1439551133.0500746 4593151133.057341 1439551133.0749385 4593151133.081711 1439551133.1032782 4593151133.115171 1439551133.1194305 1439551133.1354048 4593151133.143136 4593151133.151044 1439551133.1612003 4593151133.16934 1439551133.1827784 4593151133.19687 1439551133.201899 4593151133.209947 1439551133.271833 4593151133.277573 1439551133.3090906 4593151133.312978 1439551133.3408027 4593151133.344741 1439551133.3722978 4593151133.376283 1439551133.4031894 4593151133.407124 1439551133.434834 4593151133.439074 </code></pre> <p>I am not sure which of these values causes the error. I am guessing it's the one with 4 in front? On a windows machine <code>time.gmtime(4593151133.439074)</code> returns a struct which contains the year 2115.</p> <p>On the Cubox when starting a python shell and entering <code>time.gmtime(4593151133.439074)</code> I can reproduce the error. But I don't know where these values come from. </p> <p><strong>EDIT</strong></p> <p>I have found the file and line in CherryPy that returns me the floating numbers which lead to the year 2115. It is line 949 - 951 in the file session.py: </p> <pre><code>if timeout: e = time.time() + (timeout * 60) cookie[name]['expires'] = httputil.HTTPDate(e) </code></pre> <p>Why I get such a high timeout, I don't know.</p>73928701232	0	 <p>In order to query based on two separate Parse classes, where one part of the query is a pointer to another class, the best way to do so is to have an outer query on the class which contains the pointer, and then an inner query that finds whatever supplementary objects you're looking for. In my case, this meant finding businesses that were in the user's location, and then only showing Business Posts near the user's location, where in the "BusinessPost" class, the key "Business" is a pointer to my "Business" class, that contains other information about the business that the UI needed. The query would look as follows: </p> <pre><code>override func queryForTable() -&gt; PFQuery! { var getPosts = PFQuery(className: self.parseClassName) var getBusinesses = PFQuery(className: "Businesses") if locationUpdated == false { return nil } else { getBusinesses.whereKey("City", equalTo: self.city) getBusinesses.whereKey("State", equalTo: self.state) getPosts.whereKey("Business", matchesQuery: getBusinesses) getPosts.includeKey("Business") self.tableView.hidden = false self.tableView.reloadData() return getPosts } </code></pre> <p>Hope this can help others that are looking to accomplish a similar query with Parse and Swift. </p>74024622604	0	 <pre><code>$('td:first-child').after('&amp;lt;td&amp;gt;new cell&amp;lt;/td&amp;gt;'); </code></pre>7419245224	0	 <p>What you are looking for is a <a href="http://stackoverflow.com/questions/211383/which-method-of-clearfix-is-best">clearfix</a> so that your elements will load properly. See <a href="http://stackoverflow.com/questions/211383/which-method-of-clearfix-is-best">the linked SO question "Which method of 'clearfix' is best?"</a> for numerous possible clearfixes.</p> <p>The reason why the <code>footer</code> element places itself next to the <code>main</code> element is because absolutely-positioned elements are removed from the page flow. As a result, later elements treat the absolutely-positioned element as if it was not there in the first place. With a clearfix, this issue is resolved.</p>74223806149	0	Installing Java Cryptography Extension in Debian <p>I need to install the JCE in my Wheezy machine.</p> <p>According to the documentation, I should replace the files local_policy.jar and US_export_policy.jar in $java_home/lib/security. However, my system doesn't have these files, and just copying JCE's files there don't work, as my code is failing and looking for the error it seems to be due to the lack of JCE. </p> <pre><code> [java] GSSException: Failure unspecified at GSS-API level (Mechanism level: Checksum failed) [java] at sun.security.jgss.krb5.Krb5Context.acceptSecContext(Krb5Context.java:788) [java] at sun.security.jgss.GSSContextImpl.acceptSecContext(GSSContextImpl.java:342) [java] at sun.security.jgss.GSSContextImpl.acceptSecContext(GSSContextImpl.java:285) [java] at mistic.id.krbAction.run(krbAction.java:44) [java] at mistic.id.krbAction.run(krbAction.java:1) [java] at java.security.AccessController.doPrivileged(Native Method) [java] at javax.security.auth.Subject.doAs(Subject.java:356) [java] at mistic.id.Server.acceptSecurityContext(Server.java:119) [java] at mistic.id.Server.main(Server.java:70) [java] Caused by: KrbException: Checksum failed [java] at sun.security.krb5.internal.crypto.Aes256CtsHmacSha1EType.decrypt(Aes256CtsHmacSha1EType.java:102) [java] at sun.security.krb5.internal.crypto.Aes256CtsHmacSha1EType.decrypt(Aes256CtsHmacSha1EType.java:94) [java] at sun.security.krb5.EncryptedData.decrypt(EncryptedData.java:177) [java] at sun.security.krb5.KrbApReq.authenticate(KrbApReq.java:278) [java] at sun.security.krb5.KrbApReq.&lt;init&gt;(KrbApReq.java:144) [java] at sun.security.jgss.krb5.InitSecContextToken.&lt;init&gt;(InitSecContextToken.java:108) [java] at sun.security.jgss.krb5.Krb5Context.acceptSecContext(Krb5Context.java:771) [java] ... 8 more [java] Caused by: java.security.GeneralSecurityException: Checksum failed [java] at sun.security.krb5.internal.crypto.dk.AesDkCrypto.decryptCTS(AesDkCrypto.java:451) [java] at sun.security.krb5.internal.crypto.dk.AesDkCrypto.decrypt(AesDkCrypto.java:272) [java] at sun.security.krb5.internal.crypto.Aes256.decrypt(Aes256.java:76) [java] at sun.security.krb5.internal.crypto.Aes256CtsHmacSha1EType.decrypt(Aes256CtsHmacSha1EType.java:100) [java] ... 14 more </code></pre> <p>So, how could I successfully install JCE in Debian?</p>74337040467	1	Ignoring zero division error <p>I'm writing a program that reads integer values from an input file, divides the numbers, then writes percentages to an output file. Some of the values that my program may be zero, and bring up a 0/0 or 4/0 occasion. </p> <p>From here, I get a Zerodivisionerror, is there a way to ignore this error so that it simply prints 0%??</p> <p>Thanks. </p>74420989083	0	 <p><code>atomically $ readTVar checking</code> does what you want. The GHCi REPL automatically executes any IO action that you give it.</p>74536179369	0	Detail page of split app without model <p>In my split app the detail view does not bind any model.</p> <p>In the <code>component.js</code> I instantiate a named model like this:</p> <pre><code>// creation and setup of the oData model var oConfig = { metadataUrlParams: {}, json: true, defaultBindingMode : "TwoWay", defaultCountMode : "Inline", useBatch : false } // ### tab-employee ### var oModelEmpl = new sap.ui.model.odata.v2.ODataModel("/sap/opu/odata/sap/EMP_SRV"), oConfig); oModelEmpl.attachMetadataFailed(function() { this.getEventBus().publish("Component", "MetadataFailedEMPL"); }, this); this.setModel(oModelEmpl, "EMPL"); </code></pre> <p>The method <code>onSelect</code> in der master-view controller is fired by clicking on an listitem.</p> <pre><code>onSelect: function(oEvent) { this.showDetail(oEvent.getParameter("listItem") || oEvent.getSource()); } </code></pre> <p>This will call the method <code>showDetail</code></p> <pre><code>showDetail: function(oItem) { var bReplace = jQuery.device.is.phone ? false : true; this.getRouter().navTo("detail", { from: "master", entity: oItem.getBindingContext('EMPL').getPath().substr(1), }, bReplace); }, </code></pre> <p>In the controller of the detail-view I've these two methods for updating the binding. <code>onRouteMatched</code> calls <code>bindView</code>, where I get the error-message <code>TypeError: oView.getModel(...) is undefined</code>. </p> <pre><code>onRouteMatched: function(oEvent) { var oParameters = oEvent.getParameters(); jQuery.when(this.oInitialLoadFinishedDeferred).then(jQuery.proxy(function() { var oView = this.getView(); if (oParameters.name !== "detail") { return; } var sEntityPath = "/" + oParameters.arguments.entity; this.bindView(sEntityPath); }, this)); }, bindView: function(sEntityPath) { var oView = this.getView(); oView.bindElement(sEntityPath); //Check if the data is already on the client if (!oView.getModel().getData(sEntityPath)) { // Check that the entity specified was found. oView.getElementBinding().attachEventOnce("dataReceived", jQuery.proxy(function() { var oData = oView.getModel().getData(sEntityPath); if (!oData) { this.showEmptyView(); this.fireDetailNotFound(); } else { this.fireDetailChanged(sEntityPath); } }, this)); } else { this.fireDetailChanged(sEntityPath); } }, </code></pre> <p>I've tried to implement this split app relative to the template generated by WebIDE. Any idea what is missing?</p>746178891	0	 <p>I would avoid using the !important clause and instead just ensure their values appear in a <code>&lt;style&gt;</code> tag following the import of the regular style sheets.</p> <p>Otherwise, I would do it the same way.</p>74712311391	0	 <p>set height as <code>fill_parent</code>, the width as <code>wrap_content</code> </p> <p>and you fix the aspect ratio with <code>android:adjustViewBounds="true"</code></p>74828824855	0	 <p><code>containerView</code> and <code>show button</code> are in different viewControllers. So you can't just hide it. The simple way to achieve it is when you select the cell in <code>containerView</code>, present the <code>ParentViewController</code>, and the view in <code>ContainerViewController</code> will dismiss automatically. </p> <pre><code>- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { [self.delegate ContainerViewBLETable:self andSelectedDone:[NSString stringWithFormat:@"%ld",indexPath.row]]; ParentViewController *vc = [[self storyboard] instantiateViewControllerWithIdentifier:@"ParentViewController"]; [self presentViewController:vc animated:YES completion:nil]; } </code></pre> <p>To show the container, you can just dismiss the <code>ParentViewController</code> that presenting. 1. </p> <pre><code>- (IBAction)btnAction:(id)sender { [self.presentingViewController dismissModalViewControllerAnimated:YES]; } </code></pre> <p>Or 2. Set up segue to dismiss viewController and use prepareForSegue for delegate to communicate with other viewController.</p> <p>Also <strong>REMOVE</strong> <code>vc.view.hidden = YES</code> in delegate you had implemented</p> <pre><code> -(void) ContainerViewBLETable:(ContainerViewBLETable *)vc andSelectedDone:(NSString *)selectedStr. </code></pre>74924762104	0	Prevent recursive function locking the browser <p>I have a recursive function which is locking my browser while running.</p> <p>While this function is running all my jquery commands are locked waiting for the function end.</p> <p>What should I do to make this function asynchronous? </p> <p>This function runs on document.ready</p> <pre><code>function SearchTrip() { $.post("/extensions/searchtrip", { from: $("#from").val(), to: $("#to").val(), ddate: $("#ddate").val() }, function (mReturn) { if (mReturn.fTotalAmount != '0,00') { var sAirline = ''; if (mReturn.Airline) sAirline = ' pela ' + mReturn.Airline; $("#buscandoPassagens").hide(); } else if (SearchTripAmount &lt; 5) { SearchTripAmount++; setTimeout(function () { SearchTrip(); }, 500); } else { $("#pNaoEncontrada").show(); } }, "json"); } </code></pre>7507788299	0	 <p>I agree with the other commenters that this question needs more information about the initial conditions of your problem before it can be properly answered. However, a scenario that causes your code to fail comes to mind immediately.</p> <p>Suppose that plist is a circularly linked list with three elements: A &lt;-> B &lt;-> C &lt;-> A, and plist points to A.</p> <p>When your code runs, it will: deallocate A, advance to B, deallocate B, advance to C, deallocate C and then advance to the <em>freed</em> memory that was A. Now your code blows up. (or runs forever)</p> <p>Since it is a doubly linked list, you should use your previous links to null out your next links before deallocating. And for good measure, null out your prev links as well.</p> <pre><code>temp_nlist = n_list-&gt;next; temp_nlist-&gt;prev = NULL; if (n_list-&gt;prev != NULL) n_list-&gt;prev-&gt;next = NULL; free(n_list); n_list = temp_nlist; </code></pre>75115538241	0	combining cells in table <p>how do i embed a youtube video to a table. i want the left and right columns to be 2 rows high and the middle column to have 2 cells, i want the video in the bottom cell, and the text in the top but i cant figure out how to move it there</p> <pre><code>&lt;div class="cbody"&gt; &lt;table class="ctable"&gt; &lt;tr&gt; &lt;td rowspan="2" style="width:105px"&gt;&lt;img class="cimg1" src="meh.png" alt=" " width="100px" height="500px"&gt;&lt;/td&gt; &lt;td&gt;&lt;p class="ctxt"&gt; my text here &lt;/p&gt;&lt;/td&gt; &lt;td rowspan="2" style="width:105px"&gt;&lt;img class="cimg2" src="meh.png" alt=" " width="100px" height="500px"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;iframe width="420" height="315" src="http://www.youtube.com/embed/xI_6oLPC-S0" frameborder="0" allowfullscreen&gt;&lt;/iframe&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/div&gt; </code></pre> <p>and the css...</p> <pre><code>.cbody { width:800px; margin-left: auto; margin-right: auto; border-style:solid; border-width:3px; } .cimg1 { padding-left:5px; padding-top:5px; padding-bottom:5px; float:left; } .cimg2 { padding-left:5px; padding-top:5px; padding-bottom:5px; float:right; } .ctxt { margin-left:5px; margin-right:5px; text-align:center; } .ctable { width:800px; margin-left:auto; margin-right: auto; border-style:solid; border-width:2px; } </code></pre>75219477217	0	Calling a Java method using javascript from within a JPanel <p>I have a Java application which displays results on a JPanel. The results are displayed using HTML by using a JLabel. </p> <p>Now I want to let the user interact with the local application by allowing local methods to be called when the user clicks on a link in that HTML document.</p> <p>Is this possible?</p>7531551407	0	How to represent AppDomain in ASP.NET? <p>Recently i attentened an interview.I have been asked to explain the "Application Domain" and the special purpose about the introduction of "application domain".</p> <p><strong>I explained :</strong></p> <p>AppDomain is a runtime representation of a logical process withing a physical process (win32) managed by CLR.</p> <p><strong>Special purpose :</strong></p> <p>Keeps high level application isolation ;fall down of one AppDomain never interrupt othe AppDomain.</p> <p>But still the interviewer expects lots from me ? what are the additional points could i add further?</p> <p>Thanks.</p>75440659955	0	 <p>What happened to?:</p> <pre><code>public interface AsyncResponse&lt;T&gt; { void processFinish(T output); } </code></pre> <p>Even if it's not overloading, it seems simple In my eyes.</p>75514040996	0	 <p>No. Theres a similar question here: <a href="http://stackoverflow.com/questions/136278/why-should-you-remove-unnecessary-c-sharp-using-directives">Why should you remove unnecessary C# using directives?</a></p> <p>Check it out, it's very well answered.</p>75613975467	0	 <p>Change your code as:</p> <pre><code>String strcategory = getIntent().getExtras().getString("categoriaId"); </code></pre> <p>because you are passing <code>String</code> from onListItemClick to sondaggioActivity Activity and trying to receive as <code>Int</code></p> <p><strong>NOTE :</strong> </p> <p>Second and important point is <code>id</code> is <code>long</code> and you are trying to parsing it to <code>Int</code> which is also not valid . see this post: <a href="http://stackoverflow.com/questions/4355303/how-can-i-convert-a-long-to-int-in-java">How can I convert a long to int in Java?</a></p> <p>Solution is just send id as long from <code>onListItemClick</code> as</p> <pre><code> myIntent.putExtra("categoriaId",id); </code></pre> <p>and receive it as in <code>sondaggioActivity</code> Activity :</p> <pre><code>long category = getIntent().getExtras().getLong("categoriaId"); </code></pre>75716050081	0	PostgresSQL combining tables <p>I am a little confused about merging one table into another. My two tables looks like so:</p> <pre><code>Table A Table B id | name | likes | email | username id | name | email | username 1 | joe | 3 | null | null 1 | ben | a@co.co | user Result: Table A id | name | likes | email | username 1 | joe | 3 | null | null 2 | ben | null | a@co.co | user </code></pre> <p>My issue is that I do not want to overwrite the properties that are in the Table A. Is this a simple <code>UNION</code>?</p>75840861784	0	 <p>Slight modification to @maxim-lanin's answer. You can use it like this, fluently.</p> <pre><code>\Mail::send('email.view', ['user' =&gt; $user], function ($message) use ($user) { $message-&gt;to($user-&gt;email, $user-&gt;name) -&gt;subject('your message') -&gt;getSwiftMessage() -&gt;getHeaders() -&gt;addTextHeader('x-mailgun-native-send', 'true'); }); </code></pre>7596915150	0	Error when using getter/setter methods on Sprite <p>I'm trying to make a class that extends the Sprite, have some private properties attached to it and be able to read and write those properties using getters and setters. Simple... but the compiler throw this error "Access of possibly undefined property speed through a reference with static type flash.display:Sprite." It works if I set my class to extend the MovieClip object. Could someone explain me the logic behind this? why I can't use getter and setters with a Sprite?</p> <p>Here is a sample code:</p> <pre><code>package { import flash.display.Sprite; public class Vehicle extends Sprite{ private var _speed:uint = 3; public function get speed():uint { return _speed; } public function set speed(value:uint):void { _speed = value; } public function Vehicle() { super(); } } } </code></pre>76034697812	0	 <p>With Automatic Uploads checked ON, it is uploading files automatically even before I'm done making all changes to the PHP files and before I even click SAVE button and resulting in INCOMPLETE script files. It is also uploading files in other tab pages. Looks like there is no precise control on uploads in PhpStorm.</p>76139116778	0	how to convert S3ObjectInputStream to PushbackInputStream <p>I am uploading an excel(xls) file to s3 and then another application should download that file from s3 and parse using Apache POI reader. The reader accepts <code>inputstream</code> type as the input but for proper parsing of the excel it expects <code>PushbackInputStream</code>. The inputstream i get from the file downloaded from s3 is of type <code>S3ObjectInputStream</code>. How do i convert <code>S3ObjectInputStream</code> to <code>PushbackInputStream</code>?</p> <p>I tried directly passing the <code>S3ObjectInputStream</code> (since this is an <code>inputStream</code>) to <code>PushbackInputStream</code>, but it resulted in the following exception :</p> <pre><code>org.springframework.batch.item.ItemStreamException: Failed to initialize the reader at org.springframework.batch.item.support.AbstractItemCountingItemStreamItemReader.open(AbstractItemCountingItemStreamItemReader.java:147) at org.springframework.batch.item.support.CompositeItemStream.open(CompositeItemStream.java:96) ..... ..... Caused by: java.lang.IllegalStateException: InputStream MUST either support mark/reset, or be wrapped as a PushbackInputStream at org.springframework.batch.item.excel.poi.PoiItemReader.openExcelFile(PoiItemReader.java:82) ..... </code></pre> <p>I tried casting S3ObjectInputStream to PushbackInputStream, but it resulted in classcastexception.</p> <pre><code>java.lang.ClassCastException: com.amazonaws.services.s3.model.S3ObjectInputStream cannot be cast to java.io.PushbackInputStream </code></pre> <p>Anyone knows the solution for this</p>76240348524	0	 <h1>Repeat 10 times:</h1> <ol> <li>I will never use a symlink to solve a missing library problem due to a different soname</li> <li>I will never use a symlink to solve a missing library problem due to a different soname</li> <li>I will never use a symlink to solve a missing library problem due to a different soname</li> <li>I will never use a symlink to solve a missing library problem due to a different soname</li> <li>I will never use a symlink to solve a missing library problem due to a different soname</li> <li>I will never use a symlink to solve a missing library problem due to a different soname</li> <li>I will never use a symlink to solve a missing library problem due to a different soname</li> <li>I will never use a symlink to solve a missing library problem due to a different soname</li> <li>I will never use a symlink to solve a missing library problem due to a different soname</li> <li>I will never use a symlink to solve a missing library problem due to a different soname</li> </ol> <p><strong>Never <em>ever</em> solve that kind of problems via symlinking</strong>. If your system does not provide the exact soname required by a library or an executable, you'll need to recompile that library or executable. There is a reason why libraries have the soname version number in their file names, and a mismatching soname will result in a <code>not found</code> for the dynamic linker/loader. You're just breaking that process <em>and your entire system</em> by inserting a broken soname for a library.</p> <h1>So, <strong>first thing to do: get rid of the symlink you introduced.</strong> Go in <code>/usr/lib/x86_64-linux-gnu/</code> and remove it. Do it <strong>now</strong>.</h1> <hr> <p><strong>Then, how to recompile the plugin so that it works on Ubuntu?</strong></p> <p>(Or, actually, anywhere. Even Windows or Mac. Just adapt the instructions)</p> <p>Step by step:</p> <ol> <li>Install the mysql development packages. On Ubuntu it should be the <code>libmysqlclient-dev</code> package, but double check in case the name changed on your particular Ubuntu edition. Go on <a href="https://packages.ubuntu.com" rel="nofollow">https://packages.ubuntu.com</a> and use the file-based search to look for <code>mysql.h</code>.</li> <li>Run the maintanance tool from the installer, and ask it to also install the Qt source components. You'll find the tool in your Qt installation directory.</li> <li>Go under <code>INSTALL_DIR/Src/5.7/qtbase/src/plugins/sqldrivers/mysql</code> (adjust <code>INSTALL_DIR</code> and <code>5.7</code> to your actual case).</li> <li>Run <strong>the right</strong> <code>qmake</code>. The right one is the one coming from the same installation of Qt, and whose version matches the sources. In your case it's likely to be in <code>INSTALL_DIR/5.7/gcc_64/bin/qmake</code>.</li> <li>Run <code>make</code>. If it fails to compile due to some library not found, install the required packages on your system. The Ubuntu package search linked above may be useful.</li> <li>Once <code>make</code> runs successfully, it will create a brand new <code>libqsqlmysql.so</code>. It should automatically overwrite the one in <code>INSTALL_DIR/5.7/gcc_64/plugins/sqldrivers</code>. If for any reason it's not automatically overwritten, move it manually there.</li> </ol> <p>Done! Enjoy your MySQL database connection.</p>7633474206	0	 <p>Hope I understood it right. Basically you want a mapping from primitive class types to their wrapper methods.</p> <p>A static utility method implemented in some Utility class would be an elegant solution, because you would use the conversion like this:</p> <pre><code>Class&lt;?&gt; wrapper = convertToWrapper(int.class); </code></pre> <p>Alternatively, declare and populate a static map:</p> <pre><code>public final static Map&lt;Class&lt;?&gt;, Class&lt;?&gt;&gt; map = new HashMap&lt;Class&lt;?&gt;, Class&lt;?&gt;&gt;(); static { map.put(boolean.class, Boolean.class); map.put(byte.class, Byte.class); map.put(short.class, Short.class); map.put(char.class, Character.class); map.put(int.class, Integer.class); map.put(long.class, Long.class); map.put(float.class, Float.class); map.put(double.class, Double.class); } private Class&lt;?&gt; clazz = map.get(int.class); // usage </code></pre>76439910041	0	How to Route without reloading the whole page? <p>I am Using react-route, and i am facing some trouble with routing.</p> <p>The whole page is reloading , causing all the data that i have already fetched and stored in the reducer to load every time.</p> <p>Here is my Route file :</p> <pre><code>var CustomRoute = React.createClass({ render:function(){ return &lt;Router history={browserHistory}&gt; &lt;Route path="/" component={Layout}&gt; &lt;IndexRedirect to="/landing" /&gt; &lt;Route path="landing" component={Landing} /&gt; &lt;Route path="login" component={Login} /&gt; &lt;Route path="form" component={Form} /&gt; &lt;Route path="*" component={NoMatch} /&gt; &lt;/Route&gt; &lt;/Router&gt; }, }); </code></pre> <p>Before routing i already store data by calling action in my main.jsx</p> <pre><code>/** @jsx React.DOM */ 'use strict' var ReactDOM = require('react-dom') var React = require('react') var Index = require('./components/index') var createStore = require("redux").createStore var applyMiddleware = require("redux").applyMiddleware var Provider = require("react-redux").Provider var thunkMiddleware = require("redux-thunk").default var reducer = require("./reducers") var injectTapEventPlugin =require('react-tap-event-plugin'); injectTapEventPlugin() var createStoreWithMiddleware=applyMiddleware(thunkMiddleware)(createStore); var store=createStoreWithMiddleware(reducer); store.dispatch(actions.load_contacts()) //////////// &lt;&lt;&lt;&lt;&lt;&lt; this is what i call to store data already ReactDOM.render( &lt;Provider store={store}&gt;&lt;Index/&gt;&lt;/Provider&gt; , document.getElementById('content')) </code></pre> <p>The issue is i have to route to another page if sucess login :</p> <pre><code>this.props.dispatch(actions.login(this.state.login,this.state.password,(err)=&gt;{ this.setState({err:err}) if (!err){ window.location = "/form" } })); </code></pre> <p>The <strong>window.location</strong> does the trick but it reloads everything which is very inefficient. In manual route i use <code>&lt;Link\&gt;</code> that routes without reloading, however for automated i am not sure how to do it.</p> <p>Any Suggestion will be much appreciated.</p>76540233293	0	 <p>The error, if you say callbacks are not being called, might just be the sign that you may not have connected first. I imagine you have implemented the callbacks and they are not being called? </p> <p>In any case, to "handle" the error situation, you may want to check if the <code>GoogleApiClient</code> is connected.. like this:</p> <pre><code>if (mGoogleApiClient != null &amp;&amp; mGoogleApiClient.isConnected()) { Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback( new ResultCallback&lt;Status&gt;() { @Override public void onResult(Status status) { ApplicationPreferences.get().clearAll(); Intent intent = getIntent(); finish(); startActivity(intent); } }); } else{ Log.w("SomeTag", "It looks like GoogleApiClient is not connected"); } </code></pre> <p>But I do think you need to check if there are any errors (for instance does <code>onConnectionFailed(ConnectionResult result)</code> get called instead? What error do you see?</p> <p>Hope this helps. </p>76623265815	0	ASP.NET MVC: Accessing binded model in controller without using a form AND Ajax <p>I have the following scenario:</p> <pre><code>@model IEnumerable&lt;UI.Models.Customer&gt; @grid.GetHtml( columns: grid.Columns( grid.Column( format: @&lt;text&gt; @Html.ActionLink("Edit", "EditAct", ???) &lt;/text&gt; ), grid.Column( format: @&lt;text&gt; @Html.TextBox("Name", (string)item.Name) &lt;/text&gt; ) ) ) </code></pre> <p>model is just a List consisting of 3 Customer's (Customer is a dummy class with only 2 properties, i.e. ID and Name)</p> <p>Now, i want to be able to capture in the controller action "EditAct "the Customer, which the user want's to edit. Those were the things, that i desperately tried without success:</p> <hr> <p>1) I tried to fill in ??? with a</p> <pre><code>new {customer: item} </code></pre> <p>and to capture it in controller this way:</p> <pre><code>public ActionResult SampleFormParams(Customer customer) {...} </code></pre> <p>This approach does not work, because HTML anchor links uses GET and we can't send an object with GET.</p> <hr> <p>2) It tried to fill in ??? with a</p> <pre><code>new {customer: jsSerializer.Serialize(item)} </code></pre> <p>and to capture it in controller this way:</p> <pre><code>public ActionResult SampleFormParams(String customer) { //deserialize(customer) } </code></pre> <p>This also does not work, because "item" is not a Customer object, but it is a WebGridRow object.</p> <hr> <p>3) It tried to fill in ??? with a</p> <pre><code>new {customer: item.ID} </code></pre> <p>and to capture it in controller this way:</p> <pre><code>public ActionResult SampleFormParams(int id) { ... } </code></pre> <p>I wanted to know if it would be possible to access the whole IEnumerable model, so that i can find the specified customer in the model using the given id ?</p> <hr> <p>So the question is, is there any way, that i can access model directly just with an anchor i.e. ActionLink <br/> - without using a form> AND without using Ajax ?</p> <p>I also checked the Custom Model Binder, but it is also based on a form>.</p>76740341014	0	 <p>The list is showing inside a <a href="https://material.google.com/components/bottom-sheets.html" rel="nofollow">Bottom Sheet</a>. It can be slide up from the bottom of the screen to reveal more content. Bottom Sheets are now supported in v23.2 of the support design library and onwards. There are two types of bottom sheets supported: <a href="https://material.google.com/components/bottom-sheets.html#bottom-sheets-persistent-bottom-sheets" rel="nofollow">persistent</a> and <a href="https://material.google.com/components/bottom-sheets.html#bottom-sheets-modal-bottom-sheets" rel="nofollow">modal</a>. Persistent bottom sheets show in-app content, while modal sheets expose menus or simple dialogs.</p> <p>There are lots of tutorials available. Here are some of them: <a href="https://guides.codepath.com/android/Handling-Scrolls-with-CoordinatorLayout#bottom-sheets" rel="nofollow">https://guides.codepath.com/android/Handling-Scrolls-with-CoordinatorLayout#bottom-sheets</a></p> <p><a href="https://code.tutsplus.com/articles/how-to-use-bottom-sheets-with-the-design-support-library--cms-26031" rel="nofollow">https://code.tutsplus.com/articles/how-to-use-bottom-sheets-with-the-design-support-library--cms-26031</a></p>76827377491	0	Set number of cells depending on array size <p>I'm a beginner and I want to change the number of cells in a collection view depending on whether the user would like to add more cells or not. I tried doing the same thing i did for table views but that doesn't seem to work. no matter what I change the size of the decks array to i only seem to be getting one cell on the screen.</p> <p>Here is my code :</p> <pre><code>class FlashViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { @IBOutlet var collectionView: UICollectionView! var decks = [5] override func viewDidLoad() { super.viewDidLoad() // Move on ... let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout() layout.sectionInset = UIEdgeInsets(top: 75, left: 20, bottom: 10, right: 20) layout.itemSize = CGSize(width: 150, height: 200) collectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout) self.collectionView.dataSource = self self.collectionView.delegate = self collectionView.registerClass(DeckCollectionViewCell.self, forCellWithReuseIdentifier: "DeckCollectionViewCell") collectionView.backgroundColor = UIColor.whiteColor() self.view.addSubview(collectionView!) } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -&gt; Int { return self.decks.count } </code></pre>76921113348	0	Android alertdialog not showing when I think it should <p>I'm developing an android app which I want to check if there's internet connection, if it's not the case display a warning message, and when there's internet connection again load a certain url.</p> <p>It can be said that both displaying the message and checking there's internet connection work... but no separately.</p> <p>I mean I have the following code:</p> <pre><code> if (!checkConnectivity()) { browser.stopLoading(); LayoutInflater layoutinflater = LayoutInflater.from(app); final View textEntryView; textEntryView = layoutinflater.inflate(R.layout.exitdialog, null); new AlertDialog.Builder(app) .setView(textEntryView) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle("Exit") .setNegativeButton("CANCEL", null) .show(); while (!checkConnectivity()) { } browser.loadUrl(url); } </code></pre> <p>If I don't use from while (!checkConnectivity()) to browser.loadUrl(url); then AlertDialog shows properly.</p> <p>If I don't use from LayoutInflater layoutinflater = LayoutInflater.from(app); to .show(); then the app loads the web page correctly on browser.</p> <p>But if I use the whole code it looks like it enters the while (!checkConnectivity()) loop before it does the show as what happens when internet connection is restabilished is that the alert dialog is shown briefly and the the web page is loaded.</p> <p>I find this pretty weird, as I'm not using, as far as I know, threads that could cause that one could be executed before other one, and this is not the case this thing doesn't fulfill one of the most basic things in programming, I mean if an instruction is before another one, the one that's before should be plenty executed logically (except for threads).</p> <p>Hope someone has an idea about this and can help me.</p>77012054987	0	Devise/OmniAuth - LinkedIn: Email is blank in callback <p>I'm using Devise 2.1.2 with multiple OmniAuth providers. My devise.rb file contains this line:</p> <pre><code>config.omniauth :linkedin, API_KEY, SECRET_KEY, :scope =&gt; 'r_emailaddress', :fields =&gt; ["email-address"] </code></pre> <p>It is currently stripped down to just email-address since that is the only thing acting strange. Taking a look inside <code>request.env['omniauth.auth'].info</code>, the <code>email</code> key is blank.</p> <p>How come? I don't want to bypass validation, I wan't to use the email address from the users LinkedIn account.</p>77136608393	0	 <p><code>scanf</code> doesn't try to do a full pattern match of the format string. <code>%s</code> input format simply reads everything up to the next whitespace (or EOF). After that, it looks for a <code>;</code>, and since it doesn't find that it doesn't parse any of the other inputs.</p> <p>If you want to stop at some other character, use <code>[^char]</code></p> <pre><code>scanf("[^;];%[^=]=%s", id, banner, cp); </code></pre>77230664773	0	Why ClassName.class.getFields() returns only public fields? <p>I have one class A</p> <pre><code>public class A { String host = "localhost"; public String port = "8078"; protected String preFix = "www."; private String postFix = "/uploads"; } </code></pre> <p>I am getting field details of class A using below code</p> <pre><code>public static void main(String[] args) { Field[] fields = A.class.getFields(); System.out.println("fields are:" + Arrays.toString(fields)); } </code></pre> <p>The output is </p> <pre><code>fields are:[public java.lang.String org.test.A.port] </code></pre> <p>I understand getFields() method returns only those fields which are declared with public access specifier.</p> <p><strong>But why Java implemented getFields() like this?</strong> </p> <p><strong>What is the main intention of Java Team for this kind of implementation?</strong></p>7738073396	0	 <p>When the file is uploaded it is stored in the tmp folder, to perform any action on it you need to use the tmp path which can be accessed using <code>$_FILES['fotoname']['tmp_name']</code> , I think thats what you are looking for.</p>77437910532	0	 <p>You can take the <code>iterator</code> from the List of <strong>OrdemItem</strong> here:</p> <pre><code>private List&lt;OrderItem&gt; items = new ArrayList&lt;OrderItem&gt;(); </code></pre> <p>and do:</p> <pre><code>public Iterator&lt;OrderItem&gt; iterator() { return items.iterator(); } </code></pre> <p>instead of doing </p> <pre><code>public Iterator&lt;OrderItem&gt; iterator() { return this.iterator(); //How to do this part?? } </code></pre>77540956784	0	 <p>I would use:</p> <pre><code>if [ $YARN -eq 1 ]; then npm install -g yarn &amp;&amp; echo "yarn installed" fi </code></pre> <p>My bash reports 1 if program is not installed and i am not sure if value 1 will pass the -z test</p>77610050677	0	 <p>You can enable the re-pinning button by clicking the "Stop Debugging" button.</p>77730422729	0	Performance difference between member function and global function in release version <p>I have implemented two functions to perform the cross product of two Vectors (not std::vector), one is a member function and another is a global one, here is the key codes(additional parts are ommitted)</p> <pre><code>//for member function template &lt;typename Scalar&gt; SquareMatrix&lt;Scalar,3&gt; Vector&lt;Scalar,3&gt;::outerProduct(const Vector&lt;Scalar,3&gt; &amp;vec3) const { SquareMatrix&lt;Scalar,3&gt; result; for(unsigned int i = 0; i &lt; 3; ++i) for(unsigned int j = 0; j &lt; 3; ++j) result(i,j) = (*this)[i]*vec3[j]; return result; } //for global function: Dim = 3 template&lt;typename Scalar, int Dim&gt; void outerProduct(const Vector&lt;Scalar, Dim&gt; &amp; v1 , const Vector&lt;Scalar, Dim&gt; &amp; v2, SquareMatrix&lt;Scalar, Dim&gt; &amp; m) { for (unsigned int i=0; i&lt;Dim; i++) for (unsigned int j=0; j&lt;Dim; j++) { m(i,j) = v1[i]*v2[j]; } } </code></pre> <p>They are almost the same except that one is a member function having a return value and another is a global function where the values calculated are straightforwardly assigned to a square matrix, thus requiring no return value. <br> Actually, I was meant to replace the member one by the global one to improve the performance, since the first one involes copy operations. The strange thing, however, is that <strong>the time cost by the global function is almost two times longer than the member one.</strong> Furthermore, I find that the execution of</p> <pre><code>m(i,j) = v1[i]*v2[j]; // in global function </code></pre> <p>requires much more time than that of</p> <pre><code>result(i,j) = (*this)[i]*vec3[j]; // in member function </code></pre> <p>So the question is, how does this performance difference between member and global function arise? </p> <p>Anyone can tell the reasons? <br> Hope I have presented my question clearly, and sorry to my poor english!</p> <p>//----------------------------------------------------------------------------------------<br> More information added:<br> The following is the codes I use to test the performance:</p> <pre><code> //the codes below is in a loop Vector&lt;double, 3&gt; vec1; Vector&lt;double, 3&gt; vec2; Timer timer; timer.startTimer(); for (unsigned int i=0; i&lt;100000; i++) { SquareMatrix&lt;double,3&gt; m = vec1.outerProduct(vec2); } timer.stopTimer(); std::cout&lt;&lt;"time cost for member function: "&lt;&lt; timer.getElapsedTime()&lt;&lt;std::endl; timer.startTimer(); SquareMatrix&lt;double,3&gt; m; for (unsigned int i=0; i&lt;100000; i++) { outerProduct(vec1, vec2, m); } timer.stopTimer(); std::cout&lt;&lt;"time cost for global function: "&lt;&lt; timer.getElapsedTime()&lt;&lt;std::endl; std::system("pause"); </code></pre> <p>and the result captured:<br> <img src="https://i.stack.imgur.com/MtPLB.png" alt="enter image description here"></p> <p>You can see that the member funtion is almost twice faster than the global one.<br><br> Additionally, my project is built upon a 64bit windows system, and the codes are in fact used to generate the static lib files based on the Scons construction tools, along with vs2010 project files produced.</p> <p>I have to remind that <strong>the strange performance difference only occurs in a release version, while in a debug build type, the global function is almost five times faster than the member one.(about 0.10s vs 0.02s)</strong></p>77826994885	0	 <p>I think you can't do this only in css. I think some JQuery will help.</p> <pre><code>$('#mytable tr:visible').each(function( index ){ //Your code to add ODD and even class }) </code></pre>77913676790	0	 <p>It seems that Visual Studio 2012 doesn't like non-default fonts. Probably a bug in VS2012. Press the use Default fonts to solve the problem, so far that's the only solution I know.</p>78036784597	0	 <p>Assuming you already have a database connection called <code>db</code> set up, to get a list of the column names, you can use the following code:</p> <pre><code>do { let tableInfo = Array(try db.prepare("PRAGMA table_info(table_name)")) for line in tableInfo { print(line[1]!, terminator: " ") } print() } catch _ { } </code></pre> <p>where <code>table_name</code> is replaced with the literal string of your table's name.</p> <p>You can also add </p> <pre><code>print(tableInfo) </code></pre> <p>to see more pragma info about your table.</p> <p><strong>Credits</strong></p> <p>Thanks to <a href="http://stackoverflow.com/a/29866725/3681880">this answer</a> for clues of how to do this.</p>7814993372	0	 <p>You should not embed firstName and lastName in the primary key. userId should be your primary key, and you should add a unique constraint on [firstName, lastName]. BTW, putting these additional fields in the primary key only guarantees that [idUser, firstName, lastName] is unique, but you might still have two users with different idUsers, but with the same [firstName, lastName].</p> <p>Now to answer the original question, I don't see where the problem is :</p> <pre><code>UserId userId = new UserId("theId", "theFirstName", "theLastName"); User user = (User) session.load(User.class, userId); </code></pre>7823272072	0	 <p>As explained in <a href="http://stackoverflow.com/questions/2921702/change-managed-c-project-to-another-framework-than-4-0-with-vs2010">this answer</a>, you need to add a TargetFrameworkVersion by manually editing the .vcxproj file.</p> <p>I have VS2008 installed on that machine but I think I also selected to include the VC90 compilers when I installed 2010.</p> <p>However, it appears it is <strong>not supported by design,</strong> according to <a href="https://connect.microsoft.com/VisualStudio/feedback/details/560606/c1001-compiler-crash-on-c-cli-project-in-vs2010-when-target-framework-is-3-5" rel="nofollow noreferrer">this Microsoft response</a>: <em>targeting the 3.5 framework with the Visual C++ 2010 compiler is not supported. The Visual C++ 2010 compiler only supports targeting the 4.0 framework.</em></p>7831070569	0	 <p>The answer is: don't do it.</p> <p>Have the calling application either pass you whatever you need to know in the call, or perhaps in your constructor. The called component should not require knowledge of the caller.</p>78418254011	0	 <p>The first expands to the second, so there is no technical difference. Nowadays, the first is the recommended one, while the second is the underlying implementation.</p>78513248261	0	How to make inapp purchase using MKStoreKit 4.x receipt secure from being modified? <p>I have been storing inapp purchase receipt string in nsuserdefaults or a custom plist .This string used to determine the version of the app as full or limited.But how to make it secure.If any person modify this string by modifying the plist the app will change to full version rite.Then i came to know about keychains,but i am not able to understand how it works..is it a separate place where the string is saved or is it encrypting the string and saving it in plist..If anybody knows how to save inapp receipts from mkstorekit using keychains please share it here.. and also the keychains concept</p>78639987143	0	 <p>Final Update: I was able to fix this by using psqlodbc_09_03_0400. For whatever reason, other versions kept throwing error.</p>78738548372	0	Reformatting a csv file, script is confused by ' %." ' <p>I'm using bash on cygwin.</p> <p>I have to take a .csv file that is a subset of a much larger set of settings and shuffle the new csv settings (same keys, different values) into the 1000-plus-line original, making a new .json file. </p> <p>I have put together a script to automate this. The first step in the process is to "clean up" the csv file by extracting lines that start with "mme " and "sms ". Everything else is to pass through cleanly to the "clean" .csv file.</p> <p>This routine is as follows:</p> <pre><code># clean up the settings, throwing out mme and sms entries cat extract.csv | while read -r LINE; do if [[ $LINE == "mme "* ]] then printf "$LINE\n" &gt;&gt; mme_settings.csv elif [[ $LINE == "sms "* ]] then printf "$LINE\n" &gt;&gt; sms_settings.csv else printf "$LINE\n" &gt;&gt; extract_clean.csv fi done </code></pre> <p>My problem is that this thing stubs its toe on the following string at the end of one entry: <code> 100%."</code> When it's done with the line, it simply elides the <code>%."</code> and the new-line marker following it, and smears the two lines together:</p> <pre><code>... 100next.entry.keyname... </code></pre> <p>I would love to reach in and simply manually delimit the <code>%</code> sign, but it's not a realistic option for my use case. Clearly I'm missing something. My suspicion is that I am in some wise abusing <code>cat</code> or <code>read</code> in the first line. </p> <p>If there is some place I should have looked to find the answer before bugging you all, by all means point me in that direction and I'll sod off.</p>78829217158	0	how to list all directories for group has access to in unix/linux <p>Is there a way to list all directories for group has access to in unix/linux. Or a way to list all groups along with directories for which the group has access.</p>78922636707	0	 <p>No, it's not possible. But you can add your feature request on JetBrains tracker: <a href="http://youtrack.jetbrains.com/issues/WI#newissue=yes" rel="nofollow">http://youtrack.jetbrains.com/issues/WI#newissue=yes</a> </p>79034643822	0	Accessing Metacritic API and/or Scraping <p>Does anybody know where documentation for the Metacritic api is/if it still works. There used to be a Metacritic API at <a href="https://market.mashape.com/byroredux/metacritic-v2#get-user-details" rel="nofollow">https://market.mashape.com/byroredux/metacritic-v2#get-user-details</a> which disappeared today.</p> <p>Otherwise I'm trying to scrape the site myself but keeping getting a blocked by a 429 Slow down. I got data like 3 times this hour and haven't been able to get anymore in the last 20 minutes which is making testing difficult and application possibly useless. Please let me know if there's anything else I can be doing to scape I don't know about.</p>79132780669	0	 <p>From developer.android.com: </p> <blockquote> <p>Subclasses should override this method and verify that the given fragment is a valid type to be attached to this activity. The default implementation returns true for apps built for android:targetSdkVersion older than KITKAT. For later versions, it will throw an exception.</p> </blockquote> <p>Basically on TargetSDK &lt;= KITKAT, you should make sure the fragment name <code>isValidFragment</code> passes is a correct one.</p>79222009597	0	 <h2>Some background info...</h2> <p>If you come from the webforms and code-behind world is common to you that an HTML element calls a script in the code, but actually what asp.net webforms does is an http call to the script on the server. If you had an <code>updatepanel</code>, asp.net webforms would have done the same call via ajax.</p> <p>That's the reason why in asp.net webforms the elements have the preceding <code>asp:</code> on their branded <code>html</code> tags. That way asp.net can convert their branded elements to real HTML elements. </p> <h2>The answer</h2> <p>The only way to execute the code of an <code>action</code> from an HTML element on-click event in asp.net MVC is by calling the URL that gets to that method. Either via ajax or by a request from the browser, an http request needs to be done.</p> <p>With javascript you can listen when an element's on-click event is fired and then do some logic. If you're using jquery you can use the <code>$.ajax()</code> or <code>$.get()</code> methods to make a call to your action URL. </p>7935308595	0	SQL query (can include pl/sql bits) based on conditional count <p>Premise: We've got a table with 5 fields. 2 fields are always unique. </p> <p>What would be a good way to fulfill this: </p> <p>if (count_of_result == 3) { add up the 3 rows from the same table. unique values get added up &amp; the non-unique values are assumed to be same for all the 3 rows. the query result should show 1 row, with the values added up. } else { </p> <p>display all the results of the query as usual.</p> <p>}</p> <p>Thank you.</p>79415897174	0	 <p><a href="http://www.scala-lang.org/node/3388">This thread</a> seems to describe the solution:</p> <pre><code>object Test { def apply( int : Int ) = new Test( int ) } class Test @deprecated( "Don't construct directly - use companion constructor", "09/04/13" ) ( int : Int ) { override def toString() = "Test: %d".format( int ) } </code></pre> <p>Can't try it right now though.</p>79528931183	0	 <p>Further messing around yielded the answer: <code>xargs</code> instead of a subshell:</p> <pre><code>echo \'foo bar\' \'baz quux\' | xargs /usr/bin/defaults write com.apple.systemuiserver menuExtras -array </code></pre>79635168470	0	Windows Virtual Machine getting connection refused to port 9090 webpack dev server <p>I have a Meteor + Webpack application I'm working on, but I can't get a Windows VM (Win10, IE11, from modern.ie running inside VirtualBox) to access the Webpack dev server assets on port 9090, while the Meteor assets on the same host but on port 3000 work fine for whatever reason. The app is running and being accessed at {host}:3000 but this one bundled JS file is on on the same host at port 9090 and the VM is unable to fetch it.</p>79714158048	0	 <p>According to the <a href="http://cpansearch.perl.org/src/PJCJ/Devel-Cover-0.99/docs/TODO" rel="nofollow">TODO file</a> on CPAN, this capability is not currently supported, but the developers see it as a valuable addition:</p> <blockquote> <ul> <li>Enhancements: <ul> <li>Marking of unreachable code - commandline tool and gui.</li> </ul></li> </ul> </blockquote> <p>The <code>cover</code> script mentions promising options: <code>-add_uncoverable_point</code> and <code>-delete_uncoverable_point</code>.</p>79836285195	0	After using importRange to get Hyperlinked cells, how do you get the value of the URL? <p>I was trying to help someone solve a problem the other day and I came across an interesting issue I couldn't solve.</p> <p>Imagine two sheets. One containing HYPERLINKS created by HYPERLINK function in Google Sheets, such as this sheet. <a href="https://docs.google.com/spreadsheets/d/1hVr-PnmpAj7VaT6xTfwhMAS2zi-JzruDZcjvHzQIpyk/edit?usp=sharing" rel="nofollow">Source Sheet</a></p> <p>Then you have another sheet that uses importRange to import these URL's, like this sheet. <a href="https://docs.google.com/spreadsheets/d/1r5Zt-7ByW8A17kKPdcIBs_gzH8RuM4n3Q5aW6mHxyKM/edit?usp=sharing" rel="nofollow">import Sheet</a></p> <p>The URLs import correctly, with correct link and link text. But no matter what I tried, in the import sheet, I couldn't extract the link value.</p> <p>I tried to do this via formulas and via scripting. I'm guessing the URL must be some sort of object but I cannot seem to read or split it. Whatever efforts I've tried have always returned the link text, EG Google, Yahoo and not the URL itself.</p>79922001333	0	 <p>If you just want to enable/disable input:</p> <pre><code>$("#your_input").attr('disabled','disabled'); // disable $("#your_input").removeAttr('disabled');//enable </code></pre> <p>Example:</p> <p><a href="http://jsfiddle.net/juvian/R95qu" rel="nofollow">http://jsfiddle.net/juvian/R95qu</a></p>80036711688	0	 <p>You second thread is not appending content to the file, which was written by first thread. Instead it is overwriting content written by first thread. </p> <p>So you are getting output only from second thread.</p> <p>Change your code </p> <p>from </p> <pre><code> FileWriter f = new FileWriter("C:\\Users\\Desktop\\sample.txt"); </code></pre> <p>to </p> <pre><code> FileWriter f = new FileWriter("C:\\Users\\Desktop\\sample.txt",true); </code></pre> <p>Refer to java documentation <a href="https://docs.oracle.com/javase/8/docs/api/java/io/FileWriter.html#FileWriter-java.io.File-boolean-" rel="nofollow">page</a> on <code>FileWriter</code></p> <pre><code>public FileWriter(File file, boolean append) throws IOException </code></pre> <blockquote> <p>Constructs a FileWriter object given a File object. If the second argument is true, then bytes will be written to the end of the file rather than the beginning.</p> </blockquote>80120174142	0	keytool error :Alias ​​<andoiddebugkey> does not exist <p>I get an error when I write this command in the console</p> <pre><code>C:\Program Files\Java\jdk1.7.0_21\bin&gt; keytool-list-alias-andoiddebugkey keystore C:\Users\AbuHamza\android\debug.keystore-storepass android-keypass androi. d </code></pre> <p>error</p> <pre><code>keytool error: java.lang.Exception: Alias ​​&lt;andoiddebugkey&gt; does not exist </code></pre>8024423417	0	C++, function that loads text ignores last few lines with only some of the .txt files <p>I'm following theForger's Win API tutorial to load text files into an edit control. Sometimes the entire file is loaded correctly and sometimes the last part of it is left out, where 'part' is in one case 2 and a half lines and in another 10 lines o_O Here's how the files look:</p> <p>(I'm a new user so it's not letting me post more than one hyperlink, so here's the gallery where the screenshots are: <a href="http://nancy.imgur.com/all/" rel="nofollow">http://nancy.imgur.com/all/</a> and I'm referring to the order in which they appear in the gallery)</p> <p>2.5 lines left out: second (reading stops at the cursor after the 'F')</p> <p>10 lines left out: fourth (also stops at the cursor after the f)</p> <p>Read completely: first and third</p> <p>I tried using fstreams instead, and the same stuff was left out (I also couldn't get the new line characters to show in the edit control =( ). Any idea what could be wrong?</p> <p>I couldn't link to theForger's tutorial so here's the function:</p> <pre><code>BOOL LoadTextFileToEdit(HWND hEdit, LPCTSTR pszFileName) { HANDLE hFile; BOOL bSuccess = FALSE; hFile = CreateFile(pszFileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); if(hFile != INVALID_HANDLE_VALUE) { DWORD dwFileSize; dwFileSize = GetFileSize(hFile, NULL); if(dwFileSize != 0xFFFFFFFF) { LPSTR pszFileText; pszFileText = GlobalAlloc(GPTR, dwFileSize + 1); if(pszFileText != NULL) { DWORD dwRead; if(ReadFile(hFile, pszFileText, dwFileSize, &amp;dwRead, NULL)) { pszFileText[dwFileSize] = 0; // Add null terminator if(SetWindowText(hEdit, pszFileText)) bSuccess = TRUE; // It worked! } GlobalFree(pszFileText); } } CloseHandle(hFile); } return bSuccess; } </code></pre>8032844661	0	 <p>Checkout the newest revision of the restored backup into a working copy. do an svn export of and old working copy and simply copy all files/folders onto the previously checkout working copy. Than do an svn add if needed and commit. This should summ all changes.</p>8049025780	0	 <p>Getting co-ordinates for a polygon would require GIS files and a GIS software like MapInfo to read. </p> <p>My advice would be visit this site;</p> <p><a href="http://bbs.keyhole.com/ubb/ubbthreads.php?ubb=showthreaded&amp;Number=332073" rel="nofollow">http://bbs.keyhole.com/ubb/ubbthreads.php?ubb=showthreaded&amp;Number=332073</a></p> <p>Download the KML file which has the district boundaries of UK counties and then use it in either google earth or fusion tables.</p> <p>Finding out what your using these for may help get a better answer...</p>80510255619	0	 <p>I think you're looking for <a href="http://msdn.microsoft.com/en-us/library/7977ey2c.aspx">System.Collections.Generic.Queue</a> instead of <a href="http://msdn.microsoft.com/en-us/library/system.collections.queue.aspx">System.Collections.Queue</a>.</p> <p>Change</p> <pre><code>open System.Collections </code></pre> <p>to </p> <pre><code>open System.Collections.Generic </code></pre>80628699427	0	Printing the value of an R variable in Latex <p>I am writing .Rnw file in RStudio. At one point, I store (but do not print) the value of the number of rows (nR) of a data frame (df), using the following command:</p> <pre><code>&lt;&lt;results = hide, echo=FALSE&gt;&gt;= nR = nrow(sbGeneal) nC = ncol(sbGeneal) @ </code></pre> <p>Late, in the .Rnw file, I would like to use the nR variable and print it. An equivalent syntax in .Rmd (markdown) would be:</p> <pre><code>`r nrow(sbGeneal)` </code></pre> <p>Is there such a possibility in Latex? Thanks!</p>80721699836	0	 <p>Yet another solution:</p> <pre><code>&lt;lable&gt;Set1&lt;/lable&gt; &lt;input type="checkbox" name="set_199[]" value="Apple" /&gt; &lt;input type="checkbox" name="set_199[]" value="Mango" /&gt; &lt;input type="checkbox" name="set_199[]" value="Grape" /&gt; &lt;input type="button" value="check" class="js-submit"&gt; </code></pre> <p>Js:</p> <pre><code>$(".js-submit").on("click", function(){ var a = $("input[type='checkbox']:checked"); var values = {}; a.each(function(){ var value = $(this).val(); var name = $(this).attr("name"); if(!values[name]) values[name] = []; values[name].push(value) }); console.log(values) }); </code></pre> <p><a href="http://jsfiddle.net/6775b/" rel="nofollow">Demo</a></p>80833965928	0	 <p>The button elements are not sibling elements.</p> <p>You need to select the parent element's sibling elements.</p> <p><a href="http://jsfiddle.net/eakbvwxL/" rel="nofollow"><strong>Working Example Here</strong></a></p> <pre><code>$(document).on('click', '.btn-group button', function (e) { $(this).addClass('active').parent().siblings().find('button').removeClass('active'); }); </code></pre> <p>However, the proper way to do this is to use the attribute <code>data-toggle="buttons"</code>.</p> <p>In doing so, you don't need to write any custom JS. For more information, see <a href="http://stackoverflow.com/questions/22362750/bootstrap-button-group-pre-select-button-with-html-only">this old answer</a> of mine explaining how it works.</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet"/&gt; &lt;script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"&gt;&lt;/script&gt; &lt;div class="btn-group btn-group-justified" data-toggle="buttons" role="group" aria-label="..."&gt; &lt;label class="btn btn-default"&gt; &lt;input type="radio" name="options" /&gt;Low Cost/Effeciency &lt;/label&gt; &lt;label class="btn btn-default"&gt; &lt;input type="radio" name="options" /&gt;Average &lt;/label&gt; &lt;label class="btn btn-default"&gt; &lt;input type="radio" name="options" /&gt;High Cost/Effeciency &lt;/label&gt; &lt;/div&gt;</code></pre> </div> </div> </p>80913524314	0	Sorting listview in javascript <p>I have listview with Title, image and date. I want to sort that list on the basis of date field and then display in html5 page. I used jquery and html5 on this.</p> <pre><code>$j('#task_summary_list').empty(); if (response.totalSize &gt; 0) { $j.each(response.records, function(i, record) { var imgName; switch (record.Priority) { case "High": imgName = "images/prio_high24.png"; break; case "Low": imgName = "images/prio_low24.png"; break; default: imgName = "images/prio_normal24.png"; } // create new list entry for record to the listview $j('&lt;li&gt;&lt;/li&gt;') .attr('id', record.Id) .hide() .append( '&lt;a href="#"&gt;' + '&lt;img src="' + imgName + '" alt="High" class="ui-li-icon"&gt;' + '&lt;h1&gt;' + record.Subject + '&lt;/h1&gt;' + '&lt;p&gt;' + '&lt;strong&gt;' + record.ActivityDate + '&lt;/strong&gt;' + '&lt;/p&gt;' + '&lt;/a&gt;') .click(function(e) { e.preventDefault(); console.log("Under onSuccessTasks " + record.Id); showTaskDetails(record); }) .appendTo('#task_summary_list') .show(); }); } else { $j('&lt;li class="norecord"&gt;No records to display&lt;/li&gt;').appendTo('#task_summary_list'); } $j('#task_summary_list').listview('refresh'); $j.mobile.hidePageLoadingMsg(); </code></pre> <p>Any help is appreciated. Thanks in avance.</p>81030296654	0	OnClientClick not working in IE11 <p>The onClientClick event is not getting fired in IE11 browser, however the same piece of code is working perfectly fine in IE8,9 and 10 browsers. Is there any extra piece of code that i need to add in there. </p> <pre><code> &lt;table width="100%"&gt; &lt;tr&gt; &lt;td align="center"&gt; &lt;asp:Button runat="server" ID="btnFTCancel" Text="Cancel" OnClientClick="return confirmCancel();" OnClick="btnUpdate_Click" ClientIDMode="Static"/&gt; &lt;/td&gt; &lt;td align="center"&gt; &lt;asp:Button runat="server" ID="btnApprove" Text="Approve" Enabled="false" OnClientClick="return confirmApprove();" OnClick="btnUpdate_Click"/&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;script type="text/javascript"&gt; function confirmCancel() { var returnvalue; $("#btnFTCancel").css("cursor", "text"); returnvalue = confirm('Transactions generated for this request ID will be cancelled. Do you wish to continue ?'); return returnvalue; } function confirmApprove() { var returnvalue; returnvalue = confirm('Transactions generated for this request ID will be sent to FCS. Do you wish to continue ?'); return returnvalue; } function setBtnCursor() { $("input[type='submit']").css('cursor', 'pointer'); $("input[type='submit'][disabled='disabled']").css('cursor', 'default'); } &lt;/script&gt; </code></pre> <p>TIA,</p> <p>Amit</p>8119081449	0	 <p>According to <a href="http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html" rel="nofollow">here</a>:</p> <blockquote> <p>Operators on the same line have equal precedence. When operators of equal precedence appear in the same expression, a rule must govern which is evaluated first. All binary operators except for the assignment operators are evaluated from left to right; assignment operators are evaluated right to left.</p> </blockquote> <p>So yes.</p>8121808882	0	 <p>Not too sure if this will help, but perhaps try getting the the modules first and then the types from there.</p> <pre><code>Assembly a = Assembly.Load(brockenAssembly); Module[] mList = a.GetModules(); for (int i = 0; i &lt; mList.length; i++) { Module m = a.GetModules()[i]; Type[] tList = m.GetTypes(); } </code></pre> <p>Hope fully you could get the list of types available in one of the modules.</p>81316967562	0	 <p>Yould could just popup a dialog with the progress in there but if you do not want to block the user from using the map then another alternative would be to overlay another layout on top of the map fragment and put the progress bar in that layout</p>81417161110	0	How to turn on table name autocomplete feature in Toad? <p>I'm using Toad version 11.0.0.116. I'm not getting default tablename options when I start typing table. How to turn the autocomplete feature on??</p>81513292537	0	 <p>Assuming you have any <code>View</code> instance in your activity, you can use <a href="http://developer.android.com/reference/android/view/View.html#postDelayed%28java.lang.Runnable,%20long%29" rel="nofollow">View.postDelayed()</a> to post runnable with a given delay. In this runnable you can call <a href="http://developer.android.com/reference/android/app/Activity.html#finish%28%29" rel="nofollow">Activity.finish()</a>. You should also use <a href="http://developer.android.com/reference/android/view/View.html#removeCallbacks%28java.lang.Runnable%29" rel="nofollow">View.removeCallbacks()</a> to remove your callback in <code>onDestroy()</code>, to avoid your callback being called after user already navigated back from your activity.</p> <p>Using <code>AsyncTask</code> just to count some time is just an overkill (unless you want to use <code>AsyncTask</code> to actually do some useful, background work). The <code>Looper</code> and <code>Handler</code> classes provide everything you need to execute any code on UI thread after a given delay. The <code>View</code> methods mentioned above are just convenience methods exposing the <code>Handler</code> functionality.</p>81636149764	0	 <p>The <code>upload_to</code> argument can be a function, <a href="https://docs.djangoproject.com/en/1.9/ref/models/fields/#django.db.models.FileField.upload_to" rel="nofollow">as described in the documentation</a>:</p> <pre><code>def group_based_upload_to(instance, filename): return "image/group/{}/{}".format(instance.group.id, filename) class Group_Photo(models.Model): group = models.ForeignKey(Group) photo = models.ImageField(upload_to=group_based_upload_to) </code></pre> <p>The function takes two arguments - instance of the model to which the file is being attached and the original name of the file. It has to return a relative path under witch the file will be saved. It will be appended to the path defined in the <code>MEDIA_ROOT</code> setting.</p> <p>The example above uses directories based on group's numeric id. You can obviously use other fields, for example to use the slug (if it has one) just replace <code>instance.group.id</code> with <code>instance.group.slug</code>.</p>8173304314	0	 <p>You should also measure the length of the stick in the first part of the for loop, otherwise you'll be measuring it with every iteration. And you can also make the <code>k</code> bit even more compact:</p> <pre><code>for (var i = k = 0, j = mystick.length; i &lt; j; i++) { if (mystick[i] == 'huge') { k++; } } </code></pre>81839233034	0	 <p>Well, I dont have a direct approach. But this hack should help you get what you want.. </p> <pre><code>// Start the Browser As Process to start in Private mode Process browserProcess = new Process(); browserProcess.StartInfo.FileName = "iexplore.exe"; browserProcess.StartInfo.Arguments = "-private"; browserProcess.StartInfo.WindowStyle = ProcessWindowStyle.Maximized; // Start browser browserProcess.Start(); // Get Process (Browser) Handle Int64 browserHandle = browserProcess.Handle.ToInt64(); // Create a new Browser Instance &amp; Assign the browser created as process using the window Handle BrowserWindow browserFormHandle = new BrowserWindow(); browserFormHandle.SearchProperties.Add(BrowserWindow.PropertyNames.WindowHandle, browserFormHandle.ToString()); browserFormHandle.NavigateToUrl(new Uri("http://www.google.com")); </code></pre>81937114802	0	 <p>You need to set the value of <code>$scope.objectData[key]</code> to an object before you can add more keys to it.</p> <pre><code>$scope.objectData[key] = {}; $scope.objectData[key]['digits'] = 'foo'; </code></pre>82029356529	0	 <p>If you don't need it to undock and float then you can use a <a href="https://msdn.microsoft.com/en-us/library/system.windows.controls.headeredcontentcontrol%28v=vs.110%29.aspx" rel="nofollow">HeaderedContentControl</a>.</p> <p>When you want to add the close button you can template the header presenter to include a button.</p>82118965510	0	 <p>The way to do this is in the controller for the news_article in <code>def show</code> you write <code>redirect_to @news_article.attach.url</code></p> <p>in news_article paperclip store url in attach (I call it this in model) and the .url helper is what makes the browser go there :)</p>8225223322	0	Domain Name with unicode Pitfalls <p>According to yahoo and stackoverflow.com they advise having a static content site that you don't assign cookies to. <a href="http://developer.yahoo.com/performance/rules.html#cookie_free" rel="nofollow">http://developer.yahoo.com/performance/rules.html#cookie_free</a> http://sstatic.net</p> <p>Based of the desire for a static only domain name I though it would be cool to have the domain name made up of unicode characters. From what I understand pitfalls of unicode characters include: difficulty to type and automatic punycode conversation due to the paypal.com innocent. </p> <p>For example if I wanted to link my stylesheet.</p> <pre><code>&lt;link rel=stylesheet href=☺.com/s.css&gt; .... &lt;script src=☺.com/s.js&gt;&lt;/script&gt; </code></pre> <p>Considering I only plan to link to static content, are there are issues or pitfalls?</p> <p>Do all browsers natively support unicode -> punycode conversation? It has been unclear to me if internet explorer less than 7 supports punycode. Also would IE display a notice if you are simply linking to server content in unicode format. </p> <p><strong>Bonus:</strong> Also is there any place to find a list of legal url unicode url characters? Supposedly some characters aren't permitted?! Or would a url containing non permitted characters simply be translated to punycode immediately therefore not effecting my situation?</p>82340751775	0	 <p>Not sure how this should be done in query syntax, but here is the method syntax version:</p> <pre><code>this.Data = data .Split(new[] { "@" }, StringSplitOptions.RemoveEmptyEntries) .Select(table =&gt; table.Split(new[] { "^^" }, StringSplitOptions.RemoveEmptyEntries) .Select(row =&gt; row.Split(';')) .ToArray()) .ToArray(); </code></pre> <hr> <p>In query synax : </p> <pre><code>this.Data = ( from table in data.Split(new[] { "@" }, StringSplitOptions.RemoveEmptyEntries) select ( from row in table.Split(new[] { "^^" }, StringSplitOptions.RemoveEmptyEntries) select row.Split(';') ).ToArray() ).ToArray(); </code></pre>8245817142	0	 <p>Exactly, UML class diagrams are just a notation that you could (and should) differently depending on the sofware development phase you are in. You can start with only classes, attributes and associations, then refine the diagram to add types information for the attributes, then navigation, class methods, qualifiers for associations ... until you get a complete class diagram ready for the implementation phase </p> <p>Note that you could even iterate to the point in which you remove associations and replace them by attributes of complex types to have a class diagram even more similar to the final implementation. It's up to you how to use class diagrams in each phase.</p>82540989587	0	 <p>If you use a val, you're not allowed to assign it a new value, so in your code example above, if you switch the third line with</p> <pre><code>val fa2 = fa.:+(ra) </code></pre> <p>then fa can be a val.</p>82633589252	0	 <p>I see only two good choices: </p> <ol> <li>make that site a webproxy</li> <li>use <code>unlimitedStorage</code> permission and store the urls in WebSQL database (it's also the fastest). Despite the general concern that it may be deprecated in Chrome after W3C stopped developing the specification in favor of IndexedDB I don't think it'll happen any time soon because <em>all</em> the other available storage options are either [much] slower or less functional.</li> </ol>82716320287	0	 <p>Use <a href="http://codex.wordpress.org/Function_Reference/is_page" rel="nofollow"><code>is_page</code></a> to detect your front-end login and registration pages:</p> <pre><code>&lt;?php if ( ! is_user_logged_in() &amp;&amp; ! ( is_page( 'register' ) || is_page( 'login' ) ) ) { echo '&lt;div&gt;Some stuff here&lt;/div&gt;'; // your code } ?&gt; </code></pre>82832933716	0	 <p>NPE is because of the below reason</p> <pre><code>try { desktop.browse(uri); } catch(IOException ioe) { System.out.println("The system cannot find the " + uri + " file specified"); //ioe.printStackTrace(); } </code></pre> <p>you are initializing desktop in DesktopDemo constructor but onLaunchBrowser() is a static method so desktop object is not instantiated! </p>8295645072	0	 <p>Hope U R USING PHP</p> <p>choose your own separator like</p> <pre><code>$glue=®(alt 0174) CONCAT_WS($glue,str1,$str2) </code></pre>83027037271	0	 <p>One quick solution is to change your html structure and move sidebar as first child of div wih id <code>#tekst</code>:</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>body { background: #98c8d7; width: 1000px; margin: auto; font-family: "Trebuchet ms", Verdana, sans-serif; } #header { background: #fff url(banner.jpg) no-repeat; margin: 10px 0 10px 0; padding: 8em 2em 1em 2em; text-align: center; border-radius: 15px; opacity: 0.8; border: 1px dotted #000 } /*Dette formaterer menuen */ ul { list-style-type: none; margin: 0; padding: 0; overflow: hidden; } li { float: left; } a:link, a:visited { display: block; width: 312.5px; font-weight: bold; color: #000; background-color: #51a7c2; text-align: center; padding: 4px; text-decoration: none; text-transform: uppercase; border: 1px solid #91cfca; opacity: 0.8; } a:hover, a:active { background-color: #98c8d7; } #content { background: #b4cdd9; color: #000; padding: 1em 1em 1em 1em; top right bottom left } #tekst { background: #98c8d7; color: #000; opacity: 0.8; margin: 5px 0 5px 0; padding: 0.5em 1em 1em 1em; text-align: left; } #sidebar { background: #b4cdd9; color: #000; width: 320px; position: relative; float: right; margin: 5px 0 5px 0; padding: 0.5em 1em 1em 1em; text-align: left; border-style: outset; border-width: 3px; border-color: black; } a { color: #0060B6; text-decoration: none; } a:hover { color: #00A0C6; text-decoration: none; cursor: pointer; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;body&gt; &lt;!-- Denne div indeholder dit content, altså din brødtekst --&gt; &lt;div id="content"&gt; &lt;!--Header. Indeholder banner --&gt; &lt;div id="header"&gt;&lt;/div&gt; &lt;!-- Menu --&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="forside.html"&gt;Forside&lt;/a&gt; &lt;/li&gt; &lt;li&gt;&lt;a href="priser.html"&gt;Priser&lt;/a&gt; &lt;/li&gt; &lt;li&gt;&lt;a href="kontakt.html"&gt;Kontakt&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;!-- Her kommer din brødtekst så --&gt; &lt;div id="tekst"&gt; &lt;div id="sidebar"&gt; &lt;!-- move it here --&gt; &lt;h3&gt;Leon Laksø&lt;/h3&gt; &lt;p&gt;Så-og-så-mange år i tjeneste, certificeret bla bla, alt muligt andet shit her. Måske et billede hvor du ser venlig ud?&lt;/p&gt; &lt;p&gt;Mail link kunne være her?&lt;/p&gt; &lt;/div&gt; &lt;h1&gt;Overskrift 1&lt;/h1&gt; &lt;p&gt;Her kan du skrive, hvad du tilbuder, hvorfor, hvorledes, til hvem og anden info&lt;/p&gt; &lt;!-- Overskrift to. Der er flere former for overskrifter. H1 betegner en bestemt slags, H2 en mindre slags osv. Du kan godt bruge H1 flere gange --&gt; &lt;h2&gt;Underoverskrift 1&lt;/h2&gt; &lt;p&gt;Her kan du måske skrive lidt om dig selv og dine kvalifikationer?&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt;</code></pre> </div> </div> </p>83126020180	0	 <p>OK, I'm not going to try a fix your code. I'm just going to create constraints that I would use to achieve your layout. I'll put the thought process in comments.</p> <p><strong>First get a nice vertical layout going...</strong></p> <pre><code>// I'm just using standard padding to make it easier to read. // Also, I'd avoid the variable padding stuff. Just set it to a fixed value. // i.e. ==padding not (&gt;=0, &lt;=padding). That's confusing to read and ambiguous. @"V:|-[titleLabel]-[ratingBubbleView]-[descriptionLabel]-|" </code></pre> <p><strong>Then go through layer by layer adding horizontal constraints...</strong></p> <pre><code>// constraint the trailing edge too. You never know if you'll get a stupidly // long title. You want to stop it colliding with the end of the screen. // use &gt;= here. The label will try to take it's intrinsic content size // i.e. the smallest size to fit the text. Until it can't and then it will // break it's content size to keep your &gt;= constraint. @"|-[titleLabel]-&gt;=20-|" // when adding this you need the option "NSLayoutFormatAlignAllBottom". @"|-[ratingBubbleView]-[dateLabel]-&gt;=20-|" @"|-[descriptionLabel]-|" </code></pre> <p>Try not to "over constrain" your view. In your code you are constraining the same views with multiple constraints (like descriptionLabel to the bottom of the superview).</p> <p>Once they're defined they don't need to be defined again.</p> <p>Again, with the padding. Just use <code>padding</code> rather than <code>&gt;=padding</code>. Does >=20 mean 20, 21.5, or 320? The inequality is ambiguous when laying out.</p> <p>Also, In my constraints I have used the layout option to constrain the vertical axis of the date label to the rating view. i.e. "Stay in line vertically with the rating view". Instead of constraining against the title label and stuff... This means I only need to define the position of that line of UI once.</p>8322846831	0	 <p>An alternative to filtering would be to maintain the list of selected users. In <code>setSelected(true)</code> you could add a user to the list and use <code>setSelected(false)</code> to remove it.</p> <pre><code>class User { List&lt;User&gt; selectedUsers = new ArrayList&lt;User&gt;(0); void setSelected(boolean isSelected) { if ( isSelected) { selectedUsers.add(user.getId()); } else { int idx = selectedUsers.indexOf( this ); if ( idx &gt;= 0 ) selectedUsers.remove( idx ); } } } </code></pre> <p>This aproach requires an implemented equals method. BTW your snippet adds the userId (Int?) to the list of type User.</p>83318205592	0	 <p>When you do writeObject, the objevt you write needs to be Serializable. Try to change the signature of your <code>copy</code>-method to </p> <pre><code>public static Object copy(Serializable oldObj) </code></pre> <p>The error message will be clearer.</p>8342894704	0	 <p>The <code>DataContext</code> on your usercontrol isn't set. Specify a <code>Name</code> for it (I usually call mine "ThisControl") and modify the TextBox's binding to <code>Text="{Binding ElementName=ThisControl, Path=TitleValue, Mode=TwoWay}"</code>. You can also set the <code>DataContext</code> explicitly, but I believe this is the preferred way.</p> <p>It seems like the default DataContext should be "this", but by default, it's nothing.</p> <p>[edit] You may also want to add <code>, UpdateSourceTrigger=PropertyChanged</code> to your binding, as by default TextBoxes' Text binding only updates when focus is lost.</p>83516890317	0	How to make UIViewController's view inherit from another UIView? <p>I have one <code>UIViewController</code> without NIB file. Now i have one my customized <code>UIView</code>. I want to make <code>UIViewController</code>'s view inherit from my customized <code>UIView</code>, is it possible ? I know that if I have XIB file than I can make Custom Class from there but without XIB can it be done? <img src="https://i.stack.imgur.com/oXxy6.png" alt="enter image description here"></p> <p>Thanks in Advance</p>8362038527	0	 <pre><code>int* memory = NULL; memory = malloc(sizeof(int)); if (memory != NULL) { memory=10; free(memory); } </code></pre> <p>This will crash. You're setting the pointer to memory location 10 and then asking the system to release the memory. It's extremely unlikely that you previously allocated some memory that happeneds to start at 0x10, even in the crazy world of virutal address spaces. Furthermore, IF malloc failed, no memory has been allocated, so you do not need to free it.</p> <pre><code>int* memory = NULL; memory = malloc(sizeof(int)); if (memory != NULL) { memory=10; } free(memory); </code></pre> <p>This is also a bug. If malloc fails, then you are setting the pointer to 10 and freeing that memory. (as before.) If malloc succeeds, then you're immediately freeing the memory, which means it was pointless to allocate it! Now, I imagine this is just example code simplified to get the point across, and that this isn't present in your real program? :)</p>83716783675	0	Running Continumm Standalone <p>I have downloaded apache continuum. </p> <p>After that i unpacked and i typed continuun console. </p> <p>It´s started fine... but when i put localhost:8080/continuum in the browser the console show this error: What´s happend?</p> <pre><code>jvm 1 | org.apache.jasper.JasperException: PWC6345: There is an error in invo king javac. A full JDK (not just JRE) is required jvm 1 | at org.apache.jasper.compiler.DefaultErrorHandler.jspError(Defau ltErrorHandler.java:92) jvm 1 | at org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDisp atcher.java:378) jvm 1 | at org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDisp atcher.java:119) jvm 1 | at org.apache.jasper.compiler.Jsr199JavaCompiler.compile(Jsr199J avaCompiler.java:208) jvm 1 | at org.apache.jasper.compiler.Compiler.generateClass(Compiler.ja va:384) jvm 1 | at org.apache.jasper.compiler.Compiler.compile(Compiler.java:453 ) jvm 1 | at org.apache.jasper.JspCompilationContext.compile(JspCompilatio nContext.java:625) jvm 1 | at org.apache.jasper.servlet.JspServletWrapper.service(JspServle tWrapper.java:374) jvm 1 | at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServle t.java:492) jvm 1 | at org.apache.jasper.servlet.JspServlet.service(JspServlet.java: 378) jvm 1 | at javax.servlet.http.HttpServlet.service(HttpServlet.java:848) jvm 1 | at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder. java:648) jvm 1 | at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHand ler.java:455) jvm 1 | at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedH andler.java:137) jvm 1 | at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHan dler.java:577) jvm 1 | at org.eclipse.jetty.server.session.SessionHandler.doHandle(Sess ionHandler.java:231) jvm 1 | at org.eclipse.jetty.server.handler.ContextHandler.doHandle(Cont extHandler.java:1072) jvm 1 | at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandl er.java:382) jvm 1 | at org.eclipse.jetty.server.session.SessionHandler.doScope(Sessi onHandler.java:193) jvm 1 | at org.eclipse.jetty.server.handler.ContextHandler.doScope(Conte xtHandler.java:1006) jvm 1 | at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedH andler.java:135) jvm 1 | at org.eclipse.jetty.server.Dispatcher.forward(Dispatcher.java:2 76) jvm 1 | at org.eclipse.jetty.server.Dispatcher.forward(Dispatcher.java:1 03) jvm 1 | at org.eclipse.jetty.servlet.DefaultServlet.doGet(DefaultServlet .java:566) jvm 1 | at javax.servlet.http.HttpServlet.service(HttpServlet.java:735) jvm 1 | at javax.servlet.http.HttpServlet.service(HttpServlet.java:848) jvm 1 | at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder. java:648) jvm 1 | at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter (ServletHandler.java:1336) jvm 1 | at org.apache.struts2.dispatcher.ng.filter.StrutsExecuteFilter.d oFilter(StrutsExecuteFilter.java:85) jvm 1 | at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter (ServletHandler.java:1307) jvm 1 | at com.opensymphony.sitemesh.webapp.SiteMeshFilter.obtainContent (SiteMeshFilter.java:129) jvm 1 | at com.opensymphony.sitemesh.webapp.SiteMeshFilter.doFilter(Site MeshFilter.java:77) jvm 1 | at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter (ServletHandler.java:1307) jvm 1 | at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareFilter.d oFilter(StrutsPrepareFilter.java:82) jvm 1 | at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter (ServletHandler.java:1307) jvm 1 | at org.springframework.web.filter.CharacterEncodingFilter.doFilt erInternal(CharacterEncodingFilter.java:96) jvm 1 | at org.springframework.web.filter.OncePerRequestFilter.doFilter( OncePerRequestFilter.java:76) jvm 1 | at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter (ServletHandler.java:1307) jvm 1 | at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHand ler.java:453) jvm 1 | at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedH andler.java:137) jvm 1 | at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHan dler.java:559) jvm 1 | at org.eclipse.jetty.server.session.SessionHandler.doHandle(Sess ionHandler.java:231) jvm 1 | at org.eclipse.jetty.server.handler.ContextHandler.doHandle(Cont extHandler.java:1072) jvm 1 | at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandl er.java:382) jvm 1 | at org.eclipse.jetty.server.session.SessionHandler.doScope(Sessi onHandler.java:193) jvm 1 | at org.eclipse.jetty.server.handler.ContextHandler.doScope(Conte xtHandler.java:1006) jvm 1 | at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedH andler.java:135) jvm 1 | at org.eclipse.jetty.server.handler.ContextHandlerCollection.han dle(ContextHandlerCollection.java:255) jvm 1 | at org.eclipse.jetty.server.handler.HandlerCollection.handle(Han dlerCollection.java:154) jvm 1 | at org.eclipse.jetty.server.handler.HandlerWrapper.handle(Handle rWrapper.java:116) jvm 1 | at org.eclipse.jetty.server.Server.handle(Server.java:365) jvm 1 | at org.eclipse.jetty.server.AbstractHttpConnection.handleRequest (AbstractHttpConnection.java:485) jvm 1 | at org.eclipse.jetty.server.AbstractHttpConnection.headerComplet e(AbstractHttpConnection.java:926) jvm 1 | at org.eclipse.jetty.server.AbstractHttpConnection$RequestHandle r.headerComplete(AbstractHttpConnection.java:988) jvm 1 | at org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:6 35) jvm 1 | at org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.j ava:235) jvm 1 | at org.eclipse.jetty.server.AsyncHttpConnection.handle(AsyncHttp Connection.java:82) jvm 1 | at org.eclipse.jetty.io.nio.SelectChannelEndPoint.handle(SelectC hannelEndPoint.java:627) jvm 1 | at org.eclipse.jetty.io.nio.SelectChannelEndPoint$1.run(SelectCh annelEndPoint.java:51) jvm 1 | at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedT hreadPool.java:608) jvm 1 | at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedTh readPool.java:543) jvm 1 | at java.lang.Thread.run(Unknown Source) jvm 1 | 2013-05-27 23:52:11.265:WARN:oejs.ErrorPageErrorHandler:EXCEPTION jvm 1 | org.apache.jasper.JasperException: PWC6345: There is an error in invo king javac. A full JDK (not just JRE) is required jvm 1 | at org.apache.jasper.compiler.DefaultErrorHandler.jspError(Defau ltErrorHandler.java:92) jvm 1 | at org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDisp atcher.java:378) jvm 1 | at org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDisp atcher.java:119) jvm 1 | at org.apache.jasper.compiler.Jsr199JavaCompiler.compile(Jsr199J avaCompiler.java:208) jvm 1 | at org.apache.jasper.compiler.Compiler.generateClass(Compiler.ja va:384) jvm 1 | at org.apache.jasper.compiler.Compiler.compile(Compiler.java:453 ) jvm 1 | at org.apache.jasper.JspCompilationContext.compile(JspCompilatio nContext.java:625) jvm 1 | at org.apache.jasper.servlet.JspServletWrapper.service(JspServle tWrapper.java:374) jvm 1 | at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServle t.java:492) jvm 1 | at org.apache.jasper.servlet.JspServlet.service(JspServlet.java: 378) jvm 1 | at javax.servlet.http.HttpServlet.service(HttpServlet.java:848) jvm 1 | at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder. java:648) jvm 1 | at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHand ler.java:455) jvm 1 | at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedH andler.java:137) jvm 1 | at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHan dler.java:577) jvm 1 | at org.eclipse.jetty.server.session.SessionHandler.doHandle(Sess ionHandler.java:231) jvm 1 | at org.eclipse.jetty.server.handler.ContextHandler.doHandle(Cont extHandler.java:1072) jvm 1 | at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandl er.java:382) jvm 1 | at org.eclipse.jetty.server.session.SessionHandler.doScope(Sessi onHandler.java:193) jvm 1 | at org.eclipse.jetty.server.handler.ContextHandler.doScope(Conte xtHandler.java:1006) jvm 1 | at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedH andler.java:135) jvm 1 | at org.eclipse.jetty.server.Dispatcher.forward(Dispatcher.java:2 76) jvm 1 | at org.eclipse.jetty.server.Dispatcher.error(Dispatcher.java:112 ) jvm 1 | at org.eclipse.jetty.servlet.ErrorPageErrorHandler.handle(ErrorP ageErrorHandler.java:136) jvm 1 | at org.eclipse.jetty.server.Response.sendError(Response.java:348 ) jvm 1 | at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHand ler.java:538) jvm 1 | at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedH andler.java:137) jvm 1 | at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHan dler.java:559) jvm 1 | at org.eclipse.jetty.server.session.SessionHandler.doHandle(Sess ionHandler.java:231) jvm 1 | at org.eclipse.jetty.server.handler.ContextHandler.doHandle(Cont extHandler.java:1072) jvm 1 | at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandl er.java:382) jvm 1 | at org.eclipse.jetty.server.session.SessionHandler.doScope(Sessi onHandler.java:193) jvm 1 | at org.eclipse.jetty.server.handler.ContextHandler.doScope(Conte xtHandler.java:1006) jvm 1 | at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedH andler.java:135) jvm 1 | at org.eclipse.jetty.server.handler.ContextHandlerCollection.han dle(ContextHandlerCollection.java:255) jvm 1 | at org.eclipse.jetty.server.handler.HandlerCollection.handle(Han dlerCollection.java:154) jvm 1 | at org.eclipse.jetty.server.handler.HandlerWrapper.handle(Handle rWrapper.java:116) jvm 1 | at org.eclipse.jetty.server.Server.handle(Server.java:365) jvm 1 | at org.eclipse.jetty.server.AbstractHttpConnection.handleRequest (AbstractHttpConnection.java:485) jvm 1 | at org.eclipse.jetty.server.AbstractHttpConnection.headerComplet e(AbstractHttpConnection.java:926) jvm 1 | at org.eclipse.jetty.server.AbstractHttpConnection$RequestHandle r.headerComplete(AbstractHttpConnection.java:988) jvm 1 | at org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:6 35) jvm 1 | at org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.j ava:235) jvm 1 | at org.eclipse.jetty.server.AsyncHttpConnection.handle(AsyncHttp Connection.java:82) jvm 1 | at org.eclipse.jetty.io.nio.SelectChannelEndPoint.handle(SelectC hannelEndPoint.java:627) jvm 1 | at org.eclipse.jetty.io.nio.SelectChannelEndPoint$1.run(SelectCh annelEndPoint.java:51) jvm 1 | at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedT hreadPool.java:608) jvm 1 | at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedTh readPool.java:543) jvm 1 | at java.lang.Thread.run(Unknown Source) </code></pre>8389043173	0	MIniMagick::Image.write() saves files with varying permissions <p>I am writing a little photo gallery with Rails 3.0.11 and MiniMagick. </p> <pre><code>def JadeImage.rescale path,new_path,max_height=150 image = MiniMagick::Image.open(path) image.adaptive_resize(self.resize(image[:height],max_height))if image[:height] &gt; max_height image.write(new_path) end </code></pre> <p>I am using this to save two resized images from the same photo. One of the files gets saved with 644 permissions and all is right in the world. The other always get saved as 600 and as such can't be displayed in the webpage. </p> <p>For now, after saving them, I run a little utility to set everything in that directory as 644 so it works now.</p> <p>Is there any reason why this would occur?</p>83940918033	0	 <p>I ended up using a <code>BindingTargetVisitor</code> which covers the use cases that I need.</p> <p>Note that this solution works for our specific use case but might be too limited for your use case, depending on the type of bindings and injections that you use.</p> <pre><code>public class InjectionPointExtractor extends DefaultBindingTargetVisitor&lt;Object, InjectionPoint&gt; { private final Predicate&lt;TypeLiteral&lt;?&gt;&gt; filter; public InjectionPointExtractor(Predicate&lt;TypeLiteral&lt;?&gt;&gt; filter) { this.filter = filter; } @Override public InjectionPoint visit(UntargettedBinding&lt;?&gt; untargettedBinding) { return getInjectionPointForKey(untargettedBinding.getKey()); } @Override public InjectionPoint visit(LinkedKeyBinding&lt;?&gt; linkedKeyBinding) { return getInjectionPointForKey(linkedKeyBinding.getLinkedKey()); } @Override public InjectionPoint visit(ProviderKeyBinding&lt;?&gt; providerKeyBinding) { return getInjectionPointForKey(providerKeyBinding.getProviderKey()); } private InjectionPoint getInjectionPointForKey(Key&lt;?&gt; key) { if (filter.test(key.getTypeLiteral())) { return InjectionPoint.forConstructorOf(key.getTypeLiteral()); } return null; } } </code></pre> <p>We use the <code>filter</code> to filter only on classes defined in our packages. This gets the job done in a nice and clean fashion.</p> <p>If you don't use <code>@Inject</code> constructors but instead use Guice to set fields directly, you could use <a href="https://github.com/google/guice/wiki/CustomInjections" rel="nofollow noreferrer">TypeListener</a></p>8401879594	0	How should I start to learn JavaScript, jQuery, etc.? My programming knowledge is zero <p>I'm from a design background. My programming knowledge is zero. After learning XHTML and CSS I want to learn and get good command on JavaScript, jQuery, etc. How should I start?</p> <p>This will be my first attempt to programming. I can use and edit readymade available jQuery/JavaScript scripts, but I can't make my own and can't do high level editing in readymade scripts.</p> <p>Is there any other post on Stack Overflow, any link of start-up tutorial, or any book for my needs?</p> <p><strong>Edit 1:</strong></p> <p>This book will work best for me, "<a href="http://www.friendsofed.com/book.html?isbn=1590595335" rel="nofollow noreferrer">DOM Scripting: Web Design with JavaScript and the Document Object Model</a>".</p> <p><img src="http://www.friendsofed.com/img/cover/1590595335.jpg" alt="alt text"></p> <p><strong>Edit 2:</strong></p> <p>Will my design background and knowledge of XHTML CSS help me to learn JavaScript quickly?</p> <p>and is this correct? If I learn only jQuery then I will not be able to work with other JavaScript framework like <a href="http://en.wikipedia.org/wiki/MooTools" rel="nofollow noreferrer">MooTools</a>, <a href="http://en.wikipedia.org/wiki/Prototype_JavaScript_Framework" rel="nofollow noreferrer">Prototype</a>, etc. But if I learn core JavaScript then I would be able to work with all JavaScript frameworks and anything in JavaScript.</p>8419919278	0	SQL multiple replace <p>I want to read the company table and take out all possible suffixes from the name. Here's what I have so far:</p> <pre><code>declare @badStrings table (item varchar(50)) INSERT INTO @badStrings(item) SELECT 'company' UNION ALL SELECT 'co.' UNION ALL SELECT 'incorporated' UNION ALL SELECT 'inc.' UNION ALL SELECT 'llc' UNION ALL SELECT 'llp' UNION ALL SELECT 'ltd' select id, (companyname = Replace(name, item, '') FROM @badStrings) from companies where name != '' </code></pre>84236775266	0	 <p>to handle ALL worksheet, place this in ThisWorkbook code pane</p> <pre><code>Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range) If Not Intersect(Target, Sh.Columns(13)) Is Nothing Then MsgBox "Help Help" End If End Sub </code></pre> <p>or</p> <pre><code>Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range) If Target.Column = 13 Then MsgBox "Help Help" End If End Sub </code></pre> <p>Otherwise place the following in the code pane of the Sheet(s) you want to "handle" only</p> <pre><code>Private Sub Worksheet_Change(ByVal Target As Range) If Target.Column = 13 Then MsgBox "Help Help" End If End Sub </code></pre>8439569438	0	 <p>This is an example of code that works for me. It performs these operations:</p> <ol> <li>It splits the string based on whitespace, and each element is stored on an array of strings;</li> <li>It checks the size of each element of the array;</li> <li>If the size is == 4 (the number of characters of the postal code), then it checks (with a pattern) if the current element is a number;</li> <li><p>If the current element is a number, then this element and the next element (the city) is stored on an <a href="http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html" rel="nofollow">ArrayList</a>.</p> <pre><code>import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.*; public class split{ private List&lt;String&gt; newline = new ArrayList&lt;String&gt;(); public split(){ String myString = "Graaf Karel De Goedelaan 1 8500 Kortrijk"; String array[] = myString.split("\\s+"); for(int z = 0;z&lt;arr.length;z++){ int sizestr = array[z].length(); if(sizestr==4){/* if the generic string has 4 characters */ String expression = "[0-9]*"; CharSequence inputStr = array[z]; Pattern pattern = Pattern.compile(expression); Matcher matcher = pattern.matcher(inputStr); if(matcher.matches()){/* then if the string has 4 numbers, we have the postal code" */ newline.add(array[z]); /* now we add the postal code and the next element to an array list" */ newline.add(array[z+1]); } } } Iterator&lt;String&gt; itr = newline.iterator(); while (itr.hasNext()) { String element = itr.next(); System.out.println(element); /* prints "8500" and "Kortrijk" */ } } public static void main(String args[]){ split s = new split(); } } </code></pre></li> </ol> <p>For further info about the check of the string, take a look to this <a href="http://www.zparacha.com/best-way-to-check-if-a-java-string-is-a-number/#.T1TX_ZeA8vs" rel="nofollow">page</a>, and, for the ArrayList Iterator, see <a href="http://www.java2s.com/Code/JavaAPI/java.util/ArrayListiterator.htm" rel="nofollow">this</a>.</p> <p>I hope this can help to solve your problem.</p>84426775709	0	Fastest way to join multiple MVC projects into a single one <p>We have about 4 different MVC projects, in separate Solutions, with their own Controllers, Models and Views.</p> <p>We need to join all these projects into a single Project (Solution). The new project will have an entry point (Home Page), from which you can go to any of the existing projects.</p> <p>We will navigate from one project to another (one section to another - after integration) using simple navigation links.</p> <p>Is <code>Areas</code> a good solution for this approach?</p> <p>I read this <a href="http://stackoverflow.com/questions/1200424/multiple-asp-net-mvc-projects-that-builds-as-single-asp-net-mvc-application/1362621#1362621">post</a> but i don't understand what the solution from there is.</p>84526038374	0	 <p>You can make change in below css </p> <pre><code>.content { margin-top:50px;//added position:absolute;//changed clear: both; width:100px; height:50px; background:#D52100; } .click_menu{ width:100px; height:50px; float:left; color:#191919; text-align:center; position: absolute;// added z-index: 100;//added } </code></pre> <p><strong><a href="http://jsfiddle.net/kawadkarbk31/yy76mtmm/31/" rel="nofollow">Demo</a></strong></p>84638934847	0	 <p>The line of code <code>num1, num2 = num2, (num1 + num2)</code> is assigning two variables at once. <code>num1</code> gets the old value of <code>num2</code>, while <code>num2</code> gets the new value <code>(num1 + num2)</code>.</p> <p>Having multiple assignments on a single line of code allows you to do both operations without needing to use a temporary variable. For example, this won't work:</p> <pre><code>num1 = num2 num2 = (num1 + num2) </code></pre> <p>because <code>num1</code> has been overwritten with a new value before the addition step, so <code>num2</code> will be assigned the wrong value. The one-line version is equivalent to:</p> <pre><code>temp = (num1 + num2) num1 = num2 num2 = temp </code></pre> <p>For reference, this is called <a href="https://en.wikipedia.org/wiki/Assignment_(computer_science)#Parallel_assignment" rel="nofollow"><strong>parallel assignment</strong></a> or sometimes <strong>multiple assignment</strong>.</p>84717099774	0	 <p>Try this: </p> <pre><code> String strEvents = new JSONArray(apiResponse).getJSONObject(0).toString(); String strVenues= new JSONArray(apiResponse).getJSONObject(1).toString(); jsonArray = new JSONObject(strEvents).getJSONArray("fql_result_set"); jsonVenues = new JSONObject(strVenues).getJSONArray("fql_result_set"); </code></pre>8484159189	0	Rails Bundler on windows refuses to install hpricot (even on manual gem install get Error: no such file to load -- hpricot) <p>Upgraded to rails 3, and using Bundler for gems, in a mixed platform development group. I am on Windows. When I run Bundle Install it completes succesfully but will not install hpricot. The hpricot line is:</p> <pre><code>gem "hpricot", "0.8.3", :platform =&gt; :mswin </code></pre> <p>also tried</p> <pre><code>gem "hpricot", :platform =&gt; :mswin </code></pre> <p>Both complete fine but when I try to do a "bundle show hpricot" I get:</p> <pre><code>Could not find gem 'hpricot' in the current bundle. </code></pre> <p>If I do a run a rails console and try "require 'hpricot'" I get: </p> <pre><code>LoadError: no such file to load -- hpricot </code></pre> <p>I have manually installed hpricot as well, and still get the above error. This worked fine before moving to rails 3.</p>84928226538	0	 <p>Try setting your text to "My name is John" outside of the button click, perhaps in a <code>Form.Init</code> handler, then removing <code>txtOutPut.Text = "My name is John"</code> from <code>btnClickMe_Click1</code> </p> <p>What's happening here is the button click is changing the text first to "My name is John", then changing it to "and this is my first VB program" and the change happens too quickly for it to be visible. </p>85036968760	0	 <p>As mentioned by Turnip there is -webkit filter for that. However it is more convenient to use SVG:</p> <pre><code>&lt;svg&gt; &lt;pattern id="mypattern" patternUnits="userSpaceOnUse" width="750" height="800"&gt; &lt;image width="750" height="800" xlink:href="https://placekitten.com/g/100/100"&gt;&lt;/image&gt; &lt;/pattern&gt; &lt;text x="0" y="80" class="fa fa-5x" style="fill:url(#mypattern);"&gt;&amp;#xf0f4;&lt;/text&gt; &lt;/svg&gt; </code></pre> <p>You just need to include icon character in SVG</p> <p><a href="https://jsfiddle.net/xd6gny56/" rel="nofollow">Demo fiddle</a></p>85137612974	0	 <p>I've spent two days fighting with it. Adding "*" namespace to xPath solved the issue for me (my input file did not have any).</p> <pre><code>return &lt;label&gt;{fn:doc(fn:concat($collection, '/', $child))//*:testResult/text()}&lt;/label&gt; </code></pre>8522107911	0	Safe class imports from JAR Files <p>Consider a scenario that a java program imports the classes from jar files. If the same class resides in two or more jar files there could be a problem.</p> <blockquote> <ol> <li><p>In such scenarios what is the class that imported by the program? Is it the class with the older timestamp??</p></li> <li><p>What are the practices we can follow to avoid such complications.</p></li> </ol> </blockquote> <p>Edit : This is an example. I have 2 jar files my1.jar and my2.jar. Both the files contain com.mycompany.CrazyWriter</p>85318630530	0	 <p>You can use <code>ValueProvider.GetValue("HasEditPermission").RawValue</code> to access the value. </p> <p><strong>Controller:</strong></p> <pre><code>public class BController : Controller { public ActionResult Index() { ViewBag.HasEditPermission = Boolean.Parse( ValueProvider.GetValue("HasEditPermission").RawValue.ToString()); return PartialView(); } } </code></pre> <p><strong>View:</strong></p> <pre><code>... @if (ViewBag.HasEditPermission) { // some html rendering } ... </code></pre> <p><strong>Update:</strong></p> <p><code>Request.Params</code> gets a combined collection of QueryString, Form, Cookies, and ServerVariables items not RouteValues.</p> <p>In </p> <pre><code>@Html.Action("Index", "BController", new { HasEditPermission = true }) </code></pre> <p><code>HasEditPermission</code> is a <code>RouteValue</code>. </p> <p>you can also try something like this </p> <pre><code>ViewContext.RouteData.Values["HasEditPermission"] </code></pre> <p>in your View and subsequent child action views as well..</p>85439643679	0	 <pre><code>var orders = JSON.parse($('#orderData')); console.log(orders[0].value); </code></pre>8558984472	0	 <p>Indeed, it's possible. I suggest you to use a @property/@synthesize object on the receiver UIViewController (the one with the UIWebView) that it's initialized/filled from the calling viewController with the search string that you want to use.</p>8563092562	0	 <p>A couple of ways:</p> <p>In your web.config on the customErrors mode set the <a href="http://msdn.microsoft.com/en-us/library/system.web.configuration.customerrorssection.redirectmode.aspx" rel="nofollow noreferrer"><code>redirectMode</code></a> to <code>ResponseRewrite</code> - this removes the 302 redirect from the server to the error page - this also has the happy coincidence that uses can easily see what the original page they requested was, and can retry with an F5 if that's likely to resolve the issue.</p> <p>If you are hooking into the ApplicationError event, make sure that rather than redirecting to your error pages you use <code>Server.Transfer</code> instead.</p> <p>I have the following in one of my web.configs:</p> <pre><code>&lt;customErrors mode="On" defaultRedirect="ErrorHandler.aspx" redirectMode="ResponseRewrite"&gt; </code></pre> <p>Then in my ErrorHandler page I check for the last error from the server, and configure those:</p> <pre><code> var serverError = Server.GetLastError(); var error = serverError as HttpException; int errorCode; string errorMessage; if (null != error) { errorCode = error.GetHttpCode(); errorMessage = error.GetHtmlErrorMessage(); } else { errorCode = 404; errorMessage = "Page not found"; } Response.StatusCode = errorCode; Response.StatusDescription = errorMessage; </code></pre> <p>Obviously you may want to do additional processing - for example before I do all this I'm comparing the original request with my Redirects database to check for moved content/vanity urls, and only falling back to this if I couldn't find a suitable redirect.</p>85722708706	0	Time taken to reconnect to a BLE peripheral after restored by State Restoration <p>Has anyone used State Restoration to reconnect to a peripheral? if so do you have any feel for the how long it took to reconnect?</p> <p>It's abit of a difficult question, as it is not easy to tell when to start timing from. </p> <p>It should be when the iDevice gets in range of its peripheral for which the connection request has been issued.</p>8587061264	0	Access a flash object from jQuery <p>I am using swfobject 2 to dynamically embed my flash... let's call my object "swfContent"</p> <p>I have tried to use $('swfContent') and $("#swfContent") to access my swf object, but no luck.</p> <p>Thanks!</p>8599369161	0	 <p>The Visual Studio Visualizer's architecture requires all Visualizers to be Modal windows, so the answer is No. Your best bet is to copy/paste the text into a diff tool. </p>86036704302	0	 <p>The error <code>0000052D</code> is a <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms681385%28v=vs.85%29.aspx" rel="nofollow">system error code</a>. Specifically, it means:</p> <blockquote> <p>ERROR_PASSWORD_RESTRICTION</p> <p>1325 (0x52D)</p> <p>Unable to update the password. The value provided for the new password does not meet the length, complexity, or history requirements of the domain.</p> </blockquote> <p>The problem would seem to be that the account you're enabling has a password-policy applied to it, whereby enabling it that password-policy would not be met.</p> <p>I would first figure out what the password policy is for the account, then set the password to something that meets that policy criteria before flipping the bit to enable it.</p> <p>If, however, you really want the user to be able to login with no password then the password should be set to null. But I'm not sure under what circumstances that would be desirable. </p>8619729428	0	 <p>I think you're on the right track. Instead of grouping FlightTimes by FlightType, try building FlightTimeResults and grouping those by FlightType instead:</p> <pre><code>var results = from ft in schedules.FlightTimes group new FlightTimeResult { FlightTimeData = ft, FlagRedeye = ft.DepartureTime.Hour &gt;= 0 &amp;&amp; ft.DepartureTime.Hour &lt; 6 } by ft.FlightType.ToString() into groupedFlights select groupedFlights; </code></pre>86225581405	0	 <p>I'm not quite sure whether I have completely understood what the problem here is! But you can simply use a <code>Dictionary</code> to hold string values of each 45-degree slice and check it against the word user drags.</p> <pre><code>Dictionary&lt;int, string&gt; dict = new Dictionary&lt;int, string&gt;(); dict.Add(1, "Eraser"); dict.Add(2, "Glue"); dict.Add(3, "Pen"); dict.Add(4, "Scissors"); dict.Add(5, "Stapler"); dict.Add(6, "Sharpener"); dict.Add(7, "Ruler"); dict.Add(8, "Pencil"); </code></pre> <p>And change your code to:</p> <pre><code>double degree = rng.Next(360, 720); double resultAngle = degree - 360; int num = (int)Math.Ceiling(resultAngle / 45); </code></pre> <p>Then, the name of the element the pointer is currently pointing at would be:</p> <pre><code>string currentElem = dict[num]; </code></pre>86313061209	0	Stopping a CSS animation but letting its current iteration finish <p>I have the following HTML:</p> <pre><code>&lt;div class="rotate"&gt;&lt;/div&gt;​ </code></pre> <p>And the following CSS:</p> <pre><code>@-webkit-keyframes rotate { to { -webkit-transform: rotate(360deg); } } .rotate { width: 100px; height: 100px; background: red; -webkit-animation-name: rotate; -webkit-animation-duration: 5s; -webkit-animation-iteration-count: infinite; -webkit-animation-timing-function: linear; }​ </code></pre> <p>I want to know if there is a way (using JavaScript) to stop the animation but let it finish its current iteration (preferably by changing one or a few CSS properties). I have tried setting <code>-webkit-animation-name</code> to have a blank value but that causes the element to jump back to its original position in a jarring fashion. I have also tried setting <code>-webkit-animation-iteration-count</code> to <code>1</code> but that does the same thing.</p>864267110	0	 <p>When you specify the DestinationFolder for the Copy task, it takes all items from the SourceFiles collection and copies them to the DestinationFolder. This is expected, as there is no way for the Copy task to figure out what part of each item's path needs to be replaced with the DestinationFolder in order to keep the tree structure. For example, if your SourceDir collection is defined like this:</p> <pre><code>&lt;ItemGroup&gt; &lt;SourceDir Include="$(Source)\**\*" /&gt; &lt;SourceDir Include="E:\ExternalDependencies\**\*" /&gt; &lt;SourceDir Include="\\sharedlibraries\gdiplus\*.h" /&gt; &lt;/ItemGroup&gt; </code></pre> <p>What would you expect the destination folder tree look like?</p> <p>To preserve the tree, you need to do identity transformation and generate one destination item for each item in the SourceFiles collection. Here's an example:</p> <pre><code>&lt;Copy SourceFiles="@(Compile)" DestinationFiles="@(Compile-&gt;'$(DropPath)%(Identity)')" /&gt; </code></pre> <p>The Copy task will take the each item in the SourceFiles collection, and will transform its path by replacing the part before the ** in the source item specification with $(DropPath).</p> <p>One could argue that the DestinationFolder property should have been written as a shortcut to the following transformation:</p> <pre><code>&lt;Copy SourceFiles="@(Compile)" DestinationFiles="@(Compile-&gt;'$(DestinationFolder)%(Identity)')" /&gt; </code></pre> <p>Alas, that would prevent the deep copy to flat folder scenario that you are trying to avoid, but other people might using in their build process.</p>8653500096	0	Lost transaction with JPA unique constraint? <p>I have a field with an unique constraint:</p> <pre><code>@Column(unique=true) private String uriTitle; </code></pre> <p>When I try to save two entities with the same value, I get an exception - but another exception than I exected:</p> <pre><code>java.lang.IllegalStateException: &lt;|Exception Description: No transaction is currently active at org.eclipse.persistence.internal.jpa.transaction.EntityTransactionImpl.rollback(EntityTransactionImpl.java:122) at com.example.persistence.TransactionFilter.doFilter(TransactionFilter.java:35) </code></pre> <p>The questionable filter method looks like this:</p> <pre><code>public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { EntityManager entityManager = ThreadLocalEntityManager.get(); EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); try { chain.doFilter(request, response); transaction.commit(); } catch (Throwable t) { transaction.rollback(); // line 35, mentioned in the exception throw new RuntimeException(t); } finally { entityManager.close(); ThreadLocalEntityManager.reset(); } } </code></pre> <p>... and the ThreadLocalEntityManager like this:</p> <pre><code>public class ThreadLocalEntityManager { private static EntityManagerFactory entityManagerFactory = null; private static final ThreadLocal&lt;EntityManager&gt; entityManager = new ThreadLocal&lt;EntityManager&gt;() { @Override protected EntityManager initialValue() { return entityManagerFactory.createEntityManager(); } }; private ThreadLocalEntityManager() {} public static synchronized void init(String persistenceUnit) { requireNotNull(persistenceUnit); requireState(entityManagerFactory == null, "'init' can be called only " + "once."); entityManagerFactory = Persistence.createEntityManagerFactory(persistenceUnit); } public static EntityManager get() { requireState(entityManagerFactory != null, "Call 'init' before calling " + "'get'"); return entityManager.get(); } public static void reset() { entityManager.remove(); } } </code></pre> <p>I wrapped the call to <code>save</code> with <code>try ...catch</code> to handle the unique constraint violation, but that doesn't work:</p> <pre><code>try { ThreadLocalEntityManager.get().persist(article); // article is constrained } catch(Throwable t) { t.printStackTrace(); } </code></pre> <p>Any idea why there is no transaction? What is the correct way to handle a unique constraint violation?</p>86636343298	0	semantic-ui search following link when pressing 'enter' <p>I want to allow users to navigate the search tool only with the keyboard which means that they navigate search results with arrows and, when they press 'enter', it follows the item's link.</p> <p>How could this be done ?</p> <p><a href="http://semantic-ui.com/modules/search.html#using-different-response-fields" rel="nofollow">Here is an example from the docs, with a GitHub search box</a></p>8679378795	0	 <p>You can work with fancybox Ajax or Iframe and load your HTML page into box.</p>8689100372	0	Javascript: obj.fn() vs x=obj.fn;x() <p>Take a look at this snippet:</p> <pre><code>var obj = { fn: function () {return this;} }; var x = obj.fn; obj.fn(); // returns obj x(); // returns window (in the browser) </code></pre> <p>I'm curious why <code>obj.fn()</code> is different from <code>x=obj.fn; x()</code>. Is there a special case for attribute lookup directly followed by a function call within a single expression - or there is some more complex magic going on under the hood (like with <a href="http://docs.python.org/reference/datamodel.html#implementing-descriptors" rel="nofollow">descriptor protocol</a> in Python) ?</p>8693725123	0	 <p>You cannot programatically fill in login information, that is against the Facebook terms and conditions. You can, however, authenticate as an application as opposed to a user. Use the following method:</p> <pre><code>Make a GET request to: https://graph.facebook.com/oauth/access_token?grant_type=client_credentials&amp;client_id=CLIENT_ID&amp;client_secret=CLIENT_SECRET Facebook returns: access_token=SOME_TOKEN Use this token as your access token and it should allow you to access the group. I have tested this with my application and can confirm it works. You request the wall information via the request: https://graph.facebook.com/GROUP_ID/feed?access_token=SOME_TOKEN </code></pre> <p>This will not pop up any login screens as you are not required to be logged in to view a public group. Ensure your privacy settings are public for the group as well.</p>87034589096	0	Instagram Media Endpoint Paging <p>I'm currently looking at reading out posts and related json data from a given number of Instagram users using the following URL:</p> <p><a href="https://www.instagram.com/" rel="nofollow">https://www.instagram.com/</a>/media/</p> <p>This will only bring back the latest 20 posts. I have done some hunting around and I am unable to see how to form the url to bring back the next 20 results. I've seen some places that have suggested using max_timestamp, but I can't see how to make this work.</p> <p>For various reasons I do not wish to use the standard Instagram API.</p>87115831268	0	 <p>There is a "cacheDirectory" in your "data/package_name" directory. </p> <p>If you want to store something in that cache memory,</p> <pre><code>File cacheDir = new File(this.getCacheDir(), "temp"); if (!cacheDir.exists()) cacheDir.mkdir(); </code></pre> <p>where <strong>this</strong> is context.</p>87218177680	0	 <p>try this</p> <pre><code>Dim HttpReq As HttpWebRequest = DirectCast(WebRequest.Create("http://...."), HttpWebRequest) Using HttpResponse As HttpWebResponse = DirectCast(HttpReq.GetResponse(), HttpWebResponse) Using Reader As New BinaryReader(HttpResponse.GetResponseStream()) Dim RdByte As Byte() = Reader.ReadBytes(1 * 1024 * 1024 * 10) Using FStream As New FileStream("FileName.extension", FileMode.Create) FStream.Write(RdByte, 0, RdByte.Length) End Using End Using End Using </code></pre>8738334422	0	 <p>I would personally use an interface as suggested, but in case you didn't have access to who is calling you (such as third party .dll) then you can accept an argument of type object:</p> <pre><code> /// &lt;summary&gt; /// Draw any type of object if the objec type is supported. /// Circles, Squares, etc. /// &lt;/summary&gt; /// &lt;param name="objectToDraw"&gt;&lt;/param&gt; public void Draw(object objectToDraw) { // get the type of object string type = objectToDraw.GetType().ToString(); switch(type) { case "Circle": // cast the objectToDraw as a Circle Circle circle = objectToDraw as Circle; // if the cast was successful if (circle != null) { // draw the circle circle.Draw(); } // required break; case "Square": // cast the object as a square Square square = objectToDraw as Square; // if the square exists if (square != null) { // draw the square square.Draw(); } // required break; default: // raise an error throw new Exception("Object Type Not Supported in Draw method"); } } </code></pre>8744005032	0	 <p>If you're augmenting rows that already exist you'll want to use an UPDATE statement.</p>87522092822	0	 <p>There is no official release of OpenCV for system without OS. OpenCV library is available for Windows, linux, mac, Android and Ios operating system.</p> <p><a href="http://www.societyofrobots.com/robotforum/index.php?topic=2278.0" rel="nofollow">Here</a> you can find a link which explain the challenges of having OpenCV running on microcontrollers</p>87639467508	0	 <p>try this solution:</p> <pre><code> quest.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(ActionEvent e) { JButton b = (JButton)e.getSource(); for(Component c : yourPanel.getComponents()){ if(c instanceof JButton &amp;&amp; !c.equals(b)){ c.setEnabled(false); } } } }); </code></pre>87721394141	0	Database table structure for storing SSO information for FB or Google+ <p>I have a web application that I would like to add single sign on capability using user's Facebook or Google+/Google App account. </p> <p>I have a <code>USERS</code> table that stores users login information. All users are required to have a record in this table no matter if they signed up using FB or Google+.</p> <p>I am trying to figure out the information that I need to store in the database in order to link <code>USERS</code> table records to FB or Google information. </p> <p>Facebook <a href="https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow#token" rel="nofollow">documentation states</a>:</p> <blockquote> <p>the app should store the token in a database along with the <code>user_id</code> to identify it.</p> </blockquote> <p>So should I create a table called <code>SSO_LOOKUP</code> with following columns:</p> <ul> <li>USER_ID // user's id that links to my <code>USER</code> table</li> <li>PROVIDER_ID // user's FB or Google account id</li> <li>PROVIDER_TYPE // indicates if it is Google, FB, Twitter, etc. </li> <li>ACCESS_TOKEN</li> </ul>8787695751	0	 <p>Note that <code>@</code> is already a 1-char infix operator to concat lists.</p>87925349880	0	GetJsonObject from a for looped JsonArray show syntax error <pre><code> JsonObject jObj = JsonObject.Parse(json); JsonArray jArr = jObj.GetNamedArray("records"); for (int i = 0; i &lt; jArr.Count; i++) { JsonObject innerObj = jArr.GetObjectAt(i); mData[i] = new Data(innerObj .GetNamedString("countryName"), innerObj .GetNamedString("countryId"), innerObj.GetNamedString("callPrefix"), innerObj .GetNamedString("isoCode")); } </code></pre> <p>Visual studio show syntax error: the best overloaded method for jArr.GetObjectAt(uint) has an invalid argument</p>88025614224	1	How to print a variable from a derived class? <p>I know there are similar questions on this topics but none of them seem to apply to my case Why would the following code print None and not True? Thanks</p> <pre><code>class A(object): flag = None @classmethod def set_flag(cls): cls.flag = True class B(A): @classmethod def print_super_flag(cls): print cls.__bases__[0].flag # This prints None print super(B, cls).flag # This also if __name__ == "__main__": b = B() b.set_flag() b.print_super_flag() </code></pre>88119984966	0	 <p>No - there are separate endpoints for web services.</p> <p>Look in ADFS under Services / Endpoints. Note that not all are enabled by default.</p> <p>I blogged about this - <a href="http://nzpcmad.blogspot.co.nz/2013/04/adfs-wcf-web-service.html" rel="nofollow">ADFS : WCF web service</a></p>88223362695	0	Trouble about assign char pointer in C <p>I have a simple C program about assign char pointer and malloc like this</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; int main() { char str[] = "0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789"; char* str1 = malloc(sizeof(char*)); strcpy(str1, str); printf("%s\n\n", str1); char* str2 = malloc(sizeof(char*)); str2 = str1; printf("%s\n", str2); return 0; } </code></pre> <p>And the result is:</p> <pre><code>0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 01! </code></pre> <p>So why the str2 just gets 25 characters from str1? And where is the "!" (in the end of str2) come from?</p> <p>Could you help me? Thanks!</p>8837650906	0	 <p><strong>Option 1:</strong></p> <pre><code>class Example { public: Example( std::string str, const std::complex&lt;float&gt;&amp; v ): m_str( std::move(str) ), m_v( v ) { } /* other methods */ private: std::string m_str; std::complex&lt;float&gt; m_v; }; </code></pre> <p>This has pretty good performance and is easy to code. The one place it falls a little short of the optimum is when you bind an lvalue to <code>str</code>. In this case you execute both a copy construction and a move construction. The optimum is only a copy construction. Note though that a move construction for a <code>std::string</code> should be very fast. So I would start with this.</p> <p>However if you really need to pull the last cycles out of this for performance you can do:</p> <p><strong>Option 2:</strong></p> <pre><code>class Example { public: Example( const std::string&amp; str, const std::complex&lt;float&gt;&amp; v ): m_str( str ), m_v( v ) { } Example( std::string&amp;&amp; str, const std::complex&lt;float&gt;&amp; v ): m_str( std::move(str) ), m_v( v ) { } /* other methods */ private: std::string m_str; std::complex&lt;float&gt; m_v; }; </code></pre> <p>The main disadvantage of this option is having to overload/replicate the constructor logic. Indeed this formula will become unrealistic if you have more than one or two parameters that you need to overload between <code>const&amp;</code> and <code>&amp;&amp;</code>.</p>88410292660	0	Getting Windows 8 Live ID: GetPrincipalNameAsync() returns empty string <p>I'm trying to use the method </p> <pre><code>Windows.System.UserProfile.UserInformation.GetPrincipalNameAsync() </code></pre> <p>to get Windows Live ID, but it returns an empty string, anyone knows why?</p> <p>Thanks a lot.</p>88538896485	0	 <p>I guess the problem is that <code>CD V:\</code> is not enough. If you are on C:\ <code>CD V:\</code> won't move the scope to V:. To achieve this you have to add the <code>/d</code> switch to the <code>CD</code> command:</p> <pre><code>... cd /d V:\ ... </code></pre>88630187285	0	 <p>Values of <code>background-size</code> property should be like <code>Xpx Ypx</code>. Try change Your last line to this:</p> <pre><code>t.getBody().style.backgroundSize = newWidth+"px "+newHeight+"px"; </code></pre>88718876763	0	Android Calendar RRULE - Events not being created in the calendar <p>I would appreciate any possible help from people that have already experienced the same problem.</p> <p><a href="https://groups.google.com/forum/#!searchin/android-developers/rrule/android-developers/4di2k6c49XY/EiS5FRqcwxoJ" rel="nofollow">https://groups.google.com/forum/#!searchin/android-developers/rrule/android-developers/4di2k6c49XY/EiS5FRqcwxoJ</a></p> <p>Thanks.</p> <p>EDIT: Problem found: <a href="https://code.google.com/p/android/issues/detail?id=60589" rel="nofollow">https://code.google.com/p/android/issues/detail?id=60589</a></p>88813016625	0	 <p>Assuming your xml code is saved to "test.xml":</p> <pre><code>from xml.dom.minidom import parse dom1 = parse("test.xml") for node in dom1.getElementsByTagName('t'): print node.childNodes[0].nodeValue </code></pre> <p>This should print the inner values of all tags "". </p>88934390723	0	 <p>From <a href="https://docs.oracle.com/javase/8/docs/api/java/awt/KeyEventDispatcher.html" rel="nofollow">the documentation for <code>dispatchKeyEvent</code></a>:</p> <blockquote> <p>Return <code>true</code> if the KeyboardFocusManager should take no further action with regard to the KeyEvent; <code>false</code> otherwise</p> </blockquote> <p>Also you can directly consume the event in your <code>dispatchKeyEvent</code> implementation when no further processing of the event is required.</p> <pre><code>e.consume(); </code></pre> <p>Suggestion of @MadProgrammer is also important. Using of global event processing possibilities is the last choice.</p>89030962416	0	 <p>If you don't want to use <code>RestClient::Resource</code>, you can include basic auth in a request like this:</p> <p><code>RestClient::Request.execute method: :get, url: url, user: 'username', password: 'secret'</code></p> <p>The trick is not to use the <code>RestClient.get</code> (or <code>.post</code>, <code>.put</code> etc.) methods since all options you pass in there are used as headers.</p> <p>I just did a quick writeup on this over here: <a href="https://www.krautcomputing.com/blog/2015/06/21/how-to-use-basic-authentication-with-the-ruby-rest-client-gem/" rel="nofollow">https://www.krautcomputing.com/blog/2015/06/21/how-to-use-basic-authentication-with-the-ruby-rest-client-gem/</a></p>89111361072	0	input not submitting data to mysql <p>I'm making a very simple groups(like vb forum groups). I've coded all of it, after getting some errors and fixing it now it's showing the page without errors.</p> <p>The problem now is the data ISN'T being inserted to mysql. When putting the input into forms and then pressing create it goes to "?update=update" and echo's the success message, but doesn't submit to mysql.</p> <p>Code:</p> <pre><code>&lt;? if(!$update) { ?&gt; &lt;form action="make_group.php?update=update" method="post"&gt; Group name: &lt;br /&gt; &lt;input name="title" type="text" size="30" /&gt; &lt;br /&gt; Group picture: &lt;br /&gt; &lt;input name="picture" type="text" size="30" /&gt; &lt;br /&gt; Group desc: &lt;br /&gt; &lt;textarea name="desc" cols=30 rows=10 wrap=physical&gt;&lt;/textarea&gt; &lt;br /&gt; &lt;input type="submit" value="Create" /&gt; &lt;? } elseif($update==update) { $username = $_SESSION[usr_name]; $action = "made a group"; $title = clean($_POST[title]); $desc = clean($_POST[desc]); $pictures = clean($_POST[pictures]); $updateemail = mysql_query("insert into usr_groups(username, title, desc, picture) values('$username', '$title', '$desc', '$picture')"); $result = @mysql_query($qry2); echo("Your group has been created"); } ?&gt; </code></pre> <p>Above page code</p> <pre><code>&lt;? session_start(); include("config.php"); $ip = $_SERVER['REMOTE_ADDR']; $sqlcontent = mysql_query("select * from usr_config"); $content = mysql_fetch_array($sqlcontent); if(!isset($_SESSION[usr_name]) || empty($_SESSION[usr_name]) || !isset($_SESSION[usr_level]) || empty($_SESSION[usr_level])) { session_destroy(); session_unset(); die(' &lt;tr&gt; &lt;td&gt;&lt;meta http-equiv="REFRESH" content="0;url=/index.php"&gt;&lt;/HEAD&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/div&gt; &lt;/body&gt;'); } include("func.php"); $update = clean($_GET[update]); $getprof = mysql_query("select * from usr_users where username = '$_SESSION[usr_name]'"); $prof = mysql_fetch_array($getprof); ?&gt; </code></pre>89212528564	0	friend function returning reference to private data member <p>I have two questions about the following code. </p> <pre><code>class cls{ int vi; public: cls(int v=37) { vi=v; } friend int&amp; f(cls); }; int&amp; f(cls c) { return c.vi; } int main(){ const cls d(15); f(d)=8; cout&lt;&lt;f(d); return 0; } </code></pre> <ol> <li>Why does it compile, since f(d) = 8 attemps to modify a const object?</li> <li>Why does it still print 15, even after removing the const attribute?</li> </ol>8936369681	0	 <p>Initially load part of data in your list view. You have to use concept of <code>Handler</code>. onclick event you have to send message to handler inside handler you have to write the logic to load your full data and call <code>notifydataSetChanged</code> method</p> <p>have a look on the sample code below. Initially user is able to see some part of list. If user cvlicks on any list item then list user is able to see the whole list view. It is similar to as that you are expecting. </p> <h2>Sample Code</h2> <pre><code>import java.util.ArrayList; import android.app.ListActivity; import android.content.res.Configuration; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; public class MyListView extends ListActivity { ArrayList&lt;String&gt; pens = new ArrayList&lt;String&gt;(); ArrayAdapter arrayAdapter = null; private static final byte UPDATE_LIST = 100; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); pens.add("MONT Blanc"); pens.add("Gucci"); pens.add("Parker"); arrayAdapter = new ArrayAdapter&lt;String&gt;(this, android.R.layout.simple_list_item_1, pens); setListAdapter(arrayAdapter); getListView().setTextFilterEnabled(true); ListView lv = getListView(); lv.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView&lt;?&gt; arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub System.out.println("..Item is clicked.."); Message msg = new Message(); msg.what = UPDATE_LIST; updateListHandler.sendMessage(msg); } }); // System.out.println("....g1..."+PhoneNumberUtils.isGlobalPhoneNumber("+912012185234")); // System.out.println("....g2..."+PhoneNumberUtils.isGlobalPhoneNumber("120121852f4")); } @Override public void onConfigurationChanged(Configuration newConfig) { // TODO Auto-generated method stub super.onConfigurationChanged(newConfig); System.out.println("...11configuration is changed..."); } void addMoreDataToList() { pens.add("item1"); pens.add("item2"); pens.add("item3"); } protected void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); Object o = this.getListAdapter().getItem(position); String pen = o.toString(); Toast.makeText(this, id + "You have chosen the pen: " + " " + pen, Toast.LENGTH_LONG).show(); } private Handler updateListHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case UPDATE_LIST: addMoreDataToList(); arrayAdapter.notifyDataSetChanged(); break; } ; }; }; } </code></pre> <p>Thanks Deepak</p>89418350059	0	 <p>A web proxy is not normally defined by <em>just</em> a port, but is usually a full host name. Charles is very likely installed on localhost. Therefore the following adjustment may work for you:</p> <pre><code>@agent ||= Mechanize.new do |agent| agent.set_proxy("localhost", 8888) end </code></pre>895410752	0	 <p>See <a href="http://dotnetslackers.com/articles/designpatterns/InversionOfControlAndDependencyInjectionWithCastleWindsorContainerPart2.aspx" rel="nofollow noreferrer">Inversion of Control and Dependency Injection with Castle Windsor Container - Part II</a> at DotNetSlackers. It shows how to pass an array of the same service interface to an object.</p>8962150387	0	 <p>Probably both elements are linked by a ID..</p>8976229054	0	Unable to load webview in tab view <p>I have no idea why my webview is unable to load in my tabhost/tabwidget. For the tabhost/tabwidget, I am using the tutorial that was provided by Android Developer. Also, in my logcat, the warning seems to be at the tab1Activity.java, pointing the warning to "wv.loadDataWithBaseURL("http://lovetherings.livejournal.com/961.html", myString, "text/html", "UTF-8", "about:blank"); " </p> <p>Below are my codes. Can anyone help me? Thanks so much in advance! :D </p> <p>Here is my main.xml </p> <pre><code> &lt;LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="5dp"&gt; &lt;TabWidget android:id="@android:id/tabs" android:layout_width="fill_parent" android:layout_height="wrap_content" /&gt; &lt;FrameLayout android:id="@android:id/tabcontent" android:layout_width="fill_parent" android:layout_height="fill_parent" &gt; &lt;WebView android:id="@+id/webview" android:layout_width="fill_parent" android:layout_height="fill_parent" /&gt; &lt;/FrameLayout&gt; &lt;/LinearLayout&gt; </code></pre> <p> </p> <p>My main activity</p> <pre><code>public class HelloTabWidgetMain extends TabActivity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Resources res = getResources(); // Resource object to get Drawables TabHost tabHost = getTabHost(); // The activity TabHost TabHost.TabSpec spec; // Resusable TabSpec for each tab Intent intent; // Reusable Intent for each tab // Create an Intent to launch an Activity for the tab (to be reused) intent = new Intent().setClass(this, ArtistsActivity.class); // Initialize a TabSpec for each tab and add it to the TabHost spec = tabHost.newTabSpec("tab1").setIndicator("tab1", res.getDrawable(R.drawable.ic_tab_tab1)) .setContent(intent); tabHost.addTab(spec); // Do the same for the other tabs intent = new Intent().setClass(this, tab2Activity.class); spec = tabHost.newTabSpec("tab2").setIndicator("tab2", res.getDrawable(R.drawable.ic_tab_tab2)) .setContent(intent); tabHost.addTab(spec); intent = new Intent().setClass(this, tab3Activity.class); spec = tabHost.newTabSpec("tab3").setIndicator("tab3", res.getDrawable(R.drawable.ic_tab_tab3)) .setContent(intent); tabHost.addTab(spec); tabHost.setCurrentTab(0); } </code></pre> <p>}</p> <p>And my tab activity (where I would want my webview contents to be displayed)</p> <pre><code>public class tab1Activity extends Activity{ WebView wv; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); try { URL url = new URL("http://lovetherings.livejournal.com/961.html"); // Make the connection URLConnection conn = url.openConnection(); BufferedReader reader = new BufferedReader( new InputStreamReader(conn.getInputStream())); // Read the contents line by line (assume it is text), // storing it all into one string String content =""; String line = reader.readLine(); while (line != null) { content += line + "\n"; line = reader.readLine(); } reader.close(); String myString = content.substring(content.indexOf("&lt;newcollection&gt;")); int start = myString.indexOf("&lt;newcollection&gt;"); if (start &lt; 0) { Log.d(this.toString(), "collection start tag not found"); } else { int end = myString.indexOf("&lt;/newcollection&gt;", start) + 8; if (end &lt; 0) { Log.d(this.toString(), "collection end tag not found"); } else { myString = "&lt;html&gt;&lt;body&gt;" + myString.substring(start, end) + "&lt;/body&gt;&lt;/html&gt;"; } WebView wv = (WebView)findViewById(R.id.webview); wv.loadDataWithBaseURL("http://lovetherings.livejournal.com/961.html", myString, "text/html", "UTF-8", "about:blank"); } } catch (Exception ex) { ex.printStackTrace(); // Display the string in txt_content //TextView txtContent = (TextView)findViewById(R.id.txt_content); //txtContent.setText(myString); } } </code></pre> <p>}</p> <p>Please help me! Thanks in advance! </p>89821102386	0	What is the term for a "stack" of sub-pages that displays on one page? <p>I'm building a Wordpress site and am looking for a plugin for managing a very specific kind of content / design scheme. Unfortunately, I do not know what this is called, and am looking for pointers on terminology so I can ease my search.</p> <p>Imagine a very long page (as tall as 7 screens, for instance). </p> <p>This is divided into 7 sub-pages, each the size of one screen, stacked one on top of the other. </p> <p>Each sub-page has its own background and content. </p> <p>The viewer can scroll from top to bottom of the "parent" page, and get 7 distinct background / content groupings for 7 different products.</p> <p>What is this kind of content called? "Frames", isn't right, and "divs" is too general. I would appreciate any guidance on this that can be provided. Thanks!</p> <p>I don't have any live demos of this sort of content, but will post them as I find them.</p>8994440306	0	 <p>First try updating your statistics. </p> <p>Then, look into your indexing, and make sure you have only what you need. Additional indexes can most definitely slow down inserts. </p> <p>Then, try rebuilding the indexes.</p> <p>Without knowing the schema, query, or amount of data, it is hard to say more than that.</p>90025039982	0	 <p>This is implementation defined as per the <a href="http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf" rel="nofollow">draft C99 standard</a> section <code>6.3.2.3</code> <em>Pointers</em> which says:</p> <blockquote> <p>Any pointer type may be converted to an integer type. Except as previously specified, the result is implementation-defined. If the result cannot be represented in the integer type, the behavior is undefined. The result need not be in the range of values of any integer type.</p> </blockquote> <p><code>gcc</code> documents there implementation <a href="https://gcc.gnu.org/onlinedocs/gcc/Arrays-and-pointers-implementation.html#Arrays-and-pointers-implementation" rel="nofollow">here</a>:</p> <blockquote> <p>The result of converting a pointer to an integer or vice versa (C90 6.3.4, C99 and C11 6.3.2.3).</p> <ul> <li><p>A cast from pointer to integer discards most-significant bits if the pointer representation is larger than the integer type, sign-extends1 if the pointer representation is smaller than the integer type, otherwise the bits are unchanged.</p></li> <li><p>A cast from integer to pointer discards most-significant bits if the pointer representation is smaller than the integer type, extends according to the signedness of the integer type if the pointer representation is larger than the integer type, otherwise the bits are unchanged.</p></li> </ul> </blockquote> <p>Alternatively you could use <em>uinitptr_t</em> assuming <code>stdint.h</code> is available which is an unsigned integer that can hold a pointer value:</p> <pre><code>#include &lt;stdint.h&gt; #include &lt;inttypes.h&gt; uintptr_t ip = &amp;i ; printf("0x%016" PRIxPTR "\n", ip ) ; </code></pre>9014176241	0	I call Alert.Show in a function and want to get the result from there (Flex, ActionScript) <p>I'm using the Alert.show in a function and I want to get the user answer from there. So how can I achieve this. The problem is the function that call Alert.show will return a true or false value depend the user answer. but It seem that in Alert.show it only allow to pass in a CloseHandler for this. that is a new function. and since that I can get the user answer from where it is call to return the user answer.</p> <p>Really thanks for help Yuan</p>9026119230	0	You need 10,000 digits of e on a windows box <p>Let's say you have a bare-bones Windows XP machine, nothing added. This means no compilers, no MS Office, etc. Oh, and no network connection.</p> <p>You want 10,000 digits of e (e is the base of the natural logarithm). You have one hour. How could you do it?</p> <p><strong>Disclaimer:</strong> There are probably multiple "good" answers, but I have one particular idea in mind.</p>90325907377	0	error in spring-security.xml for constructor arg error <p>i m using spring security for my login page.in this in the database user password is stored using sha-password encoder.now i want to use the same in my spring-security.xml.i tried this</p> <pre><code>&lt;beans:bean id="passwordEncoder" class="org.springframework.security.authentication.encoding.ShaPasswordEncoder"&gt; &lt;constructor-arg value="256"/&gt; &lt;/beans:bean&gt; &lt;authentication-manager&gt; &lt;authentication-provider&gt; &lt;password-encoder ref="passwordEncoder"/&gt; &lt;jdbc-user-service data-source-ref="dataSource" users-by-username-query= "select email,password, 'true' as enabled from user_login where email=? limit 1" authorities-by-username-query= "select email, role from user_roles where email =? " /&gt; &lt;/authentication-provider&gt; &lt;/authentication-manager&gt; &lt;/beans:beans&gt; </code></pre> <p>i m getting error at </p> <pre><code>cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'constructor-arg'. - Security namespace does not support decoration of element [constructor-arg] - Configuration problem: Security namespace does not support decoration of element. </code></pre> <p>anyone help me for this,please.</p>90419253826	0	 <p>I found the solution. If load following HTML in UIWebView in iOS 7 (not Safari), the <code>onblur</code> event doesn't work:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;meta name='viewport' content='initial-scale=1.0,maximum-scale=10.0'/&gt; &lt;/head&gt; &lt;body&gt; &lt;table style='height:80%'&gt;&lt;tr&gt;&lt;td&gt; &lt;select onblur="alert('blur')" &gt; &lt;option value="1"&gt;1&lt;/option&gt; &lt;option value="2"&gt;2&lt;/option&gt; &lt;option value="3"&gt;3&lt;/option&gt; &lt;/select&gt; &lt;/td&gt;&lt;/tr&gt;&lt;/table&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>The important components: <em>viewport</em>, <em>table</em> with some <em>height</em> defined, <em>select</em> inside this table. If remove table OR remove height style OR remove viewport, then <code>onblur</code> works.</p> <p>I can't explain this effect, but I just remove table height style and it works. Maybe it helps somebody.</p>90516496963	0	 <p><code>HKL9</code> (string) is greater than <code>HKL15</code>, beacause they are compared as strings. One way to deal with your problem is to define a column function that returns only the numeric part of the invoice number.</p> <p>If all your invoice numbers start with <code>HKL</code>, then you can use:</p> <pre><code>SELECT MAX(CAST(SUBSTRING(invoice_number, 4, length(invoice_number)-3) AS UNSIGNED)) FROM table </code></pre> <p>It takes the invoice_number excluding the 3 first characters, converts to int, and selects max from it.</p>90624092656	0	 <p>You can either use, but $('title') will fail in IE8</p> <pre><code>document.title="new title"; </code></pre> <p>or</p> <pre><code>$('title').html('new title'); </code></pre> <p>or</p> <pre><code>$(document).attr('title','new title'); </code></pre>90734736811	0	 <p>You can use the LIKE ability of mysql:</p> <pre><code>SELECT * FROM company WHERE country LIKE '%$country%'; </code></pre>90816013020	0	How use Video.js player via Flash fallback without CDN swf file <p>IE8 or older automatically uses flash fallback player but the player is hosted in CDN.</p> <p>I want to use hosted <code>video-js.swf</code> file in my server instead of CDN contents. Because CDN swf file is not secured.</p> <p>The Video.js version is 3.2, that is currently you can download from <a href="http://videojs.com/" rel="nofollow">http://videojs.com/</a>.</p> <p>I tried <a href="http://help.videojs.com/discussions/suggestions/184-using-protocol-relative-urls-to-switch-between-http-and-https" rel="nofollow">this code</a> but it does not work.</p> <p>Can someone help me with the solution?</p> <p>Thanks!</p>9099359946	0	Call user defined function on click in jQuery <p>I have made a jQuery function and want to call it on click event. My code is like below:</p> <pre><code>&lt;script type="text/javascript"&gt; (function($){ $.fn.my_function = function(options){ return this.each(function(){ alert("Hello"); }); }; })(jQuery); $(document).ready(function(){ $('#submit_buttom').my_function(); }); &lt;/script&gt; </code></pre> <p>Please help.</p> <p>Thanks</p>91015148571	0	 <p>You need to open the applications screen, in it to scroll right until you get to the widgets section. from there pull the widget that you want and add it to the desired desktop.</p>9118043579	0	How to strip path while archiving with TAR <p>I have a file that contain list of files I want to archive with tar. Let's call it <code>mylist.txt</code></p> <p>It contains:</p> <pre><code>/path1/path2/file1.txt /path1/path2/file3.txt ... /path1/path2/file10.txt </code></pre> <p>What I want to do is to archive this file into a tarball but excluding <code>/path1/path2/</code>. Currently by doing this:</p> <pre><code>tar -cvf allfiles.tar -T mylist.txt </code></pre> <p>preserves the path after unarchiving.</p> <p>I tried this but won't work too:</p> <pre><code>tar -cvf -C /path1/path2 allfiles.tar -T mylist.txt </code></pre> <p>It archives all the files in <code>/path1/path2</code> even those which are not in mylist.txt</p> <p>Is there a way to do it?</p>91238588513	0	Best practice to deploy wso2 esb policies <p>I have setup an ESB cluster using jdbc connections to ms sql databases for local and remotely mounted config and gov registries. 1x mgt and 2xworker</p> <p>Our .car file contains some ws-security policy artifacts which go to config. When I deploy to mgt it deploys OK. I have SVN dep sync setup to the cluster and when it picks up the .car it starts to deploy on the worker but fails when loading the policy files into conf. It is trying to duplicate the policy in the shared conf and fails - of course that is right but; how should I deploy these 'shared' artifacts when a .car file is distributed by svn? I need to be able to control the deploy properly. The only way I can see is via the dev studio which is terrible for our change management practice.</p> <p>Thanks for you help.</p>9132998841	0	 <p>Use the application identifier in the .config file to differentiate between your applications. It's in the Membership Provider section. <code>applicationName="MyApplication"</code></p>9144846718	0	asp.net 3.5 referencing project with assembly reference throws signing/strong name error in Unit Test <p>I have a reference to a MySQL.Data 5.2.3 assembly in a data layer, great. I currently I have small console app inteh same solution referencing JUST THIS data layer which connects just fine. I then created a unit test project (also in the same solution) and reference that same data layer project, and from that I get:</p> <blockquote> <p><strong>Test method LTTests.WrapperTest.LoginTest threw exception: System.IO.FileLoadException: Could not load file or assembly 'MySql.Data, Version=5.2.3.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d' or one of its dependencies. Strong name signature could not be verified. The assembly may have been tampered with, or it was delay signed but not fully signed with the correct private key. (Exception from HRESULT: 0x80131045).</strong></p> </blockquote> <p>So I'm trying to understand...I can do this for a console exe and it works but not a unit test? This makes me nervous to build on something apparently flawed, but I'm at a loss for what to do next. I'm lost, I've been re-adding various things looking for what the deal is and I have no clue. </p> <p>The exception is from the data layer and not from the test (per the stack) so it's like the test is calling the layer's method (duh) and the data layer is puking but not for the console? </p> <p>Thanks.</p>91535030093	0	 <p>Is it crucial for it to have to equal -3.40282306e+38 for your algorithm to work? If nor try an inequality instead of equals. Equlaity works on floating point numbers if they are perfect integers such as 0,for numbers like youre using an inequality maybe the answer. Wont something like </p> <blockquote> <p>(-3.40282306e+38-smallnumber) fix your problem?-You have to set small number to somthing in the context of your problem which I dont know what it is.</p> </blockquote>91622829563	0	 <blockquote> <p>1. Can we get all field names of a collection with their data types?</p> </blockquote> <p>mongodb collections are schema-less, which means each <code>document</code> (row in relation database) can have different fields. When you find a <code>document</code> from a <code>collection</code>, you could get its fields names and data types.</p> <blockquote> <p>2. Can we generate a random value of that data type in mongo shell?</p> <p>3. how to set the values dynamically to store random data.</p> </blockquote> <p>mongo shell use JavaScript, you may write a js script and run it with <code>mongo the_js_file.js</code>. So you could generate a random value in the js script.</p> <p>It's useful to have a look at the <a href="http://api.mongodb.org/js" rel="nofollow">mongo JavaScript API documentation</a> and the mongo shell <a href="http://docs.mongodb.org/manual/reference/method/" rel="nofollow">JavaScript Method Reference</a>.</p> <p>Other script language such as Python can also do that. mongodb has their APIs too.</p>91711568153	0	 <p>The useful difference between </p> <pre><code>data Point = Point Float Float data Radius = Radius Float data Shape = Circle Point Radius </code></pre> <p>and<br> <code>data LengthQty = Radius Float | Length Float | Width Float</code></p> <p>is the way Haskell's type system handles them. Haskell has a powerful type system, which makes sure that a function is passed data that it can handle. The reason you'd write a definition like <code>LengthQuantity</code> is if you had a function which could take either a <code>Radius</code>, <code>Length</code>, or <code>Width</code>, which your function can't do. </p> <p>If you <em>did</em> have a function which could take a <code>Radius</code>, <code>Length</code>, or <code>Width</code>, I'd write your types like this: </p> <pre><code>data Point = Point Float Float data Radius = Radius Float data Shape = Circle Point Radius data LengthQty = R Radius | L Length | W Width </code></pre> <p>This way, functions that can only take a <code>Radius</code> benefit from that more specific type checking.</p>91816917797	0	how do i implement a basic timestamp in pull to refresh <p>I have implemented a pull to refresh and now trying to add a timestamp showing "Last updated: "time""(4:50/tuesday etc). I have implemented a method for the same:</p> <pre><code>public void setLastUpdated(CharSequence lastUpdated) { if (!TextUtils.isEmpty(lastUpdated)) { eikonLastUpdated.setVisibility(View.VISIBLE); eikonLastUpdated.setText(lastUpdated); } else { eikonLastUpdated.setVisibility(View.GONE); } } </code></pre> <p>Does anyone know how I can add the same to an XML, and how do I go about it, do I also have to add the same to java by calling <code>settext</code> method? example: </p> <pre><code>textView.setText("Last updated:"); </code></pre> <p>How do I call the <code>setlastupdated</code> method for the same?</p>9197161624	0	Converting a variadic macro to a variadic template function? <p>Given a variadic macro of the form:</p> <pre><code>#define MY_CALL_RETURN_F(FType, FId, ...) \ if(/*prelude omitted*/) { \ FType f = (FType)GetFuncFomId(FId); \ if(f) { \ return f(__VA_ARGS__); \ } else { \ throw invalid_function_id(FId); \ } \ } \ /**/ </code></pre> <p>-- how can this be rewritten to a variadic function template?</p> <pre><code>template&lt;typename FType, typename ...Args&gt; /*return type?*/ tmpl_call_return_f(MyFunId const&amp; FId, /*what goes here?*/) { ... FType f = (FType)GetFuncFomId(FId); return f(/*what goes here?*/); ... } </code></pre> <p>Update: I'm specifically interested in how to declare the reference type for the <code>Args</code>: <code>&amp;&amp;</code> or <code>const&amp;</code> or what?</p> <p>Update: Note that FType is supposed to be a "plain" function pointer.</p>92036067236	0	 <p>did you try this</p> <pre><code>{% load games_tags %} </code></pre> <p>at the top instead of pygmentize? </p>92111765378	0	 <pre><code>Iterator&lt;Integer&gt; it=ar1.iterator(); Iterator&lt;Integer&gt; it2=ar2.iterator(); while(it.hasNext()&amp;&amp;it2.hasNext()) { result.add(new Integer(it.next().intValue()*it2.next().intValue())); } </code></pre> <p>will also work efficiently for any list. </p>922630955	0	How to implement dispose pattern with close method correctly (CA1063) <p>The Framework Design Guidelines (2nd Ed., page 327) say:</p> <blockquote> <p>CONSIDER providing method <code>Close()</code>, in addition to the <code>Dispose()</code>, if close is standard terminology in the area.</p> <p>When doing so, it is important that you make the Close implementation identical to <code>Dispose</code> and consider implementing <code>IDisposable.Dispose</code> method explicitly.</p> </blockquote> <p>So, following the provided example, I've got this class:</p> <pre><code>public class SomeClass : IDisposable { private SomeDisposable someInnerDisposable; public void Open() { this.someInnerDisposable = new SomeDisposable(); } void IDisposable.Dispose() { this.Close(); } public void Close() { this.Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { this.someInnerDisposable.Dispose(); this.someInnerDisposable = null; } } } </code></pre> <p>FxCop doesn't seem to like that:</p> <blockquote> <p>CA1816 : Microsoft.Usage : 'SomeClass.Close()' calls 'GC.SuppressFinalize(object)', a method that is typically only called within an implementation of 'IDisposable.Dispose'. Refer to the IDisposable pattern for more information.</p> <p>CA1816 : Microsoft.Usage : Change 'SomeClass.IDisposable.Dispose()' to call 'GC.SuppressFinalize(object)'. This will prevent unnecessary finalization of the object once it has been disposed and it has fallen out of scope.</p> <p>CA1063 : Microsoft.Design : Modify 'SomeClass.IDisposable.Dispose()' so that it calls Dispose(true), then calls GC.SuppressFinalize on the current object instance ('this' or 'Me' in Visual Basic), and then returns.</p> <p>CA1063 : Microsoft.Design : Rename 'SomeClass.IDisposable.Dispose()' to 'Dispose' and ensure that it is declared as public and sealed.</p> </blockquote> <ul> <li>How do I implement the dispose pattern with close method correctly?</li> </ul> <p>-or-</p> <ul> <li>How do I suppress the warnings?</li> </ul> <p>I tried</p> <pre><code>[SuppressMessage("Microsoft.Design", "CA1063:ImplementIDisposableCorrectly", Justification = "Framework Design Guidelines say it's ok.")] void IDisposable.Dispose() { this.Close(); } </code></pre> <p>but FxCop 1.36 still reports them.</p> <p><strong>EDIT</strong>: Changing it around as suggested eliminates all but this warning:</p> <blockquote> <p>CA1063 : Microsoft.Design : Rename 'SomeClass.IDisposable.Dispose()' to 'Dispose' and ensure that it is declared as public and sealed.</p> </blockquote> <p><strong>EDIT 2</strong>: CODE_ANALYSIS was indeed missing. Thanks.</p>9233112665	0	 <p>What about just using <code>typedef</code>s?</p> <pre><code>typedef V&amp; I; typedef const V&amp; CI; </code></pre> <p>Edit:</p> <p>No. See comments :)</p>92422119836	0	How to Implement a Class/Database Listener? <p>I am using the Parse.com database service for a PhoneGap app we are creating. We have users that can mark themselves (First User) "Available" for their friends (Second User), and I need a way to listen for that toggle in availability on the second user's side, so their friends list can update without having the refresh the page.</p> <p>With Parse, your interaction with the database is monitored by # API calls and Burst Limit (Number of API calls per second) so I need to only call the database for the change in status when it is actually changed, I can't keep a setInterval on otherwise it will make the burst limit too small for other user, or it will cause to many API calls for no reason if the status isn't changing.</p> <p>How can I got about this?</p>92539015432	0	run Spark-Submit on YARN but Imbalance (only 1 node is working) <p>i try to run <strong>Spark Apps</strong> on <strong>YARN-CLUSTER (2 Nodes)</strong> but it seems those 2 nodes are imbalance because only 1 node is working but another one is not.</p> <p>My Script :</p> <pre><code>spark-submit --class org.apache.spark.examples.SparkPi --master yarn-cluster --deploy-mode cluster --num-executors 2 --driver-memory 1G --executor-memory 1G --executor-cores 2 spark-examples-1.6.1-hadoop2.6.0.jar 1000 </code></pre> <p>I see one of my node is working but another is not, so this is imbalance :</p> <p><a href="https://i.stack.imgur.com/S8L57.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/S8L57.png" alt="enter image description here"></a> Note : in the left is <code>namenode</code>, and <code>datanode</code> is on the right...</p> <p>Any Idea ?</p>92620764999	0	 <p>As it turns out, there <em>is</em> a way to do this, but it's not pretty. It involves using the WinForms version of <code>MessageBox</code> and passing an undocumented option as the last property. </p> <pre><code>var result = System.Windows.Forms.MessageBox.Show("Are you sure you want to exit this app?", "Exit", System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Question, System.Windows.Forms.MessageBoxDefaultButton.Button2, (System.Windows.Forms.MessageBoxOptions)8192 /*MB_TASKMODAL*/); </code></pre> <p>Source: <a href="http://social.msdn.microsoft.com/Forums/vstudio/en-US/8d1bd4a2-455e-4e3f-8c88-7ed49aeabc09/messagebox-is-not-applicationmodal?forum=wpf" rel="nofollow">http://social.msdn.microsoft.com/Forums/vstudio/en-US/8d1bd4a2-455e-4e3f-8c88-7ed49aeabc09/messagebox-is-not-applicationmodal?forum=wpf</a></p> <p>Hopefully this is helpful to somebody else in the future!</p>92740907417	0	Why is infinity printed as "8" in the Windows 10 console? <p>I was testing what was returned from division including zeroes i.e. <code>0/1</code>, <code>1/0</code> and <code>0/0</code>. For this I used something similar to the following:</p> <pre><code>Console.WriteLine(1d / 0d); </code></pre> <p>However this code prints <code>8</code> not <code>Infinity</code> or some other string constant like <code>PositiveInfinity</code>.</p> <p>For completeness all of the following print <code>8</code>:</p> <pre><code>Console.WriteLine(1d / 0d); double value = 1d / 0d; Console.WriteLine(value); Console.WriteLine(Double.PositiveInfinity); </code></pre> <p>And <code>Console.WriteLine(Double.NegativeInfinity);</code> prints <code>-8</code>.</p> <p>Why does this infinity print 8?</p> <hr> <p>For those of you who seem to think this is an infinity symbol not an eight the following program:</p> <pre><code>Console.WriteLine(1d / 0d); double value = 1d / 0d; Console.WriteLine(value); Console.WriteLine(Double.PositiveInfinity); Console.WriteLine(8); </code></pre> <p>Outputs:</p> <p><a href="https://i.stack.imgur.com/ODbah.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ODbah.png" alt="Inifinity output"></a></p>92810294436	0	 <p>This code:</p> <pre><code>for(NSString *jidAct in occupantsArray){ if([jidAct isEqualToString:jid]){ [occupantsArray removeObjectAtIndex:i]; } i++; } </code></pre> <p>is probably causing your problems. You shouldn't be removing elements while enumerating the array. The way you avoid this is by using an NSMutableIndexSet:</p> <pre><code>NSMutableIndexSet *indexes = [NSMutableIndexSet set]; // assuming NSInteger i; for(NSString *jidAct in occupantsArray){ if([jidAct isEqualToString:jid]){ [indexes addIndex:i]; } i++; } [occupantsArray removeObjectsAtIndexes:indexes]; </code></pre>92929617983	0	 <p>Here's how I'd approach this:</p> <pre><code>combiner &lt;- function(n, ...) { ## Capture the unevaluated calls and symbols passed via ... ll &lt;- as.list(substitute(list(...)))[-1] ## Process each one in turn lapply(ll, FUN = function(X) { ## Turn any symbols/names into calls if(is.name(X)) X &lt;- as.call(list(X)) ## Add/replace an argument named n X$n &lt;- n ## Evaluate the fixed up call eval(X) }) } combiner(6, fun1(), fun2, rnorm(), fun4(y=8)) # [[1]] # [1] 3 8 9 7 4 7 # # [[2]] # [1] "Z" "M" "U" "A" "Z" "U" # # [[3]] # [1] 0.6100340 -1.0323017 -0.6895327 1.2534378 -0.3513120 0.3116020 # # [[4]] # [1] 112.31979 91.96595 79.11932 108.30020 107.16828 89.46137 </code></pre>93032262515	0	 <p>Yes: </p> <pre><code>Application.EnableEvents = False </code></pre> <p>Then when you are done with the procedure:</p> <pre><code>Application.EnableEvents = True </code></pre>93132651039	0	 <p>If the client name section of the URL is after the <code>access-guid/</code> and before the next <code>/</code>:</p> <pre><code>http://www.disabledgo.com/access-guide/the-university-of-manchester/176-waterloo-place-2 |----------------------------| </code></pre> <p>you need to use a negated character class to only match <code>university</code> before the regex reaches that rightmost <code>/</code> boundary.</p> <p>As per the <a href="https://support.google.com/analytics/answer/2853546?hl=en&amp;ref_topic=1727167&amp;vid=1-635784241538251930-2972435195#extract" rel="nofollow">Reference</a>:</p> <blockquote> <p>You can extract pages by Page URL, Page Title, or Screen Name. Identify each one with a regex capture group (Analytics uses the first capture group for each expression)</p> </blockquote> <p>Thus, you can use</p> <pre><code>/access-guide/([^/]*(universit(y|ies)|colleges?)) ^^^^^ </code></pre> <p>See <a href="https://regex101.com/r/oU0hT1/3" rel="nofollow">demo</a>.</p> <p>The regex matches</p> <ul> <li><code>/access-guide/</code> - leftmost boundary, matches <code>/access-guide/</code> literally</li> <li><code>[^/]*</code> - any character other than <code>/</code> (so we still remain in that customer section)</li> <li><code>(universit(y|ies)|colleges?)</code> - <code>university</code>, or <code>universities, or</code>college<code>or</code>colleges` literally. Add more if needed.</li> </ul>93212796448	0	 <p><strong>Position parameter of the getView() method gives the position of the newly created View (i.e the list item), it wont give the clicked item position.</strong></p> <p>Use <code>listView.onClickListener</code> in the Activity instead of Adater.</p>93334080123	0	 <p>You can make Django go back to the Poll instance by overriding the <code>response_change</code> method on the full Choice admin:</p> <pre><code>from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect class ChoiceAdmin(admin.ModelAdmin): ''' To be called from the Poll choice inline. It will send control back to the Poll change form, not the Choice change list. ''' fields = [...] def response_change(self, request, choice): if not '_continue' in request.POST: return HttpResponseRedirect(reverse("admin:appname_poll_change", args=(choice.poll.id,))) else: return super(ChoiceAdmin, self).response_change(request, choice) </code></pre> <p>To address the second part of your question: I think you'll have to register a second, unmodified, admin on the model. You can do that using a proxy model. See <a href="http://stackoverflow.com/questions/2223375">Multiple ModelAdmins/views for same model in Django admin</a></p>93434755100	0	How to parse BigInt from the num crate? <p>I am trying to use <a href="http://rust-num.github.io/num/num/bigint/struct.BigInt.html" rel="nofollow"><code>BigInt</code></a>. My code is like this:</p> <pre><code>extern crate num; use num::bigint::BigInt; ... println!("{}", from_str::&lt;BigInt&gt;("1")); //this is line 91 in the code </code></pre> <p>In my Cargo.toml file I have the following:</p> <pre><code>[dependencies] num = "0.1.30" </code></pre> <p>What I did seem to match what was said in <a href="http://rust-num.github.io/num/num/bigint/struct.BigInt.html#method.from_bytes_be" rel="nofollow">this document</a>, <a href="http://docs.piston.rs/conrod/num/bigint/struct.BigInt.html" rel="nofollow">also this document</a> and also <a href="http://stackoverflow.com/questions/23391440/in-rust-how-do-i-use-implemented-trait-fromstr-on-bigint">an answer here on Stack Overflow</a>.</p> <p>However I got the following error:</p> <pre><code>Compiling example v0.1.0 (file:///C:/src/rust/example) src\main.rs:91:20: 91:38 error: unresolved name `from_str` [E0425] src\main.rs:91 println!("{}", from_str::&lt;BigInt&gt;("1")); </code></pre>93514601824	0	 <p>While your pictures are fairly large and you should try to reduce the number and size, you can make gains through packaging the .png into pvr.ccz files. There are multiple different programs available to do this. I like to use Texture Packer which is available here: <a href="http://www.codeandweb.com/texturepacker" rel="nofollow">http://www.codeandweb.com/texturepacker</a></p>93620111762	0	Mysql date_add 1 year <p>Can someone help me figure out why adding 1 year doesn't work for me?</p> <p>I have 6 other conditions (1 day, 1 week, 2 month, etc). The only one NOT working is the year.</p> <p>Anyone see why? In case it matters, this is Perl.</p> <pre><code>elsif ($data{length} == "6month") { $store = qq(INSERT INTO main (creator_name,email2,relationship,reason,email1,name1,creator_email,email3,name2,name3,creator_url,victim_url,length_of_stay,release_date) VALUES("$data{creatorname}","$data{email2}","$data{relationship}","$data{reason}","$data{email1}","$data{person1}","$data{creatoremail}","$data{email3}","$data{person2}","$data{person3}", "$creatorURL", "$victimURL","$data{length}", DATE_ADD(NOW(), INTERVAL 6 MONTH)) ); } elsif($data{length} == "1year") { $store = qq(INSERT INTO main (creator_name,email2,relationship,reason,email1,name1,creator_email,email3,name2,name3,creator_url,victim_url,length_of_stay,release_date) VALUES("$data{creatorname}","$data{email2}","$data{relationship}","$data{reason}","$data{email1}","$data{person1}","$data{creatoremail}","$data{email3}","$data{person2}","$data{person3}", "$creatorURL", "$victimURL","$data{length}", DATE_ADD(NOW(), INTERVAL 1 YEAR)) ); } my $sth = $dbh-&gt;prepare($store); $sth-&gt;execute() or die $dbh-&gt;errstr; </code></pre>9371154732	0	many domains = much memory usage? <p>I would like to know if for example, I have about 80 domains on my projects, does it means that the 80 domains will be loaded into memory when I run the project or it will be loaded when I need that domain ... </p> <p>It seems if I have many domains in one project, I have to disable auto compile and increase the perm gen space.</p> <p>is there any solutions to load just when I need to acces those domain ? not all domain will be used ... sometimes it just small domain that almost never touched by users incase something happens (ie special cases)</p> <p>I'm using grails 1.1.1 at the moment and have to disable the auto compile for domain or else it will stuck and depleted memory / memory gen space</p>93813831968	0	 <p>You can use the http put method to handle the file upload. In this method the data is directly streamed to the PHP script and you can handle it using file functions:</p> <pre><code>&lt;?php $f = fopen('php://input','r'); while(!feof($f)){ $chunk = fread($f,CHUNK_SIZE); [Handle the uploading file here] } fclose($f); ?&gt; </code></pre> <p>(Replace CHUNK_SIZE with your value)</p>93913841315	0	 <p>For valid xHTML it should have the alt attribute.</p> <p>Something like this would work:</p> <pre><code>$xml = new SimpleXMLElement($doc); // $doc is the html document. foreach ($xml-&gt;xpath('//img') as $img_tag) { if (isset($img_tag-&gt;attributes()-&gt;alt)) { unset($img_tag-&gt;attributes()-&gt;alt); } } $new_doc = $xml-&gt;asXML(); </code></pre>94013799947	1	Python Filling Up Disk <p>I need to setup some test conditions to simulate a filled up disk. I created the following to simply write garbage to the disk:</p> <pre><code>#!/usr/bin/python import os import sys import mmap def freespace(p): """ Returns the number of free bytes on the drive that ``p`` is on """ s = os.statvfs(p) return s.f_bsize * s.f_bavail if __name__ == '__main__': drive_path = sys.argv[1] output_path = sys.argv[2] output_file = open(output_path, 'w') while freespace(drive_path) &gt; 0: output_file.write("!") print freespace(drive_path) output_file.flush() output_file.close() </code></pre> <p>As far as I can tell by looking at the return value from freespace, the write method does not write the file to until it is closed, thereby making the while condition invalid.</p> <p>Is there a way I can write the data directly to the file? Or another solution perhaps?</p>94131752059	0	 <p>The main issue you seem to be encountering is that the proxy example you're using requires a POST to update the destination URL you're trying to browse through the proxy. That's why you're not getting any content from the target page, and the error message</p> <pre><code>&lt;div id="error"&gt;Hotlinking directly to proxied pages is not permitted.&lt;/div&gt; </code></pre> <p>I don't know how your code looks like, but it seems like you could use the <a href="http://stackoverflow.com/a/4015346/1519377">HttpWebRequest POST Method</a></p> <pre><code>WebRequest request = (HttpWebRequest)WebRequest.Create("http://www.glype-proxy.info/includes/process.php?action=update"); var postData = "url="+"http://www.example.com"; postData += "&amp;allowCookies=on"; var data = Encoding.ASCII.GetBytes(postData); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = data.Length; using (var stream = request.GetRequestStream()) { stream.Write(data, 0, data.Length); } var response = (HttpWebResponse)request.GetResponse(); var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd(); </code></pre> <hr> <p>You're going to need to find or host a proxy that returns the HTML of the page, such as <a href="http://www.glype-proxy.info/" rel="nofollow">http://www.glype-proxy.info/</a>. Even so, in order for a proxy to function correctly, it must change the link to the page's resources to it's own "proxied" path.</p> <pre><code>http://www.glype-proxy.info/browse.php?u=https%3A%2F%2Fwww.example.com%2F&amp;b=4&amp;f=norefer </code></pre> <p>In the URL above, if you want the path to the original resources, you'll have to find all the resources that have been redirected and unencode the path passed in as the <code>u=</code> parameter to this specific proxy. Also, you may wish to ignore additional elements injected by the proxy , in this case the <code>&lt;div id="include"&gt;</code> element.</p> <hr> <p>I believe the proxy you're using works the same way as the "Glype" proxy I used in this example, but I do not have access to it at the time of posting. Also, if you want to use use other proxies, you may want to note that many proxies display the result in an iFrame (probably for XSS prevention, navigation, or skinning).</p> <p><strong>Note:</strong> Generally, using another service outside of a built-in API is a bad practice, since services often get a GUI update or some other change that could break your script. Also, those services could experiences interruptions or just be taken down.</p>94236406243	0	Spring-boot app not rendering war file in Tomcat 8 <p>I know by default Spring-Boot uses Tomcat 7. Therefore I have declared it in my POM file:</p> <pre><code>&lt;properties&gt; &lt;project.build.sourceEncoding&gt;UTF-8&lt;/project.build.sourceEncoding&gt; &lt;java.version&gt;1.8&lt;/java.version&gt; &lt;tomcat.version&gt;8.0.33&lt;/tomcat.version&gt; &lt;/properties&gt; </code></pre> <p>I confirm that that is the Tomcat version I am using. <a href="https://i.stack.imgur.com/kZlpJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kZlpJ.png" alt="Tomcat"></a></p> <p>I placed the War file in the webapps folder, it naturally unwrapped it but the path localhost:8080/personalsite gives me a 404.</p> <p><a href="https://i.stack.imgur.com/yaczB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yaczB.png" alt="enter image description here"></a></p> <p>If I run <code>java -jar personalsite</code> it works fine. Now I am wondering what to do next or where to look.</p> <p>My log file only outputs the following:</p> <pre><code>04-Apr-2016 10:16:47.834 INFO [http-nio-8080-exec-8] org.apache.catalina.core.ApplicationContext.log Spring WebApplicationInitializers detected on classpath: [org.springframework.boot.autoconfigure.jersey.JerseyAutoConfiguration$JerseyWebApplicationInitializer@35a7f52a] </code></pre> <p>pom.xml</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;groupId&gt;com.personalsite&lt;/groupId&gt; &lt;artifactId&gt;personalsite&lt;/artifactId&gt; &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt; &lt;packaging&gt;war&lt;/packaging&gt; &lt;name&gt;PersonalSite&lt;/name&gt; &lt;description&gt;Demo project for Spring Boot&lt;/description&gt; &lt;parent&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt; &lt;version&gt;1.3.3.RELEASE&lt;/version&gt; &lt;relativePath/&gt; &lt;!-- lookup parent from repository --&gt; &lt;/parent&gt; &lt;properties&gt; &lt;project.build.sourceEncoding&gt;UTF-8&lt;/project.build.sourceEncoding&gt; &lt;java.version&gt;1.8&lt;/java.version&gt; &lt;tomcat.version&gt;8.0.33&lt;/tomcat.version&gt; &lt;/properties&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-data-jpa&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-tomcat&lt;/artifactId&gt; &lt;scope&gt;provided&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;mysql&lt;/groupId&gt; &lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt; &lt;version&gt;5.1.6&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-context-support&lt;/artifactId&gt; &lt;version&gt;${spring.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-mail&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;javax.servlet&lt;/groupId&gt; &lt;artifactId&gt;javax.servlet-api&lt;/artifactId&gt; &lt;scope&gt;provided&lt;/scope&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt; &lt;/plugin&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-war-plugin&lt;/artifactId&gt; &lt;configuration&gt; &lt;failOnMissingWebXml&gt;false&lt;/failOnMissingWebXml&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; &lt;/project&gt; </code></pre>9433668746	0	How do I move old content down in the search engine rankings? <p>There is <a href="http://stackoverflow.com/questions/58484/getting-good-google-pagerank">some</a> <a href="http://stackoverflow.com/questions/585175/google-pagerank-does-it-count-per-domain-or-per-webpage">precedent</a> for search-engine-ranking-related questions on StackOverflow, so please don't close this question. It's programming-related to the extent that HTML META tags can be called "programming".</p> <p>Here's the problem:</p> <p>We make <a href="http://www.fogcreek.com/FogBugz/" rel="nofollow noreferrer">FogBugz</a>, the software project planning and bug tracking suite.</p> <p>Either we did a great job with our old documentation or a crummy job with our new documentation, but for most of the popular searches on FogBugz terms, documentation for our old versions comes up.</p> <p><a href="http://www.google.com/search?aq=f&amp;sourceid=chrome&amp;ie=UTF-8&amp;q=fogbugz+delete+shared+filter" rel="nofollow noreferrer">Here's an example</a>. For context, our current FogBugz version is FogBugz 7. The top two results for that search are for FogBugz 5, which is positively ancient.</p> <p>As best I can tell, there are several options for getting these results out of the top slots, but each has problems:</p> <ul> <li>A <code>NOINDEX</code> tag, but what happens if someone is actually searching for help on an old version?</li> <li>Finding the incoming links to the old documentation and placing a <code>NOFOLLOW</code> on them to deprive the old docs of PageRank. Problem here is that it's really fiddly to find the links to the content, rather than changing the content itself.</li> <li>The <code>unavailable_after</code> tag, which is just a time-delayed <code>NOINDEX</code>, with the same problem of removal rather than demotion.</li> </ul> <p>I just want these old documentation versions to stop competing with our current versions, without being completely unavailable.</p>9449129513	0	 <p>Try this:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" &gt; &lt;LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" &gt; &lt;Button android:layout_width="100dip" android:layout_height="70dip" android:layout_gravity="center" android:text="111" /&gt; &lt;Button android:layout_width="100dip" android:layout_height="70dip" android:layout_gravity="center" android:text="111 222 333" /&gt; &lt;Button android:layout_width="100dip" android:layout_height="70dip" android:layout_gravity="center" android:text="111 222 333 444 555 666" /&gt; &lt;Button android:layout_width="100dip" android:layout_height="70dip" android:layout_gravity="center" android:text="111" /&gt; &lt;/LinearLayout&gt; &lt;/LinearLayout&gt; </code></pre>94533104604	0	 <p>You just need to add a "Add Row" button at the end and push a new value to your <code>List1</code> like this in your controller. See an update to your <a href="https://jsfiddle.net/4zbvv5gq/7/" rel="nofollow">fiddle</a> here.</p> <pre><code>$scope.addRow = function(){ var len = $scope.List1.length; $scope.List1.push('product'+(len+1)); } </code></pre> <p>And right after your table, add a button that calls the above function:</p> <pre><code> &lt;/table&gt; &lt;button ng-click="addRow()"&gt;Add a row&lt;/button&gt; </code></pre>9468862508	1	iFrame within wxpython? <p>Hi i am wondering if there is a widget or someway to put an iFrame in a program with wxpython. An iFrame with the same capabilities as the HTML one, (ability to see other websites).</p> <p>Thanks.</p>94729542878	0	Excel VBA fill 100 x 100 martix based on value in a column <p>I would love to fill a spreadsheet with 100 columns and 100 rows. I used the analysis toolpack to create a column of 10,000 numbers from a distribution (using the discrete distribution options 1 variable, 10,000 numbers and the two columns below as values). </p> <p>I want the columns to simulate 100 trials of 100 years using the column as the reproduction rates. The column created simulates the reproduction rates for each cell within the 100 x 100 matrix. I would like the initial row value for all columns to be 31. </p> <p>For the first column, I would like the (2,1) to multiple 31 by the first value in the reproduction column. For (3,1) I would like the to multiple (2,1) by the second value in the reproduction column. I would like this to continue for all 100 cells in the first column. I would then like it to start over on the next column starting with (2,1) being 31 multiplied by the 101 value in the reproductive column. </p> <pre><code>Private Sub Code() Dim i As Long Dim j As Long Dim iCol Dim ws As Worksheet 'Set this to the source sheet (where your trial counts are) Set ws = ActiveWorkbook.Sheets(4) For i = 2 To 100 iCol = ws.Cells(i, 1) For j = 1 To 100 Cells(1, i).Value = 34 For k = 1 To iCol Cells(j + 1, i + 1).Value = Cells(j, i).Value * k Next k Next j Next i End Sub </code></pre> <p>Here is the distribution that I would like the random numbers to be generated from. If there is a way to use the analysis tool within the VBA to allow so the numbers are generated there instead of externally, that would be great!</p> <pre><code>Value, Probability -0.15,0 -0.125,0 -0.1,0.05 -0.075,0 -0.05,0.05 -0.025,0 0,0 0.025,0.05 0.05,0 0.075,0 0.1,0.15 0.125,0.15 0.15,0.3 0.175,0.05 0.2,0.15 0.225,0.05 0.25,0 </code></pre> <p>Any help or advice is greatly appreciated!</p> <p>Thank you!!</p>94834976274	0	 <p>You have to create the table before Model from migration file check Documentation <strong><a href="https://laravel.com/docs/5.1/migrations#creating-tables" rel="nofollow">Creating tables</a></strong> section, then the model will use the plural name of the class as the table name.</p> <p><strong>NOTE :</strong> You have to set up your database configuration firstly and create database manually check <strong><a href="https://laravel.com/docs/5.1/database#accessing-connections" rel="nofollow">Database: Getting Started</a></strong> section.</p> <p>Hope this helps.</p>94914617635	0	php thumbnail organizer <p>Ok, i have this code and is working perfectly, but i need the order of the images to be by the date the image was created, can someone give me a hand?</p> <pre><code>$images=array(); $dir = @opendir('.') or die("Unable to open $path"); $i=0; while($file = readdir($dir)) { if(is_dir($file)) continue; else if($file != '.' &amp;&amp; $file != '..' &amp;&amp; $file != 'index.php') { $images[$i]=$file; $i++; } } sort($images); for($i=0; $i&lt;sizeof($images); $i++) { echo "&lt;a href=".chr(34).$path.$images[$i].chr(34)."&gt;&lt;img style='border:1px solid #666666; width:200px; margin: 10px;' src='".$images[$i]."'/&gt;&lt;/a&gt;"; } closedir($dir); </code></pre>95038942937	0	 <p><code>df["dataset_code"]</code> is a <code>Series</code>, not a <code>DataFrame</code>. Since you want to append one DataFrame to another, you need to change the Series object to a DataFrame object.</p> <pre><code>&gt;&gt;&gt; type(df) &lt;class 'pandas.core.frame.DataFrame'&gt; &gt;&gt;&gt; type(df['dataset_code']) &lt;class 'pandas.core.series.Series'&gt; </code></pre> <p>To make the conversion, do this:</p> <pre><code>df = df["dataset_code"].to_frame() </code></pre>95127532359	0	Spring-Boot : Referencing another Spring Boot Project <p>I created two spring boot projects, one is with JPA and the other with Web. I initially combined both of them into one project and everything works perfectly.</p> <p>I now want to separate the JPA portion from the Web. So I added the JPA project as a dependency of the Web. But spring-boot is unable to detect the beans on JPA. </p> <p>Is there any examples on how to implement this?</p> <p>I am getting the exception when I tried to autowire the beans from the JPA project.</p> <pre><code> BeanCreationException: Could not autowire field: </code></pre>95239906977	0	 <p>OGNL allows execution of methods, but the static access is disabled by default, so you cannot use static method in expressions. However, you can teach OGNL which classes needs to access the static methods.</p> <blockquote> <h2><a href="https://commons.apache.org/proper/commons-ognl/developer-guide.html#Method_Accessors" rel="nofollow">OGNL developer guide: Method Accessors</a></h2> <p>Method calls are another area where OGNL needs to do lookups for methods based on dynamic information. The <code>MethodAccessor</code> interface provides a hook into how OGNL calls a method. When a static or instance method is requested the implementor of this interface is called to actually execute the method.</p> <pre><code>public interface MethodAccessor { Object callStaticMethod( Map context, Class targetClass, String methodName, List args ) throws MethodFailedException; Object callMethod( Map context, Object target, String methodName, List args ) throws MethodFailedException; } </code></pre> <p>You can set a method accessor on a class-by-class basis using <code>OgnlRuntime.setMethodAccessor()</code>. The is a default method accessor for Object (which simply finds an appropriate method based on method name and argument types and uses reflection to call the method).</p> </blockquote> <hr> <p>You can code something</p> <pre><code>public class StringUtil extends StringUtils implements MethodAccessor { //implement above methods } </code></pre> <hr> <h1>Action class</h1> <pre><code>public static final String MESSAGE = "hello.message"; /** * Field for Message property. */ private String message; /** * Return Message property. * * @return Message property */ public String getMessage() { return message; } private StringUtil stringUtil = new StringUtil(); public StringUtil getStringUtil() { return stringUtil; } public String execute() throws Exception { setMessage(getText(MESSAGE)); OgnlRuntime.setMethodAccessor(StringUtil.class, stringUtil); return SUCCESS; } </code></pre> <hr> <h1>In JSP</h1> <pre class="lang-jsp prettyprint-override"><code>&lt;s:if test="!stringUtil.isEmpty(message)"&gt; &lt;h2&gt;&lt;s:property value="message"/&gt;&lt;/h2&gt; &lt;/s:if&gt; </code></pre> <hr>95317287528	0	 <p>Try this:</p> <pre><code>&gt; d &lt;- as.Date("01-01-2013", "%d-%m-%Y") + 0:7 # first 8 days of 2013 &gt; d [1] "2013-01-01" "2013-01-02" "2013-01-03" "2013-01-04" "2013-01-05" [6] "2013-01-06" "2013-01-07" "2013-01-08" &gt; &gt; ufmt &lt;- function(x) as.numeric(format(as.Date(x), "%U")) &gt; ufmt(d) - ufmt(cut(d, "year")) + 1 [1] 1 1 1 1 1 2 2 2 </code></pre> <p><em>Note:</em> The first Sunday in the year is defined as the start of week 1 by <code>%U</code> which means that if the year does not start on Sunday then we must add 1 to the week so that the first week is week 1 rather than week 0. <code>ufmt(cut(d, "year"))</code> equals one if <code>d</code>'s year starts on Sunday and zero otherwise so the formula above reduces to <code>ufmt(d)</code> if d's year starts on Sunday and <code>ufmt(d)+1</code> if not.</p> <p>UPDATE: corrections so Jan starts at week 1 even if year starts on a Sunday, e.g. 2006. </p>95414660230	0	 <p>I've spend many hours on that subject, one (working) thing I've found is this: <a href="https://github.com/jgallen23/OWAParser" rel="nofollow">https://github.com/jgallen23/OWAParser</a></p> <p>My problem was, after testing many times with my company's Exchange server they've locked my account. And even thought it works, after changing something small in the server configuration it will stop working, and that wasn't an option for me.</p> <p>Hope this helps you! :-)</p>95516314092	0	 <p>have you tried like below one</p> <p>Call below Method From the TableView DataSource Method <code>(cellForAtIndexPath)</code> For Doing the same Task</p> <pre><code> - (void)setCellBGColorNormalAndSelectedForTableViewCell:(UITableViewCell*)cell cellForRowAtIndexPath:(NSIndexPath*)indexPath { UIImageView *normalCellBG = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, cell.frame.size.width, cell.frame.size.height)]; [normalCellBG setImage:[UIImage imageNamed:@"box_nonselected.png"]];//Set Image for Normal [normalCellBG setBackgroundColor:[UIColor clearColor]]; [cell setBackgroundView:normalCellBG]; UIImageView *selecetedCellBG = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, cell.frame.size.width, cell.frame.size.height)]; [selecetedCellBG setImage:[UIImage imageNamed:@"box_selected.png"]];//Set Name for selected Cell [selecetedCellBG setBackgroundColor:[UIColor clearColor]]; [cell setSelectedBackgroundView:selecetedCellBG ]; } </code></pre>9563006440	0	Xcode File management. What is best practice? <p>I've been using Xcode for a while now. One thing that always bugs me is the way it handles files. I like to have my files all in nested folders rather than one big physical folder, but when you create a group in Xcode by default it does not create a folder just a virtual folder within the project.</p> <p>I can see that virtual folders are great for linking code in arbitrary places into your project but once you get beyond a few classes I find the one big folder approach really painful. And then if you try to fix it later it takes ages and is easy to break your build.</p> <p>Is it possible to change this behaviour so that by default it creates a physical folder? Or am I doing it wrong and trying to cling to some other way of working? How do other people work with files in Xcode?</p>95738052724	0	 <p><code>format</code> is a method of <code>str</code> so you should call that from your string, then pass the result of that into <code>print</code>.</p> <pre><code>print ("So you are {name} and you are{age}".format(name=my_name,age=my_age)) </code></pre>9583983809	0	 <p>If your goal is to make a game per se with the requirements of developing on OSX and running anywhere it's sounding a lot like Unity3D would be a good match. On this path you'll end up coding in UnityScript and or C# probably. It gives you a lot of tools in a package and it's popular in games development circles. So it sounds like a good match for you too me. </p> <p>If you just want to learn, you can use whatever language you like. Something fairly popular if you want readily tranferrable skills. I wouldn't worry too much about performance if you're just learning concepts. Languages are a dime a dozen and most will teach you a strong basis to build on.</p> <p>If you want to become a professional games developer for a big name studio working on consoles you might want to consider learning some C or C++ - particularly to understand memory management, pointers and some other low level concepts. </p>95914044514	0	Can't get data from a codeigniter function with ajax <p>This is what I've got so far:</p> <p>This function that returns data from the model:</p> <pre><code>function get_user2() { $this-&gt;load-&gt;model('my_model'); $id=$this-&gt;input-&gt;post('users1'); $users2=$this-&gt;my_model-&gt;get_relations($id); return $users2; } </code></pre> <p>the model function:</p> <pre><code>function get_relations($usr) { $this-&gt;db-&gt;where('id',$usr); $rel=$this-&gt;db-&gt;get('relacion'); if($rel-&gt;num_rows!=0) { $relacion=array(); foreach ($rel-&gt;result_array() as $row) { $relacion[]=array( 'id'=&gt;$row['id'], 'username1'=&gt;$row['username1'], 'username2'=&gt;$row['username2'], ); } return $relacion; }else{ return false; } } </code></pre> <p>and in my view:</p> <pre><code>&lt;select name="users1" id="drop1"&gt; &lt;?php if($opciones!=false){ foreach ($opciones as $row) { echo '&lt;option value="'.$row['user_id'].'"&gt;'.$row['username'].'&lt;/option&gt;'; } } ?&gt; &lt;/select&gt; &lt;script src="jquery.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; $("#drop1").change(function(){ $.ajax({ type: "POST", url: "example.com/CI/index.php/evaluation/get_user2", data: "users1="+$('#drop1').val(), success: function(){ alert('it works!'); } }); }); &lt;/script&gt; </code></pre> <p>I want to fill a second dropdown with the options returned by the controller function, but the ajax request doesn't do anything so I haven't even got to that part. Can someone help me spot what's wrong? I already tested the controller and model's function and they work. And could you tell me how to fill the second dropdown's options? Thank you very much!</p>96018947308	0	Horizontal manager alignment of its child view? <p>How can I align a child view in the horizontal LinearLayout? I have two textviews (width height is wrap_content) in the horizontal manager. How I can align one to right and the other one to the left? </p>9613072316	0	how do i receive messages sent to gtalk? <p>im making an application that needs to get received messages that were sent to google chat. is there an api for working with google chat?</p> <p>can someone please give me an example in C# how do i receive gtalk messages? im sorry the xmpp documentation is too complex and i do not understand where to start</p>96232187702	0	How to call Pinch and Zoom class on am ImageView? <p>I am a newbie to android development. Here I am trying to add pinch and zoom an image in my image view. The image is loaded on an activity called FullScreenView</p> <p>Here is my FullScreenView.java file</p> <pre><code>public class FullScreenViewActivity extends Activity implements OnClickListener { private static final String TAG = FullScreenViewActivity.class .getSimpleName(); public static final String TAG_SEL_IMAGE = "selectedImage"; private Wallpaper selectedPhoto; private ImageView fullImageView; private LinearLayout llSetWallpaper, llDownloadWallpaper,btShare; private Utils utils; private ProgressBar pbLoader; InterstitialAd mInterstitialAd; // Picasa JSON response node keys private static final String TAG_ENTRY = "entry", TAG_MEDIA_GROUP = "media$group", TAG_MEDIA_CONTENT = "media$content", TAG_IMG_URL = "url", TAG_IMG_WIDTH = "width", TAG_IMG_HEIGHT = "height"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_fullscreen_image); //add code AdView mAdView = (AdView) findViewById(R.id.adView); AdRequest adRequest = new AdRequest.Builder().build(); mAdView.loadAd(adRequest); mInterstitialAd = new InterstitialAd(this); mInterstitialAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712"); requestNewInterstitial(); fullImageView = (ImageView) findViewById(R.id.imgFullscreen); llSetWallpaper = (LinearLayout) findViewById(R.id.llSetWallpaper); llDownloadWallpaper = (LinearLayout) findViewById(R.id.llDownloadWallpaper); btShare = (LinearLayout) findViewById(R.id.btShare); pbLoader = (ProgressBar) findViewById(R.id.pbLoader); // hide the action bar in fullscreen mode getActionBar().hide(); utils = new Utils(getApplicationContext()); // layout click listeners llSetWallpaper.setOnClickListener(this); llDownloadWallpaper.setOnClickListener(this); btShare.setOnClickListener(this); // setting layout buttons alpha/opacity llSetWallpaper.getBackground().setAlpha(70); llDownloadWallpaper.getBackground().setAlpha(70); btShare.getBackground().setAlpha(70); Intent i = getIntent(); selectedPhoto = (Wallpaper) i.getSerializableExtra(TAG_SEL_IMAGE); // check for selected photo null if (selectedPhoto != null) { // fetch photo full resolution image by making another json request fetchFullResolutionImage(); } else { Toast.makeText(getApplicationContext(), getString(R.string.msg_unknown_error), Toast.LENGTH_SHORT) .show(); } } private void requestNewInterstitial() { AdRequest adRequest = new AdRequest.Builder() .addTestDevice("PFSW5H65PRTS9TTO") .build(); mInterstitialAd.loadAd(adRequest); } /** * Fetching image fullresolution json * */ private void fetchFullResolutionImage() { String url = selectedPhoto.getPhotoJson(); // show loader before making request pbLoader.setVisibility(View.VISIBLE); llSetWallpaper.setVisibility(View.GONE); llDownloadWallpaper.setVisibility(View.GONE); btShare.setVisibility(View.GONE); // volley's json obj request JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET, url, null, new Response.Listener&lt;JSONObject&gt;() { @Override public void onResponse(JSONObject response) { Log.d(TAG, "Image full resolution json: " + response.toString()); try { // Parsing the json response JSONObject entry = response .getJSONObject(TAG_ENTRY); JSONArray mediacontentArry = entry.getJSONObject( TAG_MEDIA_GROUP).getJSONArray( TAG_MEDIA_CONTENT); JSONObject mediaObj = (JSONObject) mediacontentArry .get(0); final String fullResolutionUrl = mediaObj .getString(TAG_IMG_URL); // image full resolution widht and height final int width = mediaObj.getInt(TAG_IMG_WIDTH); final int height = mediaObj.getInt(TAG_IMG_HEIGHT); Log.d(TAG, "Full resolution image. url: " + fullResolutionUrl + ", w: " + width + ", h: " + height); ImageLoader imageLoader = AppController .getInstance().getImageLoader(); // We download image into ImageView instead of // NetworkImageView to have callback methods // Currently NetworkImageView doesn't have callback // methods imageLoader.get(fullResolutionUrl, new ImageListener() { @Override public void onErrorResponse( VolleyError arg0) { Toast.makeText( getApplicationContext(), getString(R.string.msg_wall_fetch_error), Toast.LENGTH_LONG).show(); } @Override public void onResponse( ImageContainer response, boolean arg1) { if (response.getBitmap() != null) { // load bitmap into imageview fullImageView .setImageBitmap(response .getBitmap()); adjustImageAspect(width, height); // hide loader and show set &amp; // download buttons pbLoader.setVisibility(View.GONE); llSetWallpaper .setVisibility(View.VISIBLE); llDownloadWallpaper .setVisibility(View.VISIBLE); btShare .setVisibility(View.VISIBLE); } } }); } catch (JSONException e) { e.printStackTrace(); Toast.makeText(getApplicationContext(), getString(R.string.msg_unknown_error), Toast.LENGTH_LONG).show(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e(TAG, "Error: " + error.getMessage()); // unable to fetch wallpapers // either google username is wrong or // devices doesn't have internet connection Toast.makeText(getApplicationContext(), getString(R.string.msg_wall_fetch_error), Toast.LENGTH_LONG).show(); } }); // Remove the url from cache AppController.getInstance().getRequestQueue().getCache().remove(url); // Disable the cache for this url, so that it always fetches updated // json jsonObjReq.setShouldCache(false); // Adding request to request queue AppController.getInstance().addToRequestQueue(jsonObjReq); } /** * Adjusting the image aspect ration to scroll horizontally, Image height * will be screen height, width will be calculated respected to height * */ @SuppressWarnings("deprecation") @SuppressLint("NewApi") private void adjustImageAspect(int bWidth, int bHeight) { LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( LayoutParams.FILL_PARENT , LayoutParams.FILL_PARENT); if (bWidth == 0 || bHeight == 0) return; int sHeight = 0; if (android.os.Build.VERSION.SDK_INT &gt;= 13) { Display display = getWindowManager().getDefaultDisplay(); Point size = new Point(); display.getSize(size); sHeight = size.y; } else { Display display = getWindowManager().getDefaultDisplay(); sHeight = display.getHeight(); } int new_width = (int) Math.floor((double) bWidth * (double) sHeight / (double) bHeight); params.width = new_width; params.height = sHeight; Log.d(TAG, "Fullscreen image new dimensions: w = " + new_width + ", h = " + sHeight); //fullImageView.setLayoutParams(params); // fullImageView.setAdjustViewBounds(true); fullImageView.setScaleType(ImageView.ScaleType.FIT_CENTER); } /** * View click listener * */ @Override public void onClick(View v) { if (mInterstitialAd.isLoaded()) { mInterstitialAd.show(); } //else //{ // beginPlayingGame(); // } Bitmap bitmap = ((BitmapDrawable) fullImageView.getDrawable()) .getBitmap(); File cache = getApplicationContext().getExternalCacheDir(); File sharefile = new File(cache, "toshare.png"); try { FileOutputStream out = new FileOutputStream(sharefile); bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out); out.flush(); out.close(); } catch (IOException e) { } switch (v.getId()) { // button Download Wallpaper tapped case R.id.llDownloadWallpaper: utils.saveImageToSDCard(bitmap); break; // button Set As Wallpaper tapped case R.id.llSetWallpaper: utils.setAsWallpaper(bitmap); break; case R.id.btShare: Intent share = new Intent(android.content.Intent.ACTION_SEND); share.setType("image/*"); share.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + sharefile)); try { startActivity(Intent.createChooser(share, "Share photo")); } catch (Exception e) { } break; default: break; } } } </code></pre> <p>I also create the class for bringing pinch and zoom facility to this.</p> <p>ZoomableImageView.java</p> <pre><code>public class ZoomableImageView extends View { //Code goes here } </code></pre> <p>How to call this ZoomableImageView java class file to FullScreenViewActivity so that,when i pinch and zoom, it get works...</p>96328844383	0	Deploy Node.js app to AWS elastic beanstalk that contains static assets <p>I'm having some trouble visualizing how I should handle static assets with my EB Node.js app. It only deploys whats committed in the git repo when you do <code>eb deploy</code> (correct?) but I don't want to commit all our static files. Currently we are uploading to S3 and the app references those (<code>the.s3.url.com/ourbucket/built.js</code>), but now that we are setting up dev, staging, and prod envs we can reference <code>built.js</code> since there can be up to 3 versions of it. </p> <p>Also, there's a timespan where the files are uploaded and the app is rolling out and the static assets don't work with the two versions up on the servers (i.e. built.js works with app version 0.0.2 but server one is deploy 0.0.1 and server two is running version 0.0.2)</p> <p>How do keep track of these mismatches or is there a way to just deploy a static assets to the EB instance directly.</p>96437262091	0	Analog timepicker inside scrollView not displaying time chooser <p>So, in portrait mode is displayed correctly, no matter if timePicker is in scrollView or not.</p> <p><a href="https://i.stack.imgur.com/KPYVu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KPYVu.png" alt="enter image description here"></a></p> <p>Landscape mode when is inside scroolView.</p> <p><a href="https://i.stack.imgur.com/c4Tti.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/c4Tti.png" alt="enter image description here"></a></p> <p>Landscape mode when there is no scroolView.</p> <p><a href="https://i.stack.imgur.com/BM3eU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BM3eU.png" alt="enter image description here"></a></p> <p>[Edit] Code:</p> <pre><code>&lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.aapps.groupalarmclock.NewAlarmActivity"&gt; &lt;ImageView android:layout_width="match_parent" android:layout_height="match_parent" android:scaleType="centerCrop" android:src="@drawable/background" android:alpha="@dimen/background_transparency" android:layout_centerHorizontal="true" /&gt; &lt;LinearLayout android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="@dimen/toolbar_height" android:layout_alignParentTop="true" android:weightSum="2" android:background="@color/colorToolbar" android:gravity="center_vertical" android:id="@+id/linearLayout"&gt; &lt;RelativeLayout android:layout_width="0dp" android:layout_height="match_parent" android:id="@+id/rl_cancle" android:layout_weight="1" android:background="@drawable/click_effect" android:gravity="center"&gt; &lt;ImageView android:layout_width="@dimen/toolbar_icon_size" android:layout_height="@dimen/toolbar_icon_size" android:id="@+id/iv_cancel" android:src="@drawable/cancel" android:layout_centerVertical="true" android:layout_centerHorizontal="true" android:layout_marginRight="@dimen/cancel_done_right_margin" android:layout_marginEnd="@dimen/cancel_done_right_margin"/&gt; &lt;TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" android:textColor="@color/colorText" android:id="@+id/tv_cancel" android:layout_centerVertical="true" android:layout_toRightOf="@+id/iv_cancel" android:layout_toEndOf="@+id/iv_cancel" /&gt; &lt;/RelativeLayout&gt; &lt;View android:layout_width="1dp" android:layout_height="@dimen/separator_height" android:background="@color/colorLineSeparator" android:id="@+id/v_cancel_done"&gt; &lt;/View&gt; &lt;RelativeLayout android:layout_width="0dp" android:layout_height="match_parent" android:id="@+id/rl_done" android:layout_weight="1" android:background="@drawable/click_effect" android:gravity="center"&gt; &lt;ImageView android:layout_width="@dimen/toolbar_icon_size" android:layout_height="@dimen/toolbar_icon_size" android:id="@+id/iv_done" android:src="@drawable/done" android:layout_centerVertical="true" android:layout_centerHorizontal="true" android:layout_marginRight="@dimen/cancel_done_right_margin" android:layout_marginEnd="@dimen/cancel_done_right_margin"/&gt; &lt;TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" android:textColor="@color/colorText" android:id="@+id/tv_done" android:layout_centerVertical="true" android:layout_toRightOf="@+id/iv_done" android:layout_toEndOf="@+id/iv_done" /&gt; &lt;/RelativeLayout&gt; &lt;/LinearLayout&gt; &lt;ScrollView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/scrollView" android:layout_below="@+id/linearLayout" android:layout_centerHorizontal="true" android:fillViewport="true"&gt; &lt;RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/lltp"&gt; &lt;TimePicker tools:targetApi="23" android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/timePicker" android:timePickerMode="clock" android:background="#80FFFFFF"/&gt; &lt;/RelativeLayout&gt; &lt;/ScrollView&gt; </code></pre> <p></p> <p>Anyone know what is wrong?</p>9651274738	0	 <p>You could use <a href="http://docs.jquery.com/Traversing/contains" rel="nofollow noreferrer">Traversing/contains</a> also:</p> <pre><code>$('ul#accordion a').contains(bctext); </code></pre>96637067215	0	 <p>Finally I managed to access it from my computer. I had to modify the configuration file for the operation center, located in <code>/etc/opscenter/opscenterd.conf</code> (only for package installation):</p> <pre><code>[webserver] port = 8888 interface = 127.0.0.1 </code></pre> <p>By default the webserver accepts requests only from the localhost. Probably it won't be the best option, but since the operation center allows to configure users, I set <code>interface = 0.0.0.0</code>, allowing any host to contact it. </p>96712780917	0	 <p>Your echos are failing;</p> <p><code>echo(&lt;p&gt;test1&lt;/p&gt;);</code> should be <code>echo('&lt;p&gt;test1&lt;/p&gt;');</code></p> <p>and <code>echo(&lt;h1&gt;fail&lt;/h1&gt;);</code> should be <code>echo('&lt;h1&gt;fail&lt;/h1&gt;');</code></p> <p>FYI: echo doesn't require brackets, you could do <code>echo '&lt;h1&gt;fail&lt;/h1&gt;';</code> </p>96813769307	0	 <blockquote> <p>product_size alone will not be a PK and so I cannot reference it</p> </blockquote> <p>Imagine you have two rows in <code>product_stock</code> table that have the same <code>product_size</code> (and different <code>product_code</code>). Now imagine one of these rows (but not the other) is deleted. </p> <ul> <li>Should that be restricted because there are <code>orderline</code> rows that reference it? </li> <li>Or should it be allowed because there still exists the other <code>product_stock</code> row, that <code>orderline</code> rows <em>also</em> reference?</li> </ul> <p><em>(Similar problems exist for ON DELETE CASCADE / SET NULL and also when UPDATE-ing the PK.)</em></p> <p>To avoid these kinds of ambiguities, the DBMS won't let you create a foreign key unless you can uniquely identify parent row, meaning you must use the <strong>whole</strong> key after the REFERENCES clause of your FK.</p> <hr> <p>That being said, you could create both...</p> <pre><code>FOREIGN KEY (product_code) REFERENCES product (product_code) </code></pre> <p>...and...</p> <pre><code>FOREIGN KEY (product_code, product_size) REFERENCES product_stock (product_code, product_size) </code></pre> <p>Although, if you have the latter, the former is <em>probably</em> redundant.</p> <p>In fact, (since you already have the FK <code>product_stock -&gt; product</code>), having both FKs would create a "diamond shaped" dependency. BTW, some DMBSes have restrictions on diamond-shaped FKs (MS SQL Server doesn't support cascading referential actions on them).</p>96936168438	0	 <p>I just realized that if in eclipse i check "<code>use system default php.ini</code>" under <code>window-&gt;preferences-&gt;php-&gt;phpexecutables</code> it will magically work.</p> <p>Does anyone know what is "system default php.ini"?</p> <p>I do a a quick <code>$php --ini</code> and it returns:</p> <pre><code>Configuration File (php.ini) Path: /etc/php5/cli Loaded Configuration File: /etc/php5/cli/php.ini Scan for additional .ini files in: /etc/php5/cli/conf.d Additional .ini files parsed: /etc/php5/cli/conf.d/05-opcache.ini, /etc/php5/cli/conf.d/10-mysqlnd.ini, /etc/php5/cli/conf.d/10-pdo.ini, /etc/php5/cli/conf.d/20-json.ini, /etc/php5/cli/conf.d/20-mysql.ini, /etc/php5/cli/conf.d/20-mysqli.ini, /etc/php5/cli/conf.d/20-pdo_mysql.ini, /etc/php5/cli/conf.d/20-readline.ini </code></pre>9704078397	0	 <p>I found Scintilla to be very feature-packed, and covered everything I needed. You have to do a bit of work to get all the functionality out of it (ensuring that keyboard short-cuts perform the desired effect, etceteras), but it was incredibly easy to compile, include and get working, though as I said you have to do a bit of legwork to get everything out of it, but this is better than having to tear your hair out getting an "all-purpose" control to stop doing something you don't want to. It is as if the authors have given you a toolbox to work with.</p>97140079467	0	 <p>First of all, to check if the number is even just check the modulus by 2, no need to check if the last digit is 2 or 4 or 6 or 8. I would substitute all your checks with <code>next1%2==0</code>, <code>next1%5==0</code> and <code>next1%10==0</code>, also you need to change every <code>cout&lt;&lt;next2</code> to <code>cout&lt;&lt;next1</code> because <code>next2</code> is modulus of 10 of <code>next1</code>. Also as a good practice I suggest you to read Straustrup C++ book to get the basics of C++.</p>9728294873	0	What is the right way to add invisible text for a resizeable logo <p>I want to do 2 things:</p> <ol> <li>Know that I am <strong>SEO friendly</strong> and that I inserted correctly the text (so search engines would know that this is "my logo"</li> <li><p>Learn how to <strong>resize the logo</strong> in case the screen is lower than a specific width (assuming that I know how to work with media-queries)</p> <pre><code>&lt;div id="myLogo"&gt; &lt;a href="#"&gt; &lt;img src="css/img/my_logo.png" alt="My Logo"&gt; &lt;/a&gt; &lt;/div&gt;&lt;!--End of #myLogo--&gt; </code></pre></li> </ol> <p>What should I do to achieve them both? What should be my CSS and did I wrote the code correctly?</p>97326297202	0	 <p>I had the same problem. The only workaround I found was to reduce the number of new Image() to use (ideally one):</p> <pre><code>function ImageLoader() { var img = new Image(); var queue = []; var lock = false; var lastURL; var lastLoadOk; return { load: load }; function load(url, callback, errorCallback) { if (lock) return queue.push(arguments); lock = true; if (lastURL === url) return lastLoadOk ? onload() : onerror(); lastURL = url; img.onload = onload; img.onerror = onerror; img.src = url; function onload() { lastLoadOk = true; callback(img); oncomplete(); } function onerror() { lastLoadOk = false; if (errorCallback) errorCallback(url); oncomplete(); } } function oncomplete() { lock = false; if (queue.length) load.apply(null, queue.shift()); } } var loader = new ImageLoader(); loader.load(url1, function(img) { // do something }); loader.load(url2, function(img) { // do something }); </code></pre> <p>Note that images will be loaded in serie. If if want to load 2 images in parallel, you'll need to instantiate 2 ImageLoader.</p>97440266753	0	Multiple operations in ternary operator <p>Is it possible to have multiple operations within a ternary operator's if/else?</p> <p>I've come up with an example below, probably not the best example but I hope you get what I mean.</p> <pre><code>var totalCount = 0; var oddCount = 0; var evenCount = 0; for(var i = 0; i &lt; arr.length; i++) { if(arr[i] % 2 === 0) { evenCount ++; totalCount ++; } else { oddCount ++; totalCount ++; } } </code></pre> <p>into something like:</p> <pre><code>var totalCount = 0; var oddCount = 0; var evenCount = 0; for(var i = 0; i &lt; arr.length; i++) { arr[i] % 2 === 0? evenCount ++ totalCount ++ : oddCount ++ totalCount ++; } } </code></pre>97527196026	0	 <pre><code> ALTER TABLE table_name ADD COLUMN column_name datatype </code></pre> <p>correct syntax </p> <pre><code>ALTER TABLE `WeatherCenter` ADD COLUMN BarometricPressure SMALLINT NOT NULL, ADD COLUMN CloudType VARCHAR(70) NOT NULL, ADD COLUMN WhenLikelyToRain VARCHAR(30) NOT NULL; </code></pre> <p>check <a href="http://dev.mysql.com/doc/refman/5.1/en/alter-table.html">syntax</a> </p>97624260321	0	Work with version control Offline \ Online <p>How can I change the status from version control work offline to working online using the API? </p> <p>Can I do it to all of the model or to a particular package?</p>97717908090	0	How to Validate Column with Same Value? <p>How to validate the column with same value, i try with this code :</p> <pre><code>protected void ASPxGridView1_RowValidating(object sender, DevExpress.Web.Data.ASPxDataValidationEventArgs e) { XPQuery&lt;Inventory_Library.Inventory.t_barang_master&gt; q = new XPQuery&lt;Inventory_Library.Inventory.t_barang_master&gt;(ses); List&lt;Inventory_Library.Inventory.t_barang_master&gt; lst = (from o in q where (o.nama_barang == e.OldValues["nama_barang"] &amp;&amp; o.kode_barang == e.OldValues["kode_barang"]) select o).ToList&lt;Inventory_Library.Inventory.t_barang_master&gt;(); if (lst.Contains(e.OldValues["nama_barang"])) { e.RowError = "Nama barang yang anda masukkan telah terdaftar dalam sistem"; } else if (lst.Contains(e.OldValues["kode_barang"])) { e.RowError = "Kode barang yang anda masukkan telah terdaftar dalam sistem"; } } </code></pre> <p>but that's not work, how to solve this problem, thanks for the answer</p>97834032027	0	 <p>I would recommend that you look into breaking this down into parts. For example, do you have the login working on the web portion (rails)? If so then you can begin to try to get it to work on the iOS side. Next I would recommend you look into POST and GET requests as a basic way of talking to a back end. Once you have gotten simple apps to work with that then you might have a better idea of the path that lies ahead.</p>97919697644	0	Successful implementation of user online or not <p>I have a Java EE 7 application with Spring MVC, which is a web service for mobile application as a final school project. I attribute a Calendar for the last request received and Boolean "Online" for each user. So here's my problem implementer how well a system will change the attribute of the user in my DB if the web service no longer get from the user's request after X minutes?</p> <p>I need to make a class that implements Runnable and make an infinite loop on my DB looking the Online User and compares how long that has made a request?</p> <p>If the answer is yes how to do a method that is still running?</p> <p>Sorry for my english I'm not English.</p>98023498294	0	Linq to Entities SQL Multiple LIKE statements <p>I have to search an Entity by some values, the ones empty I don't have to consider them but the others I have to use a LIKE statement using Linq to Entities.</p> <p>The result I want to obtain should be similar to this SQL,</p> <pre><code>... WHERE (@taxid = '' OR m.taxid LIKE @taxid + '%') AND (@personalid = '' OR m.personalid LIKE @personalid + '%') AND (@certificate = '' OR m.certificate LIKE @certificate + '%') </code></pre> <p>My Linq to Entities looks like:</p> <pre><code>persons = context.Persons.Where(e =&gt; e.TaxId.Contains(taxId) &amp;&amp; e.PersonalId.Contains(personalId) &amp;&amp; e.Certificate.Contains(certificate)).ToList(); </code></pre> <p>Any clue?</p>981679088	0	 <p>I would go with "from" + confirmation, to avoid forging.</p> <p>I.e. receive the email, but send a response with auth token in the subject line (or in the body) back to the "from" address. The user either will need reply, or click a link to confirm the submission.</p> <p>And you post the content only after confirmation.</p>9821688307	0	 <p>Start the MonoDevelop program and select "New Solution" and then select the iPhone template.</p> <p>There are a handful of walk through documents like: <a href="http://monotouch.net/Tutorials/MonoDevelop_HelloWorld" rel="nofollow noreferrer">http://monotouch.net/Tutorials/MonoDevelop_HelloWorld</a></p> <p>Or a complete step-by-step screencast here:</p> <p><a href="http://www.codesnack.com/blog/2009/9/20/getting-started-with-monotouch.html" rel="nofollow noreferrer">http://www.codesnack.com/blog/2009/9/20/getting-started-with-monotouch.html</a></p> <p>Building Hello world: <a href="http://tv.falafel.com/iphone/09-09-18/Writing_your_First_IPhone_application_in_C_using_MonoTouch.aspx" rel="nofollow noreferrer">http://tv.falafel.com/iphone/09-09-18/Writing_your_First_IPhone_application_in_C_using_MonoTouch.aspx</a></p>9834802728	0	 <p>Have you looked at <code>ObjectDataSource</code>? You configure it by providing the the names of your C# methods responsible for the CRUD operations. Then in your methods you can do whatever you want.</p>98416239106	0	Finding a row by position <p>I am getting an error at position 1996250 in my mysql replication. How can I find out what table/row is at that position?</p>98534958453	0	 <p>Try to perform the action in a background-queue using the following code:</p> <pre><code>SwiftSpinner.show("Generating new calendar for \(forYear)", animated: true) dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), { let calendar = generateCalendarFor(forYear) print("GENERATED NEW calendar for \(forYear)") dispatch_async(dispatch_get_main_queue(), { SwiftSpinner.show("Saving calendar", animated: false) }) saveNew(calendar, year: forYear) dispatch_async(dispatch_get_main_queue(), { SwiftSpinner.hide() onCompletion(calendar) }) }) </code></pre> <p>What you do here:</p> <ul> <li>you create a background-queue</li> <li>create the calendar</li> <li>update the UI from the main-queue (<code>dispatch_async(dispatch_get_main_queue(), { SwiftSpinner.show("Saving calendar", animated: false) })</code> (main-queue is important because the UI shpuld only be modified from the main-queue)</li> <li>save the calendar (in the background-queue again)</li> <li>call a custom function (here I named it <code>onCompletion</code> in the main-queue which does something with the calendar (replaces <code>return calendar</code>)</li> </ul> <p>You should make sure that your UI-buttons etc. are disabled before <code>dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), { ... })</code> gets called and enabled again in <code>onCompletion</code> else the user would be able to press some buttons while your app is working (and maybe change some data used by the queue -> not good).</p> <p><strong>Why:</strong> The UI is updated from the main-queue, but usually not immediately after you call the code to update it; if you block the main-queue, your UI cannot be updated. So we do the work in a background-queue so your main-queue can update the UI.</p> <p><strong>In detail:</strong> You call <code>dispatch_async</code> (from GrandCentralDispatch) which creates a new queue with the priority <code>QOS_CLASS_USER_INITIATED</code> (~normal priority). Then it passes the code in the curly braces to this queue; the OS will execute the queue in a separate thread. Because the UI must only be modified from the main-queue, we pass the code that updates the UI (<code>SwiftSpinner.show("Saving calendar", animated: false)</code>) to the main-queue by using <code>dispatch_async</code> again.</p> <p>The use of a completion-function is necessary because the code/queue is executed in the background and independently from <code>getOrCreateCalendar</code>; your function probably returns before the queue is completed and the calendar created and saved.</p>98625765221	0	What is the point of splitting up a project into 2 separate projects? <p>A lot of times I see people splitting up a Project into 2 separate projects, like in this screenshot: </p> <p><img src="https://i.stack.imgur.com/Xvgkl.png" alt="enter image description here"></p> <p>What is the point of seperating Ingot and IngotAPI instead of putting them both in the same project because they get compiled together anyways?</p>98715133470	0	 <p>You can have 6 unique games between 4 teams. There are 7 possible pairing hence 42 unique games.</p> <p>Each player pairs up with every other player only once and play against each one of them 6 times exactly.</p> <p>List:</p> <pre><code>Pairs 01: (1,2),(3,4),(5,6),(7,8) PairRound 1: GameRound 01: (1,2) - (3,4) | (5,6) - (7,8) GameRound 02: (1,2) - (7,8) | (3,4) - (5,6) GameRound 03: (1,2) - (5,6) | (3,4) - (7,8) Pairs 02: (1,3),(2,4),(5,7),(6,8) PairRound 2: GameRound 04: (1,3) - (2,4) | (5,7) - (6,8) GameRound 05: (1,3) - (6,8) | (2,4) - (5,7) GameRound 06: (1,3) - (5,7) | (2,4) - (6,8) Pairs 03: (1,4),(2,3),(5,8),(6,7) PairRound 3: GameRound 07: (1,4) - (2,3) | (6,7) - (5,8) GameRound 08: (1,4) - (5,8) | (2,3) - (6,7) GameRound 09: (1,4) - (6,7) | (2,3) - (5,8) Pairs 04: (1,5),(2,6),(3,7),(4,8) PairRound 4: GameRound 10: (1,5) - (2,6) | (3,7) - (4,8) GameRound 11: (1,5) - (4,8) | (2,6) - (3,7) GameRound 12: (1,5) - (3,7) | (2,6) - (4,8) Pairs 05: (1,6),(2,5),(3,8),(4,7) PairRound 5: GameRound 13: (1,6) - (2,5) | (3,8) - (4,7) GameRound 14: (1,6) - (4,7) | (2,5) - (3,8) GameRound 15: (1,6) - (3,8) | (2,5) - (4,7) Pairs 06: (1,7),(2,8),(3,5),(4,6) PairRound 6: GameRound 16: (1,7) - (2,8) | (3,5) - (4,6) GameRound 17: (1,7) - (4,6) | (2,8) - (3,5) GameRound 18: (1,7) - (3,5) | (2,8) - (4,6) Pairs 07: (1,8),(2,7),(3,6),(4,5) PairRound 8: GameRound 19: (1,8) - (2,7) | (3,6) - (4,5) GameRound 20: (1,8) - (4,5) | (2,7) - (3,6) GameRound 21: (1,8) - (3,6) | (2,7) - (4,5) </code></pre>98826053837	0	ajax function not opening a page <p>i don't understand why ajax is not working. my code:</p> <pre><code>&lt;script type="text/javascript" src="js/jquery-1.9.1.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; function edit_row(id) { $.ajax({ method:'get', url:'form.php', success:function(data) { $('#form_div').html(data); } }); } </code></pre> <pre><code>&lt;?php echo '&lt;td style='.$style.'&gt;'.$status.'&lt;a href="" title="Edit" onClick=edit_row('.$data['type_id'].')&gt;&lt;img src="images/pencil.png" width="30px" height="30px"&gt;&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;'; ?&gt; </code></pre> <p>its not opening form.php onclick what is the problem please help me!!!</p>98935972058	0	 <pre><code>class Letter { char c; boolean isRevealed; //... getters and setters } Letter[] word = new Letter[MAX_WORD_LENGTH]; private boolean isGuessRight(char chr){ for (int i = 0 ; i &lt; word.length ; i++){ if (word[i].getChar() == chr &amp;&amp; word[i].getRevealed() == false){ word[i].reveal(); return true; } else if (word[i] == chr &amp;&amp; word[i].getRevealed()){ return false; } } } </code></pre>99015119711	0	 <p>Let's say branches <code>A</code> and <code>B</code>, standing on <code>A</code>, file <code>f</code> was modified (and not checked into <code>A</code>), while <code>B</code> contains another version. If I try to rebase <code>B</code> onto <code>A</code>, the local changes for <code>f</code> are lost. Solution: Commit the changes to <code>f</code>, or stash them away for later, or perhaps discard them by <code>git checkout f</code>.</p> <p>That is what the message says, in a nutshell.</p> <p>If you "tried again until it worked", you probably lost changes like the above.</p> <p><strong>Morals of the story:</strong> If you want to do any more complex operation with <code>git</code> (like pulling from upstream, rebasing, changing last commit, ...) make <em>sure</em> everything is tidy. I.e., <code>git status</code> says it is clean, and hopefully no untracked files.</p>99121507914	0	Bad credentials Exception | Spring Security <p>Trying to use Spring security for authentication process, but getting <code>Bad credentials</code> exception.here is how I have defined things in my <code>spring-security.xml</code> file</p> <pre><code>&lt;beans:bean id="passwordEncoder" class="org.springframework.security.authentication.encoding.ShaPasswordEncoder"&gt; &lt;/beans:bean&gt; &lt;beans:bean id="passwordEncoder" class="org.springframework.security.authentication.encoding.ShaPasswordEncoder"&gt; &lt;/beans:bean&gt; &lt;authentication-manager id="customerAuthenticationManager"&gt; &lt;authentication-provider user-service-ref="customerDetailsService"&gt; &lt;password-encoder hash="sha" /&gt; &lt;/authentication-provider&gt; &lt;/authentication-manager&gt; </code></pre> <p><code>customerDetailsService</code> is our own implementation being provided to spring security.In my Java code while registering user, I am encoding provided password before adding password to Database something like</p> <pre><code>import org.springframework.security.authentication.encoding.PasswordEncoder; @Autowired private PasswordEncoder passwordEncoder; customerModel.setPassword(passwordEncoder.encodePassword(customer.getPwd(), null)); </code></pre> <p>When I tried to debug my application, it seems Spring is calling <code>AbstractUserDetailsAuthenticationProvider</code> authenticate method and when its performing additionalAuthenticationCheck with <code>additionalAuthenticationChecks(user, (UsernamePasswordAuthenticationToken) authentication);</code> of <code>DaoAuthenticationProvider</code>, it throwing Bad credential exception at following point</p> <pre><code>if (authentication.getCredentials() == null) { logger.debug("Authentication failed: no credentials provided"); throw new BadCredentialsException(messages.getMessage( "AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"), userDetails); } </code></pre> <p>I am not sure where I am doing wrong and what needs to be done here to put things in right place, I already checked customer is there in database and password is encoded.</p>99212095153	0	 <blockquote> <p>Is there any way to check a user has like a facebook page without permission request?</p> </blockquote> <p>Only if your app is running as a page tab app on that Facebook page.</p> <p>If so, the info is contained inside the <code>signed_request</code> parameter.</p>99330460279	0	 <p>following query works fine for delete the record based on current timestamp.</p> <blockquote> <p>DELETE FROM table WHERE datecolumn = date('Y-m-d h:i A'); //'2012-05-05 10:00PM'</p> </blockquote>99426311715	0	Solving a difficult compilation issue <p>Good day,</p> <p>First up, I have a mac running Mavericks, and I am attempting to build PCL (Point Cloud Library) as part of ROS.</p> <p>This is the command that fails:</p> <pre><code>cd /Users/X/ros_catkin_ws/build_isolated/pcl_ros &amp;&amp; /Users/X/ros_catkin_ws/install_isolated/env.sh cmake -vd /Users/X/ros_catkin_ws/src/perception_pcl/pcl_ros -DCATKIN_DEVEL_PREFIX=/Users/X/ros_catkin_ws/devel_isolated/pcl_ros -DCMAKE_INSTALL_PREFIX=/Users/X/ros_catkin_ws/install_isolated -DCMAKE_BUILD_TYPE=Release </code></pre> <p>With:</p> <pre><code>CMake Error at /usr/local/share/pcl-1.8/PCLConfig.cmake:47 (message): simulation is required but glew was not found Call Stack (most recent call first): /usr/local/share/pcl-1.8/PCLConfig.cmake:500 (pcl_report_not_found) /usr/local/share/pcl-1.8/PCLConfig.cmake:663 (find_external_library) CMakeLists.txt:8 (find_package) </code></pre> <p>Now, I have done what I can to debug this. Looking up online, I notice this is happening due to the fact that in Mavericks, there is no longer the GLEW.framework <a href="https://github.com/PointCloudLibrary/pcl/issues/492" rel="nofollow">https://github.com/PointCloudLibrary/pcl/issues/492</a></p> <p>Hence, I installed it via brew, and yet I still get the same issue. Now, I'm thinking, perhaps cmake cannot find it, so I created my own cmake project, and attempted to add find_package(glew). It seems to have found the package here:</p> <pre><code>-- Found GLEW: /usr/local/include </code></pre> <p>Hence, I included /usr/local/include in my $PATH variable. Yet once again, it seems to fail with the same error. I am kind of at a lost here, and am not sure how to continue. I am speculating that in the command above, it seems that somehow the env.sh there seems to change the environmental variables such that it can't find glew.</p> <p>Any thoughts?</p> <p>EDIT: <strong>More absurdity. I create a CMake file and included find_package(PCL). It works perfectly. WTF? It even says it found glew</strong></p> <pre><code>Found Glew: -framework GLEW;-framework Cocoa </code></pre> <p>How come it works in my Cmake file, but not in theirs? What might cause this</p>99527850563	0	Call new parameters on a jQuery slider depending on window size <p>I am using bxslider.js to make a slider on my page. Since my site is responsive, the code I have allows different parameters for the slider depending on the size of the window. For example, when the window is over 768px the slider shows 2 slides. When it is under 768 it shows 1 slide and when it's under 480, the slider function stops completely. All this works fine. However it only works on load. I want it to work on resize too. I've played around the the window.resize function, but I don't have enough of a programing background to really know what I am doing or what the best way to do this is. Can anyone tell me how to get this to work both on load and on resize?</p> <pre><code>var sliderWidth = $('#testimonialSlider').width(); if ($(window).width() &gt; 768) { doubleslider = $('#testimonialSlider').bxSlider({ minSlides: 2, maxSlides: 2, slideWidth: sliderWidth / 2, auto: false, moveSlides:2, autoHover:true, pager:true }); } else if ($(window).width() &lt; 480) { singleslider.destroySlider(); } else{ singleslider = $('#testimonialSlider').bxSlider({ minSlides: 1, maxSlides: 1, slideWidth: sliderWidth, auto: false, moveSlides:1, autoHover:true, pager:true }); } </code></pre>9966017914	0	 <p>There's no guarantee, but one thing you can do to protect yourself is hide the persistence implementation details behind a well-designed interface. It won't keep you from having to rewrite implementation if you switch, but it will isolate clients from the changes. You'll be able to test implementations separately and swap them in and out in a declarative fashion if you're using a dependency injection engine.</p>99727599571	0	white space below footer <p>There seems to be random white space after the footer at the bottom of the site. When I try to use inspect element, the white space doesn't seem to fall under any tags. It doesn't seem tied to any footer tags either as removing them didn't change anything. </p> <p>I'm using <a href="http://ryanfait.com/resources/footer-stick-to-bottom-of-page/" rel="nofollow">Ryan Fait's Sticky Footer solution</a> for my footer.</p> <p>You can test it at: <a href="http://www.edmhunters.com/martin-garrix/" rel="nofollow">http://www.edmhunters.com/martin-garrix/</a></p> <p>Any ideas what I'm doing wrong?</p>99827513335	0	 <p>use this method this vl definitely work 100%. </p> <pre><code>- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath; { GalleryCell *cell1 = (GalleryCell*)[_resumeCollectionView cellForItemAtIndexPath:indexPath]; cell1= nil; } </code></pre>99914085705	0	 <p>The message is just a warning. You can ignore it. If you're using Xcode, it won't even show you the warning in its Issue Navigator.</p> <p>Rename your Bison input file to have a <code>.ym</code> extension instead of a <code>.y</code> extension. That tells Xcode that it's a grammar with Objective-C actions.</p>100031869496	0	 <p>The version will start after you send it the first request (unless you use Managed VM - <a href="https://cloud.google.com/appengine/docs/managed-vms" rel="nofollow">https://cloud.google.com/appengine/docs/managed-vms</a>).</p>100129800656	0	 <p>The <code>break</code> keyword will always "break-out" of the current block of code. In this case, it is your inner for-loop.</p> <p>I think you looking for the <code>continue</code> keyword.</p>100236168997	0	 <p>This immmediate thing that jumps out at me: this is wrong:</p> <pre><code>if (section._isInViewport) { </code></pre> <p><code>_isInViewport</code> requires you to pass the element in as an argument, like so:</p> <pre><code>if (_isInViewport(section)) { </code></pre> <p>You also don't need to check the event type in the event handler. Since you're only calling that on scroll, you already know the event type is a scroll event. Instead of thing:</p> <pre><code>if (event.type === 'scroll') { _getSections(); } </code></pre> <p>You want this:</p> <pre><code>_getSections(); </code></pre>100332915370	0	 <p>This is typically what I do when I want to convert many columns in a data.frame to a different data type:</p> <pre><code>convNames &lt;- c("NY", "CHI", "LA", "ATL", "MIA") for(name in convNames) { city1[, name] &lt;- as.numeric(as.character((city1[, name])) } </code></pre> <p>It's a nice two lines and you just have to add the names of whatever columns you want to coerce to the convNames vector to add a new column to the coercing loop below.</p> <p>EDIT: Do to a factor issue, do the lapply method above.</p>100419539822	0	Exclude items of one list in another with different object data types, LINQ? <p>I have two lists filled with their own data. lets say there are two models <code>Human</code> and <code>AnotherHuman</code>. Each model contains different fields, however they have some common fields like <code>LastName, FirstName, Birthday, PersonalID</code>.</p> <pre><code>List&lt;Human&gt; humans = _unitOfWork.GetHumans(); List&lt;AnotherHuman&gt; anotherHumans = _unitofWork.GetAnotherHumans(); </code></pre> <p>I would like to exclude the items from list <code>anotherHumans</code> where <code>LastName, FirstName, Birthday</code> are all equal to the corresponding fields of any item in list <code>humans</code>.</p> <p>However if any item in <code>anotherHumans</code> list has <code>PersonalID</code> and item in list <code>humans</code> have the same <code>PersonalID</code>, then it is enough to compare <code>Human</code> with <code>AnotherHuman</code> only by this <code>PersonalID</code>, otherwise by <code>LastName, FirstName and Birthday</code>.</p> <p>I tried to create new list of dublicates and exclude it from <code>anotherHumans</code>:</p> <pre><code>List&lt;AnotherHuman&gt; duplicates = new List&lt;AnotherHuman&gt;(); foreach(Human human in humans) { AnotherHuman newAnotherHuman = new AnotherHuman(); newAnotherHuman.LastName = human.LastName; newAnotherHuman.Name= human.Name; newAnotherHuman.Birthday= human.Birthday; duplicates.Add(human) } anotherHumans = anotherHumans.Except(duplicates).ToList(); </code></pre> <p>But how can I compare <code>PersonalID</code> from both lists if it presents (it is nullable). Is there any way to get rid from creating new instance of AnotherHuman and list of duplicates and use LINQ only?</p> <p>Thanks in advance!</p>100512917807	0	Simple request using googleapis to freebase <p>I would like to query freebase, to get some basic information about a celebrity. For example, I would like to get the place of birth, and the gender of Madonna.</p> <p>I achieved to get Madonna's friends by using:</p> <p><a href="https://www.googleapis.com/freebase/v1/mqlread" rel="nofollow">https://www.googleapis.com/freebase/v1/mqlread</a>?&amp;query={"id":"/en/madonna","name":null,"type":"/base/popstra/celebrity","/base/popstra/celebrity/friendship":[{"participant":[]}]}</p> <p>But, I'm understanding this request pretty badly. How can I change it to get the information I talked above ?</p> <p>I was thinking about :</p> <p><a href="https://www.googleapis.com/freebase/v1/mqlread" rel="nofollow">https://www.googleapis.com/freebase/v1/mqlread</a>?&amp;query={"id":"/en/madonna","name":null,"type":"/base/popstra/celebrity","/base/popstra/celebrity/gender":[{"gender":}], "/base/popstra/celebrity/place_of_birth":[{"place of birth":}]} </p> <p>but it's not working ofc.</p>100612107726	0	 <p>Either make the selector more specific: </p> <pre><code>ul li ul li:first-child{background-color:transparent} </code></pre> <p>Or add a class to the UL And select the first child there:</p> <pre><code>ul.nested li:first-child{background-color: #fff;} ... &lt;li&gt;one &lt;ul class="nested"&gt; &lt;li&gt;two&lt;/li&gt; ... </code></pre> <p><a href="http://jsfiddle.net/Kyle_Sevenoaks/fX9Gy/15/" rel="nofollow">http://jsfiddle.net/Kyle_Sevenoaks/fX9Gy/15/</a></p>10071857815	0	 <p>You can't use REPLACE to create a comma delimited list for use in an <code>IN</code> clause. To use that as-is, you'd have to utilize <a href="http://dev.mysql.com/tech-resources/articles/4.1/prepared-statements.html" rel="nofollow noreferrer">MySQL's Prepared Statements</a> (effectively dynamic SQL) - creating the comma separated list first, and inserting that into the SQL query constructed as a string before executing it.</p> <pre><code>SELECT a.category_id, a.yyyymm, a.cat_balance_ytd FROM GL_VIEW_CAT_BALANCES a JOIN GL_OPTIONS o ON INSTR(o.detail2, a.category_id) AND o.option_id = 'GLREPFUNCJOB01' JOIN (SELECT b.category_id, b.gl_unique_id, MAX(b.yyyymm) 'yyyymm' FROM GL_REPCAT_BALSs b WHERE b.yyyymm &lt;= 200910 GROUP BY b.category_id, b.gl_unique_id) x ON x.category_id = a.category_id AND x.gl_unique_id = a.unique_id AND x.yyyymm = a.yyyymm WHERE a.gl_id = '/JOB//9' AND a.fin_years_ago = 0 </code></pre> <p>Here's an untested, possible non-dynamic SQL alternative, using <a href="http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_find-in-set" rel="nofollow noreferrer"><code>FIND_IN_SET</code></a>:</p> <pre><code>SELECT a.category_id, a.yyyymm, a.cat_balance_ytd FROM GL_VIEW_CAT_BALANCES a JOIN (SELECT REPLACE(o.detail_2, ' ', ', ') 'detail2_csv' FROM GL_OPTIONS o WHERE o.option_id = 'GLREPFUNCJOB01') y ON FIND_IN_SET(a.category, y.detail2_csv) &gt; 0 JOIN (SELECT b.category_id, b.gl_unique_id, MAX(b.yyyymm) 'yyyymm' FROM GL_REPCAT_BALSs b WHERE b.yyyymm &lt;= 200910 GROUP BY b.category_id, b.gl_unique_id) x ON x.category_id = a.category_id AND x.gl_unique_id = a.unique_id AND x.yyyymm = a.yyyymm WHERE a.gl_id = '/JOB//9' AND a.fin_years_ago = 0 </code></pre>100811582627	1	Python get micro time from certain date <p>I was browsing the Python guide and some search machines for a few hours now, but I can't really find an answer to my question.</p> <p>I am writing a switch where only certain files are chosen to be in the a file_list (list[]) when they are modified after a given date.</p> <p>In my loop I do the following code to get its micro time:</p> <pre><code>file_time = os.path.getmtime(path + file_name) </code></pre> <p>This returns me a nice micro time, like this: 1342715246.0</p> <p>Now I want to compare if that time is after a certain date-time I give up. So for testing purposes, I used 1790:01:01 00:00:00.</p> <pre><code># Preset (outside the class/object) start_time = '1970-01-01 00:00:00' start_time = datetime.datetime.strptime(start_time, '%Y-%m-%d %H:%M:%S') start_time = start_time.strftime("%Y-%m-%d %H:%M:%S") # In my Method this check makes sure I only append files to the list # that are modified after the given date if file_time &gt; self.start_time: file_list.append(file_name) </code></pre> <p>Of course this does not work, haha :P. What I'm aiming for is to make a micro time format from a custom date. I can only find ClassMethods online that make micro time formats from the current date.</p>10094317703	0	 <p>Seems it can't be done with the C preprocessor, at least the <a href="http://gcc.gnu.org/onlinedocs/gcc-4.5.1/cpp/Stringification.html#Stringification" rel="nofollow">gcc doc</a>s states it bluntly:</p> <blockquote> <p>There is no way to convert a macro argument into a character constant.</p> </blockquote>10105326377	0	 <p>Using a bit of psychic debugging, I'm going to guess that the strings in your application are pooled in a read-only section.</p> <p>It's possible that the CreateSysWindowsEx is attempting to write to the memory passed in for the window class or title. That would explain why the calls work when allocated on the heap (SysAllocString) but not when used as constants. </p> <p>The easiest way to investigate this is to use a low level debugger like windbg - it should break into the debugger at the point where the access violation occurs which should help figure out the problem. Don't use Visual Studio, it has a nasty habit of being helpful and hiding first chance exceptions.</p> <p>Another thing to try is to enable appverifier on your application - it's possible that it may show something.</p>10113893509	0	 <p>My only current solution uses reflection to build the <code>string</code> or paths for the <code>.Expand</code> method.</p> <pre><code>foo_entitiesctx = new foo_entities(new Uri("http://url/FooService.svc/")); ctx.MergeOption = MergeOption.AppendOnly; var collections = from pi in typeof(TestResult).GetProperties() where IsSubclassOfRawGenericCollection(pi.PropertyType) select pi.Name; var things = ctx.Things.Expand(string.Join(",", collections)); foreach (var item in things) { foreach (var child in item.ChildCollectionProperty1) { //do thing } } </code></pre> <p>(The <code>IsSubclassOfRawGenericCollection</code> method is a wrapper around the <code>IsSubclassOfRawGeneric</code> method from <a href="http://stackoverflow.com/questions/457676/c-reflection-check-if-a-class-is-derived-from-a-generic-class/457708#457708">Jared Par on SO</a>)</p>101228172523	0	 <p>something like this? <a href="http://jsfiddle.net/93zb8Lzs/6/" rel="nofollow">http://jsfiddle.net/93zb8Lzs/6/</a></p> <pre><code>&lt;img src="https://www.google.at/images/srpr/logo11w.png" width="368" height="138" alt="Logo" /&gt; &lt;!-- Nvigationselemente --&gt; &lt;div class="nav"&gt; &lt;/div&gt; img { display:block; margin:auto; } </code></pre>101329633777	0	Syntax Error OledbException delete statement <p>I can't fugure out what my syntax error is here. Anyone spot it? Or am I going about this all wrong?</p> <pre><code>Dim myCommand As New OleDb.OleDbCommand("delete * from Team where intPlayerNo='" &amp; txtUniformNo.Text &amp; "'_ strFirstName='" &amp; txtFirstName.Text &amp; "'_ strLastName='" &amp; txtLastName.Text &amp; "'_ strParentName='" &amp; txtParent.Text &amp; "'_ strAddress='" &amp; txtAddress.Text &amp; "'_ strCity='" &amp; txtCity.Text &amp; "'_ strState='" &amp; txtState.Text &amp; "'_ strZipCode='" &amp; txtZip.Text &amp; "'_ strPhone='" &amp; txtPhone.Text &amp; "'_ intAge='" &amp; txtAge.Text &amp; "'", myConnection) </code></pre>101430484473	0	 <p>The error can occur only if there exists a document in the database with some <code>_id</code>, say <code>ID1</code>, and you are trying to insert a new document which has <code>ID1</code> as its value for <code>_id</code> field.</p> <p>This can be because of the following:</p> <ul> <li>You already have some documents in the collection, and there is a document in the collection and CSV file that share the same <code>_id</code></li> <li>There are just at least two rows in the CSV file that share the same <code>_id</code></li> </ul> <p>If the value of <code>_id</code> field is not critical for you, you can just remove that attribute from your objects read from CSV right in your JavaScript code using <code>delete</code>.</p> <p>Otherwise, you have a conflict, and need to decide what you want to do with duplicate <code>_id</code> documents. If you are ok with overwriting, you can achieve that by having <code>{upsert: 1}</code> option, which will update the document with new values in case if there is one existing with the same <code>_id</code>.</p>101528137764	0	 <p>You're passing <code>self</code> twice in the super call. The call to <code>post</code> is a standard method call, so self is always included automatically. It should be:</p> <pre><code> super(ClassA, self).post(request, *args, **kwargs) </code></pre>10162319872	0	 <p>Many folks, including Zend, tell programmers to use camel case, but personally I used underscores as word separators for variable names, array keys, class names and function names. Also, all lowercase, except for class names, where I <em>will</em> use capitals.</p> <p>For example:</p> <pre><code>class News { private $title; private $summary; private $content; function get_title() { return $this-&gt;title; } } $news = new News; </code></pre>101715356416	0	After I install Wampserver2, while opening phpmyadmin i got error Firefox can't establish a connection to the server at localhost <p>After I install Wampserver2,</p> <ol> <li>while opening phpmyadmin i got error "Unable to connect <strong>Firefox can't establish a connection to the server at localhost.</strong> The site could be temporarily unavailable or too busy. Try again in a few moments. If you are unable to load any pages, check your computer's network connection. If your computer or network is protected by a firewall or proxy, make sure that Firefox is permitted to access the Web.</li> <li><p>Apache > Service > Test port 80 : <strong>Your port 80 is not actually used.</strong> also tried Apache > Service > install service : But Apache > Service > Start/resume service is still disabled.</p> <p>C:\WINDOWS\system32\drivers\etc\host file has the statement 127.0.0.1 localhost</p></li> </ol>101829165859	0	 <blockquote> <p>getDefaultSharedPreferences(Context) in the type PreferenceManager is not applicable for the arguments (DBTools)</p> </blockquote> <p>Because <code>getDefaultSharedPreferences</code> takes Context object as parameters instead of <code>DBTools.this</code> or any other class context.</p> <p>To fix this issue create a private Context object as assign value in object inside <code>DBTools</code> class constructor in which you are passing context when creating object of <code>DBTools</code> class:</p> <pre><code> private Context mContext; public DBTools(Context applicationContext){ super(applicationContext, "contactbook.db", null, 1); this.mContext=applicationContext; } </code></pre> <p>Now, use <code>mContext</code> as parameter to <code>getDefaultSharedPreferences</code> method:</p> <pre><code>SharedPreferences sp = PreferenceManager .getDefaultSharedPreferences(mContext); </code></pre>101914504560	0	 <p>What you are understanding is correct. Here is an example:</p> <pre><code>string* str_rptr = new string("hello"); string* str2_rptr = str_rptr; str2_rptr-&gt;replace(0,5,"goodbye"); std::cout &lt;&lt; *str_rptr &lt;&lt; std::endl; </code></pre> <p>The output of this fragment would print "goodbye" rather than "hello". After the "perfect int" example you gave, this code:</p> <pre><code>y = 400; std::cout &lt;&lt; x &lt;&lt; std::endl; </code></pre> <p>will print out "200". The important point is that copying a variable does not prevent changes to one from changing the other.</p>102033725788	0	C# Ask user another input <p>I am creating a soundDex application and I need to ask the user for a second name after they have inputted the first one. I also want "error no input" if the user does not input a second name. How would I do this within my soundDex? </p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SoundDexFinal { class Program { static void Main(string[] args) { string input = null; bool good = false; Console.WriteLine("SoundDex is a phonetic algorithm which allows a user to encode words which sound the same into digits." + "The program allows the user essentially to enter two names and get an encoded value."); while (!good) // while the boolean is true { Console.WriteLine("Please enter a name -&gt; "); // asks user for an input input = Console.ReadLine(); // Make sure the user entered something good = !string.IsNullOrEmpty(input); // if user enters a string which is null or empty if (!good) // if boolean is true Console.WriteLine("Error! No input."); // displays an error to the user } soundex soundex = new soundex(); // sets new instance variable and assigns from the method Console.WriteLine(soundex.GetSoundex(input)); // gets the method prior to whatever the user enters Console.ReadLine(); // reads the users input } class soundex { public string GetSoundex(string value) { value = value.ToUpper(); // capitalises the string StringBuilder soundex = new StringBuilder(); // Stringbuilder holds the soundex code or digits foreach (char ch in value) // gets the individual chars via a foreach which loops through the chars { if (char.IsLetter(ch)) AddChar(soundex, ch); // When a letter is found this will then add a char } // soundex in (parameter) is for adding the soundex code or digits return soundex.ToString(); //return the value which is then converted into a .String() } private void AddChar(StringBuilder soundex, char character) //encodes letter as soundex char and this then gets appended to the code { string code = GetSoundexValue(character); if (soundex.Length == 0 || code != soundex[soundex.Length - 1].ToString()) soundex.Append(code); } private string GetSoundexValue(char ch) { string chString = ch.ToString(); if ("BFPV".Contains(chString)) // converts this string into a value returned as '1' return "1"; else if ("CGJKQSXZ".Contains(chString)) // converts this string into a value returned as '2' return "2"; else if ("DT".Contains(chString)) // converts this string into a value returned as '3' return "3"; else if ("L".Contains(chString)) // converts this string into a value returned as '4' return "4"; else if ("MN".Contains(chString)) // converts this string into a value returned as '5' return "5"; else if ("R".Contains(chString)) // converts this string into a value returned as '6' return "6"; else return ""; // if it can't do any of these conversions then return nothing } } } } </code></pre>10211724872	0	 <p>The problem was related to the version of the NVelocity assembly I was using.</p>102216746227	0	Generate a random number from another number <p>In JavaScript, is it possible to generate a random number from another number?</p> <p>I'm trying to implement a predictable random number generator for one of my fractal terrain generators. I already know that it's possible to generate a random number using Math.random(), but I want to create a random number generator that produces exactly one output for every input. (For example, <code>predictableRandomGenerator(1)</code> would always produce the same result, which would not necessarily be the same as the input.)</p> <p>So is it possible to generate a random number from another number, where the output is always the same for each input?</p>102332773409	0	 <p>Here's a quick function:</p> <pre><code>myfun &lt;- function(df){ z &lt;- colSums(df) matrix(rowSums(expand.grid(z, z)), ncol = ncol(df)) } </code></pre> <p>It first takes the <code>colSums</code> as <code>z</code>. Then we use <code>expand.grid</code> to take all combinations of <code>z</code> to <code>z</code> and takes the <code>rowSums</code>. The output is coerced to a matrix with the correct number of columns.</p> <pre><code>myfun(df) [,1] [,2] [,3] [,4] [1,] 16 17 19 13 [2,] 17 18 20 14 [3,] 19 20 22 16 [4,] 13 14 16 10 </code></pre>10243791466	0	How do I know if the user clicks the "back" button? <p>I'm using anchors for dealing with unique urls for an ajaxy website. However, I want to reload the content when the user hits the Browser's "back" button so the contents always matches the url.</p> <p>How can I achieve this? Is there a jQuery event triggering when user clicks "Back"?</p>10255737426	0	 <p>RabbitMQ should fit your bill. The server is free and ready to use. You just need a client side to connect, push/send out message and get/pull notified message</p> <p>Server: <a href="http://www.rabbitmq.com/download.html" rel="nofollow">http://www.rabbitmq.com/download.html</a> Do a google for client or implement yourself</p> <p>Cheers</p>102613673443	0	 <p>OpenCV is bar-none the defacto computer vision library. It is packed full of functions to make your life easier.</p> <p>With respect to image stabilization, <a href="http://stackoverflow.com/questions/3431434/video-stabilization-with-opencv">Stackoverflow has answered possible approaches to this</a>. Most of the time, you want to extract robust local feature descriptors and use them to perform <a href="http://en.wikipedia.org/wiki/Image_registration" rel="nofollow">registration</a> on consecutive image frames.</p>102725982811	0	"No XLIFF language files were found." After updating to MAT 3.1 <p>I have a Windows Store project that I've been developing for quite some time. The Multilingual App Toolkit has been amazing so far. Recently I updated to version 3.1. Unfortunately, this caused the build process to not process my <code>.xlf</code> files that I've been using for a year now.</p> <p>Based on <a href="http://blog.giovannimodica.com/post/how-to-use-the-multilingual-app-toolkit-mat-in-a-portable-class-library-pcl-project" rel="nofollow">this entry</a> I took a look at my project file. The resources were defined similarly to how the blog entry suggested they <em>should</em> be. Similar to this:</p> <pre><code>&lt;ItemGroup&gt; &lt;XliffResource Include="MultilingualResources\MyProject.WinRT_ar.xlf" /&gt; &lt;XliffResource Include="MultilingualResources\MyProject.WinRT_bg-BG.xlf" /&gt; &lt;XliffResource Include="MultilingualResources\MyProject.WinRT_ca-ES.xlf" /&gt; ... </code></pre> <p>I tried many things, including adding <code>&lt;Generator&gt;</code> tags. None of it seemed to be working. How can I get the project to see my <code>.xlf</code>s?</p>10289763404	0	SaaS Platform - Different database user for each user or one master account <p>I have a SaaS platform that I am working on; written in PHP and using a MySQL database (using the PHP PDO class).</p> <p>The application is already functional and I have decided to use a separate database for each instance.</p> <p>One of the reasons for using multiple databases is to ensure that client data is separated (and hopefully secure). This also allows us to easily transfer their instance into the on-premise version.</p> <p>Security is always something that I worry about. I want to ensure this system is as secure as possible before it goes live.</p> <p>Currently we are using a single MySQL username &amp; password that has access to every database (on that specific MySQL Farm).</p> <p>Theoretically if there was a security breach then the attacker might be able to access a different database (username &amp; password is unset after the PDO/Database connection is made, but they might be able to run a query such as "use databaseB").</p> <p>Is this something that I should be concerned about? For example a SaaS platform that simply uses database partitioning is already less secure as a simple SQL error could expose client data.</p> <p>I've already started looking into using different database usernames &amp; passwords, but it does add to the complexity of the SaaS platform, and keeping things simple is always a good idea.</p> <p>Thanks!</p> <hr> <p>I have decided to go with different usernames and password for each instance.</p> <p>This is another layer of security and that cannot hurt.</p>10297180829	0	Generate Multiples XML with PHP <p>I have a PHP script that is generating an XML file. He reads the contents of the subfolders in the folder X, and generates only one XML with all subfolders and their contents. I'm wanting the same script generates an XML for each subfolder to find it, would someone help me?</p> <pre><code>&lt;?php $sortorder = $_REQUEST['sortorder']; $indir = '../galleries'; $files = opendir($indir); $outxml = &lt;'xml version=\'1.0\' encoding=\'utf-8\'?&gt;\n\n'; $outxml .= '&lt;galleries&gt;\n\n'; while ($file = readdir($files)) { if(is_dir($indir.'/'.$file)){ if ($file != '.' &amp;&amp; $file != '..') { $tmp_outxml[] = $file; } } } if ($sortorder == 'date') { foreach ($tmp_outxml as $k =&gt; $v) { $modified = filemtime ($indir.'/'.$v); $moddate[$k] = $modified; } array_multisort ($moddate, $tmp_outxml); } else if ($sortorder == 'random') { shuffle ($tmp_outxml); } else { sort ($tmp_outxml); } foreach ($tmp_outxml as $v) { $outxml .= get_folder_xml($indir.'/'.$v,$v); } $outxml .= "&lt;/galleries&gt;"; closedir($files); $fp = fopen('../xml/gallery.xml', 'w'); fwrite($fp, $outxml); fclose($fp); function get_folder_xml($imageDir,$title) { $extensions = array('.jpg', '.jpeg', '.JPG','.JPEG','.gif','.GIF','.swf','.SWF'); $output = ''; if($folder = opendir($imageDir)) { $filenames=array(); while (false !== ($file = readdir($folder))) { $dot = strrchr($file, '.'); if(in_array($dot, $extensions)) { array_push($filenames, $file); } } $spaceTitle = str_replace('_',' ',$title); $newPath = str_replace('../','',$imageDir); $output .= '&lt;gallery&gt;\n'; $output .= '&lt;title&gt;$spaceTitle&lt;/title&gt;\n'; $output .= ' &lt;images&gt;\n'; foreach ($filenames as $source) { $imageName = str_replace('mainThumb_','',$source); $finalName = str_replace('_',' ',$imageName); $imageName = str_replace($extensions,'',$finalName); $output .= '\t &lt;image src=\'$newPath/$source\' thumb=\'$newPath/thumbs/$source\'&gt;$imageName&lt;/image&gt;\n'; } $output .= ' &lt;/images&gt;\n'; $output .= '&lt;/gallery&gt;\n\n'; return $output; closedir($folder); } } ?&gt; </code></pre> <p>i think i need to modify on this line, but i dont know how... </p> <pre><code>$fp = fopen('../xml/gallery.xml', 'w'); fwrite($fp, $outxml); fclose($fp); </code></pre> <p>ty for help!!</p>103028100899	0	how do i fit unique curves on each unique plot in a for loop <p>I have written this code (see below) for my data frame <code>kleaf.df</code> to combine multiple plots of variable <code>press_mV</code> with each individual plot for unique <code>ID</code></p> <p>I need some help fitting curves to my plots. when i run this code i get the same fitted curve (the curve fitted for the first plot) on ALL the plots where i want each unique fitted curve on each unique plot.</p> <p>thanks in advance for any help given</p> <pre><code>f &lt;- function(t,a,b) {a * exp(b * t)} par(mfrow = c(5, 8), mar = c(1,1,1,1), srt = 0, oma = c(1,6,5,1)) for (i in unique(kleaf.df$ID)) { d &lt;- subset(kleaf.df, kleaf.df$ID == i) plot(c(1:length(d$press_mV)),d$press_mV) #----tp:turning point. the last maximum value before the values start to decrease tp &lt;- tail(which( d$press_mV == max(d$press_mV) ),1) #----set the end points(A,B) to fit the curve to A &lt;- tp+5 B &lt;- A+20 #----t = time, p = press_mV # n.b:shift by 5 accomadate for the time before attachment t &lt;- A:B+5 p &lt;- d$press_mV[A:B] fit &lt;- nls(p ~ f(t,a,b), start = c(a=d$press_mV[A], b=-0.01)) #----draw a curve on plot using the above coefficents curve(f(x, a=co[1], b=co[2]), add = TRUE, col="green", lwd=2) } </code></pre>10317542409	0	C# Linq Expressions - Use String functions for all EF4 class attributes <p> I have this EF class called COMPONENT</p> <pre class="lang-cs prettyprint-override"><code>public partial class COMPONENT : INotifyPropertyChanging, INotifyPropertyChanged { private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty); private int _ID; private string _NAME; private string _BRAND; private string _IMAGE; private System.Nullable&lt;double&gt; _PRICE; private string _OBSERVATION; private int _COMPONENT_TYPE_ID; private string _USERNAME; private System.DateTime _CREATE_DATE; </code></pre> <p>I want to treat all it's attributes like strings in the predicates of a generic query function using LinqKit PredicateBuilder.<br> The function is something like this:</p> <pre class="lang-cs prettyprint-override"><code> public static List&lt;TEntity&gt; getResults&lt;TEntity&gt;(IList&lt;PredicateFilter&gt; conditions) where TEntity: class { var predicate = PredicateBuilder.True&lt;TEntity&gt;(); foreach (var condition in conditions) { var lambda = createPredicateLambda&lt;TEntity&gt;(condition); predicate = predicate.And(lambda); } DataClassesDataContext db = new DataClassesDataContext(); var components = from com in db.GetTable&lt;TEntity&gt;().Where(predicate) select com; return components.AsExpandable().ToList(); } </code></pre> <p>The class PredicateFilter look like this:</p> <pre class="lang-cs prettyprint-override"><code> public class PredicateFilter { public string attribute; public string logicOperator; public object value; } </code></pre> <p>The problem became in the function createPredicateLambda(condition). This function returns a Expression>. In it's body calls another function called createLambdaExpression</p> <pre class="lang-cs prettyprint-override"><code> createLambdaExpression&lt;TEntity&gt;(string methodOperator, ParameterExpression param, MemberExpression attribute, ConstantExpression value) where TEntity : class </code></pre> <p>This function, in certain conditions, try to generate a expression where the attribute contains the value (no matter the Type of both the parameter) I want to do something like this but i don't see the solution:</p> <pre class="lang-cs prettyprint-override"><code> return Expression.Lambda&lt;Func&lt;TEntity, bool&gt;&gt;(Expression.Contains(Expression.Convert(attribute,typeof(string)),value),param); </code></pre> <p>Obviously this wont's compile (The Expression.Convert it's not implemented). However, if i use </p> <pre class="lang-cs prettyprint-override"><code> Expression.Lambda&lt;Func&lt;TEntity, bool&gt;&gt;(Expression.Equal(Expression.Convert(attribute,typeof(string)),value),param); </code></pre> <p>i get an exception in runtime: "The binary operator Equal is not defined for the types 'System.Int32' and 'System.String'".</p> <p>Like i said later, i want to compare different data types or use (in certain conditions) the method String.Contains in all the data types. I've tried without any luck... Anyone knows if this can be done?</p> <p>Thanks in advance!</p>10321389139	0	 <p><a href="http://msdn.microsoft.com/en-us/library/ht8ecch6(VS.71).aspx" rel="nofollow noreferrer">Compiling MSIL to Native Code</a> <a href="http://msdn.microsoft.com/en-us/library/6t9t5wcf.aspx" rel="nofollow noreferrer">Ngen.exe</a></p> <blockquote> <p>SUMMARY: </p> <p>The runtime supplies another mode of compilation called install-time code generation. The install-time code generation mode converts MSIL to native code just as the regular JIT compiler does, but it converts larger units of code at a time, storing the resulting native code for use when the assembly is subsequently loaded and run. When using install-time code generation, the entire assembly that is being installed is converted into native code, taking into account what is known about other assemblies that are already installed.</p> </blockquote> <p>Take look at - <a href="http://stackoverflow.com/questions/45702/is-there-some-way-to-compile-a-net-application-to-native-code">How to compile a .NET application to native code?</a></p>10333021636	0	how can i execute large mysql queries fast <p>I have 4 mysql tables and have a single query with JOIN on multiple tables and I am requesting it via jquery ajax, but it takes much too long, from about 1-3 minutes while I want to execute them on average 2-5 seconds.</p> <p>Is there any special way to execute the queries fast?</p>103435044770	0	 <p>I ended up using some jquery in my change events.</p> <pre><code>'change .edit-status': function(event, template){ var status = event.target.value; if (status === "UnAssigned") { $(".edit-assigned-to").val(""); } return false; }, 'change .edit-assigned-to': function(event, template){ var assignedTo = event.target.value; if (!template.data.assignedTo &amp;&amp; assignedTo !== "") { $(".edit-status").val("Not Started"); } if (assignedTo === "") { $(".edit-status").val("UnAssigned"); } return false; } </code></pre> <p>I'm not sure if there are better approaches or pitfalls to this solution, but it seems to be meeting my needs.</p>103510788749	0	 <p>The <code>NSMutableSet</code> class declares the programmatic interface to an object that manages a mutable set of objects. <code>NSMutableSet</code> provides support for the mathematical concept of a set. </p> <p><code>NSMutableSet</code> is “toll-free bridged” with its Core Foundation counterpart, <code>CFMutableSetRef</code>.</p> <h3>Resources:</h3> <ul> <li><a href="http://www.gnustep.org/resources/OpenStepSpec/FoundationKit/Classes/NSMutableSet.html" rel="nofollow">gnustep</a> </li> <li><a href="https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/nsmutableset_Class/Reference/NSMutableSet.html" rel="nofollow">NSMutableSet Class Reference</a></li> </ul>103624928132	0	 <p>Actually, I still don't know, <em>why</em> code works as described above. But I have found acceptable method to solve task other way.</p> <p>Looks like "put a needle into egg, egg into duck, duck into rabbit": ScrollView must contain a ListView component which has a corresponding ListModel and a custom component should act as delegate. Only with ListModel I've got correct automatic scrolling and relative emplacement support.</p> <pre><code>ScrollView { id: id_scrollView anchors.fill: parent objectName: "ScrollView" frameVisible: true highlightOnFocus: true style: ScrollViewStyle { transientScrollBars: true handle: Item { implicitWidth: 14 implicitHeight: 26 Rectangle { color: "#424246" anchors.fill: parent anchors.topMargin: 6 anchors.leftMargin: 4 anchors.rightMargin: 4 anchors.bottomMargin: 6 } } scrollBarBackground: Item { implicitWidth: 14 implicitHeight: 26 } } ListView { id: id_listView objectName: "ListView" anchors.top: parent.top anchors.left: parent.left anchors.right: parent.right anchors.rightMargin: 11 flickableDirection: Flickable.VerticalFlick boundsBehavior: Flickable.StopAtBounds delegate: view_component model: id_listModel ListModel { id :id_listModel objectName: "ListModel" } //delegate: View_item2.Item Component { id: view_component View_item2 { objectName: name } } } </code></pre>103730023758	0	Trailing space while using "headertemplate" in asp gridview <p>I have a gridview which is bounded as </p> <pre><code>&lt;asp:GridView runat="server" ID="gvShipDetails" AutoGenerateColumns="false" OnRowDataBound="gvShipDetails_RowDataBound"&gt; &lt;Columns&gt; &lt;asp:TemplateField&gt; &lt;HeaderTemplate&gt; Ship name &lt;br /&gt; &lt;asp:TextBox class="search_textbox" runat="server" BorderStyle="None" Width="100%"&gt; &lt;/asp:TextBox&gt; &lt;/HeaderTemplate&gt; &lt;ItemTemplate&gt; &lt;%#Eval("VesselName")%&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;/Columns&gt; &lt;/asp:GridView&gt; </code></pre> <p>The problem is the finally rendered html table td is rendered as</p> <pre><code>&lt;td&gt; sample vessel name &lt;/td&gt; </code></pre> <p>A lot of spaces inside td.How is this possible.<br> If I replace this bound code as</p> <pre><code>&lt;asp:BoundField HeaderText="vessel name" DataField="vesselname" /&gt; </code></pre> <p>Then html is renderd as <code>&lt;td&gt;sample vessel name&lt;td&gt;</code></p> <p>Why is it so? I wanted to use headertemplate and i wanted to avoid these trailing spaces. How to do it</p> <p>Any help will be appreciated</p>103813211993	0	Estimating the variance of eigenvalues of sample covariance matrices in Matlab <p>I am trying to investigate the statistical variance of the eigenvalues of sample covariance matrices using Matlab. To clarify, each <strong>sample</strong> covariance matrix is constructed from a <strong>finite</strong> number of vector snapshots (afflicted with random white Gaussian noise). Then, over a <strong>large</strong> number of trials, a large number of such matrices are generated and eigendecomposed in order to estimate the <strong>theoretical</strong> statistics of the eigenvalues.</p> <p>According to several sources (see, for example, [1, Eq.3] and [2, Eq.11]), the variance of each <strong>sample</strong> eigenvalue should be equal to that <strong>theoretical</strong> eigenvalue squared, divided by the number of vector snapshots used for each covariance matrix. However, the results I get from Matlab aren't even close.</p> <p>Is this an issue with my code? With Matlab? (I've never had such trouble working on similar problems).</p> <p>Here's a very simple example:</p> <pre><code>% Data vector length Lvec = 5; % Number of snapshots per sample covariance matrix N = 200; % Number of simulation trials Ntrials = 10000; % Noise variance sigma2 = 10; % Theoretical covariance matrix Rnn_th = sigma2*eye(Lvec); % Theoretical eigenvalues (should all be sigma2) lambda_th = sort(eig(Rnn_th),'descend'); lambda = zeros(Lvec,Ntrials); for trial = 1:Ntrials % Generate new (complex) white Gaussian noise data n = sqrt(sigma2/2)*(randn(Lvec,N) + 1j*randn(Lvec,N)); % Sample covariance matrix Rnn = n*n'/N; % Save sample eigenvalues lambda(:,trial) = sort(eig(Rnn),'descend'); end % Estimated eigenvalue covariance matrix b = lambda - lambda_th(:,ones(1,Ntrials)); Rbb = b*b'/Ntrials % Predicted (approximate) theoretical result Rbb_th_approx = diag(lambda_th.^2/N) </code></pre> <p>References:</p> <p>[1] Friedlander, B.; Weiss, A.J.; , "<a href="http://www.scribd.com/doc/112067632" rel="nofollow">On the second-order statistics of the eigenvectors of sample covariance matrices</a>," Signal Processing, IEEE Transactions on , vol.46, no.11, pp.3136-3139, Nov 1998 [2] Kaveh, M.; Barabell, A.; , "<a href="http://www.scribd.com/doc/112046406/Kaveh-86" rel="nofollow">The statistical performance of the MUSIC and the minimum-norm algorithms in resolving plane waves in noise</a>," Acoustics, Speech and Signal Processing, IEEE Transactions on , vol.34, no.2, pp. 331- 341, Apr 1986</p>10393879203	0	Tab focus granting event <p>I need to capture tab focus granting event in Firefox browser. Is there any type of listener implement for this event?</p>104024045360	0	 <p>Think about what the compiler would have to do to catch the problem you're demonstrating. It would have to look at all callers of test1 to see whether they're passing it a local. Perhaps easy enough, but what if you insert more and more intermediate functions?</p> <pre><code>int &amp; test1(int &amp; x) { return x; } int &amp; test2(int &amp; x) { return test1(x); } int &amp; test3() { int x = 0; return test2(x); } int main(void){ int &amp; r = test3(); return r; } </code></pre> <p>The compiler would have to look not only at all callers of test1, but then also all callers of test2. It would also have to work through test2 (imagine that it's more complex than the example here) to see whether it's passing any of its own locals to test1. Extrapolate that to a truly complex piece of code--keeping track of that sort of thing would be prohibitively complex. The compiler can only do so much to protect us from ourselves.</p>104129159691	0	 <p>There are 2 delegate methods of FBLoginView</p> <pre><code>-(void)loginViewShowingLoggedOutUser:(FBLoginView *)loginView -(void)loginViewShowingLoggedInUser:(FBLoginView *)loginView </code></pre> <p>The first method would inform you whether the user is logged out and the second method would inform you whether the user is logged in and you can perform your action on the basis of that.</p> <p>For getting the image of the Profile picture u can use users id or objectID from this delegate method which contains all the user information.</p> <pre><code>-(void)loginViewFetchedUserInfo:(FBLoginView *)loginView user:(id&lt;FBGraphUser&gt;)user { NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"https://graph.facebook.com/%@/picture?type=normal",user.id]]; NSData *data = [NSData dataWithContentsOfURL:url]; UIImage *profileImage = [UIImage imageWithData:data]; } </code></pre> <p>where the profileImage would contain the user profile Image and you can use that image to show on your custom button.</p>104229595534	0	 <p>First of all, your question is too-broad, and you haven't provided much info, but if you make vague questions, you'll get vague answers, so here we go.</p> <p>I also developed an app with Laravel 5, and had a pagination with next / previous links. I used AJAX to make a call to the next page, and return the HTML into the current page.</p> <pre><code>$(document).on("click", ".pagination a", function(e) { e.preventDefault(); url = $(this).attr('href') + " #search_results-listing"; $("#search_results").load(url, function() { setGetParameter('page', '2'); }); }); </code></pre>104322882485	0	Plot two conditions in one plot <p>i'm sorry to ask such a dumb question, but i can't find an answer ... </p> <p>So i have this table called : "linearsep" : </p> <pre><code> color x y 1 red 1 1 2 red 1 3 3 red 3 3 4 red 2 4 5 blue 4 1 6 blue 6 3 7 blue 2 -2 8 blue 6 -1 </code></pre> <p>each line corresponds to a points (1,1 ; 1,3 etc...) , I just want to plot the ''red'' points in red , and the "blue" points in blue.</p> <p>I know this is pretty dumb : but i just can't find a way to get a vector with the first four line. </p> <p>I thought it was something like that: </p> <blockquote> <p>plot(linearsep$color~x, linearsep$color~y)</p> </blockquote> <p>but obviously it doesn't work ... I've tested some stuff with ggplot:</p> <pre><code>ggplot(data=a, + aes(x=x, y=y, colour=color)) + geom_point() </code></pre> <p>Which works, but seems like a 'hack' , how can i just get the vector i want ? Someone could please help me ... Again sorry for such a dumb question </p>104418644597	0	 <p>I'm an FPDF noob myself but have you tried the AcceptPageBreak function?</p> <p>Something like this (copied from fpdf website):</p> <pre><code>function AcceptPageBreak() { // Method accepting or not automatic page break if($this-&gt;col&lt;2) { // Go to next column $this-&gt;SetCol($this-&gt;col+1); // Set ordinate to top $this-&gt;SetY($this-&gt;y0); // Keep on page return false; } else { // Go back to first column $this-&gt;SetCol(0); // Page break return true; } } </code></pre> <p>As a reference, the <a href="http://www.fpdf.org/en/tutorial/index.php" rel="nofollow">fpdf tutorials</a> are really helpful. I suspect <a href="http://www.fpdf.org/en/tutorial/tuto4.htm" rel="nofollow">this one in particular</a> would help you for what you're doing.</p>104534195319	0	"Warning:mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in?"And after searching I rectified my code as below <p>DisplayLandlord PHP: I couldn't get the output.The query is not fetching the result</p> <pre><code> &lt;?php include("dbconfig.php"); ?&gt; &lt;?php $query = "SELECT * FROM rmuruge4_landlord"; $result = mysqli_query(mysqli_connect(),$query); if ($result === false) {die(mysqli_error(mysqli_connect())); } echo "&lt;div class='bs-example'&gt;"; echo "&lt;table class='table table-striped'&gt;"; echo "&lt;tr&gt;&lt;th&gt;LLID&lt;/th&gt;&lt;th&gt;LName&lt;/th&gt;&lt;th&gt;Phone&lt;/th&gt;&lt;th&gt;Address&lt;/th&gt;&lt;/td&gt;"; while($row = mysqli_fetch_array($result)){ echo "&lt;tr&gt;&lt;td&gt;" . $row['LLID'] . "&lt;/td&gt;&lt;td &gt;" . $row['LName'] . "&lt;/td&gt;&lt;td &gt;". $row['Phone'] . "&lt;/td&gt;&lt;td &gt;" . $row['Address'] . "&lt;/td&gt;&lt;/tr&gt;"; } echo "&lt;/table&gt;"; echo "&lt;/div&gt;"; mysqli_close(mysqli_connect()); ?&gt; dbconfig.php: Connection is successful </code></pre>104625811244	0	 <p>These redirects follow your route configuration. The default route is {siteUrl}/{controller}/{action}, which is why when you give it the "Index" action and the "Home" controller, you get the URL you're seeing.</p> <p>You need to specify a new route similar to this:</p> <pre><code>MapRoute("CustomRoute", "MyApp/{controller}/{action}"; </code></pre> <p>You can then redirect to it like this:</p> <pre><code>RedirectToRoute("CustomRoute", new {Controller = "Home", Action = "Index" }); </code></pre> <p><strong>EDIT to clarify for the comments -</strong></p> <p>It is also possible to solve this using IIS to make MyApp an application. This is the right solution <em>only if</em> MyApp is the only value you ever want at the beginning of your route for this site. If, for example, you sometimes need MyApp/{controller}/{action} and other times you need OtherSubfolder/{controller}/{action}, you need to use the routes as I have outlined above (or use areas) instead of just updating IIS. </p> <p>I am assuming you want the solution using MVC, so that is what is here, but you should also consider the IIS application if that's the right solution for you.</p>10477946771	0	UIDocumentInteractionController or QLPreviewController can't zoom PDF on iOS5? <p>I use QLPreviewController to view PDF files in one of my apps. However, ever since iOS5, users can no longer pinch to zoom in/out of the PDF. This is terrible for iPhone users, as they can't read anything.</p> <p>I have also tried using UIDocumentInteractionController but have had the same problem.</p> <p>Anyone know what's going on with this?</p>104829846864	0	Change the app-name sent by docker's syslog driver <p>I'm using <a href="https://papertrailapp.com/">Papertrail</a> to collect my Docker container's logs. Do to that, I used the syslog driver when I created the container:</p> <pre><code>sudo docker run --name my_container --log-driver=syslog ... </code></pre> <p>... and added the following line to my <code>/etc/rsyslog.conf</code></p> <pre><code>*.* @logsXXX.papertrailapp.com:YYYY </code></pre> <p>At the end, I get on Papertrail logs like this:</p> <pre><code>Apr 24 13:41:55 ip-10-1-1-86 docker/3b00635360e6: 10.0.0.5 - - [24/Apr/2015:11:41:57 +0000] "GET /healthcheck HTTP/1.1" 200 0 "-" "" "-" </code></pre> <p>The problem is that the app-name (see <a href="https://tools.ietf.org/html/rfc5424">syslog RFC</a>) is <strong>docker/container_id</strong></p> <p>I would rather have the container name (or host). But I don't know how to do. I tried to set a specific hostname to my container like below, but it didn't work better:</p> <pre><code>sudo docker run --name my_container -h my_container --log-driver=syslog ... </code></pre>104929411338	0	How to handle OVER_QUERY_LIMIT <p>I am using google maps to draw the path among various location which are stored in database.</p> <p><a href="http://jsfiddle.net/en608jxa/" rel="nofollow noreferrer">fiddle</a></p> <p>While passing 15 geopoints(anything more than 10) am getting status as OVER_QUERY_LIMIT.</p> <p>I understand that we need to give some milliseconds of time gap when we pass more than 10 geopoints per seconds.</p> <p>My question is <strong>HOW TO DO THAT..Where to add sleep() or setTimeout() or any other time delay code</strong></p> <p>I've tried all,maximum all possibilities provided at SO but failed.As because they are just saying give some time gap between request but how to do that?</p> <p>Code Snippet:</p> <pre><code> var markers = [ { "title": 'abc', "lat": '17.5061925', "lng": '78.5049901', "description": '1' }, { "title": 'abc', "lat": '17.50165', "lng": '78.5139204', "description": '2' }, . . . . . { "title": 'abc', "lat": '17.4166067', "lng": '78.4853992', "description": '15' } ]; var map; var mapOptions = { center: new google.maps.LatLng(markers[0].lat, markers[0].lng), zoom: 15 , mapTypeId: google.maps.MapTypeId.ROADMAP }; var path = new google.maps.MVCArray(); var service = new google.maps.DirectionsService(); var infoWindow = new google.maps.InfoWindow(); var map = new google.maps.Map(document.getElementById("map"), mapOptions); var poly = new google.maps.Polyline({ map: map, strokeColor: '#000000' }); var lat_lng = new Array(); for (var i = 0; i &lt;= markers.length-1; i++) { var src = new google.maps.LatLng(markers[i].lat, markers[i].lng); var des = new google.maps.LatLng(markers[i+1].lat, markers[i+1].lng); poly.setPath(path); service.route({ origin: src, destination: des, travelMode: google.maps.DirectionsTravelMode.DRIVING }, function (result, status) { if (status == google.maps.DirectionsStatus.OK) { for (var i = 0, len = result.routes[0].overview_path.length; i &lt; len; i++) { path.push(result.routes[0].overview_path[i]); } } else{ if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) { document.getElementById('status').innerHTML +="request failed:"+status+"&lt;br&gt;"; } } }); } }); </code></pre> <p>RESULT MAP(OVER_QUERY_LIMIT):</p> <p><img src="https://i.stack.imgur.com/dCwVQ.png" alt="OVER_QUERY_LIMIT"></p>105028928062	0	Hovercard not displaying in knockoutJS with-binding <p>I got this hover card and I want to display it inside a sub-menu. It works int the header, but somehow the hover effect does not kick in when inside the sub-menu "with:$root.chosenMenu"-bindings.</p> <p>This is my code:</p> <p>HTML:</p> <pre><code>&lt;div&gt; &lt;span class="previewCard"&gt; &lt;label class="hovercardName" data-bind="text: displayName"&gt;&lt;/label&gt; &lt;span class="hovercardDetails"&gt; &lt;span data-bind="text: miniBio"&gt;&lt;/span&gt;.&lt;br/&gt; &lt;a data-bind="attr: { href: webpage, title: webpage }, text: webpage"&gt;My blog&lt;/a&gt; &lt;/span&gt; &lt;/span&gt; &lt;br/&gt;&lt;br/&gt; &lt;div class="wysClear wysLeft buttonRow"&gt; &lt;a href="#pid1" data-bind="click: function(){$root.chosenMenu('a');return false;}"&gt;Panel A&lt;/a&gt; &lt;a href="#pid2" data-bind="click: function(){$root.chosenMenu('b');return false;}"&gt;Panel B&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;hr/&gt; &lt;div data-bind="with: $root.chosenMenu"&gt; &lt;div id="pid1" data-bind="visible: $root.chosenMenu() === 'a'"&gt; panel A: &lt;br/&gt;&lt;br/&gt; &lt;span class="previewCard"&gt; &lt;label class="hovercardName" data-bind="text: $root.displayName"&gt;&lt;/label&gt; &lt;span class="hovercardDetails"&gt; &lt;span data-bind="text: $root.miniBio"&gt;&lt;/span&gt;.&lt;br/&gt; &lt;a data-bind="attr: { href: $root.webpage, title: $root.webpage }, text: $root.webpage"&gt;My blog&lt;/a&gt; &lt;/span&gt; &lt;/span&gt; &lt;/div&gt; &lt;div id="pid2" data-bind="visible: $root.chosenMenu() === 'b'"&gt; panel B: &lt;br/&gt;&lt;br/&gt; &lt;span class="previewCard"&gt; &lt;label class="hovercardName" data-bind="text: $root.displayName"&gt;&lt;/label&gt; &lt;span class="hovercardDetails"&gt; &lt;span data-bind="text: $root.miniBio"&gt;&lt;/span&gt;.&lt;br/&gt; &lt;a data-bind="attr: { href: $root.webpage, title: $root.webpage }, text: $root.webpage"&gt;My blog&lt;/a&gt; &lt;/span&gt; &lt;/span&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Javascript:</p> <pre><code>viewModel = function(){ var self = this; self.chosenMenu = ko.observable(); self.displayName = ko.observable("Asle G"); self.miniBio = ko.observable("Everywhere we go - there you are!"); self.webpage = ko.observable("http://blog.a-changing.com") }; ko.applyBindings( new viewModel() ); // hovercard $(".previewCard").hover(function() { $(this).find(".hovercardDetails").stop(true, true).fadeIn(); }, function() { $(this).find(".hovercardDetails").stop(true, true).fadeOut(); }); </code></pre> <p>CSS:</p> <pre><code>.previewCard { position:relative; } .hovercardName { font-weight:bold; position:relative; z-index:100; /*greater than details, to still appear in card*/ } .hovercardDetails { background:#fff ; border:solid 1px #ddd; position:absolute ; width:300px; left:-10px; top:-10px; z-index:50; /*less than name*/ padding:2em 10px 10px; /*leave enough padding on top for the name*/ display:none; } </code></pre> <p>Fiddle: <a href="http://jsfiddle.net/AsleG/jb6b61oh/" rel="nofollow">http://jsfiddle.net/AsleG/jb6b61oh/</a></p>105124731408	0	 <p>Filed an issue at jboss jira and the issue is fixed in upcoming release.</p> <p>A work-around currently is to have the following in your jboss-web.xml:</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;jboss-web&gt; &lt;session-config&gt; &lt;cookie-config&gt; &lt;path&gt;/&lt;/path&gt; &lt;/cookie-config&gt; &lt;/session-config&gt; &lt;/jboss-web&gt; &lt;xml&gt; </code></pre>105234895249	0	 <p>If you <em>must</em> use a loop, you can do something like</p> <pre><code>uint64_t text = 0; for (int i = 15; i &gt;= 0; --i) { text &lt;&lt;= 4; text |= a[i] &amp; 0x0f; // Masking in case a[i] have more than the lowest four bits set } </code></pre>105327795202	0	 <p>It's not flushed at this moment, changes kept in memory for a while. If you need to force Grails to update DB exactly at this moment, add <code>flush: true</code> parameter:</p> <pre><code>person.save(flush: true) </code></pre>105432102014	0	 <p>Yeah, You can use SHOW CREATE TABLE to display the CREATE VIEW statement that created a view.</p> <p>Link for reference: <a href="https://cwiki.apache.org/confluence/display/Hive/LanguageManual+DDL#LanguageManualDDL-CreateView" rel="nofollow">Hive CREATE VIEW</a> </p>105516393853	0	 <p>You don't initialize <code>array</code> and <code>s</code> in the copy constructor.</p>10566995738	0	ASP javascript radiobutton enable disable not included in postback ajax <p>Here is the problem. I have a radiobutton group (two radiobuttons).</p> <p>These guys are initialy disabled. When the user clicks a checkbox, I dynamically enable radiobuttons in javascript by setting <code>rbtn.disabled = false;</code> and doing the same for it's parent (span element) so it correctly works in IE. The problem is that these dynamically enabled radiobuttons are not returned on postback (I see <code>rbtn.Checked == false</code> on serverside and <code>request.form</code> does not contain proper value).</p> <p>Why is this happening? Is there another fix except for a workaround with hidden fields?</p> <p>Expected answer decribes post-back policy, why/how decides which fields are included in postback and fix to this problem.</p>105721883693	0	 <p>Try This:</p> <pre><code> int maxNo = 4; //you can change this no and logic works till 9 comboboxes void clearPreceding(ComboBox cmbBox) { int cmbBoxNo = Convert.ToInt32(cmbBox.Name.Substring(cmbBox.Name.Length - 1)); for (int i = cmbBoxNo; i &lt;= maxNo; i++) { ((ComboBox)this.Controls.Find("comboBox" + i, true)[0]).Text = ""; } } </code></pre> <p>You can Subscribe to One EventHandler for all Combobox's <code>SelectedIndexChanges</code> Event as below:</p> <pre><code> comboBox1.SelectedIndexChanged += AllCombobox_SelectedIndexChanged; comboBox2.SelectedIndexChanged += AllCombobox_SelectedIndexChanged; comboBox3.SelectedIndexChanged += AllCombobox_SelectedIndexChanged; comboBox4.SelectedIndexChanged += AllCombobox_SelectedIndexChanged; </code></pre> <p>and the EventHandler is:</p> <pre><code> private void AllCombobox_SelectedIndexChanged(object sender, EventArgs e) { clearPreceding((ComboBox)sender); } </code></pre> <p><strong>Complete Code:</strong></p> <pre><code>public partial class Form1 : Form { int maxNo = 4; public Form1() { InitializeComponent(); comboBox1.SelectedIndexChanged+=AllCombobox_SelectedIndexChanged; comboBox2.SelectedIndexChanged += AllCombobox_SelectedIndexChanged; comboBox3.SelectedIndexChanged += AllCombobox_SelectedIndexChanged; comboBox4.SelectedIndexChanged += AllCombobox_SelectedIndexChanged; } private void AllCombobox_SelectedIndexChanged(object sender, EventArgs e) { clearPreceding((ComboBox)sender); } void clearPreceding(ComboBox cmbBox) { int cmbBoxNo = Convert.ToInt32(cmbBox.Name.Substring(cmbBox.Name.Length - 1)); for (int i = cmbBoxNo; i &lt;= maxNo; i++) { ((ComboBox)this.Controls.Find("comboBox" + i, true)[0]).Text = ""; } } } </code></pre>105816844290	0	Excel Loading via c# <p>Try to Load an excel file using this code below gives me this error </p> <p>The Microsoft Access database engine could not find the object 'Sheet Name'. Make sure the object exists and that you spell its name and the path name correctly. If 'Sheet Name' is not a local object, check your network connection or contact the server administrator.</p> <p>i am sure the Sheet Name is correct.</p> <p>Any suggestions?</p> <pre><code>if (strFile.Trim().EndsWith(".xlsx")) { strConnectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\";", strFile); } else if (strFile.Trim().EndsWith(".xls")) { strConnectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\";", strFile); } OleDbConnection SQLConn = new OleDbConnection(strConnectionString); SQLConn.Open(); OleDbDataAdapter SQLAdapter = new OleDbDataAdapter(); string sql = "SELECT * FROM [" + sheetName + "]"; OleDbCommand selectCMD = new OleDbCommand(sql, SQLConn); SQLAdapter.SelectCommand = selectCMD; ///error in this line SQLAdapter.Fill(dtXLS); SQLConn.Close(); </code></pre>105938319846	0	 <p>You can use the code like this. I done for you..</p> <pre><code>editText.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View arg0, boolean hasFocus) { // TODO Auto-generated method stub if(hasFocus){ spinner.setVisibility(View.VISIBLE); } } }); spinner.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView&lt;?&gt; parent, View view,int position, long id) { editText.setText(spinner.getSelectedItem().toString()); //this is taking the first value of the spinner by default. } @Override public void onNothingSelected(AdapterView&lt;?&gt; parent) { // TODO Auto-generated method stub } }); </code></pre> <p>You can only use OnItemSelectedListener on spinner in android.<a href="https://developer.android.com/guide/topics/ui/controls/spinner.html" rel="nofollow">Red more from Android Developers</a>. Good luck..</p>106017545781	0	 <p>As others have said, IE8 does not support the <code>nth-child()</code> selector in CSS.</p> <p>You have the following options:</p> <ol> <li><p>Refactor your code to use an alternative method rather than <code>nth-child()</code>. Maybe just add a class to the relevant elements.</p></li> <li><p>Use a javascript polyfill such a <a href="https://code.google.com/p/ie7-js/" rel="nofollow">IE9.js</a> or <a href="http://selectivizr.com/" rel="nofollow">Selectivizr</a>, which back-ports the <code>nth-child()</code> selector (and others) to IE8.</p></li> <li><p>Use jQuery or a similar library that supports <code>nth-child()</code> to set the styles rather than doing it in CSS.</p></li> <li><p>Drop support for IE8.</p></li> </ol> <p>Which of those options you decide to use will depend on what matters to you.</p> <p>If you've got code that works in other browsers and you need it to work in IE8 with the least amount of additional work, then I would suggest trying out the Selectivizr library. Or IE9.js. But I'd suggest trying Selectivizr first, as IE9.js does a lot of other stuff to the browser that may or may not affect your site.</p> <p>If you don't want to have to use a Javascript library for this but you still need IE8 support, then you'll need to take option 1, and refactor your code. That may or may not be a lot of work, depending how your code is structured and how much code there is. Bit of a shame to have to make a backward step when the CSS is there.</p> <p>Option 4 sounds like the worst option, but might be more suitable than it sounds. If the <code>nth-child</code> styling is being used for something like zebra striping, it may not be the end of the world for IE8 users just to not get the stripes. If everything else in the site works okay, they may not even miss it. And if they do miss it, you can tell them to upgrade their browser.</p>106112927929	0	Sorting the report in birt <p>I have created a column binding in a report(datetime column) using birt. The datetime value that the column binding fetches based on the value of another string type column. Now when I'm sorting the report based on the column binding, the result that I'm getting is initially sorted on the basis of the string column and then on the basis of the column binding.</p> <p>I want the report to be sorted only on the basis of column binding (datetime) value.</p>106226497171	0	 <p>Check if your version of Vim has support for client-server functionality: <code>:echo has('clientserver')</code></p> <p>If so, you can write an alias to tell Vim to change its cwd:</p> <p>In your .bashrc:</p> <pre><code>alias fg="$VIM --remote-send ':cd $PWD&lt;CR&gt;'; fg" </code></pre> <p>Where $VIM is <code>vim</code> or <code>gvim</code> or <code>macvim</code>.</p> <p>You need the colon and the <code>&lt;CR&gt;</code> because you're sending Vim keystrokes rather than commands (<code>&lt;CR&gt;</code> is a special notation for "Enter")</p> <p>I'm not sure whether <code>--remote-send</code> works when Vim is suspended - this approach might be better if you use something like screen or tmux to run vim and your shell at the same time.</p> <p>Otherwise, it's a bit trickier.</p> <p>There's a :shell command that is similar to suspending and resuming, but I'm assuming it forks a child process instead of returning you to Vim's parent process. If you're ok with that, there's a ShellCmdPost autocmd you can attach to to load information. You can use that in association with an alias that writes the $CWD to a file to load the required directory and change to it.</p> <p>In your .bashrc:</p> <pre><code>alias fgv="echo $PWD &gt; ~/.cwd; exit" </code></pre> <p>In your .vimrc:</p> <pre><code>autocmd ShellCmdPost * call LoadCWD() function! LoadCWD() let lines = readfile('~/.cwd') if len(lines) &gt; 0 let cwd = lines[0] execute 'cd' cwd endif endfunction </code></pre> <p>Looking through the list of autocommands, I was not able to find any that detect when Vim has been suspended and has just been resumed. You could remap ctrl-z to first set a flag variable then do an unmapped ctrl-z. Then write a shell script like before that writes its $CWD to a specific file. Then you can set up an autocmd to watch that file for modification and in the handler, check the flag variable, and if it's set, reset it, read the file, and change to that directory. A bit complex, but it would work.</p> <p>That would look like this. You'll have to load the file when you start Vim so that it can monitor it for changes. You may want to <code>set hidden</code> so that you can keep the buffer open but hide it.</p> <p>In your .bashrc:</p> <pre><code>alias fg="echo $PWD &gt; ~/.cwd; fg" </code></pre> <p>In your .vimrc:</p> <pre><code>set hidden edit ~/.cwd enew nnoremap &lt;C-Z&gt; :let g:load_cwd = 1&lt;CR&gt;&lt;C-Z&gt; autocmd FileChangedShell ~/.cwd call LoadCWD() function! LoadCWD() if g:load_cwd let g:load_cwd = 0 let lines = readfile('~/.cwd') if len(lines) &gt; 0 let cwd = lines[0] execute 'cd' cwd endif endif endfunction </code></pre>106334993478	0	 <p>This is probably late, but editing the permission levels on the site might be easier than removing users access, and your SC admins will still have access.</p>10647231546	0	How to pass Arraylist of Objects to a Procedure using spring mybatis <p>I want to pass an Arraylist of Objects for e.g.</p> <pre><code>Arraylist &lt;SomeObject&gt; listOFSomeObject </code></pre> <p>Where <strong>SomeObject</strong> is having two attributes <strong>key</strong> and <strong>value</strong>.</p> <p>On DB side i have a table type of variable i.e.</p> <pre><code>create or replace type tableTypeVariable is table of SomeType; CREATE OR REPLACE TYPE SomeTypeAS OBJECT (key VARCHAR2(50),value VARCHAR2(50)) </code></pre> <p>Now i want to map my each object of type <strong>SomeObject</strong> from a <strong>listOFSomeObject</strong> to the <strong>tableTypeVariable</strong>.</p> <p>Can any body help me with that ?</p>106530910328	0	 <p>The vector handles its memory outside of the structure, in the heap as mentioned in another answer. So resizing or reallocating the vector inside the structure won't change the structure's size at all, not even the vector containing that structure.</p> <p><a href="http://www.cplusplus.com/reference/vector/vector/" rel="nofollow">http://www.cplusplus.com/reference/vector/vector/</a></p> <p>The vector handles its own memory dynamically ( in the heap ).</p>106620334365	0	 <p>The problem with your code is that you’re only ever removing one character at a time, and so repeated sequences will be reduced to a single character, but that single character will stick around at the end. For example, your code goes from “xxx” to “xx” to “x”, but since there’s only a single “x” left that “x” is not removed from the string. Adapt your code to remove <em>all</em> of the consecutive repeated characters and your problem will be fixed.</p>106718000537	0	 <p>You could use the function <a href="http://www.php.net/manual/en/function.eval.php" rel="nofollow">eval</a>, but this is very dangerous !</p> <p>This class might help you : <a href="http://www.phpclasses.org/browse/package/2695.html" rel="nofollow">http://www.phpclasses.org/browse/package/2695.html</a></p> <ul> <li>This class can be used to safely evaluate mathematical expressions.</li> <li>The class can take an expression in a text string and evaluate it by replacing values of variables and calculating the results of mathematical functions and operations.</li> <li>It supports implicit multiplication, multivariable functions and nested functions.</li> <li><strong>It can be used to evaluate expressions from untrusted sources. It provides robust error checking and only evaluates a limited set of functions.</strong></li> <li>It could be used to generate graphs from expressions of formulae. </li> </ul>1068533014	0	finder_sql for has_many relation <p>Given the following two (simplified) models:</p> <pre><code>class Customer &lt; ActiveRecord::Base # finder sql to include global users in the association has_many :users, :dependent =&gt; :destroy, :finder_sql =&gt; 'SELECT `u`.* FROM `users` `u` WHERE (`u`.`customer_id` = "#{id}" OR `u`.`customer_id` IS NULL)' validates_presence_of :name end class User &lt; ActiveRecord::Base # most users belong to a customer. # however, the customer_id may be NULL # to implement the concept of "global" users. belongs_to :customer validates_presence_of :email end </code></pre> <p>At first, this seems to work just fine:</p> <pre><code>&gt;&gt; Customer.first.users # =&gt; Array of users including global users </code></pre> <p>But when i try following i get an mysql error:</p> <pre><code>&gt;&gt; Customer.first.users.find_by_email("test@example.com") ActiveRecord::StatementInvalid: Mysql::Error: Operand should contain 1 column(s): SELECT * FROM `users` WHERE (`users`.`email` = 'test@example.com') AND ( SELECT `u`.* FROM `users` `u` WHERE (`u`.`customer_id` = "1" OR `u`.`customer_id` IS NULL) ORDER BY u.nickname ) LIMIT 1 from /Library/Ruby/Gems/1.8/gems/activerecord-2.2.2/lib/active_record/connection_adapters/abstract_adapter.rb:188:in `log' from /Library/Ruby/Gems/1.8/gems/activerecord-2.2.2/lib/active_record/connection_adapters/mysql_adapter.rb:309:in `execute' from /Library/Ruby/Gems/1.8/gems/activerecord-2.2.2/lib/active_record/connection_adapters/mysql_adapter.rb:563:in `select' from /Library/Ruby/Gems/1.8/gems/activerecord-2.2.2/lib/active_record/connection_adapters/abstract/database_statements.rb:7:in `select_all_without_query_cache' from /Library/Ruby/Gems/1.8/gems/activerecord-2.2.2/lib/active_record/connection_adapters/abstract/query_cache.rb:62:in `select_all' from /Library/Ruby/Gems/1.8/gems/activerecord-2.2.2/lib/active_record/base.rb:635:in `find_by_sql' from /Library/Ruby/Gems/1.8/gems/activerecord-2.2.2/lib/active_record/base.rb:1490:in `find_every' from /Library/Ruby/Gems/1.8/gems/activerecord-2.2.2/lib/active_record/base.rb:1452:in `find_initial' from /Library/Ruby/Gems/1.8/gems/activerecord-2.2.2/lib/active_record/base.rb:587:in `find' from /Library/Ruby/Gems/1.8/gems/activerecord-2.2.2/lib/active_record/base.rb:1812:in `find_by_email' from /Library/Ruby/Gems/1.8/gems/activerecord-2.2.2/lib/active_record/base.rb:1800:in `send' from /Library/Ruby/Gems/1.8/gems/activerecord-2.2.2/lib/active_record/base.rb:1800:in `method_missing' from /Library/Ruby/Gems/1.8/gems/activerecord-2.2.2/lib/active_record/associations/association_collection.rb:370:in `send' from /Library/Ruby/Gems/1.8/gems/activerecord-2.2.2/lib/active_record/associations/association_collection.rb:370:in `method_missing' from /Library/Ruby/Gems/1.8/gems/activerecord-2.2.2/lib/active_record/base.rb:2003:in `with_scope' from /Library/Ruby/Gems/1.8/gems/activerecord-2.2.2/lib/active_record/associations/association_proxy.rb:202:in `send' from /Library/Ruby/Gems/1.8/gems/activerecord-2.2.2/lib/active_record/associations/association_proxy.rb:202:in `with_scope' from /Library/Ruby/Gems/1.8/gems/activerecord-2.2.2/lib/active_record/associations/association_collection.rb:366:in `method_missing' </code></pre> <p>So, Rails is generating an invalid SQL Statement. The reason for that is probably my finder_sql, because the association without finder_sql works as expected.</p> <p>I've already tried to remove all optional plugins (will_paginate). The thing I'm trying to achieve is actually quite simple: Include all User Models matching the following the condition <code>(users.customer_id = 1 OR users.customer_id IS NULL)</code> in my association.</p> <p>Appreciate any help!</p>106933034773	0	 <pre><code>public class GuessingGame { public static void main(String[] args) { int NumberGuess = 0; Random randomNumber = new Random(); int randomInt = randomNumber.nextInt(51); System.out.println("Guess the number between 0 -50:"); int i = 1; Scanner UserGuess = new Scanner(System.in); while (i &lt;= 7) { NumberGuess = UserGuess.nextInt(); if (NumberGuess == randomInt) { System.out.println("Correct! You win!"); System.out.println("It took you " + i + " guesses."); System.exit(0); } else if (NumberGuess &lt; 0 || NumberGuess &gt; 50) { System.out.println("Invalid Input, please enter numbers between 0 and 50"); } else if (NumberGuess &lt; randomInt) { System.out.println("Guess is too small."); } else if (NumberGuess &gt; randomInt) { System.out.println("Guess is too big."); } System.out.println("You have made " + i + " guesses out of 7"); i++; } System.out.println("Game over!"); System.out.println("All 7 Guesses used!"); System.exit(0); } } </code></pre> <p>Also you should not <code>Scanner UserGuess = new Scanner(System.in);</code> use this statement inside the loop. <strong>Only one copy of the scanner should be created, outside the loop.</strong></p>107015837920	0	Find all <img> tags and change style attribute <p>i am trying to find a way to get the tag from a string and remove the style attribute . After that i want to add my own style and keep the following text.. For example, i have:</p> <pre><code>&lt;p&gt;&lt;img alt="" src="images/epsth/arismagnisiakos.jpg" style="width: 600px; height: 405px;" /&gt;&lt;/p&gt;&lt;p&gt;&amp;nbsp;&lt;/p&gt;&lt;p&gt; </code></pre> <p>end the endresult should be:</p> <pre><code>&lt;p&gt;&lt;img alt="" src="images/epsth/arismagnisiakos.jpg" style="width: 100%;" /&gt;&lt;/p&gt;&lt;p&gt;&amp;nbsp;&lt;/p&gt;&lt;p&gt; </code></pre> <p>I have unsuccesfully tried regex but it seems like i am too dumb to understand its functionality... </p> <p>Every help would be appreciated! Greetings from Greece Jim</p>107124452117	0	 <p>I just ran into this issue myself, the problem was that syntax coloring was set to C instead of Objective-C.</p> <p>Click Editor->Syntax Coloring->Objective-C</p>107216701980	0	 <p>Please make sure you have the same settings for <code>ansi_null</code> for both your local DB settings and your clients. style like "name is not null" will return the desired result, not like "name =/&lt;> null" that depends on ansi_null settings.</p> <p>check for ansi_null: <a href="http://msdn.microsoft.com/en-us/library/ms188048(v=sql.105).aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms188048(v=sql.105).aspx</a></p>107322203284	0	 <p>Python looks for the installed packages in the PYTHON_PATH environment variable. But I am not sure if that is your problem here. The error message suggests that there is a problem with the shared object versions... I would recommend you that you install everything you need with the pip install command on the console... </p>107415428036	0	how to remove 3 lines in row if the first line contain a specific character? <p>I have a data file (which a matrix with 290 lines and 2 columns) like this:</p> <pre><code># RIR1 ABABABABABABABABAA ABABABABABABABABBA # WR ABABABABABABABABAB BABABBABABABABABAA # BR2 ABABABABABABABBABA ABBABABABABABABABA # SL AAABABABABABABBABA AAABBABABABABABABA </code></pre> <p>I would like to remove all the data that are for SL and WR (as example). So I will have only:</p> <pre><code># RIR1 ABABABABABABABABAA ABABABABABABABABBA # BR2 ABABABABABABABBABA ABBABABABABABABABA </code></pre> <p>I know how to remove one line that start or contain something but no idea how to do with 3 lines in row.</p> <p>this is what I use for one line:</p> <pre><code>old&lt;-old[!substr(old[1,],1,5)=="# BR2",] old&lt;-old[!substr(old[1,],1,6)=="# RIR1",] </code></pre> <p>thanks in advance.</p>107528702920	0	 <p>Here's one <code>bash</code> solution (assuming the numbers are in a file, one per line):</p> <pre><code>sort -n numbers.txt | grep -n . | grep -v -m1 '\([0-9]\+\):\1' | cut -f1 -d: </code></pre> <p>The first part sorts the numbers and then adds a sequence number to each one, and the second part finds the first sequence number which doesn't correspond to the number in the array.</p> <p>Same thing, using sort and awk (bog-standard, no extensions in either):</p> <pre><code>sort -n numbers.txt | awk '$1!=NR{print NR;exit}' </code></pre>107610520854	0	 <pre><code>$('.className').click(funcName); </code></pre> <p>less load as it uses a single jquery object</p> <pre><code>$('.className').each(function(){ $(this).click(funcName); }); </code></pre> <p>more load as it uses the initial instance, and also generates a new instance for each 'eached' element via <code>$(this)</code>. If <code>$('.className')</code> contains 50 elements, you now have 51 jQuery objects, versus a single object.</p> <p>As far as pluggin development, you can use javascript objects and use <code>new</code> for each instance of the plugin. Or you can define a parent object class, and use <code>.each</code> on that to set up instances. I hope this helps, it hard to make a recommendation without knowing what your are cooking.</p>107717199202	0	How to create a mustache without using a file? <p>I have the template saved as a string somewhere and I want to create the mustache with that. How can I do this? Or is it doable?</p>10788170148	0	 <p>Generic info about buttons <a href="http://developer.android.com/reference/android/widget/Button.html" rel="nofollow">here</a></p> <p>To use image for a button you need an <a href="http://developer.android.com/reference/android/widget/ImageButton.html" rel="nofollow">android.widget.ImageButton</a>. Example of drawable selector (put it in res/drawable/):</p> <pre><code>&lt;selector xmlns:android="http://schemas.android.com/apk/res/android"&gt; &lt;item android:state_pressed="true" android:drawable="@drawable/button_pressed" /&gt; &lt;!-- pressed --&gt; &lt;item android:state_focused="true" android:drawable="@drawable/button_focused" /&gt; &lt;!-- focused --&gt; &lt;item android:drawable="@drawable/button_normal" /&gt; &lt;!-- default --&gt; &lt;/selector&gt; </code></pre> <p>So you can use different images for various states. To generate buttons on the fly you can define base layout with any layout manager (FrameLayout, RelativeLayout, LinearLayout), find it by id (findViewById()) within your Activity and make it visible: </p> <pre><code>public void createContainerForImageView() { LinearLayout container = new LinearLayout(this); container.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); container.setOrientation(LinearLayout.HORIZONTAL); ImageView img=(ImageView)findViewById(R.id.ImageView01); Bitmap bmp=BitmapFactory.decodeResource(getResources(), R.drawable.sc01); int width=200; int height=200; Bitmap resizedbitmap=Bitmap.createScaledBitmap(bmp, width, height, true); img.setImageBitmap(resizedbitmap); container.addView(img); // or you can set the visibility of the img } </code></pre> <p>Hope this helps.</p>107919733155	0	 <p>You would need to use the <a href="http://msdn.microsoft.com/en-us/library/ms132072.aspx">constructor for Dictionary</a> which accepts a custom <code>IEqualityComparer(Of T)</code> for your key type.</p> <p>Arrays, without a custom <a href="http://msdn.microsoft.com/en-us/library/ms132151%28v=vs.110%29.aspx"><code>IEqualityComparer(Of T)</code></a>, are not valid object types as keys to a dictionary (or other hash-based collection).</p>108037837741	0	MySQL - How to set auto_increment_increment permanently, to last server restart? <p>Is it possible to set MySQL auto_increment_increment so that it survives the server restart?</p> <p>Currently I'm setting it like this:</p> <pre><code>SET @@auto_increment_increment=2; </code></pre> <p>But it loses the value when I:</p> <pre><code>sudo service mysql restart </code></pre> <p>And returns to default value of 1.</p> <p>I'm on a AWS and I would like to be able to handle possible doomsday errors as easy as possible: by setting up a new instance from an AMI. I would like it to be ready to serve right away when it's up and avoid things like setting the auto_increment_increment -value by hand.</p>108111313935	1	Trying to catch integrity error with SQLAlchemy <p>I'm having problems with trying to catch an error. I'm using Pyramid/SQLAlchemy and made a sign up form with email as the primary key. The problem is when a duplicate email is entered it raises a IntegrityError, so I'm trying to catch that error and provide a message but no matter what I do I can't catch it, the error keeps appearing.</p> <pre><code>try: new_user = Users(email, firstname, lastname, password) DBSession.add(new_user) return HTTPFound(location = request.route_url('new')) except IntegrityError: message1 = "Yikes! Your email already exists in our system. Did you forget your password?" </code></pre> <p>I get the same message when I tried <code>except exc.SQLAlchemyError</code> (although I want to catch specific errors and not a blanket catch all). I also tried <code>exc.IntegrityError</code> but no luck (although it exists in the API).</p> <p>Is there something wrong with my Python syntax, or is there something I need to do special in SQLAlchemy to catch it?</p> <hr> <p>I don't know how to solve this problem but I have a few ideas of what could be causing the problem. Maybe the try statement isn't failing but succeeding because SQLAlchemy is raising the exception itself and Pyramid is generating the view so the <code>except IntegrityError:</code> never gets activated. Or, more likely, I'm catching this error completely wrong.</p>10826592841	0	 <p>An alternative approach is to just add a few forwarding functions:</p> <pre><code>T numberedFunction( unsigned int i ) { ... } T single() { return numberedFunction(1); } T halfDozen() { return numberedFunction(6); } </code></pre>108320520733	0	CSS code a:visited does not work <p>I have a pretty noob problem, so I hope someone could help me out.</p> <p>I have a Blogger blog, and I can't get the links to function like I want to.</p> <p>I want the links in the post content and in the sidebar - the ones that are a purple shade (#8B7083) and underlined - to look the same for both a:link and a:visited. For some reason visited links turn black, even though I don't have that anywhere in my CSS.</p> <p>Help me, please?</p>108439556966	0	 <p>This line:</p> <pre><code>A[j - 1] = 1; </code></pre> <p>Should be:</p> <pre><code>A[j] = 1; </code></pre> <p>So, now should works well:</p> <pre><code>#include&lt;stdio.h&gt; int A[1000000]; void sieve(int till) { for(int i = 2; i &lt; till; i++) { if(A[i] == 0) { for(int j = i*i; j &lt; till; j+=i) { A[j] = 1; } } } } int main() { int N,i; scanf("%i", &amp;N); for (i = 0;i &lt; N;i++) A[i] = 0; sieve(N); for (i = 2;i &lt; N;i++) if (A[i]) printf("%i is not prime\n",i); else printf("%i is prime\n",i); } </code></pre>108534104103	0	 <p>In <code>BigInt</code>, note <code>/%</code> operation which delivers a pair with the division and the reminder (see <a href="http://www.scala-lang.org/api/current/#scala.math.BigInt" rel="nofollow">API</a>). Note for instance</p> <pre><code>scala&gt; BigInt(3) /% BigInt(2) (scala.math.BigInt, scala.math.BigInt) = (1,1) scala&gt; BigInt(3) /% 2 (scala.math.BigInt, scala.math.BigInt) = (1,1) </code></pre> <p>where the second example involves an implicit conversion from <code>Int</code> to <code>BigInt</code>.</p>108623030942	0	 <p>I use this code:</p> <pre><code>public void getDefaultLauncher() { final Intent intent = new Intent(Intent.ACTION_MAIN); intent.addCategory(Intent.CATEGORY_HOME); PackageManager pm = getPackageManager(); final List&lt;ResolveInfo&gt; list = pm.queryIntentActivities(intent, 0); pm.clearPackagePreferredActivities(getApplicationContext().getPackageName()); for(ResolveInfo ri : list) { if(!ri.activityInfo.packageName.equals(getApplicationContext().getPackageName())) { startSpecificActivity(ri); return; } } } private void startSpecificActivity(ResolveInfo launchable) { ActivityInfo activity=launchable.activityInfo; ComponentName name=new ComponentName(activity.applicationInfo.packageName, activity.name); Intent i=new Intent(Intent.ACTION_MAIN); i.addCategory(Intent.CATEGORY_LAUNCHER); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); i.setComponent(name); startActivity(i); } </code></pre> <p>Maybe it works for you as well.</p>108723922079	1	How to write unittests for a custom pylint checker? <p>I have written a custom pylint checker <a href="https://github.com/rory/python-pylint-i18n" rel="nofollow">to check for non-i18n'ed strings in python code</a>. I'd like to write some unittests for that code now.</p> <p>But how? I'd like to have tests with python code as a string, which will get passed through my plugin/checker and check the output?</p> <p>I'd rather not write the strings out to temporary files and then invoke the pylint binary on it. Is there a cleaner more robust approach, which only tests my code?</p>108835737341	0	 <p>You are referencing to the wrong API. The link you have provided is for the Google Play Developer API which is for subscription, in-app purchase and publishing. The API for sharing progress and other in-game API calls is the <a href="https://developers.google.com/games/services/" rel="nofollow">Google Play Games Services</a> which has a default quota of 50000000 requests/day and in which the user can have 500 requests per second(The quotas can be seen in the Developer's Console). You could also see <a href="https://developers.google.com/games/services/quota" rel="nofollow">Managing Quota and Rate Limiting</a> for other info about the quota and limits.</p>108912784538	0	 <p>You should try moving your integration test to the top level project. This way it will run after the WAR artifact has been built.</p> <p>Have you had a look at the <a href="http://maven.apache.org/plugins/maven-failsafe-plugin/" rel="nofollow">Maven Failsafe Plugin</a>? It's designed for the sort of thing you're doing, which is actually an integration test and not a unit test. The page offers some good advice on why you might want to use the <code>integration-test</code> phase for your integration testing.</p> <p>Namely, it describes why you might want to do <code>start-jetty</code> during <code>pre-integration-test</code> and so on, so that you can tear it all down appropriately.</p>109028584599	0	 <p>This is a duplcate of an existing question</p> <p>See <a href="http://stackoverflow.com/a/7661057/2319909">http://stackoverflow.com/a/7661057/2319909</a></p> <p>Converted code for reference:</p> <p>You need to set the button to allow multiple lines. This can be achieved with following P/Invoke code.</p> <pre><code>Private Const BS_MULTILINE As Integer = &amp;H2000 Private Const GWL_STYLE As Integer = -16 &lt;System.Runtime.InteropServices.DllImport("coredll")&gt; _ Private Shared Function GetWindowLong(hWnd As IntPtr, nIndex As Integer) As Integer End Function &lt;System.Runtime.InteropServices.DllImport("coredll")&gt; _ Private Shared Function SetWindowLong(hWnd As IntPtr, nIndex As Integer, dwNewLong As Integer) As Integer End Function Public Shared Sub MakeButtonMultiline(b As Button) Dim hwnd As IntPtr = b.Handle Dim currentStyle As Integer = GetWindowLong(hwnd, GWL_STYLE) Dim newStyle As Integer = SetWindowLong(hwnd, GWL_STYLE, currentStyle Or BS_MULTILINE) End Sub </code></pre> <p>Use it like this:</p> <pre><code>MakeButtonMultiline(button1) </code></pre>109111932580	0	 <p>I solved this problem by using an activation profile :- </p> <pre><code>&lt;profiles&gt; &lt;profile&gt; &lt;id&gt;ptest&lt;/id&gt; &lt;activation&gt; &lt;property&gt; &lt;name&gt;ptest&lt;/name&gt; &lt;/property&gt; &lt;/activation&gt; &lt;build&gt; &lt;resources&gt; &lt;resource&gt; &lt;directory&gt;src/jmeter&lt;/directory&gt; &lt;/resource&gt; &lt;/resources&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;com.lazerycode.jmeter&lt;/groupId&gt; &lt;artifactId&gt;jmeter-maven-plugin&lt;/artifactId&gt; &lt;version&gt;1.4.1&lt;/version&gt; &lt;executions&gt; &lt;execution&gt; &lt;id&gt;jmeter-tests&lt;/id&gt; &lt;phase&gt;verify&lt;/phase&gt; &lt;goals&gt; &lt;goal&gt;jmeter&lt;/goal&gt; &lt;/goals&gt; &lt;/execution&gt; &lt;/executions&gt; &lt;configuration&gt; &lt;useOldTestEndDetection&gt;true&lt;/useOldTestEndDetection&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; &lt;/profile&gt; &lt;/profiles&gt; </code></pre> <p>Using this approach you can install once, not using the profile, and then run subsequently with the profile turned on. </p>109219092733	0	 <p>You can try and run an exception handler on the occurrence of exception. You can use a flag, I have used the exception for checking the exception occurence itself in the example:</p> <pre><code> private static AggregateException exception = null; static void Main(string[] args) { Console.WriteLine("Start"); Task.Factory.StartNew(PrintTime, CancellationToken.None).ContinueWith(HandleException, TaskContinuationOptions.OnlyOnFaulted); for (int i = 0; i &lt; 20; i++) { Console.WriteLine("Master Thread i={0}", i + 1); Thread.Sleep(1000); if (exception != null) { break; } } Console.WriteLine("Finish"); Console.ReadLine(); } private static void HandleException(Task task) { exception = task.Exception; Console.WriteLine(exception); } private static void PrintTime() { for (int i = 0; i &lt; 10; i++) { Console.WriteLine("Inner Thread i={0}", i + 1); Thread.Sleep(1000); } throw new Exception("exception"); } </code></pre>109321068282	0	Checkbox look like radio buttons on iPad/iPad Mini? <p>Not sure why this is happening, but couldn't find anything on this. Every <em>input type="checkbox"</em> look like radio buttons on iPads. Has anyone come across this issue and if so, how were you able to fix the problem?</p> <p>Thank you guys!</p> <pre><code>&lt;div&gt; &lt;input type="checkbox" name="checkNow"&gt;Check Now &lt;/div&gt; </code></pre>10942023342	0	 <p>You can achieve this with a <code>DockPanel</code>:</p> <pre><code>&lt;DockPanel Width="300"&gt; &lt;TextBlock&gt;Left&lt;/TextBlock&gt; &lt;Button HorizontalAlignment="Right"&gt;Right&lt;/Button&gt; &lt;/DockPanel&gt; </code></pre> <p>The difference is that a <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.stackpanel.aspx" rel="nofollow noreferrer"><code>StackPanel</code> will arrange child elements into single line</a> (either vertical or horizontally) whereas a <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.dockpanel.aspx" rel="nofollow noreferrer"><code>DockPanel</code> defines an area where you can arrange child elements either horizontally or vertically, relative to each other</a> (the <code>Dock</code> property changes the position of an element relative to other elements within the same container. Alignment properties, such as <code>HorizontalAlignment</code>, change the position of an element relative to its parent element).</p>10953998888	0	 <p>Every valid JSON is also valid JavaScript but not every valid JavaScript is also valid JSON as JSON is a proper subset of JavaScript:</p> <blockquote> <p>JSON ⊂ JavaScript</p> </blockquote> <p>JSON requires the names of name/value pairs to be quoted while JavaScript doesn’t (as long as they are not reserved keywords).</p> <p>So your first example <code>{"active": "yes"}</code> is both valid JSON and valid JavaScript while the second example <code>{active: "yes"}</code> is only valid JavaScript.</p>109624136726	0	 <p>You need to send exception about your error, to method <code>fail()</code>.</p> <pre><code>Assert.fail("Some message", new Exception(errorDivs.get(0).getText())); </code></pre>109714341379	0	Trigger a process (SQL update) when leaving an APEX page <p>This is a very odd question but i wondered whether it was possible to trigger a process that runs an SQL UPDATE when the user leaves this specific page, either by clicking on the breadcrumb, tabs or back button?</p> <p>I did setup the process to run on the 'Back' button; however i ran into the problem of: What if s/he clicks on the breadcrumb or a tab instead.</p> <p>I have searched the net and posting this question was a last resort. I wondered if anyone can point me in the correct direction?</p> <p><strong>UPDATED POST</strong> </p> <p><strong>Page 1:</strong><br> Includes a text field and a button. The user enters the category into the text field and clicks on the button to proceed to the next page. The button passes the value in the text field to a text field on Page 2.</p> <p><strong>Page 2:</strong><br> Two regions on the page. One region holds information about the category - Category name from the previous page, category description, and the category revision number (which is what i'm trying to get working). The second region is a report that pulls the item name and number that are listed under the category in the category text field. A 'View' link is used on the report to load the edit page for the specific item selected. The 'View' link passes the 'category name' (from the category text field) and the 'item number' from the report to page 3.</p> <p><strong>Page 3</strong><br> Two regions are used, first region: Lists the Item number which came from page 2 and name of the item (which i use a simple query to retrieve). In the second region: A report is used with two columns: a list of item properties in column 1, and a text field next to each item property in column 2 to hold the value that can be updated. The 'Apply Changes' button has some PlSql behind which looks for changes and updates where required. It updates the relevant fields that have changed, and it then takes the user back to Page 2 (Page showing user the items listed for the category intitally entered).</p> <p>I cant increase the category revision on the 'apply changes' button on page 3 because the user may complete edits for items under the same category. So i dont know where i can increase the category revision by 1 per vist to a category. P.s I already increment the revision number for each item by 1 if the info has been changed using the 'apply changes' button on page 3.</p>109821044819	0	 <p>You have to create a new serie and then add it to your chart.</p> <pre><code>Series series1 = new Series("series1"); chart1.Series.Add(series1); </code></pre> <p>You can also create them in your .aspx.</p> <pre><code>&lt;form id="form1" runat="server"&gt; &lt;asp:Chart ID="Chart1" runat="server" ImageType="Png"&gt; &lt;ChartAreas&gt; &lt;asp:ChartArea Name="ChartArea1"&gt;&lt;/asp:ChartArea&gt; &lt;/ChartAreas&gt; &lt;Legends&gt; &lt;asp:Legend Name="Legends1"&gt;&lt;/asp:Legend&gt; &lt;/Legends&gt; &lt;Series&gt; &lt;asp:Series Name="Series0"&gt;&lt;/asp:Series&gt; &lt;asp:Series Name="Series1"&gt;&lt;/asp:Series&gt; &lt;asp:Series Name="Series2"&gt;&lt;/asp:Series&gt; &lt;/Series&gt; &lt;/asp:Chart&gt; &lt;/form&gt; </code></pre>10997556033	0	Load or functional testing of GWT app using JMeter <p>I am new to JMeter. I wanted to do some functional testing of my GWT application using JMeter. Does it support GWT testing? For example I would like to write a script that might check if the login module of my GWT application is doing good or not. Please let me know if we have some sort of documentation specific to GWT testing with JMeter. </p> <p>Thanks a million. </p> <p>-- Mohyt</p>11004139738	0	Need help with a mIRC macro <p>I'm trying to make a script that will automatically says "see you later" as soon as one specific handle in a channel says the words "going home". I tried to do it on my own but got lost. Could anyone help me out?</p>110113168565	0	 <p>Why not to convert your pseudo-code to real code?</p> <pre><code>public static class MyExtensions { public static IEnumerable&lt;T&gt; RunMeOnEachItemLater(this IEnumerable&lt;T&gt; sequence, Action&lt;T&gt; action) { foreach(T item in sequence) { action(item); yield return item; } } } </code></pre> <p>Now you can execute custom function for each item later using LINQ deferred execution:</p> <pre><code>IEnumerable&lt;BaseModel&gt; l = Cache[type].Data.Cast&lt;BaseModel&gt;() .RunMeOnEachItemLater(m =&gt; m.Init()); </code></pre>11027257281	0	Using doxygen to create documentation for existing C# code with XML comments <p>I've read <em>everywhere</em> that doxygen is the way to go for generating documentation for C# code. I've got a single interface that I want to document first (baby steps), and it already has the XML comments (///) present.</p> <p>Because of the vast number of posts and information available (including doxygen.org) that say these comments are already supported, I'm surprised that when I run doxywizard, I get errors like "warning: Compound Company::Product::MyInterface is not documented".</p> <p>This leads me to believe that I have somehow misunderstood XML documentation (hopefully not, according to <a href="http://msdn.microsoft.com/en-us/library/b2s063f7.aspx">MSDN</a> I am talking about the right thing), or I have misconfigured doxywizard.</p> <p>I first ran doxywizard via the Wizard tab, and specified that I want to support C#/Java. When I run it, my HTML page is blank, presumably because of the previously-mentioned warnings. I then tried specifying a single file via the Expert tab and ran again -- same behavior.</p> <p>Can anyone tell me what switch or setting I'm missing to get doxygen to generate the HTML?</p> <p>Here's an example of what a documented property/method looks like in my interface:</p> <pre><code>/// &lt;summary&gt; /// Retrieve the version of the device /// &lt;/summary&gt; String Version { get; } /// &lt;summary&gt; /// Does something cool or really cool /// &lt;/summary&gt; /// &lt;param name="thing"&gt;0 = something cool, 1 = something really cool&lt;/param&gt; void DoSomething( Int32 thing); </code></pre> <p>I do have a comment above the interface, like this:</p> <pre><code>/// &lt;summary&gt; /// MyInterface /// &lt;/summary&gt; public interface MyInterface {...} </code></pre>110340597239	0	 <p>You will have to decide on a library to do API calls. A simple way is to use <code>fetch</code>, which is built-in in modern browsers. There's a <a href="https://github.com/github/fetch" rel="nofollow noreferrer">polyfill</a> to cover older ones. <a href="http://api.jquery.com/jquery.ajax/" rel="nofollow noreferrer">jQuery's AJAX</a> or <a href="http://visionmedia.github.io/superagent" rel="nofollow noreferrer">SuperAgent</a> are two alternatives. Here's a simple example using <code>fetch</code>. You'll only have to change the URL of the request.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>class Example extends React.Component { constructor() { super(); this.state = { data: {} }; } componentDidMount() { var self = this; fetch('http://reqres.in/api/users') .then(function(response) { return response.json() }).then(function(data) { self.setState({ data }, () =&gt; console.log(self.state)); }); } render() { return ( &lt;div/&gt; ); } } ReactDOM.render(&lt;Example/&gt;, document.getElementById('View'));</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"&gt;&lt;/script&gt; &lt;div id="View"&gt;&lt;/div&gt;</code></pre> </div> </div> </p>110410164600	0	 <p>%p is the format token to show AM/PM</p> <pre><code>time_tag(time, :format=&gt;'%B %d, %Y %l:%M %p') </code></pre>110531740599	0	 <p>You have error in your query, you are writing <code>select*</code> but there should be a space like so <code>select *</code></p> <p><code>$sql = mysql_query("select * from login where user= '$user' AND pass='$pass' LIMIT 3 ") or die(mysql_error());</code></p> <p><strong>EDIT</strong></p> <p>Also YOU MUST HAVE TO PUT <code>session_start();</code> as the first line of your code... else it would not work.</p> <p>So make this as your first lines of code</p> <pre><code>session_start(); error_reporting(E_ALL); // to see if there is error in code </code></pre> <p>And also PHP varialble names are <a href="http://php.net/manual/en/language.variables.basics.php" rel="nofollow">case-sensitive</a>, </p> <blockquote> <p>Variables in PHP are represented by a dollar sign followed by the name of the variable. <strong>The variable name is case-sensitive</strong>.</p> </blockquote> <p>So please change</p> <pre><code>if($user==$username &amp;&amp; $pass==$password) </code></pre> <p>to </p> <pre><code>if($user==$UserName &amp;&amp; $pass==$Password) </code></pre>11063896348	0	 <pre><code>Seq.initInfinite (fun _ -&gt; Console.ReadLine()) </code></pre>110710042197	0	 <p>It seems your mapper outputs a key-value pair of type <code>ImmutableBytesWritable -&gt; Result</code> but your Reducer reads in a key-value pair of type <code>ImmutableBytesWritable -&gt; Put</code>. This can't work as the output of the mapper must be of the same type the input of the reducer is. You should either</p> <ul> <li>change your mapper to output a <code>Put</code> object and adjust your method and class signatures</li> <li>or change the reducer signatures to allow for a Result object as in-value.</li> </ul>110825958074	1	Deleting multiple variables each pass of a loop <p>In the main loop of my program, I have around a dozen variables that are calculated each time the loop is actioned. At this stage I would prefer a 'NameError' than to have the variables from an earlier pass affect the outcome of a future pass of the loop.</p> <p>Right now I just have a series of the following statements run at the final step of each loop:</p> <pre><code>try: del my_var1 except: pass </code></pre> <p>I suspect there's a better way to do this?</p>110911281019	0	 <p>Third option:</p> <pre><code>&gt;&gt;&gt; from urlparse import urlparse, parse_qs &gt;&gt;&gt; url = 'http://something.com?blah=1&amp;x=2' &gt;&gt;&gt; urlparse(url).query 'blah=1&amp;x=2' &gt;&gt;&gt; parse_qs(urlparse(url).query) {'blah': ['1'], 'x': ['2']} </code></pre>111036026699	0	How to know whether Arduino Bluetooth is paired or not? <p>I am using an Arduino Mega and a Bluetooth module hc-05 zs040. I want to connect an external LED to the Arduino, which will indicate whether Bluetooth is paired or not. I read about the STATE pin and tried to use it but my state always outputs digital 0, no matter whether it is connected or not. Is there any other way to do this (other than soldering)?</p>111125275368	0	 <p>Explicitly declare all the variables:</p> <pre><code>function animate(num, element, transitionUnit, delayUnit) { var delay = 0; var transition = 0; var x = document.getElementById(element).getElementsByTagName("LI"); for (var i = 0; i &lt;= x.length - 1; i++) { x[i].style.WebkitTransform = "translate3d(" + num + "px,0,0)"; x[i].style.transition = transition + "s " + delay + "s ease-in-out"; delay += delayUnit; transition += transitionUnit; if (x[i].querySelectorAll('ul li').length &gt; 0) { x[i].style.background = "rgba(0,0,0,0.35)"; } } } </code></pre> <p>Using implicit globals in for loops causes problems.</p> <p>As aSeptik mentioned, you might be inverting values:</p> <pre><code>animate(0,"mainNav",0.04,0.02); </code></pre>111222980046	0	how to solve onTouchListener android <p>i have problem, I am successfully to display image in alert dialog custom, but when I want to add event <code>onTouchListener</code> to the image, i cannot get problem : <code>the method setonTouchListener in Type View is not applicable</code>. Here my source code :</p> <pre><code>public class ViewDetailItem extends Activity implements OnTouchListener{ bla bla... onloaditem() } </code></pre> <p>here onloaditem() sourcecode :</p> <pre><code> imgmain.setImageResource(imgID); imgmain.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub /*Intent MyIntentDetailItem=new Intent(getBaseContext(), ViewDetailItemFullscreen.class); Other_class.setItemCode(timgName); startActivity(MyIntentDetailItem);*/ LayoutInflater li = LayoutInflater.from(ViewDetailItem.this); final View inputdialogcustom = li.inflate(R.layout.activity_view_detail_item_fullscreen2, null); final AlertDialog.Builder alert = new AlertDialog.Builder(ViewDetailItem.this); final ImageView imgmainbig=((ImageView) inputdialogcustom.findViewById(R.id.imgmainbig)); imgID=getBaseContext().getResources().getIdentifier(imgName2+"_1", "drawable", getBaseContext().getPackageName()); imgmainbig.setImageResource(imgID); imgmainbig.setOnTouchListener(this); } } </code></pre> <p>The problem refers to <code>imgmainbig.setOnTouchListener(this);</code></p>111315423760	0	 <p>Microsoft tried to do something like that with <a href="http://en.wikipedia.org/wiki/WinFS" rel="nofollow">WinFS</a> but gave up on it. It would be great if they could get it to work.</p>11141765718	0	Android - NPE in BrowserFrame <p>I get this exception triggered by users occasionally that I cannot reproduce. Since it's issued from looper I suppose it is result of Handler-type callback. I found <a href="http://code.google.com/p/android/issues/detail?id=3355" rel="nofollow noreferrer">similar bug</a> on Google code but putting the solution into code didn't solve it. The problem is at this line of <a href="http://android.git.kernel.org/?p=platform/frameworks/base.git;a=blob;f=core/java/android/webkit/BrowserFrame.java;hb=cf4550c3198d6b3d92cdc52707fe70d7cc0caa9f" rel="nofollow noreferrer">code in BrowserFrame</a>: </p> <pre><code>WebAddress uri = new WebAddress( mCallbackProxy.getBackForwardList().getCurrentItem() .getUrl()); </code></pre> <p>Which throws this Exception because I suppose mCallbackProxy is null</p> <pre><code>java.lang.NullPointerException at android.webkit.BrowserFrame.handleMessage(BrowserFrame.java:348) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:123) at android.webkit.WebViewCore$WebCoreThread.run(WebViewCore.java:471) at java.lang.Thread.run(Thread.java:1060) </code></pre> <p>And the questions are - will this forclose the app? And how do I work around this bug?</p>111530478039	1	entering data and displaying entered data using python <p>I am newbie to python , I am trying to write a program in which i can print the entered data .</p> <p>here is the program which I tried.</p> <pre><code>#!"C:\python34\python.exe" import sys print("Content-Type: text/html;charset=utf-8") print() firststring = "bill" secondstring = "cows" thridstring = "abcdef" name = input('Enter your name : ') print ("Hi %s, Let us be friends!" % name) </code></pre> <p>The output of this program is only : "Enter your name : " I cannot enter anything from my keyboard. I am running this program using apache in localhost like <a href="http://localhost:804/cgi-bin/ex7.py" rel="nofollow">http://localhost:804/cgi-bin/ex7.py</a> Can anyone plz help me to print the user entered data. Thank you.</p>111617328937	0	Does installing a file automatically register it? <p>I am creating an MSI installer using WiX. I have several .ocx and .dll files that must be registered on the end user's computer. Does including these files in the installation automatically register them as if the regsvr32 command had been run?</p>111711461733	0	How to embed a property as a string argument in soapUI <p>I have recently started using soapui to test web services and fairly new. I was wondering how to embed a property value as a string in the request. For example the request is like below</p> <pre><code>&lt;org:Customer org1:Description="customer" org1:DisplayName="google" org1:Name="google"/&gt; </code></pre> <p>Essentially I am looking to do this something like this,</p> <pre><code>&lt;org:Customer org1:Description=${#Project#orgdesc} org1:DisplayName=${#Project#orgdisplayname} org1:Name=${#Project#orgdisplayname}/&gt; </code></pre> <p>I have properties defined for all of the fields above at the project level for parameterizing my test. I am trying to embed these properties within the request. I tried following things but none of them work. Can someone please let me know what I am missing?</p> <p><strong>Edit#1</strong></p> <p>I think I am not doing the right thing below. Because in the original request above, Description, DisplayName and Name are the attributes of Customer and I sending the request by making them as child nodes below. It seems fundamentally incorrect. Then how do I embed value of the properties I defined within attributes of a tag?</p> <p><strong>Attempt 1</strong></p> <pre><code> &lt;org:Customer&gt; &lt;arg0&gt; &lt;org1:Description&gt;${#Project#orgdesc}&lt;/org1:Description&gt; &lt;org1:DisplayName&gt;${#Project#orgdisplayname}&lt;/org1:DisplayName&gt; &lt;org1:Name&gt;${#Project#orgname}&lt;/org1:Name&gt; &lt;/arg0&gt; &lt;/org:Customer&gt; </code></pre> <p><strong>Attempt 2</strong></p> <pre><code> &lt;org:Customer&gt; &lt;org1:Description&gt; &lt;arg0&gt;${#Project#orgdesc}&lt;/arg0&gt; &lt;/org1:Description&gt; &lt;org1:DisplayName&gt; &lt;arg0&gt;${#Project#orgdisplayname}&lt;/arg0&gt; &lt;/org1:DisplayName&gt; &lt;org1:Name&gt; &lt;arg0&gt;${#Project#orgname}&lt;/arg0&gt; &lt;/org1:Name&gt; &lt;/org:Customer&gt; </code></pre>111838900347	0	 <p>There is an event in magento,</p> <pre><code>sales_quote_collect_totals_after </code></pre> <p>This is fired whenever your total is calculated, what you can do is set a flag in session on click on the button to apply discount, and in this above event's observer method, check if it is set then apply discount.</p> <p>In your config.xml</p> <pre><code>&lt;global&gt; &lt;events&gt; &lt;sales_quote_collect_totals_after&gt; &lt;observers&gt; &lt;class&gt;Custom_Module_Model_Observer&lt;/class&gt; &lt;method&gt;collectTotals&lt;/method&gt; &lt;/observers&gt; &lt;/sales_quote_collect_totals_after&gt; &lt;/events&gt; &lt;/global&gt; </code></pre> <p>Make a Observer.php in</p> <pre><code>Custom /Module /Model /Observer.php </code></pre> <p>Make a function in Observer.php</p> <pre><code>public function collectTotals(Varien_Event_Observer $observer) { $quote=$observer-&gt;getEvent()-&gt;getQuote(); $quoteid=$quote-&gt;getId(); //check condition here if need to apply Discount if($disocuntApply) $discountAmount =5; if($quoteid) { if($discountAmount&gt;0) { $total=$quote-&gt;getBaseSubtotal(); $quote-&gt;setSubtotal(0); $quote-&gt;setBaseSubtotal(0); $quote-&gt;setSubtotalWithDiscount(0); $quote-&gt;setBaseSubtotalWithDiscount(0); $quote-&gt;setGrandTotal(0); $quote-&gt;setBaseGrandTotal(0); $canAddItems = $quote-&gt;isVirtual()? ('billing') : ('shipping'); foreach ($quote-&gt;getAllAddresses() as $address) { $address-&gt;setSubtotal(0); $address-&gt;setBaseSubtotal(0); $address-&gt;setGrandTotal(0); $address-&gt;setBaseGrandTotal(0); $address-&gt;collectTotals(); $quote-&gt;setSubtotal((float) $quote-&gt;getSubtotal() + $address-&gt;getSubtotal()); $quote-&gt;setBaseSubtotal((float) $quote-&gt;getBaseSubtotal() + $address-&gt;getBaseSubtotal()); $quote-&gt;setSubtotalWithDiscount( (float) $quote-&gt;getSubtotalWithDiscount() + $address-&gt;getSubtotalWithDiscount() ); $quote-&gt;setBaseSubtotalWithDiscount( (float) $quote-&gt;getBaseSubtotalWithDiscount() + $address-&gt;getBaseSubtotalWithDiscount() ); $quote-&gt;setGrandTotal((float) $quote-&gt;getGrandTotal() + $address-&gt;getGrandTotal()); $quote-&gt;setBaseGrandTotal((float) $quote-&gt;getBaseGrandTotal() + $address-&gt;getBaseGrandTotal()); $quote -&gt;save(); $quote-&gt;setGrandTotal($quote-&gt;getBaseSubtotal()-$discountAmount) -&gt;setBaseGrandTotal($quote-&gt;getBaseSubtotal()-$discountAmount) -&gt;setSubtotalWithDiscount($quote-&gt;getBaseSubtotal()-$discountAmount) -&gt;setBaseSubtotalWithDiscount($quote-&gt;getBaseSubtotal()-$discountAmount) -&gt;save(); if($address-&gt;getAddressType()==$canAddItems) { $address-&gt;setSubtotalWithDiscount((float) $address-&gt;getSubtotalWithDiscount()-$discountAmount); $address-&gt;setGrandTotal((float) $address-&gt;getGrandTotal()-$discountAmount); $address-&gt;setBaseSubtotalWithDiscount((float) $address-&gt;getBaseSubtotalWithDiscount()-$discountAmount); $address-&gt;setBaseGrandTotal((float) $address-&gt;getBaseGrandTotal()-$discountAmount); if($address-&gt;getDiscountDescription()){ $address-&gt;setDiscountAmount(-($address-&gt;getDiscountAmount()-$discountAmount)); $address-&gt;setDiscountDescription($address-&gt;getDiscountDescription().', Amount Waived'); $address-&gt;setBaseDiscountAmount(-($address-&gt;getBaseDiscountAmount()-$discountAmount)); }else { $address-&gt;setDiscountAmount(-($discountAmount)); $address-&gt;setDiscountDescription('Amount Waived'); $address-&gt;setBaseDiscountAmount(-($discountAmount)); } $address-&gt;save(); }//end: if } //end: foreach //echo $quote-&gt;getGrandTotal(); foreach($quote-&gt;getAllItems() as $item){ //We apply discount amount based on the ratio between the GrandTotal and the RowTotal $rat=$item-&gt;getPriceInclTax()/$total; $ratdisc=$discountAmount*$rat; $item-&gt;setDiscountAmount(($item-&gt;getDiscountAmount()+$ratdisc) * $item-&gt;getQty()); $item-&gt;setBaseDiscountAmount(($item-&gt;getBaseDiscountAmount()+$ratdisc) * $item-&gt;getQty())-&gt;save(); } } } } </code></pre> <p><code>collectTotals</code> function will be called, whenever the quote totals is updated, so there is no need to call it explicitly.</p> <p>Check for how it works <a href="http://www.aschroder.com/2010/01/magento-events-explained-and-a-few-gotchas-avoided/" rel="nofollow">here</a>.</p> <p>Setting magento session variables, check <a href="http://www.apptha.com/blog/how-to-set-retrieve-and-unset-session-variables-in-magento/" rel="nofollow">here</a>.</p> <p>hope it helps!</p>111939225329	0	 <p>First one is an example of a nested state which fulfills your requirement for inheriting the scope object. e.g state/sub-state-a, state/sub-state-b The comment above the first snippet you took from the doc reads:</p> <blockquote> <p>Shows prepended url, inserted template, paired controller, and inherited $scope object.</p> </blockquote> <p>The second example is a nested view where you can define multiple views per state and use each depending on your use-case. From the docs:</p> <blockquote> <p>Then each view in views can set up its own templates (template, templateUrl, templateProvider), controllers (controller, controllerProvider).</p> </blockquote>112026493784	0	 <p>To get the results you want without changing your existing code too much, you can get the sequence line when you're processing the header line:</p> <pre><code>while ( my $line = &lt;FILE2&gt; ) { if ($line =~ /^&gt;(\S+)\s+\S+\s+(\d+)\s+(\d+)\s+(\S+)/) { my $cds1 = $1; my $cds2 = $2; my $cds3 = $3; my $cds4 = $4; # fetch the next line from the file -- i.e. the sequence $nextline = &lt;FILE2&gt;; for my $cc22 (@file1list) { if ( $cc22 &gt; $cds2 &amp;&amp; $cc22 &lt; $cds3 ) { print "$cc22 $cds2 $cds3 $cds4 $nextline"; } } } } </code></pre>11215730726	0	 <p>The mouse does work for single finger gestures and taps, not sure why it wouldn't work for you except to assume that your code must not be working as you assume :-)</p> <p>Just for reference, the other way of testing multi-touch is to have a multi-touch enabled monitor</p>11223319559	0	 <p>" <em>Is it possible with some code in the controller to define the nested master page and master page?</em>"</p> <p>Nope. The default view engine only lets you define one level of MasterPages. </p> <p>See: <a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.controller.view.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.web.mvc.controller.view.aspx</a></p>11232420358	0	Why does using a structure in C program cause Link error <p>I am writing a C program for a 8051 architecture chip and the SDCC compiler.</p> <p>I have a structure called FilterStructure;</p> <p>my code looks like this...</p> <pre><code>#define NAME_SIZE 8 typedef struct { char Name[NAME_SIZE]; } FilterStructure; void ReadFilterName(U8 WheelID, U8 Filter, FilterStructure* NameStructure); int main (void) { FilterStructure testStruct; ReadFilterName('A', 3, &amp;testFilter); ... ... return 0; } void ReadFilterName(U8 WheelID, U8 Filter, FilterStructure* NameStructure) { int StartOfName = 0; int i = 0; ///... do some stuff... for(i = 0; i &lt; 8; i++) { NameStructure-&gt;Name[i] = FLASH_ByteRead(StartOfName + i); } return; } </code></pre> <p>For some reason I get a link error "?ASlink-Error-Could not get 29 consecutive bytes in internal RAM for area DSEG" </p> <p>If I comment out the line that says <code>FilterStructure testStruct;</code> the error goes away.</p> <p>What does this error mean? Do I need to discard the structure when I am done with it?</p>11241351741	0	 <p>The answer is <strong>no</strong>, by default object identity is not preserved via serialization if you are considering 2 separate serializations of a given object/graph. For example, if a I serialize an object over the wire (perhaps I send it from a client to a server via RMI), and then do it again (in separate RMI calls), then the 2 deserialized objects on the server will <em>not</em> be ==.</p> <p>However, in a "single serialization" e.g. a single client-server message which is a graph containing the same object multiple times then upon deserialization, identity <em>is</em> preserved. </p> <p>For the first case, you can, however, provide an implementation of the <a href="http://docs.oracle.com/javase/7/docs/platform/serialization/spec/input.html#5903" rel="nofollow noreferrer"><code>readResolve</code></a> method in order to ensure that the correct instance is returned (e.g. in the <em>typesafe enum</em> pattern). <code>readResolve</code> is a private method which will be called by the JVM on a de-serialized Java object, giving the object the chance to return a different instance. For example, this is how the <code>TimeUnit</code> <code>enum</code> may have been implemented before <code>enum</code>'s were added to the language:</p> <pre><code>public class TimeUnit extends Serializable { private int id; public TimeUnit(int i) { id = i; } public static TimeUnit SECONDS = new TimeUnit(0); //Implement method and return the relevant static Instance private Object readResolve() throws ObjectStreamException { if (id == 0) return SECONDS; else return this; } } </code></pre> <p>.</p>112529765240	0	If without else not running <p>I have a little code for testing a sprite, that I want to move with the mouse. When I click the screen, the sprite has to move to the clicked point. But something weird is going on.</p> <p>I'm running it in a thread, called Controls, that extends to Thread and implements MouseListener, and using the following code, the sprite moves.</p> <pre><code>public void run() { while(true){ if((int)point.getX() &gt; player.getX()){ while((int)point.getX() &gt; player.getX()){ player.moveX(1); } } else{ System.out.println("Nah!"); } } } </code></pre> <p>Everything works as expected, but if i do this:</p> <pre><code>public void run() { while(true){ if((int)point.getX() &gt; player.getX()){ while((int)point.getX() &gt; player.getX()){ player.moveX(1); } } } } </code></pre> <p>It doesn't work. If i do this:</p> <pre><code>public void run() { while(true){ if((int)point.getX() &gt; player.getX()){ while((int)point.getX() &gt; player.getX()){ player.moveX(1); } } else{ } } } </code></pre> <p>It doesn't work either. I have no idea of what is going on, any ideas?</p>112628395585	0	Laravel 4.2 returning soft deleted on BelongsToMany results <p>Hello I just noticed one weird behaviour of softDelete. Basically, when I query for a related set of models, Eloquent returns a collection that also contains soft deleted rows.</p> <p>I have been following the 4.2 guides on traits usage for softdelete and my code works just fine as long as I get/delete/restore/force delete my models. The issue is triggered with relations.</p> <p>Consider this scenario: I have a user model that has a belongToMany friendship relation where the friendship status can be accepted/pending/requested/blocked as follows:</p> <pre><code>public function friends() { return $this-&gt;belongsToMany('User', 'friends', 'user_id', 'friend_id')-&gt;where('status', 'accepted'); } </code></pre> <p>This friends table rows are basically "vectors" where user1->status->user2 and viceversa (user2->status->user1 is on another row). When user1 decides not to be friend with user2 anymore, the 2 friends rows are softdeleted.</p> <p>Here is the issue: when I query the DB from the controller like this:</p> <pre><code>$friends = $user-&gt;friends; </code></pre> <p>even the softdeleted rows show up in the returned collection even though I would have expected these to be hidden from results unless I used ->withTrashed().</p> <p>I suspect the belongsToMany() method doesn't take into account the deleted_at field on the pivot table.</p> <p>Did anyone faced a similar issue? Am I doing something wrong with this relation?</p> <p>Thanks a lot for your help!!!</p>112718988439	0	 <p><strong>Method 1:</strong> Using <code>list.index</code>:</p> <pre><code>def match(strs, actual): seen = {} act = actual.split('/') for x in strs.split('/'): if x in seen: #if the item was already seen, so start search #after the previous matched index ind = act.index(x, seen[x]+1) yield ind seen[x] = ind else: ind = act.index(x) yield ind seen[x] = ind ... &gt;&gt;&gt; p1 = '/foo/baz/myfile.txt' &gt;&gt;&gt; p2 = '/bar/foo/myfile.txt' &gt;&gt;&gt; actual = '/foo/bar/baz/myfile.txt' &gt;&gt;&gt; list(match(p1, actual)) #ordered list, so matched [0, 1, 3, 4] &gt;&gt;&gt; list(match(p2, actual)) #unordered list, not matched [0, 2, 1, 4] &gt;&gt;&gt; p1 = '/foo/bar/bar/myfile.txt' &gt;&gt;&gt; p2 = '/bar/bar/baz/myfile.txt' &gt;&gt;&gt; actual = '/foo/bar/baz/bar/myfile.txt' &gt;&gt;&gt; list(match(p1, actual)) #ordered list, so matched [0, 1, 2, 4, 5] &gt;&gt;&gt; list(match(p2, actual)) #unordered list, not matched [0, 2, 4, 3, 5] </code></pre> <hr> <p><strong>Method 2:</strong> Using <code>defaultdict</code> and <code>deque</code>:</p> <pre><code>from collections import defaultdict, deque def match(strs, actual): indexes_act = defaultdict(deque) for i, k in enumerate(actual.split('/')): indexes_act[k].append(i) prev = float('-inf') for item in strs.split('/'): ind = indexes_act[item][0] indexes_act[item].popleft() if ind &gt; prev: yield ind else: raise ValueError("Invalid string") prev = ind </code></pre> <p><strong>Demo:</strong></p> <pre><code>&gt;&gt;&gt; p1 = '/foo/baz/myfile.txt' &gt;&gt;&gt; p2 = '/bar/foo/myfile.txt' &gt;&gt;&gt; actual = '/foo/bar/baz/myfile.txt' &gt;&gt;&gt; list(match(p1, actual)) [0, 1, 3, 4] &gt;&gt;&gt; list(match(p2, actual)) ... raise ValueError("Invalid string") ValueError: Invalid string &gt;&gt;&gt; p1 = '/foo/bar/bar/myfile.txt' &gt;&gt;&gt; p2 = '/bar/bar/baz/myfile.txt' &gt;&gt;&gt; actual = '/foo/bar/baz/bar/myfile.txt' &gt;&gt;&gt; list(match(p1, actual)) [0, 1, 2, 4, 5] &gt;&gt;&gt; list(match(p2, actual)) ... raise ValueError("Invalid string") ValueError: Invalid string </code></pre>112834621470	0	 <p>I assume, the question reflects an attemtpt to use unique_lock, which OP is saying works. The same example with lock_guard would not work, since <code>std::vector::emplace_back</code> requires the type to be both <code>MoveInsertable</code> and <code>EmplaceConstructible</code>, and <code>std::lock_guard</code> does not suit.</p>112922336760	0	 <p>Use:</p> <pre><code>NodeList nodeList = doc.getElementsByTagName("xLabel"); for (int temp = 0; temp &lt; nodeList.getLength(); temp++) { Node node = nodeList.item(temp); NodeList namexLabelNodes = node.getChildNodes(); for (int i = 0; i &lt; namexLabelNodes.getLength(); i++) { System.out.println(" Name : " + namexLabelNodes.item(i).getTextContent()); } } </code></pre> <p>For yLabel will be same code. </p>113022907415	0	Eclipse PHP code formatter removes pipe symbols from @return comments <p>I'm using Eclipse Kepler (4.3.1) for a PHP project.</p> <p>I've stumbled across a problem with the eclipse code formatter for PHP regarding PHPDoc's @return with pipe (vertical bar) symbol: When having a comment like this:</p> <pre><code>&lt;?php /** * * @param string|array The parameter. Either a string or an array. * @return int|string The return value. Either an int or a string. */ function test($param) { } </code></pre> <p>Using the format function with [CTRL]+[SHIFT]+[F] results in:</p> <pre><code>&lt;?php /** * * @param * string|array The parameter. Either a string or an array. * @return int string return value. Either an int or a string. */ function test($param) { } </code></pre> <p>As one can see, the pipe symbol between 'int' and 'string' in the '@return' statement has been replaced by a space. But not only that. Also the first word of the description ('The') has been chopped off. On the other hand, it works just fine for the '@param' statement.</p> <p>phpdoc.org states, that the pipe symbol is used when handling ambigous return values: <a href="http://www.phpdoc.org/docs/latest/for-users/phpdoc/tags/return.html" rel="nofollow">phpdoc-@return</a></p> <p>Somebody also asked a question about this int the Eclipse Community Forums: <a href="http://www.eclipse.org/forums/index.php/t/683282/" rel="nofollow">Forum Post</a> just a few days ago.</p> <p>Using '@formatter:off' and '@formatter:on' is no option, since this setting is only local and others might not have it set.</p> <p>Does anyone know how to fix-configure the eclipse php code formatter? Does anybody have a workaround?</p>113138567369	0	 <p><a href="http://stackoverflow.com/a/38566818/6573268">Rudy Velthuis's answer</a> explains it perfectly. If I understand correctly what you are trying to do can be done like this.</p> <pre><code>int pckt_number = 0; // 0 pckt_number |= 0 &lt;&lt; 24; // most significant byte, pckt_number |= 1 &lt;&lt; 16; // second most significant byte, pckt_number |= 0 &lt;&lt; 8; // third most significant byte, pckt_number |= 0; // least significant byte, </code></pre>113241059077	0	 <p>The correct path to use is the <code>platform/google_appengine/</code> directory, within the <code>google-cloud-sdk</code> installation directory, </p>113329374058	0	 <p>All your optionals need to be unwrapped. So <code>lvt</code> should become <code>lvt!</code></p> <p><strong>Word of Caution</strong> Unwrapping an optional which doesn't have a value will thrown an exception. So it might be a good idea to make sure your lvt isn't nil. </p> <pre><code>if (lvt != nil) </code></pre>113438529477	0	Repeating Javascript Animation <p>I have found a JSFiddle that has some great code to animate a ball - it rotates it through 360 deg. What I would like to do is have the ball constantly rotate through 360 deg - it needs to turn continuously. I have tried to achieve this but have had no success. I would be grateful for any help in adjusting this javascript.</p> <pre><code>$(document).ready(function(){ var s=$('.ball').position(); var g=s.left; var r=$('.ball').css('margin-left'); $('.ball').css({'margin-left':'0px'}); $('.ball').css({'margin-left':''+r+''}); if(r=="0px") { $('.ball').css({'position':'absolute'}); $('.ball').animate({'left':''+g+'px'}); } $('.ball').css({'transform': 'rotate(360deg)','-webkit-transform': 'rotate(360deg)','-moz-transform': 'rotate(360deg)'}); }); </code></pre> <p>This is the JSFiddle I found <a href="http://jsfiddle.net/996PJ/5/" rel="nofollow">http://jsfiddle.net/996PJ/5/</a></p>11357053631	0	 <p>You can try to use a different library to load this assembly, like <a href="http://www.mono-project.com/Cecil" rel="nofollow"><code>Mono.Cecil</code></a>.</p>113620149966	1	Python Error: list index out of range <p>I keep getting the error list index out of range. I'm not sure what I'm doing wrong.</p> <p>My code:</p> <pre><code>from scanner import * def small(array): smallest=array[0] for i in range(len(array)): if (array[i]&lt;smallest): smallest=array[i] return smallest def main(): s=Scanner("data.txt") array=[] i=s.readint() while i!="": array.append(i) i=s.readint() s.close() print("The smallest is", small(array)) main() </code></pre> <p>The traceback I get:</p> <pre><code>Traceback (most recent call last): File "file.py", line 21, in &lt;module&gt; main() File "file.py", line 20, in main print("The smallest is", small(array)) File "file.py", line 5, in small smallest=array[0] IndexError: list index out of range </code></pre>113712503239	0	 <p>Use the <a href="http://msdn.microsoft.com/en-us/library/ef48waz8.aspx">overload</a> that takes a <a href="http://msdn.microsoft.com/en-us/library/system.midpointrounding.aspx"><code>MidpointRounding</code></a></p> <pre><code>Math.Round(276.5, MidpointRounding.AwayFromZero); </code></pre> <p>demo: <a href="http://ideone.com/sQ26z">http://ideone.com/sQ26z</a></p>11386561284	0	 <ol> <li>Allocating memory with <code>new/new[]/malloc</code> and not freeing it</li> <li>Allocating memory to some pointer and overwrite it accidently e.g. <code>p = new int; p = new int[1];</code></li> <li>Allocating memory in air. i.e. <code>new int[100];</code> or <code>cout&lt;&lt;(*new string("hello"))&lt;&lt;endl;</code></li> </ol>113926981858	0	 <p>using row number windowed function along with a CTE will do this pretty well. For example:</p> <pre><code>;With preResult AS ( SELECT TOP(100) [ID] = c.[ID], [Name] = c.[Name], [Keyword] = [colKeyword].[StringVal], [DateAdded] = [colDateAdded].[DateVal], ROW_NUMBER()OVER(PARTITION BY c.ID ORDER BY [colDateAdded].[DateVal]) rn FROM @cards AS c LEFT JOIN @cardindexes AS [colKeyword] ON [colKeyword].[CardID] = c.ID AND [colKeyword].[IndexType] = 1 LEFT JOIN @cardindexes AS [colDateAdded] ON [colDateAdded].[CardID] = c.ID AND [colDateAdded].[IndexType] = 2 WHERE [colKeyword].[StringVal] LIKE 'p%' AND c.[CardTypeID] = 1 ORDER BY [DateAdded] ) SELECT * from preResult WHERE rn = 1 </code></pre>11408643895	0	QTableView - change selection when scrolling <p>I have a QTableView. I want the selection to be moved when i scroll - so the cursor would be always visible.</p> <p><img src="https://i.stack.imgur.com/DddG0.png" alt="enter image description here"></p> <p>There is <code>QTableView.selectRow(rowNo)</code>, but do you have a suggestion where to call this?</p> <p>Ideally i would like upon scrolling the selected row to be in the center.</p>114135714038	0	 <p>You have to enable the allowable rotations at the project level and then restrict rotation on all the viewControllers you DON'T want to rotate. i.e. if you have 5 viewControllers, you'll need to restrict rotation on 4 of them and only allow rotation on the Player Controller. You can see more on this here <a href="http://stackoverflow.com/questions/19502251/handling-autorotation-for-one-view-controller-in-ios7">Handling autorotation for one view controller in iOS7</a></p>11423431255	0	 <p>Thanks to advice, I made it! Here is the code.</p> <pre><code>var foo = function(){}; foo.prototype = { say : function(s){ Queue.enqueue(function(){ alert(s); }); Queue.flush(); return this; }, delay : function(ms){ Queue.enqueue('delay:' + ms); return this; } } Queue = { entries : [], inprocess : null, enqueue : function(entry){ Queue.entries.push(entry); }, flush : function(){ if(Queue.inprocess) return; while (Queue.entries.length){ var entry = Queue.entries.shift(); if(entry.toString().indexOf('delay:') !== -1){ var ms = Number(entry.split(':')[1]); Queue.inprocess = setTimeout(function(){ Queue.inprocess = null; Queue.flush(); }, ms); return; } entry(); } } } </code></pre> <p>I prepared a Queue object to manage functions' entries. With this, I can play with a method-chain:</p> <pre><code>var bar = new foo(); bar.delay(2000).say('Hello, ').delay(3000).say('world!'); </code></pre> <p>Many thanks!</p>114323850869	0	 <p>Return a pair of values containing the weight and value:</p> <pre><code>pair&lt;int, int&gt; knapsack(int N, int budget) { if((!N) || (!budget)) return pair&lt;int, int&gt;(0, 0); pair&lt;int, int&gt; local(N, budget); if(hash_memo[local].second) return hash_memo[local]; pair&lt;int, int&gt; b = pair&lt;int, int&gt;(0, 0); pair&lt;int, int&gt; a = knapsack(N-1, budget); if(budget &gt;= arr[N-1].first) { pair&lt;int, int&gt; c = knapsack(N-1, budget - arr[N-1].first); b = pair&lt;int, int&gt;(c.first + arr[N-1].first, c.second + arr[N-1].second); } if(a.second &gt; b.second) { return hash_memo[local] = a; } return hash_memo[local] = b; } </code></pre>114422752345	0	 <p>I'm assuming you left some out, is this the complete code?</p> <pre><code>public class House { private final House house; public static void main(String[] args) { house = new House("Robinsons"); house.setColor("Red"); } public House(String houseName) { // do something } public void setColor(String color) { // do something } } </code></pre> <p>If so, there are a number of problems with this.</p> <ol> <li>a final variable needs to be given a value right on declaration. And to answer your question, <strike>once a final variable is given a value (when declaring it), that will be the last time you can modify it.</strike> (refer to comments below, thanks exception1!).</li> <li>House is not a static variable, so it cannot be accessed from inside the <code>main</code> method, either make <code>house</code> a static variable, which I wouldn't recommend. Or declare an instance inside the <code>main</code> method before using it.</li> </ol>114514378969	0	Google GCM demo app - Server messages not being received <p>I am trying to get the Google GCM demo app up and running. My android emulator makes a successful connection to the GCM server and goes on to make successful connection to my own server which is located at <code>http://localhost:8080/gcm-demo-server</code> (ie. the emulator sends the request to <code>http://10.0.2.2:8080/gcm-demo-server</code>).</p> <p>However when I click 'Send message' on my server's webpage the message doesn't get delivered to the emulator. Nothing shows up in Logcat and my breakpoint in onMessage() in the GCMIntentService class doesn't get hit.</p> <p>I can't understand how it can successfully register with the server, passing it's registrationId, yet when that registrationId is used to send a message back to the emulator it doesn't get received. I have not altered the demo app code.</p> <p>Anyone ideas what could be going where or where I could start looking for problems as I don't even know where to start with this.</p>11465721079	0	Issue with transferring of developer certificate and Provisioning Profile under Xcode <p>I am trying transfer my developer certificate under the keychain to someone. I exported the item. And also send him the provisioning profile which includes his device ID. He installed my certificate to his keychain and also the provisioning profile to his xcode. However, The provisioning profile under his xcode complains of there's no Valid signing Identity. Well I already sent him the certificate.</p> <p>What's wrong?</p>114715025659	0	 <pre><code>if( browser.Button("id").Enabled) Console.Write("Enabled"); else Console.Write("Disabled"); </code></pre> <p>you can try this.</p>114810101095	0	Please explain the behaviour of Rails's cache in this case <p>Imagine I have 5 tags: <code>tag1,tag2...tag5</code>. If I do the following:</p> <pre><code>Rails.cache.fetch("all.tags") { Tag.all } </code></pre> <p>and afterwards I write <code>Rails.cache.fetch("all.tags")</code>, I see the 5 tags. If I add another tag, and I try to fetch from the cache again, the new tag is also loaded. Why is that?</p> <p>EDIT: Here's my actual code:</p> <pre><code>Rails.cache.fetch("autocomplete.#{term}") { puts "Cache miss #{term}"; Tag.starting_with(term) } </code></pre> <p>Where <code>starting_with</code> is doing a where to find tags starting with certain letters. Here's the behaviour I get in the console:</p> <pre><code>1.9.3p125 :046 &gt; Rails.cache.read("autocomplete.ta") Tag Load (1.0ms) SELECT "tags".* FROM "tags" WHERE (name like 'ta%') =&gt; [#&lt;Tag id: 10, name: "tag1"&gt;, #&lt;Tag id: 11, name: "tag2"&gt;, #&lt;Tag id: 12, name: "tag3"&gt;, #&lt;Tag id: 13, name: "tag4"&gt;] 1.9.3p125 :048 &gt; Tag.create(name:"tag5") (0.2ms) begin transaction SQL (1.0ms) INSERT INTO "tags" ("name") VALUES (?) [["name", "tag5"]] (150.9ms) commit transaction =&gt; #&lt;Tag id: 14, name: "tag5"&gt; 1.9.3p125 :049 &gt; Rails.cache.read("autocomplete.ta") Tag Load (0.8ms) SELECT "tags".* FROM "tags" WHERE (name like 'ta%') =&gt; [#&lt;Tag id: 10, name: "tag1"&gt;, #&lt;Tag id: 11, name: "tag2"&gt;, #&lt;Tag id: 12, name: "tag3"&gt;, #&lt;Tag id: 13, name: "tag4"&gt;, #&lt;Tag id: 14, name: "tag5"&gt;] </code></pre>114917066858	0	 <p>It is a typo indeed</p> <pre><code>&lt;? require($_SERVER["DOCUMENT_ROOT"] . '/WestAncroftSettings.php' ); ?&gt; </code></pre> <p>should be</p> <pre><code>&lt;?php require($_SERVER["DOCUMENT_ROOT"] . '/WestAncroftSettings.php' ); ?&gt; </code></pre> <p>and later in your code you have the same line again without <code>&lt;?php</code> and your missing quotes around <code>DOCUMENT_ROOT</code></p>115038098717	0	Running praat on remote ubuntu server <p>I am working for a web application using praat features. I have written a script for that and it is working fine in ubuntu. But now i want to run these .praat scripts in a remote ubuntu server and I have already installed praat but when I run praat it gives me the following error:</p> <blockquote> <p>(praat:1364): GLib-GObject-WARNING **: invalid (NULL) pointer instance</p> <p>(praat:1364): GLib-GObject-CRITICAL **: g_signal_connect_data: assertion 'G_TYPE_CHECK_INSTANCE (instance)' failed</p> <p>(praat:1364): Gtk-WARNING **: Screen for GtkWindow not set; you must always set a screen for a GtkWindow before using the window</p> <p>(praat:1364): Gdk-CRITICAL **: IA__gdk_screen_get_default_colormap: assertion 'GDK_IS_SCREEN (screen)' failed</p> <p>(praat:1364): Gdk-CRITICAL **: IA__gdk_colormap_get_visual: assertion 'GDK_IS_COLORMAP (colormap)' failed</p> <p>(praat:1364): Gdk-CRITICAL **: IA__gdk_screen_get_default_colormap: assertion 'GDK_IS_SCREEN (screen)' failed</p> <p>(praat:1364): Gdk-CRITICAL **: IA__gdk_screen_get_root_window: assertion 'GDK_IS_SCREEN (screen)' failed</p> <p>(praat:1364): Gdk-CRITICAL **: IA__gdk_screen_get_root_window: assertion 'GDK_IS_SCREEN (screen)' failed</p> <p>(praat:1364): Gdk-CRITICAL **: IA__gdk_window_new: assertion 'GDK_IS_WINDOW (parent)' failed Segmentation fault (core dumped)</p> </blockquote> <p>Please tell me way a that I can run a praat script in remote ubuntu server. </p>115111334903	0	 <p>I guess you are not using server side code. If that is the case, I suggest you to read this short tutorial on Javascript and cookies from w3schools:</p> <p><a href="http://www.w3schools.com/js/js_cookies.asp" rel="nofollow">http://www.w3schools.com/js/js_cookies.asp</a></p>115226632555	0	 <p>I think that instead of build a table of images I would put the first image and I would store the url of the others images ina javascript variable. Then, when you want to load the others images (timer, click event, ...) you just have to change the src parameter of the original image.</p>115339902288	0	Opening a form, closing it, then opening it again in the same location <p>I have a pop up selector for my main form that comes up when I click a button. After I make my selection the box is closed and I continue my work in the main form. However if I go to click that button again, the pop up will appear slightly under where it had opened up previously. Is there a way to fix this so that every time that form is opened it opens in the same spot?</p>11546968494	0	 <p>Perhaps the problem is already at the point where you <code>malloc</code> your <code>data</code>. It gets past around wrong (<code>0x4</code> isn't plausible) so probably you already have had problems there. A common error is to forget to include the header file and have <code>malloc</code> interpreted as returning <code>int</code> per default rules.</p> <p>Casting almost always hides a programming or, worse, design error:</p> <ul> <li>don't cast the return value of <code>malloc</code>. <code>malloc</code> returns <code>void*</code> this is compatible with any other data type pointer</li> <li>don't cast pointers to <code>void*</code> as you do when calling <code>pthread_create</code>. All data type pointers are converted to <code>void*</code> without problems</li> </ul>11553797219	1	object oriented programming basics (python) <p>Level: Beginner</p> <p>In the following code my 'samePoint' function returns False where i am expecting True. Any hints?</p> <pre><code>import math class cPoint: def __init__(self,x,y): self.x = x self.y = y self.radius = math.sqrt(self.x*self.x + self.y*self.y) self.angle = math.atan2(self.y,self.x) def cartesian(self): return (self.x, self.y) def polar(self): return (self.radius, self.angle) class pPoint: def __init__(self,r,a): self.radius = r self.angle = a self.x = r * math.cos(a) self.y = r * math.sin(a) def cartesian(self): return (self.x, self.y) def polar(self): return (self.radius, self.angle) def samePoint(p, q): return (p.cartesian == q.cartesian) &gt;&gt;&gt; p = cPoint(1.0000000000000002, 2.0) &gt;&gt;&gt; q = pPoint(2.23606797749979, 1.1071487177940904) &gt;&gt;&gt; p.cartesian() (1.0000000000000002, 2.0) &gt;&gt;&gt; q.cartesian() (1.0000000000000002, 2.0) &gt;&gt;&gt; samePoint(p, q) False &gt;&gt;&gt; </code></pre> <p>source: MIT OpenCourseWare <a href="http://ocw.mit.edu" rel="nofollow">http://ocw.mit.edu</a> Introduction to Computer Science and Programming Fall 2008</p>11564612798	0	In SQL Server 2008, how do I check if a varchar parameter can be converted to datatype money? <p>I've got a stored procedure I use to insert data from a csv. The data itself is a mix of types, some test, some dates, and some money fields. I need to guarantee that this data gets saved, even if it's formatted wrong, so, I'm saving them all to varchars. Later, once the data's been validated and checked off on, it will be moved to another table with proper datatypes. </p> <p>When I do the insert into the first table, I'd like to do a check that sets a flag (bit column) on the row if it needs attention. For instance, if what should be a money number has letters in it, I need to flag that row and add the column name in an extra errormsg field I've got. I can then use that flag to find and highlight for the users in the interface the fields they need to edit. </p> <p>The date parameters seem to be easy, I can just use <code>IF ISDATE(@mydate) = '0'</code> to test if that parameter could be converted from varchar to datetime. But, I can't seem to find an ISMONEY(), or anything that's remotely equivalent. </p> <p>Does anyone know what to call to test if the contents of a varchar can legitimately be converted to money?</p> <p><strong>EDIT:</strong> I haven't tested it yet, but what do you think of a function like this?:</p> <pre><code>CREATE FUNCTION CheckIsMoney ( @chkCol varchar(512) ) RETURNS bit AS BEGIN -- Declare the return variable here DECLARE @retVal bit SET @chkCol = REPLACE(@chkCol, '$', ''); SET @chkCol = REPLACE(@chkCol, ',', ''); IF (ISNUMERIC(@chkCOl + 'e0') = '1') SET @retVal = '1' ELSE SET @retVal = '0' RETURN @retVal END GO </code></pre> <p><strong>Update</strong></p> <p>Just finished testing the above code, and it works!</p>115727756694	0	 <p>To change from a many-to-many relationship to a one-to-one, start by removing the <code>best_friends</code> table. </p> <pre><code>friends = db.Table('friends', db.Column('user_id', db.Integer, db.ForeignKey('user.id')), db.Column('friend_id', db.Integer, db.ForeignKey('user.id')) ) </code></pre> <p>You then want to add a foreign key to <code>User</code> that references another <code>User</code>. </p> <pre><code>class User(db.Model): id = db.Column(db.Integer, primary_key = True) name = db.Column(db.String(50), index=True, unique= True) email = db.Column(db.String(50),index=True, unique= True) bestfriend_id = db.Column(db.Integer, db.ForeignKey('user.id')) bestfriend = db.relationship('User', remote_side=['id'], lazy='dynamic') def are_bestfriends(self, user): return self.best_friend == user def be_bestfriend(self, user): if not self.are_bestfriends(user): self.bestfriend = user user.bestfriend = self return self </code></pre>115812452961	0	How to get city code weather in AccuWeather? <p>Have someone ever use AccuWeather to search your country weather? I want to get my city weather code in AccuWeather who can help me? The code generate has form like this: EUR|DE|GM014|TORGAU. I can't find my city code (Phnom Penh, Cambodia)</p>115925054125	0	ASP MVC / EF6 - Automatic logging <p>Every table of my database has got 2 columns at the end, which allows logging (User who made the action, and Date of the action). <strong>EDIT :</strong> I use Code-First migrations.<br/> So I would like those two logging columns to be filled automatically :</p> <ol> <li><p>Each time I insert a new entry in my table (using DbContext.[Model].Add(entry))</p></li> <li><p><strong>OR</strong> each time I do a DbContext.SaveChanges() action</p></li> </ol> <p><br /></p> <p><strong>I have considered overriding the DbContext.SaveChanges() method</strong>, but it didn't work out...<br /></p> <p><strong>I have also tried overriding the DbSet Add() method</strong>, to do the log filling action there. For that I have created a CustomDbSet class which inherits from DbSet :</p> <pre><code>public class CustomDbSet&lt;TEntity&gt; : DbSet&lt;TEntity&gt; where TEntity : class { public TEntity Add(TEntity entity) { //Do logging action here return base.Add(entity); } } </code></pre> <p><strong>But this didn't make it neither.</strong> <br /> <strong>EDIT :</strong> What happens with this CustomDbSet is that any DbContext.[Model] returns null, now (instead of being filled with the content of the database table)<br /><br /> I already have the extension method which will do the logging action, but I don't know where to put it so logging would become an "automatic" action..</p> <pre><code>public static void EntityLogCreate&lt;T&gt;(this T model, string userName) where T : LogColumns { model.Create_User = userName; model.Create_Date = DateTime.Now; } </code></pre> <p>Any idea to achieve that ?</p>11601514725	0	 <p>Usually when I have come across this it has been a fatal error in PHP somewhere. Have a look at your PHP-cgi log to see if it is in there. There should be something in the nginx log like this: <code>104: Connection reset by peer</code>. Depending on your setup this <em>(sorry, link dead)</em> might help but if you're using <a href="http://php-fpm.org/" rel="nofollow noreferrer">php-fpm</a> it won't.</p>116113046854	0	jQuery on() method is firing more than one time <p>I made some jQuery code for preventing users from typing chars but only numbers:</p> <pre><code> $("div").on("keydown", ":text", checkKey); function checkKey(e) { var n = e.keyCode; if (n == 13) { $(this).closest("form").submit(); console.log('enter'); } else if (e.shiftKey || e.ctrlKey || e.altKey) { e.preventDefault(); } else { if (!((n == 8) || (n == 46) || (n == 9) || (n &gt;= 35 &amp;&amp; n &lt;= 40) || (n &gt;= 48 &amp;&amp; n &lt;= 57) || (n &gt;= 96 &amp;&amp; n &lt;= 105)) ) { e.preventDefault(); console.log('ok'); } } } </code></pre> <p>end in html:</p> <pre><code> &lt;div&gt; &lt;input type="text" id="test" /&gt; &lt;/div&gt; </code></pre> <p>but whenever I type something, it seems it's being fired three times for example for one pressing enter I get three 'enter' in console and for numbers I get three 'ok', why is that? I also replaced it with delegate and live, live worked fine but delegate also was fired three times. thanks. </p>116222503882	0	What does the read call return on earth if there are already both FIN and RST in the TCP buffer? <p>Assuming that the client and server send packets according to the order of sequence as shown in the figure, the client does not know FIN has arrived. </p> <p>It sends “hello again” to the server, the server responds to the client with an RST and the RST has arrived. Then if the client is blocking on a read, why it return 0 due to the FIN instead of -1 because the RST? In the 《Effective TCP/IP programming》, it tells us that the core will return ECONNRESET error. </p> <p>My operating system is Ubuntu 12.10. Is it related with the operating system? Please tell me some TCP’s details on this implementation. Thanks in advance.</p> <p><img src="https://i.stack.imgur.com/qcGY7.jpg" alt="enter image description here"></p>116325872507	0	Give user input for batch file via c# code <p>I have a batch file which is asking for some user input text in the middle of that process. I need to run this batch file through c# code. I cannot change the bat file. So the option having command line arguments also is not working for me. Is there any way that i can provide the input when it prompts? </p>116412585443	0	 <p>Use <code>mysql_fetch_row()</code>to get the $amount_data.Mysql_query() returns only the resouce id</p> <pre><code>$amount_data = mysql_query ("SELECT * FROM subscriber WHERE payment_amount = '$payment_amount' AND id = '$id' "); $row = mysql_fetch_row($amount_data); echo $row[0]; </code></pre> <p>Check the link <a href="http://php.net/manual/en/function.mysql-fetch-row.php" rel="nofollow">http://php.net/manual/en/function.mysql-fetch-row.php</a></p>11652791931	1	Speed vs security vs compatibility over methods to do string concatenation in Python <p><a href="http://stackoverflow.com/questions/1225637/python-string-formatting">Similar</a> questions <a href="http://stackoverflow.com/questions/376461/string-concatenation-vs-string-substitution-in-python/376508#376508">have been brought</a> (good speed comparison there) on this same <a href="http://en.wikipedia.org/wiki/Concatenation" rel="nofollow noreferrer">subject</a>. Hopefully this question is different and updated to Python <em>2.6</em> and <em>3.0</em>.</p> <p>So far I believe the faster and most compatible method (among different Python versions) is the plain simple <code>+</code> sign:</p> <pre><code>text = "whatever" + " you " + SAY </code></pre> <p>But I keep hearing and reading it's not secure and / or advisable.</p> <p>I'm not even sure how many methods are there to manipulate strings! I could count only about 4: There's <a href="http://en.wikipedia.org/wiki/Variable_interpolation#Interpolation" rel="nofollow noreferrer">interpolation</a> and all its sub-options such as <code>%</code> and <code>format</code> and then there's the simple ones, <code>join</code> and <code>+</code>.</p> <p>Finally, the <a href="http://docs.python.org/release/3.0.1/whatsnew/3.0.html#pep-3101-a-new-approach-to-string-formatting" rel="nofollow noreferrer">new approach to string formatting</a>, which is with <code>format</code>, is certainly not good for backwards compatibility at same time making <code>%</code> not good for forward compatibility. But should it be used for every string manipulation, including every concatenation, whenever we restrict ourselves to 3.x only?</p> <p>Well, maybe this is more of a wiki than a question, but I do wish to have an answer on <strong>which is the proper usage of each string manipulation method</strong>. And which one could be generally used with each focus in mind (best all around for compatibility, for speed and for security).</p> <p>Thanks.</p> <p>edit: I'm not sure I should accept an answer if I don't feel it really answers the question... But my point is that all them 3 together do a proper job.</p> <p>Daniel's most voted answer is actually the one I'd prefer for accepting, if not for the "note". I highly disagree with <em>"concatenation is strictly using the + operator to concatenate strings"</em> because, for one, <code>join</code> does string concatenation as well, and we can build any arbitrary library for that.</p> <p><strong>All current 3 answers are valuable</strong> and I'd rather having some answer mixing them all. While nobody volunteer to do that, I guess by choosing the one less voted (but fairly broader than THC4k's, which is more like a large and very welcomed comment) I can draw attention to the others as well.</p>116631377154	0	 <p>Expand the size of your <code>q1</code> buffer. <code>scanf("%s", q1)</code> doesn't have enough room to store the input. Remember that C uses a null character <code>'\0'</code> to terminate strings. If you don't account for that, the buffer could overrun into other memory causing <a href="https://en.wikipedia.org/wiki/Undefined_behavior" rel="nofollow">undefined behavior</a>. In this instance, it's probably overwriting memory allocated to <code>name</code>, so <code>name</code> ends up pointing to "\0ick". This causes <code>printf(%s)</code>, which looks for <code>'\0'</code> to know when to stop printing, to think that the string is shorter than it really is.</p> <p>The code works perfectly if you expand the buffer:</p> <pre><code>#include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; #include &lt;string.h&gt; int main(void) { char name[50]; char q1[50]; printf( " What is your name?\n"); scanf("%49s", name); printf( " Hi %s, Do you want to have some fun? [Y/N]\n",name); scanf("%49s",q1); if(strcmp(q1,"Y") == 0||strcmp(q1,"y")==0) { printf("Awesome, let's play!\n"); } else { printf("Fine"); } printf( "So %s, it's time to get started\n", name); getchar(); return 0; } </code></pre> <p>Output:</p> <pre><code> What is your name? Nick Hi Nick, Do you want to have some fun? [Y/N] y Awesome, let's play! So Nick, it's time to get started </code></pre> <p>Note that I've added the qualifier <code>%49s</code> to avoid buffer overruns like this.</p> <hr> <p>You could also circumvent the need for another string entirely by changing <code>char q1[50]</code> and <code>scanf("%49s")</code> to simply <code>char q1</code> and <code>scanf("%c%*c", &amp;q1)</code> (note the "address of" operator because <code>q1</code> is no longer a pointer).</p> <p>You'll probably even get a performance gain from this (albeit small), because strings are notorious memory hoggers. Comparing a single character is usually preferred over comparing strings.</p> <pre><code>#include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; #include &lt;string.h&gt; int main(void) { char name[50]; char q1; printf( " What is your name?\n"); scanf("%49s%*c", name); printf( " Hi %s, Do you want to have some fun? [Y/N]\n",name); scanf("%c%*c",&amp;q1); if(q1 == 'Y' || q1 == 'y') { printf("Awesome, let's play!\n"); } else { printf("Fine"); } printf( "So %s, it's time to get started\n", name); getchar(); return 0; } if(q1 == 'Y' || q1 == 'y') { printf("Awesome, let's play!\n"); } else { printf("Fine"); } printf( "So %s, it's time to get started\n", name); getchar(); return 0; } </code></pre> <p>If you go this route, you have to ignore the enter key using the format specifier <code>%*c</code> because pressing enter sends a key to the stream as well.</p>11676224276	0	Problem comparing extremes <p>I'm trying to sort trough a list of 32-bit numbers using MIPS assembler and <a href="http://en.wikipedia.org/wiki/SPIM" rel="nofollow">xspim</a>. I've been stepping trough my code to see what fails and noticed that when comparing 0x00000000 with 0xFFFFFFFF it doesn't switch those numbers as it should. At the point where the program fails I got 0x00000000 in $t3 and 0xFFFFFFFF in $t4 and it looks like this.</p> <p><code>bge $t3,$t4,lol</code> #So if <code>t3</code> is greater than or equal I should jump forward else continue. Now the problem is that the program jumps even though <code>t3</code> is smaller.</p>116828739363	0	 <p>I'm not sure where you quoted that from, it doesn't appear in the documentation at all. To actually quote from the <a href="https://msdn.microsoft.com/library/bb359438%28v=vs.110%29.aspx" rel="nofollow">documentation</a>:</p> <blockquote> <p>The <code>HashSet&lt;T&gt;</code> class is based on the model of mathematical sets and provides high-performance set operations similar to accessing the keys of the <code>Dictionary&lt;TKey, TValue&gt;</code> or <code>Hashtable</code> collections. In simple terms, the <code>HashSet&lt;T&gt;</code> class can be thought of as a <code>Dictionary&lt;TKey, TValue&gt;</code> collection without values.</p> </blockquote> <p>So it is a collection, containing actual values. The sentence you quoted there is false.</p> <p>That being said, you <em>could</em> create an <code>ISet&lt;T&gt;</code> implementation that works that way, e.g. representing numbers in a set as ranges. But trying to do that with a vanilla <code>HashSet&lt;T&gt;</code> will quickly break down.</p>116931699416	0	 <p>Use an initializer parameter:</p> <pre><code>static char calc_crc(char init, unsigned char *data, unsigned len) { for ( int i = 0 ; i &lt; len; i++ ) init = init ^ data[i]; return init; } </code></pre> <p>Then you can do result=calc_crc(calc_crc(0,buffer1,buffer1len), buffer2, buffer2len);</p>117017294712	0	 <p>I can't quite make out what you're trying to say. Are the folders still empty, or is there content in them now?</p> <p>Git doesn't track folders, it only tracks files. So you can't add an empty folder into the Git repo, if that's what you're trying to do. If you really want the directory there, the standard practice is to add an empty <code>.gitkeep</code> file into it, so that Git has some content to track there. Then you would <code>git add foldername</code> and commit it.</p>117120225904	0	 <p>Have a look at the documentation on the website but pretty sure it should be like below:</p> <pre><code>has_attached_file :avatar, :styles =&gt; { :thumb =&gt; ["32x32#", :png] } </code></pre> <p><a href="https://github.com/thoughtbot/paperclip" rel="nofollow">https://github.com/thoughtbot/paperclip</a></p> <p>Under post processing</p> <p>Guess your issue is here:</p> <pre><code>@format = options[:format] @basename = File.basename(@file.path, @current_format) temp_file = Tempfile.new([@basename, @format].compact.join(".")) </code></pre>117233630716	0	 <p>You installed a <code>jquery</code> module as global module.</p> <h2>Loading local modules</h2> <p>If the module identifier passed to <code>require()</code> is not a native module (e.g. <code>http</code>), and does not begin with '/', '../', or './', then <code>Node.js</code> starts at the parent directory of the current module, and adds <code>/node_modules</code>, and attempts to load the module from that location.</p> <p>If it is not found there, then it moves to the parent directory, and so on, until the root of the file system is reached.</p> <h2>Loading global modules</h2> <p>To make global modules available to the Node.js (and CoffeeScript) REPL, it might be useful to also add the <code>/usr/lib/node_modules</code> folder to the <code>$NODE_PATH</code> environment variable. Since the module lookups using node_modules folders are all relative, and based on the real path of the files making the calls to <code>require()</code>, the packages themselves can be anywhere.</p>11731303660	0	 <p>Tough to answer without knowing more. Drupal is not very strong if all you're doing is building [x], where [x] is an online store, blog, forum, rss aggregation site, etc. We recently retooled our company store in Drupal using the Ubercart plugin suite, though, and were able to exercise a lot of control over the final results -- and more importantly, intgrate it better with the rest of our site's content.</p> <p>That's where the real win is -- if you have lots of existing content and/or community, and you want that integrated smoothly with your store. We can do things like auto-suggest products from the store that match the tags on the articles a user is reading, give people access to private forums on our main site based on purchases they make in the store, etc.</p> <p>If you aren't already an old hand with Drupal, and you don't need that kind of connection, it's probably better to go with a dedicated solution.</p> <p>(Random notes: <a href="http://www.lullabot.com/blog/our-new-%C3%BCbercart-based-store" rel="nofollow noreferrer">Article about putting up the store</a>, <a href="http://www.lullabot.com/audiocast/podcast-76-ubercart-and-building-lullabot-store" rel="nofollow noreferrer">podcast about same</a>)</p>11746681159	0	 <p>Instead of messing about with <code>errorformat</code>, just set <code>cscopequickfix</code> and use the normal <code>:cscope</code> commands. eg. (from vim help)</p> <pre><code>:set cscopequickfix=s-,c-,d-,i-,t-,e- </code></pre> <p>Edit</p> <p>You could also use a filter like the following to reorder the fields</p> <pre><code>sed -e 's/^\([^ ]\+\) \([^ ]\+\) \([^ ]\+\) \(.*\)$/\1 \3 \4 inside \2/' </code></pre> <p>set it to filter your message, then use the <code>efm</code></p> <pre><code>errorformat=%f\ %l\ %m </code></pre>11754693000	0	 <p>Your problem is the space after <code>CMD=</code>. This evaluates to <code>CMD=&lt;empty string&gt; "git --version"</code>. First, the environment variable <code>CMD</code> is set to an empty string, then the command <code>git --version</code> is called. Notice that due to the <code>"..."</code> the shell really tries to execute a command <code>git --version</code> and not <code>git</code> with argument <code>--version</code>. Simple remove the space between <code>=</code> and <code>"</code> to fix this.</p>11763043018	0	 <p>Since CMIS was approved as a standard last month, the new best way to achieve this is probably via CMIS, as explained <a href="http://www.liferay.com/web/jonas.yuan/blog/-/blogs/integrating-alfresco-through-cmis-in-liferay" rel="nofollow noreferrer">here</a>.</p>117710330814	0	 <p>Use REST; REST is nothing more than using plain HTTP 'better'. Since you are already using HTTP, somehow you are already doing REST like calls and moving these calls to full fledged REST will be easy.</p> <p>Implementing REST calls is easy. You have two approaches: </p> <ul> <li>Low end: using URLConnection objects on the client, servlets on the server and following some REST conventions on using HTTP methods and 'clean' URLs (see <a href="http://en.wikipedia.org/wiki/Clean_URL" rel="nofollow">here</a>). Advantage is that you need no 3rd party library and minimize the footprint. Maintenance and evolutions are harder though.</li> <li>High-end: a framework and specifications like JAX-RS. Using <a href="http://www.restlet.org/" rel="nofollow">Restlet</a> you can be up in running with a REST server in a couple of hours without having to deploy a servlet container.</li> </ul> <p>Don't use SOAP. The only reason you would want to use SOAP is that you want to contractualise using a WSDL what you are exposing (you can do the same with REST btw, see the Amazon documentation for instance). Trust me, SOAP is way too heavy and confusing for what you are trying to do.</p>117834693184	0	 <blockquote> <p>Do I need to include ;WITH CTE_Backup AS at the beginning of the query when I use it in Java code?</p> </blockquote> <p>Yes you should, otherwise use simple subquery:</p> <pre><code>SELECT D.name ,ISNULL(CONVERT(VARCHAR,backup_start_date),'No backups') AS last_backup_time ,D.recovery_model_desc ,state_desc, CASE WHEN type ='D' THEN 'Full database' WHEN type ='I' THEN 'Differential database' WHEN type ='L' THEN 'Log' WHEN type ='F' THEN 'File or filegroup' WHEN type ='G' THEN 'Differential file' WHEN type ='P' THEN 'Partial' WHEN type ='Q' THEN 'Differential partial' ELSE 'Unknown' END AS backup_type ,physical_device_name FROM sys.databases D LEFT JOIN ( SELECT database_name,backup_start_date,type,physical_device_name ,Row_Number() OVER(PARTITION BY database_name,BS.type ORDER BY backup_start_date DESC) AS RowNum FROM msdb..backupset BS JOIN msdb.dbo.backupmediafamily BMF ON BS.media_set_id=BMF.media_set_id ) AS CTE ON D.name = CTE.database_name AND RowNum = 1 ORDER BY D.name,type; </code></pre> <p><a href="https://msdn.microsoft.com/en-us/library/ms175972.aspx" rel="nofollow">Common Table Expression</a> is nice readable way to introduce derived tables.</p>117914462559	0	 <p>One solution is to translate the mesh geometry, and compensate by changing the mesh position, like so:</p> <pre><code>var offset = objMesh.centroid.clone(); objMesh.geometry.applyMatrix(new THREE.Matrix4().makeTranslation( -offset.x, -offset.y, -offset.z ) ); objMesh.position.copy( objMesh.centroid ); </code></pre> <p>updated fiddle: <a href="http://jsfiddle.net/Ldt7z/165/" rel="nofollow">http://jsfiddle.net/Ldt7z/165/</a></p> <p>P.S. You do not need to save your fiddle before running it. There is no reason to have so many versions.</p> <p>three.js r.55</p>118036542725	0	 <p><a href="http://stackoverflow.com/a/31309657/2593751">Niknam ansuwer</a> is perfect and I want to add if you use tor just add in your environment </p> <pre><code>export _JAVA_OPTIONS="-DsocksProxyHost=127.0.0.1 -DsocksProxyPort=9050" </code></pre>11812651470	0	 <p>The most common path is to include a licensing notice at the top of files inside block comments - that's the way most likely to ensure that anyone utilizing the code is aware of the license, since the only possible way for it to be decoupled from the code is someone intentionally removing it.</p>118231319822	0	Modal is coming back undefined in directive <p>Google is giving me the error: "TypeError: Cannot read property 'open' of undefined" in response to my ui-bootstrap module. I've been using other ui-bootsrap directives fine. </p> <p>Am I not declaring the modal dependency correctly?</p> <pre><code>angular.module('ireg').directive('study', function (studyFactory) { return { restrict:'E', scope: { objectid:'@objectid' }, templateUrl: '/ireg/components/study/study.html', link: function (scope, element, attrs, $modal) { scope.openMilestonesDialog = function () { var modalInstance = $modal.open({ animation: $scope.animationsEnabled, templateUrl: '/ireg/components/add-milestones/addMilestonesDialog.html', controller: '/ireg/components/add-milestones/addMilestonesDialogController.js', size: lg }); }; }//end of link } }); angular.module('ireg').controller('addMilestonesDialogController', function ($scope, $modalInstance, studyId) { $scope.ok = function () { $modalInstance.close(); }; }); </code></pre>118334939698	0	 <p>out.println () is a little ugly in terms of readability - but the cost of these calls will be small compared to I/O times.</p> <p>Using + for String concatenation inside your loop might harm your memory footprint (and it's not the fastest way either). Consider this line you have:</p> <pre><code> out.println("&lt;td&gt;"+ rs.getString("FirstName") + " " + rs.getString("LastName") + "&lt;/td&gt;"); </code></pre> <p>You could gain readability and speed and have less char [] left to be garbage collected by coding with <code>format()</code>:</p> <pre><code> out.format ("&lt;td&gt;%s %s&lt;/td&gt;", rs.getString ("FirstName"), rs.getString ("LastName")); </code></pre> <p><strong>More Notes</strong></p> <p>You create and connect a new database connection every time your servlet is called. This will severly impact your performance and scalability. You should consider using a connection pool from which you fetch pre-connected Connections. The performance you gain will make up for very many String concats or println calls.</p>11843186544	0	iOS4 and audio playback during backgrounding <p>When my app is backgrounded, the audioplayer continues to play, but i cant hear any sound. When i open my app again, it plays from the point where it would have been had the app not been backgrounded at all. This shows that the app is playing in the background though it is not audible. Why could this be happening?</p> <p>I have set the audio key in the info.plist for the UIBackgroundModes array. Also my audioplayer is set to the "AVAudioSessionCategoryPlayback" category with an override to allow for audio mixing. So what am i doing wrong that im unable to hear the audio even though it is playing in the background?</p> <p>Could this be an issue with the simulator alone as i have not been able to test this on a device with iOS4 so iv only been testing it on the simulator.</p>11852633115	0	Java GUI File Menu <p>I have a GUI with a Menu named file</p> <p>how do I Add a file open and close function to the program. If the program is in the encrypting mode, it should load/save the cleartext text area. If the program is in decrypting mode, it should load/save the ciphertext area.</p>118640014705	0	How to convert a “String” value to “Type” in Angular 2 TS <p>This is my current object, Home refers to my import </p> <pre><code>import { Home } from '../home/home'; arr = [ { name: "Home", root: "Home", icon: "calc" } ]; </code></pre> <p>This is what i want to achieve:</p> <pre><code> import { Home } from '../home/home'; arr = [ { name: "Home", root: Home, icon: "calc" } ]; </code></pre> <p>Im getting a error because "Home" is a string. eval() works but i'm looking for a alternative</p> <p>Working code:</p> <pre><code> for (var i = 0; i &lt; arr.length; i++) { arr[i].root = eval(arr[i].root); } </code></pre>118713516947	0	how to make a connection to datastore inside jstl tags <p>I'm making a project on Google App Engine and in one of my jsp files, I want to search an entry in my datastore. I normally do this search by clicking on a button on this jsp page, then I make the connection to datastore in a servlet and then I send the query results to jsp back . Well, I want to query datastore without clicking this button. When I load the page, I want to see the query results on my page. When I was using EL tag lib, I could do that by just typing &lt;% %>, now I'm using jstl tag lib. So is there any way to do ? After using jstl tags, I'm not able to use EL tags.</p>118826092740	0	 <p><code>System.out.println((int)(5.4%((int)5.4)*10));</code></p> <p>Basically <code>5.4 mod 5</code> gets you <code>.4 * 10</code> gets you <code>4</code>.</p>11896604248	0	Unit test which requires a file in Request.Files <p>I'm writing a unit test and the piece of code its testing requires that a file be in Request.Files.</p> <p>In my controller I'm calling something called <code>AddDocument(file)</code> and the file is taken from Request.Files.</p> <p>How do you achieve unit testing this? Isn't the Request only available in the controller?</p>119029722509	0	Foreach loop - three columns(dynamic) table layout <p>i have the below code, which will create a table with three columns.</p> <pre><code>&lt;?php $t = array(' 1 ' , ' 2 ' ,' 3 ', ' 4 ' , ' 5 '); $count = 0; $col =3; echo '&lt;table&gt;&lt;tr&gt;'; foreach($t AS $r){ $count++; echo '&lt;td&gt; '.$r.' &lt;/td&gt;'; if($count == $col){ echo '&lt;/tr&gt;&lt;tr&gt;'; $count = 0; } } echo '&lt;/tr&gt;&lt;/table&gt;'; ?&gt; </code></pre> <p>but what i really want is for the first column to have at least 4 rows before creating a new column and so on. max number of columns is 3 and each column should have at least 4 rows.</p>119110580465	0	How can I populate Viewmodel list collection <p>How can I populate list collection in ViewModel</p> <p>Controller:</p> <pre><code> SchoolEntities db = new SchoolEntities(); public ActionResult Index() { var student= from s in db.Students select s.Name.ToList(); return View(); } </code></pre> <p>ModelView:</p> <pre><code> public List&lt;Student&gt;students { get; set;} </code></pre>119223015705	0	 <p>Try this....</p> <pre><code>ScriptManager.RegisterStartupScript(this, this.GetType(), "onclick", "javascript:window.open( 'SomePage.aspx','_blank','height=600px,width=600px,scrollbars=1');", true); </code></pre>11939039733	0	 <p>I believe it's working the way it's supposed to. If you want arrivingLabelRed to end with it's alpha at 0 you should set it that way in the completion block.</p>119420014967	0	How can remove white screen when page changes one to another page? <p>I have done my application in iphone using phonegap and jquery mobile. It is major project and it is totally completed. But there is one problem , in application pages load using rel="external" , when page changes one to another page in between 2 to 3 seconds screen display totaly white, that time don't want to display white screen. Anybody idea what can we do for that ? and don't reply with remove rel="external". </p>11959626322	0	Apache + NginX reverse proxy: serving static and proxy files within nested URLs <p>I have Apache running on my server on port 8080 with NginX running as a reserve proxy on port 80. I am attempting to get NginX to serve static HTML files for specific URLs. I am struggling to write the NginX configuration that does this. I have conflicting directives as my URLs are nested within each other.</p> <p>Here's what I want to have:</p> <ul> <li><p>One URL is at <code>/example/</code> and I want NginX to serve a static HTML file located on my server at <code>/path/to/www/example-content.html</code> instead of letting Apache serve the page to NginX.</p></li> <li><p>Another URL is at <code>/example/images/</code> and I want Apache to serve that page to NginX, just as it does for the rest of the site.</p></li> </ul> <p>I have set up my nginx.conf file like this:</p> <pre><code>server { listen 80; server_name localhost; # etc... location / { proxy_pass http://127.0.0.1:8080/; } # etc... </code></pre> <p>My attempt to serve the static file at <code>/example/</code> from NginX went like this:</p> <pre><code> location /example/ { alias /path/to/www/; index example-content.html; } </code></pre> <p>This works, but it means everything after the <code>/example/</code> URL (such as <code>/example/images/</code>) is aliased to that local path also.</p> <p>I would like to use regex instead but I've not found a way to serve up the file specifically, only the folder. What I want to be able to say is something like this:</p> <pre><code> location ~ ^/example/$ { alias /path/to/www/example-content.html; } </code></pre> <p>This specifically matches the <code>/example/</code> folder, but using a filename like that is invalid syntax. Using the explicit <code>location = /example/</code> in any case doesn't work either.</p> <p>If I write this:</p> <pre><code> location ~ ^/example/$ { alias /path/to/www/; index example-content.html; } location ~ /example/(.+) { alias /path/to/www/$1; } </code></pre> <p>The second directive attempts to undo the damage of the first directive, but it ends up overriding the first directive and it fails to serve up the static file.</p> <p>So I'm at a bit of a loss. Any advice at all extremely welcome! Many thanks.</p>119633573673	0	Hiding flyout of a button <p>I got my <em>DataTemplate</em> for items and within this <em>DataTemplate</em> I have such code:</p> <pre><code>&lt;Button x:Name="DoneButton" Style="{StaticResource ButtonStyle1}" BorderThickness="1" Margin="0,0,20,0" HorizontalAlignment="Left" VerticalAlignment="Center" Grid.Column="2" Grid.Row="1" Width="50" Height="50" &gt; &lt;Image Source="Images/WPIcons/checked.png" Width="30" Height="30" Margin="-10,0,-10,0" /&gt; &lt;Button.Flyout&gt; &lt;Flyout x:Name="myFly"&gt; &lt;Grid Margin="10"&gt; &lt;Grid.RowDefinitions&gt; &lt;RowDefinition Height="Auto" /&gt; &lt;RowDefinition Height="Auto" /&gt; &lt;RowDefinition Height="Auto" /&gt; &lt;/Grid.RowDefinitions&gt; &lt;TextBlock Grid.Row="0" x:Uid="myNote" Text="Note: " Style="{StaticResource myText}" /&gt; &lt;TextBox Grid.Row="1" TextWrapping="Wrap" AcceptsReturn="True" Height="40" x:Name="note" Text="{Binding RecentNote, Mode=TwoWay}" Style="{StaticResource TextBoxStyle1}"/&gt; &lt;Button x:Name="CompletedButton" Command="{Binding CompletedCommand}" CommandParameter="{Binding}" Style="{StaticResource ButtonStyle1}" BorderThickness="1" HorizontalAlignment="Left" VerticalAlignment="Center" Grid.Row="2" Click="CompletedButton_Click" Content="Done" MinWidth="80" Height="40" /&gt; &lt;/Grid&gt; &lt;/Flyout&gt; &lt;/Button.Flyout&gt; &lt;/Button&gt; </code></pre> <p>After the flyout for the item has been called and user put his data in it I want to hide this flyout as soon as user hits the "Done" button (<strong><em>x:Name="CompletedButton"</em></strong>).</p> <p>I tried to do that in code behind like:</p> <pre><code>private void CompletedButton_Click(object sender, RoutedEventArgs e) { Button button = (Button)sender; Grid grid = (Grid)VisualTreeHelper.GetParent(button); Flyout fly = (Flyout)VisualTreeHelper.GetParent(grid); fly.Hide(); } </code></pre> <p>But I get cast exception with that I can't cast <em>ContentPresenter</em> to <em>Flyout</em> so I guess it's not the way I look for. How I can hide this flyout?</p>119722359144	0	 <p>use <code>[[NSDate date] timeIntervalSince1970]</code></p>11984482058	0	 <p>The keyword DISTINCT is used to eliminate duplicate rows from a query result:</p> <pre><code>SELECT DISTINCT ... FROM A JOIN B ON ... </code></pre> <p>However, you can sometimes (possibly even 'often', but not always) avoid the need for it if the tables are organized correctly and you are joining correctly.</p> <p>To get more information, you are going to have to ask your question more clearly, with concrete examples.</p>119936864836	0	How to register a post type and taxonomy in WordPress and display in a page/single post <p>I have a question about WordPress register post type:</p> <p>How can I register a post type like <code>portfolio</code>? </p> <p>For example: In the WordPress dashboard, I can register a post type and taxonomy. After this I want to create a page to display all the portfolio and taxonomies like (portfolio.php) and display a single portfolio in a (single-portfolio.php). </p> <p>Can someone explain this for me please?</p>12004254487	0	 <p>Try setting up a view in the DB that applies the security filter to the records as needed, and then when retrieving records through L2S. This will ensure that the records that you need will not be returned.</p> <p>Alternatively, add a .Where() to the query before it is submitted that will apply the security filter. This will allow you to apply the filter programmatically (in case it needs to change based on the scenario).</p>

Showing the first 1,200 of 7466 lines. Download the file for the rest.