id
int64
4
73.8M
title
stringlengths
10
150
body
stringlengths
17
50.8k
accepted_answer_id
int64
7
73.8M
answer_count
int64
1
182
comment_count
int64
0
89
community_owned_date
stringlengths
23
27
creation_date
stringlengths
23
27
favorite_count
int64
0
11.6k
last_activity_date
stringlengths
23
27
last_edit_date
stringlengths
23
27
last_editor_display_name
stringlengths
2
29
last_editor_user_id
int64
-1
20M
owner_display_name
stringlengths
1
29
owner_user_id
int64
1
20M
parent_id
null
post_type_id
int64
1
1
score
int64
-146
26.6k
tags
stringlengths
1
125
view_count
int64
122
11.6M
answer_body
stringlengths
19
51k
16,957,275
Python to JSON Serialization fails on Decimal
<p>I have a python object which includes some decimals. This is causing the json.dumps() to break.</p> <p>I got the following solution from SO (e.g. <a href="https://stackoverflow.com/questions/1960516/python-json-serialize-a-decimal-object">Python JSON serialize a Decimal object</a>) but the recoomended solution still does not work. Python website - has the exact same answer.</p> <p>Any suggestions how to make this work?</p> <p>Thanks. Below is my code. It looks like the dumps() doesn't even go into the specialized encoder.</p> <pre><code>clayton@mserver:~/python&gt; cat test1.py import json, decimal class DecimalEncoder(json.JSONEncoder): def _iterencode(self, o, markers=None): print "here we go o is a == ", type(o) if isinstance(o, decimal.Decimal): print "woohoo! got a decimal" return (str(o) for o in [o]) return super(DecimalEncoder, self)._iterencode(o, markers) z = json.dumps( {'x': decimal.Decimal('5.5')}, cls=DecimalEncoder ) print z clayton@mserver:~/python&gt; python test1.py Traceback (most recent call last): File "test1.py", line 11, in &lt;module&gt; z = json.dumps( {'x': decimal.Decimal('5.5')}, cls=DecimalEncoder ) File "/home/clayton/python/Python-2.7.3/lib/python2.7/json/__init__.py", line 238, in dumps **kw).encode(obj) File "/home/clayton/python/Python-2.7.3/lib/python2.7/json/encoder.py", line 201, in encode chunks = self.iterencode(o, _one_shot=True) File "/home/clayton/python/Python-2.7.3/lib/python2.7/json/encoder.py", line 264, in iterencode return _iterencode(o, 0) File "/home/clayton/python/Python-2.7.3/lib/python2.7/json/encoder.py", line 178, in default raise TypeError(repr(o) + " is not JSON serializable") TypeError: Decimal('5.5') is not JSON serializable clayton@mserver:~/python&gt; </code></pre>
16,957,370
3
2
null
2013-06-06 08:32:15.793 UTC
8
2017-08-15 09:24:47.83 UTC
2017-08-15 09:24:47.83 UTC
null
100,297
null
1,397,919
null
1
35
python|json|decimal
53,435
<p>It is not (no longer) recommended you create a subclass; the <code>json.dump()</code> and <code>json.dumps()</code> functions take a <code>default</code> function:</p> <pre><code>def decimal_default(obj): if isinstance(obj, decimal.Decimal): return float(obj) raise TypeError json.dumps({'x': decimal.Decimal('5.5')}, default=decimal_default) </code></pre> <p>Demo:</p> <pre><code>&gt;&gt;&gt; def decimal_default(obj): ... if isinstance(obj, decimal.Decimal): ... return float(obj) ... raise TypeError ... &gt;&gt;&gt; json.dumps({'x': decimal.Decimal('5.5')}, default=decimal_default) '{"x": 5.5}' </code></pre> <p>The code you found only worked on Python 2.6 and overrides a private method that is no longer called in later versions.</p>
16,627,751
Building with Lombok's @Slf4j and Eclipse: Cannot find symbol log
<p>I have the lombok plugin in Eclipse and enabled annotation processing in Eclipse under java compiler, but still it is unable to recognize the log statements when I use @Slf4j annotation. </p> <p>Do we have to make any other settings? </p>
16,730,520
5
5
null
2013-05-18 18:46:15.433 UTC
2
2020-08-08 13:24:18.06 UTC
2013-05-24 08:17:43.667 UTC
null
12,634
null
2,022,957
null
1
37
eclipse|slf4j|lombok
78,995
<p>You also have to install Lombok into Eclipse. </p> <p>See also <a href="https://stackoverflow.com/questions/3418865/cannot-make-project-lombok-work-on-eclipse-helios/3425327#3425327">this answer</a> on how to do that or check if Lombok is installed correctly.</p> <p>Full Disclosure: I am one of the <a href="http://projectlombok.org" rel="noreferrer">Project Lombok</a> developers.</p>
16,916,903
MongoDB performance - having multiple databases
<p>Our application needs 5 collections in a db. When we add clients to our application we would like to maintain separate db for each customer. For example, if we have 500 customers, we would have 500 dbs and 2500 collections (each db has 5 collection). This way we can separate each customer data. My concern is, will it lead to any performance problems?</p> <blockquote> <p><strong>UPDATE:</strong> Also follow this <a href="https://groups.google.com/forum/?fromgroups#!starred/mongodb-user/UBkJKoeM6Tw" rel="noreferrer">google-group discussion</a>.</p> </blockquote>
16,928,992
1
2
null
2013-06-04 11:41:59.867 UTC
16
2017-08-01 12:10:48.9 UTC
2017-09-22 17:57:57.377 UTC
null
-1
null
1,280,221
null
1
41
mongodb|database
25,345
<blockquote> <p>Our application needs 5 collections in a db. When we add clients to our application we would like to maintain separate db for each customer. For example, if we have 500 customers, we would have 500 dbs and 2500 collections (each db has 5 collection). This way we can separate each customer data.</p> </blockquote> <p>That's a great idea. On top of logical separation this will provide for you, you will also be able to use database level security in MongoDB to help prevent inadvertent access to other customers' data.</p> <blockquote> <p>My concern is, will it lead to any performance problems?</p> </blockquote> <p>No, and in fact it will help as with database level lock extremely heavy lock contention for one customer (if that's possible in your scenario) would not affect performance for another customer (it still might if they are competing for the same I/O bandwidth but if you use --directoryperdb option then you have the ability to place those DBs on separate physical devices.</p> <p>Sharding will also allow easy scaling as you won't even have to partition any collections - you can just round-robin databases across multiple shards to allow the load to be distributed to separate clusters (if and when you reach that level).</p> <p>Contrary to the claim in the other answer, TTLMonitor thread does NOT pull documents into RAM unless they are being deleted (and added to the free list). They work off of TTL indexes both to tell if any documents are to be expired as well as to located the document directly.</p> <p>I would strongly recommend against the one database many collections solution as that doesn't allow you to either partition the load, nor provide security, nor is it any easier to handle on the application side.</p>
16,872,082
How can I send cookies using PHP curl in addition to CURLOPT_COOKIEFILE?
<p>I am scraping some content from a website after a form submission. The problem is that the script is failing every now and then, say 2 times out of 5 the script fails. I am using php curl, COOKIEFILE and COOKIEJAR to handle the cookie. However when I observed the sent headers of my browser (when visiting the target website from my browser and using live http headers) and the headers sent by php and saw there are many differences. </p> <p>My browser sent a lot more cookie variables than php curl. I think this difference might be because javascript is resposible for setting most of the cookies, however I'm not sure about this.</p> <p>I am using the below code to do the scraping and I am showing the sent headers of my browser and of php curl:</p> <pre><code>$ckfile = tempnam ("/tmp", 'cookiename'); $url = 'https://www.domain.com/firststep'; $poststring = 'variable1=4&amp;variable2=5'; $ch = curl_init ($url); curl_setopt ($ch, CURLOPT_COOKIEJAR, $ckfile); curl_setopt ($ch, CURLOPT_COOKIEFILE, $ckfile); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt ($ch, CURLOPT_POST, 1); curl_setopt ($ch, CURLOPT_POSTFIELDS, $poststring); $output = curl_exec ($ch); curl_close($ch); $url = 'https://www.domain.com/nextstep'; $poststring = 'variableB1=4&amp;variableB2=5'; $ch = curl_init ($url); curl_setopt ($ch, CURLOPT_COOKIEJAR, $ckfile); curl_setopt ($ch, CURLOPT_COOKIEFILE, $ckfile); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt ($ch, CURLOPT_POST, 1); curl_setopt ($ch, CURLOPT_POSTFIELDS, $poststring); curl_setopt($ch, CURLINFO_HEADER_OUT, true); $output = curl_exec ($ch); $headers = curl_getinfo($ch, CURLINFO_HEADER_OUT); curl_close($ch); print_r($headers); // Gives: POST /d-cobs-web/doffers.html;jsessionid=7BC2A5277A4EB07D9A7237A707BE1366 HTTP/1.1 User-Agent: Mozilla Host: domain.subdomain.nl Accept: */* Cookie: JSESSIONID=7BC2A5277A4EB07D9A7237A707BE1366; www-20480=MIFBNLFDFAAA Content-Length: 187 Content-Type: application/x-www-form-urlencoded // Where live http headers gives: POST /d-cobs-web/doffers.html;jsessionid=7BC2A5277A4EB07D9A7237A707BE1366 HTTP/1.1 Host: domain.subdomain.nl User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:21.0) Gecko/20100101 Firefox/21.0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: nl,en-us;q=0.7,en;q=0.3 Accept-Encoding: gzip, deflate Content-Type: application/x-www-form-urlencoded; charset=UTF-8 Referer: https://domain.subdomain.nl/dd/doffers.html?returnUrl=https%3A%2F%2Fttcc.subdomain.nl%2Fdd%2Fpreferences.html%3FValueChanged%3Dfalse&amp;BEGBA=&amp;departureDate=13-06-2013&amp;extChangeTime=&amp;pax2=0&amp;bp=&amp;pax1=1&amp;pax4=0&amp;bk=&amp;pax3=0&amp;shopId=&amp;xtpage=&amp;partner=NSINT&amp;bc=&amp;xt_pc=&amp;ov=&amp;departureTime=&amp;comfortClass=2&amp;destination=DEBHF&amp;thalysTicketless=&amp;beneUser=&amp;debugDOffer=&amp;logonId=&amp;valueChanged=&amp;iDomesticOrigin=&amp;rp=&amp;returnTime=&amp;locale=nl_NL&amp;vu=&amp;thePassWeekend=false&amp;returnDate=&amp;xtsite=&amp;pax=A&amp;lc2=&amp;lc1=&amp;lc4=&amp;lc3=&amp;lc6=&amp;lc5=&amp;BECRA=&amp;passType2=&amp;custId=&amp;lc9=&amp;iDomesticDestination=&amp;passType1=A&amp;lc7=&amp;lc8=&amp;origin=NLASC&amp;toporef=&amp;pid=&amp;passType4=&amp;returnTimeType=1&amp;passType3=&amp;departureTimeType=1&amp;socusId=&amp;idr3=&amp;xtn2=&amp;loyaltyCard=&amp;idr2=&amp;idr1=&amp;thePassBusiness=false&amp;cid=14812 Content-Length: 219 Cookie: subdomainPARTNER=NSINT; JSESSIONID=CB3FEB3AC72AD61A80BFED91D3FD96CA; www-20480=MHFBNLFDFAAA; campaignPos=5; www-47873=MGFBNLFDFAAA; __utma=1.993399624.1370027094.1370040145.1370082133.5; __utmc=1; __utmz=1.1370027094.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); BCSessionID=5dc05787-c2c8-43e1-9abe-93989970b087; BCPermissionLevel=PERSONAL; __utmb=1.1.10.1370082133 Connection: keep-alive Pragma: no-cache Cache-Control: no-cache AJAXREQUEST=_viewRoot&amp;doffersForm=doffersForm&amp;doffersForm%3AvalueChanged=&amp;doffersForm%3ArequestValid=true&amp;javax.faces.ViewState=j_id3&amp;doffersForm%3Aj_id937=doffersForm%3Aj_id937&amp;valueChanged=false&amp;AJAX%3AEVENTS_COUNT=1&amp; </code></pre> <p>I would like to use:</p> <pre><code>$headers = array(); $headers[] = 'Cookie: ' . $cookie; </code></pre> <p>and:</p> <pre><code>curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); </code></pre> <p>where:</p> <pre><code>$cookie = 'subdomainPARTNER=NSINT; JSESSIONID=CB3FEB3AC72AD61A80BFED91D3FD96CA; www-20480=MHFBNLFDFAAA; campaignPos=5; www-47873=MGFBNLFDFAAA; __utma=1.993399624.1370027094.1370040145.1370082133.5; __utmc=1; __utmz=1.1370027094.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); BCSessionID=5dc05787-c2c8-43e1-9abe-93989970b087; BCPermissionLevel=PERSONAL; __utmb=1.1.10.1370082133'; </code></pre> <p>Some of the parameters in the cookie above I might be able to scrape from the content of the website, but not all. Some of them I might be able to read from the $ckfile, but I don't know how to do that. Especially the utma utmc, utmz, utmcsr, utmccn, utmcmd I am not able to get from anywhere, I think these are generated by the javascript. </p> <p><strong>Question 1:</strong> Am I doing something wrong with the cookie handling in the current code as very few cookie variables are sent by php curl and a lot more by the browser? Further: can other differences between sent headers by browser and php curl be a problem to return the right content?</p> <p><strong>Question 2:</strong> Are the missing cookie variables due to the javascript setting those cookies?</p> <p><strong>Question 3:</strong> What is the best way to handle the cookies to make sure that all required cookies are being sent to the remote server?</p> <p>Your help is very welcome!</p>
22,261,052
4
2
null
2013-06-01 11:14:34.417 UTC
13
2019-11-24 22:22:18.333 UTC
null
null
null
null
879,618
null
1
49
php|cookies|curl|setcookie
157,682
<p>If the cookie is generated from script, then you can send the cookie manually along with the cookie from the file(using cookie-file option). For example:</p> <pre><code># sending manually set cookie curl_setopt($ch, CURLOPT_HTTPHEADER, array("Cookie: test=cookie")); # sending cookies from file curl_setopt($ch, CURLOPT_COOKIEFILE, $ckfile); </code></pre> <p>In this case curl will send your defined cookie along with the cookies from the file.</p> <p>If the cookie is generated through javascrript, then you have to trace it out how its generated and then you can send it using the above method(through http-header).</p> <p>The <code>utma utmc, utmz</code> are seen when cookies are sent from Mozilla. You shouldn't bet worry about these things anymore.</p> <p>Finally, the way you are doing is alright. Just make sure you are using absolute path for the file names(i.e. <code>/var/dir/cookie.txt</code>) instead of relative one.</p> <p>Always enable the verbose mode when working with curl. It will help you a lot on tracing the requests. Also it will save lot of your times.</p> <pre><code>curl_setopt($ch, CURLOPT_VERBOSE, true); </code></pre>
25,763,533
How to identify file type by Base64 encoded string of a image
<p>I get a file which is <a href="https://en.wikipedia.org/wiki/Base64" rel="noreferrer">Base64</a> encoded string as the image. But I think the content of this contains information about file type like png, jpeg, etc. How can I detect that? Is there any library which can help me here? </p>
35,419,967
6
4
null
2014-09-10 10:52:06.417 UTC
5
2019-12-31 04:52:24.197 UTC
2017-06-22 12:12:28.98 UTC
null
1,429,387
null
393,639
null
1
16
java|image|mime-types
77,301
<p>I have solved my problem with using <code>mimeType = URLConnection.guessContentTypeFromStream(inputstream);</code></p> <pre><code>{ //Decode the Base64 encoded string into byte array // tokenize the data since the 64 encoded data look like this "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAoAAAAKAC" String delims="[,]"; String[] parts = base64ImageString.split(delims); String imageString = parts[1]; byte[] imageByteArray = Base64.decode(imageString ); InputStream is = new ByteArrayInputStream(imageByteArray); //Find out image type String mimeType = null; String fileExtension = null; try { mimeType = URLConnection.guessContentTypeFromStream(is); //mimeType is something like "image/jpeg" String delimiter="[/]"; String[] tokens = mimeType.split(delimiter); fileExtension = tokens[1]; } catch (IOException ioException){ } } </code></pre>
4,179,606
How to copy observable collection
<p>I have</p> <pre><code>Observablecollection&lt;A&gt; aRef = new Observablecollection&lt;A&gt;(); bRef = aRef(); </code></pre> <p>In this case both point to same <code>ObservableCollection</code>. How do I make a different copy?</p>
4,179,627
2
0
null
2010-11-14 20:46:23.213 UTC
1
2021-02-28 07:12:05.61 UTC
2021-02-28 07:12:05.61 UTC
null
2,164,365
null
298,891
null
1
23
wpf|copy|observablecollection
39,812
<p>Do this:</p> <pre><code>// aRef being an Observablecollection Observablecollection&lt;Entity&gt; bRef = new Observablecollection&lt;Entity&gt;(aRef); </code></pre> <p>This will create an observable collection but the items are still pointing to the original items. If you need the items to point a clone rather than the original items, you need to implement and then call a cloning method.</p> <p><strong>UPDATE</strong></p> <p>If you try to add to a list and then the observable collection have the original list, just create the Observablecollection by passing the original list:</p> <pre><code>List&lt;Entity&gt; originalEnityList = GetThatOriginalEnityListFromSomewhere(); Observablecollection&lt;Entity&gt; bRef = new Observablecollection&lt;Entity&gt;(originalEnityList); </code></pre>
9,722,168
How can I get the same undefined ProgressBar as ICS with 2 rotating circles?
<p>I am currently writing an open source project that aims to port the famous Holo theme to previous versions of Android (since 1,6!!!)</p> <p>Everything works fine and I am really proud of my work, but the problem I am facing now is to get the ProgressBar totally looking like the ICS one.</p> <p>I used the same xml code than Android source: (progress_medium_holo.xml)</p> <pre><code>&lt;layer-list xmlns:android="http://schemas.android.com/apk/res/android"&gt; &lt;item&gt; &lt;rotate android:drawable="@drawable/spinner_48_outer_holo" android:pivotX="50%" android:pivotY="50%" android:fromDegrees="0" android:toDegrees="1080" /&gt; &lt;/item&gt; &lt;item&gt; &lt;rotate android:drawable="@drawable/spinner_48_inner_holo" android:pivotX="50%" android:pivotY="50%" android:fromDegrees="720" android:toDegrees="0" /&gt; &lt;/item&gt; &lt;/layer-list&gt; </code></pre> <p>With same png:</p> <p>spinner_76_outer_holo.png and spinner_76_inner_holo.png</p> <p><img src="https://i.stack.imgur.com/aJ4kX.png" alt="enter image description here"> white pic => <img src="https://i.stack.imgur.com/kyecc.png" alt="enter image description here"></p> <p>But unfortunately, I only get one circle...</p> <p>If you don't understand what I mean, you can try this app on a pre-ICS device:</p> <p><a href="https://play.google.com/store/apps/details?id=com.WazaBe.HoloDemo" rel="noreferrer">https://play.google.com/store/apps/details?id=com.WazaBe.HoloDemo</a></p> <p>FULL SOURCE IS HERE: <a href="https://github.com/ChristopheVersieux/HoloEverywhere" rel="noreferrer">https://github.com/ChristopheVersieux/HoloEverywhere</a></p> <p>Thank a lot for your help</p> <p><img src="https://i.stack.imgur.com/6o4Bd.png" alt="enter image description here"></p>
9,778,226
3
7
null
2012-03-15 14:47:01.263 UTC
10
2012-03-25 08:09:13.187 UTC
2012-03-25 08:09:13.187 UTC
null
383,793
null
327,402
null
1
26
android|progress-bar|android-4.0-ice-cream-sandwich
9,858
<p>Just found the answer here! </p> <p><a href="https://stackoverflow.com/a/8697806/327402">https://stackoverflow.com/a/8697806/327402</a></p> <p>Very usefull post!</p> <p>There is indeed a platform limitation, although it's not what you might think. The issue is that pre-API11, <code>RotateDrawable</code> had some crude code in it to require that the animation rotate clockwise by checking if <code>toDegrees</code> was greater than <code>fromDegrees</code>; if not, the two were forced equal to each other. If you modified your example to have the second item move in a forward direction (from 0 to 720, or even -720 to 0), both images would animate fine on all platforms; though I realize that defeats the purpose of what you're aiming for.</p> <p>Take a look at the cached version Google Codesearch has of <code>RotateDrawable.inflate()</code>, which is the 2.3 version of the method used to turn the XML into the object, and you'll see what I mean.</p> <p><a href="http://codesearch.google.com/codesearch#uX1GffpyOZk/graphics/java/android/graphics/drawable/RotateDrawable.java" rel="nofollow noreferrer">RotateDrawable.java</a> ...the offending code is around line 235...</p> <pre><code> float fromDegrees = a.getFloat( com.android.internal.R.styleable.RotateDrawable_fromDegrees, 0.0f); float toDegrees = a.getFloat( com.android.internal.R.styleable.RotateDrawable_toDegrees, 360.0f); toDegrees = Math.max(fromDegrees, toDegrees); //&lt;--There's the culprit </code></pre> <p>This takes an XML block like the second item that you have there, and turns it into a <code>RotateDrawable</code> that ends up with the same value for <code>fromDegrees</code> and <code>toDegrees</code> (in your case, 720), causing the image to simply stand still. You can visible test this by setting the start value to some value not a multiple of 360 (like 765). You'll see that the image still does not animate, but is rotated to the initial coordinate.</p> <p>This awkward check was removed in the Honeycomb/ICS sources, which is why you can do backwards rotation on those platforms. Also, it doesn't look like there is a way to set these values from Java code, so a custom <code>RotateDrawableCompat</code> may be in your future :)</p> <p>HTH</p>
10,237,731
CSS3 transitions inside jQuery .css()
<p>When I add the transition line into my code it breaks jQuery. How can I fix it?</p> <pre><code>a(this).next().css({ left: c, transition: 'opacity 1s ease-in-out' }); </code></pre> <p>I'm trying to set up a fade from one div to the next inside a slider</p>
10,237,742
2
3
null
2012-04-19 22:26:13.567 UTC
13
2019-01-07 13:43:35.353 UTC
null
null
null
null
209,102
null
1
28
jquery|css-transitions
119,492
<p><strong>Step 1)</strong> Remove the semi-colon, it's an object you're creating...</p> <pre><code>a(this).next().css({ left : c, transition : 'opacity 1s ease-in-out'; }); </code></pre> <p>to</p> <pre><code>a(this).next().css({ left : c, transition : 'opacity 1s ease-in-out' }); </code></pre> <p><strong>Step 2)</strong> Vendor-prefixes... no browsers use <code>transition</code> since it's the standard and this is an experimental feature even in the latest browsers:</p> <pre><code>a(this).next().css({ left : c, WebkitTransition : 'opacity 1s ease-in-out', MozTransition : 'opacity 1s ease-in-out', MsTransition : 'opacity 1s ease-in-out', OTransition : 'opacity 1s ease-in-out', transition : 'opacity 1s ease-in-out' }); </code></pre> <p>Here is a demo: <a href="http://jsfiddle.net/83FsJ/" rel="nofollow noreferrer">http://jsfiddle.net/83FsJ/</a></p> <p><strong>Step 3)</strong> Better vendor-prefixes... Instead of adding tons of unnecessary CSS to elements (that will just be ignored by the browser) you can use jQuery to decide what vendor-prefix to use:</p> <pre><code>$('a').on('click', function () { var myTransition = ($.browser.webkit) ? '-webkit-transition' : ($.browser.mozilla) ? '-moz-transition' : ($.browser.msie) ? '-ms-transition' : ($.browser.opera) ? '-o-transition' : 'transition', myCSSObj = { opacity : 1 }; myCSSObj[myTransition] = 'opacity 1s ease-in-out'; $(this).next().css(myCSSObj); });​ </code></pre> <p>Here is a demo: <a href="http://jsfiddle.net/83FsJ/1/" rel="nofollow noreferrer">http://jsfiddle.net/83FsJ/1/</a></p> <p>Also note that if you specify in your <code>transition</code> declaration that the property to animate is <code>opacity</code>, setting a <code>left</code> property won't be animated.</p>
9,723,949
iOS SFHFKeychainUtils failing *sometimes* with error -25308 errSecInteractionNotAllowed
<p>I have this code getting back a password from the keychain for a given username NSString:</p> <pre><code>NSError *error = nil; NSString *appName = [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString*)kCFBundleNameKey]; NSString *pw = [SFHFKeychainUtils getPasswordForUsername:username andServiceName:appName error:&amp;error]; if(error != nil) // log the error </code></pre> <p>Most of the time for most users this all works fine - but for some specific users this call seems to fail (and carry on failing) where it returns the following error:</p> <pre><code>The operation couldn’t be completed. (SFHFKeychainUtilsErrorDomain error -25308.) </code></pre> <p>This is apparently errSecInteractionNotAllowed - which from what I've read I <em>think</em> this means some kind of user interaction is required for the keychain to be accessed.</p> <p>Does anyone have any idea why this call may be failing for some specific users only? This keychain entry is specific to my app - so why would any user interaction be required to access it?</p> <p>Any pointers much appreciated...</p>
9,735,506
2
0
null
2012-03-15 16:27:43.39 UTC
20
2021-06-11 07:02:33.803 UTC
null
null
null
null
651,899
null
1
37
ios|keychain|sfhfkeychainutils
12,730
<p>OK so I worked this out finally.</p> <p>Eventually I worked out the users who were having problems had set a lock code on their phone. If the phone was locked the keychain system was returning this -25308 error.</p> <p>If you only ever need to access the keychain when the app is active in the forground you would never see this issue - but if you need to carry on processing when the phone is locked or if the app is in background then you would see it.</p> <p>Elsewhere I'd read that the default access attribute for the kechain system is kSecAttrAccessibleAlways - but I think that is out of date. It seems the default access attribute for the keychain system is such that when the phone is locked with a pin code then the items are unavailable.</p> <p>The fix for this is to change the SFHFKeychainUtils code to set a specific kSecAttrAccessible attribute on the keychain items it manages (which the original code did not do - presumably as it pre-dated these attributes).</p> <p>This wordpress <a href="https://github.com/wordpress-mobile/WordPress-iOS/blob/8f231977c4ebb0337ede7657a38bd64b90f0a288/WordPress/Classes/Utility/SFHFKeychainUtils.m" rel="noreferrer">updated version</a> of the SFHFKeychainUtils code has the fixes in it - search for kSecAttrAccessible to see where they have added the accessible attribute code.</p> <p>Hope this helps anyone else running into this...</p>
10,224,856
jQuery UI Slider Labels Under Slider
<p>I am limited to using jQuery 1.4.2 and jQuery ui 1.8.5 (this is not by choice, please do not ask me to upgrade to latest versions). I have created a slider that shows the current value above the slide bar, but what I need now is a way to populate a legend below the slide bar distanced the same as the slider (i.e. if the slider is 100px wide and there are five values the slider will snap every 20px. In this example, I would like the values in the legend to be placed at 20px intervals).</p> <p>Here is an example of what I want:</p> <p><img src="https://richard.parnaby-king.co.uk/wp-content/uploads/2012/04/scroll-bar1.png" alt="Slider" /></p> <p>Here is the jQuery I have (assimilated from the ui slider demo page):</p> <pre><code>//select element with 5 - 20 options var el = $('.select'); //add slider var slider = $( '&lt;div class="slider"&gt;&lt;/div&gt;' ).insertAfter( el ).slider({ min: 1, max: el.options.length, range: 'min', value: el.selectedIndex + 1, slide: function( event, ui ) { el.selectedIndex = ui.value - 1; slider.find("a").text(el.options[el.selectedIndex].label); }, stop: function() { $(el).change(); } }); slider.find("a").text(el.options[el.selectedIndex].label); //pre-populate value into slider handle. </code></pre>
10,225,209
5
0
null
2012-04-19 09:03:11.043 UTC
13
2019-09-02 15:15:04.573 UTC
2017-02-08 14:35:25.12 UTC
null
-1
null
351,785
null
1
37
jquery|jquery-ui|jquery-ui-slider
69,569
<p>To create a legend, we need to know the width of the slider and the number of elements then divide one against the other:</p> <pre><code>//store our select options in an array so we can call join(delimiter) on them var options = []; for each(var option in el.options) { options.push(option.label); } //how far apart each option label should appear var width = slider.width() / (options.length - 1); //after the slider create a containing div with p tags of a set width. slider.after('&lt;div class="ui-slider-legend"&gt;&lt;p style="width:' + width + 'px;"&gt;' + options.join('&lt;/p&gt;&lt;p style="width:' + width + 'px;"&gt;') +'&lt;/p&gt;&lt;/div&gt;'); </code></pre> <p>The p tag needs to have the style 'display:inline-block' to render correctly, otherwise each label will take one line or the labels will be stacked up right next to each other.</p> <p>I have created a post explaining the problem and solution: <a href="http://richard.parnaby-king.co.uk/2012/04/jquery-ui-slider-legend-under-slider/" rel="noreferrer">jQuery UI Slider Legend Under Slider</a> which contains a live demo of this working.</p>
9,757,400
Setting ActionBarSherlock Theme for Android app
<p><strong>READ UPDATE 2 BELOW FOR THE ANSWER</strong></p> <p>I'm trying to use ActionBarSherlock in my app. I checked out the 4.0.0 release from the <a href="https://github.com/JakeWharton/ActionBarSherlock" rel="noreferrer">project github repo</a>, built it in Netbeans, then copied the library-4.0.0.jar file into my project's lib directory (I'm not using Eclipse).</p> <p>It's just a skeleton activity right now, and it launches just fine in ICS, but when I run it on Gingerbread I get the following exception complaining that I haven't the app theme to Theme.Sherlock (or similar):</p> <pre><code>java.lang.RuntimeException: Unable to start activity ComponentInfo{com.arashpayan.prayerbook/com.arashpayan.prayerbook.PrayerBook}: java.lang.IllegalStateException: You must use Theme.Sherlock, Theme.Sherlock.Light, Theme.Sherlock.Light.DarkActionBar, or a derivative. at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663) at android.app.ActivityThread.access$1500(ActivityThread.java:117) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:130) at android.app.ActivityThread.main(ActivityThread.java:3683) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:507) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597) at dalvik.system.NativeStart.main(Native Method) Caused by: java.lang.IllegalStateException: You must use Theme.Sherlock, Theme.Sherlock.Light, Theme.Sherlock.Light.DarkActionBar, or a derivative. at com.actionbarsherlock.internal.ActionBarSherlockCompat.generateLayout(ActionBarSherlockCompat.java:987) at com.actionbarsherlock.internal.ActionBarSherlockCompat.installDecor(ActionBarSherlockCompat.java:899) at com.actionbarsherlock.internal.ActionBarSherlockCompat.setContentView(ActionBarSherlockCompat.java:852) at com.actionbarsherlock.ActionBarSherlock.setContentView(ActionBarSherlock.java:655) at com.actionbarsherlock.app.SherlockFragmentActivity.setContentView(SherlockFragmentActivity.java:316) at com.arashpayan.prayerbook.PrayerBook.onCreate(PrayerBook.java:44) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611) ... 11 more </code></pre> <p>The line it complains about (PrayerBook:44) is the call to <code>setContentView</code>. The app just consists of a single activity with an <code>onCreate()</code> method that I call <code>setTheme()</code> from at the top:</p> <pre><code>public void onCreate(Bundle savedInstanceState) { setTheme(com.actionbarsherlock.R.style.Theme_Sherlock); super.onCreate(savedInstanceState); TextView rootTextView = new TextView(this); rootTextView.setText("Hello, world!"); setContentView(rootTextView); getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); ActionBar.Tab tab = getSupportActionBar().newTab(); tab.setText("Prayers"); getSupportActionBar().addTab(tab); tab = getSupportActionBar().newTab(); tab.setText("Recents"); getSupportActionBar().addTab(tab); tab = getSupportActionBar().newTab(); tab.setText("Bookmarks"); getSupportActionBar().addTab(tab); } </code></pre> <p>I must be setting the theme incorrectly, but I just don't see how. Can anyone help?</p> <p><b>UPDATE</b> Below, CommonsWare noted that the theme can be set in the AndroidManifest.xml. I've tried that like so:</p> <pre><code>&lt;application android:label="@string/app_name" android:icon="@drawable/icon" android:theme="@style/Theme.Sherlock"&gt; &lt;activity android:name="PrayerBook" android:label="@string/app_name" android:configChanges="orientation|keyboardHidden|screenLayout|uiMode|mcc|mnc|locale|navigation|fontScale|screenSize"&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="LanguagesActivity" /&gt; &lt;/application&gt; </code></pre> <p>but Ant gives me an error when it tries to build the app:</p> <pre><code>/Users/arash/coding/prayerbook/AndroidManifest.xml:7: error: Error: No resource found that matches the given name (at 'theme' with value '@style/Theme.Sherlock'). </code></pre> <p><strong>UPDATE 2</strong> With CommonsWare's help in his follow up comments, I was able to get it working. I needed to add ActionBarSherlock as a project dependency. To do so,</p> <p>1) I removed <code>library-4.0.0.jar</code> and <code>android-support-4.0.jar</code> from my project's <code>lib</code> directory.</p> <p>2) Next, navigate into the <code>library</code> folder inside the root of the ActionBarSherlock directory checked out from github. Type <code>android update project</code> so a <code>build.xml</code> and <code>proguard.cfg</code> file will be created for the library.</p> <p>3) Finally, <code>cd</code> back into the main project directory and add ABS as a library dependency with <code>android update project --path . --library ../ActionBarSherlock/library</code> The path to the <code>--library</code> in the command will vary according to where you checked out the repo. ActionBarSherlock and my app's project directory were sibling directories.</p>
9,757,822
7
2
null
2012-03-18 09:54:20.27 UTC
7
2017-03-03 19:18:15.697 UTC
2012-03-18 12:00:57.93 UTC
null
211,180
null
211,180
null
1
42
android|actionbarsherlock
51,409
<p>Usually, you set your theme in the manifest, as shown in <a href="http://developer.android.com/guide/topics/ui/themes.html#ApplyATheme" rel="noreferrer">the Android developer documentation</a> (and linked to from <a href="http://actionbarsherlock.com/theming.html" rel="noreferrer">the ActionBarSherlock theming page</a>).</p> <p>If you want to use ActionBarSherlock everywhere within your app, this works:</p> <pre><code>&lt;application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/Theme.Sherlock"&gt; </code></pre>
9,765,007
How do you undo bundle install --without
<p>How do you undo running</p> <pre><code>bundle install --without development </code></pre> <p>Right now, I have gems in the development group that are being ignored because I ran this once... (note that I have tried deleting gemfile.lock to no avail)</p>
9,765,342
4
1
null
2012-03-19 04:23:23.493 UTC
9
2015-06-25 00:38:31.73 UTC
null
null
null
null
743,522
null
1
45
ruby-on-rails|bundler
17,695
<p>The updated, correct answer is @caspyin's, <a href="https://stackoverflow.com/a/15145462/292586">here</a>.</p> <p>My answer is still here for historical purposes:</p> <blockquote> <p>Bundler settings are stored in a file named <code>.bundle/config</code>. You can reset it by removing it, or removing the entire <code>.bundle</code> directory, like this:</p> <pre><code>rm -rfv .bundle </code></pre> <p>Or, if you're scared of <code>rm -rf</code> (it's OK, many people are):</p> <pre><code>rm .bundle/config rmdir .bundle </code></pre> </blockquote>
10,004,685
Selecting which project under a solution to debug or run in Visual Studio 2010
<p>This one should be easy. I just can't figure out what to search for...</p> <p>For this one solution I created a unit test project, and I've been adding unit tests frantically. When I went back to try to run the original project after making all the unit tests pass I realized that I couldn't figure out how to debug the original project.</p> <p>In other words, every time I try to "debug" (e.g., by pressing <kbd>F5</kbd>), Visual Studio will run the unit tests. So the question is how do I run various projects in a single solution? How do I select which one will run when I want it to?</p>
10,004,706
5
0
null
2012-04-04 03:50:26.503 UTC
7
2020-05-06 11:22:22.08 UTC
2015-08-11 12:30:47.71 UTC
null
1,497,596
null
181,310
null
1
46
c#|.net|visual-studio|visual-studio-2010|ide
39,106
<p><a href="http://msdn.microsoft.com/en-us/library/a1awth7y.aspx" rel="noreferrer">You can right click on the project and choose to set as startup project</a></p>
27,988,502
Applying angularjs ng-repeat to owl-carousel
<pre><code>&lt;div class="owl-carousel"&gt; &lt;div ng-repeat="items in itemlist"&gt; &lt;a href="series.html"&gt;&lt;img ng-src="{{items.imageUrl}}" /&gt;&lt;/a&gt; &lt;/div&gt; &lt;div&gt; &lt;a href="series.html"&gt;&lt;img src="http://placehold.it/350x150" /&gt;&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>View carousel here: <a href="http://www.owlcarousel.owlgraphic.com/">Owl-carousel2</a></p> <p>I'm running into an issue where whenever the ng-repeat directive is applied to carousel the items are stacked vertically instead of being layout horizontally.</p> <p>If I leave out ng-repeat and use static items then it works as it should.</p> <p>Is there a directive I can write and apply to owl-carousel to maintain the layout?</p> <p>Also what is about ng-repeat that is causing the carousel to break? </p> <p>Is angular somehow stripping the owl-carousel classes applied to the carousel?</p> <p>Note* If build the list manually then iterate through and append the elements using :</p> <pre><code>var div = document.createElement('div'); var anchor = document.createElement('a'); var img = document.createElement('img'); ..... carousel.appendChild(div); </code></pre> <p>then call the owl.owlCarousel({..}) It works, not sure if this is the best work around because ng-repeat makes everything bit easier.</p> <p>I discovered a hack , if I wrap the owl init in a timeout then ng-repat works.</p> <pre><code>setTimeout(function(){ ...call owl init now },1000); </code></pre> <hr> <pre><code>&lt;link rel="stylesheet" href="css/owl.carousel.css"/&gt; &lt;link rel="stylesheet" href="css/owl.theme.default.min.css"/&gt; ..... &lt;script src="/js/lib/owl.carousel.min.js"&gt;&lt;/script&gt; &lt;script&gt; $(document).ready(function() { var owl = $('.owl-carousel'); owl.owlCarousel({ ..... }); owl.on('mousewheel', '.owl-stage', function(e) { if (e.deltaY &gt; 0) { owl.trigger('next.owl'); } else { owl.trigger('prev.owl'); } e.preventDefault(); }); }) &lt;/script&gt; </code></pre>
29,686,215
4
9
null
2015-01-16 16:33:43.603 UTC
8
2018-09-07 13:09:00.613 UTC
2015-01-16 17:49:38.113 UTC
null
1,243,905
null
1,243,905
null
1
14
javascript|angularjs|angularjs-directive|owl-carousel
39,406
<p>Was able to modify a directive from <a href="https://stackoverflow.com/users/635411/dting">DTing</a> on another <a href="https://stackoverflow.com/questions/29157623/owl-carousel-not-identifying-elements-of-ng-repeat/29685686#29685686">post</a> to get it working with multiple carousels on the same page. Here is a working <a href="http://plnkr.co/edit/pOIh2mOkj9N5HajbiC9h?p=preview" rel="nofollow noreferrer">plnkr</a></p> <p>-- Edit -- Have another <a href="http://plnkr.co/edit/qAnXhA7yVyZDQUq6sXGY?p=preview" rel="nofollow noreferrer">plnkr</a> to give an example on how to add an item. Doing a reinit() did not work cause any time the owl carousel is destroyed it loses the data- elements and can never initialize again.</p> <pre><code>var app = angular.module('plunker', []); app.controller('MainCtrl', function($scope) { $scope.items1 = [1,2,3,4,5]; $scope.items2 = [1,2,3,4,5,6,7,8,9,10]; }).directive("owlCarousel", function() { return { restrict: 'E', transclude: false, link: function (scope) { scope.initCarousel = function(element) { // provide any default options you want var defaultOptions = { }; var customOptions = scope.$eval($(element).attr('data-options')); // combine the two options objects for(var key in customOptions) { defaultOptions[key] = customOptions[key]; } // init carousel $(element).owlCarousel(defaultOptions); }; } }; }) .directive('owlCarouselItem', [function() { return { restrict: 'A', transclude: false, link: function(scope, element) { // wait for the last item in the ng-repeat then call init if(scope.$last) { scope.initCarousel(element.parent()); } } }; }]); </code></pre> <p>Here is the HTML</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html ng-app="plunker"&gt; &lt;head&gt; &lt;meta charset="utf-8" /&gt; &lt;title&gt;AngularJS Plunker&lt;/title&gt; &lt;script&gt;document.write('&lt;base href="' + document.location + '" /&gt;');&lt;/script&gt; &lt;link rel="stylesheet" href="style.css" /&gt; &lt;link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/owl-carousel/1.3.3/owl.carousel.min.css" /&gt; &lt;link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/owl-carousel/1.3.3/owl.theme.min.css" /&gt; &lt;link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/owl-carousel/1.3.3/owl.transitions.min.css" /&gt; &lt;link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/owl-carousel/1.3.3/owl.carousel.min.js" /&gt; &lt;script data-require="angular.js@1.3.x" src="https://code.angularjs.org/1.3.15/angular.js" data-semver="1.3.15"&gt;&lt;/script&gt; &lt;script data-require="jquery@2.1.3" data-semver="2.1.3" src="http://code.jquery.com/jquery-2.1.3.min.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/owl-carousel/1.3.3/owl.carousel.min.js"&gt;&lt;/script&gt; &lt;script src="app.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body ng-controller="MainCtrl"&gt; &lt;data-owl-carousel class="owl-carousel" data-options="{navigation: true, pagination: false, rewindNav : false}"&gt; &lt;div owl-carousel-item="" ng-repeat="item in ::items1" class="item"&gt; &lt;p&gt;{{::item}}&lt;/p&gt; &lt;/div&gt; &lt;/data-owl-carousel&gt; &lt;data-owl-carousel class="owl-carousel" data-options="{navigation: false, pagination: true, rewindNav : false}"&gt; &lt;div owl-carousel-item="" ng-repeat="item in ::items2" class="item"&gt; &lt;p&gt;{{::item}}&lt;/p&gt; &lt;/div&gt; &lt;/data-owl-carousel&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
9,652,720
How to run 'sudo' command in windows
<p>How would I run the following command in windows:</p> <pre><code>$ sudo django-admin.py startproject NEW </code></pre> <p>?</p>
9,652,749
17
6
null
2012-03-11 05:30:39.647 UTC
26
2022-03-01 06:00:04.09 UTC
2014-06-23 13:55:53.373 UTC
user3413108
null
null
651,174
null
1
150
windows
589,393
<p>There is no <code>sudo</code> command in Windows. The nearest equivalent is "run as administrator."</p> <p>You can do this using the <a href="http://technet.microsoft.com/en-us/library/cc771525%28v=ws.10%29.aspx"><code>runas</code></a> command with an administrator trust-level, or by right-clicking the program in the UI and choosing <em>"run as administrator."</em></p>
7,759,837
Put divs below float:left divs
<p>I'm trying to have a site that has the basic structure: </p> <pre><code>&lt;1 div&gt; &lt;3 divs next to each other&gt; &lt;1 div&gt; </code></pre> <p>The 3 divs are float:left in order to make be on the same level. However, they 5th div (at the bottom) sort of moves up to the top of the 3 divs in IE, and shown like that in Chrome, although the content is below the 3 divs.<br> I think I've just done some lazy coding here, but don't really know any better.<br> I've currently got: </p> <pre><code>&lt;div id="results"&gt; &lt;!-- Ajax Content Here --&gt; &lt;/div&gt; &lt;div id="leftpanel"&gt; &lt;/div&gt; &lt;div id="photo"&gt; &lt;/div&gt; &lt;div id="top3"&gt; &lt;/div&gt; &lt;div id="voting"&gt; &lt;/div&gt; </code></pre> <p>The results is the top one, leftpanel, photo and top3 are the middle 3, whilst voting is below the 3.<br> Basic CSS is :</p> <pre><code>#leftpanel { float:left; width:20%; height: 600px; } #top3 { float: left; width:20% } #photo { width: 60%; float:left; text-align: center; } #voting { width: 500px; height: 250px; text-align: center; margin-left: auto; margin-right: auto; } #results{ width: 300px; height: 20px; margin-left: auto; margin-right:auto; margin-bottom: 5px; text-align: center; } </code></pre> <p>I'm sure it's something silly I'm doing, so any input is much appreciated, I could use to learn how to do this properly :) I previously had a containing div on the 3 middle divs, but this didn't work since the ones inside change size. Maybe I need to do this, but in a different way?</p>
7,760,064
3
0
null
2011-10-13 20:07:58.967 UTC
3
2020-04-15 15:16:06.347 UTC
null
null
null
null
657,676
null
1
23
html|css
44,370
<p>Rather than working with floats, you might consider simply setting the display attribute of the middle divs to "inline-block". Remember that be default, div elements have a block display, which means that they take up the entire width of its parent element, even if its width is less than the parent width. inline blocks on the other hand fit together like puzzle pieces and flow horizontally rather than vertically. I think this would make your code much cleaner than dealing with floats. Here's a demo:</p> <p><a href="http://jsfiddle.net/scMFC/" rel="noreferrer">http://jsfiddle.net/scMFC/</a></p>
7,945,082
Insert multiple inputs on one line in C++
<p>I'm trying to insert multiple inputs on one line, with comma and a space between the inputs. The method I've been using so far separates inputs with spaces.</p> <pre><code>int a, b , c ,d cin &gt;&gt; a &gt;&gt; b &gt;&gt; c &gt;&gt; d ; </code></pre> <p>With this method , the input line looks like this :</p> <pre><code>1 2 3 4 </code></pre> <p>But I want to be able to input data like this:</p> <pre><code>1, 2, 3, 4 </code></pre>
7,945,121
4
4
null
2011-10-30 13:11:43.807 UTC
1
2021-07-29 16:17:32.66 UTC
null
null
null
null
969,489
null
1
1
c++|input|iostream
58,334
<p>The delimiter character for <code>&gt;&gt;</code> isn't modifiable, but you can use it in combination with <code>ignore</code>:</p> <pre><code>std::cin &gt;&gt; a; std::cin.ignore(1, ',') // rinse and repeat </code></pre>
11,586,923
SELECT DISTINCT with LEFT JOIN, ORDERed BY in t-SQL
<p>I have the following table in SQL Server 2008:</p> <pre><code>CREATE TABLE tbl (ID INT, dtIn DATETIME2, dtOut DATETIME2, Type INT) INSERT tbl VALUES (1, '05:00', '6:00', 1), (2, '05:00', '7:00', 1), (3, '05:01', '8:00', 1), (4, '05:00', '8:00', 1), (5, '05:00', '6:00', 2), (6, '05:00', '7:00', 2) </code></pre> <p>that selects IDs of all records of the same type, with the same dtIn date, ordered by stOut in ascending order:</p> <pre><code>SELECT DISTINCT tbl.id FROM tbl LEFT JOIN tbl AS t1 ON tbl.type = t1.type AND tbl.dtIn = t1.dtIn ORDER BY tbl.dtOut ASC </code></pre> <p>But it gives me an error:</p> <blockquote> <p>ORDER BY items must appear in the select list if SELECT DISTINCT is specified</p> </blockquote> <p>I tried putting that ORDER BY in different places and it all doesn't seem to work. What am I doing wrong here?</p>
11,587,144
5
2
null
2012-07-20 21:04:42.14 UTC
3
2020-10-27 16:46:46.13 UTC
2012-07-20 21:06:07.033 UTC
null
13,302
null
670,017
null
1
14
sql|sql-server|tsql|sql-order-by|distinct
112,027
<p>When you narrow it down to individual id's, you create the possibility that each id might have more than one <code>dtOut</code> associated with it. When that happens, how will Sql Server know which order to use?</p> <p>You could try:</p> <pre><code>SELECT t1.id FROM tbl t1 LEFT JOIN tbl t2 on t1.type = t2.type AND t1.dtIn = t2.dtIn GROUP BY t1.id, t2.dtOut ORDER BY t2.dtOut </code></pre> <p>However, as I mentioned above this can open the possibility of having the same id listed more than once, if it matches to more than one record on the right-side table.</p>
11,929,781
Check preconditions in Controller or Service layer
<p>I'm using Google's Preconditions class to validate user's input data.<br> But I'm worried about where is the best point of checking user's input data using Preconditions class.<br> First, I wrote validation check code in Controller like below: </p> <pre><code>@Controller ... public void register(ProductInfo data) { Preconditions.checkArgument(StringUtils.hasText(data.getName()), "Empty name parameter."); productService.register(data); } @Service ... public void register(ProductInfo data) { productDao.register(data); } </code></pre> <p>But I thought that <code>register</code> method in Service layer would be using another Controller method like below: </p> <pre><code>@Controller ... public void register(ProductInfo data) { productService.register(data); } public void anotherRegister(ProductInfo data) { productService.register(data); } @Service ... public void register(ProductInfo data) { Preconditions.checkArgument(StringUtils.hasText(data.getName()), "Empty name parameter."); productDao.register(data); } </code></pre> <p>On the other hand, the method of service layer would be used in just one controller.<br> I was confused. Which is the better way of checking preconditions in controller or service?<br> Thanks in advance. </p>
12,041,382
4
0
null
2012-08-13 07:22:09.583 UTC
15
2020-05-04 15:07:37.267 UTC
2012-08-16 00:43:04.13 UTC
null
1,454,671
null
889,158
null
1
20
spring|validation|service|controller
14,506
<p>Ideally you would do it in both places. But you are confusing two different things:</p> <ul> <li>Validation (with error handling)</li> <li>Defensivie Programming (aka assertions, aka design by contract).</li> </ul> <p>You absolutely should do <strong>validation</strong> in the controller and <strong>defensive programming</strong> in your service. And here is why.</p> <p>You need to <strong>validate</strong> for forms and REST requests so that you can send a sensible error back to the client. This includes what fields are bad and then doing localization of the error messages, etc... (your current example would send me a horrible 500 error message with a stack trace if ProductInfo.name property was null).</p> <p>Spring has a <a href="http://static.springsource.org/spring/docs/current/spring-framework-reference/html/validation.html" rel="noreferrer">solution for validating objects</a> in the controller.</p> <p><strong>Defensive programming</strong> is done in the service layer BUT NOT <strong>validation</strong> because you don't have access to locale to generate proper error messages. Some people do but Spring doesn't really help you there.</p> <p>The other reason why validation is not done in the service layer is that the ORM already typically does this through the JSR Bean Validation spec (hibernate) but it doesn't generate sensible error messages.</p> <p>One strategy people do is to create their own preconditions utils library that throws custom derived <code>RuntimeException</code>s instead of guava's (and commons lang) <code>IllegalArgumentException</code> and <code>IllegalStateException</code> and then <code>try</code>...<code>catch</code> the exceptions in the controller converting them to validation error messages.</p>
11,965,087
Open a new tab/window and write something to it?
<p>I'm using <a href="https://addons.mozilla.org/vi/firefox/addon/execute-js/?src=search">Execute JS</a> to write and test Javascript code within Firefox. I want to open a new tab/window and write something to it and I tried</p> <pre><code>var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"].getService(Components.interfaces.nsIWindowMediator); var win = wm.getMostRecentWindow("navigator:browser"); printWindow = win.open("about:blank"); printWindow = wm.getMostRecentWindow("navigator:browser"); printWindow.gBrowser.selectedBrowser.contentDocument.write('hello'); </code></pre> <p>And</p> <pre><code>myWindow=window.open('','','width=200,height=100') myWindow.document.write("&lt;p&gt;This is 'myWindow'&lt;/p&gt;") myWindow.focus() </code></pre> <p>However I always get this error </p> <blockquote> <p>[Exception... "The operation is insecure." code: "18" nsresult: "0x80530012 (SecurityError)"</p> </blockquote> <p>Is there any way to get through this exception?</p>
11,967,627
3
1
null
2012-08-15 06:42:23.037 UTC
7
2018-03-01 15:00:21.93 UTC
2012-08-15 10:17:54.853 UTC
null
785,541
null
433,531
null
1
23
javascript|firefox|firefox-addon|xpcom
56,783
<p><strong>Edit</strong>: As of 2018, this solution <a href="https://blog.mozilla.org/security/2017/11/27/blocking-top-level-navigations-data-urls-firefox-58/" rel="noreferrer">no longer works</a>. So you are back to opening <code>about:blank</code> in a new window and adding content to it.</p> <p>Don't "write" to the window, just open it with the contents you need:</p> <pre><code>var data = "&lt;p&gt;This is 'myWindow'&lt;/p&gt;"; myWindow = window.open("data:text/html," + encodeURIComponent(data), "_blank", "width=200,height=100"); myWindow.focus(); </code></pre> <p>For reference: <a href="https://developer.mozilla.org/en-US/docs/data_URIs" rel="noreferrer">data URIs</a></p>
11,618,696
Shell - Write variable contents to a file
<p>I would like to copy the contents of a variable (here called <code>var</code>) into a file.</p> <p>The name of the file is stored in another variable <code>destfile</code>. </p> <p>I'm having problems doing this. Here's what I've tried:</p> <pre><code>cp $var $destfile </code></pre> <p>I've also tried the same thing with the dd command... Obviously the shell thought that <code>$var</code> was referring to a directory and so told me that the directory could not be found. </p> <p>How do I get around this?</p>
11,618,931
7
4
null
2012-07-23 18:56:42.82 UTC
24
2022-05-18 14:23:38.66 UTC
2012-07-23 19:40:35.42 UTC
null
778,118
null
1,546,083
null
1
142
linux|bash|shell
388,587
<p>Use the <code>echo</code> command:</p> <pre><code>var="text to append"; destdir=/some/directory/path/filename if [ -f "$destdir" ] then echo "$var" &gt; "$destdir" fi </code></pre> <p>The <code>if</code> tests that <code>$destdir</code> represents a file.</p> <p>The <code>&gt;</code> appends the text after truncating the file. If you only want to append the text in <code>$var</code> to the file existing contents, then use <code>&gt;&gt;</code> instead:</p> <pre><code>echo "$var" &gt;&gt; "$destdir" </code></pre> <p>The <code>cp</code> command is used for copying files (to files), not for writing text to a file.</p>
3,280,576
How does RabbitMQ compare to Mule
<p>How does RabbitMQ compare to Mule, I am going to build an application using message oriented architecture and AMQP (RabbitMQ) provides everything i want, but i am perplexed with so many related technology choice and similar concepts like ESB. I am having a doubt if i am making a choice without considering other alternatives.</p> <p>I am mostly clear that RabbitMQ is a message broker and it helps me in mediating message between producer and consumer (all forms or publish subscribe and i could understand how its used from real examples like twitter , or Facebook updates, etc)</p> <p>What is Mule, if i could achieve what i do in RabbitMQ using mule, should i consider mule similar to RabbitMQ?</p> <p>Does mule has a different objective than that of a message broker?</p> <p>Does mule assumes that underlying it there is a message broker that delivers message to the appropriate mule listeners (i could easily write a listener in RabbitMQ)</p> <p>Is mule a complete Java bases system ( The current experiment i did with RabbitMQ took me less than 30 Min to write a simple RPC Client Server with client as C# and Server as Java , will such things be done in Mule easily).</p>
3,346,417
4
0
null
2010-07-19 11:20:36.647 UTC
16
2019-06-05 14:13:00.68 UTC
null
null
null
null
376,188
null
1
49
jms|esb|rabbitmq|mule|eai
19,848
<p>Mule is an ESB (Enterprise Service Bus). RabbitMQ is a message broker.</p> <p>An <b>ESB</b> provides added layers atop of a message broker such as routing, transformations and business process management. It is a mediator between applications, integrating Web Services, REST endpoints, database connections, email and ftp servers - you name it. It is a high-level integration backbone which orchestrates interoperability within a network of applications that speak different protocols.</p> <p>A <b>message broker</b> is a lower level component which enables you as a developer to relay raw messages between publishers and subscribers, typically between components of the same system but not always. It is used to enable asynchronous processing to keep response times low. Some tasks take longer to process and you don't want them to hold things up if they're not time-sensitive. Instead, post a message to a queue (as a publisher) and have a subscriber pick it up and process it "later".</p>
4,001,316
How do I preserve transparency in ggplot2?
<p>I love the plots that ggplot generates. However, it is still somewhat cumbersome to get publication quality plots directly. I usually have to do some post processing in Illustrator (i.e. changing fonts, numbering figures etc). While I could save as tiff or png, eps is best for manipulating figures in Illustrator (I can ungroup objects, move the legend/text etc).</p> <p>When I save a ggplot object with some transparency (either in points or a smoother) I get this error:</p> <pre><code>Warning message: In grid.Call.graphics("L_points", x$x, x$y, x$pch, x$size) : semi-transparency is not supported on this device: reported only once per page </code></pre> <p>Is there a workaround? </p>
4,001,378
6
3
null
2010-10-22 22:05:50.453 UTC
11
2018-11-03 23:32:01.707 UTC
null
null
null
null
313,163
null
1
28
r
19,034
<p>R's eps "device" doesn't support partial transparency, but, if I remember correctly, its PDF device does. Illustrator ought to be able to read PDFs with equal facility to EPSes, or if not, try converting them after generation with <code>pdftops</code> (<em>not</em> <code>pdf2ps</code>, they are totally different programs and pdf2ps's output is ... inferior).</p> <p>Note that R doesn't try to optimize its PDF output <em>at all</em>, so even if you do get a plot that needs no postproduction, you will want to run it through a compression utility like <code>qpdf</code> at the very least.</p>
3,612,378
can't multiply sequence by non-int of type 'float'
<p>Why do I get an error of &quot;can't multiply sequence by non-int of type 'float'&quot;? from the following code:</p> <pre><code>def nestEgVariable(salary, save, growthRates): SavingsRecord = [] fund = 0 depositPerYear = salary * save * 0.01 for i in growthRates: fund = fund * (1 + 0.01 * growthRates) + depositPerYear SavingsRecord += [fund,] return SavingsRecord print nestEgVariable(10000,10,[3,4,5,0,3]) </code></pre>
3,612,407
6
4
null
2010-08-31 19:15:48.673 UTC
7
2021-12-07 00:36:13.39 UTC
2021-12-07 00:36:13.39 UTC
null
1,727,948
user425727
null
null
1
57
python|floating-point|sequence
270,549
<pre><code>for i in growthRates: fund = fund * (1 + 0.01 * growthRates) + depositPerYear </code></pre> <p>should be:</p> <pre><code>for i in growthRates: fund = fund * (1 + 0.01 * i) + depositPerYear </code></pre> <p>You are multiplying 0.01 with the growthRates list object. Multiplying a list by an integer is valid (it's overloaded syntactic sugar that allows you to create an extended a list with copies of its element references).</p> <p>Example:</p> <pre><code>&gt;&gt;&gt; 2 * [1,2] [1, 2, 1, 2] </code></pre>
3,797,982
How to query abstract-class-based objects in Django?
<p>Let's say I have an abstract base class that looks like this:</p> <pre><code>class StellarObject(BaseModel): title = models.CharField(max_length=255) description = models.TextField() slug = models.SlugField(blank=True, null=True) class Meta: abstract = True </code></pre> <p>Now, let's say I have two actual database classes that inherit from StellarObject</p> <pre><code>class Planet(StellarObject): type = models.CharField(max_length=50) size = models.IntegerField(max_length=10) class Star(StellarObject): mass = models.IntegerField(max_length=10) </code></pre> <p>So far, so good. If I want to get Planets or Stars, all I do is this:</p> <pre><code>Thing.objects.all() #or Thing.objects.filter() #or count(), etc... </code></pre> <p>But what if I want to get ALL StellarObjects? If I do:</p> <pre><code>StellarObject.objects.all() </code></pre> <p>It of course returns an error, because an abstract class isn't an actual database object, and therefore cannot be queried. Everything I've read says I need to do two queries, one each on Planets and Stars, and then merge them. That seems horribly inefficient. Is that the only way?</p>
3,798,211
7
0
null
2010-09-26 13:29:36.493 UTC
11
2018-07-18 07:50:18.693 UTC
null
null
null
null
422,073
null
1
63
django|abstract-class
19,849
<p>At its root, this is part of the mismatch between objects and relational databases. The ORM does a great job in abstracting out the differences, but sometimes you just come up against them anyway.</p> <p>Basically, you have to choose between abstract inheritance, in which case there is no database relationship between the two classes, or multi-table inheritance, which keeps the database relationship at a cost of efficiency (an extra database join) for each query.</p>
3,692,738
Floating point versus fixed point: what are the pros/cons?
<p>Floating point type represents a number by storing its significant digits and its exponent separately on separate binary words so it fits in 16, 32, 64 or 128 bits.</p> <p>Fixed point type stores numbers with 2 words, one representing the integer part, another representing the part past the radix, in negative exponents, 2^-1, 2^-2, 2^-3, etc.</p> <p>Float are better because they have wider range in an exponent sense, but not if one wants to store number with more precision for a certain range, for example only using integer from -16 to 16, thus using more bits to hold digits past the radix.</p> <p>In terms of performances, which one has the best performance, or are there cases where some is faster than the other ?</p> <p>In video game programming, does everybody use floating point because the FPU makes it faster, or because the performance drop is just negligible, or do they make their own fixed type ?</p> <p>Why isn't there any fixed type in C/C++ ?</p>
3,692,789
8
6
null
2010-09-11 21:32:33.453 UTC
9
2016-07-29 11:14:35.267 UTC
2013-01-27 10:43:14.3 UTC
null
1,488,917
null
414,063
null
1
24
c++|c|processor|video-game-consoles
17,730
<p>That definition covers a very limited subset of fixed point implementations.</p> <p>It would be more correct to say that in fixed point only the mantissa is stored and the exponent is a constant determined a-priori. There is no requirement for the binary point to fall inside the mantissa, and definitely no requirement that it fall on a word boundary. For example, all of the following are "fixed point":</p> <ul> <li>64 bit mantissa, scaled by 2<sup>-32</sup> (this fits the definition listed in the question)</li> <li>64 bit mantissa, scaled by 2<sup>-33</sup> (now the integer and fractional parts cannot be separated by an octet boundary)</li> <li>32 bit mantissa, scaled by 2<sup>4</sup> (now there is no fractional part)</li> <li>32 bit mantissa, scaled by 2<sup>-40</sup> (now there is no integer part)</li> </ul> <p>GPUs tend to use fixed point with no integer part (typically 32-bit mantissa scaled by 2<sup>-32</sup>). Therefore APIs such as OpenGL and Direct3D often use floating-point types which are capable of holding these values. However, manipulating the integer mantissa is often more efficient so these APIs allow specifying coordinates (in texture space, color space, etc) this way as well.</p> <p>As for your claim that C++ doesn't have a fixed point type, I disagree. All integer types in C++ are fixed point types. The exponent is often assumed to be zero, but this isn't required and I have quite a bit of fixed-point DSP code implemented in C++ this way.</p>
7,965,135
What is the duration of a Toast LENGTH_LONG and LENGTH_SHORT
<p>I need the exact duration of LENGTH_LONG and LENGTH_SHORT in milliseconds (ms). Also I need to know if the duration of Toast message with LENGTH_LONG will have the same duration in any phone and with any API version.</p> <p>Does someone know where is the duration defined ?, I mean defined in ms . I know that LENGTH_LONG is some int const with value 1. But I could not find where is the actual duration defined.</p>
7,965,192
7
1
null
2011-11-01 10:26:24.697 UTC
8
2021-02-02 11:30:22.34 UTC
2016-02-09 13:54:58.097 UTC
null
895,245
null
706,780
null
1
111
android|time|toast|duration|milliseconds
76,763
<p>Answered <a href="https://stackoverflow.com/a/5079536/1993204">here</a>. Like you mentioned <code>Toast.LENGTH_SHORT</code> and <code>Toast.LENGTH_LONG</code> are not in ms but 0 or 1.</p> <p>The actual durations are:</p> <pre><code>private static final int LONG_DELAY = 3500; // 3.5 seconds private static final int SHORT_DELAY = 2000; // 2 seconds </code></pre>
8,173,622
Add ResourceDictionary to class library
<p>I created a class library which is contained of WPF Windows and some user controls inherited from my c# classes that helps me to customize certain wpf controls.</p> <p>Now I want to add ResourceDictionary, to help me share styles between my wpf classes. Is it possible?</p> <p>Thx.</p> <hr> <p>EDIT: resource dictionary file located in MY.WpfPresentation.Main project (named Styles.xaml):</p> <pre><code>&lt;ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:dxg="http://schemas.devexpress.com/winfx/2008/xaml/grid" xmlns:dxgt="http://schemas.devexpress.com/winfx/2008/xaml/grid/themekeys" xmlns:MYNetMisc="clr-namespace:MY.Net.Misc;assembly=MY.Net" &gt; &lt;Style x:Key="customRowStyle" BasedOn="{StaticResource {dxgt:GridRowThemeKey ResourceKey=RowStyle}}" TargetType="{x:Type dxg:GridRowContent}"&gt; &lt;Setter Property="Foreground" Value="{Binding Path=DataContext.balance, Converter={MYNetMisc:BalanceToColor OnlyNegative=false}}" /&gt; &lt;/Style&gt; &lt;/ResourceDictionary&gt; </code></pre> <p>using it:</p> <pre><code>&lt;MYNetPresentation:frmDockBase.Resources&gt; &lt;ResourceDictionary x:Key="style"&gt; &lt;ResourceDictionary.MergedDictionaries&gt; &lt;ResourceDictionary Source="pack://application:,,,/MY.WpfPresentation.Main;component/Styles.xaml" /&gt; &lt;/ResourceDictionary.MergedDictionaries&gt; &lt;/ResourceDictionary&gt; &lt;DataTemplate x:Key="TabTemplate"&gt; &lt;dxlc:LayoutControl Padding="0" ScrollBars="None" Background="Transparent"&gt; &lt;Image Source="/Images/Icons/table-32x32.png" Width="12" Height="12" /&gt; &lt;TextBlock Text="{Binding}" HorizontalAlignment="Left" VerticalAlignment="Center" /&gt; &lt;/dxlc:LayoutControl&gt; &lt;/DataTemplate&gt; &lt;/MYNetPresentation:frmDockBase.Resources&gt; </code></pre>
8,173,767
8
0
null
2011-11-17 20:12:05.177 UTC
9
2021-02-12 10:15:44.13 UTC
2011-11-17 22:02:29.15 UTC
null
935,836
null
935,836
null
1
28
c#|wpf|class-library|resourcedictionary
42,343
<p>create a resource dictionary like this one</p> <pre><code>&lt;ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&gt; &lt;ResourceDictionary&gt; &lt;ResourceDictionary.MergedDictionaries&gt; &lt;!-- Common base theme --&gt; &lt;ResourceDictionary Source="pack://application:,,,/Another.AssemblyName;component/YourResDictionaryFolder/OtherStyles.xaml" /&gt; &lt;ResourceDictionary Source="pack://application:,,,/Another.AssemblyName;component/YourResDictionaryFolder/AnotherStyles.xaml" /&gt; &lt;/ResourceDictionary.MergedDictionaries&gt; &lt;/ResourceDictionary&gt; &lt;!-- store here your styles --&gt; &lt;/ResourceDictionary&gt; </code></pre> <p>and you can put it where you want</p> <pre><code>&lt;Window x:Class="DragMoveForms.Window2" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window2" Height="300" Width="300"&gt; &lt;Window.Resources&gt; &lt;ResourceDictionary Source="pack://application:,,,/Your.Base.AssemblyName;component/YourResDictionaryFolder/Dictionary1.xaml" /&gt; &lt;/Window.Resources&gt; &lt;Grid&gt; &lt;/Grid&gt; &lt;/Window&gt; </code></pre>
8,227,481
Simple HTML Dom: How to remove elements?
<p>I would like to use Simple HTML DOM to remove all images in an article so I can easily create a small snippet of text for a news ticker but I haven't figured out how to remove elements with it. </p> <p>Basically I would do</p> <ol> <li>Get content as HTML string</li> <li>Remove all image tags from content</li> <li>Limit content to x words</li> <li>Output.</li> </ol> <p>Any help?</p>
8,227,616
10
0
null
2011-11-22 13:20:50.993 UTC
6
2022-06-27 03:04:37.793 UTC
2011-11-22 13:24:14.667 UTC
null
218,196
null
221,968
null
1
38
php|dom|simple-html-dom
51,884
<p>There is no dedicated methods for removing elements. You just find all the img elements and then do</p> <pre><code>$e-&gt;outertext = ''; </code></pre>
4,642,665
Why does capturing a mutable struct variable inside a closure within a using statement change its local behavior?
<p><strong>Update</strong>: Well, now I've gone and done it: I <a href="https://connect.microsoft.com/VisualStudio/feedback/details/635745" rel="nofollow noreferrer">filed a bug report with Microsoft</a> about this, as I seriously doubt that it is correct behavior. That said, I'm still not 100% sure what to believe regarding <a href="https://stackoverflow.com/questions/4662633">this question</a>; so I can see that what is "correct" is open to <em>some</em> level of interpretation.</p> <p>My feeling is that either Microsoft will accept that this is a bug, or else respond that the modification of a mutable value type variable within a <code>using</code> statement constitutes undefined behavior.</p> <p>Also, for what it's worth, I have at least a <em>guess</em> as to what is happening here. I suspect that the compiler is generating a class for the closure, "lifting" the local variable to an instance field of that class; and since it is within a <code>using</code> block, <strong>it's making the field <code>readonly</code></strong>. As LukeH pointed out in <a href="https://stackoverflow.com/questions/4662633/is-modifying-a-value-type-from-within-a-using-statement-undefined-behavior/4662740#4662740">a comment to the other question</a>, this would prevent method calls such as <code>MoveNext</code> from modifying the field itself (they would instead affect a copy).</p> <hr> <p><em>Note: I have shortened this question for readability, though it is still not exactly short. For the original (longer) question in its entirety, see the edit history.</em></p> <p>I have read through what I believe are the relevant sections of the ECMA-334 and cannot seem to find a conclusive answer to this question. I will state the question first, then provide a link to some additional comments for those who are interested.</p> <h2>Question</h2> <p>If I have a mutable value type that implements <code>IDisposable</code>, I can (1) call a method that modifies the state of the local variable's value within a <code>using</code> statement and the code behaves as I expect. Once I capture the variable in question inside a closure <em>within</em> the <code>using</code> statement, however, (2) modifications to the value are no longer visible in the local scope.</p> <p>This behavior is only apparent in the case where the variable is captured inside the closure <strong>and</strong> within a <code>using</code> statement; it is not apparent when only one (<code>using</code>) or the other condition (closure) is present.</p> <p><strong>Why does capturing a variable of a mutable value type inside a closure within a <code>using</code> statement change its local behavior?</strong></p> <p>Below are code examples illustrating items 1 and 2. Both examples will utilize the following demonstration <code>Mutable</code> value type:</p> <pre><code>struct Mutable : IDisposable { int _value; public int Increment() { return _value++; } public void Dispose() { } } </code></pre> <h3>1. Mutating a value type variable within a <code>using</code> block</h3> <pre><code>using (var x = new Mutable()) { Console.WriteLine(x.Increment()); Console.WriteLine(x.Increment()); } </code></pre> <p>The output code outputs:</p> <pre>0 1</pre> <h3>2. Capturing a value type variable inside a closure within a <code>using</code> block</h3> <pre><code>using (var x = new Mutable()) { // x is captured inside a closure. Func&lt;int&gt; closure = () =&gt; x.Increment(); // Now the Increment method does not appear to affect the value // of local variable x. Console.WriteLine(x.Increment()); Console.WriteLine(x.Increment()); } </code></pre> <p>The above code outputs:</p> <pre>0 0</pre> <h2>Further Comments</h2> <p>It has been noted that the Mono compiler provides the behavior I expect (changes to the value of the local variable are still visible in the <code>using</code> + closure case). Whether this behavior is correct or not is unclear to me.</p> <p>For some more of my thoughts on this issue, see <a href="http://philosopherdeveloper.wordpress.com/2011/01/11/further-comments-on-the-mutable-structclosureusing-issue/" rel="nofollow noreferrer">here</a>.</p>
4,688,670
4
12
null
2011-01-09 23:58:24.4 UTC
10
2011-01-14 06:56:20.143 UTC
2017-05-23 12:24:58.297 UTC
null
-1
null
105,570
null
1
20
.net|struct|closures|mutable|ienumerator
1,152
<p>It's a known bug; we discovered it a couple years ago. The fix would be potentially breaking, and the problem is pretty obscure; these are points against fixing it. Therefore it has never been prioritized high enough to actually fix it.</p> <p>This has been in my queue of potential blog topics for a couple years now; perhaps I ought to write it up.</p> <p>And incidentally, your conjecture as to the mechanism that explains the bug is completely accurate; nice psychic debugging there.</p> <p>So, yes, known bug, but thanks for the report regardless!</p>
4,704,969
Functional way of implementing domain driven design
<p>I've had a lot of experience with writing domain driven applications using C#. The more applications I write the more I find that I want to take an approach that doesn't fit that well with standard C#/OO techniques:</p> <ol> <li>I want to write as many pure functions as possible because they are really easy to test.</li> <li>I want to write my business logic in a more declarative fashion.</li> </ol> <p>So I've been looking at functional languages such as F#. After all there is no reason why domain driven design <em>has</em> to be implemented using OO.</p> <p>I was wondering if anyone has any ideas/experience with doing Domain driven design design whilst using a functional language. Especially:</p> <ul> <li>What would a functional domain model look like?</li> <li>How would you abstract the data access layer from the domain model.</li> </ul>
4,707,493
4
2
null
2011-01-16 11:12:40.093 UTC
13
2018-08-27 01:42:50.073 UTC
null
null
null
null
208,567
null
1
28
.net|f#|domain-driven-design
2,609
<p><em><strong>Disclaimer:</strong> I have only a vague knowledge about domain driven design, so the answer may not use the right terms and may be overly focused on code rather than general concepts, but here are some thoughts anyway...</em></p> <p>The focus on understanding the <em>domain</em> rather than designing specific features or objects to implement them seems very natural to how people use functional programming languages in general. Very often (at least in a part of a functional application) you start by designing data structure that describes (or models) the world you're working with. The data structure is separated from the implementation, so it nicely models the domain.</p> <p>A very nice example is described in <a href="http://research.microsoft.com/en-us/um/people/simonpj/papers/financial-contracts/contracts-icfp.htm" rel="noreferrer">paper about composing financial contracts</a>. The example is an application for valuation (and other processing) of financial contracts. The most important thing is to create model of the contracts - what are they actually? To answer that, the authors design a data structure for describing contracts. Something like:</p> <pre><code>type Contract = | Zero // No trades | Single of string * float // Single trade (buy something for some price) | And of Contract * Contract // Combine two contracts | Until of Contract * DateTime // Contract that can be executed only until... // (...) </code></pre> <p>There are a few other cases, but the data structure is very simple and models a wide range of pretty complex contracts that are used in the financial industry.</p> <p><strong>Summary</strong> I think the focus on data structures that are used to model the world (and are separated from the implementation that uses them) is very close to the key concepts of DDD.</p>
4,599,971
Algorithm For Ranking Items
<p>I have a list of 6500 items that I would like to trade or invest in. (Not for real money, but for a certain game.) Each item has 5 numbers that will be used to rank it among the others.</p> <p><strong>Total quantity of item traded per day:</strong> The higher this number, the better.</p> <p><strong>The Donchian Channel of the item over the last 5 days:</strong> The higher this number, the better.</p> <p><strong>The median spread of the price:</strong> The lower this number, the better.</p> <p><strong>The spread of the 20 day moving average for the item:</strong> The lower this number, the better.</p> <p><strong>The spread of the 5 day moving average for the item:</strong> The higher this number, the better.</p> <p>All 5 numbers have the same 'weight', or in other words, they should all affect the final number in the with the same worth or value.</p> <p>At the moment, I just multiply all 5 numbers for each item, but it doesn't rank the items the way I would them to be ranked. I just want to combine all 5 numbers into a weighted number that I can use to rank all 6500 items, but I'm unsure of how to do this correctly or mathematically.</p> <p>Note: The total quantity of the item traded per day and the donchian channel are numbers that are much higher then the spreads, which are more of percentage type numbers. This is probably the reason why multiplying them all together didn't work for me; the quantity traded per day and the donchian channel had a much bigger role in the final number.</p>
4,606,078
5
7
null
2011-01-05 01:02:30.347 UTC
10
2019-01-07 19:11:36.23 UTC
2019-01-07 19:11:36.23 UTC
null
10,849,397
null
559,495
null
1
11
algorithm|statistics|ranking
28,754
<p>The reason people are having trouble answering this question is we have no way of comparing two different "attributes". If there were just two attributes, say quantity traded and median price spread, would (20million,50%) be worse or better than (100,1%)? Only you can decide this.</p> <p>Converting everything into the same size numbers could help, this is what is known as "normalisation". A good way of doing this is the z-score which Prasad mentions. This is a statistical concept, looking at how the quantity varies. You need to make some assumptions about the statistical distributions of your numbers to use this.</p> <p>Things like spreads are probably <a href="http://en.wikipedia.org/wiki/Normal_distribution">normally distributed - shaped like a normal distribution</a>. For these, as Prasad says, take <code>z(spread) = (spread-mean(spreads))/standardDeviation(spreads)</code>.</p> <p>Things like the quantity traded might be a <a href="http://en.wikipedia.org/wiki/Power_law">Power law distribution</a>. For these you might want to take the <code>log()</code> before calculating the mean and sd. That is the z score is <code>z(qty) = (log(qty)-mean(log(quantities)))/sd(log(quantities))</code>.</p> <p>Then just add up the z-score for each attribute.</p> <p>To do this for each attribute you will need to have an idea of its distribution. You could guess but the best way is plot a graph and have a look. You might also want to plot graphs on log scales. See <a href="http://en.wikipedia.org/wiki/List_of_probability_distributions">wikipedia for a long list</a>. </p>
4,586,557
php send email with attachment
<p>How to send the email with resume attachment ,</p> <p>i take snippet from this place <a href="http://www.weberdev.com/get_example-4595.html">Click here</a> </p> <p>In this site, snippet works fine,</p> <p>Even i got the mail, but attachment is not working, am getting attment as noname with 0kb </p> <p>size file, What is Issue in that snippet ,</p>
4,586,659
5
2
null
2011-01-03 17:09:36.673 UTC
11
2013-05-10 23:35:22.177 UTC
2012-07-12 08:26:05.54 UTC
null
367,456
null
246,963
null
1
14
php
31,370
<pre><code> function mail_attachment($to, $subject, $message, $from, $file) { // $file should include path and filename $filename = basename($file); $file_size = filesize($file); $content = chunk_split(base64_encode(file_get_contents($file))); $uid = md5(uniqid(time())); $from = str_replace(array("\r", "\n"), '', $from); // to prevent email injection $header = "From: ".$from."\r\n" ."MIME-Version: 1.0\r\n" ."Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n" ."This is a multi-part message in MIME format.\r\n" ."--".$uid."\r\n" ."Content-type:text/plain; charset=iso-8859-1\r\n" ."Content-Transfer-Encoding: 7bit\r\n\r\n" .$message."\r\n\r\n" ."--".$uid."\r\n" ."Content-Type: application/octet-stream; name=\"".$filename."\"\r\n" ."Content-Transfer-Encoding: base64\r\n" ."Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n" .$content."\r\n\r\n" ."--".$uid."--"; return mail($to, $subject, "", $header); } </code></pre>
4,354,722
How to fix the height of a <div> element?
<p>I've defined my div's height in a stylesheet:</p> <pre><code>.topbar{ width:100%; height:70px; background-color:#475; } </code></pre> <p>But as soon as text is entered into the div, the divs height changes. </p> <p>Any ideas?</p>
4,354,745
5
1
null
2010-12-04 17:12:59.853 UTC
8
2021-10-19 10:08:51.107 UTC
2017-07-17 14:20:41.35 UTC
null
2,427,065
null
530,588
null
1
39
css|html
204,312
<p>change the div to display block </p> <pre><code>.topbar{ display:block; width:100%; height:70px; background-color:#475; overflow:scroll; } </code></pre> <p>i made a jsfiddle example here please check</p> <p><a href="http://jsfiddle.net/TgPRM/" rel="noreferrer">http://jsfiddle.net/TgPRM/</a></p>
4,709,076
How to enable gzip?
<p>I have found a couple of tutorials on how to enable gzip, but nothing seems to be working for me, so my question is how do i enable gzip. I am on a shared Dreamhost hosting server, It is running PHP version 5.2, and Apache, from the php info i have found this line, maybe this could help?</p> <pre><code>zlib ZLib Support enabled Stream Wrapper support compress.zlib:// Stream Filter support zlib.inflate, zlib.deflate Compiled Version 1.2.3.3 Linked Version 1.2.3.3 Directive Local Value Master Value zlib.output_compression Off Off zlib.output_compression_level -1 -1 zlib.output_handler no value no value </code></pre> <p>I have also found this line</p> <pre><code>_SERVER["HTTP_ACCEPT_ENCODING"] gzip, deflate </code></pre> <p>I don't know if that has anything to do with it. But that is my first question, secondly, i have dropbox, hosting a javscript file, and I am wondering is it possible to have that file gzipped, It is not being transfered compressed, so is ther any way to do so?</p>
4,709,107
6
1
null
2011-01-17 00:32:56.7 UTC
13
2020-07-10 07:24:48.78 UTC
2018-04-13 12:00:07.547 UTC
null
3,903,902
null
476,412
null
1
36
php|apache|.htaccess|gzip
85,287
<p>Have you tried with <a href="http://php.net/manual/en/function.ob-gzhandler.php" rel="noreferrer">ob_gzhandler</a>?</p> <pre><code>&lt;?php ob_start(&quot;ob_gzhandler&quot;); ?&gt; &lt;html&gt; &lt;body&gt; &lt;p&gt;This should be a compressed page.&lt;/p&gt; &lt;/html&gt; &lt;body&gt; </code></pre> <p>As an alternative, with the Apache web server, you can add <a href="https://httpd.apache.org/docs/current/mod/mod_deflate.html#recommended" rel="noreferrer">a DEFLATE output filter</a> to your top-level server configuration, or to a <code>.htaccess</code> file:</p> <pre><code>&lt;IfModule mod_deflate.c&gt; AddOutputFilterByType DEFLATE text/text text/html text/plain text/xml \ text/css application/x-javascript application/javascript &lt;/IfModule&gt; </code></pre> <p>Tip: Sometimes it is pretty tricky to detect if the web server is sending compressed content or not. <a href="https://www.whatsmyip.org/http-compression-test/" rel="noreferrer">This online tool</a> can help with that.</p> <p>Using the developer tools in my web browser, I tested a PHP file with and without compression to compare the size. In my case, the difference was 1 MB (non-compressed) and 56 KB compressed.</p>
4,257,545
How can I check in JavaScript if a DOM element contains a class?
<p>How can I check in JavaScript if a DOM element contains a class?</p> <p>I tried the following code, but for some reason it doesn't work...</p> <pre><code>if (document.getElementById('element').class == "class_one") { //code... } </code></pre>
4,257,563
8
1
null
2010-11-23 15:18:40.713 UTC
7
2022-04-14 11:13:32 UTC
2022-04-11 22:19:28.77 UTC
null
1,946,501
null
496,965
null
1
23
javascript|html|css|dom|htmlelements
56,643
<p>To get the whole value of the class atribute, use <code>.className</code></p> <p><a href="https://developer.mozilla.org/en/DOM/element.classname" rel="noreferrer">From MDC:</a> </p> <blockquote> <p>className gets and sets the value of the class attribute of the specified element.</p> </blockquote> <h1>Since 2013, you get an extra helping hand.</h1> <p>Many years ago, when this question was first answered, <code>.className</code> was the only <em>real</em> solution in pure JavaScript. Since 2013, <a href="http://caniuse.com/#search=classlist" rel="noreferrer">all browsers support</a> <code>.classList</code> interface.</p> <p>JavaScript:</p> <pre><code>if(document.getElementById('element').classList.contains("class_one")) { //code... } </code></pre> <p>You can also do fun things with <code>classList</code>, like <code>.toggle()</code>, <code>.add()</code> and <code>.remove()</code>.</p> <p><a href="https://developer.mozilla.org/en-US/docs/Web/API/Element.classList" rel="noreferrer">MDN documentation</a>.</p> <p>Backwards compatible code:</p> <pre><code>if(document.getElementById('element').className.split(" ").indexOf("class_one") &gt;= 0) { //code... } </code></pre>
4,627,940
How to detect if a video file was recorded in portrait orientation, or landscape in iOS
<p>I am using <code>AlAssetsGroup enumerateAssetsAtIndexes</code> to list the assets in the Photos (Camera) app. For a given video asset I want to determine whether it was shot in portrait or landscape mode. </p> <p>In the following code, asset is an <code>AlAsset</code> and I have tested to see if it is a video asset <code>[asset valueForProperty:ALAssetPropertyType]</code> is <code>AlAssetTypeVideo</code>, then:</p> <pre><code>int orientation = [[asset valueForProperty:ALAssetPropertyOrientation] intValue]; </code></pre> <p>In this case <code>orientation</code> is always 0 which is <code>ALAssetOrientationUp</code>. Maybe this is to be expected, all videos are up right, but a portrait video is represented in MPEG-4 as a landscape video turned 90 degrees (i.e. all videos are actually landscape, try the MediaInfo app on the mac if you don't believe me). </p> <p>Where within the file and/or how do I access the information that tells me it was actually recorded while holding the phone in portrait orientation?</p> <p>I have also tried this, given the url of the asset:</p> <pre><code>AVURLAsset *avAsset = [[AVURLAsset alloc] initWithURL:url options:nil]; CGSize size = [avAsset naturalSize]; NSLog(@"size.width = %f size.height = %f", size.width, size.height); CGAffineTransform txf = [avAsset preferredTransform]; NSLog(@"txf.a = %f txf.b = %f txf.c = %f txf.d = %f txf.tx = %f txf.ty = %f", txf.a, txf.b, txf.c, txf.d, txf.tx, txf.ty); </code></pre> <p>Which always yields a width > height so for iPhone 4, width=1280 height=720 and the transform a and d values are <code>1.0</code>, the others are <code>0.0</code>, regardless of the capture orientation.</p> <p>I have looked at the meta data using MediaInfo app on the Mac, I have done a Hexdump and so far have not found any difference between a landscape and portrait video. But QuickTime knows and displays portrait videos vertically, and the phone knows by rotating a portrait video if you are holding the phone in landscape orientation on playback and correctly displaying it if holding it in portrait.</p> <p>BTW I can't use <code>ffmpeg</code> (can't live with the license restrictions). Is there an iPhone SDK native way to do this?</p>
4,684,110
8
0
null
2011-01-07 16:46:03.937 UTC
21
2020-07-22 15:51:58.863 UTC
2017-09-15 16:18:57.503 UTC
null
1,000,551
null
567,194
null
1
32
ios|objective-c|video-processing|video-encoding
29,481
<p>Somebody on apple dev forums suggested getting the transform of the video track, this does the job. You can see from the logs below that for these orientations the results make sense and our web developer is now able to rotate a variety of vids so they all match and composite them into one video.</p> <pre><code>AVAssetTrack* videoTrack = [[avAsset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0]; CGSize size = [videoTrack naturalSize]; NSLog(@"size.width = %f size.height = %f", size.width, size.height); CGAffineTransform txf = [videoTrack preferredTransform]; NSLog(@"txf.a = %f txf.b = %f txf.c = %f txf.d = %f txf.tx = %f txf.ty = %f", txf.a, txf.b, txf.c, txf.d, txf.tx, txf.ty); </code></pre> <p>Logs using 4 iPhone 4 videos with the normal cam: (1) landscape cam on right side (home button on left) (2) landscape left (3) portrait upside-down (4) portrait up-right (home button at bottom)</p> <blockquote> <ol> <li><p>2011-01-07 20:07:30.024 MySecretApp[1442:307] size.width = 1280.000000 size.height = 720.000000 2011-01-07 20:07:30.027 MySecretApp[1442:307] txf.a = -1.000000 txf.b = 0.000000 txf.c = 0.000000 txf.d = -1.000000 txf.tx = 1280.000000 txf.ty = 720.000000</p></li> <li><p>2011-01-07 20:07:45.052 MySecretApp[1442:307] size.width = 1280.000000 size.height = 720.000000 2011-01-07 20:07:45.056 MySecretApp[1442:307] txf.a = 1.000000 txf.b = 0.000000 txf.c = 0.000000<br> txf.d = 1.000000 txf.tx = 0.000000<br> txf.ty = 0.000000</p></li> <li><p>2011-01-07 20:07:53.763 MySecretApp[1442:307] size.width = 1280.000000 size.height = 720.000000 2011-01-07 20:07:53.766 MySecretApp[1442:307] txf.a = 0.000000 txf.b = -1.000000 txf.c = 1.000000<br> txf.d = 0.000000 txf.tx = 0.000000 txf.ty = 1280.000000</p></li> <li><p>2011-01-07 20:08:03.490 MySecretApp[1442:307] size.width = 1280.000000 size.height = 720.000000 2011-01-07 20:08:03.493 MySecretApp[1442:307] txf.a = 0.000000 txf.b = 1.000000 txf.c = -1.000000<br> txf.d = 0.000000 txf.tx = 720.000000 txf.ty = 0.000000</p></li> </ol> </blockquote>
4,233,605
Elegant way to get the count of months between two dates?
<p>Let's assume I have two dates in variables, like</p> <pre><code>$date1 = &quot;2009-09-01&quot;; $date2 = &quot;2010-05-01&quot;; </code></pre> <p>I need to get the count of months between <code>$date2</code> and <code>$date1</code>(<code>$date2 &gt;= $date1</code>). I.e. i need to get <code>8</code>.</p> <p>Is there a way to get it by using <a href="http://php.net/manual/en/function.date.php" rel="nofollow noreferrer">date</a> function, or I have to explode my strings and do required calculations?</p> <p>Thanks.</p>
4,233,624
10
0
null
2010-11-20 15:59:11.913 UTC
19
2020-07-04 19:18:09.087 UTC
2020-07-04 19:18:09.087 UTC
null
291,772
null
291,772
null
1
64
php|date
87,293
<p>For PHP >= 5.3</p> <pre><code>$d1 = new DateTime("2009-09-01"); $d2 = new DateTime("2010-05-01"); var_dump($d1-&gt;diff($d2)-&gt;m); // int(4) var_dump($d1-&gt;diff($d2)-&gt;m + ($d1-&gt;diff($d2)-&gt;y*12)); // int(8) </code></pre> <p>DateTime::diff returns a <a href="http://ca3.php.net/manual/en/class.dateinterval.php">DateInterval</a> object</p> <p>If you don't run with PHP 5.3 or higher, I guess you'll have to use unix timestamps :</p> <pre><code>$d1 = "2009-09-01"; $d2 = "2010-05-01"; echo (int)abs((strtotime($d1) - strtotime($d2))/(60*60*24*30)); // 8 </code></pre> <p>But it's not very precise (there isn't always 30 days per month).</p> <p>Last thing : if those dates come from your database, then use your DBMS to do this job, not PHP.</p> <p><strong>Edit:</strong> This code should be more precise if you can't use DateTime::diff or your RDBMS :</p> <pre><code>$d1 = strtotime("2009-09-01"); $d2 = strtotime("2010-05-01"); $min_date = min($d1, $d2); $max_date = max($d1, $d2); $i = 0; while (($min_date = strtotime("+1 MONTH", $min_date)) &lt;= $max_date) { $i++; } echo $i; // 8 </code></pre>
4,457,030
How to show the text on a ImageButton?
<p>I have an <code>ImageButton</code> and I want to show a text and an image on it. But when I try on emulator:</p> <pre><code>&lt;ImageButton android:text="OK" android:id="@+id/buttonok" android:src="@drawable/buttonok" android:layout_width="match_parent" android:layout_height="wrap_content" /&gt; </code></pre> <p>I get the image but without the text. How can I show the text? Please help me!</p>
4,457,063
12
0
null
2010-12-16 02:46:03.573 UTC
31
2020-12-06 19:25:37.37 UTC
2018-09-06 10:57:43.777 UTC
null
4,853,133
null
502,214
null
1
138
android|imagebutton
231,584
<p>As you can't use <code>android:text</code> I recommend you to use a normal button and use one of the compound drawables. For instance:</p> <pre><code>&lt;Button android:id="@+id/buttonok" android:layout_width="match_parent" android:layout_height="wrap_content" android:drawableLeft="@drawable/buttonok" android:text="OK"/&gt; </code></pre> <p>You can put the drawable wherever you want by using: <code>drawableTop</code>, <code>drawableBottom</code>, <code>drawableLeft</code> or <code>drawableRight</code>.</p> <p><strong>UPDATE</strong></p> <p>For a button this too works pretty fine. Putting <code>android:background</code> is fine!</p> <pre><code>&lt;Button android:id="@+id/fragment_left_menu_login" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/button_bg" android:text="@string/login_string" /&gt; </code></pre> <p>I just had this issue and is working perfectly.</p>
14,864,971
How do I create my own completion handler as part of method parameters
<p>I want to create a completion handler for a certain class, instead of firing off the class's main code and waiting for a delegate callback. I've read through the Apple documentation and they don't seem to give a very good example of how to directly implement something like this. </p>
14,865,037
4
0
null
2013-02-13 23:04:32.203 UTC
18
2016-07-30 09:52:23.363 UTC
null
null
null
null
2,070,259
null
1
26
ios|objective-c
22,566
<p>You need to treat the completion block just like a variable. The method will accept a block as part of it's parameters, then store it for later. </p> <p><code>- (void)myMethodWithCompletionHandler:(void (^)(id, NSError*))handler;</code></p> <p>You can typedef that block type for easier reading: </p> <p><code>typedef void (^CompletionBlock)(id, NSError*);</code></p> <p>And then store your block as an instance variable:</p> <p>In your @interface: <code>CompletionBlock _block;</code></p> <p>In the myMethod.. <code>_block = [handler copy]</code></p> <p>Then when you want the completion block to execute you just call it like a regular block:</p> <p><code>_block(myData, error);</code></p>
14,545,978
How to change the background color for changed files in eclipse project explorer?
<p>Changed files under version control are displayed with a dark brown background in the project explorer, making the file names unreadable. I would like to change it.</p> <p><img src="https://i.stack.imgur.com/vtqdX.png" alt="the brown"></p> <p>I have switched between several color themes, but they don't affect the colors in the project explorer. I have not found any useful options neither in the <code>General-&gt;Appearance-&gt;Colors&amp;Fonts</code> menu nor in the <code>Team-&gt;Git</code> menu.</p> <p>The right-click on the colored filename does not offer an option to change color, as it does when used inside the editor.</p> <p>I am using eclipse 3.7 SR2 with EGit.</p> <p>EDIT: I can confirm that it is the git decorator providing the colors - once I switch it off (General->Appearance->Label decorators), the brown color is gone.</p>
14,548,965
2
1
null
2013-01-27 09:11:28.583 UTC
10
2014-04-27 04:54:25.257 UTC
2013-01-27 10:58:24.93 UTC
null
216,021
null
216,021
null
1
27
eclipse|colors|egit|color-scheme
17,834
<p>The settings you want are under <em>Preferences</em> > <em>General</em> > <em>Appearance</em> > <em>Colors and Fonts</em>, look for the section "<strong>Git</strong>" in the list and under there, "Uncommitted Change (Background)" and "Uncommitted Change (Foreground)." <img src="https://i.stack.imgur.com/zuND3.png" alt="enter image description here"></p> <p>I edited those settings to be a light blue background with white foreground and this is what a changed file looks like in my Project/Package Explorers:</p> <p><img src="https://i.stack.imgur.com/9k7IC.png" alt="enter image description here"></p>
14,583,018
Knockout 'flickering' issue
<p>I'm building a SPA (Single Page Application) using KO. the application looks like a book and the user can flip pages.</p> <p>The problem is that every time a page loads, there is a short moment where the page 'flickers' and the user sees the unstyled version of the page. I guess this is caused due to the fact that a lot of the styling is dependant on ko bindings so until ko finishes it 'magic' the user gets a glimpse of the unstyled code.</p> <p>Is it possible to tell when KO finished all its bindings and only then show the page? </p> <p>I've managed to partially solve it by setting a timeout before loading the view but of course this is not a good solution.</p>
14,588,728
2
1
null
2013-01-29 12:34:10.617 UTC
8
2013-11-01 19:27:36.377 UTC
null
null
null
null
812,303
null
1
32
javascript|knockout.js|singlepage|single-page-application
7,190
<p>Yes, it is very easy actually. Apply <code>display:none</code> to the top level <code>div</code> (or w/e container), and <code>data-bind="visible: true"</code>. This will cause the page to be hidden until knockout unhides it via binding (which obviously can't happen until its fully loaded).</p> <p>Since you are using a non-observable value, Knockout won't even bother to re-check this again. There shouldn't be a performance concern after the initial binding.</p>
2,614,242
Show blank UITableViewCells in custom UITableView
<p>I am trying to customize a UITableView. So far, it looks good. But when I use a custom UITableViewCell sub-class, I do not get the blank table cells when there's only 3 cells:</p> <p><a href="http://img193.imageshack.us/img193/2450/picture1zh.png">alt text http://img193.imageshack.us/img193/2450/picture1zh.png</a></p> <p>Using the default TableView style I can get the repeating blank rows to fill the view (for example, the mail application has this). I tried to set a backgroundColor pattern on the UITableView to the same tile background:</p> <pre><code>UIColor *color = [UIColor colorWithPatternImage:[UIImage imageNamed:@"score-cell-bg.png"]]; moneyTableView.backgroundColor = color; </code></pre> <p>...but the tile starts a bit before the TableView's top, so the tile is off once the actual cell's are done displaying:</p> <p><a href="http://img707.imageshack.us/img707/8445/picture2jyo.png">alt text http://img707.imageshack.us/img707/8445/picture2jyo.png</a></p> <p>How can I customize my tableview but still keep the blank rows if there's less rows than fill a page?</p>
2,614,312
2
2
null
2010-04-10 17:30:57.843 UTC
10
2010-04-10 18:14:54.103 UTC
null
null
null
null
53,653
null
1
12
iphone|uitableview
11,182
<p>Did you by chance remove the background color and separator style? If you did, that could be why there are no extra cells. I would think the default UITableView doesn't add more cells really, it just has the separator style to create that illusion and because it has a white background, they look like cells.</p> <pre><code>- (void)viewDidLoad { [super viewDidLoad]; self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone; } </code></pre> <p>If that's not the case, you could always try adding extra cells that can't be selected:</p> <pre><code>- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return ([source count] &lt;= 7) ? 7 : [source count]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; } // Set all labels to be blank if([source count] &lt;= 7 &amp;&amp; indexPath.row &gt; [source count]) { cell.textLabel.text = @""; cell.selectionStyle = UITableViewCellSelectionStyleNone; } else { cell.textLabel.text = [source objectAtIndex:indexPath.row]; cell.selectionStyle = UITableViewCellSelectionStyleBlue; } return cell; } </code></pre>
41,202,233
How can I use if statement in ejs?
<p>I have a page that makes a foreach and show some photos like this</p> <pre><code>&lt;% imgs.forEach(function(img) { %&gt; &lt;img src="uploads/&lt;%=user.username%&gt;/screenshots/&lt;%= img %&gt;"&gt; &lt;% }); %&gt; </code></pre> <p>And I want make a if statement because, in case that not photos to show gives a message like this:</p> <blockquote> <p>"no photos uploaded"</p> </blockquote>
41,202,290
4
0
null
2016-12-17 19:24:13.667 UTC
5
2022-07-17 08:39:28.973 UTC
2016-12-17 23:42:56.387 UTC
null
472,495
null
6,053,835
null
1
18
javascript|html|node.js|express|ejs
40,040
<p>Something like this:</p> <pre><code>&lt;% if(imgs.length &gt; 0){ %&gt; &lt;% imgs.forEach(function(img) { %&gt; &lt;img src="uploads/&lt;%=user.username%&gt;/screenshots/&lt;%= img %&gt;"&gt; &lt;% }); %&gt; &lt;% } else{ %&gt; &lt;p&gt;no photos uploaded&lt;/p&gt; &lt;% } %&gt; </code></pre> <p><a href="https://stackoverflow.com/questions/8216918/can-i-use-conditional-statements-with-ejs-templates-in-jmvc">Reference</a></p>
42,436,370
Executing powershell command directly in jenkins pipeline
<p>Is it possible to call a PowerShell command directly in the pipelines groovy script? While using custom jobs in Jenkins I am able to call the command with the PowerShell Plugin. But there is no snippet to use this in the groovy script.</p> <p>I also tried <code>sh()</code> but it seems that this command does not allow multiple lines and comments inside the command.</p>
42,576,572
4
0
null
2017-02-24 10:31:58.713 UTC
12
2020-12-10 15:48:49.98 UTC
null
null
null
null
5,422,075
null
1
21
powershell|jenkins|jenkins-plugins|jenkins-pipeline
63,080
<p>To call a PowerShell script from the Groovy-Script:</p> <ul> <li>you have to use the <code>bat</code> command.</li> <li>After that, you have to be sure that the Error Code (<code>errorlevel</code>) variable will be correctly returned (<code>EXIT 1</code> should resulting in a <code>FAILED</code> job).</li> <li>Last, to be compatible with the PowerShell-Plugin, you have to be sure that <code>$LastExitCode</code> will be considered.</li> <li>I have notice that the 'powershell' is now available in pipeline, but since it have several issues I prefer this variant. Still waiting it works stabil. I actually have an issue with the 'dontKillMe' behavior.</li> </ul> <blockquote> <p>Since Jenkins 2.207 with Powershell plugin 1.4, I have replace all my calls with the official powershell pipeline command. I do now recommend to use it. Note that you must predent <code>\$ErrorActionPreference='Stop';</code> to your Script if you want it to abort on Write-Error because of <a href="https://issues.jenkins.io/browse/JENKINS-36002" rel="nofollow noreferrer">an Issue with the powershell plugin</a>.</p> </blockquote> <p>For that porpuse I have written a little groovy method which could be integrate in any pipeline-script:</p> <pre><code>def PowerShell(psCmd) { psCmd=psCmd.replaceAll(&quot;%&quot;, &quot;%%&quot;) bat &quot;powershell.exe -NonInteractive -ExecutionPolicy Bypass -Command \&quot;\$ErrorActionPreference='Stop';[Console]::OutputEncoding=[System.Text.Encoding]::UTF8;$psCmd;EXIT \$global:LastExitCode\&quot;&quot; } </code></pre> <p><em>[EDIT] I have added the UTF8 OutputEncoding: works great with Server 2016 and Win10.[/EDIT]</em> <em>[EDIT] I have added the '%' mask[/EDIT]</em></p> <p>In your Pipeline-Script you could then call your Script like this:</p> <pre><code>stage ('Call Powershell Script') { node ('MyWindowsSlave') { PowerShell(&quot;. '.\\disk-usage.ps1'&quot;) } } </code></pre> <p>The best thing with that method, is that you may call <code>CmdLet</code> without having to do this in the Script, which is best-praxis.</p> <p>Call ps1 to define <code>CmdLet</code>, an then call the <code>CmdLet</code></p> <pre><code>PowerShell(&quot;. '.\\disk-usage.ps1'; du -Verbose&quot;) </code></pre> <ul> <li>Do not forget to use <a href="https://www.cloudbees.com/blog/top-10-best-practices-jenkins-pipeline-plugin" rel="nofollow noreferrer">withEnv()</a> an then you are better than fully compatible with the Powershell plugin.</li> <li>postpone your Script with <code>.</code> to be sure your step failed when the script return an error code (should be preferred), use <code>&amp;</code> if you don't care about it.</li> </ul>
27,766,623
How to store routes in separate files when using Hapi?
<p>All of the Hapi examples (and similar in Express) shows routes are defined in the starting file:</p> <pre><code>var Hapi = require('hapi'); var server = new Hapi.Server(); server.connection({ port: 8000 }); server.route({ method: 'GET', path: '/', handler: function (request, reply) { reply('Hello, world!'); } }); server.route({ method: 'GET', path: '/{name}', handler: function (request, reply) { reply('Hello, ' + encodeURIComponent(request.params.name) + '!'); } }); server.start(function () { console.log('Server running at:', server.info.uri); }); </code></pre> <p>However, it's not hard to image how large this file can grow when implementing production application with a ton of different routes. Therefore I would like to break down routes, group them and store in separate files, like UserRoutes.js, CartRoutes.js and then attach them in the main file (add to server object). How would you suggest to separate that and then add? </p>
27,767,658
7
0
null
2015-01-04 14:40:53.24 UTC
22
2019-11-13 21:16:41.213 UTC
2015-01-04 16:28:25.097 UTC
null
775,443
null
597,292
null
1
59
node.js|routes|hapi.js
25,413
<p>You can create a separate file for user routes (<code>config/routes/user.js</code>):</p> <pre><code>module.exports = [ { method: 'GET', path: '/users', handler: function () {} }, { method: 'GET', path: '/users/{id}', handler: function () {} } ]; </code></pre> <p>Similarly with cart. Then create an index file in <code>config/routes</code> (<code>config/routes/index.js</code>):</p> <pre><code>var cart = require('./cart'); var user = require('./user'); module.exports = [].concat(cart, user); </code></pre> <p>You can then load this index file in the main file and call <code>server.route()</code>:</p> <pre><code>var routes = require('./config/routes'); ... server.route(routes); </code></pre> <p>Alternatively, for <code>config/routes/index.js</code>, instead of adding the route files (e.g. <code>cart</code>, <code>user</code>) manually, you can load them dynamically:</p> <pre><code>const fs = require('fs'); let routes = []; fs.readdirSync(__dirname) .filter(file =&gt; file != 'index.js') .forEach(file =&gt; { routes = routes.concat(require(`./${file}`)) }); module.exports = routes; </code></pre>
29,059,530
Is there any way to generate the same UUID from a String
<p>I am wondering if there is a way to generate the same UUID based on a <code>String.</code> I tried with UUID, it looks like it does not provide this feature.</p>
29,059,595
4
0
null
2015-03-15 10:19:02.803 UTC
19
2022-01-11 17:26:34.28 UTC
2019-01-30 10:56:33.597 UTC
null
545,127
null
1,136,700
null
1
109
java|uuid
98,580
<p>You can use UUID this way to get always the same UUID for your input String:</p> <pre><code> String aString="JUST_A_TEST_STRING"; String result = UUID.nameUUIDFromBytes(aString.getBytes()).toString(); </code></pre>
29,474,673
Passing a number to a component
<p>I am trying to pass a number to a React component but it is getting parsed as string (<a href="http://jsfiddle.net/utj7qprh/2/" rel="noreferrer">jsfiddle</a>). How do I make React understand that I am passing a number? Should I cast the string to a number in the component?</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 Rectangle = React.createClass({ render: function() { return &lt;div&gt; &lt;div&gt;{this.props.intValue + 10}&lt;/div&gt; &lt;div&gt;{this.props.stringValue + 10}&lt;/div&gt; &lt;/div&gt;; } }); React.render(&lt;Rectangle intValue="10" stringValue="Hello" /&gt; , document.getElementById('container'));</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://facebook.github.io/react/js/jsfiddle-integration.js"&gt;&lt;/script&gt; &lt;div id="container"&gt; &lt;!-- This element's contents will be replaced with your component. --&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
29,474,674
2
0
null
2015-04-06 15:52:11.427 UTC
6
2020-08-03 13:29:31.047 UTC
2015-04-06 16:43:28.183 UTC
null
64,046
null
126,574
null
1
46
javascript|reactjs
42,101
<p>It seems that in case of integers (and actually for strings as well) I should be passing the numbers via <code>{}</code> like so:</p> <p><code>React.render(&lt;Rectangle intValue={10} stringValue={"Hello"} /&gt;, document.getElementById('container'));</code></p>
31,971,256
How to convert a Swift object to a dictionary
<p>I'm relatively new to iOS programming. However, I would have assumed that Swift would have an automated way of converting objects to JSON and vice versa. That being said, I have found several libraries that can do this.</p> <p>HOWEVER...</p> <p>It seems that no matter how you post data to a web service (even using something like AlamoFire), the requests must be a dictionary. All these forums show examples of how easy it is to convert the returned JSON string to objects. True. But the request needs to be manually coded. That is, go through all of the object properties and map them as a dictionary.</p> <p>So my question is this: Am I missing something? Have I got this all wrong and there's a super-easy way to either (a) send JSON (instead of a dictionary) in the REQUEST or (b) convert an object automatically to a dictionary?</p> <p>Again, I see how easy it is to deal with a JSON response. I'm just looking for an automatic way to convert the request object I want to post to a web service into a format that a library like AlamoFire (or whatever) requires. With other languages this is fairly trivial, so I'm hoping there's an equally easy and automated way with Swift.</p>
31,976,110
7
0
null
2015-08-12 16:58:03.65 UTC
7
2022-02-21 10:41:03.977 UTC
null
null
null
null
3,965,322
null
1
37
json|swift|dictionary|service|alamofire
35,360
<p>Swift currently does not support advanced reflection like Java or C# so the answer is: no, there is not an equally easy and automated way with pure Swift.</p> <p>[Update] Swift 4 has meanwhile the <code>Codable</code> protocol which allows serializing to/from JSON and PLIST.</p> <pre><code>typealias Codable = Decodable &amp; Encodable </code></pre>
25,948,511
When to use "if" and "when" in Clojure?
<p>When is one better than the other? Is one faster than the other or does the only difference is the return of false or nil?</p>
25,948,588
3
0
null
2014-09-20 11:56:38.257 UTC
5
2022-05-14 22:53:14.453 UTC
2017-09-07 18:33:17.37 UTC
null
3,924,118
null
1,998,149
null
1
40
if-statement|clojure
11,114
<p>Use <code>if</code> when you have exactly one truthy and one falsy case and you don't need an implicit <code>do</code> block. In contrast, <code>when</code> should be used when you only have to handle the truthy case and the implicit <code>do</code>. There is no difference in speed, it's a matter of using the most idiomatic style.</p> <pre><code> (if (my-predicate? my-data) (do-something my-data) (do-something-else my-data)) (when (my-predicate? my-data) (do-something my-data) (do-something-additionally my-data)) </code></pre> <p>In the <code>if</code> case, only <code>do-something</code> will be run if <code>my-predicate?</code> returns a truthy result, whereas in the <code>when</code> case, both <code>do-something</code> and <code>do-something-additionally</code> are executed.</p>
22,743,663
In Android/Gradle how to define a task that only runs when building specific buildType/buildVariant/productFlavor (v0.10+)
<p>Android Plugin for Gradle generates for every BuilType/Flavor/BuildVariant a task. The problem is that this task will be generated dynamically and thus won't be available as a dependency when defining a task like this:</p> <pre><code>task myTaskOnlyForDebugBuildType(dependsOn:assembleDebug) { //do smth } </code></pre> <p>A proposed workaround from this <a href="https://stackoverflow.com/a/19598746/774398">answer</a> would be this</p> <pre><code>task myTaskOnlyForDebugBuildType(dependsOn:"assembleDebug") { //do smth } </code></pre> <p>or this</p> <pre><code>afterEvaluate { task myTaskOnlyForDebugBuildType(dependsOn:assembleDebug) { //do smth } } </code></pre> <p>But both didn't work for me.</p>
22,743,664
4
0
null
2014-03-30 11:54:07.8 UTC
13
2017-03-13 10:12:30.913 UTC
2017-05-23 12:26:35.83 UTC
null
-1
null
774,398
null
1
30
android|gradle|android-gradle-plugin
23,409
<p><strong>Here is a full example on how to do this <a href="http://www.jayway.com/2013/02/26/using-gradle-for-building-android-applications/" rel="noreferrer">inspired by this post</a>:</strong> <em>(android plugin v.0.9.2 and gradle 1.11 at the time of writing)</em></p> <p>We are going to define a task that only runs when we build a "debugCustomBuildType"</p> <pre><code>android { ... buildTypes { debugCustomBuildType { //config } } } </code></pre> <p>Define the task that should only be executed on a specific builtType/variant/flavor</p> <pre><code>task doSomethingOnWhenBuildDebugCustom { doLast { //task action } } </code></pre> <p>Dynamically set the dependency when the tasks are added by gradle</p> <pre><code>tasks.whenTaskAdded { task -&gt; if (task.name == 'generateDebugCustomBuildTypeBuildConfig') { task.dependsOn doSomethingOnWhenBuildDebugCustom } } </code></pre> <p>Here we use the "generateBuildConfig" task, but you can use any task that works for you (<a href="http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Manipulating-tasks" rel="noreferrer">also see official docs</a>)</p> <ul> <li>processManifest</li> <li>aidlCompile</li> <li>renderscriptCompile</li> <li>mergeResourcess.</li> <li>mergeAssets</li> <li>processResources</li> <li>generateBuildConfig</li> <li>javaCompile</li> <li>processJavaResources </li> <li>assemble</li> </ul> <p>Don't forget to use the buildTypeSpecific task (<code>generateBuildConfig</code> vs. <code>generateDebugCustomBuildTypeBuildConfig</code>)</p> <p>And that's it. It's a shame this workaround isn't well documented because for me this seems like one of the simplest requirements for a build script.</p>
40,529,817
Reactive Forms - mark fields as touched
<p>I am having trouble finding out how to mark all form's fields as touched. The main problem is that if I do not touch fields and try to submit form - validation error in not shown up. I have placeholder for that piece of code in my controller.<br> My idea is simple: </p> <ol> <li>user clicks submit button</li> <li>all fields marks as touched</li> <li>error formatter reruns and displays validation errors</li> </ol> <p>If anyone have other idea how to show errors on submit, without implementing new method - please share them. Thanks!</p> <hr> <p><strong>My simplified form:</strong></p> <pre class="lang-html prettyprint-override"><code>&lt;form class="form-horizontal" [formGroup]="form" (ngSubmit)="onSubmit(form.value)"&gt; &lt;input type="text" id="title" class="form-control" formControlName="title"&gt; &lt;span class="help-block" *ngIf="formErrors.title"&gt;{{ formErrors.title }}&lt;/span&gt; &lt;button&gt;Submit&lt;/button&gt; &lt;/form&gt; </code></pre> <p><strong>And my controller:</strong></p> <pre class="lang-js prettyprint-override"><code>import {Component, OnInit} from '@angular/core'; import {FormGroup, FormBuilder, Validators} from '@angular/forms'; @Component({ selector : 'pastebin-root', templateUrl: './app.component.html', styleUrls : ['./app.component.css'] }) export class AppComponent implements OnInit { form: FormGroup; formErrors = { 'title': '' }; validationMessages = { 'title': { 'required': 'Title is required.' } }; constructor(private fb: FormBuilder) { } ngOnInit(): void { this.buildForm(); } onSubmit(form: any): void { // somehow touch all elements so onValueChanged will generate correct error messages this.onValueChanged(); if (this.form.valid) { console.log(form); } } buildForm(): void { this.form = this.fb.group({ 'title': ['', Validators.required] }); this.form.valueChanges .subscribe(data =&gt; this.onValueChanged(data)); } onValueChanged(data?: any) { if (!this.form) { return; } const form = this.form; for (const field in this.formErrors) { if (!this.formErrors.hasOwnProperty(field)) { continue; } // clear previous error message (if any) this.formErrors[field] = ''; const control = form.get(field); if (control &amp;&amp; control.touched &amp;&amp; !control.valid) { const messages = this.validationMessages[field]; for (const key in control.errors) { if (!control.errors.hasOwnProperty(key)) { continue; } this.formErrors[field] += messages[key] + ' '; } } } } } </code></pre>
44,150,793
20
1
null
2016-11-10 14:19:49.383 UTC
15
2022-08-02 12:43:04.967 UTC
2020-05-10 18:41:55.453 UTC
null
5,377,805
null
6,156,929
null
1
126
angular|angular-reactive-forms|angular2-forms|angular2-formbuilder
160,242
<p>The following function recurses through controls in a form group and gently touches them. Because the control's field is an object, the code call <code>Object.values()</code> on the form group's control field.</p> <pre class="lang-js prettyprint-override"><code> /** * Marks all controls in a form group as touched * @param formGroup - The form group to touch */ private markFormGroupTouched(formGroup: FormGroup) { (&lt;any&gt;Object).values(formGroup.controls).forEach(control =&gt; { control.markAsTouched(); if (control.controls) { this.markFormGroupTouched(control); } }); } </code></pre>
2,752,574
What's the "DNS_BLOCK_ASSERTIONS" (C compiler flag)?
<p>What's the "DNS_BLOCK_ASSERTIONS" (C compiler flag)?</p>
2,752,581
1
1
null
2010-05-02 05:51:29.427 UTC
7
2011-07-14 01:39:44.523 UTC
null
null
null
null
246,776
null
1
42
c|compiler-flags
8,337
<p>The NS_BLOCK_ASSERTIONS macro (no "D") suppresses the checks performed by NSAssert. You supply it to the compiler using <code>-DNS_BLOCK_ASSERTIONS</code> (see the comments for an explanation of the "D").</p>
37,575,368
Angular dynamic background images
<p>In the html template I have this style with a dynamic image:</p> <pre><code>&lt;div style="background: url('/img/{{item.img}}'); width: 200px; height: 150px"&gt;&lt;/div&gt; </code></pre> <p>Which works in web browsers and android browser. However background images that are dynamic using "style=" are not showing on iPad. </p> <p>I could always create dynamic images using the img tag but I'm looking for a style/css solution for iPad.</p>
37,575,497
4
0
null
2016-06-01 17:37:46.8 UTC
10
2021-04-20 11:28:26.863 UTC
2018-11-25 15:50:16.89 UTC
null
4,155,124
null
4,155,124
null
1
42
css|ipad|angular|styles
73,819
<p>Use instead</p> <pre><code>&lt;div [ngStyle]="{background: 'url(/img/' + item.img + ')', width: '200px', height: '150px'"&gt;&lt;/div&gt; </code></pre> <p>or</p> <pre><code>&lt;div [style.background]="'url(/img/' + item.img + ')'" [style.width.px]="200" [style.height.px]="150p"&gt;&lt;/div&gt; </code></pre> <p>See also <a href="https://stackoverflow.com/questions/37076867/in-rc-1-some-styles-cant-be-added-using-binding-syntax/37233523#37233523">In RC.1 some styles can&#39;t be added using binding syntax</a></p>
38,540,481
Return value by lambda in Java
<p>Till now I manage to find all answers I need but this one confusing me. Let's say we have example code:</p> <pre><code>public class Animal { private String species; private boolean canHop; private boolean canSwim; public Animal(String speciesName, boolean hopper, boolean swimmer) { species = speciesName; canHop = hopper; canSwim = swimmer; } public boolean canHop() { return canHop; } public boolean canSwim() { return canSwim; } public String toString() { return species; } } public interface CheckAnimal { public boolean test(Animal a); } public class FindSameAnimals { private static void print(Animal animal, CheckAnimal trait) { if(trait.test(animal)){ System.out.println(animal); } public static void main(String[] args) { print(new Animal("fish", false, true), a -&gt; a.canHop()); } } </code></pre> <p>OCA Study Guide (Exam 1Z0-808) book says that these two lines are equivalent:</p> <pre><code>a -&gt; a.canHop() (Animal a) -&gt; { return a.canHop(); } </code></pre> <p>Does this mean that, behind the scenes, Java adds keyword <strong><em>return</em></strong> to code in the first case?</p> <p>If answer is YES then how next code compile (imagine everything else is in proper place):</p> <pre><code>static int counter = 0; ExecutorService service = Executors.newSingleThreadExecutor(); service.execute(() -&gt; counter++)); </code></pre> <p>if we know that signatures for <em>execute</em> and Runnable's <em>run</em> are:</p> <pre><code>void execute(Runnable command) void run() </code></pre> <p>If answer is NO then how Java know when it need to return something and when not to? Maybe in</p> <pre><code>a -&gt; a.canHop() </code></pre> <p>case we wanted to ignore <em>boolean</em> return type of method.</p>
38,540,546
3
2
null
2016-07-23 09:59:56.977 UTC
3
2016-07-23 10:21:00.92 UTC
null
null
null
null
5,950,177
null
1
15
java|lambda|runnable
70,890
<blockquote> <p>Does this mean that, behind the scenes, Java adds keyword return to code in the first case?</p> </blockquote> <p>No, The compiler generates byte code, and it might generate the same byte code but it doesn't change the syntax and then compile it again.</p> <blockquote> <p>we wanted to ignore boolean return type of method.</p> </blockquote> <p>It has the option of ignoring a value based on what functional interfaces it is considering.</p> <pre><code>a -&gt; a.canHop() </code></pre> <p>could be</p> <pre><code>(Animal a) -&gt; { return a.canHop(); } </code></pre> <p>or</p> <pre><code>(Animal a) -&gt; { a.canHop(); } </code></pre> <p>based on context, however it favours the first if possible.</p> <p>Consider <code>ExecutorService.submit(Callable&lt;T&gt;)</code> and <code>ExecutorService.submit(Runnable)</code></p> <pre><code>ExecutorService es = Executors.newSingleThreadExecutor(); es.execute(() -&gt; counter++); // has to be Runnable es.submit(() -&gt; counter++); // Callable&lt;Integer&gt; or Runnable? </code></pre> <p>Saving the return type you can see it's a <code>Callable&lt;Integer&gt;</code></p> <pre><code>final Future&lt;Integer&gt; submit = es.submit(() -&gt; counter++); </code></pre> <hr> <p>To try yourself, here is a longer example.</p> <pre><code>static int counter = 0; public static void main(String[] args) throws ExecutionException, InterruptedException { ExecutorService es = Executors.newSingleThreadExecutor(); // execute only takes Runnable es.execute(() -&gt; counter++); // force the lambda to be Runnable final Future&lt;?&gt; submit = es.submit((Runnable) () -&gt; counter++); System.out.println(submit.get()); // returns a value so it's a Callable&lt;Integer&gt; final Future&lt;Integer&gt; submit2 = es.submit(() -&gt; counter++); System.out.println(submit2.get()); // returns nothing so it must be Runnable final Future&lt;?&gt; submit3 = es.submit(() -&gt; System.out.println("counter: " + counter)); System.out.println(submit3.get()); es.shutdown(); } </code></pre> <p>prints</p> <pre><code>null 2 counter: 3 null </code></pre> <p>The first <code>submit</code> take a <code>Runnable</code> so <code>Future.get()</code> returns <code>null</code></p> <p>The second <code>submit</code> defaults to being a <code>Callable</code> so <code>Future.get()</code> returns <code>2</code></p> <p>The third <code>submit</code> can only be a <code>void</code> return value so it must be a <code>Runnable</code> so <code>Future.get()</code> returns <code>null</code></p>
31,617,345
What is the ASP.NET Core MVC equivalent to Request.RequestURI?
<p>I found a <a href="http://www.strathweb.com/2015/01/migrating-asp-net-web-api-mvc-6-exploring-web-api-compatibility-shim/" rel="noreferrer">blog post</a> that shows how to "shim" familiar things like HttpResponseMessage back into ASP.NET Core MVC, but I want to know what's the new native way to do the same thing as the following code in a REST Post method in a Controller:</p> <pre><code>// POST audit/values [HttpPost] public System.Net.Http.HttpResponseMessage Post([FromBody]string value) { var NewEntity = _repository.InsertFromString(value); var msg = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Created); msg.Headers.Location = new Uri(Request.RequestUri + NewEntity.ID.ToString()); return msg; } </code></pre> <p>In an ASP.NET Core MVC project, I can't seem to get Request.RequestUri. </p> <p>I tried inspecting Request, and I was able to make a function like this:</p> <pre><code>private string UriStr(HttpRequest Request) { return Request.Scheme + "://" + Request.Host + Request.Path; // Request.Path has leading / } </code></pre> <p>So I could write <code>UriStr(Request)</code> instead. But I'm not sure that's right. I feel like I'm hacking my way around, and not using this correctly.</p> <p>A <a href="https://stackoverflow.com/questions/7413466/how-can-i-get-the-baseurl-of-site">related question</a> for earlier non-Core ASP.NET MVC versions asks how to get the base url of the site.</p>
31,618,160
3
0
null
2015-07-24 18:26:07.533 UTC
8
2020-09-11 08:18:18.177 UTC
2017-07-06 15:35:21.627 UTC
null
3,792,634
null
84,704
null
1
48
c#|asp.net|asp.net-core-mvc
38,282
<p>A cleaner way would be to use a <code>UriBuilder</code>:</p> <pre><code>private static Uri GetUri(HttpRequest request) { var builder = new UriBuilder(); builder.Scheme = request.Scheme; builder.Host = request.Host.Value; builder.Path = request.Path; builder.Query = request.QueryString.ToUriComponent(); return builder.Uri; } </code></pre> <p>(not tested, the code might require a few adjustments)</p>
6,014,520
Copying a stream in Python
<p>How do I transfer the contents of a stream to another in Python?</p> <p>The trivial solution would be</p> <pre><code>output.write(input.read()) </code></pre> <p>but that fails if the input file is larger than the available memory (or even infinitely large); and it doesn't work well when a partial copy is useful as well. Basically I'm looking for the equivalent of <a href="http://commons.apache.org/io/apidocs/org/apache/commons/io/IOUtils.html#copy%28java.io.InputStream,%20java.io.OutputStream%29"><code>org.apache.commons.IOUtils.copy</code></a>.</p>
6,014,540
1
0
null
2011-05-16 07:54:56.207 UTC
2
2011-05-16 08:06:29.01 UTC
null
null
null
null
35,070
null
1
34
python|io
14,240
<p><code>shutil.copyfile</code> and <code>shutil.copyfileobj</code> for the rescue. See <a href="http://docs.python.org/library/shutil.html#module-shutil">http://docs.python.org/library/shutil.html#module-shutil</a></p>
5,616,421
increment map<string, int> using ++ operator
<p>I have a map to count the occurrence of words in a file. I am reading words from the file, and each time I read a word I want to do this:</p> <pre><code>map[word]++; //(where map is the name of my map, I'm not using map as a name of course) </code></pre> <p>so that if the my map already has 'word' as a key, it increments it, otherwise it creates the new key and increments it.</p> <p>Here's where I am concerned: if I do map[word]++ on a new key (which is unavoidable in the first word read), will my program crash because the int in my map is unitialized? If so, what's the most efficient way of telling my map: if the word is already there, do ++ on the value, otherwise, create the new key with value = 1? Using an if statement with 'map.find' here seems unnecessarily redundant, what do you think?</p> <p>Thanks</p>
5,616,434
1
0
null
2011-04-11 03:11:21.037 UTC
12
2020-02-11 14:17:23.817 UTC
null
null
null
null
666,956
null
1
62
c++|map|operators
26,268
<blockquote> <p>will my program crash because the int in my map is unitialized?</p> </blockquote> <p>No; if the element with key <code>word</code> doesn't exist, the element will be created and value initialized. A value-initialized <code>int</code> has a value of <code>0</code>.</p>
7,259,511
Increase a ProgressBar with Timer in WinForms
<p>I have a timer with an interval of 1 minute and I would like to increase a progress bar in parallel with it. I'm using Winforms and C#. How can I do this ?</p> <p>Help me please</p>
7,259,769
1
0
null
2011-08-31 15:34:12.023 UTC
3
2012-06-27 20:27:21.09 UTC
2011-08-31 16:50:20.183 UTC
null
190,327
null
921,936
null
1
2
c#|winforms|visual-studio-2010
68,265
<p>Here is an example of how to use the <code>Timer</code> control with a progress bar. First, create a new <code>Timer</code> and a <code>ProgressBar</code>. then, start the time when the form is loaded, using this function:</p> <pre><code>timer1.Enabled = true; // Enable the timer. timer1.Start();//Strart it timer1.Interval = 1000; // The time per tick. </code></pre> <p>Then, create an event for the tick, as shown:</p> <pre><code>timer1.Tick += new EventHandler(timer1_Tick); </code></pre> <p>Create the event's function:</p> <pre><code>void timer1_Tick(object sender, EventArgs e) { throw new NotImplementedException(); } </code></pre> <p>After this, add code to the tick function that adds value to the progress bar, similar to this:</p> <pre><code>progressBar1.Value++; </code></pre> <p>Don't forget to set a maximum value for the progress bar, which you can do by adding this code to the <code>form_load</code> function:</p> <pre><code>progressBar1.Maximum = 10; // 10 is an arbitrary maximum value for the progress bar. </code></pre> <p>Also, don't forget to check the maximum value so your timer will stop. You can stop the timer with this code:</p> <pre><code>timer1.Stop(); </code></pre> <p>Full Code:</p> <pre><code>public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { timer1.Enabled = true; timer1.Start(); timer1.Interval = 1000; progressBar1.Maximum = 10; timer1.Tick += new EventHandler(timer1_Tick); } void timer1_Tick(object sender, EventArgs e) { if (progressBar1.Value != 10) { progressBar1.Value++; } else { timer1.Stop(); } } } </code></pre>
21,349,475
Calendar.getInstance(TimeZone.getTimeZone("UTC")) is not returning UTC time
<p>I am really confused with the result I am getting with <code>Calendar.getInstance(TimeZone.getTimeZone("UTC"))</code> method call, it's returning IST time. </p> <p>Here is the code I used </p> <pre><code>Calendar cal_Two = Calendar.getInstance(TimeZone.getTimeZone("UTC")); System.out.println(cal_Two.getTime()); </code></pre> <p>and the response I got is:</p> <pre><code>Sat Jan 25 15:44:18 IST 2014 </code></pre> <p>So I tried changing the default TimeZone to UTC and then I checked, then it is working fine</p> <pre><code>Calendar cal_Two = Calendar.getInstance(TimeZone.getTimeZone("UTC")); System.out.println(cal_Two.getTime()); TimeZone tz = TimeZone.getDefault() ; TimeZone.setDefault(TimeZone.getTimeZone("UTC")); Calendar cal_Three = Calendar.getInstance(); System.out.println(cal_Three.getTime()); TimeZone.setDefault(tz); </code></pre> <p>Result:</p> <pre><code>Sat Jan 25 16:09:11 IST 2014 Sat Jan 25 10:39:11 UTC 2014 </code></pre> <p>Am I missing something here?</p>
21,349,556
7
0
null
2014-01-25 10:41:23.607 UTC
18
2020-10-10 10:23:58.81 UTC
2017-10-12 19:38:35.583 UTC
null
3,885,376
null
1,228,301
null
1
121
java
204,485
<p>The <code>System.out.println(cal_Two.getTime())</code> invocation returns a <code>Date</code> from <code>getTime()</code>. It is the <code>Date</code> which is getting converted to a string for <code>println</code>, and that conversion will use the default <code>IST</code> timezone in your case.</p> <p>You'll need to explicitly use <code>DateFormat.setTimeZone()</code> to print the <code>Date</code> in the desired timezone.</p> <p>EDIT: Courtesy of @Laurynas, consider this:</p> <pre><code>TimeZone timeZone = TimeZone.getTimeZone("UTC"); Calendar calendar = Calendar.getInstance(timeZone); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EE MMM dd HH:mm:ss zzz yyyy", Locale.US); simpleDateFormat.setTimeZone(timeZone); System.out.println("Time zone: " + timeZone.getID()); System.out.println("default time zone: " + TimeZone.getDefault().getID()); System.out.println(); System.out.println("UTC: " + simpleDateFormat.format(calendar.getTime())); System.out.println("Default: " + calendar.getTime()); </code></pre>
7,225,045
HTTP PUT Request with Node.js
<p>I'm trying to figure out how to make an HTTP PUT request with node.js. I've tried a lot of different things, but can't get it working.</p> <p>The idea is to have a method for putting the file, eg:</p> <pre><code>function putFile(file_path, callback) { // Put the file } </code></pre> <p>Any help would be appreciated.</p>
7,225,102
1
0
null
2011-08-29 00:38:55.133 UTC
2
2011-08-29 01:18:14.2 UTC
null
null
null
null
401,019
null
1
14
node.js
62,796
<p>Here is an example which sends a <code>POST</code> request: <a href="http://nodejs.org/docs/v0.4.11/api/http.html#http.request" rel="nofollow noreferrer">http://nodejs.org/docs/v0.4.11/api/http.html#http.request</a> , basically you just have to change it to <code>PUT</code>.</p> <p>You could open your file using <a href="http://nodejs.org/docs/v0.4.11/api/fs.html#fs.createReadStream" rel="nofollow noreferrer">createReadStream()</a> and <a href="http://nodejs.org/docs/v0.4.11/api/all.html#stream.pipe" rel="nofollow noreferrer">pipe()</a> it to the response object.</p> <p>Here is another <a href="https://stackoverflow.com/questions/6158933/http-post-request-in-node-js/6158966#6158966">example</a> which uses <code>readFile()</code>, the problem with that is that the whole file is loaded into memory, so better use <code>createReadStream()</code> and <code>pipe()</code> if the files are large.</p>
22,791,170
Purpose of EF 6.x DbContext Generator option when adding a new data item in Visual Studio
<p>I have a web app that I built using LINQ to SQL and I'm looking to upgrade it to LINQ to Entity Framework. I've looked at some tutorials and what I've learned is that basically in the database-first scenario, you create an ADO.NET Entity Data Model. And from there, you select which tables to include in the model (very similar to LINQ to SQL).</p> <p>Within the <strong>Add New Item</strong> dialog, I see that there is another option that creates an <strong>EF 6.x DbContext Generator</strong>:</p> <p><img src="https://i.stack.imgur.com/75vuC.png" alt="Visual Studio Add New Item dialog"></p> <p>What is the purpose of <strong>EF 6.x DbContext Generator</strong> compared to <strong>ADO.NET Entity Data Model</strong> (first option in dialog)? And, what is <strong>EF 6.x DbContext Generator</strong> for? It seems to create a text file. What should I do with it?</p>
22,957,529
5
0
null
2014-04-01 16:07:47.697 UTC
10
2018-11-02 13:50:32.007 UTC
2018-11-02 13:50:32.007 UTC
null
1,497,596
null
565,968
null
1
65
c#|asp.net|entity-framework|linq|linq-to-sql
46,228
<p>If you already have a database, the first option is better, given that the approach is very similar to the one you are already working in LinqToSQL. The .EDMX file also can provide you a graphical visualization of your database, and you don't have to worry about anything else.</p>
22,025,476
What is "swappable" in model meta for?
<p>Looking tough django auth models code, I came across this bit of code:</p> <pre><code>class User(AbstractUser): class Meta(AbstractUser.Meta): swappable = 'AUTH_USER_MODEL' </code></pre> <p>It's obvious that it has something to do with the new <code>AUTH_USER_MODEL</code> setting in settings.py, but how does it actually work, by what python "trick"?</p> <p>And in what other situations can it be used?</p>
24,921,458
2
0
null
2014-02-25 20:29:27.53 UTC
8
2014-07-23 21:35:15.027 UTC
2014-02-25 21:03:34.587 UTC
null
236,195
null
236,195
null
1
29
django|django-models|django-users|django-settings
10,527
<p><strong>swappable</strong> is an "intentionally undocumented" feature which is currently under development / in-test. It's used to handle "I have a base abstract model which has some foreign-key relationships." Slightly more detail is available from <a href="https://code.djangoproject.com/ticket/19103">Django's ticketing system</a> and <a href="https://github.com/wq/django-swappable-models">github</a>. Because it's a "stealth alpha" feature, it's not guaranteed to work (for anything other than User), and understanding the detailed operation will likely require diving into source code. It works with <strong>AUTH_USER_MODEL</strong> because the User model and <strong>swappable</strong> flag were developed together, specifically for each other.</p>
21,936,503
Get empty string when null
<p>I want to get string values of my fields (they can be type of long string or any object),</p> <p>if a field is null then it should return empty string, I did this with guava;</p> <pre><code>nullToEmpty(String.valueOf(gearBox)) nullToEmpty(String.valueOf(id)) ... </code></pre> <p>But this returns null if gearbox is null! Not empty string because valueOf methdod returns string "null" which leads to errors.</p> <p>Any Ideas?</p> <p>EDIt: there are 100s fields I look for something easy to implement</p>
21,936,577
8
0
null
2014-02-21 13:59:17.77 UTC
17
2021-01-29 12:49:27.577 UTC
2019-03-14 07:14:32.403 UTC
null
4,203,152
null
379,028
null
1
104
java|guava
138,301
<p>You can use <a href="http://docs.oracle.com/javase/7/docs/api/java/util/Objects.html#toString%28java.lang.Object,%20java.lang.String%29"><code>Objects.toString()</code></a> (standard in Java 7):</p> <pre><code>Objects.toString(gearBox, "") Objects.toString(id, "") </code></pre> <hr> <p>From the linked documentation:</p> <blockquote> <p><code>public static String toString(Object o, String nullDefault)</code></p> <blockquote> <p>Returns the result of calling <code>toString</code> on the first argument if the first argument is not null and returns the second argument otherwise.</p> <p><strong>Parameters:</strong><br> <code>o</code> - an object<br> <code>nullDefault</code> - string to return if the first argument is <code>null</code></p> <p><strong>Returns:</strong><br> the result of calling <code>toString</code> on the first argument if it is not <code>null</code> and the second argument otherwise.</p> <p><strong>See Also:</strong><br> <a href="http://docs.oracle.com/javase/7/docs/api/java/util/Objects.html#toString%28java.lang.Object%29"><code>toString(Object)</code></a></p> </blockquote> </blockquote>
2,752,319
Android - Simulate Home click
<p>I know calling finish() in activity will produce same result as if user clicked on Back button; is there a similar thing for Home button? (would like to automatically show Home screen after certain action).</p> <p>EDIT: Also, I would appreciate same thing for Menu &amp; Search buttons.</p> <p>Thanks!</p>
2,752,749
4
0
null
2010-05-02 03:13:18.723 UTC
10
2016-06-09 10:17:52.063 UTC
2010-05-05 21:22:41.017 UTC
null
237,858
null
237,858
null
1
28
android
18,303
<p>You can simply use an Intent for that:</p> <pre><code>Intent i = new Intent(Intent.ACTION_MAIN); i.addCategory(Intent.CATEGORY_HOME); startActivity(i); </code></pre>
2,792,675
How portable is mktemp(1)?
<p>As the title suggests — can I be reasonably sure that <code>mktemp</code> will exist on any unix-y operating system I'm likely to encounter?</p>
2,792,789
4
1
null
2010-05-08 02:15:45.617 UTC
11
2018-02-06 07:03:05.687 UTC
null
null
null
null
71,522
null
1
32
shell|portability
6,497
<p>POSIX does not seem to specify <em>mktemp(1)</em>.</p> <p>It looks like most modern systems have it, but the available functionality and the semantics of the options vary between implementations (so particular invocations may not be portable):</p> <ul> <li><a href="http://man.openbsd.org/mktemp.1" rel="noreferrer"><em>mktemp(1)</em> from OpenBSD</a> — <em>mktemp(1)</em> originated in OpenBSD 2.1</li> <li><a href="http://www.freebsd.org/cgi/man.cgi?query=mktemp" rel="noreferrer"><em>mktemp(1)</em> from FreeBSD</a></li> <li><a href="http://developer.apple.com/mac/library/DOCUMENTATION/Darwin/Reference/ManPages/man1/mktemp.1.html" rel="noreferrer"><em>mktemp(1)</em> from Mac OS X</a> — almost always the same as from FreeBSD</li> <li><a href="http://www.mktemp.org/manual.html" rel="noreferrer"><em>mktemp(1)</em> from Todd C. Miller</a> of sudo fame</li> <li><a href="http://docs.oracle.com/cd/E23823_01/html/816-5165/mktemp-1.html#scrolltoc" rel="noreferrer" title="mktemp(1) - Solaris 10 man pages section 1: User Commands"><em>mktemp(1)</em> from Solaris</a></li> <li><a href="http://www.gnu.org/software/coreutils/manual/html_node/mktemp-invocation.html#mktemp-invocation" rel="noreferrer"><em>mktemp(1)</em> from GNU coreutils</a></li> <li><a href="https://docstore.mik.ua/manuals/hp-ux/en/B2355-60130/mktemp.1.html" rel="noreferrer"><em>mktemp(1)</em> from HP/UX</a> — this one seems particularly divergent from most of the others listed here</li> </ul> <p>So if you want a portable solution you may need to stick to functionality and options that mean the same thing on all of your platforms of interest.</p>
2,819,245
Is std::pair<int, std::string> ordering well-defined?
<p>It seems that I can sort a <code>std::vector&lt;std::pair&lt;int, std::string&gt;&gt;</code>, and it will sort based on the int value. Is this a well defined thing to do?</p> <p>Does <code>std::pair</code> have a default ordering based on its elements?</p>
2,819,287
4
0
null
2010-05-12 13:35:23.247 UTC
5
2019-05-10 23:19:05.113 UTC
2019-05-10 23:19:05.113 UTC
null
1,848,654
null
212,865
null
1
38
c++|sorting|stl
17,502
<p><code>std::pair</code> uses lexicographic comparison: It will compare based on the first element. If the values of the first elements are equal, it will then compare based on the second element.</p> <p>The definition in the C++03 standard (section 20.2.2) is:</p> <pre><code>template &lt;class T1, class T2&gt; bool operator&lt;(const pair&lt;T1, T2&gt;&amp; x, const pair&lt;T1, T2&gt;&amp; y); Returns: x.first &lt; y.first || (!(y.first &lt; x.first) &amp;&amp; x.second &lt; y.second). </code></pre>
2,483,205
MySQL - how long to create an index?
<p>Can anyone tell me how adding a key scales in MySQL? I have 500,000,000 rows in a database, trans, with columns i (INT UNSIGNED), j (INT UNSIGNED), nu (DOUBLE), A (DOUBLE). I try to index a column, e.g.</p> <pre><code>ALTER TABLE trans ADD KEY idx_A (A); </code></pre> <p>and I wait. For a table of 14,000,000 rows it took about 2 minutes to execute on my MacBook Pro, but for the whole half a billion, it's taking 15hrs and counting. Am I doing something wrong, or am I just being naive about how indexing a database scales with the number of rows?</p>
2,486,278
4
1
null
2010-03-20 13:35:56.24 UTC
10
2018-02-20 14:18:14.95 UTC
null
null
null
null
293,594
null
1
46
mysql|indexing
35,359
<p>There are a couple of factors to consider:</p> <ul> <li>Sorting is a N.log(N) operation.</li> <li>The sort for 14M rows might well fit in main memory; the sort with 500M rows probably doesn't, so the sort spills to disk, which slows things up enormously.</li> </ul> <p>Since the factor is about 30 in size, the nominal sort time for the big data set would be of the order of 50 times as long - under two hours. However, you need 8 bytes per data value and about another 8 bytes of overhead (that's a guess - tune to mySQL if you know more about what it stores in an index). So, 14M × 16 ≈ 220 MB main memory. But 500M × 16 ≈ 8 GB main memory. Unless your machine has that much memory to spare (and MySQL is configured to use it), then the big sort is spilling to disk and that accounts for a lot of the rest of the time.</p>
2,539,796
C, reading multiple numbers from single input line (scanf?)
<p>I have written an app in C which expects two lines at input. First input tells how big an array of int will be and the second input contains values separated by space. For example, the following input</p> <pre><code>5 1 2 3 4 99 </code></pre> <p>should create an array containing <code>{1,2,3,4,99}</code></p> <p>What is the fastest way to do so? My problem is to read multiple numbers without looping through the whole string checking if it's space or a number?</p> <p>Thanks.</p>
2,539,843
5
0
null
2010-03-29 17:05:27.527 UTC
7
2017-06-18 09:31:12.693 UTC
2013-04-22 17:22:33.17 UTC
null
2,105,110
null
146,248
null
1
9
c|c99|scanf
68,166
<pre><code>int i, size; int *v; scanf("%d", &amp;size); v = malloc(size * sizeof(int)); for(i=0; i &lt; size; i++) scanf("%d", &amp;v[i]); </code></pre> <p>Remember to <code>free(v)</code> after you are done!</p> <p>Also, if for some reason you already have the numbers in a string, you can use <code>sscanf()</code></p>
31,953,317
What is the purpose of a db context class in asp.net mvc
<p>I'm new to MVC and have done some tutorials to get the hang of it, but in some of these tutorials I have come across an example with a DbContext class <a href="https://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application" rel="noreferrer">asp.net mvc5 with EF6 tutorial</a></p> <p>I have tried researching information on DbContext Class but was unable to get any information that made me any the wiser! all I could find are more of the same tutorials with little information I also looked up the class on msdn <a href="https://msdn.microsoft.com/en-us/library/system.data.entity.dbcontext(v=VS.103).aspx" rel="noreferrer">DbContext Class</a>.</p> <p>I have done previous tutorials without a db context class and it works fine and my question is do I need to use a context class, and what are the advantages of using a DbContext Class?</p> <p>Any help would be appreciated thanks.</p>
31,953,580
5
0
null
2015-08-11 22:53:05.3 UTC
7
2019-08-02 14:54:27.663 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
5,162,579
null
1
26
c#|asp.net-mvc|entity-framework
45,512
<p>I would first say that the <code>DbContext</code> class relates to <a href="https://msdn.microsoft.com/en-us/data/ef.aspx" rel="noreferrer">Entity Framework (EF)</a>, but then the question tags would suggest you figured that much out yourself. In typical usage, deriving from the <code>DbContext</code> class is simply <em>the way</em> to incorporate EF-based data access into your application. The class that derives from <code>DbContext</code> is, in essence, the data access layer of your application.</p> <p>So to put it the other way around, if you want to do data access with Entity Framework, <code>DbContext</code> is what you want.</p>
56,858,924
Multivariate input LSTM in pytorch
<p>I would like to <strong>implement</strong> LSTM for multivariate input <strong>in Pytorch</strong>. </p> <p>Following this article <a href="https://machinelearningmastery.com/how-to-develop-lstm-models-for-time-series-forecasting/" rel="noreferrer">https://machinelearningmastery.com/how-to-develop-lstm-models-for-time-series-forecasting/</a> which uses keras, the input data are in shape of (number of samples, number of timesteps, number of parallel features)</p> <pre><code>in_seq1 = array([10, 20, 30, 40, 50, 60, 70, 80, 90]) in_seq2 = array([15, 25, 35, 45, 55, 65, 75, 85, 95]) out_seq = array([in_seq1[i]+in_seq2[i] for i in range(len(in_seq1))]) . . . Input Output [[10 15] [20 25] [30 35]] 65 [[20 25] [30 35] [40 45]] 85 [[30 35] [40 45] [50 55]] 105 [[40 45] [50 55] [60 65]] 125 [[50 55] [60 65] [70 75]] 145 [[60 65] [70 75] [80 85]] 165 [[70 75] [80 85] [90 95]] 185 n_timesteps = 3 n_features = 2 </code></pre> <p>In keras it seems to be easy:</p> <p><code>model.add(LSTM(50, activation='relu', input_shape=(n_timesteps, n_features)))</code></p> <p>Can it be done in other way, than creating <code>n_features</code> of LSTMs as first layer and feed each separately (imagine as multiple streams of sequences) and then flatten their output to linear layer?</p> <p>I'm not 100% sure but by nature of LSTM the input cannot be flattened and passed as 1D array, because each sequence "plays by different rules" which the LSTM is supposed to learn.</p> <p>So how does such implementation with keras equal to PyTorch <code>input of shape (seq_len, batch, input_size)</code>(source <a href="https://pytorch.org/docs/stable/nn.html#lstm" rel="noreferrer">https://pytorch.org/docs/stable/nn.html#lstm</a>)</p> <hr> <p><strong>Edit:</strong></p> <blockquote> <p>Can it be done in other way, than creating <code>n_features</code> of LSTMs as first layer and feed each separately (imagine as multiple streams of sequences) and then flatten their output to linear layer? </p> </blockquote> <p>According to PyTorch <a href="https://pytorch.org/docs/stable/nn.html#lstm" rel="noreferrer">docs</a> the <em>input_size</em> parameter actually means number of features (if it means number of parallel sequences)</p>
56,893,248
3
0
null
2019-07-02 19:27:34.773 UTC
9
2022-04-13 02:32:07.597 UTC
2019-07-02 19:49:29.853 UTC
null
5,990,202
null
5,990,202
null
1
14
python|pytorch|lstm
17,652
<p>I hope that problematic parts are commented to make sense:</p> <h2>Data preparation</h2> <pre><code>import random import numpy as np import torch # multivariate data preparation from numpy import array from numpy import hstack # split a multivariate sequence into samples def split_sequences(sequences, n_steps): X, y = list(), list() for i in range(len(sequences)): # find the end of this pattern end_ix = i + n_steps # check if we are beyond the dataset if end_ix &gt; len(sequences): break # gather input and output parts of the pattern seq_x, seq_y = sequences[i:end_ix, :-1], sequences[end_ix-1, -1] X.append(seq_x) y.append(seq_y) return array(X), array(y) # define input sequence in_seq1 = array([x for x in range(0,100,10)]) in_seq2 = array([x for x in range(5,105,10)]) out_seq = array([in_seq1[i]+in_seq2[i] for i in range(len(in_seq1))]) # convert to [rows, columns] structure in_seq1 = in_seq1.reshape((len(in_seq1), 1)) in_seq2 = in_seq2.reshape((len(in_seq2), 1)) out_seq = out_seq.reshape((len(out_seq), 1)) # horizontally stack columns dataset = hstack((in_seq1, in_seq2, out_seq)) </code></pre> <h2>Multivariate LSTM Network</h2> <pre><code>class MV_LSTM(torch.nn.Module): def __init__(self,n_features,seq_length): super(MV_LSTM, self).__init__() self.n_features = n_features self.seq_len = seq_length self.n_hidden = 20 # number of hidden states self.n_layers = 1 # number of LSTM layers (stacked) self.l_lstm = torch.nn.LSTM(input_size = n_features, hidden_size = self.n_hidden, num_layers = self.n_layers, batch_first = True) # according to pytorch docs LSTM output is # (batch_size,seq_len, num_directions * hidden_size) # when considering batch_first = True self.l_linear = torch.nn.Linear(self.n_hidden*self.seq_len, 1) def init_hidden(self, batch_size): # even with batch_first = True this remains same as docs hidden_state = torch.zeros(self.n_layers,batch_size,self.n_hidden) cell_state = torch.zeros(self.n_layers,batch_size,self.n_hidden) self.hidden = (hidden_state, cell_state) def forward(self, x): batch_size, seq_len, _ = x.size() lstm_out, self.hidden = self.l_lstm(x,self.hidden) # lstm_out(with batch_first = True) is # (batch_size,seq_len,num_directions * hidden_size) # for following linear layer we want to keep batch_size dimension and merge rest # .contiguous() -&gt; solves tensor compatibility error x = lstm_out.contiguous().view(batch_size,-1) return self.l_linear(x) </code></pre> <h2>Initialization</h2> <pre><code>n_features = 2 # this is number of parallel inputs n_timesteps = 3 # this is number of timesteps # convert dataset into input/output X, y = split_sequences(dataset, n_timesteps) print(X.shape, y.shape) # create NN mv_net = MV_LSTM(n_features,n_timesteps) criterion = torch.nn.MSELoss() # reduction='sum' created huge loss value optimizer = torch.optim.Adam(mv_net.parameters(), lr=1e-1) train_episodes = 500 batch_size = 16 </code></pre> <h2>Training</h2> <pre><code>mv_net.train() for t in range(train_episodes): for b in range(0,len(X),batch_size): inpt = X[b:b+batch_size,:,:] target = y[b:b+batch_size] x_batch = torch.tensor(inpt,dtype=torch.float32) y_batch = torch.tensor(target,dtype=torch.float32) mv_net.init_hidden(x_batch.size(0)) # lstm_out, _ = mv_net.l_lstm(x_batch,nnet.hidden) # lstm_out.contiguous().view(x_batch.size(0),-1) output = mv_net(x_batch) loss = criterion(output.view(-1), y_batch) loss.backward() optimizer.step() optimizer.zero_grad() print('step : ' , t , 'loss : ' , loss.item()) </code></pre> <h2>Results</h2> <pre><code>step : 499 loss : 0.0010267728939652443 # probably overfitted due to 500 training episodes </code></pre>
51,510,655
“Unverified breakpoint” in Visual Studio Code with Chrome Debugger extension
<p>I am trying to debug my Typescript code in Visual Studio Code, using the Chrome Debugger extension, but I am getting the "Unverified breakpoint" message on my breakpoint, and execution does not stop on my breakpoint.</p> <p>Here is my launch.json file:</p> <pre><code>{ linkid=830387 "version": "0.2.0", "configurations": [ { "type": "chrome", "request": "launch", "name": "Launch Chrome against localhost", "url": "http://localhost:4200", "sourceMaps": true, "webRoot": "${workspaceFolder}" } ] } </code></pre> <p>App Version:</p> <ul> <li>Visual Studio Code: 1.25.1 </li> <li>Chrome: 67.0.3396.99</li> </ul> <p>Any other suggestions on how I can solve this issue?</p>
51,553,490
28
0
null
2018-07-25 04:10:02.57 UTC
14
2022-07-20 06:47:10.563 UTC
2019-05-23 07:24:59.607 UTC
null
5,587,356
null
6,024,969
null
1
85
typescript|debugging|visual-studio-code|vscode-settings
75,257
<p>I finally found out whats wrong:</p> <p>When I read the definition of '${workspaceFolder}', it states the following:</p> <blockquote> <p>the path of the folder opened in VS Code</p> </blockquote> <p><strong>My mistake:</strong> </p> <p>My path in Windows to my project was as follow: <code>C:\Users\myusername\Documents\VSCode\Source\ProjectName</code></p> <p>Through Visual Studio Code, I had the <code>Source</code> folder open, and always needed to do a change directory (cd ProjectName) command in <code>Integrated Terminal</code> to 'ProjectName'. This lead to the <code>.vscode folder and launch.json file</code> being created in the <code>Source</code> folder, and not the <code>ProjectName</code> folder. </p> <p>The above mistake lead to the fact that the <code>${workspaceFolder}</code> was pointing to the <code>Source</code> folder, where no Angular components was, instead of pointing to the <code>ProjectName</code> folder.</p> <p><strong>The Fix:</strong></p> <p>In Visual Studio Code, open folder: <code>C:\Users\myusername\Documents\VSCode\Source\ProjectName</code> and setup my <code>launch.json</code> in that directory.</p>
1,184,556
Servlet context scope vs global variable
<p>What (if any) is the difference between storing a variable in the ServletContext and just having it as a public static member of one of the classes?</p> <p>Instead of writing:</p> <pre><code>// simplified (!) int counter = (Integer)getServletContext().getAttribute("counter"); counter++; this.getServletContext().setAttribute("counter", counter); </code></pre> <p>Why not just have:</p> <pre><code>// in class MyServlet public static int counter = 0; // in a method somewhere MyServlet.counter++; </code></pre> <p>(Ignore concurrency issues, please, this is just a dumb example)</p> <p>From what I can tell, these two options behave the same way under Tomcat. Is there something better about using the first option?</p>
1,184,646
2
0
null
2009-07-26 13:10:58.21 UTC
9
2013-07-03 20:51:26.46 UTC
2009-07-26 22:43:52.37 UTC
null
21,234
null
7,581
null
1
22
java|tomcat|servlets
19,234
<p>The web container knows about your servlet context, but not about your static variables which as <a href="https://stackoverflow.com/a/1184558/53897">skaffman says</a> are private to your classloader. </p> <p>Anything that cause two different requests to be served by an application instance in a different classloader (this could be server restarting, web application redeployment, or multi-node servers) will case your logic to break. The servlet context will survive these things as the web container knows about it and can serialize it or have a common repository.</p>
559,506
Using LIKE vs. = for exact string match
<p>First off, I recognize the differences between the two:<br> - Like makes available the wildcards % and _<br> - significant trailing whitespace<br> - colation issues</p> <p>All other things being equal, for an exact string match which is more efficient:</p> <pre><code>SELECT field WHERE 'a' = 'a'; </code></pre> <p>Or:</p> <pre><code>SELECT field WHERE 'a' LIKE 'a'; </code></pre> <p>Or: Is the difference so insignificant that it doesn't matter?</p>
559,512
2
4
null
2009-02-18 01:32:32.33 UTC
6
2017-08-27 22:13:53.067 UTC
2017-08-27 22:04:49.457 UTC
null
13,860
mluebke
4,678
null
1
32
mysql|string|performance
54,208
<p>I would say that the = comparator would be faster. The lexical doesn't send the comparison to another lexical system to do general matches. Instead the engine is able to just match or move on. Our db at work has millions of rows and an = is always faster.</p>
598,113
Can terminals detect <Shift-Enter> or <Control-Enter>?
<p>Is it possible for the terminal to detect <kbd>⇧ Shift</kbd>+<kbd>Enter↵</kbd> or <kbd>Ctrl</kbd>+<kbd>Enter↵</kbd> keypresses?</p> <p>I am trying to configure vim to do key mappings that use these sequences, and while they work fine in gvim, they don't seem to work in any terminal console.</p> <p>The curious thing is that although <kbd>Ctrl</kbd>+<kbd>Enter↵</kbd> is not detected in vim, mapping <kbd>Enter↵</kbd> to <Kbd>Esc</kbd> maps properly, but then pressing <kbd>Ctrl</kbd>+<kbd>Enter↵</kbd> behaves like <kbd>Enter↵</kbd>!</p>
598,404
2
1
null
2009-02-28 14:57:25.107 UTC
19
2020-11-23 17:36:18.787 UTC
2017-08-23 08:39:52.587 UTC
null
72,224
null
72,224
null
1
47
vim|console|terminal
21,902
<p>Some terminals send <code>&lt;NL&gt;</code> when <code>&lt;C-Enter&gt;</code> is pressed. This is equivalent to sending <code>&lt;C-J&gt;</code>. </p> <p>To find out what your terminal does with <code>&lt;Shift-Enter&gt;</code>, <code>&lt;Ctrl-Enter&gt;</code> and <code>&lt;Enter&gt;</code>, go to your terminal, type <code>&lt;Ctrl-V&gt;</code> (similar to sykora's suggestion for vim), and type in the sequence you're interested in.</p> <p>Using gnome-terminal, I get the following:</p> <pre><code> &lt;Enter&gt; : ^M &lt;S-Enter&gt; : ^M &lt;C-Enter&gt; : &lt;NL&gt; </code></pre> <p>Looking at <code>man ascii</code> indicates that <code>^M</code> gives the <code>&lt;CR&gt;</code> sequence.</p> <p>The answer is that it depends on the terminal, and there's an easy way to check.</p>
2,375,118
how to open *.sdf files?
<p>I used to open sdf (sqlCE) files with visual-studio? or sql-server? I really don't remember. Now I can't open this sdf file. With what program do I need to open it?</p>
2,375,148
6
0
null
2010-03-03 21:29:33.13 UTC
25
2022-08-22 21:20:40.61 UTC
2012-01-15 15:03:03.12 UTC
null
110,204
null
43,907
null
1
52
c#|visual-studio-2008|sql-server-ce
112,864
<p>It's a SQL Compact database. You need to define what you mean by "Open". You can open it via code with the SqlCeConnection so you can write your own tool/app to access it. </p> <p>Visual Studio can also <a href="http://arcanecode.com/2007/04/10/creating-a-sql-server-compact-edition-database-using-visual-studio-server-explorer/" rel="noreferrer">open the files directly</a> if was created with the right version of SQL Compact. </p> <p>There are also some <a href="http://www.primeworks-mobile.com/Products/DataPortConsole.html" rel="noreferrer">third-party tools</a> for manipulating them.</p>
2,748,825
What is the recommended approach towards multi-tenant databases in MongoDB?
<p>I'm thinking of creating a multi-tenant app using MongoDB. I don't have any guesses in terms of how many tenants I'd have yet, but I would like to be able to scale into the thousands.</p> <p>I can think of three strategies:</p> <ol> <li>All tenants in the same collection, using tenant-specific fields for security</li> <li>1 Collection per tenant in a single shared DB</li> <li>1 Database per tenant</li> </ol> <p>The voice in my head is suggesting that I go with option 2. </p> <p>Thoughts and implications, anyone?</p>
23,202,825
6
8
null
2010-05-01 03:55:23.31 UTC
52
2019-01-25 13:03:03.97 UTC
null
null
null
null
228,221
null
1
114
mongodb|multi-tenant
45,974
<p>I have the same problem to solve and also considering variants. As I have years of experience creating SaaS multi-tenant applicatios I also was going to select the second option based on my previous experience with the relational databases.</p> <p>While making my research I found this article on mongodb support site (way back added since it's gone): <a href="https://web.archive.org/web/20140812091703/http://support.mongohq.com/use-cases/multi-tenant.html" rel="noreferrer">https://web.archive.org/web/20140812091703/http://support.mongohq.com/use-cases/multi-tenant.html</a></p> <p>The guys stated to avoid 2nd options at any cost, which as I understand is not particularly specific to mongodb. My impression is that this is applicable for most of the NoSQL dbs I researched (CoachDB, Cassandra, CouchBase Server, etc.) due to the specifics of the database design. </p> <p>Collections (or buckets or however they call it in different DBs) are not the same thing as security schemas in RDBMS despite they behave as container for documents they are useless for applying good tenant separation. I couldn't find NoSQL database that can apply security restrictions based on collections.</p> <p>Of course you can use mongodb role based security to restrict the access on database/server level. (<a href="http://docs.mongodb.org/manual/core/authorization/" rel="noreferrer">http://docs.mongodb.org/manual/core/authorization/</a>)</p> <p>I would recommend 1st option when:</p> <ul> <li>You have enough time and resources to deal with the complexity of the design, implementation and testing of this scenario.</li> <li>If you are not going to have much differences in structure and functionality in the database for different tenants.</li> <li>Your application design will allow tenants to make only minimal customizations at runtime.</li> <li>If you want to optimize space and minimize usage of hardware resources.</li> <li>If you are going to have thousands of tenants.</li> <li>If you want to scale out fast and at good cost.</li> <li>If you are NOT going to backup data based on tenants (keep separate backups for each tenant). It is possible to do that even in this scenario but the effort will be huge.</li> </ul> <p>I would go for variant 3 if:</p> <ul> <li>You are going to have small list of tenants (several hundred).</li> <li>The specifics of the business requires you to be able to support big differences in the database structure for different tenants (e.g. integration with 3rd-party systems, import-export of data).</li> <li>Your application design will allow customers (tenants) to make significant changes in the application runtime (adding modules, customizing the fields etc.).</li> <li>If you have enough resources to scale out with new hardware nodes quickly.</li> <li>If you are required to keep versions/backups of data per tenant. Also the restore will be easy.</li> <li>There are legal/regulatory restrictions that forces you to keep different tenants in different databases (even data centers).</li> <li>If you want to fully utilize the out-of-the-box security features of mongodb such as roles.</li> <li>There are big differences in matter of size between tenants (you have many small tenants and few very large tenants).</li> </ul> <p>If you post additional details about your application, perhaps I can give you more detailed advice.</p>
2,739,376
Definition of "downstream" and "upstream"
<p>I've started playing with Git and have come across the terms "upstream" and "downstream". I've seen these before but never understood them fully. What do these terms mean in the context of SCMs (<a href="https://en.wikipedia.org/wiki/Software_configuration_management" rel="noreferrer">Software Configuration Management</a> tools) and source code?</p>
2,739,476
6
3
null
2010-04-29 17:18:21.957 UTC
244
2021-12-03 01:06:27.133 UTC
2019-06-07 14:17:34.223 UTC
null
540,815
null
295,069
null
1
1,021
git|version-control|versioning|terminology|definition
345,978
<p>In terms of source control, you're downstream when you copy (clone, checkout, etc) from a repository. Information flowed &quot;downstream&quot; to you.</p> <p>When you make changes, you usually want to send them back &quot;upstream&quot; so they make it into that repository so that everyone pulling from the same source is working with all the same changes. This is mostly a social issue of how everyone can coordinate their work rather than a technical requirement of source control. You want to get your changes into the main project so you're not tracking divergent lines of development.</p> <p>Sometimes you'll read about package or release managers (the people, not the tool) talking about submitting changes to &quot;upstream&quot;. That usually means they had to adjust the original sources so they could create a package for their system. They don't want to keep making those changes, so if they send them &quot;upstream&quot; to the original source, they shouldn't have to deal with the same issue in the next release.</p>
2,524,928
dos batch iterate through a delimited string
<p>I have a delimited list of IPs I'd like to process individually. The list length is unknown ahead of time. How do I split and process each item in the list?</p> <pre><code>@echo off set servers=127.0.0.1,192.168.0.1,10.100.0.1 FOR /f "tokens=* delims=," %%a IN ("%servers%") DO call :sub %%a :sub echo In subroutine echo %1 exit /b </code></pre> <p>Outputs:</p> <pre><code>In subroutine 127.0.0.1 In subroutine ECHO is off. </code></pre> <p><strong>Update:</strong> Using Franci's answer as reference, here's the solution:</p> <pre><code>@echo off set servers=127.0.0.1,192.168.0.1,10.100.0.1 call :parse "%servers%" goto :end :parse setlocal set list=%1 set list=%list:"=% FOR /f "tokens=1* delims=," %%a IN ("%list%") DO ( if not "%%a" == "" call :sub %%a if not "%%b" == "" call :parse "%%b" ) endlocal exit /b :sub setlocal echo In subroutine echo %1 endlocal exit /b :end </code></pre> <p>Outputs:</p> <pre><code>In subroutine 127.0.0.1 In subroutine 192.168.0.1 In subroutine 10.100.0.1 </code></pre>
2,525,008
7
1
null
2010-03-26 16:32:16.593 UTC
16
2017-12-28 02:39:38.64 UTC
2010-03-26 17:57:38.55 UTC
null
223,214
null
223,214
null
1
41
command-line|batch-file
92,171
<p><strong>Update</strong>: If the number of items in the list is not known, it is still possible to parse all items with simple recursion on the head of the list. (I've changed the IPs to simple numbers for simplicity of the list)</p> <p><em>Finally that Lisp class I took 18 years ago paid off...</em></p> <pre><code>@echo off setlocal set servers=1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24 echo %servers% call :parse "%servers%" goto :eos :parse set list=%1 set list=%list:"=% FOR /f "tokens=1* delims=," %%a IN ("%list%") DO ( if not "%%a" == "" call :sub %%a if not "%%b" == "" call :parse "%%b" ) goto :eos :sub echo %1 goto :eos :eos endlocal </code></pre>
3,015,335
jQuery .html() vs .append()
<p>Lets say I have an empty div:</p> <pre><code>&lt;div id='myDiv'&gt;&lt;/div&gt; </code></pre> <p>Is this:</p> <pre><code>$('#myDiv').html("&lt;div id='mySecondDiv'&gt;&lt;/div&gt;"); </code></pre> <p>The same as:</p> <pre><code>var mySecondDiv=$("&lt;div id='mySecondDiv'&gt;&lt;/div&gt;"); $('#myDiv').append(mySecondDiv); </code></pre>
3,015,581
8
2
null
2010-06-10 14:29:04.973 UTC
86
2021-04-08 06:23:13.257 UTC
2021-04-08 06:23:13.257 UTC
null
9,193,372
null
36,525
null
1
267
jquery|html
597,859
<p>Whenever you pass a string of HTML to any of jQuery's methods, this is what happens:</p> <p>A temporary element is created, let's call it x. x's <code>innerHTML</code> is set to the string of HTML that you've passed. Then jQuery will transfer each of the produced nodes (that is, x's <code>childNodes</code>) over to a newly created document fragment, which it will then cache for next time. It will then return the fragment's <code>childNodes</code> as a fresh DOM collection. </p> <p>Note that it's actually a lot more complicated than that, as jQuery does a bunch of cross-browser checks and various other optimisations. E.g. if you pass just <code>&lt;div&gt;&lt;/div&gt;</code> to <code>jQuery()</code>, jQuery will take a shortcut and simply do <code>document.createElement('div')</code>.</p> <p><strong>EDIT</strong>: To see the sheer quantity of checks that jQuery performs, have a look <a href="http://github.com/jquery/jquery/blob/master/src/manipulation.js#L302" rel="noreferrer">here</a>, <a href="http://github.com/jquery/jquery/blob/master/src/manipulation.js#L393" rel="noreferrer">here</a> and <a href="http://github.com/jquery/jquery/blob/master/src/manipulation.js#L455" rel="noreferrer">here</a>.</p> <hr> <p><code>innerHTML</code> is <em>generally</em> the faster approach, although don't let that govern what you do all the time. jQuery's approach isn't quite as simple as <code>element.innerHTML = ...</code> -- as I mentioned, there are a bunch of checks and optimisations occurring. </p> <hr> <p>The correct technique depends heavily on the situation. If you want to create a large number of identical elements, then the last thing you want to do is create a massive loop, creating a new jQuery object on every iteration. E.g. the quickest way to create 100 divs with jQuery:</p> <pre><code>jQuery(Array(101).join('&lt;div&gt;&lt;/div&gt;')); </code></pre> <hr> <p>There are also issues of readability and maintenance to take into account.</p> <p>This:</p> <pre><code>$('&lt;div id="' + someID + '" class="foobar"&gt;' + content + '&lt;/div&gt;'); </code></pre> <p>... is <em>a lot</em> harder to maintain than this:</p> <pre><code>$('&lt;div/&gt;', { id: someID, className: 'foobar', html: content }); </code></pre>
2,936,000
How to show SQL queries run in the Rails console?
<p>When I run queries (e.g. <code>MyModel.where(...)</code> or <code>record.associated_things</code>) in the console, how can I see the actual database queries being run so I can gain more understanding of what is happening?</p>
2,936,016
8
2
null
2010-05-29 17:37:01.677 UTC
51
2022-09-23 10:31:46.913 UTC
2014-12-18 06:09:33.143 UTC
null
211,563
null
175,836
null
1
155
ruby-on-rails|activerecord
100,938
<h1>Rails 3+</h1> <p>Enter this line in the console:</p> <pre><code>ActiveRecord::Base.logger = Logger.new(STDOUT) </code></pre> <h1>Rails 2</h1> <p>Enter this line in the console:</p> <pre><code>ActiveRecord::Base.connection.instance_variable_set :@logger, Logger.new(STDOUT) </code></pre>
40,677,708
Which exceptions can HttpClient throw?
<p>I am using <a href="https://msdn.microsoft.com/de-de/library/system.net.http.httpclient(v=vs.118).aspx" rel="noreferrer">HttpClient</a> in a xamarin forms project</p> <p>The class is documented, but I can not find any documentation about which exceptions its methods might throw.</p> <p>For example the <a href="https://msdn.microsoft.com/de-de/library/hh158944(v=vs.118).aspx" rel="noreferrer">GetAsync</a> Method does not have any documentation about possible exceptions. But I assume it throws, for example when the server is unreachable.</p> <p>Is there somewhere a list of exceptions this class might throw?</p>
44,387,523
1
9
null
2016-11-18 12:56:23.707 UTC
8
2020-12-06 18:00:52.647 UTC
2016-11-18 13:06:24.87 UTC
null
491,605
null
491,605
null
1
64
c#|httpclient
56,350
<p>As others have commented it depend on what you are calling with HttpClient. I get what you meant though and so here are some exceptions thrown with typical method calls.</p> <p><strong><code>SendAsync</code></strong> can throw:</p> <ul> <li><strong>ArgumentNullException</strong> The request was null.</li> <li><strong>InvalidOperationException</strong> The request message was already sent by the HttpClient instance.</li> <li><strong>HttpRequestException</strong> The request failed due to an underlying issue such as network connectivity, DNS failure, server certificate validation or timeout.</li> <li><strong>TaskCanceledException</strong> <a href="https://stackoverflow.com/questions/10547895/how-can-i-tell-when-httpclient-has-timed-out/12901496#12901496">The request timed-out or the user canceled the request's <code>Task</code></a>.</li> </ul> <p>Source: <a href="https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient.sendasync#System_Net_Http_HttpClient_SendAsync_System_Net_Http_HttpRequestMessage_" rel="noreferrer">Microsoft Docs -&gt; HttpClient -&gt; SendAsync</a></p> <p>Similarly <strong><code>GetAsync</code> <code>PostAsync</code> <code>PutAsync</code> <code>GetStringAsync</code> <code>GetStreamAsync</code></strong> etc can throw <strong><code>ArgumentNullException</code></strong>, <strong><code>HttpRequestException</code></strong> and as above (but not <code>InvalidOperationException</code>).</p> <p>Source: <a href="https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient.getasync#System_Net_Http_HttpClient_GetAsync_System_String_" rel="noreferrer">Microsoft Docs -&gt; HttpClient -&gt; GetAsync</a></p> <p>Once you have called <code>SendAsync</code> or <code>GetAsync</code> etc you will have a <code>Task&lt;HttpResponseMessage&gt;</code>. Once awaited I tend to call <code>EnsureSuccessStatusCode()</code> to throw a <strong><code>HttpRequestException</code></strong> if there is a non success HTTP status code returned. <a href="https://github.com/dotnet/corefx/blob/master/src/System.Net.Http/src/System/Net/Http/HttpResponseMessage.cs#L161" rel="noreferrer">https://github.com/dotnet/corefx/blob/master/src/System.Net.Http/src/System/Net/Http/HttpResponseMessage.cs#L161</a></p>
42,233,542
Appending (pushing) and removing from a JSON array in PostgreSQL 9.5+
<h2><a href="https://stackoverflow.com/q/30707482/124486"><em>For versions less than 9.5 see this question</em></a></h2> <p>I have created a table in PostgreSQL using this:</p> <pre><code>CREATE TEMP TABLE jsontesting AS SELECT id, jsondata::jsonb FROM ( VALUES (1, '["abra","value","mango", "apple", "sample"]'), (2, '["japan","china","india", "russia", "australia"]'), (3, '["must", "match"]'), (4, '["abra","value","true", "apple", "sample"]'), (5, '["abra","false","mango", "apple", "sample"]'), (6, '["string","value","mango", "apple", "sample"]'), (7, '["must", "watch"]') ) AS t(id,jsondata); </code></pre> <p>Now what I wanted was to </p> <ul> <li><p><strong>add</strong> Something like <em>append_to_json_array</em> takes in the actual jsondata which is a json-array and the newString which I have to add to that jsondata array and this function should return the updated json-array. </p> <pre><code>UPDATE jsontesting SET jsondata=append_to_json_array(jsondata, 'newString') WHERE id = 7; </code></pre></li> <li><p><strong>remove</strong> a value from the json data array, one function for removing the value.</p></li> </ul> <p>I tried to search documentation of PostgreSQL but found nothing there.</p>
42,233,548
3
0
null
2017-02-14 18:23:25.483 UTC
22
2022-06-15 15:41:38.757 UTC
2017-05-23 11:54:37.177 UTC
null
-1
null
124,486
null
1
67
arrays|postgresql|jsonb|postgresql-9.5|array-push
53,134
<p>To add the value use the JSON array append opperator (<code>||</code>)</p> <pre><code>UPDATE jsontesting SET jsondata = jsondata || '[&quot;newString&quot;]'::jsonb WHERE id = 7; </code></pre> <p>Removing the value looks like this</p> <pre><code>UPDATE jsontesting SET jsondata = jsondata - 'newString' WHERE id = 7; </code></pre> <p>Concatenating to a nested field looks like this</p> <pre><code>UPDATE jsontesting SET jsondata = jsonb_set( jsondata::jsonb, array['nestedfield'], (jsondata-&gt;'nestedfield')::jsonb || '[&quot;newString&quot;]'::jsonb) WHERE id = 7; </code></pre>
40,302,026
What does the tt metavariable type mean in Rust macros?
<p>I'm reading a book about Rust, and start playing with <a href="https://doc.rust-lang.org/book/macros.html" rel="noreferrer">Rust macros</a>. All metavariable types are explained there and have examples, except the last one – <code>tt</code>. According to the book, it is a “a single token tree”. I'm curious, what is it and what is it used for? Can you please provide an example?</p>
40,303,308
1
0
null
2016-10-28 09:24:51.75 UTC
4
2019-08-13 17:24:44.88 UTC
2016-10-28 10:12:22.773 UTC
null
2,037,422
null
2,037,422
null
1
33
macros|rust|metaprogramming|rust-macros
8,401
<p>That's a notion introduced to ensure that whatever is in a macro invocation correctly matches <code>()</code>, <code>[]</code> and <code>{}</code> pairs. <code>tt</code> will match any single token <strong>or</strong> any pair of parenthesis/brackets/braces <em>with their content</em>.</p> <p>For example, for the following program:</p> <pre><code>fn main() { println!("Hello world!"); } </code></pre> <p>The token trees would be:</p> <ul> <li><code>fn</code></li> <li><code>main</code></li> <li><code>()</code> <ul> <li>∅</li> </ul></li> <li><code>{ println!("Hello world!"); }</code> <ul> <li><code>println</code></li> <li><code>!</code></li> <li><code>("Hello world!")</code> <ul> <li><code>"Hello world!"</code></li> </ul></li> <li><code>;</code></li> </ul></li> </ul> <p>Each one forms a tree where simple tokens (<code>fn</code>, <code>main</code> etc.) are leaves, and anything surrounded by <code>()</code>, <code>[]</code> or <code>{}</code> has a subtree. Note that <code>(</code> does not appear alone in the token tree: it's not possible to match <code>(</code> without matching the corresponding <code>)</code>.</p> <p>For example:</p> <pre><code>macro_rules! { (fn $name:ident $params:tt $body:tt) =&gt; { /* … */ } } </code></pre> <p>would match the above function with <code>$name → main</code>, <code>$params → ()</code>, <code>$body → { println!("Hello world!"); }</code>.</p> <p>Token tree is the least demanding metavariable type: it matches anything. It's often used in macros which have a “don't really care” part, and especially in macros which have a “head” and a “tail” part. For example, the <code>println!</code> macros have a branch matching <code>($fmt:expr, $($arg:tt)*)</code> where <code>$fmt</code> is the format string, and <code>$($arg:tt)*</code> means “all the rest” and is just forwarded to <code>format_args!</code>. Which means that <code>println!</code> does not need to know the actual format and do complicated matching with it.</p>
10,296,711
How to take a screenshot and share it programmatically
<p>I am making an application in Android in which I have to take screenshot of one of my activities and mail it as attachment. </p> <p>I want to take screenshot of the current page and then share it via email, Bluetooth, Twitter or Facebook.</p> <p>My code is as follows:</p> <pre><code>@Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menuselected1, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.ScreenShot: try { takeScreenShot(this); } catch (Exception e) { System.out.println(e); } return true; default: return super.onOptionsItemSelected(item); } } private static void savePic(Bitmap b, String strFileName) { FileOutputStream fos = null; try { fos = new FileOutputStream(strFileName); if (null != fos) { b.compress(Bitmap.CompressFormat.PNG, 90, fos); System.out.println("b is:"+b); fos.flush(); fos.close(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static void shoot(Activity a,String b) { //savePic(takeScreenShot(a), "sdcard/xx.png"); savePic(takeScreenShot(a), b); } private static Bitmap takeScreenShot(Activity activity) { View view = activity.getWindow().getDecorView(); view.setDrawingCacheEnabled(true); view.buildDrawingCache(); Bitmap b1 = view.getDrawingCache(); Rect frame = new Rect(); activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame); int statusBarHeight = frame.top; int width = activity.getWindowManager().getDefaultDisplay().getWidth(); int height = activity.getWindowManager().getDefaultDisplay() .getHeight(); // Bitmap b = Bitmap.createBitmap(b1, 0, 25, 320, 455); Bitmap b = Bitmap.createBitmap(b1, 0, statusBarHeight, width, height - statusBarHeight); view.destroyDrawingCache(); return b; } </code></pre>
10,296,881
5
0
null
2012-04-24 11:08:50.387 UTC
32
2019-04-10 03:46:10.05 UTC
2017-04-04 09:58:53.467 UTC
null
1,788,806
user1025050
null
null
1
28
android|screenshot
35,951
<p>Try this for taking screenshot of current Activity:</p> <p>Android 2.2 :</p> <pre><code>private static Bitmap takeScreenShot(Activity activity) { View view = activity.getWindow().getDecorView(); view.setDrawingCacheEnabled(true); view.buildDrawingCache(); Bitmap b1 = view.getDrawingCache(); Rect frame = new Rect(); activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame); int statusBarHeight = frame.top; DisplayMetrics displaymetrics = new DisplayMetrics(); mContext.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics); int width = displaymetrics.widthPixels; int height = displaymetrics.heightPixels; Bitmap b = Bitmap.createBitmap(b1, 0, statusBarHeight, width, height - statusBarHeight); view.destroyDrawingCache(); return b; } private static void savePic(Bitmap b, String strFileName) { FileOutputStream fos = null; try { fos = new FileOutputStream(strFileName); if (null != fos) { b.compress(Bitmap.CompressFormat.PNG, 90, fos); fos.flush(); fos.close(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } </code></pre>
10,680,601
Nodejs Event Loop
<p>Are there internally two event loops in nodejs architecture?</p> <ul> <li>libev/libuv </li> <li>v8 javascript event loop</li> </ul> <p>On an I/O request does node queue the request to libeio which in turn notifies the availability of data via events using libev and finally those events are handled by v8 event loop using callbacks?</p> <p>Basically, How are libev and libeio integrated in nodejs architecture?</p> <p>Are there any documentation available to give a clear picture of nodejs internal architecture?</p>
11,082,422
8
0
null
2012-05-21 06:46:32.783 UTC
134
2021-06-23 08:48:45.167 UTC
null
null
null
null
973,308
null
1
145
javascript|node.js|event-loop|libev
30,154
<p>I have been personally reading the source code of node.js &amp; v8.</p> <p>I went into a similar problem like you when I tried to understand node.js architecture in order to write native modules.</p> <p>What I am posting here is my understanding of node.js and this might be a bit off track as well.</p> <ol> <li><p><a href="http://software.schmorp.de/pkg/libev.html" rel="noreferrer">Libev</a> is the event loop which actually runs internally in node.js to perform simple event loop operations. It's written originally for *nix systems. Libev provides a simple yet optimized event loop for the process to run on. You can read more about libev <a href="http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod" rel="noreferrer">here</a>.</p></li> <li><p><a href="http://software.schmorp.de/pkg/libeio.html" rel="noreferrer">LibEio</a> is a library to perform input output asynchronously. It handles file descriptors, data handlers, sockets etc. You can read more about it here <a href="http://pod.tst.eu/http://cvs.schmorp.de/libeio/eio.pod" rel="noreferrer">here</a>.</p></li> <li><p><a href="https://github.com/joyent/libuv" rel="noreferrer">LibUv</a> is an abstraction layer on the top of libeio , libev, c-ares ( for DNS ) and iocp (for windows asynchronous-io). LibUv performs, maintains and manages all the io and events in the event pool. ( in case of libeio threadpool ). You should check out <a href="http://vimeo.com/24713213" rel="noreferrer">Ryan Dahl's tutorial</a> on libUv. That will start making more sense to you about how libUv works itself and then you will understand how node.js works on the top of libuv and v8.</p></li> </ol> <p>To understand just the javascript event loop you should consider watching these videos</p> <ul> <li><a href="http://jsconf.eu/2010/speaker/techniques_for_a_single_stack.html" rel="noreferrer">JS-conference</a></li> <li><a href="http://blip.tv/jsconf/jsconf2011-tom-hughes-croucher-5478056" rel="noreferrer">JSConf2011 ( has very irritative sfx) </a></li> <li><a href="http://code.danyork.com/2011/01/25/node-js-doctors-offices-and-fast-food-restaurants-understanding-event-driven-programming/" rel="noreferrer">Understanding event driven programming</a></li> <li><a href="http://blog.mixu.net/2011/02/01/understanding-the-node-js-event-loop/" rel="noreferrer">Understanding the node.js event loop</a></li> </ul> <p>To see how libeio is used with node.js in order to create async modules you should see <a href="https://github.com/pkrumins/node-png" rel="noreferrer">this example</a>.</p> <p>Basically what happens inside the node.js is that v8 loop runs and handles all javascript parts as well as C++ modules [ when they are running in a main thread ( as per official documentation node.js itself is single threaded) ]. When outside of the main thread, libev and libeio handle it in the thread pool and libev provide the interaction with the main loop. So from my understanding, node.js has 1 permanent event loop: that's the v8 event loop. To handle C++ async tasks it's using a threadpool [via libeio &amp; libev ].</p> <p>For example:</p> <pre><code>eio_custom(Task,FLAG,AfterTask,Eio_REQUEST); </code></pre> <p>Which appears in all modules is usually calling the function <code>Task</code> in the threadpool. When it's complete, it calls the <code>AfterTask</code> function in the main thread. Whereas <code>Eio_REQUEST</code> is the request handler which can be a structure / object whose motive is to provide communication between the threadpool and main thread.</p>
6,195,781
IronPython: EXE compiled using pyc.py cannot import module "os"
<p>I have a simple IronPython script:</p> <pre><code># Foo.py import os def main(): print( "Hello" ) if "__main__" == __name__: main() </code></pre> <p>It runs fine and prints <em>Hello</em> if I run it with IronPython as:</p> <pre><code>ipy Foo.py </code></pre> <p>Following the instructions given in <em><a href="http://dbaportal.eu/2009/12/21/ironpython-how-to-compile-exe/" rel="nofollow noreferrer">IronPython - how to compile exe</a></em>, I compiled this IronPython script to a EXE using:</p> <pre><code>ipy pyc.py /main:Foo.py /target:exe </code></pre> <p>Executing Foo.exe gives this error:</p> <pre><code>Unhandled Exception: IronPython.Runtime.Exceptions.ImportException: No module named os at Microsoft.Scripting.Runtime.LightExceptions.CheckAndThrow(Object value) at DLRCachedCode.__main__$1(CodeContext $globalContext, FunctionCode $functionCode) at IronPython.Compiler.OnDiskScriptCode.Run() at IronPython.Compiler.OnDiskScriptCode.Run(Scope scope) at IronPython.Runtime.PythonContext.InitializeModule(String fileName, ModuleContext moduleContext, ScriptCode scriptC ode, ModuleOptions options) </code></pre> <p>Why cannot module "os" be found? How do I fix this, so I can get a working EXE?</p> <p>(Note that this is different from the question <em><a href="https://stackoverflow.com/questions/3904374">IronPython cannot import module os</a></em> since the script works fine if I run with <code>ipy.exe</code>.)</p>
6,205,193
2
0
null
2011-06-01 02:57:08.793 UTC
26
2018-04-24 05:11:10.983 UTC
2017-05-23 12:25:45.573 UTC
null
-1
null
1,630
null
1
23
python|ironpython
15,835
<p>Building an Ironpython EXE that you can distribute is a bit tricky - especially if you are using elements of the standard library. My typical solution is the following:</p> <p>I copy all of the stdlib modules I need into a folder (usually all of them just for completeness) and use this script to build my exe. In this example I have two files <strong>FredMain.py</strong> and <strong>FredSOAP.py</strong> that get compiled into an EXE called <strong>Fred_Download_Tool</strong></p> <pre><code>import sys sys.path.append(r'C:\Program Files\IronPython 2.7\Lib') sys.path.append(r'C:\Program Files\IronPython 2.7') import clr clr.AddReference('IronPython') clr.AddReference('IronPython.Modules') clr.AddReference('Microsoft.Scripting.Metadata') clr.AddReference('Microsoft.Scripting') clr.AddReference('Microsoft.Dynamic') clr.AddReference('mscorlib') clr.AddReference('System') clr.AddReference('System.Data') # # adapted from os-path-walk-example-3.py import os, glob import fnmatch import pyc def doscopy(filename1): print filename1 os.system ("copy %s .\\bin\Debug\%s" % (filename1, filename1)) class GlobDirectoryWalker: # a forward iterator that traverses a directory tree def __init__(self, directory, pattern="*"): self.stack = [directory] self.pattern = pattern self.files = [] self.index = 0 def __getitem__(self, index): while 1: try: file = self.files[self.index] self.index = self.index + 1 except IndexError: # pop next directory from stack self.directory = self.stack.pop() self.files = os.listdir(self.directory) self.index = 0 else: # got a filename fullname = os.path.join(self.directory, file) if os.path.isdir(fullname) and not os.path.islink(fullname) and fullname[-4:]&lt;&gt;'.svn': self.stack.append(fullname) if fnmatch.fnmatch(file, self.pattern): return fullname #Build StdLib.DLL gb = glob.glob(r".\Lib\*.py") gb.append("/out:StdLib") #print ["/target:dll",]+gb pyc.Main(["/target:dll"]+gb) #Build EXE gb=["/main:FredMain.py","FredSOAP.py","/target:exe","/out:Fred_Download_Tool"] pyc.Main(gb) #CopyFiles to Release Directory doscopy("StdLib.dll") doscopy("Fred_Download_Tool.exe") doscopy("Fred_Download_.dll") #Copy DLLs to Release Directory fl = ["IronPython.dll","IronPython.Modules.dll","Microsoft.Dynamic.dll","Microsoft.Scripting.Debugging.dll","Microsoft.Scripting.dll","Microsoft.Scripting.ExtensionAttribute.dll","Microsoft.Scripting.Core.dll"] for f in fl: doscopy(f) </code></pre> <p>In my scripts I add the following when I am ready to compile. This allows the program to use the Standard Modules from my DLL instead of the Python Install. This is necessary if you want to distribute to people without Python installed. Just make sure you include the necessary DLL's when you create your installer.</p> <pre><code>#References to created DLL of python modules clr.AddReference('StdLib') </code></pre>
5,775,580
Git pulling changes between two local repositories
<p>I have two clones of same remote repository. I have made some changes to one local repository, how can I pull these changes to the other local repository without pushing it to the remote?</p>
5,775,607
2
1
null
2011-04-25 05:44:35.177 UTC
14
2020-05-05 00:04:45.843 UTC
2019-04-06 15:34:15.777 UTC
null
2,624,876
null
7,965
null
1
76
git|git-pull
30,239
<p>You can treat the second clone the same way you treat a remote respository on another system. You can perform all of the same operations, e.g.</p> <pre><code>~/repo1 $ git remote add repo2 ~/repo2 ~/repo1 $ git fetch repo2 ~/repo1 $ git merge repo2/foo </code></pre>
32,581,404
jQuery validation with input mask
<p>Have this problem that form inputs with assigned mask (as a placeholder) are not validated as empty by jQuery validation.</p> <p>I use:</p> <ul> <li><a href="https://github.com/RobinHerbots/jquery.inputmask" rel="noreferrer">https://github.com/RobinHerbots/jquery.inputmask</a></li> <li><a href="https://github.com/1000hz/bootstrap-validator" rel="noreferrer">https://github.com/1000hz/bootstrap-validator</a> (which uses jQuery native validation in this case)</li> </ul> <p>Some strange behaviors:</p> <ol> <li>Inputs with attribute <code>required</code> are validated (by jQuery) as not empty and therefore valid, but in the other hand input is not considered as "not empty" and not checked for other validation rules (this is by validator.js)</li> <li>When i write something into input field and then erase it, I get <code>required</code> error message</li> </ol> <p>Can anyone give me some hint?</p> <p>EDIT: Relevant code:</p> <p>HTML/PHP:</p> <pre><code>&lt;form enctype="multipart/form-data" method="post" id="feedback"&gt; &lt;div class="kontakt-form-row form-group"&gt; &lt;div class="kontakt-form"&gt; &lt;label for="phone" class="element"&gt; phone&lt;span class="required"&gt;*&lt;/span&gt; &lt;/label&gt; &lt;/div&gt; &lt;div class="kontakt-form"&gt; &lt;div class="element"&gt; &lt;input id="phone" name="phone" ' . (isset($user['phone']) ? 'value="' . $user['phone'] . '"' : '') . ' type="text" maxlength="20" class="form-control" required="required" data-remote="/validator.php"&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="help-block with-errors"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/form&gt; </code></pre> <p>JS:</p> <pre><code>$(document).ready(function() { $('#phone').inputmask("+48 999 999 999"); $('#feedback').validator(); }); </code></pre>
32,608,949
4
0
null
2015-09-15 08:35:19.723 UTC
1
2018-10-18 09:24:11.95 UTC
2015-09-15 09:44:52.833 UTC
null
4,689,671
null
4,689,671
null
1
13
javascript|jquery|twitter-bootstrap|validation|masking
45,800
<p>It's not exactly the solution, but...</p> <p><strong>changing inputmask for some equivalent solves the problem</strong>.</p> <p>Still far from perfect, though : (</p> <p>EXPLANATION:</p> <p>Other masking libraries, don't have these two strange behaviors mentioned, so it's possible to validate fields.</p> <p>I used: <a href="https://github.com/digitalBush/jquery.maskedinput" rel="nofollow">https://github.com/digitalBush/jquery.maskedinput</a></p>
21,155,574
MVC - calling controller from view
<p>I am new to MVC</p> <p>I am developing a web application using MVC and the application contains only one page.</p> <p>So in that view I have to populate multiple data. Say if the application is a "News feed" application, i need to populate recent news, news liked by you, news recommended by your friends etc. So should I make a ajax call from view to all required controllers to fetch these data and append in the view??</p> <p>Currently i am able to get the data by making an ajax call to controller and fetching the data, but as per my understanding, the controller is called first in a MVC and it renders the view and in the way i am currently using I am calling the controller back from view.</p> <p>Is this method correct ?? what is the right approach to achieve this result in MVC?</p> <p>If i have to use Ajax call to controller and get data, what is going to be the different in MVC? In 3-tier app i will make ajax call to some web method or a Handler which will return some data here I am calling an action result function which is again returning some data</p>
21,155,839
2
1
null
2014-01-16 07:17:43.96 UTC
1
2015-02-18 10:12:47.56 UTC
2015-02-18 10:12:47.56 UTC
null
848,841
null
848,841
null
1
8
c#|asp.net|asp.net-mvc|asp.net-mvc-3|asp.net-mvc-4
38,701
<p>Yes you can use ajax call like this</p> <pre><code>$(document).ready(function () { $('#CategoryId').change(function () { $.getJSON('/Publication/AjaxAction/' + this.value, {}, function (html) { $("#partial").html(html); alert("go"); }); }); }); </code></pre> <p>and then load a partial view from your contoller.</p> <pre><code>public ActionResult AjaxAction(int Id) { if (Request.IsAjaxRequest()) { if (Id== 1) { ViewBag.SourceTypeId = new SelectList(db.SourceTypes, "Id", "Title"); ViewBag.CityId = new SelectList(db.Cities, "Id", "Title"); return PartialView("_CreateStatya"); } } return PartialView(); } </code></pre>
21,269,836
How to define page breaks when printing html?
<p>I have a application made with Delphi 2006 which prints with QuickReport. Due to many bugs, I will rebuild this section of the software , generating the report in HTML and then send it to printer through some component. My question is, How/Can I tell when printer should break into a new page with HTML? Some tag or event on printing component for HTML? </p>
21,270,036
1
1
null
2014-01-21 21:52:07.88 UTC
7
2014-01-22 07:59:10.503 UTC
2014-01-22 07:59:10.503 UTC
null
512,728
null
1,062,933
null
1
16
html|printing|report
39,045
<p>You can add page breaks for printing with a little bit of CSS.</p> <p>CSS:</p> <pre class="lang-css prettyprint-override"><code>@media all { .page-break { display: none; } } @media print { .page-break { display: block; page-break-before: always; } } </code></pre> <p>HTML: Use a div element with the page-break class where you want insert your breaks</p> <pre class="lang-html prettyprint-override"><code>&lt;div class="page-break"&gt;&lt;/div&gt; </code></pre> <p>Example:</p> <pre class="lang-html prettyprint-override"><code>&lt;div&gt;Some content BEFORE the page break&lt;/div&gt; &lt;div class="page-break"&gt;&lt;/div&gt; &lt;div&gt;Some content AFTER the page break&lt;/div&gt; &lt;div class="page-break"&gt;&lt;/div&gt; &lt;div&gt; ... More content after another page break ... &lt;/div&gt; </code></pre>
35,753,399
Auto generate build pipeline for gradle build using Jenkinsfile
<p><br/> I am trying to create a build pipeline based upon the Gradle tasks. I have viewed JenkinsFile configuration <a href="https://github.com/kishorebhatia/pipeline-as-code-demo">Pipeline-as-code-demo</a> but I am unable to create a pipeline for gradle tasks. Please suggest me a possible way so that I can use the Jenkinsfile to automatically show the build pipeline just by reading the configurations from the Jenkinsfile.<br/> Thankyou</p>
41,776,048
3
0
null
2016-03-02 16:52:29.11 UTC
1
2018-12-13 16:57:42.37 UTC
null
null
null
null
5,488,774
null
1
11
jenkins|gradle|continuous-integration
41,363
<p>In case you're using Artifactory to resolve your build dependencies or to deploy your build artifacts, it is recommended to use the Pipeline DSL for <a href="https://www.jfrog.com/confluence/display/RTF/Working+With+Pipeline+Jobs+in+Jenkins" rel="nofollow noreferrer">Gradle build with Artifactory</a>.</p> <p>Here's an example taken from the <a href="https://jenkins.io/doc/pipeline/examples/" rel="nofollow noreferrer">Jenkins Pipeline Examples</a> page:</p> <pre><code>node { // Get Artifactory server instance, defined in the Artifactory Plugin administration page. def server = Artifactory.server "SERVER_ID" // Create an Artifactory Gradle instance. def rtGradle = Artifactory.newGradleBuild() stage 'Clone sources' git url: 'https://github.com/jfrogdev/project-examples.git' stage 'Artifactory configuration' // Tool name from Jenkins configuration rtGradle.tool = "Gradle-2.4" // Set Artifactory repositories for dependencies resolution and artifacts deployment. rtGradle.deployer repo:'ext-release-local', server: server rtGradle.resolver repo:'remote-repos', server: server stage 'Gradle build' def buildInfo = rtGradle.run rootDir: "gradle-examples/4/gradle-example-ci-server/", buildFile: 'build.gradle', tasks: 'clean artifactoryPublish' stage 'Publish build info' server.publishBuildInfo buildInfo } </code></pre> <p>Otherwise, you can simply run the gradle command with the <em>sh</em> or <em>bat</em> Pipeline steps.</p>
43,038,060
Deploy Angular 2 to Apache Server
<p>I want to deploy an Angular 2 application on an Apache server. I've read various guides like <a href="https://github.com/mgechev/angular-seed/wiki/Deploying-prod-build-to-Apache-2" rel="nofollow noreferrer">this</a> and <a href="https://github.com/angular/angular/issues/11884" rel="nofollow noreferrer">this</a> but none of them is working. I have <code>npm</code> and <code>ng</code> installed on the server.</p> <p>In a nutshell, here's what I did:</p> <ol> <li>Cloned complete project repository on my server.</li> <li>Installed dependencies using <code>npm install</code>.</li> <li>Used <code>ng build --prod</code> command and it created a <code>dist</code> directory.</li> <li>Changed <code>apache</code> root to <code>/var/www/html/dist</code> directory.</li> <li>Enabled <code>mod_rewrite</code>, restarted <code>apache</code> and added this <code>.htaccess</code> in my <code>dist</code> directory.</li> </ol> <pre><code>&lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase / RewriteRule ^index\.html$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.html [L] &lt;/IfModule&gt; </code></pre> <p>But only my home page <code>domain.com</code> works, other pages like <code>domain.com/login</code>, <code>domain.com/register</code> etc. throw 404 error. Even <code>domain.com/index.html/login</code> doesn't work.</p> <p>The application works fine on my local system where I'm developing it using <code>ng serve</code>. What am i missing?</p>
43,038,161
9
0
null
2017-03-27 04:39:36.95 UTC
21
2021-10-05 10:02:05.117 UTC
2021-10-05 10:02:05.117 UTC
null
13,618,646
null
3,134,082
null
1
26
apache|.htaccess|angular|digital-ocean
78,578
<p>It appears i was missing this in my <code>/etc/apache2/sites-enabled/000-default.conf</code> file. After adding this and restarting <code>apache</code>, website runs fine.</p> <pre><code>&lt;Directory "/var/www/html/dist"&gt; AllowOverride All &lt;/Directory&gt; </code></pre>
8,500,445
Automatically dial a phone number
<p>I have a web page where I have a button. I need to automatically dial a phone number on the click of the button. It needs to be done in HTML.</p> <p>I need to do it on the onclick event of the button.</p>
8,505,221
4
0
null
2011-12-14 06:43:11.98 UTC
0
2020-07-31 05:20:56.557 UTC
2020-07-31 05:20:56.557 UTC
null
1,879,699
null
435,813
null
1
9
html|anchor
50,886
<p>On mobile devices, there are protocol handlers to launch the phone. Depending on the security, some will dial it, or others will bring on the phone application with the number already there.</p> <pre><code>&lt;a href="tel:+15555555555"&gt;Call me at +1 (555) 555-5555&lt;/a&gt; </code></pre>
9,004,095
Jquery count characters
<p>I'm having problems to figure out why jquery string counter won't show me the expected result.</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8"&gt; &lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; var count = $('h1').length; alert(count); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;some text&lt;/h1&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>the result should be with this example 9, but instead I'm getting 0</p>
9,004,126
4
0
null
2012-01-25 14:13:34.04 UTC
1
2019-08-03 16:49:43.647 UTC
2012-01-25 14:23:05.833 UTC
null
338,208
null
962,469
null
1
10
jquery
47,829
<p>$("h1") returns a jQuery object (in which the length property is the number of elements returned), and since you are calling it before the page is completely loaded it is actually retuning 0 elements.</p> <p>What you want is:</p> <pre><code>$(document).ready(function() { var count = $("h1").text().length; alert(count); }); </code></pre>
8,368,157
Existing ivar 'title' for unsafe_unretained property 'title' must be __unsafe_unretained
<p>I'm just getting to grips with Objective-C 2.0</p> <p>When I try to build the following in Xcode it fails. The error from the compiler is as follows:</p> <p><strong>Existing ivar 'title' for unsafe_unretained property 'title' must be __unsafe_unretained.</strong></p> <pre><code>// main.m #import &lt;Foundation/Foundation.h&gt; #import "Movie.h" int main (int argc, const char * argv[]){ Movie *movie = Movie.new; NSLog(@"%@", movie); return 0; } // movie.h #import &lt;Foundation/Foundation.h&gt; @interface Movie : NSObject{ NSString *title; int year; int rating; } @property(assign) NSString *title; @property(assign) int rating; @property(assign) int year; @end #import "Movie.h" @implementation Movie; @synthesize title; // this seems to be issue - but I don't understand why? @synthesize rating; @synthesize year; @end </code></pre> <p>Can anybody explain where I've gone wrong?</p>
8,368,240
1
0
null
2011-12-03 13:59:48.26 UTC
7
2014-05-09 07:41:03.793 UTC
2014-05-09 07:41:03.793 UTC
null
3,532,040
null
443,297
null
1
32
objective-c
14,518
<p>I assume you are using ARC.</p> <p>Under ARC, the ownership qualification of the property must match the instance variable (ivar). So, for example, if you say that the property is "strong", then the ivar has to be strong as well.</p> <p>In your case you are saying that the property is "assign", which is the same as unsafe_unretained. In other words, this property doesn't maintain any ownership of the NSString that you set. It just copies the NSString* pointer, and if the NSString goes away, it goes away and the pointer is no longer valid.</p> <p>So if you do that, the ivar <strong>also</strong> has to be marked __unsafe_unretained to match (if you're expecting the compiler to @synthesize the property for you)</p> <p>OR you can just omit the ivar declaration, and just let the compiler do that for you as well. Like this:</p> <pre><code>@interface Movie : NSObject @property(assign) NSString *title; @property(assign) int rating; @property(assign) int year; @end </code></pre> <p>Hope that helps.</p>
8,827,891
Swapping rootViewController with animation
<p>I'm having a little trouble swapping rootViewControllers with animation. Here's the code that I'm using:</p> <pre><code>[UIView transitionWithView:self.window duration:0.8 options:UIViewAnimationOptionTransitionFlipFromRight animations:^{ self.window.rootViewController = self.navigationController; } completion:nil]; </code></pre> <p>It kind of works except that right before the animation, the screen turns to black and then the animation occurs. It looks like the original rootViewController is getting removed right before the animation. Any ideas?</p>
8,828,020
7
0
null
2012-01-11 22:50:14.203 UTC
16
2020-09-17 11:29:15.597 UTC
null
null
null
null
639,668
null
1
37
objective-c|ios|cocoa-touch|uiviewcontroller
21,238
<p><code>transitionWithView</code> is intended to animate subviews of the specified container view. It is not so simple to animate changing the root view controller. I've spent a long time trying to do it w/o side effects. See:</p> <p><a href="https://stackoverflow.com/questions/8146253/animate-change-of-view-controllers-without-using-navigation-controller-stack-su/8248284#8248284">Animate change of view controllers without using navigation controller stack, subviews or modal controllers?</a></p> <p>EDIT: added excerpt from referenced answer</p> <pre><code>[UIView transitionFromView:self.window.rootViewController.view toView:viewController.view duration:0.65f options:transition completion:^(BOOL finished){ self.window.rootViewController = viewController; }]; </code></pre>
8,923,485
TFS: submit changes done locally in one branch to another branch
<p>I made changes to a lot of files, and in the meantime I figured I rather commit this untested code to a yet-to-be-created branch, so that users of the existing code base are not affected.</p> <p>As I touched really many, many files and created and added new sub-projects etc., I want to avoid copying files and folders manually.</p> <p>What's the easiest way to get this done in Visual Studio?</p>
8,925,277
1
0
null
2012-01-19 09:11:45.42 UTC
19
2013-05-23 16:40:04.123 UTC
2013-05-23 16:40:04.123 UTC
null
8,363
null
709,537
null
1
74
visual-studio-2010|tfs|branch|tfs-power-tools
21,289
<p>This functionality is provided using <code>tfpt unshelve /migrate</code>. To use it, follow these steps:</p> <ol> <li>Create a shelveset of your changes (from the UI, or <code>tf shelve . /R</code>)</li> <li>Create the new branch</li> <li>Download and install the <a href="http://visualstudiogallery.msdn.microsoft.com/c255a1e4-04ba-4f68-8f4e-cd473d6b971f" rel="noreferrer">Team Foundation Server Power Tools</a></li> <li>From a Visual Studio Command Prompt, run the following command: <code>tfpt unshelve /migrate /source:$/TeamProject/Main /target:$/TeamProject/Beta</code></li> </ol> <p>This will essentially re-write the paths in your shelveset to the new branch. </p>
61,014,661
Animated: `useNativeDriver` was not specified issue of ReactNativeBase Input
<p>I created a new react-native project today (April 3rd, 2020) and added a native-base. Then I tried to add input with the floating label. It gives a warning message: Animated: <code>useNativeDriver</code> was not specified. This is a required option and must be explicitly set to <code>true</code> or <code>false</code>. If I removed the floating label attribute or changed it to stackedLabel the warning disappeared. While this warning is appearing, <code>onChangeText</code> is not being called.</p> <p><a href="https://i.stack.imgur.com/aFLmB.png" rel="noreferrer"><img src="https://i.stack.imgur.com/aFLmB.png" alt="Warning message" /></a></p> <p><strong>Component File</strong></p> <pre class="lang-js prettyprint-override"><code>import React from 'react'; import { SafeAreaView, ScrollView, StatusBar, StyleSheet, View, } from 'react-native'; import {Input, Item, Label} from 'native-base'; import {Colors} from 'react-native/Libraries/NewAppScreen'; declare var global: {HermesInternal: null | {}}; const App = () =&gt; { return ( &lt;&gt; &lt;StatusBar barStyle=&quot;dark-content&quot; /&gt; &lt;SafeAreaView&gt; &lt;ScrollView contentInsetAdjustmentBehavior=&quot;automatic&quot; style={styles.scrollView}&gt; &lt;View style={styles.body}&gt; &lt;Item floatingLabel&gt; &lt;Label&gt;Test&lt;/Label&gt; &lt;Input onChangeText={text =&gt; console.log(text)} /&gt; &lt;/Item&gt; &lt;/View&gt; &lt;/ScrollView&gt; &lt;/SafeAreaView&gt; &lt;/&gt; ); }; </code></pre> <p><strong>package.json</strong></p> <pre><code>{ &quot;name&quot;: &quot;formtest&quot;, &quot;version&quot;: &quot;0.0.1&quot;, &quot;private&quot;: true, &quot;scripts&quot;: { &quot;android&quot;: &quot;react-native run-android&quot;, &quot;ios&quot;: &quot;react-native run-ios&quot;, &quot;start&quot;: &quot;react-native start&quot;, &quot;test&quot;: &quot;jest&quot;, &quot;lint&quot;: &quot;eslint . --ext .js,.jsx,.ts,.tsx&quot; }, &quot;dependencies&quot;: { &quot;native-base&quot;: &quot;^2.13.12&quot;, &quot;react&quot;: &quot;16.11.0&quot;, &quot;react-native&quot;: &quot;0.62.0&quot; }, &quot;devDependencies&quot;: { &quot;@babel/core&quot;: &quot;^7.6.2&quot;, &quot;@babel/runtime&quot;: &quot;^7.6.2&quot;, &quot;@react-native-community/eslint-config&quot;: &quot;^1.0.0&quot;, &quot;@types/jest&quot;: &quot;^24.0.24&quot;, &quot;@types/react-native&quot;: &quot;^0.62.0&quot;, &quot;@types/react-test-renderer&quot;: &quot;16.9.2&quot;, &quot;@typescript-eslint/eslint-plugin&quot;: &quot;^2.25.0&quot;, &quot;@typescript-eslint/parser&quot;: &quot;^2.25.0&quot;, &quot;babel-jest&quot;: &quot;^24.9.0&quot;, &quot;eslint&quot;: &quot;^6.5.1&quot;, &quot;jest&quot;: &quot;^24.9.0&quot;, &quot;metro-react-native-babel-preset&quot;: &quot;^0.58.0&quot;, &quot;react-test-renderer&quot;: &quot;16.11.0&quot;, &quot;prettier&quot;: &quot;^2.0.2&quot;, &quot;typescript&quot;: &quot;^3.8.3&quot; }, &quot;jest&quot;: { &quot;preset&quot;: &quot;react-native&quot;, &quot;moduleFileExtensions&quot;: [ &quot;ts&quot;, &quot;tsx&quot;, &quot;js&quot;, &quot;jsx&quot;, &quot;json&quot;, &quot;node&quot; ] } } </code></pre>
61,117,885
12
0
null
2020-04-03 14:57:30.45 UTC
12
2022-09-12 07:14:14.35 UTC
2020-12-27 13:45:49.14 UTC
null
8,798,220
null
466,749
null
1
65
javascript|reactjs|react-native|native-base
96,991
<p>Just add <code>useNativeDriver: true</code> to the animation config.</p> <pre><code>const [animatePress, setAnimatePress] = useState(new Animated.Value(1)) const animateIn = () =&gt; { Animated.timing(animatePress, { toValue: 0.5, duration: 500, useNativeDriver: true // Add This line }).start(); } </code></pre> <h1>UPDATED</h1> <p><strong>Solution:</strong></p> <p>As the warning says, we need to specify the <code>useNativeDriver</code> option explicitly and set it to <code>true</code> or <code>false</code> .</p> <p><strong>1- Animation methods</strong></p> <p>Refer to <a href="https://reactnative.dev/docs/animated" rel="noreferrer">Animated doc</a> , with animation types or composition functions, for example, <code>Animated.decay()</code>, <code>Animated.timing()</code>, <code>Animated.spring()</code>, <code>Animated.parallel()</code>, <code>Animated.sequence()</code>, specify <code>useNativeDriver</code> .</p> <pre><code>Animated.timing(this.state.animatedValue, { toValue: 1, duration: 500, useNativeDriver: true, // Add this line }).start(); </code></pre> <p><strong>2- Animatable components</strong></p> <p><code>Animated</code> exports the following animatable components using the above wrapper:</p> <ul> <li><code>Animated.Image</code></li> <li><code>Animated.ScrollView</code></li> <li><code>Animated.Text</code></li> <li><code>Animated.View</code></li> <li><code>Animated.FlatList</code></li> <li><code>Animated.SectionList</code></li> </ul> <p>When working with <code>Animated.event()</code> , add <code>useNativeDriver: false/true</code> to the animation config.</p> <pre><code>&lt;Animated.ScrollView scrollEventThrottle={1} onScroll={Animated.event( [{ nativeEvent: { contentOffset: { y: this.state.animatedValue } } }], { useNativeDriver: true } // Add this line )} &gt; {content} &lt;/Animated.ScrollView&gt; </code></pre>
26,643,587
Comparing BCrypt hash between PHP and NodeJS
<p>For an app I'm working on, nodejs needs to verify hashes created by PHP and vice-versa.</p> <p>The problem is, the hashes generated in PHP (via Laravel's <code>Hash</code> class, which just uses PHP's <code>password_hash</code> function) return false when tested in node.js.</p> <p>The following node.js script:</p> <pre><code>var bcrypt = require('bcrypt'); var password = 'password'; var phpGeneratedHash = '$2y$10$jOTwkwLVn6OeA/843CyIHu67ib4RixMa/N/pTJVhOjTddvrG8ge5.'; var nodeGeneratedHash = '$2a$10$ZiBH5JtTDtXqDajO6f4EbeBIXGwtcGg2MGwr90xTH9ki34SV6rZhO'; console.log( bcrypt.compareSync(password, phpGeneratedHash) ? 'PHP passed' : 'PHP failed', bcrypt.compareSync(password, nodeGeneratedHash) ? 'nodejs passed' : 'nodejs failed' ); </code></pre> <p>outputs: 'PHP failed nodejs passed', whereas the following PHP script:</p> <pre><code>&lt;?php $password = 'password'; $phpGeneratedHash = '$2y$10$jOTwkwLVn6OeA/843CyIHu67ib4RixMa/N/pTJVhOjTddvrG8ge5.'; $nodeGeneratedHash = '$2a$10$ZiBH5JtTDtXqDajO6f4EbeBIXGwtcGg2MGwr90xTH9ki34SV6rZhO'; print password_verify($password, $phpGeneratedHash) ? 'PHP passed' : 'PHP failed'; print password_verify($password, $nodeGeneratedHash) ? 'nodejs passed' : 'nodejs failed'; </code></pre> <p>outputs 'PHP passed nodejs passed'.</p> <p>I've run the tests in Ubuntu 14.04.1 using PHP 5.5.18, node.js v0.10.32 and the npm bcrypt module.</p>
26,643,637
3
0
null
2014-10-30 01:32:23.137 UTC
21
2019-07-29 03:30:33.723 UTC
2016-07-21 16:52:53.993 UTC
null
3,134,069
null
2,555,969
null
1
43
php|node.js|bcrypt
15,071
<p>This fails because the types of bcrypt hashes being generated from php and node are different. Laravel generates the <code>$2y$</code> while node generates the <code>$2a$</code>. But the good news is the only difference between <code>2a</code> and <code>2y</code> are their prefixes. </p> <p>So what you can do is make one of the prefix similar to the other. Like:</p> <pre><code>$phpGeneratedHash = '$2y$10$jOTwkwLVn6OeA/843CyIHu67ib4RixMa/N/pTJVhOjTddvrG8ge5.'; $nodeGeneratedHash = '$2a$10$ZiBH5JtTDtXqDajO6f4EbeBIXGwtcGg2MGwr90xTH9ki34SV6rZhO'; </code></pre> <p>To something like:</p> <pre><code>$phpGeneratedHash = '$2y$10$jOTwkwLVn6OeA/843CyIHu67ib4RixMa/N/pTJVhOjTddvrG8ge5.'; $nodeGeneratedHash = '$2y$10$ZiBH5JtTDtXqDajO6f4EbeBIXGwtcGg2MGwr90xTH9ki34SV6rZhO'; </code></pre> <p>Notice that I replaced the <code>$2a$</code> of the node hash to <code>$2y$</code>. You can simply do this with:</p> <h2>PHP</h2> <pre><code>$finalNodeGeneratedHash = str_replace("$2a$", "$2y$", $nodeGeneratedHash); </code></pre> <h2>Node</h2> <pre><code>finalNodeGeneratedHash = nodeGeneratedHash.replace('$2a$', '$2y$'); </code></pre> <p>Then compare <code>phpGeneratedHash</code> to <code>finalNodeGeneratedHash</code>.</p> <blockquote> <p>Note: It is recommended that if you're comparing in PHP, change the prefix of the NodeJS generated hash to <code>$2y$</code> and if you're comparing in NodeJS; change the prefix of the PHP generated hash to <code>$2a$</code>.</p> </blockquote>