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
4,028,267
How to render Latex markup using Python?
<p>How to show an easy latex-formula in python? Maybe numpy is the right choice?</p> <p>I have python code like:</p> <pre><code>a = '\frac{a}{b}' </code></pre> <p>and want to print this in a graphical output (like matplotlib).</p>
4,028,479
6
6
null
2010-10-26 21:41:03.607 UTC
8
2022-04-15 19:49:21.313 UTC
2022-04-15 19:49:21.313 UTC
null
4,621,513
null
237,934
null
1
24
python|latex|formula
80,041
<p>As suggested by Andrew little work around using matplotlib.</p> <pre><code>import matplotlib.pyplot as plt a = '\\frac{a}{b}' #notice escaped slash plt.plot() plt.text(0.5, 0.5,'$%s$'%a) plt.show() </code></pre>
3,633,900
Difference between "include" and "require" in php
<p>Is there any difference between them? Is using them a matter of preference? Does using one over the other produce any advantages? Which is better for security?</p>
3,633,912
7
4
null
2010-09-03 07:51:37.37 UTC
34
2021-01-07 13:37:02.12 UTC
null
null
null
null
418,146
null
1
176
php|include|require
122,480
<p>You find the differences explained in the detailed PHP manual on <a href="http://php.net/require" rel="noreferrer">the page of <code>require</code></a>:</p> <blockquote> <p><em><code>require</code></em> is identical to <a href="http://php.net/include" rel="noreferrer"><em><code>include</code></em></a> except upon failure it will also produce a fatal <strong><code>E_COMPILE_ERROR</code></strong> level error. In other words, it will halt the script whereas include only emits a warning (<strong><code>E_WARNING</code></strong>) which allows the script to continue.</p> </blockquote> <p>See <a href="https://stackoverflow.com/a/3633905/367456">@efritz's answer</a> for an example</p>
3,621,599
Wake Android Device up
<p>Hey i need to wake my sleeping android device up at a certain time. Any suggestions?</p> <p>P.S. Wake up: turn display on and maybe unlock phone</p>
3,623,170
8
0
null
2010-09-01 19:45:20.137 UTC
34
2020-08-11 13:32:54.563 UTC
null
null
null
null
314,597
null
1
44
android|wakeup
90,610
<p>Best is to use some appropriate combination of these window flags:</p> <p><a href="http://developer.android.com/reference/android/view/WindowManager.LayoutParams.html#FLAG_DISMISS_KEYGUARD" rel="noreferrer">http://developer.android.com/reference/android/view/WindowManager.LayoutParams.html#FLAG_DISMISS_KEYGUARD</a><br> <a href="http://developer.android.com/reference/android/view/WindowManager.LayoutParams.html#FLAG_SHOW_WHEN_LOCKED" rel="noreferrer">http://developer.android.com/reference/android/view/WindowManager.LayoutParams.html#FLAG_SHOW_WHEN_LOCKED</a><br> <a href="http://developer.android.com/reference/android/view/WindowManager.LayoutParams.html#FLAG_KEEP_SCREEN_ON" rel="noreferrer">http://developer.android.com/reference/android/view/WindowManager.LayoutParams.html#FLAG_KEEP_SCREEN_ON</a><br> <a href="http://developer.android.com/reference/android/view/WindowManager.LayoutParams.html#FLAG_TURN_SCREEN_ON" rel="noreferrer">http://developer.android.com/reference/android/view/WindowManager.LayoutParams.html#FLAG_TURN_SCREEN_ON</a></p> <p>If you want to run on older versions of the platform that don't support the desired flag(s), you can directly use wake locks and keyguard locks... but that path is fraught with peril.</p> <p><strong>ONE IMPORTANT NOTE</strong>: Your activity <strong>must be full screen</strong> in order for the above flag combination to work. In my app I tried to use these flags with an activity which is not full screen (Dialog Theme) and it didn't work. After looking at the documentation I found that these flags require the window to be a full screen window.</p>
3,642,085
Make bundler use different gems for different platforms
<p>I'm working on upgrading one of our Rails 2.3.8 apps to Rails 3, and have run into an annoying problem with bundler and deployment. I develop the application on a Windows machine, but the production environment is running Ubuntu Linux. Now, my problem is that bundler is ignoring the <code>mysql</code> gem in the production environment, and Passenger spits out: <strong>"!!! Missing the mysql gem. Add it to your Gemfile: gem 'mysql', '2.8.1'"</strong></p> <p>Here is my <code>Gemfile</code>:</p> <pre><code># Edit this Gemfile to bundle your application's dependencies. # This preamble is the current preamble for Rails 3 apps; edit as needed. source 'http://rubygems.org' gem 'rails', '3.0.0' gem 'net-ldap', :require =&gt; 'net/ldap' gem 'highline', :require =&gt; 'highline/import' gem 'mysql', '2.8.1' gem 'net-ssh', :require =&gt; 'net/ssh' # Bundle gems for the local environment. Make sure to # put test-only gems in this group so their generators # and rake tasks are available in development mode: group :development, :test do gem 'fakeweb', :require =&gt; 'fakeweb' gem 'flexmock', :require =&gt; 'flexmock/test_unit' end </code></pre> <p>As you can see, the <code>mysql</code> gem is specified. However, when deploying, bundler ignores it. Why? The reason is that Bundler generates the following <code>Gemfile.lock</code> (only relevant parts included):</p> <pre><code>.... mime-types (1.16) mysql (2.8.1-x86-mingw32) net-ldap (0.1.1) .... </code></pre> <p>Notice that it includes the platform specific gem. This is obviously NOT what I want it to do, as that gem is not suitable (and appearently ignored) when running under Linux.</p> <p>So, does Bundler come with any way to deal with these issues? Or do I have to remember to manually change the mysql gem version in the generated <code>Gemfile.lock</code> every time I run bundle install on my development machine?</p> <p>Thank you in advance!</p> <p><strong>Update</strong></p> <p>It seems like the bundler team is aware of this <a href="https://github.com/carlhuda/bundler/issues#issue/635" rel="noreferrer">issue</a>.</p>
4,113,971
11
3
null
2010-09-04 11:40:55.71 UTC
15
2021-03-20 14:52:32.647 UTC
2010-11-05 12:06:34.07 UTC
null
347,687
null
347,687
null
1
47
ruby-on-rails|bundler
30,584
<p>This is a <a href="https://github.com/carlhuda/bundler/issues/646" rel="noreferrer">known issue in Bundler</a>. The workarounds are either:</p> <ul> <li>Generate a Gemfile.lock on a system similar enough to your production environment that you get results that match your production platform. Effectively, that means you can only generate the Gemfile.lock file on Windows if your production system is Windows.</li> <li>Don't commit a Gemfile.lock file at all, and determine dependencies on the production machine at deploy time (<code>bundle install</code> without <code>--deploy</code>). While not recommended in general, this is an often-used workaround until the bug is fixed. For example, this is the recommended solution offered by Heroku.</li> <li>Switch to JRuby, which would have the same platform string across both Windows and Linux (<code>java</code>). I don't recommend this seriously, but I believe it would fix the problem.</li> <li>Fix the problem in the Bundler source code, i.e., help the Bundler team fix the bug. :)</li> </ul>
3,345,785
Getting number of elements in an iterator in Python
<p>Is there an efficient way to know how many elements are in an iterator in Python, in general, without iterating through each and counting?</p>
3,345,871
19
1
null
2010-07-27 16:32:21.153 UTC
29
2022-01-16 16:10:03.017 UTC
2011-08-24 13:52:56.967 UTC
null
377,095
user248237
null
null
1
196
python|iterator
193,889
<p>No. It's not possible.</p> <p>Example:</p> <pre><code>import random def gen(n): for i in xrange(n): if random.randint(0, 1) == 0: yield i iterator = gen(10) </code></pre> <p>Length of <code>iterator</code> is unknown until you iterate through it.</p>
3,593,420
Is there a way to get the source code from an APK file?
<p>The hard drive on my laptop just crashed and I lost all the source code for an app that I have been working on for the past two months. All I have is the APK file that is stored in my email from when I sent it to a friend. </p> <p>Is there any way to extract my source code from this APK file?</p>
6,081,365
31
12
null
2010-08-29 03:40:13.51 UTC
976
2022-08-26 10:40:24.51 UTC
2014-04-04 16:20:52.137 UTC
null
1,864,167
null
426,041
null
1
1,421
android|android-resources|decompiling|apk
1,384,978
<p>Simple way: use online tool <a href="https://www.decompiler.com/" rel="nofollow noreferrer">https://www.decompiler.com/</a>, upload apk and get source code.</p> <hr /> <p>Procedure for decoding .apk files, step-by-step method:</p> <h3>Step 1:</h3> <ol> <li><p>Make a new folder and copy over the .apk file that you want to decode.</p> </li> <li><p>Now rename the extension of this .apk file to .zip (e.g. rename from filename.apk to filename.zip) and save it. Now you can access the classes.dex files, etc. At this stage you are able to see drawables but not xml and java files, so continue.</p> </li> </ol> <h3>Step 2:</h3> <ol> <li><p>Now extract this .zip file in the same folder (or NEW FOLDER).</p> </li> <li><p><a href="https://github.com/pxb1988/dex2jar" rel="nofollow noreferrer">Download dex2jar</a> (Don't download the code, click on the releases button that's on the right then download that) and extract it to the same folder (or NEW FOLDER).</p> </li> <li><p>Move the classes.dex file into the dex2jar folder.</p> </li> <li><p>Now open command prompt and change directory to that folder (or NEW FOLDER). Then write <code>d2j-dex2jar classes.dex</code> (for mac terminal or ubuntu write <code>./d2j-dex2jar.sh classes.dex</code>) and press enter. You now have the classes.dex.dex2jar file in the same folder.</p> </li> <li><p><a href="http://jd.benow.ca/" rel="nofollow noreferrer">Download java decompiler</a>, double click on jd-gui, click on open file, and open classes.dex.dex2jar file from that folder: now you get class files.</p> </li> <li><p>Save all of these class files (In jd-gui, click File -&gt; Save All Sources) by src name. At this stage you get the java source but the .xml files are still unreadable, so continue.</p> </li> </ol> <h3>Step 3:</h3> <p>Now open another new folder</p> <ol> <li><p>Put in the .apk file which you want to decode</p> </li> <li><p>Download the latest version of <a href="http://ibotpeaches.github.io/Apktool/install/" rel="nofollow noreferrer">apktool <strong>AND</strong> apktool install window</a> (both can be downloaded from the same link) and place them in the same folder</p> </li> <li><p>Open a command window</p> </li> <li><p>Now run command like <code>apktool if framework-res.apk</code> (if you don't have it <a href="http://www.androidfilehost.com/?fid=23212708291677144" rel="nofollow noreferrer">get it here</a>)and next</p> </li> <li><p><code>apktool d myApp.apk</code> (where myApp.apk denotes the filename that you want to decode)</p> </li> </ol> <p>now you get a file folder in that folder and can easily read the apk's xml files.</p> <h3>Step 4:</h3> <p>It's not any step, just copy contents of both folders(in this case, both new folders) to the single one</p> <p>and enjoy the source code...</p>
8,222,127
Changing integer to binary string of digits
<p>I'm currently working on a simulation of the MIPS processor in C++ for a comp architecture class and having some problems converting from decimal numbers to binary (signed numbers both ways). Everything's working fine until the very last bit because my current algorithm falls into out of bounds areas for int on 1&lt;&lt;=31. Just need a nudge in the right direction to get it up and running. Thanks!</p> <pre><code>//Assume 32 bit decimal number string DecimalToBinaryString(int a) { string binary = ""; int mask = 1; for(int i = 0; i &lt; 31; i++) { if((mask&amp;a) &gt;= 1) binary = "1"+binary; else binary = "0"+binary; mask&lt;&lt;=1; } cout&lt;&lt;binary&lt;&lt;endl; return binary; } </code></pre> <p>I'm also including my other algorithm for completeness. I apologize for the lack of comments, but it's fairly straight forward.</p> <pre><code>int BinaryStringToDecimal(string a) { int num = 0; bool neg = false; if(a.at(0) == '1') { neg = true; for(int x = a.length()-1; x &gt;= 0; x--) { if(a.at(x) == '1') a.at(x) = '0'; else a.at(x) = '1'; } a.at(a.length()-1) += 1; for(int x = a.length()-1; x &gt;= 0; x--) { if(a.at(x) == '2') { if(x-1 &gt;= 0) { if(a.at(x-1) == '1') a.at(x-1) = '2'; if(a.at(x-1) == '0') a.at(x-1) = '1'; a.at(x) = '0'; } } else if(a.at(x) == '3') { if(x-1 &gt;= 0) a.at(x-1) += '2'; a.at(x) = '1'; } } if(a.at(0) == '2') a.at(0) = '0'; else if(a.at(0) == '3') a.at(0) = '1'; } for(int x = a.length()-1; x &gt;= 0; x--) { if(a.at(x) == '1') num += pow(2.0, a.length()-x-1); } if(neg) num = num*-1; return num; } </code></pre> <p>Also if anyone knows any good ways to go about writing these more efficiently I'd love to hear it. I've only had the two introductory programming classes but have been playing with different techniques to see how well I like their style.</p>
8,224,393
5
3
null
2011-11-22 04:48:28.607 UTC
11
2016-09-25 00:28:53.343 UTC
null
null
null
null
684,594
null
1
36
c++|algorithm|binary
103,064
<p>There are actually standard one-liners for these.</p> <pre><code>#include &lt;bitset&gt; std::string s = std::bitset&lt; 64 &gt;( 12345 ).to_string(); // string conversion std::cout &lt;&lt; std::bitset&lt; 64 &gt;( 54321 ) &lt;&lt; ' '; // direct output std::bitset&lt; 64 &gt; input; std::cin &gt;&gt; input; unsigned long ul = input.to_ulong(); </code></pre> <p><a href="http://ideone.com/kMYOJ" rel="noreferrer">See this run as a demo</a>.</p>
4,449,810
using position() function in xslt
<pre><code>&lt;EmployeeDetails&gt; &lt;Employee&gt; &lt;Name&gt;TEST&lt;/Name&gt; &lt;/Employee&gt; &lt;Employee&gt; &lt;Name&gt;TEST&lt;/Name&gt; &lt;/Employee&gt; &lt;Employee&gt; &lt;Name&gt;TEST&lt;/Name&gt; &lt;/Employee&gt; &lt;Employee&gt; &lt;Name&gt;TEST&lt;/Name&gt; &lt;/Employee&gt; &lt;Employee&gt; &lt;Name&gt;TEST&lt;/Name&gt; &lt;/Employee&gt; &lt;/EmployeeDetails&gt; </code></pre> <p>I tried using xslt as below :</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xd="http://www.oxygenxml.com/ns/doc/xsl" exclude-result-prefixes="xd" version="1.0"&gt; &lt;xsl:template match="EmployeeDetails/Employee"&gt; &lt;xsl:copy&gt; &lt;xsl:attribute name="id"&gt;&lt;xsl:value-of select="position()"/&gt;&lt;/xsl:attribute&gt; &lt;/xsl:copy&gt; &lt;/xsl:template&gt; &lt;xsl:template match="*"&gt; &lt;xsl:element name="{local-name()}"&gt; &lt;xsl:apply-templates select="@*|node()"/&gt; &lt;/xsl:element&gt; &lt;/xsl:template&gt; &lt;xsl:template match="@*"&gt; &lt;xsl:attribute name="{local-name()}"&gt; &lt;xsl:value-of select="."/&gt; &lt;/xsl:attribute&gt; &lt;/xsl:template&gt; &lt;/xsl:stylesheet&gt; </code></pre> <p>For above xslt the output for position() is printing as 2,4,6,8,10.</p> <p>and the output should be :</p> <pre><code>&lt;EmployeeDetails&gt; &lt;Employee id="1"&gt; &lt;Name&gt;TEST&lt;/Name&gt; &lt;/Employee&gt; &lt;Employee id="2"&gt; &lt;Name&gt;TEST&lt;/Name&gt; &lt;/Employee&gt; &lt;Employee id="3"&gt; &lt;Name&gt;TEST&lt;/Name&gt; &lt;/Employee&gt; &lt;Employee id="4"&gt; &lt;Name&gt;TEST&lt;/Name&gt; &lt;/Employee&gt; &lt;Employee id="5"&gt; &lt;Name&gt;TEST&lt;/Name&gt; &lt;/Employee&gt; &lt;/EmployeeDetails&gt; </code></pre> <p>How to print as a sequence like 1,2,3.... for id attribute.</p>
4,450,799
3
2
null
2010-12-15 12:21:49.453 UTC
4
2010-12-15 14:11:32.89 UTC
null
null
null
null
431,714
null
1
13
xslt
89,650
<p>The <code>xsl:number</code> instruction was made precisely for this task:</p> <pre><code>&lt;xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt; &lt;xsl:template match="Employee"&gt; &lt;xsl:copy&gt; &lt;xsl:apply-templates select="@*"/&gt; &lt;xsl:attribute name="id"&gt; &lt;xsl:number/&gt; &lt;/xsl:attribute&gt; &lt;xsl:apply-templates select="node()"/&gt; &lt;/xsl:copy&gt; &lt;/xsl:template&gt; &lt;xsl:template match="*"&gt; &lt;xsl:element name="{local-name()}"&gt; &lt;xsl:apply-templates select="@*|node()"/&gt; &lt;/xsl:element&gt; &lt;/xsl:template&gt; &lt;xsl:template match="@*"&gt; &lt;xsl:attribute name="{local-name()}"&gt; &lt;xsl:value-of select="."/&gt; &lt;/xsl:attribute&gt; &lt;/xsl:template&gt; &lt;/xsl:stylesheet&gt; </code></pre> <p>Output:</p> <pre><code>&lt;EmployeeDetails&gt; &lt;Employee id="1"&gt; &lt;Name&gt;TEST&lt;/Name&gt; &lt;/Employee&gt; &lt;Employee id="2"&gt; &lt;Name&gt;TEST&lt;/Name&gt; &lt;/Employee&gt; &lt;Employee id="3"&gt; &lt;Name&gt;TEST&lt;/Name&gt; &lt;/Employee&gt; &lt;Employee id="4"&gt; &lt;Name&gt;TEST&lt;/Name&gt; &lt;/Employee&gt; &lt;Employee id="5"&gt; &lt;Name&gt;TEST&lt;/Name&gt; &lt;/Employee&gt; &lt;/EmployeeDetails&gt; </code></pre>
4,055,450
CouchDB Authorization on a Per-Database Basis
<p>I'm working on an application supported by CouchDB. Essentially, I want to create a database for each individual user of my app. To accomplish this, the admin user will create the database, but going forward, the user will need to access their database (using HTTP Auth over SSL). I've been having a hell of a time figuring this out. </p> <p>The best resource I have found is in the CouchDB wiki, at this link:</p> <p><a href="http://wiki.apache.org/couchdb/Security_Features_Overview#Authorization" rel="noreferrer">http://wiki.apache.org/couchdb/Security_Features_Overview#Authorization</a></p> <p>It suggests that you can set per-database authorization by creating a document called "_security" to which you add a hash of admins and readers. When I attempt to create that document, the message I get back is "Bad special document member: _security".</p> <pre><code>$ curl -X GET http://localhost:5984 {"couchdb":"Welcome","version":"1.0.1"} </code></pre> <p>Any help would be appreciated!</p> <p>Cheers,</p> <p>Aaron.</p>
4,057,110
3
1
null
2010-10-29 19:59:11.93 UTC
47
2013-06-05 11:54:11.013 UTC
2013-02-25 15:24:51.683 UTC
null
203,204
null
105,728
null
1
27
security|couchdb
16,941
<p>There should be no problem with that aproach.</p> <p>Let's say you have a database "test", and have an admin account already:</p> <pre><code>curl -X PUT http://localhost:5984/test -u "admin:123" </code></pre> <p>Now you can create a _security document for it:</p> <pre><code>curl -X PUT http://localhost:5984/test/_security -u "admin:123" -d '{"admins":{"names":[], "roles":[]}, "readers":{"names":["joe"],"roles":[]}}' </code></pre> <p>Them only the user "joe" will be able to read the database. To create the user you must have already the sha1 hashed password:</p> <pre><code>curl -X POST http://localhost:5984/_users -d '{"_id":"org.couchdb.user:joe","type":"user","name":"joe","roles":[],"password_sha":"c348c1794df04a0473a11234389e74a236833822", "salt":"1"}' -H "Content-Type: application/json" </code></pre> <p>This user have the password "123" hashed using sha1 with salt "1" (sha1("123"+"1")), so he can read the database:</p> <pre><code>curl -X GET http://localhost:5984/test -u "joe:123" </code></pre> <p>He can read any document now on that database, and no other user (but him and admin) can.</p> <p><strong>UPDATED: Writer security</strong></p> <p>The above method issues the reader problem, but the reader permission here actually mean "read/write common docs", so it allows to write docs except for design-docs. The "admin"s in the _security doc are allowed to write do design-docs in this database.</p> <p>The other approach, as taken from your own answer, is the "validate_doc_update", you can have a validate_doc_update as follow in a file:</p> <pre><code>function(new_doc, old_doc, userCtx) { if(!userCtx || userCtx.name != "joe") { throw({forbidden: "Bad user"}); } } </code></pre> <p>And push it into a couchdb design:</p> <pre><code>curl -X PUT http://localhost:5984/test/_design/security -d "{ \"validate_doc_update\": \"function(new_doc,doc,userCtx) { if(userCtx || userCtx.name != 'joe') {throw({forbidden: 'Bad user'})}}\"}" --user 'admin:123' </code></pre> <p>Them "joe" can write to the database using Basic Authentication:</p> <pre><code>curl -X PUT http://localhost:5984/test/foobar -d '{"foo":"bar"}' -u 'joe:123' </code></pre> <p>As you also addressed you can use the _session api to get a cookie for authentication:</p> <pre><code>curl http://localhost:5984/_session -v -X POST -d 'name=joe&amp;password=123' -H "Content-Type: application/x-www-form-urlencodeddata" </code></pre> <p>This will return a header like:</p> <pre><code>Set-Cookie: AuthSession=am9lOjRDRDE1NzQ1Oj_xIexerFtLI6EWrBN8IWYWoDRz; Version=1; Path=/; HttpOnly </code></pre> <p>So you can include the cookie "AuthSession=am9lOjRDRDE1NzQ1Oj_xIexerFtLI6EWrBN8IWYWoDRz" in your next requests and they will be authenticated.</p>
4,266,799
Why is the PHP string concatenation operator a dot (.)?
<p>In PHP, the <a href="http://php.net/manual/en/language.operators.string.php" rel="nofollow noreferrer">string operator</a> dot (.) is used to concatenate strings. For example:</p> <pre><code>$msg = &quot;Hello there, &quot; . $yourName; </code></pre> <p>The dot operator always seems to confuse people (myself included) the first time they see it, especially since when you use it to concatenate two strings, the operation does not throw an error, but just &quot;silently&quot; fails. It is also a common mistake when switching between PHP and other languages such as JavaScript, Python, etc. that do not use this operator.</p> <p>Why does the language use the dot (.) operator instead of a more widely accepted operator, such as plus (+)? Are there any historical reasons you can point to as to why this operator was selected? Is it just because the dot can cast other variable types to string? For example:</p> <pre><code>echo 1 . 2; // Prints the string &quot;12&quot; </code></pre>
4,266,859
3
8
null
2010-11-24 12:33:27.257 UTC
5
2021-05-16 10:40:47.573 UTC
2021-05-16 10:40:47.573 UTC
null
63,550
null
101,258
null
1
42
php|operators|string-concatenation
28,402
<p>I think it is a good idea to have a different operator, because dot and plus do completely different things.</p> <p>What does <code>"a string" + "another string";</code> actually mean, from a non specific language point of view? </p> <p>Does it mean</p> <ul> <li>Add the numerical value of the two strings, or,</li> <li>concatenate the two strings</li> </ul> <p>You would assume it is the second, but a plus sign is used for numerical addition in all cases except Strings. Why?</p> <p>Also, from a loosely typed point of view (which PHP is), a php script</p> <pre><code>$myvar = 1; $myvar2 = 2; // would we expect a concatenation or addition? $concat = $myvar + $myvar2; </code></pre> <p>The dot notation therefore specifies that it is clearly used for concatenation. </p> <p>It is not that it is confusing, it is that it is not intuitive because all the other languages do it in a different way. And, is this a good reason to follow the trend? Doing things the way they are always done, is not always the right way.</p>
4,493,525
What does f+++++++++ mean in rsync logs?
<p>I'm using <code>rsync</code> to make a backup of my server files, and I have two questions:</p> <ol> <li><p>In the middle of the process I need to stop and start <code>rsync</code> again.<br> Will <code>rsync</code> start from the point where it stopped or it will restart from the beginning?</p></li> <li><p>In the log files I see <code>"f+++++++++"</code>. What does it mean?</p></li> </ol> <p>e.g.:</p> <pre><code>2010/12/21 08:28:37 [4537] &gt;f.st...... iddd/logs/website-production-access_log 2010/12/21 08:29:11 [4537] &gt;f.st...... iddd/web/website/production/shared/log/production.log 2010/12/21 08:29:14 [4537] .d..t...... iddd/web/website/production/shared/sessions/ 2010/12/21 08:29:14 [4537] &gt;f+++++++++ iddd/web/website/production/shared/sessions/ruby_sess.017a771cc19b18cd 2010/12/21 08:29:14 [4537] &gt;f+++++++++ iddd/web/website/production/shared/sessions/ruby_sess.01eade9d317ca79a </code></pre>
12,037,164
3
0
null
2010-12-20 20:19:42.087 UTC
78
2022-06-11 12:21:13.323 UTC
2019-12-08 10:43:46.17 UTC
null
775,954
null
449,613
null
1
135
backup|logging|rsync
95,571
<p>Let's take a look at how rsync works and better understand the cryptic result lines:</p> <p>1 - A huge advantage of rsync is that after an interruption the next time it continues smoothly.</p> <p>The next rsync invocation will not transfer the files again, that it had already transferred, if they were not changed in the meantime. But it will start checking all the files again from the beginning to find out, as it is not aware that it had been interrupted.</p> <p>2 - Each character is a code that can be translated if you read the section for <code>-i, --itemize-changes</code> in <code>man rsync</code></p> <p>Decoding your example log file from the question:</p> <h3>>f.st......</h3> <pre><code>&gt; - the item is received f - it is a regular file s - the file size is different t - the time stamp is different </code></pre> <h3>.d..t......</h3> <pre><code>. - the item is not being updated (though it might have attributes that are being modified) d - it is a directory t - the time stamp is different </code></pre> <h3>>f+++++++++</h3> <pre><code>&gt; - the item is received f - a regular file +++++++++ - this is a newly created item </code></pre> <hr /> <p>The relevant part of the <a href="https://download.samba.org/pub/rsync/rsync.1#opt--itemize-changes" rel="nofollow noreferrer">rsync man page</a>:</p> <blockquote> <p>-i, --itemize-changes</p> <p>Requests a simple itemized list of the changes that are being made to each file, including attribute changes. This is exactly the same as specifying --out-format='%i %n%L'. If you repeat the option, unchanged files will also be output, but only if the receiving rsync is at least version 2.6.7 (you can use -vv with older versions of rsync, but that also turns on the output of other verbose messages).</p> <p>The &quot;%i&quot; escape has a cryptic output that is 11 letters long. The general format is like the string YXcstpoguax, where Y is replaced by the type of update being done, X is replaced by the file-type, and the other letters represent attributes that may be output if they are being modified.</p> <p>The update types that replace the Y are as follows:</p> <ul> <li>A <code>&lt;</code> means that a file is being transferred to the remote host (sent).</li> <li>A <code>&gt;</code> means that a file is being transferred to the local host (received).</li> <li>A <code>c</code> means that a local change/creation is occurring for the item (such as the creation of a directory or the changing of a symlink, etc.).</li> <li>A <code>h</code> means that the item is a hard link to another item (requires --hard-links).</li> <li>A <code>.</code> means that the item is not being updated (though it might have attributes that are being modified).</li> <li>A <code>*</code> means that the rest of the itemized-output area contains a message (e.g. &quot;deleting&quot;).</li> </ul> <p>The file-types that replace the X are: <code>f</code> for a file, a <code>d</code> for a directory, an <code>L</code> for a symlink, a <code>D</code> for a device, and a <code>S</code> for a special file (e.g. named sockets and fifos).</p> <p>The other letters in the string above are the actual letters that will be output if the associated attribute for the item is being updated or a &quot;.&quot; for no change. Three exceptions to this are: (1) a newly created item replaces each letter with a &quot;+&quot;, (2) an identical item replaces the dots with spaces, and (3) an unknown attribute replaces each letter with a &quot;?&quot; (this can happen when talking to an older rsync).</p> <p>The attribute that is associated with each letter is as follows:</p> <ul> <li>A <code>c</code> means either that a regular file has a different checksum (requires --checksum) or that a symlink, device, or special file has a changed value. Note that if you are sending files to an rsync prior to 3.0.1, this change flag will be present only for checksum-differing regular files.</li> <li>A <code>s</code> means the size of a regular file is different and will be updated by the file transfer.</li> <li>A <code>t</code> means the modification time is different and is being updated to the sender’s value (requires --times). An alternate value of T means that the modification time will be set to the transfer time, which happens when a file/symlink/device is updated without --times and when a symlink is changed and the receiver can’t set its time. (Note: when using an rsync 3.0.0 client, you might see the s flag combined with t instead of the proper T flag for this time-setting failure.)</li> <li>A <code>p</code> means the permissions are different and are being updated to the sender’s value (requires --perms).</li> <li>An <code>o</code> means the owner is different and is being updated to the sender’s value (requires --owner and super-user privileges).</li> <li>A <code>g</code> means the group is different and is being updated to the sender’s value (requires --group and the authority to set the group).</li> <li>The <code>u</code> slot is reserved for future use.</li> <li>The <code>a</code> means that the ACL information changed.</li> <li>The <code>x</code> means that the extended attribute information changed.</li> </ul> <p>One other output is possible: when deleting files, the &quot;%i&quot; will output the string &quot;*deleting&quot; for each item that is being removed (assuming that you are talking to a recent enough rsync that it logs deletions instead of outputting them as a verbose message).</p> </blockquote>
4,146,621
changing colors with jquery with a color picker?
<p>i have this jquery script that changes the color of the background instantly by entering a color code into the textbox, the working example is in jsfiddle link below.</p> <p><a href="http://jsfiddle.net/7jg4e/" rel="noreferrer">http://jsfiddle.net/7jg4e/</a> </p> <p>but instead of the input field i wanted to use a color picker custom skin, becuase i dont want user to deal with hex code(just like twitter). the jquery plugin im trying to use is found at </p> <p><a href="http://www.eyecon.ro/colorpicker/" rel="noreferrer">http://www.eyecon.ro/colorpicker/</a></p> <p>at the buttom of the page it has the neat color picker with DOM element.</p> <p>so the problem is how am i going to change from the input type to the color picker div. thanks :))</p>
4,146,691
6
1
null
2010-11-10 16:26:43.153 UTC
4
2019-12-30 11:08:30.1 UTC
null
null
null
null
428,137
null
1
9
javascript|jquery|html|css|colors
38,067
<p>Replace the input element with a div use something like: (untested!)</p> <p>HTML</p> <pre><code>&lt;div id='colourPicker'&gt;&lt;/div&gt; </code></pre> <p>JS</p> <pre><code>$('#colourPicker').ColorPicker({ onChange: function(hsb, hex, rgb){ $("#full").css("background-color", '#' + hex); } }); </code></pre> <p>There's an example at the bottom of the link you have which shows you how.</p> <p><strong>Update for changing text</strong></p> <p>HTML</p> <pre><code>&lt;div id='colourPickerText'&gt;&lt;/div&gt; &lt;div id='textToBeChanged'&gt;Test text&lt;/div&gt; </code></pre> <p>JS</p> <pre><code>$('#colourPickerText').ColorPicker({ onChange: function(hsb, hex, rgb){ $("#textToBeChanged").css("color", '#' + hex); } }); </code></pre>
4,613,055
hibernate unique key validation
<p>I have a field, say, <code>user_name</code>, that should be unique in a table.</p> <p>What is the best way for validating it using Spring/Hibernate validation?</p>
4,733,441
6
0
null
2011-01-06 08:28:27.333 UTC
12
2021-04-03 16:49:03.663 UTC
2014-08-06 20:52:44.953 UTC
null
745,188
null
536,205
null
1
18
java|hibernate|spring|bean-validation|hibernate-validator
30,346
<p>One of the possible solutions is to create custom <code>@UniqueKey</code> constraint (and corresponding validator); and to look-up the existing records in database, provide an instance of <code>EntityManager</code> (or Hibernate <code>Session</code>)to <code>UniqueKeyValidator</code>.</p> <p><strong>EntityManagerAwareValidator</strong> </p> <pre><code>public interface EntityManagerAwareValidator { void setEntityManager(EntityManager entityManager); } </code></pre> <p><strong>ConstraintValidatorFactoryImpl</strong></p> <pre><code>public class ConstraintValidatorFactoryImpl implements ConstraintValidatorFactory { private EntityManagerFactory entityManagerFactory; public ConstraintValidatorFactoryImpl(EntityManagerFactory entityManagerFactory) { this.entityManagerFactory = entityManagerFactory; } @Override public &lt;T extends ConstraintValidator&lt;?, ?&gt;&gt; T getInstance(Class&lt;T&gt; key) { T instance = null; try { instance = key.newInstance(); } catch (Exception e) { // could not instantiate class e.printStackTrace(); } if(EntityManagerAwareValidator.class.isAssignableFrom(key)) { EntityManagerAwareValidator validator = (EntityManagerAwareValidator) instance; validator.setEntityManager(entityManagerFactory.createEntityManager()); } return instance; } } </code></pre> <p><strong>UniqueKey</strong></p> <pre><code>@Constraint(validatedBy={UniqueKeyValidator.class}) @Target({ElementType.TYPE}) @Retention(RUNTIME) public @interface UniqueKey { String[] columnNames(); String message() default "{UniqueKey.message}"; Class&lt;?&gt;[] groups() default {}; Class&lt;? extends Payload&gt;[] payload() default {}; @Target({ ElementType.TYPE }) @Retention(RUNTIME) @Documented @interface List { UniqueKey[] value(); } } </code></pre> <p><strong>UniqueKeyValidator</strong></p> <pre><code>public class UniqueKeyValidator implements ConstraintValidator&lt;UniqueKey, Serializable&gt;, EntityManagerAwareValidator { private EntityManager entityManager; @Override public void setEntityManager(EntityManager entityManager) { this.entityManager = entityManager; } private String[] columnNames; @Override public void initialize(UniqueKey constraintAnnotation) { this.columnNames = constraintAnnotation.columnNames(); } @Override public boolean isValid(Serializable target, ConstraintValidatorContext context) { Class&lt;?&gt; entityClass = target.getClass(); CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); CriteriaQuery&lt;Object&gt; criteriaQuery = criteriaBuilder.createQuery(); Root&lt;?&gt; root = criteriaQuery.from(entityClass); List&lt;Predicate&gt; predicates = new ArrayList&lt;Predicate&gt; (columnNames.length); try { for(int i=0; i&lt;columnNames.length; i++) { String propertyName = columnNames[i]; PropertyDescriptor desc = new PropertyDescriptor(propertyName, entityClass); Method readMethod = desc.getReadMethod(); Object propertyValue = readMethod.invoke(target); Predicate predicate = criteriaBuilder.equal(root.get(propertyName), propertyValue); predicates.add(predicate); } } catch (Exception e) { e.printStackTrace(); } criteriaQuery.where(predicates.toArray(new Predicate[predicates.size()])); TypedQuery&lt;Object&gt; typedQuery = entityManager.createQuery(criteriaQuery); List&lt;Object&gt; resultSet = typedQuery.getResultList(); return resultSet.size() == 0; } } </code></pre> <p><strong>Usage</strong></p> <pre><code>@UniqueKey(columnNames={"userName"}) // @UniqueKey(columnNames={"userName", "emailId"}) // composite unique key //@UniqueKey.List(value = {@UniqueKey(columnNames = { "userName" }), @UniqueKey(columnNames = { "emailId" })}) // more than one unique keys public class User implements Serializable { private String userName; private String password; private String emailId; protected User() { super(); } public User(String userName) { this.userName = userName; } .... } </code></pre> <p><strong>Test</strong></p> <pre><code>public void uniqueKey() { EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("default"); ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory(); ValidatorContext validatorContext = validatorFactory.usingContext(); validatorContext.constraintValidatorFactory(new ConstraintValidatorFactoryImpl(entityManagerFactory)); Validator validator = validatorContext.getValidator(); EntityManager em = entityManagerFactory.createEntityManager(); User se = new User("abc", poizon); Set&lt;ConstraintViolation&lt;User&gt;&gt; violations = validator.validate(se); System.out.println("Size:- " + violations.size()); em.getTransaction().begin(); em.persist(se); em.getTransaction().commit(); User se1 = new User("abc"); violations = validator.validate(se1); System.out.println("Size:- " + violations.size()); } </code></pre>
4,834,973
Decimal values in SQL for dividing results
<p>In SQL, I have <code>col1</code> and <code>col2</code>. Both are integers.</p> <p>I want to do like:</p> <pre><code>select col1/col2 from tbl1 </code></pre> <p>I get the result <code>1</code> where <code>col1=3</code> and <code>col2=2</code></p> <p>The result I want is <code>1.1</code></p> <p>I put <code>round(col1/col2,2)</code>. The result is still 1.</p> <p>I put <code>decimal(col1/col2,2)</code>. The decimal is not built in function.</p> <p>How can I do exactly to get 1.1?</p>
4,834,981
6
3
null
2011-01-29 03:31:26.403 UTC
10
2019-10-29 11:17:09.217 UTC
2016-05-15 12:22:05.583 UTC
null
437,763
null
398,909
null
1
68
sql-server|sql-server-2005
266,501
<p>You will need to cast or convert the values to decimal before division. Take a look at this <a href="http://msdn.microsoft.com/en-us/library/aa226054.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/aa226054.aspx</a></p> <p>For example</p> <pre><code>DECLARE @num1 int = 3 DECLARE @num2 int = 2 SELECT @num1/@num2 SELECT @num1/CONVERT(decimal(4,2), @num2) </code></pre> <p>The first SELECT will result in what you're seeing while the second SELECT will have the correct answer <code>1.500000</code></p>
14,414,393
Testing Controllers in Symfony2 with Doctrine
<p>I have created a very simple REST controller in Symony2 with Database insert/updates/deletes in the controller actions.</p> <p>Is there a nice way to write unit/integration tests for these controller actions without polluting the production database? Do I have to work with different environments - or is there a proposed way from the framework vendor for this?</p> <p>Current Controller Example:</p> <pre><code>public function postAction() { $json = $this-&gt;getRequest()-&gt;getContent(); $params = json_decode($json); $name = $params-&gt;name; $description = $params-&gt;description; $sandbox = new Sandbox(); $sandbox-&gt;setName($name); $sandbox-&gt;setDescription($description); $em = $this-&gt;getDoctrine()-&gt;getManager(); $em-&gt;persist($sandbox); $em-&gt;flush(); $response = new Response('/sandbox/'.$sandbox-&gt;getId()); $response-&gt;setStatusCode(201); return $response; } </code></pre> <p>Current Test Example:</p> <pre><code>class SandboxControllerTest extends WebTestCase { public function testRest() { $client = static::createClient(); $crawler = $client-&gt;request('POST', '/service/sandbox', array(), array(), array(), json_encode(array('name' =&gt; 'TestMe', 'description' =&gt; 'TestDesc'))); $this-&gt;assertEquals( 201, $client-&gt;getResponse()-&gt;getStatusCode() ); } } </code></pre>
14,414,605
3
3
null
2013-01-19 12:33:14.193 UTC
9
2014-10-27 14:39:36.137 UTC
null
null
null
null
834,114
null
1
9
php|symfony|phpunit|symfony-2.1
8,389
<p>In my opinion you should definitely avoid change database with your tests.</p> <p>My favourite way to achieve this is inject entity manager mock inside a test client. For example:</p> <pre><code>public function testRest() { // create entity manager mock $entityManagerMock = $this-&gt;getMockBuilder('Doctrine\ORM\EntityManager') -&gt;setMethods(array('persist', 'flush')) -&gt;disableOriginalConstructor() -&gt;getMock(); // now you can get some assertions if you want, eg.: $entityManagerMock-&gt;expects($this-&gt;once()) -&gt;method('flush'); // next you need inject your mocked em into client's service container $client = static::createClient(); $client-&gt;getContainer()-&gt;set('doctrine.orm.default_entity_manager', $entityManagerMock); // then you just do testing as usual $crawler = $client-&gt;request('POST', '/service/sandbox', array(), array(), array(), json_encode(array('name' =&gt; 'TestMe', 'description' =&gt; 'TestDesc'))); $this-&gt;assertEquals( 201, $client-&gt;getResponse()-&gt;getStatusCode() ); } </code></pre> <p>One thing with this solution which you should be aware is that you need inject your mocked service before each request. This is because the client reboots a kernel between each request (which means that the container is rebuild as well).</p> <p><strong>edit:</strong></p> <p>My GET approach in controller's tests is that I can mock entity repositories and so on in order to stub every getting data from db but it's a lot of work and it's not very comfortable, so I prefer in this case (I mean only if we speak about controller's test) actually getting real data from db. By real data I mean data created with doctrine fixtures. And as long as we don't change database we can depend on the fixtures.</p> <p>But if we are speaking about changing data inside db (POST/PUT/DELETE methods) I always use mocks. If you'll use em mock and set appropriate expectations on "perist" and "flush" methods, you can be sure that the data is correctly created/updated/deleted actually without any database's modifications.</p>
14,663,543
Memory limits on Arduino
<p>I have recently bought an <a href="http://en.wikipedia.org/wiki/Arduino#ArduinoUno">Arduino Uno</a>, and now I am experimenting a bit with it. I have a couple of 18B20 sensors and an ENC28J60 network module connected to it, then I am making a sketch to allow me to connect to it from a browser and read out the temperatures either as a simple web page or as <a href="http://en.wikipedia.org/wiki/JSON">JSON</a>. The code that makes the web pages looks like this:</p> <pre><code>client.print("Inne: "); client.print(tempin); client.println("&lt;br /&gt;"); client.print("Ute: "); client.print(tempout); client.print("&lt;br /&gt;&lt;br /&gt;"); client.println(millis()/1000); // client.print("&lt;a href=\"/json\"&gt;j&lt;/a&gt;"); </code></pre> <p>The strange thing is: if I uncomment the last line, the sketch compiles fine, uploads fine, but I cannot get to connect to the board. The same thing happens if I add on some more characters in some of the other printouts. Thus, it looks to me as if I'm running into some kind of memory limit (the total size of the sketch is about 15&nbsp;KB, and there are some other strings used elsewhere in the code - and yes I know, I will rewrite it to use an array to store the temporaries, I've just stolen some code from an example).</p> <p>Is there any limit on how much memory I can use to store strings in an Arduino and are there any way to get around that? (using <a href="http://en.wikipedia.org/wiki/Graphical_user_interface">GUI</a> v 1.0.1 on a <a href="http://en.wikipedia.org/wiki/Debian">Debian</a> PC with GCC-AVR 4.3.5 and <a href="http://www.nongnu.org/avr-libc/">AVR Libc</a> 1.6.8).</p>
14,664,705
4
0
null
2013-02-02 15:45:08.103 UTC
8
2014-11-17 08:38:01.82 UTC
2013-02-09 12:09:46.94 UTC
null
63,550
null
1,396,864
null
1
11
arduino
18,654
<p>The RAM is rather small, as the UNO's 328 is only 2K. You may just be running out of RAM. I learned that when it runs out, it just kind of sits there.</p> <p>I suggest reading the <a href="https://github.com/mpflaga/Arduino-MemoryFree">readme</a> from this library to get the FreeRAM. It mentions how the ".print" can consume both RAM and ROM.</p> <p>I always now use (for Arduino IDE 1.0.+)</p> <pre><code>Serial.print(F("HELLO")); </code></pre> <p>versus</p> <pre><code>Serial.print("HELLO"); </code></pre> <p>as it saves RAM, and this should be true for lcd.print. Where I always put a</p> <pre><code>Serial.println(freeMemory(), DEC); // print how much RAM is available. </code></pre> <p>in the beginning of the code, and pay attention. Noting that there needs to be room to run the actual code and re-curse into its subroutines.</p> <p>For IDE's prior to 1.0.0 the library provides getPSTR()).</p> <p>IDE 1.0.3 now starts to display the expected usage of RAM at the end of the compile. However, I find it is often short, as it is only an estimate.</p> <hr> <p>I also recommend that you look at <a href="https://github.com/sirleech/Webduino">Webduino</a> as it has a library that supports JSON. Its examples are very quick to get going. However it does not directly support the ENC28J60.</p>
14,750,375
How to create unit tests against non in-memory database such as MySQL in Play framework, with resetting to known state?
<p>I want to create unit tests that cover code that use relational database in Play framework 2.1.0. There are many possibilities for this and all cause problems:</p> <h1>Testing on in-memory H2 database</h1> <p>Play framework documentation proposes to run unit tests on H2 in-memory database, even if main database used for development and production use other software (i.e. MySQL):</p> <pre class="lang-java prettyprint-override"><code>app = Helpers.fakeApplication(Helpers.inMemoryDatabase()); </code></pre> <p>My application don't use complicated RDBMS features such as stored procedures and most database access cases are ebean calls, so it should be compatible with both MySQL and H2.</p> <p>However, table creation statements in evolutions use MySQL-specific features, such as specifying <code>ENGINE = InnoDB</code>, <code>DEFAULT CHARACTER SET = utf8</code>, etc. I fear if I will remove these proprietary parts of <code>CREATE TABLE</code>, MySQL will use some default setting that I can't control and that depend on version, so to test and develop application main MySQL config must be modified. </p> <p>Anybody used this approach (making evolutions compatible with both MySQL and H2)?</p> <p>Other ideas how it can be handled:</p> <ul> <li>Separate evolutions for MySQL and H2 (not a good idea)</li> <li>Some way to make H2 ignore additional MySQL stuff in <code>create table</code> (MySQL compatibility mode don't work, it still complain even on <code>default character set</code>). I don't know how.</li> </ul> <h1>Testing on the same database driver as main database</h1> <p>The only advantage of H2 in-memory database that it is fast, and testing on the same database driver than dev/production database may be better, because it is closer to real environment.</p> <p>How it can be done right in Play framework?</p> <p>Tried:</p> <pre class="lang-java prettyprint-override"><code>Map&lt;String, String&gt; settings = new HashMap&lt;String, String&gt;(); settings.put("db.default.url", "jdbc:mysql://localhost/sometestdatabase"); settings.put("db.default.jndiName", "DefaultDS"); app = Helpers.fakeApplication(settings); </code></pre> <p>Looks like evolutions work here, but how it's best to clean database before each test? By creating custom code that truncates each table? If it will drop tables, then will evolutions run again before next test, or they are applied once per <code>play test</code> command? Or once per <code>Helpers.fakeApplication()</code> invocation?</p> <p>What are best practices here? Heard about <a href="http://www.dbunit.org/" rel="noreferrer">dbunit</a>, is it possible to integrate it without much pain and quirks?</p>
15,056,473
5
1
null
2013-02-07 11:46:43.373 UTC
15
2018-11-28 21:14:47.247 UTC
2013-02-25 06:20:36.8 UTC
null
123,642
null
123,642
null
1
23
unit-testing|playframework|playframework-2.0|database-testing
12,703
<p>First, I would recommend you to use the same RDBMS for testing and production as it could avoid some hard-to-find bugs.</p> <p>Concerning the need to clean your database between each test, you can use Ebean <code>DdlGenerator</code> to generate scripts to create a clean database and JUnit's <code>@Before</code> annotation to automatically execute these scripts before every test.</p> <p>Using the <code>DdlGenerator</code> can be done like this :</p> <pre><code> EbeanServer server = Ebean.getServer(serverName); ServerConfig config = new ServerConfig(); DdlGenerator ddl = new DdlGenerator((SpiEbeanServer) server, new MySqlPlatform(), config); </code></pre> <p>This code can be placed in a base-class that you could make inherit your tests (or inside a custom <code>Runner</code> that you can use with the <code>@RunWith</code> annotation).</p> <p>It will also allow you to easily automate the <code>FakeApplication</code> creation, avoiding some boilerplate code.</p> <p>Some links that can be helpful : </p> <ul> <li><a href="http://blog.matthieuguillermin.fr/2012/03/unit-testing-tricks-for-play-2-0-and-ebean/">http://blog.matthieuguillermin.fr/2012/03/unit-testing-tricks-for-play-2-0-and-ebean/</a> </li> <li><a href="https://gist.github.com/nboire/2819920">https://gist.github.com/nboire/2819920</a></li> </ul>
14,615,669
Convert object's properties and values to array of key value pairs
<p>I'm fairly new to JavaScript and am not sure this is possible to do but basically I would like to take an object and convert it into an array of strings in the format; <code>array[0] = 'prop1=value1'</code></p> <p>The reasoning behind this is that I'm having a user enter a list of k=v pairs into a form, later it's written as an object within a json blob. Going from the key value csl to the json object was simple, now I need to go back the other way (I've received the JSON via an ajax call and want to populate a blank form). Is this possible in JavaScript? If not please offer a reasonable work around.</p> <p>Sample code;</p> <p>Object in debugger;</p> <pre><code> Object private_key: "private-key" public_key: "public-key" </code></pre> <p>I need to convert that to;</p> <pre><code> "private_key=private-key,public_key=public-key" </code></pre> <p>Basically I need something like this (pseudo code)</p> <pre><code>var outputString = ''; foreach (prop in obj) { outputString = outputString + prop.tostring() + '=' + prop.value + ','; } </code></pre>
14,615,788
7
6
null
2013-01-30 23:15:55.247 UTC
8
2021-01-19 00:29:57.34 UTC
2013-01-30 23:32:00.89 UTC
null
763,585
null
763,585
null
1
23
javascript|reflection|introspection
64,720
<p>You're probably looking for something along the lines of</p> <pre><code>var obj = {value1: 'prop1', value2: 'prop2', value3: 'prop3'}; var arr = []; for (var key in obj) { if (obj.hasOwnProperty(key)) { arr.push(key + '=' + obj[key]); } }; var result = arr.join(','); alert(result); </code></pre> <p>Notice that it will work fine if your values are strings; if they're complex objects then you'll need to add more code.</p> <p>Or you can just use <a href="https://api.jquery.com/jquery.param/" rel="noreferrer">jQuery.param</a>, which does what you want, even for complex types (although it uses the <code>&amp;</code> character as the separator, instead of the comma.</p>
14,476,875
ORA-01017 Invalid Username/Password when connecting to 11g database from 9i client
<p>I'm trying to connect to a schema on 11g (v11.2.0.1.0) from a PC with 9i (v9.2.0.1) client. It seems to connect fine to some schemas, but not this one - it comes back with a <code>ORA-01017 Invalid Username/Password</code> error every time.</p> <p>The username and password are DEFINITELY correct - can anyone think of a reason why this wouldn't work? </p> <p>Are there any fundamental incompatibilities between 9i and 11g?</p>
14,477,188
18
4
null
2013-01-23 09:59:58.733 UTC
11
2022-05-11 11:33:58.903 UTC
2016-03-13 17:31:02.183 UTC
null
2,306,173
null
1,578,653
null
1
69
oracle|oracle11g|oracle9i
780,664
<p>The user and password are DEFINITELY incorrect. Oracle 11g credentials are case sensitive.</p> <p>Try ALTER SYSTEM SET SEC_CASE_SENSITIVE_LOGON = FALSE; and alter password.</p> <p><a href="http://oracle-base.com/articles/11g/case-sensitive-passwords-11gr1.php" rel="noreferrer">http://oracle-base.com/articles/11g/case-sensitive-passwords-11gr1.php</a></p>
26,158,768
How to get textLabel of selected row in swift?
<p>So i am trying to get the value of the textLabel of the row I select. I tried printing it, but it didn't work. After some research I found out that this code worked, but only in Objective-C;</p> <pre><code> - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { NSLog(@"did select and the text is %@",[tableView cellForRowAtIndexPath:indexPath].textLabel.text);] } </code></pre> <p>I could not find any solution for Swift. Printing the indexpath.row is possible though, but that is not what I need.</p> <p>so what should I do? or what is the 'Swift-version' of this code?</p>
26,159,065
8
0
null
2014-10-02 10:17:13.407 UTC
13
2020-03-24 20:25:37.33 UTC
null
null
null
null
4,057,658
null
1
41
uitableview|swift|ios8|tableview|xcode6
125,924
<p>Try this:</p> <pre><code>override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let indexPath = tableView.indexPathForSelectedRow() //optional, to get from any UIButton for example let currentCell = tableView.cellForRowAtIndexPath(indexPath) as UITableViewCell print(currentCell.textLabel!.text) </code></pre>
40,563,479
Relationship between R Markdown, Knitr, Pandoc, and Bookdown
<p>What is the relationship between the functionality of R Markdown, Knitr, Pandoc, and Bookdown?</p> <p>Specifically what is the 'division of labour' between these packages in converting markup documents with embedded R code (e.g. <code>.Rnw</code> or <code>.Rmd</code>) into final outputs (e.g. <code>.pdf</code> or <code>.html</code>)? And if Knitr is used to process RMarkdown, what does the <code>rmarkdown</code> package do and how is it different to the <code>markdown package</code>?</p>
40,563,480
1
0
null
2016-11-12 13:45:42.133 UTC
56
2021-10-09 00:26:43.653 UTC
2016-11-27 12:00:42.757 UTC
null
1,779,128
null
1,779,128
null
1
115
r|knitr|r-markdown|pandoc|bookdown
22,727
<h1>Pandoc</h1> <p>Pandoc is a document converter. It can convert from a number of different markup formats to many other formats, such as <code>.doc</code>, <code>.pdf</code> etc. </p> <p>Pandoc is a command line tool with no GUI. It is an independent piece of software, separate from R. However, it comes bundled with R Studio because <code>rmarkdown</code> relies on it for document conversion. </p> <p>Pandoc not only converts documents, but it also adds functionality on top of the base markdown language to enable it to support more complex outputs.</p> <h1>R Markdown</h1> <p>R Markdown is based on markdown:</p> <h3>Markdown (markup language)</h3> <p>Markdown is a lightweight markup language with plain text formatting syntax designed so that it can be converted to HTML and many other formats. A markdown file is a plain text file that is typically given the extension <code>.md</code>.</p> <p>Like other markup languages like HTML and Latex, it is completely independent from R.</p> <p>There is no clearly defined Markdown standard. This has led to fragmentation as different vendors write their own variants of the language to correct flaws or add missing features.</p> <h3>Markdown (R package)</h3> <p><a href="https://cran.r-project.org/web/packages/markdown/index.html" rel="noreferrer"><code>markdown</code></a> is an R package which converts <code>.Rmd</code> files into HTML. It is the predecessor of <a href="https://cran.r-project.org/web/packages/rmarkdown/index.html" rel="noreferrer"><code>rmarkdown</code></a>, which offers much more functionality. It is no longer recommended for use.</p> <h3>R Markdown (markup language)</h3> <p>R Markdown is an extension of the markdown syntax. R Markdown files are plain text files that typically have the file extension <code>.Rmd</code>. They are written using an extension of markdown syntax that enables R code to be embedded in them in a way which can later be executed. </p> <p>Because they are expected to be processed by the <code>rmarkdown</code> package, it is possible to use <a href="http://pandoc.org/MANUAL.html#pandocs-markdown" rel="noreferrer">Pandoc markdown syntax</a> as part of a R markdown file. This is an extension to the original markdown syntax that provides additional functionality like raw HTML/Latex and tables.</p> <h3>R Markdown (package)</h3> <p>The R package <code>rmarkdown</code> is a library which proceses and converts <code>.Rmd</code> files into a number of different formats.</p> <p>The core function is <code>rmarkdown::render</code> which <a href="https://blog.rstudio.org/2014/06/18/r-markdown-v2/" rel="noreferrer">stands on the shoulders of pandoc</a>. This function <a href="https://www.rdocumentation.org/packages/rmarkdown/versions/0.1.2/topics/render?" rel="noreferrer">'renders the input file to the specified output format using pandoc. If the input requires knitting then <code>knitr::knit</code> is called prior to pandoc.</a></p> <p>The RMarkdown package's aim is simply <a href="https://blog.rstudio.org/2014/06/18/r-markdown-v2/" rel="noreferrer">to provide reasonably good defaults and an R-friendly interface to customize Pandoc options.</a>.</p> <p>The YAML metadata seen at the top of RMarkdown files is specificially to pass options to <code>rmarkdown::render</code>, to guide the build process.</p> <p>Note that RMarkdown only deals with markdown syntax. If you want to convert a <code>.Rhtml</code> or a <code>.Rnw</code> file, you should use the convenience functions built into <code>Knitr</code>, such as <code>knitr::knit2html</code> and <code>knitr:knit2pdf</code></p> <h1>Knitr</h1> <p>Knitr takes a plain text document with embedded code, executes the code and 'knits' the results back into the document.</p> <p>For for example, it converts </p> <ul> <li>An <a href="https://github.com/yihui/knitr-examples/blob/master/001-minimal.Rmd" rel="noreferrer">R Markdown (<code>.Rmd</code>)</a> file into a standard markdown file (<code>.md</code>) </li> <li>An <a href="https://github.com/yihui/knitr/blob/master/inst/examples/knitr-minimal.Rnw" rel="noreferrer"><code>.Rnw</code> (Sweave)</a> file into to <code>.tex</code> format. </li> <li>An <a href="https://github.com/yihui/knitr-examples/blob/master/003-minimal.Rhtml" rel="noreferrer"><code>.Rhtml</code></a> file into to html.</li> </ul> <p>The core function is <code>knitr::knit</code> and by default this will look at the input document and try and guess what type it is - Rnw, Rmd etc.</p> <p>This core function performs three roles: - A source parser, which looks at the input document and detects which parts are code that the user wants to be evaluated. - A code evaluator, which evaluates this code - An output renderer, which writes the results of evaluation back to the document in a format which is interpretable by the raw output type. For instance, if the input file is an <code>.Rmd</code>, the output render marks up the output of code evaluation in <code>.md</code> format.</p> <h3>Converting between document formats</h3> <p>Knitr does <em>not</em> convert between document formats - such as converting a <code>.md</code> into a <code>.html</code>. It does, however, provide some convenience functions to help you use other libraries to do this. <em>If you are using the <code>rmarkdown</code> package, you should ignore this functionality because it has been superceded by <code>rmarkdown::render</code>.</em></p> <p>An example is <code>knitr:knit2pdf</code> which will: <a href="https://www.rforge.net/doc/packages/knitr/knit2pdf.html" rel="noreferrer">'Knit the input Rnw or Rrst document, and compile to PDF using texi2pdf or rst2pdf'.</a></p> <p>A potential source of confusion is <code>knitr::knit2html</code>, which <a href="https://rforge.net/doc/packages/knitr/knit2html.html" rel="noreferrer">"is a convenience function to knit the input markdown source and call <code>markdown::markdownToHTML</code> to convert the result to HTML."</a> This is now legacy functionality because the <code>markdown</code> package has been superceded by the <code>rmarkdown</code> package. See <a href="https://rforge.net/doc/packages/knitr/knit2html.html" rel="noreferrer">this note</a>.</p> <h1>Bookdown</h1> <p>The bookdown package is built on top of R Markdown, and inherits the simplicity of the Markdown syntax , as well as the possibility of multiple types of output formats (PDF/HTML/Word/…). </p> <p>It offers features like multi-page HTML output, numbering and cross-referencing figures/tables/sections/equations, inserting parts/appendices, and imported the GitBook style (<a href="https://www.gitbook.com" rel="noreferrer">https://www.gitbook.com</a>) to create elegant and appealing HTML book pages. </p>
9,654,581
include a PHP result in img src tag
<p>I am trying to do something I know is probably simple, but I am having the worst time. I have functioning so far: 1.Script to upload image files to server 2. write the image file names to the database 3. I want to retrieve the image filename from the db and add it to the img src tag here is my retrieval script</p> <pre><code> &lt;?php $hote = 'localhost'; $base = 'dbasename'; $user = 'username'; $pass = '******'; $cnx = mysql_connect ($hote, $user, $pass) or die(mysql_error ()); $ret = mysql_select_db ($base) or die (mysql_error ()); $image_id = mysql_real_escape_string($_GET['ID']); $sql = "SELECT image FROM image_upload WHERE ID ='$image_id'"; $result = mysql_query($sql); $image = mysql_result($result, 0); header('Content-Type: text/html'); echo '&lt;img src="' $image'"/&gt;'; ?&gt; </code></pre> <p>I was trying to pass the Value through image.php?ID=2 but no luck</p> <p>The PHP script successfully returns the filename, but I cannot for the life of me get it to print it to the html</p> <p>Any suggestions, please and thank you very much :)</p> <p>OK, it does return the proper tag, but now it seems as though the script doesnt run to generate the tag. I have tried two ways:</p> <pre><code>&lt;div class="slides"&gt; &lt;div class="slide"&gt; &lt;div class="image-holder"&gt; &lt;?php include ("image.php?ID=2"); ?&gt; &lt;/div&gt; </code></pre> <p>and:</p> <pre><code> &lt;img src="image.php?ID=2" alt="" /&gt; </code></pre> <p>but neither one will insert the filename... I need to identify each img src by the primary key, so I was passing it the ID from each image src location but alas, my PHP ninja skills need to be honed.</p> <p>Just to clarify: I am uploading images to the server, recording the filenames in a DB and calling that filename in an HTML doc...there are several in each one so I need to pass the ID (i.e. 1,2,3 ) to correspond to the primary key in the table. But I cant get the script to process the tag first. If I go to view source, I can click the script and get the proper result...</p> <p>Thanks again, you guys and girls are very helpful</p>
9,654,637
4
0
null
2012-03-11 11:39:39.91 UTC
0
2018-12-22 06:02:15.49 UTC
2013-08-08 18:54:48.58 UTC
null
404,623
null
1,256,703
null
1
0
php|html
39,213
<p>You can do it as you did but you had the single quotes in twice, (unless you were meaning to use concatenation - which is unnecessary - if you want this see the other answer).</p> <pre><code>echo "&lt;img src=\"$image\"/&gt;"; </code></pre> <p>Or the longer form with braces if you need to embed inside text.</p> <pre><code>echo "&lt;img src=\"${image}\"/&gt;"; </code></pre> <p>I'd recommend using <a href="http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc" rel="nofollow noreferrer">heredoc</a> syntax for this if you're doing lots of HTML. This avoids the need to have lots of echo lines.</p> <pre><code>echo &lt;&lt;&lt; EOF &lt;div class="example"&gt; &lt;img src="$image" /&gt; &lt;/div&gt; EOF; </code></pre>
48,473,984
What is difference between 'npm install' and 'npm rebuild'?
<p>I upgrade my node version from v7.1.0 to v9.4.0. After this m trying to run my server then I get this.</p> <pre><code>was compiled against a different Node.js version using NODE_MODULE_VERSION 51. This version of Node.js requires NODE_MODULE_VERSION 59. Please try re-compiling or re-installing the module (for instance, using `npm rebuild` or `npm install`). </code></pre> <p>then I know about <code>npm rebuild</code>. I run both command <code>npm rebuild</code> and <code>npm install</code>. It fixed after run <code>npm rebuild</code> but I do not understand what it does. Please explain about <code>npm rebuild</code></p> <p>thank you</p>
48,474,248
1
0
null
2018-01-27 08:24:12.98 UTC
4
2019-02-09 23:16:43.277 UTC
2019-02-09 23:16:43.277 UTC
null
4,155,792
null
3,034,938
null
1
43
node.js|npm
55,156
<p><strong>npm install</strong>: It is obvious that <code>npm install</code> is used to install packages using the <code>package.json</code> file, this command also installs the other packages on which the packages (in <code>package.json</code>) are dependent. On the backside, this command uses the <code>npm build</code> which helps to build the packages you are installing.</p> <p><strong>npm rebuild</strong>: As the name rebuild, this command again builds the packages, used only when you upgrade the node version and must recompile all your C++ addons with the new binary.</p>
36,033,879
Three.js - Object follows mouse position
<p>I am creating a sphere in <code>Three.js</code> which has to follow the mouse whenever it moves, as displayed in <a href="https://stemkoski.github.io/Three.js/Mouse-Sprite.html" rel="noreferrer">this example</a>. The function that handles the mouse movement is the following:</p> <pre><code>function onMouseMove(event) { // Update the mouse variable event.preventDefault(); mouse.x = (event.clientX / window.innerWidth) * 2 - 1; mouse.y = - (event.clientY / window.innerHeight) * 2 + 1; // Make the sphere follow the mouse mouseMesh.position.set(event.clientX, event.clientY, 0); }; </code></pre> <p>I attach a <strong><a href="https://jsfiddle.net/atwfxdpd/" rel="noreferrer">JSFiddle</a></strong> with the complete code inside it, where you can see that according to the DOM, <code>mouseMesh</code> is undefined. Do you have an idea of what am I doing wrong?</p> <p>Thanks in advance for your replies!</p>
36,071,100
2
0
null
2016-03-16 11:07:40.35 UTC
11
2018-03-15 09:45:13.997 UTC
2018-03-15 09:45:13.997 UTC
null
3,207,159
null
3,207,159
null
1
10
javascript|three.js
22,080
<p>For sphere to follow mouse, you need to convert screen coordinates to threejs world position. <a href="https://stackoverflow.com/questions/13055214/mouse-canvas-x-y-to-three-js-world-x-y-z">Reference link</a>.</p> <p><a href="https://jsfiddle.net/atwfxdpd/10/" rel="noreferrer">Updated fiddle</a></p> <pre><code>var vector = new THREE.Vector3(mouse.x, mouse.y, 0.5); vector.unproject( camera ); var dir = vector.sub( camera.position ).normalize(); var distance = - camera.position.z / dir.z; var pos = camera.position.clone().add( dir.multiplyScalar( distance ) ); </code></pre>
46,098,806
Laravel delete button with HTML form
<p>I'm using the HTML form, not Laravel Collective.</p> <p>For now I've successfully created a CRUD for a users in my CMS, but one thing bothers me:</p> <p>How can I set a Delete button in my list of users, instead of the specific edit page?</p> <p>Also, it will be nice when a user clicks on the Delete button to show up confirmation popup for deleting the specific user. </p> <p>So, here's my code:</p> <p>The controller:</p> <pre><code>/** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $user = User::findOrFail($id); $user-&gt;delete(); return redirect('/admin/users'); } </code></pre> <p>The list of users page:</p> <pre><code>@extends('layouts.backend') @section('content') &lt;h1&gt;Users&lt;/h1&gt; &lt;a class="btn btn-primary" href="/admin/users/create"&gt;Create new user&lt;/a&gt; &lt;table class="table"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;Id&lt;/th&gt; &lt;th&gt;Name&lt;/th&gt; &lt;th&gt;Email&lt;/th&gt; &lt;th&gt;Role&lt;/th&gt; &lt;th&gt;Status&lt;/th&gt; &lt;th&gt;Created&lt;/th&gt; &lt;th&gt;Updated&lt;/th&gt; &lt;th&gt;Operations&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; @if($users) @foreach($users as $user) &lt;tr&gt; &lt;td&gt;{{$user-&gt;id}}&lt;/td&gt; &lt;td&gt;{{$user-&gt;name}}&lt;/td&gt; &lt;td&gt;{{$user-&gt;email}}&lt;/td&gt; &lt;td&gt;{{$user-&gt;role ? $user-&gt;role-&gt;name : 'User has no role'}}&lt;/td&gt; &lt;td&gt;{{$user-&gt;status == 1 ? 'Active' : 'Not active'}}&lt;/td&gt; &lt;td&gt;{{$user-&gt;created_at-&gt;diffForHumans()}}&lt;/td&gt; &lt;td&gt;{{$user-&gt;updated_at-&gt;diffForHumans()}}&lt;/td&gt; &lt;td&gt; &lt;a href="/admin/users/{{$user-&gt;id}}/edit" class="btn btn-primary"&gt;Edit&lt;/a&gt; &lt;a class="btn btn-danger" href=""&gt;Delete&lt;/a&gt; // HOW TO ACHIEVE THIS? &lt;/td&gt; &lt;/tr&gt; @endforeach @endif &lt;/tbody&gt; &lt;/table&gt; @endsection </code></pre> <p>The specific edit user page:</p> <pre><code>@extends('layouts.backend') @section('content') &lt;h1&gt;Edit user&lt;/h1&gt; &lt;form method="POST" action="/admin/users/{{$user-&gt;id}}"&gt; {{ csrf_field() }} {{ method_field('PATCH') }} &lt;div class="form-group"&gt; &lt;label&gt;Name:&lt;/label&gt; &lt;input type="text" name="name" class="form-control" value="{{$user-&gt;name}}"&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label&gt;Email:&lt;/label&gt; &lt;input type="text" name="email" class="form-control" value="{{$user-&gt;email}}"&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label&gt;Role:&lt;/label&gt; &lt;select name="role_id" class="form-control"&gt; @if($user-&gt;role_id == 1) &lt;option value="1" selected&gt;Administrator&lt;/option&gt; &lt;option value="2"&gt;Editor&lt;/option&gt; @else &lt;option value="1"&gt;Administrator&lt;/option&gt; &lt;option value="2" selected&gt;Editor&lt;/option&gt; @endif &lt;/select&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label&gt;Status:&lt;/label&gt; &lt;select name="status" class="form-control"&gt; @if($user-&gt;status == 1) &lt;option value="1" selected&gt;Active&lt;/option&gt; &lt;option value="0"&gt;Not active&lt;/option&gt; @else &lt;option value="1"&gt;Active&lt;/option&gt; &lt;option value="0" selected&gt;Not active&lt;/option&gt; @endif &lt;/select&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label&gt;Password&lt;/label&gt; &lt;input type="password" name="password" class="form-control" value="{{$user-&gt;password}}"&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;input type="submit" name="submit" value="Update user" class="btn btn-primary"&gt; &lt;/div&gt; &lt;/form&gt; &lt;form id="delete-form" method="POST" action="/admin/users/{{$user-&gt;id}}"&gt; {{ csrf_field() }} {{ method_field('DELETE') }} &lt;div class="form-group"&gt; &lt;input type="submit" class="btn btn-danger" value="Delete user"&gt; &lt;/div&gt; &lt;/form&gt; @include('inc.errors') @endsection </code></pre> <p>The route:</p> <pre><code>Route::group(['middleware'=&gt;'admin'], function(){ Route::resource('admin/users', 'AdminUsersController'); Route::get('/admin', function(){ return view('admin.index'); }); // Route::resource('admin/posts', 'AdminPostsController'); }); </code></pre>
46,099,194
4
0
null
2017-09-07 14:22:48.767 UTC
2
2020-05-01 13:23:28.963 UTC
2017-09-07 14:39:09.54 UTC
null
2,519,032
null
2,519,032
null
1
7
php|html|forms|laravel|laravel-5
51,331
<p>It's not obvious from the code you posted, but your <code>DELETE</code> route expects <code>DELETE</code> method. As it should!</p> <p>But on your list you're trying to access it with <code>GET</code> method.</p> <p>Really you should just reuse the code from the edit page, which fakes <code>DELETE</code> method already.</p> <p>Something like this:</p> <pre><code>... &lt;td&gt; &lt;a href="/admin/users/{{$user-&gt;id}}/edit" class="btn btn-primary"&gt;Edit&lt;/a&gt; &lt;form method="POST" action="/admin/users/{{$user-&gt;id}}"&gt; {{ csrf_field() }} {{ method_field('DELETE') }} &lt;div class="form-group"&gt; &lt;input type="submit" class="btn btn-danger delete-user" value="Delete user"&gt; &lt;/div&gt; &lt;/form&gt; &lt;/td&gt; ... ... // Mayank Pandeyz's solution for confirmation customized for this implementation &lt;script&gt; $('.delete-user').click(function(e){ e.preventDefault() // Don't post the form, unless confirmed if (confirm('Are you sure?')) { // Post the form $(e.target).closest('form').submit() // Post the surrounding form } }); &lt;/script&gt; </code></pre>
29,202,277
Update single field using spring data jpa
<p>I'm using spring-data's repositories - very convenient thing but I faced an issue. I easily can update whole entity but I believe it's pointless when I need to update only a single field:</p> <pre><code>@Entity @Table(schema = "processors", name = "ear_attachment") public class EARAttachment { private Long id; private String originalName; private String uniqueName;//yyyy-mm-dd-GUID-originalName private long size; private EARAttachmentStatus status; </code></pre> <p>to update I just call method save. In log I see the followwing:</p> <pre><code>batching 1 statements: 1: update processors.ear_attachment set message_id=100, original_name='40022530424.dat', size=506, status=2, unique_name='2014-12-16-8cf74a74-e7f3-40d8-a1fb-393c2a806847-40022530424.dat' where id=1 </code></pre> <p>I would like to see some thing like this:</p> <pre><code>batching 1 statements: 1: update processors.ear_attachment set status=2 where id=1 </code></pre> <p>Spring's repositories have a lot of facilities to select something using name conventions, maybe there is something similar for update like updateForStatus(int status);</p>
29,202,504
3
0
null
2015-03-23 02:08:40.237 UTC
12
2020-04-27 21:19:07.83 UTC
2018-10-17 02:13:26.703 UTC
null
3,641,067
null
1,004,374
null
1
64
java|spring|spring-data|updates|spring-data-jpa
101,214
<p>You can try something like this on your repository interface:</p> <pre><code>@Modifying @Query("update EARAttachment ear set ear.status = ?1 where ear.id = ?2") int setStatusForEARAttachment(Integer status, Long id); </code></pre> <p>You can also use named params, like this:</p> <pre><code>@Modifying @Query("update EARAttachment ear set ear.status = :status where ear.id = :id") int setStatusForEARAttachment(@Param("status") Integer status, @Param("id") Long id); </code></pre> <p>The int return value is the number of rows that where updated. You may also use <code>void</code> return.</p> <p>See more in <a href="http://docs.spring.io/spring-data/data-jpa/docs/current/reference/html/#jpa.modifying-queries" rel="noreferrer">reference</a> documentation.</p>
67,938,486
After installing npm on WSL Ubuntu 20.04 I get the message "/usr/bin/env: ‘bash\r’: No such file or directory"
<p>I see the following message when running the <code>npm install</code> or <code>npm</code> command from the terminal. Executing <code>node</code> works as expected.</p> <pre><code> &gt; npm install /usr/bin/env: ‘bash\r’: No such file or directory </code></pre>
67,938,487
12
0
null
2021-06-11 14:07:23.493 UTC
13
2022-08-11 15:08:06.47 UTC
null
null
null
null
314,472
null
1
47
node.js|windows|ubuntu|npm|windows-subsystem-for-linux
29,990
<p>This may be a line endings issue, but not from Ubuntu. Make sure you have <code>node</code> and <code>npm</code> installed correctly:</p> <ol> <li>From WSL run <code>sudo apt install nodejs npm</code> to install node &amp; npm</li> <li>From PowerShell/CMD run <code>wsl --shutdown</code> to restart the WSL service</li> <li>Next in WSL run <code>which npm</code> to confirm it's installed [<em>output: /usr/bin/npm</em>]</li> </ol> <p>Does the problem persist? Try this next:</p> <p>Stop Windows path variables being shared with WSL by editing the <code>/etc/wsl.conf</code> file in WSL. If the file doesn't exist, execute <code>sudo touch /etc/wsl.conf</code> first. Edit the file with the command <code>sudo nano /etc/wsl.conf</code> and add the following configuration:</p> <pre class="lang-ini prettyprint-override"><code>[interop] appendWindowsPath = false </code></pre> <p>Then restart WSL2 with command <code>wsl --shutdown</code> in Windows.</p> <p><em><strong>Note 1:</strong></em> <em>This will stop the PATH environment variables from Windows passing through to WSL. Known bug: this stops the VSCode <code>code .</code> command from working in WSL. If this is a problem, use NVM solution described here or switch to using node in a docker container.</em></p> <p><em><strong>Note 2:</strong></em> <em>this also affects <code>pyenv</code> command, see <a href="https://github.com/pyenv/pyenv/issues/1725#issuecomment-824054644" rel="noreferrer">/usr/bin/env: ‘bash\r’: No such file or directory: Incompatible line-endings (WSL?)</a></em></p> <p><em><strong>Tip from @mike:</strong></em> &quot;I did not want to disable the ability to do <code>code .</code> so I just removed the windows nodejs path by adding this line to my ~/.bashrc PATH=$(echo &quot;$PATH&quot; | sed -e 's%:/mnt/c/Program Files/nodejs%%')&quot;</p>
28,036,716
Removing elements in an array using Lodash
<p>I have this array:</p> <pre><code>var fruits = ['Apple', 'Banana', 'Orange', 'Celery']; </code></pre> <p>And I use Lodash's <code>remove</code> like so:</p> <pre><code>_.remove(fruits, function (fruit) { return fruit === 'Apple' || 'Banana' || 'Orange'; }) </code></pre> <p>The result is <code>['Apple', 'Banana', 'Orange', 'Celery']</code>, while I expected it to be <code>['Apple', 'Banana', 'Orange']</code>. Why is this so?</p>
28,036,796
5
0
null
2015-01-20 02:15:08.477 UTC
1
2016-11-18 09:08:50.797 UTC
null
null
null
null
2,517,015
null
1
28
javascript|lodash
85,286
<p>Because when <code>fruit</code> is <code>"Celery"</code>, you are testing:</p> <pre><code>"Celery" === 'Apple' || 'Banana' || 'Orange' </code></pre> <p>which evaluates to</p> <pre><code>false || true || true </code></pre> <p>which is <code>true</code>.</p> <p>You can't use that syntax. Either do it the long way around:</p> <pre><code>_.remove(fruits, function (fruit) { return fruit === 'Apple' || fruit === 'Banana' || fruit === 'Orange' }); </code></pre> <p>or test for array membership:</p> <pre><code>_.remove(fruits, function (fruit) { return _.indexOf(['Apple', 'Banana', 'Orange'], fruit) !== -1 }); </code></pre> <p>This is not limited to JavaScript, and is in fact a common mistake (e.g. <a href="https://stackoverflow.com/questions/20002503/why-does-a-b-or-c-or-d-always-evaluate-to-true">this question</a>)</p>
50,741,951
libcurl.so.4: cannot open shared object file: No such file or directory
<p>I am creating binary of <a href="https://github.com/s3fs-fuse/s3fs-fuse" rel="noreferrer">s3fs-fuse</a> on Ubuntu 14.04 by following the <a href="https://github.com/s3fs-fuse/s3fs-fuse" rel="noreferrer">compilation</a> link. In some systems I get the below error while doing the mount operation on kubernetes pods</p> <pre><code> ---- ------ ---- ---- ------- Normal Scheduled 5h default-scheduler Successfully assigned verifypod5 to 10.171.42.29 Normal SuccessfulMountVolume 5h kubelet, 10.171.42.29 MountVolume.SetUp succeeded for volume "default-token-scrsz" Warning FailedMount 5h (x8 over 5h) kubelet, 10.171.42.29 MountVolume.SetUp failed for volume "pvc-f2d4cacc-6a51-11e8-b133-fa53da29538e" : mount command failed, status: Failure, reason: Error mounting volume: s3fs mount failed: s3fs: error while loading shared libraries: libcurl.so.4: cannot open shared object file: No such file or directory </code></pre> <p>I see that the binary is using <code>libcurl-gnutls.so.4</code> but I feel we need the openssl one.</p> <pre><code>ldd /usr/local/bin/s3fs linux-vdso.so.1 =&gt; (0x00007ffc3d1cb000) libfuse.so.2 =&gt; /lib/x86_64-linux-gnu/libfuse.so.2 (0x00007fb0fd742000) libcurl-gnutls.so.4 =&gt; /usr/lib/x86_64-linux-gnu/libcurl-gnutls.so.4 (0x00007fb0fd4d5000) libxml2.so.2 =&gt; /usr/lib/x86_64-linux-gnu/libxml2.so.2 (0x00007fb0fd11a000) libcrypto.so.1.0.0 =&gt; /lib/x86_64-linux-gnu/libcrypto.so.1.0.0 (0x00007fb0fccd6000) </code></pre> <p>So from the system where I did the building of binary, I see below</p> <pre><code> dpkg -l | grep curl ii curl 7.47.0-1ubuntu2.8 amd64 command line tool for transferring data with URL syntax ii libcurl3:amd64 7.47.0-1ubuntu2.8 amd64 easy-to-use client-side URL transfer library (OpenSSL flavour) ii libcurl3-gnutls:amd64 7.47.0-1ubuntu2.8 amd64 easy-to-use client-side URL transfer library (GnuTLS flavour) ii libcurl4-openssl-dev:amd64 7.47.0-1ubuntu2.8 amd64 development files and documentation for libcurl (OpenSSL flavour) </code></pre> <p>So the binary picks up <code>libcurl3-gnutls:amd64</code> instead of <code>libcurl4-openssl-dev:amd64</code> . How can I change this behaviour. </p>
50,742,032
2
0
null
2018-06-07 13:02:25.687 UTC
null
2022-09-03 21:32:58.747 UTC
2018-06-07 13:37:52.317 UTC
null
1,117,320
null
1,117,320
null
1
11
libcurl|s3fs
40,050
<p>Please install <code>libcurl3</code> package.</p> <p>For the future, if you're missing some file, you can use <a href="https://packages.ubuntu.com" rel="noreferrer">https://packages.ubuntu.com</a> to find what package provides a file you need.</p> <p>For example: <a href="https://packages.ubuntu.com/search?searchon=contents&amp;keywords=libcurl.so.4&amp;mode=filename&amp;suite=xenial&amp;arch=any" rel="noreferrer">https://packages.ubuntu.com/search?searchon=contents&amp;keywords=libcurl.so.4&amp;mode=filename&amp;suite=xenial&amp;arch=any</a></p>
38,949,951
How to solve merge conflicts across forks?
<p>I have forked my repo say repoB from another repo say repoA. Now I don't have permissions to write into repoA. </p> <p>When I try to create a pull request on repoA to get the latest changes and merge those in to repoB I get a merge conflict error. How do I solve that?</p> <p>I tried this:</p> <pre><code>git checkout -b repoA master git pull https:repoA master git checkout master git merge --no-ff repoA git push origin master </code></pre> <p>N.B. I cannot checkout forkA as I don't have write permissions on that. </p>
38,955,036
1
2
null
2016-08-15 05:53:09.31 UTC
11
2017-05-16 12:39:54.24 UTC
2016-08-15 06:59:11.94 UTC
null
1,475,228
null
1,475,228
null
1
19
git|github|git-fork
16,522
<p>First add the upstream remote</p> <pre><code>git remote add upstream https://repoA git fetch upstream </code></pre> <p>Merge in upstream changes</p> <pre><code>git checkout master git merge upstream/master </code></pre> <p>Resolve conflicts and push</p> <pre><code>git push origin master </code></pre> <p>Your pull request should automatically update</p>
6,156,259
Sed expression doesn't allow optional grouped string
<p>I'm trying to use the following regex in a <code>sed</code> script but it doesn't work:</p> <pre><code>sed -n '/\(www\.\)\?teste/p' </code></pre> <p>The regex above doesn't seem to work. <code>sed</code> doesn't seem to apply the <code>?</code> to the grouped <code>www\.</code>.</p> <p>It works if you use the <code>-E</code> parameter that switches <code>sed</code> to use the Extended Regex, so the syntax becomes:</p> <pre><code>sed -En '/(www\.)?teste/p' </code></pre> <p>This works fine but I want to run this script on a machine that doesn't support the <code>-E</code> operator. I'm pretty sure that this is possible and I'm doing something very stupid. </p>
6,157,705
1
4
null
2011-05-27 18:26:16.713 UTC
3
2014-03-06 13:38:50.063 UTC
2014-03-06 13:38:50.063 UTC
null
15,168
null
272,031
null
1
67
regex|sed
35,656
<p>Standard <code>sed</code> only understands POSIX <a href="http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap09.html" rel="noreferrer">Basic Regular Expressions</a> (BRE), not Extended Regular Expressions (ERE), and the <code>?</code> is a metacharacter in EREs, but not in BREs.</p> <p>Your version of <code>sed</code> might support EREs if you turn them on. With GNU <code>sed</code>, the relevant options are <code>-r</code> and <code>--regexp-extended</code>, described as "use extended regular expressions in the script".</p> <p>However, if your <code>sed</code> does not support it - quite plausible - then you are stuck. Either import a version of <code>sed</code> that does support them, or redesign your processing. Maybe you should use <code>awk</code> instead.</p> <hr> <h3>2014-02-21</h3> <p>I don't know why I didn't mention that even though <code>sed</code> does not support the shorthand <code>?</code> or <code>\?</code> notation, it does support counted ranges with <code>\{n,m\}</code>, so you can simulate <code>?</code> with <code>\{0,1\}</code>:</p> <pre><code>sed -n '/\(www\.\)\{0,1\}teste/p' &lt;&lt; EOF http://www.tested.com/ http://tested.com/ http://www.teased.com/ EOF </code></pre> <p>which produces:</p> <pre><code>http://www.tested.com/ http://tested.com/ </code></pre> <p>Tested on Mac OS X 10.9.1 Mavericks with the standard BSD <code>sed</code> and with GNU <code>sed</code> 4.2.2.</p>
38,037,760
How to set <iframe src="..."> without causing `unsafe value` exception?
<p>I am working on a tutorial involving the setting of an <code>iframe</code> <code>src</code> attribute: </p> <pre><code>&lt;iframe width="100%" height="300" src="{{video.url}}"&gt;&lt;/iframe&gt; </code></pre> <p>This throws an exception:</p> <pre><code>Error: unsafe value used in a resource URL context at DomSanitizationServiceImpl.sanitize... </code></pre> <p>I have already tried using bindings with <code>[src]</code> with no success.</p>
38,037,914
9
0
null
2016-06-26 10:54:09.057 UTC
48
2022-07-25 08:48:30.65 UTC
2019-10-07 17:29:12.38 UTC
null
3,345,644
null
315,260
null
1
201
angular
270,659
<p><strong>Update v8</strong></p> <p>Below answers work but <a href="https://netbasal.com/angular-2-security-the-domsanitizer-service-2202c83bd90" rel="noreferrer">exposes your application to XSS security risks!</a>. Instead of using <code>this.domSanitizer.bypassSecurityTrustResourceUrl(url)</code>, it is recommended to use <code>this.domSanitizer.sanitize(SecurityContext.URL, url)</code></p> <p><strong>Update</strong></p> <p>For <strong>RC.6^</strong> version use <strong>DomSanitizer</strong></p> <p><strong><a href="https://plnkr.co/edit/Uifk3dxf7vwKJsUFb0d9?p=preview" rel="noreferrer">Plunker</a></strong></p> <p>And a good option is using pure pipe for that:</p> <pre class="lang-typescript prettyprint-override"><code>import { Pipe, PipeTransform } from '@angular/core'; import { DomSanitizer} from '@angular/platform-browser'; @Pipe({ name: 'safe' }) export class SafePipe implements PipeTransform { constructor(private domSanitizer: DomSanitizer) {} transform(url) { return this.domSanitizer.bypassSecurityTrustResourceUrl(url); } } </code></pre> <p>remember to add your new <code>SafePipe</code> to the <code>declarations</code> array of the AppModule. (<a href="https://angular.io/docs/ts/latest/guide/pipes.html" rel="noreferrer">as seen on documentation</a>)</p> <pre class="lang-typescript prettyprint-override"><code>@NgModule({ declarations : [ ... SafePipe ], }) </code></pre> <p>html</p> <pre class="lang-typescript prettyprint-override"><code>&lt;iframe width=&quot;100%&quot; height=&quot;300&quot; [src]=&quot;url | safe&quot;&gt;&lt;/iframe&gt; </code></pre> <p><strong><a href="https://plnkr.co/edit/9JPA5r0gjTwfVckohihp?p=preview" rel="noreferrer">Plunker</a></strong></p> <p>If you use <code>embed</code> tag this might be interesting for you:</p> <ul> <li><a href="https://stackoverflow.com/questions/39393431/how-with-angular2-rc-6-disable-sanitize-on-embed-html-tag-which-display-pdf/39394814#39394814">how with angular2 rc.6 disable sanitize on embed html tag which display pdf</a></li> </ul> <hr /> <p><strong>Old version RC.5</strong></p> <p>You can leverage <code>DomSanitizationService</code> like this:</p> <pre class="lang-typescript prettyprint-override"><code>export class YourComponent { url: SafeResourceUrl; constructor(domSanitizationService: DomSanitizationService) { this.url = domSanitizer.bypassSecurityTrustResourceUrl('your url'); } } </code></pre> <p>And then bind to <code>url</code> in your template:</p> <pre class="lang-typescript prettyprint-override"><code>&lt;iframe width=&quot;100%&quot; height=&quot;300&quot; [src]=&quot;url&quot;&gt;&lt;/iframe&gt; </code></pre> <p>Don't forget to add the following imports:</p> <pre class="lang-typescript prettyprint-override"><code>import { SafeResourceUrl, DomSanitizationService } from '@angular/platform-browser'; </code></pre> <p><strong><a href="http://plnkr.co/edit/ZJBXJVL4LhD41R8VE0jj?p=preview" rel="noreferrer">Plunker sample</a></strong></p>
2,901,541
Which coding system should I use in Emacs?
<p>I have just tried to save a simple *.rtf file with some websites and tips on how to use emacs and I got </p> <blockquote> <p>These default coding systems were tried to encode text in the buffer `notes.rtf': (iso-latin-1-dos (315 . 8216) (338 . 8217) (1514 . 8220) (1525 . 8221)) However, each of them encountered characters it couldn't encode: iso-latin-1-dos cannot encode these: ‘ ’ “ ”<br> ....<br> etc, etc, etc</p> </blockquote> <p>Now what is that? Now it is asking me to chose an encoding system</p> <blockquote> <p>Select coding system (default chinese-iso-8bit):</p> </blockquote> <p>I don't even know what an encoding system is, and I would rather not have to choose one every time I try and save a document... Is there any way I can set an encoding system that will work with all my files so I don't have to worry about this?</p> <p>I saw another question and asnswer elsewhere in this website (<a href="https://stackoverflow.com/questions/1785200/change-emacs-default-coding-system">see it here</a>) and it seems that if I type the following</p> <blockquote> <p>(defun set-coding-system () (setq buffer-file-coding-system 'utf-8-unix)) (add-hook 'find-file-hook 'set-coding-system)</p> </blockquote> <p>then I can have Emacs do this, but I am not sure... Can someone confirm this to me?</p>
2,903,256
3
4
null
2010-05-25 02:05:47.21 UTC
16
2018-08-04 05:50:21.637 UTC
2017-05-23 12:16:51.383 UTC
null
-1
null
347,646
null
1
27
emacs|character-encoding
9,460
<p>Here's a pretty comprehensive group of magic invocations to make Emacs use UTF-8 everywhere by default:</p> <pre><code> (setq utf-translate-cjk-mode nil) ; disable CJK coding/encoding (Chinese/Japanese/Korean characters) (set-language-environment 'utf-8) (set-keyboard-coding-system 'utf-8-mac) ; For old Carbon emacs on OS X only (setq locale-coding-system 'utf-8) (set-default-coding-systems 'utf-8) (set-terminal-coding-system 'utf-8) (set-selection-coding-system (if (eq system-type 'windows-nt) 'utf-16-le ;; https://rufflewind.com/2014-07-20/pasting-unicode-in-emacs-on-windows 'utf-8)) (prefer-coding-system 'utf-8) </code></pre>
2,539,109
Logging users out of a Django site after N minutes of inactivity
<p>I'm working on a website that requires us to log a user out after N minutes of inactivity. Are there any best practices for this using Django? </p>
2,539,307
4
0
null
2010-03-29 15:24:57.673 UTC
8
2022-08-07 14:57:12.773 UTC
2022-08-07 12:59:30.323 UTC
null
8,172,439
null
61,295
null
1
29
python|python-3.x|django|authentication|django-sessions
18,699
<p>Take a look at the <a href="http://docs.djangoproject.com/en/dev/topics/http/sessions/#topics-http-sessions" rel="noreferrer">session middleware</a> and its settings. Specifically these two:</p> <blockquote> <p>SESSION_COOKIE_AGE</p> <p>Default: 1209600 (2 weeks, in seconds)</p> <p>The age of session cookies, in seconds.</p> <p>SESSION_SAVE_EVERY_REQUEST</p> <p>Default: False</p> <p>Whether to save the session data on every request. If this is False (default), then the session data will only be saved if it has been modified -- that is, if any of its dictionary values have been assigned or deleted.</p> </blockquote> <p>Setting a low <code>SESSION_COOKIE_AGE</code> and turning <code>SESSION_SAVE_EVERY_REQUEST</code> on should work to create "sliding" expiration.</p>
36,540,105
How to style a “choose file” button using CSS only
<p>I want to try design this :</p> <pre><code>&lt;input type="file" multiple&gt; </code></pre> <p>What I want: I want change its color, also change its size...</p>
36,540,846
4
1
null
2016-04-11 04:54:32.753 UTC
1
2021-04-23 06:05:21.823 UTC
2019-10-30 14:50:40.51 UTC
null
356,629
null
5,881,266
null
1
4
html|css
38,714
<p>File type is a native element henceforth you cant change it's appearance. Instead you can hide at the back of some element.</p> <pre><code>&lt;div&gt; Choose File &lt;input type="file" class="hide_file"&gt; &lt;/div&gt; div{ padding:5px 10px; background:#00ad2d; border:1px solid #00ad2d; position:relative; color:#fff; border-radius:2px; text-align:center; float:left; cursor:pointer } .hide_file { position: absolute; z-index: 1000; opacity: 0; cursor: pointer; right: 0; top: 0; height: 100%; font-size: 24px; width: 100%; } </code></pre> <p>Refer <a href="https://jsfiddle.net/sqm5puzs/" rel="noreferrer">Here</a></p>
49,044,753
Scale kable table to fit page width
<p>How do you format a table in pdf using kable function? Because my output table width exceeds the width of the pdf. Here is an example:</p> <pre><code>--- output: pdf_document --- ```{r} df &lt;- cbind(mtcars[1:5,], mtcars[1:5,]) knitr::kable(df) ``` </code></pre> <p><a href="https://i.stack.imgur.com/PSyjD.png" rel="noreferrer"><img src="https://i.stack.imgur.com/PSyjD.png" alt="enter image description here"></a></p>
49,044,933
2
1
null
2018-03-01 07:36:10.977 UTC
5
2020-09-29 17:18:04.137 UTC
2018-03-01 13:10:10.46 UTC
null
7,347,699
null
9,331,903
null
1
33
r|r-markdown|kable
37,690
<p>One option is to use <code>kable_styling</code> from the <code>kableExtra</code> package. The option <code>latex_options="scale_down"</code> will fit the table within the paper margins. See <a href="https://haozhu233.github.io/kableExtra/awesome_table_in_pdf.pdf" rel="noreferrer">the vignette</a> for detailed examples on all of the formatting options.</p> <pre><code>--- output: pdf_document --- ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = FALSE) library(knitr) library(kableExtra) ``` ```{r} kable(cbind(mtcars[1:5,], mtcars[1:5,])) ``` ```{r} kable(cbind(mtcars[1:5,], mtcars[1:5,]), format="latex", booktabs=TRUE) %&gt;% kable_styling(latex_options="scale_down") ``` </code></pre> <p><a href="https://i.stack.imgur.com/jJpY2.png" rel="noreferrer"><img src="https://i.stack.imgur.com/jJpY2.png" alt="enter image description here"></a></p>
1,173,992
What is a basic example of single inheritance using the super() keyword in Python?
<p>Let's say I have the following classes set up:</p> <pre><code>class Foo: def __init__(self, frob, frotz): self.frobnicate = frob self.frotz = frotz class Bar: def __init__(self, frob, frizzle): self.frobnicate = frob self.frotz = 34 self.frazzle = frizzle </code></pre> <p>How can I (if I can at all) use super() in this context to eliminate the duplicate code?</p>
1,174,124
2
1
null
2009-07-23 19:38:02.757 UTC
9
2015-04-20 12:22:27.54 UTC
2012-07-06 15:35:36.357 UTC
null
869,912
null
90,777
null
1
28
python|inheritance|constructor|super
43,508
<p>In Python >=3.0, like this:</p> <pre><code>class Foo(): def __init__(self, frob, frotz) self.frobnicate = frob self.frotz = frotz class Bar(Foo): def __init__(self, frob, frizzle) super().__init__(frob, 34) self.frazzle = frizzle </code></pre> <p>Read more here: <a href="http://docs.python.org/3.1/library/functions.html#super" rel="noreferrer">http://docs.python.org/3.1/library/functions.html#super</a></p> <p>EDIT: As said in another answer, sometimes just using <code>Foo.__init__(self, frob, 34)</code> can be the better solution. (For instance, when working with certain forms of multiple inheritance.)</p>
1,065,672
How to link against boost.system with cmake
<p>I use a cmake generated makefile to compile a c++ file that depends on the boost filesystem library. </p> <p>During the linking process I get the following error: </p> <pre> Undefined symbols: "boost::system::get_generic_category()", referenced from: __static_initialization_and_destruction_0(int, int)in FaceRecognizer.cpp.o __static_initialization_and_destruction_0(int, int)in FaceRecognizer.cpp.o __static_initialization_and_destruction_0(int, int)in FaceRecognizer.cpp.o "boost::system::get_system_category()", referenced from: __static_initialization_and_destruction_0(int, int)in FaceRecognizer.cpp.o __static_initialization_and_destruction_0(int, int)in FaceRecognizer.cpp.o ld: symbol(s) not found collect2: ld returned 1 exit status make[2]: *** [src/ImageMarker] Error 1 </pre> <p>The action from the makefile that generates this error is this line: </p> <pre> cd /Users/janusz/Documents/workspace/ImageMarker/Debug/src && /opt/local/bin/cmake -E cmake_link_script CMakeFiles/ImageMarker.dir/link.txt --verbose=1 /usr/bin/c++ -O3 -Wall -Wno-deprecated -g -verbose -Wl,-search_paths_first -headerpad_max_install_names -fPIC CMakeFiles/ImageMarker.dir/ImageMarker.cpp.o CMakeFiles/ImageMarker.dir/Image.cpp.o CMakeFiles/ImageMarker.dir/utils.cpp.o CMakeFiles/ImageMarker.dir/XMLWriter.cpp.o CMakeFiles/ImageMarker.dir/FaceRecognizer.cpp.o -o ImageMarker -L/opt/local/lib ../libTinyXml.a /opt/local/lib/libboost_filesystem-mt.dylib </pre> <p>Some googling showed me that this error seems to be common on macs with the boost file system library because I have to link against a boost.system library or make my project depending on the boost.system library.</p> <p>How do i force cmake to link against the library without hardcoding the library path?</p> <p>Here the result from otool:</p> <pre><code>otool -L /opt/local/lib/libboost_filesystem-mt.dylib /opt/local/lib/libboost_filesystem-mt.dylib: /opt/local/lib/libboost_filesystem-mt.dylib (compatibility version 0.0.0, current version 0.0.0) /opt/local/lib/libboost_system-mt.dylib (compatibility version 0.0.0, current version 0.0.0) /usr/lib/libstdc++.6.dylib (compatibility version 7.0.0, current version 7.4.0) /usr/lib/libgcc_s.1.dylib (compatibility version 1.0.0, current version 1.0.0) /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 111.0.0) </code></pre>
1,065,729
2
1
null
2009-06-30 19:54:29.717 UTC
15
2022-02-10 16:04:17.097 UTC
2009-07-01 17:01:23.55 UTC
null
114,066
null
114,066
null
1
45
c++|macos|boost|linker|cmake
50,104
<p>On linux CMake figures itself that boost_filesystem is linked against boost_system. Obviously you have to tell it explicitly on Mac: </p> <pre><code>find_package(Boost COMPONENTS system filesystem REQUIRED) #... target_link_libraries(mytarget ${Boost_FILESYSTEM_LIBRARY} ${Boost_SYSTEM_LIBRARY} ) </code></pre>
2,601,175
How to ask BeanUtils to ignore null values
<p>Using Commons beanUtils I would like to know how to ask any converter say the Dateconverter to ignore null values and use null as default. As an example consider a public class,</p> <pre><code>public class X { private Date date1; private String string1; //add public getters and setters } </code></pre> <p>and my convertertest as,</p> <pre><code>public class Apache { @Test public void testSimple() throws Exception { X x1 = new X(), x2 = new X(); x1.setString1("X"); x1.setDate1(null); org.apache.commons.beanutils.BeanUtils.copyProperties(x2, x1); //throws ConversionException System.out.println(x2.getString1()); System.out.println(x2.getDate1()); } } </code></pre> <p>The above throws a NPE since the date happens to be null. This looks a very primitive scenario to me which should be handled by default (as in, I would expect x2 to have null value for date1). The doco tells me that I can ask the <a href="http://commons.apache.org/beanutils/v1.8.3/apidocs/org/apache/commons/beanutils/converters/DateConverter.html" rel="noreferrer">converter</a> to do this. Can someone point me as to the best way for doing this ? </p> <p>I dont want to get hold of the Converter and isUseDefault() to be true because then I have to do it for all Date, Enum and many other converters !</p>
2,601,521
5
1
null
2010-04-08 15:27:26.897 UTC
11
2015-05-12 14:44:22.233 UTC
2012-05-18 13:18:01.08 UTC
null
21,234
null
44,124
null
1
13
java|apache-commons-beanutils
39,442
<p>Apparently it looks like, there is a way to tell the ConvertUtils to not throw exceptions on null values which is achieved by calling</p> <pre><code>BeanUtilsBean.getInstance().getConvertUtils().register(false, false, 0); </code></pre>
2,608,652
Creating link to file location on network in confluence
<p>On confluence I want to create a link that links to:</p> <p>P:\myFolder\folder, where P is mapped to a network share.</p> <p>Just putting in "P:\myFolder\folder" doesn't work. Any ideas?</p> <p>(Assuming I cannot put in the full network path).</p>
2,634,343
5
0
null
2010-04-09 15:26:10.897 UTC
1
2015-10-03 13:56:53.253 UTC
2010-05-20 07:54:28.123 UTC
null
147,141
null
104,459
null
1
13
windows|confluence
46,702
<p>typically what would work is </p> <pre><code>file:///p:/myFolder/folder/ </code></pre> <p>If there are spaces in the name like 'My Documents' you can surround the link with [ ]</p> <pre><code>[file:///p:/my Folder/folder/] </code></pre> <p>Of course you can also add an alias:</p> <pre><code>[The Folder|file:///p:/my Folder/folder/] </code></pre> <p>I just tested a variation of this and it seemed to work.</p> <pre><code>[file:///\\\\servername/share/folder/file.ext] works in IE (note two back slashes in front for the server name) </code></pre>
2,811,006
What is a good buffer size for socket programming?
<p>We are using .Net and sockets. The server is using the <code>Socket.Sender(bytes[])</code> method so it just sends the entire payload. On the other side we are clients consuming the data. <code>Socket.Receive(buffer[])</code>. In all the examples from Microsoft (and others) they seem to stick with a buffer size of 8192. We have used this size but every now and then we are sending data down to the clients that exceeds this buffer size.</p> <p>Is there a way of determining how much data the server's sent method sent us? What is the best buffer size?</p>
2,811,047
5
0
null
2010-05-11 13:22:11.837 UTC
23
2020-11-05 19:28:24.95 UTC
2019-11-08 10:17:04.993 UTC
null
206,720
null
62,544
null
1
43
.net|sockets
86,268
<p>Even if you're sending more data than that, it may well not be available in one call to Receive.</p> <p>You can't determine how much data the server has sent - it's a <em>stream</em> of data, and you're just reading chunks at a time. You may read <em>part</em> of what the server sent in one Send call, or you may read the data from two Send calls in one Receive call. 8K is a reasonable buffer size - not so big that you'll waste a lot of memory, and not so small that you'll have to use loads of wasted Receive calls. 4K or 16K would quite possibly be fine too... I personally wouldn't start going above 16K for network buffers - I suspect you'd rarely fill them.</p> <p>You could experiment by trying to use a very large buffer and log how many bytes were received in each call - that would give you some idea of how much is generally <em>available</em> - but it wouldn't really show the effect of using a smaller buffer. What concerns do you have over using an 8K buffer? If it's performance, do you have any evidence that this aspect of your code is a performance bottleneck?</p>
2,902,335
Instantiating multiple beans of the same class with Spring annotations
<p>With an XML configured Spring bean factory, I can easily instantiate multiple instances of the same class with different parameters. How can I do the same with annotations? I would like something like this:</p> <pre><code>@Component(firstName="joe", lastName="smith") @Component(firstName="mary", lastName="Williams") public class Person { /* blah blah */ } </code></pre>
2,903,373
6
5
null
2010-05-25 05:55:51.027 UTC
17
2019-07-15 18:15:32.03 UTC
2016-01-13 14:45:56.54 UTC
null
540,837
null
193,283
null
1
48
spring|annotations
82,650
<p>Yes, you can do it with a help of your custom BeanFactoryPostProcessor implementation. </p> <p>Here is a simple example.</p> <p>Suppose we have two components. One is dependency for another. </p> <p>First component:</p> <pre><code>import org.springframework.beans.factory.InitializingBean; import org.springframework.util.Assert; public class MyFirstComponent implements InitializingBean{ private MySecondComponent asd; private MySecondComponent qwe; public void afterPropertiesSet() throws Exception { Assert.notNull(asd); Assert.notNull(qwe); } public void setAsd(MySecondComponent asd) { this.asd = asd; } public void setQwe(MySecondComponent qwe) { this.qwe = qwe; } } </code></pre> <p>As you could see, there is nothing special about this component. It has dependency on two different instances of MySecondComponent.</p> <p>Second component:</p> <pre><code>import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.annotation.Qualifier; @Qualifier(value = "qwe, asd") public class MySecondComponent implements FactoryBean { public Object getObject() throws Exception { return new MySecondComponent(); } public Class getObjectType() { return MySecondComponent.class; } public boolean isSingleton() { return true; } } </code></pre> <p>It's a bit more tricky. Here are two things to explain. First one - @Qualifier - annotation which contains names of MySecondComponent beans. It's a standard one, but you are free to implement your own. You'll see a bit later why. </p> <p>Second thing to mention is FactoryBean implementation. If bean implements this interface, it's intended to create some other instances. In our case it creates instances with MySecondComponent type.</p> <p>The trickiest part is BeanFactoryPostProcessor implementation:</p> <pre><code>import java.util.Map; import org.springframework.beans.BeansException; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.config.BeanFactoryPostProcessor; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor { public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException { Map&lt;String, Object&gt; map = configurableListableBeanFactory.getBeansWithAnnotation(Qualifier.class); for(Map.Entry&lt;String,Object&gt; entry : map.entrySet()){ createInstances(configurableListableBeanFactory, entry.getKey(), entry.getValue()); } } private void createInstances( ConfigurableListableBeanFactory configurableListableBeanFactory, String beanName, Object bean){ Qualifier qualifier = bean.getClass().getAnnotation(Qualifier.class); for(String name : extractNames(qualifier)){ Object newBean = configurableListableBeanFactory.getBean(beanName); configurableListableBeanFactory.registerSingleton(name.trim(), newBean); } } private String[] extractNames(Qualifier qualifier){ return qualifier.value().split(","); } } </code></pre> <p>What does it do? It goes through all beans annotated with @Qualifier, extract names from the annotation and then manually creates beans of this type with specified names. </p> <p>Here is a Spring config:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"&gt; &lt;bean class="MyBeanFactoryPostProcessor"/&gt; &lt;bean class="MySecondComponent"/&gt; &lt;bean name="test" class="MyFirstComponent"&gt; &lt;property name="asd" ref="asd"/&gt; &lt;property name="qwe" ref="qwe"/&gt; &lt;/bean&gt; &lt;/beans&gt; </code></pre> <p>Last thing to notice here is although you <strong>can</strong> do it you <strong>shouldn't</strong> unless it is a must, because this is a not really natural way of configuration. If you have more than one instance of class, it's better to stick with XML configuration. </p>
2,446,740
Post-loading : check if an image is in the browser cache
<p><strong>Short version question :</strong> Is there navigator.mozIsLocallyAvailable equivalent function that works on all browsers, or an alternative?</p> <p><strong>Long version :)</strong></p> <p>Hi, Here is my situation : I want to implement an HtmlHelper extension for asp.net MVC that handle image post-loading easily (using jQuery).</p> <p>So i render the page with empty image sources with the source specified in the "alt" attribute. I insert image sources after the "window.onload" event, and it works great.</p> <p>I did something like this :</p> <pre><code>$(window).bind('load', function() { var plImages = $(".postLoad"); plImages.each(function() { $(this).attr("src", $(this).attr("alt")); }); }); </code></pre> <p><strong>The problem is :</strong> After the first loading, post-loaded images are cached. But if the page takes 10 seconds to load, the cached post-loaded images will be displayed after this 10 seconds.</p> <p>So i think to specify image sources on the "document.ready" event if the image is cached to display them immediatly.</p> <p>I found this function : navigator.mozIsLocallyAvailable to check if an image is in the cache. Here is what I've done with jquery :</p> <pre><code>//specify cached image sources on dom ready $(document).ready(function() { var plImages = $(".postLoad"); plImages.each(function() { var source = $(this).attr("alt") var disponible = navigator.mozIsLocallyAvailable(source, true); if (disponible) $(this).attr("src", source); }); }); //specify uncached image sources after page loading $(window).bind('load', function() { var plImages = $(".postLoad"); plImages.each(function() { if ($(this).attr("src") == "") $(this).attr("src", $(this).attr("alt")); }); }); </code></pre> <p>It works on Mozilla's DOM but it doesn't works on any other one. I tried navigator.isLocallyAvailable : same result.</p> <p>Is there any alternative?</p>
2,462,369
7
0
null
2010-03-15 11:36:21.69 UTC
11
2022-01-24 17:40:30.273 UTC
null
null
null
null
293,888
null
1
30
javascript|jquery|caching|lazy-loading
22,588
<p>after some reseach, I found a solution :</p> <p>The idea is to log the cached images, binding a log function on the images 'load' event. I first thought to store sources in a cookie, but it's not reliable if the cache is cleared without the cookie. Moreover, it adds one more cookie to HTTP requests...</p> <p>Then i met the magic : <strong>window.localStorage</strong> (<a href="http://msdn.microsoft.com/en-us/library/cc197062%28VS.85%29.aspx" rel="noreferrer">details</a>)</p> <blockquote> <p>The localStorage attribute provides persistent storage areas for domains</p> </blockquote> <p>Exactly what i wanted :). This attribute is standardized in HTML5, and it's already works on nearly all recent browsers (FF, Opera, Safari, IE8, Chrome).</p> <p>Here is the code (without handling window.localStorage non-compatible browsers):</p> <pre><code>var storage = window.localStorage; if (!storage.cachedElements) { storage.cachedElements = ""; } function logCache(source) { if (storage.cachedElements.indexOf(source, 0) &lt; 0) { if (storage.cachedElements != "") storage.cachedElements += ";"; storage.cachedElements += source; } } function cached(source) { return (storage.cachedElements.indexOf(source, 0) &gt;= 0); } var plImages; //On DOM Ready $(document).ready(function() { plImages = $(".postLoad"); //log cached images plImages.bind('load', function() { logCache($(this).attr("src")); }); //display cached images plImages.each(function() { var source = $(this).attr("alt") if (cached(source)) $(this).attr("src", source); }); }); //After page loading $(window).bind('load', function() { //display uncached images plImages.each(function() { if ($(this).attr("src") == "") $(this).attr("src", $(this).attr("alt")); }); }); </code></pre>
2,910,520
Is overloading equals worthwhile
<p>Consider the following snippet:</p> <pre><code>import java.util.*; public class EqualsOverload { public static void main(String[] args) { class Thing { final int x; Thing(int x) { this.x = x; } public int hashCode() { return x; } public boolean equals(Thing other) { return this.x == other.x; } } List&lt;Thing&gt; myThings = Arrays.asList(new Thing(42)); System.out.println(myThings.contains(new Thing(42))); // prints "false" } } </code></pre> <p>Note that <code>contains</code> returns <code>false</code>!!! We seems to have lost our things!!</p> <p>The bug, of course, is the fact that we've accidentally <em>overloaded</em>, instead of <em>overridden</em>, <a href="http://java.sun.com/javase/6/docs/api/java/lang/Object.html#equals%28java.lang.Object%29" rel="noreferrer"><code>Object.equals(Object)</code></a>. If we had written <code>class Thing</code> as follows instead, then <code>contains</code> returns <code>true</code> as expected.</p> <pre><code> class Thing { final int x; Thing(int x) { this.x = x; } public int hashCode() { return x; } @Override public boolean equals(Object o) { return (o instanceof Thing) &amp;&amp; (this.x == ((Thing) o).x); } } </code></pre> <p><em>Effective Java 2nd Edition, Item 36: Consistently use the Override annotation</em>, uses essentially the same argument to recommend that <code>@Override</code> should be used consistently. This advice is good, of course, for if we had tried to declare <code>@Override equals(Thing other)</code> in the first snippet, our friendly little compiler would immediately point out our silly little mistake, since it's an overload, not an override.</p> <p>What the book doesn't specifically cover, however, is whether overloading <code>equals</code> is a good idea to begin with. Essentially, there are 3 situations:</p> <ul> <li>Overload only, no override -- <strong>ALMOST CERTAINLY WRONG</strong>! <ul> <li>This is essentially the first snippet above</li> </ul></li> <li>Override only (no overload) -- one way to fix <ul> <li>This is essentially the second snippet above</li> </ul></li> <li>Overload and override combo -- another way to fix</li> </ul> <p>The 3rd situation is illustrated by the following snippet:</p> <pre><code> class Thing { final int x; Thing(int x) { this.x = x; } public int hashCode() { return x; } public boolean equals(Thing other) { return this.x == other.x; } @Override public boolean equals(Object o) { return (o instanceof Thing) &amp;&amp; (this.equals((Thing) o)); } } </code></pre> <p>Here, even though we now have 2 <code>equals</code> method, there is still one equality logic, and it's located in the overload. The <code>@Override</code> simply delegates to the overload.</p> <p>So the questions are:</p> <ul> <li>What are the pros and cons of "override only" vs "overload &amp; override combo"?</li> <li>Is there a justification for overloading <code>equals</code>, or is this almost certainly a bad practice?</li> </ul>
2,910,559
8
8
null
2010-05-26 06:23:35.193 UTC
6
2021-05-25 11:14:56.453 UTC
2021-05-25 11:14:56.453 UTC
null
545,127
null
276,101
null
1
28
java|equals|overloading|overriding
17,489
<p>I'dont see the case for overloading equals, except that is more error-prone and harder to maintain, especially when using inheritance. </p> <p>Here, it can be extremly hard to maintain reflexivity, symmetry and transitivity or to detect their inconsistencies, because you always must be aware of the actual equals method that gets invoked. Just think of a large inheritance hierarchie and only some of the types implementing their own overloading method. </p> <p>So I'd say just don't do it.</p>
2,351,087
What is the best 32bit hash function for short strings (tag names)?
<p>What is the best 32bit hash function for relatively short strings?</p> <p>Strings are tag names that consist of English letters, numbers, spaces and some additional characters (<code>#</code>, <code>$</code>, <code>.</code>, ...). For example: <code>Unit testing</code>, <code>C# 2.0</code>.</p> <p>I am looking for 'best' as in 'minimal collisions', performance is not important for my goals.</p>
2,351,359
8
7
null
2010-02-28 12:51:38.69 UTC
22
2019-08-29 06:29:31.303 UTC
null
null
null
null
39,068
null
1
52
algorithm|hash|tags|32-bit
61,335
<p>If performance isn't important, simply take a secure hash such as MD5 or SHA1, and truncate its output to 32 bits. This will give you a distribution of hash codes that's indistinguishable from random.</p>
3,173,154
Move an item inside a list?
<p>In Python, how do I move an item to a definite index in a list?</p>
3,173,159
8
0
null
2010-07-03 23:14:15.623 UTC
24
2022-05-08 13:41:24.383 UTC
2013-10-31 17:11:18.727 UTC
null
321,731
null
151,377
null
1
130
python|list
172,117
<p>Use the <code>insert</code> method of a list:</p> <pre><code>l = list(...) l.insert(index, item) </code></pre> <p>Alternatively, you can use a slice notation:</p> <pre><code>l[index:index] = [item] </code></pre> <p>If you want to move an item that's already in the list to the specified position, you would have to delete it and insert it at the new position:</p> <pre><code>l.insert(newindex, l.pop(oldindex)) </code></pre>
2,382,826
Managing A Debug and Release Connection String
<p>What is a good approach to managing a debug and release connection string in a .NET / SQLServer application?</p> <p>I have two SQL Servers, a production and a build/debug and I need a method of switching between the two when my ASP.NET application is deployed.</p> <p>Currently I simply store them in the web.config and comment one or the other out, however that is error prone when deploying.</p>
2,382,856
9
0
null
2010-03-04 21:24:21.893 UTC
15
2019-06-07 09:32:53.57 UTC
2014-06-03 18:31:26.453 UTC
null
1,196,603
user113476
null
null
1
14
c#|asp.net|vb.net|connection-string
20,305
<p>Create a Debug and Release version of the Web.config file, e.g. Web.debug.config and Web.release.config. Then add a pre-compile condition that copies the relevant version into the web.config based upon the current Target.</p> <p><strong>Edit:</strong> To add the pre compile condition right click on you project and select "Properties" then goto the "Build Events" tab and add the code below to the precompile condition. Obviously, you will have to ammend the code to your needs, see image below.</p> <pre><code>@echo off echo Configuring web.config pre-build event ... if exist "$(ProjectDir)web.config" del /F / Q "$(ProjectDir)web.config" if "$(ConfigurationName)" == "Debug Test" goto test if "$(ConfigurationName)" == "Debug M" goto M if "$(ConfigurationName)" == "Debug BA" goto BA if "$(ConfigurationName)" == "Release Test" goto test if "$(ConfigurationName)" == "Release M" goto M if "$(ConfigurationName)" == "Release BA" goto BA echo No web.config found for configuration $(ConfigurationName). Abort batch. exit -1 goto :end :test copy /Y "$(ProjectDir)web.config.test" "$(ProjectDir)web.config" GOTO end :BA copy /Y "$(ProjectDir)web.config.BA" "$(ProjectDir)web.config" GOTO end :M copy /Y "$(ProjectDir)web.config.M" "$(ProjectDir)web.config" GOTO end :end echo Pre-build event finished </code></pre> <p><a href="http://img442.imageshack.us/img442/1843/propsa.jpg">Project Properties http://img442.imageshack.us/img442/1843/propsa.jpg</a></p>
33,608,473
Unable to cast object of type 'Newtonsoft.Json.Linq.JArray' to type 'System.Collections.Generic.List`
<p>l am reading data from webservice. The json object looks like:</p> <pre><code>var goldString = [ { "date":"20151109", "day":30, "month":"November", "year":2015, "club":9, "clubName":"Flamingo", "itw":"XYD", "races":{ "1":{ "race":1, "time":"12:20", "raceStatus":"Undecided", "reference":91, "name":"WELCOME TO FLAMINGO PARK MAIDEN PLATE", "description":"For Maidens", "distance":1000, "stake":"R46,000", "stakes":"1st: R28,750 | 2nd: R9,200 | 3rd: R4,600 | 4th: R2,300 | 5th: R1,150", "surface":"Sand", "going":"\u0000", "goingDescription":"", "grade":0, "division":"MDNM", "group":"G", "class":"MAIDEN PLATE", "condition":"For Maidens", "handicap":false, "minWins":0, "maxWins":0, "minAge":"n\/a", "maxAge":"n\/a", "gender":"n\/a", "runners":[ ] }, "2":{ "race":2, "time":"12:50", "raceStatus":"Undecided", "reference":92, "name":"RACING. IT'S A RUSH PINNACLE STAKES", "description":"Open", "distance":1800, "stake":"R66,000", "stakes":"1st: R41,250 | 2nd: R13,200 | 3rd: R6,600 | 4th: R3,300 | 5th: R1,650", "surface":"Sand", "going":"\u0000", "goingDescription":"", "grade":0, "division":"PINN", "group":"A", "class":"PINNACLE STAKES", "condition":"Open", "handicap":false, "minWins":"n\/a", "maxWins":"n\/a", "minAge":"n\/a", "maxAge":"n\/a", "gender":"n\/a", "runners":[ ] }, "3":{ "race":3, "time":"13:20", "raceStatus":"Undecided", "reference":93, "name":"INTERNATIONAL JOCKEYS' CHALLENGE 14 NOVEMBER MAIDEN PLATE", "description":"For Maidens", "distance":1800, "stake":"R46,000", "stakes":"1st: R28,750 | 2nd: R9,200 | 3rd: R4,600 | 4th: R2,300 | 5th: R1,150", "surface":"Sand", "going":"\u0000", "goingDescription":"", "grade":0, "division":"MDNM", "group":"G", "class":"MAIDEN PLATE", "condition":"For Maidens", "handicap":false, "minWins":0, "maxWins":0, "minAge":"n\/a", "maxAge":"n\/a", "gender":"n\/a", "runners":[ ] }, "4":{ "race":4, "time":"13:50", "raceStatus":"Undecided", "reference":94, "name":"SOCCER 6 MR 65 HANDICAP", "description":"Open", "distance":1600, "stake":"R43,000", "stakes":"1st: R26,875 | 2nd: R8,600 | 3rd: R4,300 | 4th: R2,150 | 5th: R1,075", "surface":"Sand", "going":"\u0000", "goingDescription":"", "grade":0, "division":"MR65", "group":"E", "class":"MR 65 HANDICAP", "condition":"Open", "handicap":true, "minWins":"n\/a", "maxWins":"n\/a", "minAge":"n\/a", "maxAge":"n\/a", "gender":"n\/a", "runners":[ ] }, "5":{ "race":5, "time":"14:20", "raceStatus":"Undecided", "reference":95, "name":"COMPUTAFORM EXPRESS MR 72 HANDICAP", "description":"Open", "distance":1400, "stake":"R46,000", "stakes":"1st: R28,750 | 2nd: R9,200 | 3rd: R4,600 | 4th: R2,300 | 5th: R1,150", "surface":"Sand", "going":"\u0000", "goingDescription":"", "grade":0, "division":"MR72", "group":"D", "class":"MR 72 HANDICAP", "condition":"Open", "handicap":true, "minWins":"n\/a", "maxWins":"n\/a", "minAge":"n\/a", "maxAge":"n\/a", "gender":"n\/a", "runners":[ ] }, "6":{ "race":6, "time":"14:55", "raceStatus":"Undecided", "reference":96, "name":"RACING ASSOCIATION FM 67 HANDICAP (F &amp; M)", "description":"For Fillies and Mares", "distance":1400, "stake":"R46,000", "stakes":"1st: R28,750 | 2nd: R9,200 | 3rd: R4,600 | 4th: R2,300 | 5th: R1,150", "surface":"Sand", "going":"\u0000", "goingDescription":"", "grade":0, "division":"FM67", "group":"E", "class":"FM 67 HANDICAP (F &amp; M)", "condition":"For Fillies and Mares", "handicap":true, "minWins":"n\/a", "maxWins":"n\/a", "minAge":"n\/a", "maxAge":"n\/a", "gender":"female", "runners":[ ] }, "7":{ "race":7, "time":"15:25", "raceStatus":"Undecided", "reference":97, "name":"SOCCER GG MR 66 HANDICAP", "description":"Open", "distance":1200, "stake":"R43,000", "stakes":"1st: R26,875 | 2nd: R8,600 | 3rd: R4,300 | 4th: R2,150 | 5th: R1,075", "surface":"Sand", "going":"\u0000", "goingDescription":"", "grade":0, "division":"MR66", "group":"E", "class":"MR 66 HANDICAP", "condition":"Open", "handicap":true, "minWins":"n\/a", "maxWins":"n\/a", "minAge":"n\/a", "maxAge":"n\/a", "gender":"n\/a", "runners":[ ] }, "8":{ "race":8, "time":"15:55", "raceStatus":"Undecided", "reference":98, "name":"BOOK A TABLE 011 6811702 MR 84 HANDICAP", "description":"Open", "distance":1000, "stake":"R55,000", "stakes":"1st: R34,375 | 2nd: R11,000 | 3rd: R5,500 | 4th: R2,750 | 5th: R1,375", "surface":"Sand", "going":"\u0000", "goingDescription":"", "grade":0, "division":"MR84", "group":"C", "class":"MR 84 HANDICAP", "condition":"Open", "handicap":true, "minWins":"n\/a", "maxWins":"n\/a", "minAge":"n\/a", "maxAge":"n\/a", "gender":"n\/a", "runners":[ ] }, "9":{ "race":9, "time":"16:30", "raceStatus":"Undecided", "reference":99, "name":"NEXT FLAMINGO PARK RACE MEETING IS MONDAY 16 NOV FM 60 HANDICAP (F &amp; M)", "description":"For Fillies and Mares", "distance":1000, "stake":"R43,000", "stakes":"1st: R26,875 | 2nd: R8,600 | 3rd: R4,300 | 4th: R2,150 | 5th: R1,075", "surface":"Sand", "going":"\u0000", "goingDescription":"", "grade":0, "division":"FM60", "group":"F", "class":"FM 60 HANDICAP (F &amp; M)", "condition":"For Fillies and Mares", "handicap":true, "minWins":"n\/a", "maxWins":"n\/a", "minAge":"n\/a", "maxAge":"n\/a", "gender":"female", "runners":[ ] } } } ] </code></pre> <p>public RunOns DeserializeAccountRunOns(string json) { var myClass = new JavaScriptSerializer().Deserialize(json); return (RunOns)myClass; }</p> <p>public class RunOns { public PubRunOns runons { get; set; } }</p> <pre><code>public class PubRunOns { public string date { get; set; } public int day { get; set; } public string month { get; set; } public int year { get; set; } public int club { get; set; } public string clubName { get; set; } public string itw { get; set; } public Array races { get; set; } public static PubRunOns CreateFromData(string[] data) { return new PubRunOns { date = data[0], day = Convert.ToInt32(data[1]), month = data[2], year = Convert.ToInt32(data[3]), club = Convert.ToInt32(data[4]), clubName = data[5], itw = data[6], races = data[7].ToCharArray() }; } } public class Races { public int race { get; set; } public string time { get; set; } public string raceStatus { get; set; } public int reference { get; set; } public string name { get; set; } public string description { get; set; } public int distance { get; set; } public string stake { get; set; } public string stakes { get; set; } public string going { get; set; } public List&lt;Runner&gt; Runners { get; set; } } public class Runner { public int draw { get; set; } public int saddle { get; set; } public string Name { get; set; } public string sex { get; set; } public string colour { get; set; } public int age { get; set; } } </code></pre> <p>if l call the function:</p> <pre><code>var test= DeserializeAccountRunOns(goldString); </code></pre> <p>l get an exception: Unable to cast object of type '<code>System.Object[]</code>'to type "<code>MyProject.Class</code>" Any Ideas? Thank you in advance.</p>
33,609,944
3
2
null
2015-11-09 11:49:57.13 UTC
3
2020-11-30 14:04:37.37 UTC
2015-11-09 12:30:53.303 UTC
null
1,814,495
null
2,543,921
null
1
8
c#|json|asp.net-mvc-4|c#-4.0|json.net
56,278
<pre><code>JArray jsonResponse = JArray.Parse(goldString); foreach (var item in jsonResponse) { JObject jRaces = (JObject)item["races"]; foreach (var rItem in jRaces) { string rItemKey = rItem.Key; JObject rItemValueJson = (JObject)rItem.Value; Races rowsResult = Newtonsoft.Json.JsonConvert.DeserializeObject&lt;Races&gt;(rItemValueJson.ToString()); } } </code></pre>
10,357,618
HTTP request in Ubuntu
<p>i need to call a HTTP request in ubuntu how do i do it? I can't seem to find an answer around on how to to do it? </p> <p><strong>How do run the following url without calling a browser like lynx to do it?</strong> </p> <pre><code>http://www.smsggglobal.com/http-api.php?action=sendsms&amp;user=asda&amp;password=123123&amp;&amp;from=123123&amp;to=1232&amp;text=adsdad </code></pre>
10,357,671
2
0
null
2012-04-27 20:47:02.38 UTC
1
2014-06-30 08:22:48.347 UTC
null
null
null
null
1,057,733
null
1
14
http|url|browser|ubuntu|request
47,094
<p>in your command prompt, run the following:</p> <pre><code>curl http://www.smsggglobal.com/http-api.php?action=sendsms&amp;user=asda&amp;password=123123&amp;&amp;from=123123&amp;to=1232&amp;text=adsdad </code></pre> <p>the curl command executes an http request for a given url and parameters.</p> <p>if you need to specify another HTTP method, <code>use curl -X &lt;TYPE&gt; &lt;URL&gt;</code>, like this:</p> <pre><code>curl -X POST http://www.smsggglobal.com/http-api.php?action=sendsms&amp;user=asda&amp;password=123123&amp;&amp;from=123123&amp;to=1232&amp;text=adsdad </code></pre> <p>curl documentation: <a href="http://curl.haxx.se/docs/manpage.html">http://curl.haxx.se/docs/manpage.html</a></p>
10,563,986
UIImage with rounded corners
<p>I have read several posts already. And almost everyone suggest using <code>QuartzCore/QuartzCore.h</code> with <code>layer.cornerRadius</code></p> <p>I have tried this method and some more methods.</p> <p>Well, everything works fine when an image doesn't move.</p> <p>But in my project I always move my images. If I add corner radius or a shadow the image movement is no longer smooth. And it looks aweful!</p> <p>That is the way I resize my image:</p> <pre><code>CGSize newSize = CGSizeMake(200*height/image.size.height, 280); CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef context = CGBitmapContextCreate(nil, newSize.width, newSize.height, 8, 0, colorSpace, kCGImageAlphaPremultipliedLast); CGContextClearRect(context, CGRectMake(0, 0, newSize.width, newSize.height)); CGContextDrawImage(context, CGRectMake(0, 0, newSize.width, newSize.height), image.CGImage); CGImageRef scaledImage = CGBitmapContextCreateImage(context); CGColorSpaceRelease(colorSpace); CGContextRelease(context); UIImage *newImage = [UIImage imageWithCGImage: scaledImage]; CGImageRelease(scaledImage); </code></pre> <p>I would like to know a good way to resize my image, add shadow, corner radius and still have smooth movement of my image.</p>
10,564,035
7
0
null
2012-05-12 13:02:36.09 UTC
17
2017-05-30 06:25:04.493 UTC
2014-10-12 09:00:48.08 UTC
null
1,292,099
null
1,292,099
null
1
22
ios|xcode|uiimage|rounded-corners
33,224
<pre><code>// Get your image somehow UIImage *image = [UIImage imageNamed:@"image.jpg"]; // Begin a new image that will be the new image with the rounded corners // (here with the size of an UIImageView) UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, NO, [UIScreen mainScreen].scale); // Add a clip before drawing anything, in the shape of an rounded rect [[UIBezierPath bezierPathWithRoundedRect:imageView.bounds cornerRadius:10.0] addClip]; // Draw your image [image drawInRect:imageView.bounds]; // Get the image, here setting the UIImageView image imageView.image = UIGraphicsGetImageFromCurrentImageContext(); // Lets forget about that we were drawing UIGraphicsEndImageContext(); </code></pre> <p>Try moving with this code, as far as I can remember I used this a while back that makes an image with rounded corners that you can move around into the targets. But it seemed to scale fine...</p>
10,652,819
django 1.4 - can't compare offset-naive and offset-aware datetimes
<p>I am in the process of migrating an application from django 1.2 To 1.4.</p> <p>I have a daily task object which contains a time of day that task should be completed:</p> <pre><code>class DailyTask(models.Model): time = models.TimeField() last_completed = models.DateTimeField() name = models.CharField(max_length=100) description = models.CharField(max_length=1000) weekends = models.BooleanField() def __unicode__(self): return '%s' % (self.name) class Meta: db_table = u'dailytask' ordering = ['name'] </code></pre> <p>In order to check if a task is still required to be completed today, I have the following code:</p> <pre><code>def getDueDailyTasks(): dueDailyTasks=[] now = datetime.datetime.now() try: dailyTasks = DailyTask.objects.all() except dailyTask.DoesNotExist: return None for dailyTask in dailyTasks: timeDue = datetime.datetime(now.year,now.month,now.day,dailyTask.time.hour,dailyTask.time.minute,dailyTask.time.second) if timeDue&lt;now and timeDue&gt;dailyTask.last_completed: if dailyTask.weekends==False and now.weekday()&gt;4: pass else: dueDailyTasks.append({'id':dailyTask.id, 'due':timeDue, 'name': dailyTask.name, 'description':dailyTask.description}) return dueDailyTasks </code></pre> <p>This worked fine under 1.2, But under 1.4 I get the error:</p> <pre><code>can't compare offset-naive and offset-aware datetimes </code></pre> <p>due to the line</p> <pre><code>if timeDue&lt;now and timeDue&gt;dailyTask.last_completed </code></pre> <p>and both comparison clauses throw this error.</p> <p>I have tried making timeDue timezone aware by adding pytz.UTC as an argument, but this still raises the same error.</p> <p>I've read some of the docs on timezones but am confused as to whether I just need to make timeDue timezone aware, or whether I need to make a fundamental change to my db and existing data.</p>
10,653,144
1
0
null
2012-05-18 12:39:51.02 UTC
30
2015-12-21 13:33:27.617 UTC
2015-12-21 13:33:27.617 UTC
null
91,616
null
91,616
null
1
94
python|django|timezone
59,801
<p>Check <a href="https://docs.djangoproject.com/en/dev/topics/i18n/timezones/" rel="noreferrer">the thorough document</a> for detail info.</p> <p>Normally, use <code>django.utils.timezone.now</code> to make an offset-aware current datetime</p> <pre><code>&gt;&gt;&gt; from django.utils import timezone &gt;&gt;&gt; timezone.now() datetime.datetime(2012, 5, 18, 13, 0, 49, 803031, tzinfo=&lt;UTC&gt;) </code></pre> <p>And <code>django.utils.timezone.make_aware</code> to make an offset-aware datetime</p> <pre><code>&gt;&gt;&gt; timezone.make_aware(datetime.datetime.now(), timezone.get_default_timezone()) datetime.datetime(2012, 5, 18, 21, 5, 53, 266396, tzinfo=&lt;DstTzInfo 'Asia/Shanghai' CST+8:00:00 STD&gt;) </code></pre> <p>You could then compare both offset-aware datetimes w/o trouble. </p> <p>Furthermore, you could convert offset-awared datetime to offset-naive datetime by stripping off timezone info, then it could be compared w/ normal <code>datetime.datetime.now()</code>, under utc.</p> <pre><code>&gt;&gt;&gt; t = timezone.now() # offset-awared datetime &gt;&gt;&gt; t.astimezone(timezone.utc).replace(tzinfo=None) datetime.datetime(2012, 5, 18, 13, 11, 30, 705324) </code></pre> <p><code>USE_TZ</code> is <code>True</code> 'by default' (actually it's <code>False</code> by default, but the <code>settings.py</code> file generated by <code>django-admin.py startproject</code> set it to <code>True</code>), then if your DB supports timezone-aware times, values of time-related model fields would be timezone-aware. you could disable it by setting <code>USE_TZ=False</code>(or simply remove <code>USE_TZ=True</code>) in settings. </p>
6,132,688
Finding the Longest Palindrome Subsequence with less memory
<p>I am trying to solve a dynamic programming problem from Cormem's <a href="https://rads.stackoverflow.com/amzn/click/com/0262033844" rel="nofollow noreferrer" rel="nofollow noreferrer">Introduction to Algorithms 3rd edition</a> (pg 405) which asks the following:</p> <blockquote> <p>A palindrome is a nonempty string over some alphabet that reads the same forward and backward. Examples of palindromes are all strings of length 1, <code>civic</code>, <code>racecar</code>, and <code>aibohphobia</code> (fear of palindromes).</p> <p>Give an efficient algorithm to find the longest palindrome that is a subsequence of a given input string. For example, given the input <code>character</code>, your algorithm should return <code>carac</code>.</p> </blockquote> <p>Well, I could solve it in two ways:</p> <p><strong>First solution:</strong></p> <p>The Longest Palindrome Subsequence (LPS) of a string is simply the <a href="http://en.wikipedia.org/wiki/Longest_common_subsequence" rel="nofollow noreferrer">Longest Common Subsequence</a> of itself and its reverse. (I've build this solution after solving another related question which asks for the <a href="http://en.wikipedia.org/wiki/Longest_increasing_subsequence" rel="nofollow noreferrer">Longest Increasing Subsequence</a> of a sequence). Since it's simply a LCS variant, it also takes O(n²) time and O(n²) memory.</p> <p><strong>Second solution:</strong></p> <p>The second solution is a bit more elaborated, but also follows the general LCS template. It comes from the following recurrence:</p> <pre><code>lps(s[i..j]) = s[i] + lps(s[i+1]..[j-1]) + s[j], if s[i] == s[j]; max(lps(s[i+1..j]), lps(s[i..j-1])) otherwise </code></pre> <p>The pseudocode for calculating the length of the lps is the following:</p> <pre><code>compute-lps(s, n): // palindromes with length 1 for i = 1 to n: c[i, i] = 1 // palindromes with length up to 2 for i = 1 to n-1: c[i, i+1] = (s[i] == s[i+1]) ? 2 : 1 // palindromes with length up to j+1 for j = 2 to n-1: for i = 1 to n-i: if s[i] == s[i+j]: c[i, i+j] = 2 + c[i+1, i+j-1] else: c[i, i+j] = max( c[i+1, i+j] , c[i, i+j-1] ) </code></pre> <p>It still takes O(n²) time and memory if I want to effectively <em>construct</em> the lps (because I 'll need all cells on the table). Analysing related problems, such as LIS, which can be solved with approaches other than LCS-like with less memory (LIS is solvable with O(n) memory), I was wondering if it's possible to solve it with O(n) memory, too.</p> <p>LIS achieves this bound by linking the candidate subsequences, but with palindromes it's harder because what matters here is not the previous element in the subsequence, but the first. Does anyone know if is possible to do it, or are the previous solutions memory optimal?</p>
6,133,040
2
6
null
2011-05-26 01:07:44.06 UTC
9
2013-04-26 13:14:53.097 UTC
2013-04-26 13:14:53.097 UTC
null
1,404,614
null
756,490
null
1
12
algorithm|language-agnostic|dynamic-programming|palindrome
16,684
<p>Here is a very memory efficient version. But I haven't demonstrated that it is <em>always</em> <code>O(n)</code> memory. (With a preprocessing step it can better than <code>O(n<sup>2</sup>)</code> CPU, though <code>O(n<sup>2</sup>)</code> is the worst case.)</p> <p>Start from the left-most position. For each position, keep track of a table of the farthest out points at which you can generate reflected subsequences of length 1, 2, 3, etc. (Meaning that a subsequence to the left of our point is reflected to the right.) For each reflected subsequence we store a pointer to the next part of the subsequence.</p> <p>As we work our way right, we search from the RHS of the string to the position for any occurrences of the current element, and try to use those matches to improve the bounds we previously had. When we finish, we look at the longest mirrored subsequence and we can easily construct the best palindrome.</p> <p>Let's consider this for <code>character</code>.</p> <ol> <li>We start with our best palindrome being the letter 'c', and our mirrored subsequence being reached with the pair <code>(0, 11)</code> which are off the ends of the string.</li> <li>Next consider the 'c' at position 1. Our best mirrored subsequences in the form <code>(length, end, start)</code> are now <code>[(0, 11, 0), (1, 6, 1)]</code>. (I'll leave out the linked list you need to generate to actually find the palindrome.</li> <li>Next consider the <code>h</code> at position 2. We do not improve the bounds <code>[(0, 11, 0), (1, 6, 1)]</code>.</li> <li>Next consider the <code>a</code> at position 3. We improve the bounds to <code>[(0, 11, 0), (1, 6, 1), (2, 5, 3)]</code>.</li> <li>Next consider the <code>r</code> at position 4. We improve the bounds to <code>[(0, 11, 0), (1, 10, 4), (2, 5, 3)]</code>. (This is where the linked list would be useful.</li> </ol> <p>Working through the rest of the list we do not improve that set of bounds.</p> <p>So we wind up with the longest mirrored list is of length 2. And we'd follow the linked list (that I didn't record in this description to find it is <code>ac</code>. Since the ends of that list are at positions <code>(5, 3)</code> we can flip the list, insert character <code>4</code>, then append the list to get <code>carac</code>.</p> <p>In general the maximum memory that it will require is to store all of the lengths of the maximal mirrored subsequences plus the memory to store the linked lists of said subsequences. Typically this will be a very small amount of memory.</p> <p>At a classic memory/CPU tradeoff you can preprocess the list once in time <code>O(n)</code> to generate a <code>O(n)</code> sized hash of arrays of where specific sequence elements appear. This can let you scan for "improve mirrored subsequence with this pairing" without having to consider the whole string, which should generally be a major saving on CPU for longer strings.</p>
5,834,298
Getting the Screen Pixel coordinates of a Rect element
<p>I am trying to get the screen pixel coordinates of a rectangle in SVG via java script. When the rectangle has been clicked, I can figure out its width, height, x and y position with getBBox().</p> <p>But these positions are the original positions. I want the screen position.</p> <p>For example if I manipulate the viewBox of the whole SVG, these getBBox coordinates are not any more the same than the screen pixels. Is there a function or way to get the coordinates considering the current viewBox and the pixel size of svg element?</p>
5,835,212
2
0
null
2011-04-29 15:52:12.513 UTC
10
2015-05-18 14:13:39.71 UTC
2011-04-29 18:02:17.85 UTC
null
671,636
null
671,636
null
1
16
javascript|svg
12,712
<h2>Demo: <a href="http://phrogz.net/SVG/screen_location_for_element.xhtml" rel="noreferrer">http://phrogz.net/SVG/screen_location_for_element.xhtml</a></h2> <pre><code>var svg = document.querySelector('svg'); var pt = svg.createSVGPoint(); function screenCoordsForRect(rect){ var corners = {}; var matrix = rect.getScreenCTM(); pt.x = rect.x.animVal.value; pt.y = rect.y.animVal.value; corners.nw = pt.matrixTransform(matrix); pt.x += rect.width.animVal.value; corners.ne = pt.matrixTransform(matrix); pt.y += rect.height.animVal.value; corners.se = pt.matrixTransform(matrix); pt.x -= rect.width.animVal.value; corners.sw = pt.matrixTransform(matrix); return corners; } </code></pre> <p>The magenta squares are absolutely-positioned divs in the HTML element, using screen space coordinates. When you drag or resize the rectangles this function is called and moves the corner divs over the four corners (lines 116-126). Note that this works even when the rectangles are in arbitrary nested transformation (e.g. the blue rectangle) and the SVG is scaled (resize your browser window).</p> <p>For fun, drag one of the rectangles off the edge of the SVG canvas and notice the screen-space corners staying over the unseen dots.</p>
5,697,171
Regex: what is InCombiningDiacriticalMarks?
<p>The following code is very well known to convert accented chars into plain Text:</p> <pre><code>Normalizer.normalize(text, Normalizer.Form.NFD).replaceAll("\\p{InCombiningDiacriticalMarks}+", ""); </code></pre> <p>I replaced my "hand made" method by this one, but i need to understand the "regex" part of the replaceAll</p> <p>1) What is "InCombiningDiacriticalMarks" ?<br> 2) Where is the documentation of it? (and similars?)</p> <p>Thanks.</p>
5,697,575
2
1
null
2011-04-17 23:26:02.27 UTC
25
2016-03-31 10:52:36.473 UTC
2011-04-18 01:02:56.497 UTC
null
471,272
null
130,028
null
1
95
java|regex|unicode
41,115
<p><code>\p{InCombiningDiacriticalMarks}</code> is a Unicode block property. In JDK7, you will be able to write it using the two-part notation <code>\p{Block=CombiningDiacriticalMarks}</code>, which may be clearer to the reader. It is documented <a href="http://www.unicode.org/reports/tr44/#Properties" rel="noreferrer">here in UAX#44: “The Unicode Character Database”</a>.</p> <p>What it means is that the code point falls within a particular range, a block, that has been allocated to use for the things by that name. This is a bad approach, because there is no guarantee that the code point in that range is or is not any particular thing, nor that code points outside that block are not of essentially the same character.</p> <p>For example, there are Latin letters in the <code>\p{Latin_1_Supplement}</code> block, like é, U+00E9. However, there are things that are <em>not</em> Latin letters there, too. And of course there are also Latin letters all over the place. </p> <p>Blocks are nearly never what you want.</p> <p>In this case, I suspect that you may want to use the property <code>\p{Mn}</code>, a.k.a. <code>\p{Nonspacing_Mark}</code>. All the code points in the Combining_Diacriticals block are of that sort. There are also (as of Unicode 6.0.0) 1087 Nonspacing_Marks that are <em>not</em> in that block. </p> <p>That is almost the same as checking for <code>\p{Bidi_Class=Nonspacing_Mark}</code>, but not quite, because that group also includes the enclosing marks, <code>\p{Me}</code>. If you want both, you could say <code>[\p{Mn}\p{Me}]</code> if you are using a default Java regex engine, since it only gives access to the General_Category property. </p> <p>You’d have to use JNI to get at the ICU C++ regex library the way Google does in order to access something like <code>\p{BC=NSM}</code>, because right now only ICU and Perl give access to <em>all</em> Unicode properties. The normal Java regex library supports only a couple of standard Unicode properties. In JDK7 though there <em>will</em> be support for the Unicode Script propery, which is just about infinitely preferable to the Block property. Thus you can in JDK7 write <code>\p{Script=Latin}</code> or <code>\p{SC=Latin}</code>, or the short-cut <code>\p{Latin}</code>, to get at any character from the Latin script. This leads to the <em>very</em> commonly needed <code>[\p{Latin}\p{Common}\p{Inherited}]</code>.</p> <p>Be aware that that will not remove what you might think of as “accent” marks from all characters! There are many it will not do this for. For example, you cannot convert <strong>Đ</strong> to <strong>D</strong> or <strong>ø</strong> to <strong>o</strong> that way. For that, you need to reduce code points to those that match the same primary collation strength in the Unicode Collation Table. </p> <p>Another place where the <code>\p{Mn}</code> thing fails is of course enclosing marks like <code>\p{Me}</code>, obviously, but also there are <code>\p{Diacritic}</code> characters which are not marks. Sadly, you need full property support for that, which means JNI to either ICU or Perl. Java has a lot of issues with Unicode support, I’m afraid.</p> <p>Oh wait, I see you are Portuguese. You should have no problems at all then if you only are dealing with Portuguese text. </p> <p>However, you don’t really want to remove accents, I bet, but rather you want to be able to match things “accent-insensitively”, right? If so, then you can do so using the <a href="http://icu-project.org/apiref/icu4j/com/ibm/icu/text/Collator.html" rel="noreferrer">ICU4J (ICU for Java) collator class</a>. If you compare at the primary strength, accent marks won’t count. I do this all the time because I often process Spanish text. I have an example of how to do this for Spanish sitting around here somewhere if you need it.</p>
31,629,409
CardView goes on top of FrameLayout, but declared first
<p>I have simple FrameLayout with support CardView as first item, and TextView as second, so TextView must be on top of inflated view. This works on pre-Lolipop but on 21+ card takes toppest place in layout, why that's so and how to fix this? Same thing with RelativeLayout. Layout: </p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="wrap_content"&gt; &lt;android.support.v7.widget.CardView android:layout_width="match_parent" android:layout_height="200dp" android:layout_margin="20dp" app:cardBackgroundColor="#ff0000" app:cardUseCompatPadding="false" /&gt; &lt;TextView android:layout_width="match_parent" android:layout_height="100dp" android:text="i am top view!" android:gravity="center" android:layout_gravity="center" android:textSize="30sp" android:textAllCaps="true" android:textColor="#00ff00" android:background="#0000ff" /&gt; &lt;/FrameLayout&gt; </code></pre>
31,629,506
4
2
null
2015-07-25 17:50:48.147 UTC
4
2018-05-24 15:18:04.787 UTC
null
null
null
null
4,009,117
null
1
36
android|xml|android-5.0-lollipop|android-support-library|android-cardview
14,007
<p>Just add your text view inside the card view, far as I know the z order is undefined inside a frame layout, but last laid out view should be drawn last.</p> <p>This probably had to do with that card views in lollipop use elevation while they fall back on border drawing code pre lollipop.</p>
32,884,780
How can I remove an attribute from a React component's state object
<p>If I have a React component that had a property set on its state:</p> <pre><code>onClick() { this.setState({ foo: 'bar' }); } </code></pre> <p>Is it possible to remove <code>&quot;foo&quot;</code> here from <code>Object.keys(this.state)</code>?</p> <p>The <a href="https://facebook.github.io/react/docs/component-api.html#replacestate" rel="noreferrer">replaceState</a> method looks like the obvious method to try but it's since been deprecated.</p>
32,884,916
11
1
null
2015-10-01 10:04:35.82 UTC
5
2021-10-12 13:10:50.673 UTC
2021-10-12 13:10:50.673 UTC
null
3,001,761
null
436,336
null
1
49
reactjs|state
129,317
<p>You can set <code>foo</code> to <code>undefined</code>, like so </p> <pre><code>var Hello = React.createClass({ getInitialState: function () { return { foo: 10, bar: 10 } }, handleClick: function () { this.setState({ foo: undefined }); }, render: function() { return ( &lt;div&gt; &lt;div onClick={ this.handleClick.bind(this) }&gt;Remove foo&lt;/div&gt; &lt;div&gt;Foo { this.state.foo }&lt;/div&gt; &lt;div&gt;Bar { this.state.bar }&lt;/div&gt; &lt;/div&gt; ); } }); </code></pre> <p><a href="https://jsfiddle.net/hoanxv2k/" rel="noreferrer"><code>Example</code></a></p> <p><strong>Update</strong></p> <p>The previous solution just remove value from <code>foo</code> and <em><code>key</code></em> skill exists in <code>state</code>, if you need completely remove key from <code>state</code>, one of possible solution can be <code>setState</code> with one parent <em><code>key</code></em>, like so</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var Hello = React.createClass({ getInitialState: function () { return { data: { foo: 10, bar: 10 } } }, handleClick: function () { const state = { data: _.omit(this.state.data, 'foo') }; this.setState(state, () =&gt; { console.log(this.state); }); }, render: function() { return ( &lt;div&gt; &lt;div onClick={ this.handleClick }&gt;Remove foo&lt;/div&gt; &lt;div&gt;Foo { this.state.data.foo }&lt;/div&gt; &lt;div&gt;Bar { this.state.data.bar }&lt;/div&gt; &lt;/div&gt; ); } }); ReactDOM.render(&lt;Hello /&gt;, document.getElementById('container'))</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"&gt;&lt;/script&gt; &lt;div id="container"&gt;&lt;/div&gt;</code></pre> </div> </div> </p>
21,125,159
Which iOS app version/build number(s) MUST be incremented upon App Store release?
<p>Version/build fields for an iOS app include:</p> <ul> <li><p>&quot;Version&quot; <strong>CFBundleShortVersionString</strong> (String - iOS, OS X) specifies the release version number of the bundle, which identifies a released iteration of the app. The release version number is a string comprised of three period-separated integers.</p> </li> <li><p>&quot;Build&quot; <strong>CFBundleVersion</strong> (String - iOS, OS X) specifies the build version number of the bundle, which identifies an iteration (released or unreleased) of the bundle. The build version number should be a string comprised of three non-negative, period-separated integers with the first integer being greater than zero. The string should only contain numeric (0-9) and period (.) characters. Leading zeros are truncated from each integer and will be ignored (that is, 1.02.3 is equivalent to 1.2.3). This key is not localizable.</p> </li> <li><p><strong>&quot;iTunes Connect Version Number&quot;</strong>: version number you specify when creating a new version of the app on iTunes Connect.</p> </li> </ul> <p>My question is:</p> <p>Which version/build numbers are <strong>required to be incremented</strong> when a new version of the app is uploaded to iTunes Connect and/or released to the App Store?</p> <p>Can either &quot;version&quot; <code>CFBundleShortVersionString</code> or &quot;build&quot; <code>CFBundleVersion</code> remain the same between app updates?</p> <p>Extra points for Apple sources or the exact error messages iTunesConnect displays upon uploading an invalid version/build number.</p> <hr /> <h3>Android / Google Play note:</h3> <p>The discussion prompting this question is that the public &quot;version&quot; of an Android app in the Google Play Store does <strong>not</strong> need to be incremented and is in <em>no way</em> validated. The <code>android:versionName</code> can remain the same between releases, upgrade, downgrade, or be any random string rather than something that appears to be a valid &quot;version number&quot;.</p> <blockquote> <p><code>android:versionName</code> — A string value that represents the release version of the application code, as it should be shown to users.</p> <p>The value is a string so that you can describe the application version as a <code>&lt;major&gt;.&lt;minor&gt;.&lt;point&gt;</code> string, <strong>or as any other type</strong> of absolute or relative version identifier.</p> </blockquote> <p><a href="https://stackoverflow.com/questions/8366113/difference-between-versionname-and-versionnumber-in-android/8366142">Difference between versionName and versionNumber in Android</a></p> <p>Whereas the <code>android:versionCode</code> is enforced to be an incrementing-on-release integer.</p> <hr /> <h3>Apple documentation</h3> <p>As noted in <a href="https://stackoverflow.com/a/38009895/1265393">the newly accepted answer</a>, Apple has recently published a Technical Note that details their version and build number scheme:</p> <p><a href="https://developer.apple.com/library/ios/technotes/tn2420/_index.html" rel="noreferrer">Apple Technical Note TN2420 - Version Numbers and Build Numbers</a></p>
38,009,895
10
1
null
2014-01-14 22:16:04.747 UTC
55
2020-03-30 05:44:23.68 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
1,265,393
null
1
145
ios|app-store|app-store-connect|mac-app-store
123,216
<p><a href="https://developer.apple.com/library/ios/technotes/tn2420/_index.html" rel="noreferrer">Apple Technical Note TN2420, Version Numbers and Build Numbers</a></p> <h2>Summary:</h2> <ul> <li>The pair (<code>Version</code>, <code>Build number</code>) must be unique. <ul> <li>The sequence is valid: (1.0.1, 12) -> (1.0.1, 13) -> (1.0.2, 13) -> (1.0.2, 14) ...</li> </ul></li> <li><code>Version</code> (<strong>CFBundleShortVersionString</strong>) must be in ascending sequential order.</li> <li><code>Build number</code> (<strong>CFBundleVersion</strong>) must be in ascending sequential order. </li> </ul> <hr> <blockquote> <h3>Version Number and Build Number Checklist</h3> <p>Here are some things you can check when submitting a new build to the App Store. Making sure you have your Version Number and Build Number set properly will help you by avoiding having your App automatically rejected for having them improperly configured.</p> <ol> <li>For each new version of your App, you need to invent a new Version Number. This number should be a greater value than the last Version Number that you used. Though you may provide many builds for any particular release of your App, you only need to use one new Version Number for each new release of your App.</li> <li>You cannot re-use Version Numbers.</li> <li>For every new build you submit, you will need to invent a new Build Number whose value is greater than the last Build Number you used (for that same version).</li> <li>You can re-use Build Numbers in different release trains, but you cannot re-use Build Numbers within the same release train. <strong>For macOS apps, you cannot re-use build numbers in any release train.</strong></li> </ol> </blockquote> <hr> <p>Based on the checklist, the following <code>(Version, Build Number)</code> sequence is valid too.</p> <ul> <li><p>Case: reuse <code>Build Number</code> in different release trains. (NOTE: <strong>NOT</strong> macOS app)</p> <p>(1.0.0, 1) -> (1.0.0, 2) -> ... -> (1.0.0, 11) -> (<strong>1.0.1</strong>, <strong>1</strong>) -> (1.0.1, 2)</p></li> </ul>
18,885,569
How do I ignore the Identity Framework magic and just use the OWIN auth middleware to get the claims I seek?
<p>The OWIN middleware stuff to integrate third-party logins to your ASP.NET app is very cool, but I can't seem to figure out how to tear it out from the new ID framework that replaces the crappy Membership API. I'm not interested in persisting the resulting claims and user info in that EF-based data persistence, I just want the claims info so I can apply it to my own user accounts in existing projects. I don't want to adopt the new ID framework just to take advantage of this stuff.</p> <p>I've been browsing the code on CodePlex, but there's a whole lot of static magic. Can you offer any suggestions?</p>
18,923,770
1
0
null
2013-09-19 03:00:42.163 UTC
24
2015-12-02 18:42:10.313 UTC
null
null
null
null
99,897
null
1
39
asp.net|owin
12,429
<p>Use the following code to setup OWIN security middlewares:</p> <pre><code>app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = "Application", AuthenticationMode = AuthenticationMode.Passive, LoginPath = new PathString("/Login"), LogoutPath = new PathString("/Logout"), }); app.SetDefaultSignInAsAuthenticationType("External"); app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = "External", AuthenticationMode = AuthenticationMode.Passive, CookieName = CookieAuthenticationDefaults.CookiePrefix + "External", ExpireTimeSpan = TimeSpan.FromMinutes(5), }); app.UseGoogleAuthentication(); </code></pre> <p>The code above sets up application cookie, external cookie and Google external login middlewares. External login middleware will convert external user login data as identity and set it to external cookie middleware. In your app, you need to get external cookie identity and convert it to external login data, then you can check it with your db user. </p> <p>Here are some sample code.</p> <p>Sign in with application cookie:</p> <pre class="lang-cs prettyprint-override"><code>var authentication = System.Web.HttpContext.Current.GetOwinContext().Authentication; var identity = new ClaimsIdentity("Application"); identity.AddClaim(new Claim(ClaimTypes.Name, "&lt;user name&gt;")); authentication.AuthenticationResponseGrant = new AuthenticationResponseGrant(identity, new AuthenticationProperties() { IsPersistent = false }); </code></pre> <p>Get application cookie identity:</p> <pre class="lang-cs prettyprint-override"><code>var identity = System.Web.HttpContext.Current.User.Identity as ClaimsIdentity; </code></pre> <p>Get external cookie identity (Google):</p> <pre class="lang-cs prettyprint-override"><code>var authentication = System.Web.HttpContext.Current.GetOwinContext().Authentication; var result = await authentication.AuthenticateAsync("External"); var externalIdentity = result.Identity; </code></pre> <p>Extract external login data from identity:</p> <pre class="lang-cs prettyprint-override"><code>public static ExternalLoginData FromIdentity(ClaimsIdentity identity) { if (identity == null) { return null; } Claim providerKeyClaim = identity.FindFirst(ClaimTypes.NameIdentifier); if (providerKeyClaim == null || String.IsNullOrEmpty(providerKeyClaim.Issuer) || String.IsNullOrEmpty(providerKeyClaim.Value)) { return null; } if (providerKeyClaim.Issuer == ClaimsIdentity.DefaultIssuer) { return null; } return new ExternalLoginData { LoginProvider = providerKeyClaim.Issuer, ProviderKey = providerKeyClaim.Value, UserName = identity.FindFirstValue(ClaimTypes.Name) }; } </code></pre>
18,940,249
Function missing 2 required positional arguments: 'x' and 'y'
<p>I am trying to write a Python turtle program that draws a Spirograph and I keep getting this error:</p> <pre><code>Traceback (most recent call last): File "C:\Users\matt\Downloads\spirograph.py", line 36, in &lt;module&gt; main() File "C:\Users\matt\Downloads\spirograph.py", line 16, in main spirograph(R,r,p,x,y) File "C:\Users\matt\Downloads\spirograph.py", line 27, in spirograph spirograph(p-1, x,y) TypeError: spirograph() missing 2 required positional arguments: 'x' and 'y' &gt;&gt;&gt; </code></pre> <p>This is the code:</p> <pre><code>from turtle import * from math import * def main(): p= int(input("enter p")) R=100 r=4 t=2*pi x= (R-r)*cos(t)-(r+p)*cos((R-r)/r*t) y= (R-r)*sin(t)-(r+p)*sin((R-r)/r*t) spirograph(R,r,p,x,y) def spirograph(R,r,p,x,y): R=100 r=4 t=2*pi x= (R-r)*cos(t)-(r+p)*cos((R-r)/r*t) y= (R-r)*sin(t)-(r+p)*sin((R-r)/r*t) while p&lt;100 and p&gt;10: goto(x,y) spirograph(p-1, x,y) if p&lt;10 or p&gt;100: print("invalid p value, enter value between 10 nd 100") input("hit enter to quite") bye() main() </code></pre> <p>I know this maybe has a simple solution but I really can't figure out what I am doing wrong, this was an exercise in my computer science 1 class and I have no idea how to fix the error.</p>
18,940,352
2
0
null
2013-09-22 04:16:36.92 UTC
2
2013-12-09 16:48:08.057 UTC
2013-09-22 10:55:01.407 UTC
null
733,077
null
2,803,457
null
1
7
python|turtle-graphics
104,894
<p>The last line of the traceback tells you where the problem is:</p> <pre><code> File "C:\Users\matt\Downloads\spirograph.py", line 27, in spirograph spirograph(p-1, x,y) # &lt;--- this is the problem line TypeError: spirograph() missing 2 required positional arguments: 'x' and 'y' </code></pre> <p>In your code, the <code>spirograph()</code> function takes 5 arguments: <code>def spirograph(R,r,p,x,y)</code>, which are <code>R</code>, <code>r</code>, <code>p</code>, <code>x</code>, <code>y</code>. In the line highlighted in the error message, you are only passing in three arguments <code>p-1, x, y</code>, and since this doesn't match what the function is expecting, Python raises an error.</p> <p>I also noticed that you are overwriting some of the arguments in the body of the function:</p> <pre><code>def spirograph(R,r,p,x,y): R=100 # this will cancel out whatever the user passes in as `R` r=4 # same here for the value of `r` t=2*pi </code></pre> <p>Here is a simple example of what is happening:</p> <pre><code>&gt;&gt;&gt; def example(a, b, c=100): ... a = 1 # notice here I am assigning 'a' ... b = 2 # and here the value of 'b' is being overwritten ... # The value of c is set to 100 by default ... print(a,b,c) ... &gt;&gt;&gt; example(4,5) # Here I am passing in 4 for a, and 5 for b (1, 2, 100) # but notice its not taking any effect &gt;&gt;&gt; example(9,10,11) # Here I am passing in a value for c (1, 2, 11) </code></pre> <p>Since you always want to keep this values as the default, you can either remove these arguments from your function's signature:</p> <pre><code>def spirograph(p,x,y): # ... the rest of your code </code></pre> <p>Or, you can give them some defaults:</p> <pre><code>def spirograph(p,x,y,R=100,r=4): # ... the rest of your code </code></pre> <p>As this is an assigment, the rest is up to you.</p>
30,047,415
How do I get mouse positions in my view model
<p>From MVVM Design pattern, the viewmodel should not know the view. But in my case, I need the view and the model, I mean : </p> <p>In my window, I've an Image component. I'd like to get mouse position when mouse moves over the Image component and save it into my model. </p> <p>The code behind would have been :</p> <pre><code>void Foo_MouseMove(objet sender, MouseEventArgs e) { model.x = e.getPosition(this.imageBox).X; model.y = e.getPosition(this.imageBox).Y; } </code></pre> <p>The problem is : I need this.imageBox and MouseEventArgs, so two View element.</p> <p>My question is : How to deal with this case using the MVVM approach ?</p> <p>I use MVVM light framework</p>
30,054,535
3
1
null
2015-05-05 08:06:56.85 UTC
9
2018-09-09 13:38:23.107 UTC
2015-05-05 08:16:30.463 UTC
null
4,303,098
null
2,190,535
null
1
7
c#|wpf|mvvm
10,343
<p>Finnally found an answer, using a EventConverter : </p> <pre><code> public class MouseButtonEventArgsToPointConverter : IEventArgsConverter { public object Convert(object value, object parameter) { var args = (MouseEventArgs)value; var element = (FrameworkElement)parameter; var point = args.GetPosition(element); return point; } } </code></pre> <p>This converter allows me to deal with Point and not with graphics components.</p> <p>Here goes the XML : </p> <pre><code> &lt;i:Interaction.Triggers&gt; &lt;i:EventTrigger EventName="MouseMove"&gt; &lt;cmd:EventToCommand Command="{Binding Main.MouseMoveCommand, Mode=OneWay}" EventArgsConverter="{StaticResource MouseButtonEventArgsToPointConverter}" EventArgsConverterParameter="{Binding ElementName=Image1}" PassEventArgsToCommand="True" /&gt; &lt;/i:EventTrigger&gt; &lt;/i:Interaction.Triggers&gt; </code></pre>
8,389,811
How to query MongoDB to test if an item exists?
<p>Does MongoDB offer a find or query method to test if an item exists based on any field value? We just want check existence, not return the full contents of the item.</p>
8,390,489
10
0
null
2011-12-05 18:10:16.347 UTC
18
2022-04-05 06:34:54.537 UTC
null
null
null
null
646,584
null
1
70
mongodb|find
135,437
<p>I dont believe that there is a straight way of checking the existence of the item by its value. But you could do that by just retrieving only id (<a href="https://docs.mongodb.org/manual/tutorial/project-fields-from-query-results/" rel="noreferrer">with field selection</a>)</p> <pre><code>db.your_collection.find({..criteria..}, {"_id" : 1}); </code></pre>
8,506,178
How to turn off Sublime 2 updates notification?
<p>I've installed Sublime 2 on Ubuntu using a PPA repository and update it via this native Ubuntu mechanism, so it just annoys me to see "A new version is available..." every time I start Sublime. I've found nothing searching for "update" in Sublime configuration file. Where can I disable the notification?</p>
12,451,054
12
0
null
2011-12-14 14:33:04.44 UTC
28
2016-09-26 05:55:20.647 UTC
2012-01-11 13:57:26.443 UTC
null
1,138,465
null
274,627
null
1
88
ubuntu|text-editor|sublimetext
42,398
<p>There is <code>update_check</code> field in Sublime version 2.0.1 build 2217.</p> <p>Just go to <code>Preferences</code> -> <code>Settings-User</code> and add there: <code>"update_check": false</code></p> <p>Sublime then stops checking for the new version.</p> <p><a href="https://i.stack.imgur.com/nbCLF.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nbCLF.jpg" alt="enter image description here"></a></p> <p>Note that at least <a href="https://github.com/SublimeTextIssues/Core/issues/1206#issuecomment-221630273" rel="nofollow noreferrer">for some versions</a> this check is deliberately broken during the evaluation period.</p>
55,762,673
How to parse list of models with Pydantic
<p>I use Pydantic to model the requests and responses to an API.</p> <p>I defined a <code>User</code> class:</p> <pre class="lang-py prettyprint-override"><code>from pydantic import BaseModel class User(BaseModel): name: str age: int </code></pre> <p>My API returns a list of users which I retrieve with <code>requests</code> and convert into a dict:</p> <pre class="lang-py prettyprint-override"><code>users = [{"name": "user1", "age": 15}, {"name": "user2", "age": 28}] </code></pre> <p>How can I convert this dict to a list of <code>User</code> instances?</p> <p>My solution for now is</p> <pre class="lang-py prettyprint-override"><code>user_list = [] for user in users: user_list.append(User(**user)) </code></pre>
61,021,183
7
0
null
2019-04-19 13:31:21.893 UTC
12
2021-10-25 05:54:43.673 UTC
null
null
null
null
3,641,865
null
1
56
python|pydantic
55,028
<p>This is now possible using <code>parse_obj_as</code>.</p> <pre class="lang-py prettyprint-override"><code>from pydantic import parse_obj_as users = [ {"name": "user1", "age": 15}, {"name": "user2", "age": 28} ] m = parse_obj_as(List[User], users) </code></pre>
3,089,038
Not all of arguments converted during string formatting
<p>Im wrtiting a script which saves the current date and time as a filename but I get an error stating "TypeError: not all arguments converted during string formatting" I am new to Python andmay of missed something obvious. Code below:</p> <pre><code>from subprocess import Popen import datetime today = datetime.date.today() today = str(today) print today f = open("%s.sql", "w" % (today)) x = Popen(["mysqldump", "-u", "root", "-pucsdrv", "normalisationtion"], stdout = f) x.wait() f.close() </code></pre>
3,089,044
2
0
null
2010-06-21 22:47:54.763 UTC
3
2020-02-15 20:04:37.713 UTC
2020-02-15 20:04:37.713 UTC
null
355,230
null
372,646
null
1
16
python|string|datetime|formatting
59,797
<p>You're putting the string formatting in the wrong place; it needs to be right after the string that's being formatted:</p> <pre><code>f = open("%s.sql" % (today), "w") </code></pre> <p>It's legal to not pass any formatting arguments, like you did with <code>"%s.sql"</code>, but it's not legal to pass arguments but not the right amount (<code>"w" % (today)</code> passes one, but there's no string formatting in <code>"w"</code>, so you get an error that not all of the arguments were used)</p>
2,462,814
Func delegate with ref variable
<pre><code>public object MethodName(ref float y) { // elided } </code></pre> <p>How do I define a <code>Func</code> delegate for this method?</p>
2,462,833
2
0
null
2010-03-17 14:04:52.853 UTC
4
2022-04-19 13:59:04.22 UTC
2022-04-19 13:59:04.22 UTC
null
1,364,007
null
31,750
null
1
70
c#|c#-3.0|reference|delegates|func
34,872
<p>It cannot be done by <code>Func</code> but you can define a custom <code>delegate</code> for it:</p> <pre><code>public delegate object MethodNameDelegate(ref float y); </code></pre> <p>Usage example:</p> <pre><code>public object MethodWithRefFloat(ref float y) { return null; } public void MethodCallThroughDelegate() { MethodNameDelegate myDelegate = MethodWithRefFloat; float y = 0; myDelegate(ref y); } </code></pre>
33,479,180
What does React Native use to allow JavaScript to be executed on iOS and Android natively?
<p>What does React Native use under the covers to interface with iOS and Android? Cordova uses a WebView to effectively display a webpage inside of a native container; Does React Native use the same approach? If not, What approach does it use?</p>
33,480,329
4
0
null
2015-11-02 13:50:32.91 UTC
7
2022-02-23 16:28:50.603 UTC
2017-10-01 06:25:26.817 UTC
null
527,702
null
1,907,902
null
1
50
javascript|android|ios|reactjs|react-native
19,258
<p>As you noticed React Native is not based on Cordova. It is not a website which looks like an app shoveled into a WebView.</p> <p>React Native uses a JavaScript runtime, but the UI is not HTML and it doesn't use a WebView. You use JSX and React Native specific components to define the UI.</p> <p>It provides a native-level performance and look and feel but some UI parts have to be configured separately for iOS and Android. For example Toolbars are completely different, but TextInput can be the same for both Operating Systems.</p>
22,988,968
Testing after_commit with RSpec and mocking
<p>I have a model Lead and a callback: <code>after_commit :create, :send_to_SPL</code></p> <p>I am using Rails-4.1.0, ruby-2.1.1, RSpec.</p> <p>1) This spec is not passing:</p> <pre><code>context 'callbacks' do it 'shall call \'send_to_SPL\' after create' do expect(lead).to receive(:send_to_SPL) lead = Lead.create(init_hash) p lead.new_record? # =&gt; false end end </code></pre> <p>2) This spec is not passing too:</p> <pre><code>context 'callbacks' do it 'shall call \'send_to_SPL\' after create' do expect(ActiveSupport::Callbacks::Callback).to receive(:build) lead = Lead.create(init_hash) end end </code></pre> <p>3) This one is passing, but I think it is not testing after_commit callback:</p> <pre><code>context 'callbacks' do it 'shall call \'send_to_SPL\' after create' do expect(lead).to receive(:send_to_SPL) lead.send(:send_to_SPL) end end </code></pre> <p>What is the best way to test after_commit callbacks in Rails?</p>
22,989,816
5
0
null
2014-04-10 13:06:22.7 UTC
5
2020-01-24 20:16:24.253 UTC
2014-04-10 13:27:26.727 UTC
null
2,767,488
null
2,767,488
null
1
34
ruby-on-rails|ruby|rspec|mocking
21,832
<p>Try to use <a href="https://github.com/grosser/test_after_commit">test_after_commit</a> gem</p> <p>or add following code in spec/support/helpers/test_after_commit.rb - <a href="https://gist.github.com/cmaitchison/5168104">Gist</a></p>
21,458,885
@extends('layout') laravel. Blade Template System seems like Not working
<p>I tried to use the laravel's template system: <code>blade</code> but seems like not working when using the code below in the file <code>users.blade.php</code>:</p> <pre><code>@extends('layout') @section('content') Users! @stop </code></pre> <p>and browser,</p> <pre><code> @extends('layout') </code></pre>
21,465,662
10
0
null
2014-01-30 14:16:45.213 UTC
1
2021-06-05 03:17:18.523 UTC
2019-01-09 09:07:13.923 UTC
null
6,529,212
null
2,640,467
null
1
13
php|laravel
56,648
<p>That should work if you have a template file at /app/views/layout.blade.php that contains</p> <pre><code>&lt;p&gt;Some content here&lt;/p&gt; @yield('content') &lt;p&gt;Some additional content here&lt;/p&gt; </code></pre> <p>Then in your /app/views/user.blade.php, the content</p> <pre><code>@extends('layout') @section('content') &lt;p&gt;This is the user content&lt;/p&gt; @stop </code></pre> <p>If you call <code>return View::make('user')</code> you should have the compiled content</p> <pre><code>&lt;p&gt;Some content here&lt;/p&gt; &lt;p&gt;This is the user content&lt;/p&gt; &lt;p&gt;Some additional content here&lt;/p&gt; </code></pre> <p>I hope that helps clarify things for you. If not, can you provide your template file locations and the relevant content?</p>
29,953,293
Is there a way to turn on ES6/ES7 syntax support in vscode?
<p><strong>Edit 3: Starting in version 0.4.0, ES6 syntax can be turned on by adding a <code>jsconfig.json</code> file to the project folder with the following contents:</strong></p> <pre><code>{ "compilerOptions": { "target": "ES6" } } </code></pre> <hr> <p><strong>Edit 2: You can <a href="http://visualstudio.uservoice.com/forums/293070-visual-studio-code/suggestions/7752489-es6-es2015-support" rel="noreferrer">vote</a> for this feature on user voice</strong></p> <hr> <p>Is there a way to "turn on" ES6/ES7 in Visual Studio Code?</p> <p><img src="https://i.imgur.com/i7QnYbM.png" alt="screenshot"></p> <p><strong>Edit 1</strong></p> <p>Tried @sarvesh's suggestion- overrode <code>javascript.validate.target</code> and restarted vscode. Didn't help.</p>
29,954,694
8
1
null
2015-04-29 19:56:11.467 UTC
16
2021-04-24 07:25:29.747 UTC
2015-07-06 13:06:26.627 UTC
null
725,866
null
725,866
null
1
112
visual-studio-code
60,487
<p>Currently, the only way to use ES6 and ES7 features is to use <a href="http://www.typescriptlang.org/" rel="noreferrer">Typescript</a>.</p> <p>On the other hand, <a href="http://visualstudio.uservoice.com/forums/293070-visual-studio-code/suggestions/7752489-es6-es2015-support" rel="noreferrer">here</a> you can see that there is a feature request for ES6 and ES7</p>
58,408,178
Query a button with specific text
<p>I have a (Jest) test to determine if a button exists:</p> <pre><code>it('renders a signup button', () =&gt; { expect(sut.getByText('Sign up for free')).toBeDefined() }) </code></pre> <p>This test because there is both a button AND heading with &quot;Sign up for free&quot; text in the component.</p> <p><a href="https://i.stack.imgur.com/UHX3e.png" rel="noreferrer"><img src="https://i.stack.imgur.com/UHX3e.png" alt="Screenshot showing both a heading and button with &quot;Sign up for free&quot; text" /></a></p> <p>A <code>testid</code> could be added to the button, but I'd prefer to follow the <strong>react-testing-library</strong> principle of simulating user behaviour.</p> <p>I feel it's legitimate a user would want to &quot;click the button labelled 'Sign up for free'&quot;. In this situation, specifying the type of HTML element makes sense as a <code>&lt;button /&gt;</code> is a distinctive element to the user, as opposed to be <code>&lt;h2 /&gt;</code> vs <code>&lt;h3 /&gt;</code>.</p> <p><strong>How can I query for a button element labelled &quot;Sign up for free&quot;? For example can <code>getByText()</code> be further limited by a query selector?</strong></p>
64,673,103
4
0
null
2019-10-16 07:40:32.533 UTC
6
2022-02-28 21:36:27.183 UTC
2020-11-04 01:29:44.237 UTC
null
9,449,426
null
1,414,008
null
1
28
reactjs|jestjs|react-testing-library
30,467
<p>I'm surprised no one here gives the most idiomatic answer yet. You can use <a href="https://testing-library.com/docs/dom-testing-library/api-queries#byrole" rel="noreferrer"><code>getByRole()</code></a> and pass an <a href="https://www.w3.org/TR/accname-1.1/" rel="noreferrer">accessible name</a>. The accessible name is the text of the button or the value of <code>aria-label</code> attribute.</p> <p>It can be used to query a specific element if multiple elements with the same role are presented on the screen.</p> <h3><a href="https://testing-playground.com/gist/d1fccaab4701aa40142da6467eedbb36/f9f79b9a4a866756bcfda75fdbb1d175400d6e46" rel="noreferrer">Text button</a></h3> <pre class="lang-html prettyprint-override"><code>&lt;button&gt;Text Button&lt;/button&gt; </code></pre> <pre class="lang-js prettyprint-override"><code>screen.getByRole('button', { name: /text button/i }) </code></pre> <h3><a href="https://testing-playground.com/gist/d1fccaab4701aa40142da6467eedbb36/a9af800216c328deb4f9cb60531cfd40e64ebc76" rel="noreferrer">Icon button</a></h3> <pre class="lang-html prettyprint-override"><code>&lt;button aria-label='edit'&gt; &lt;edit-icon /&gt; &lt;/button&gt; </code></pre> <pre class="lang-js prettyprint-override"><code>screen.getByRole('button', { name: /edit/i }) </code></pre>
49,809,702
Vertical tabs with Angular Material
<p>Using the proper <a href="https://material.angular.io/components/tabs/overview" rel="noreferrer">Angular Material directive</a>, how do I change the direction to vertical?</p> <p>Starting with vertical tabs:</p> <p><a href="https://i.stack.imgur.com/M9Cev.png" rel="noreferrer"><img src="https://i.stack.imgur.com/M9Cev.png" alt="vertical-tabs screenshot"></a></p> <p>Then want to drop to content below mat-select dropdown:</p> <p><a href="https://i.stack.imgur.com/d0I0C.png" rel="noreferrer"><img src="https://i.stack.imgur.com/d0I0C.png" alt="mat-select screenshot"></a></p> <p>EDIT: Will be working on adapting <a href="https://stackoverflow.com/a/43389018">https://stackoverflow.com/a/43389018</a> into my answer, if someone doesn't beat me to it :)</p>
49,915,087
5
2
null
2018-04-13 05:11:28.2 UTC
6
2021-02-13 08:51:05.853 UTC
2021-02-13 08:51:05.853 UTC
null
587,021
null
587,021
null
1
19
css|angular|angular-material2|angular-components|angular-material-5
40,303
<p>Wrote <a href="https://github.com/SamuelMarks/angular-vertical-tabs" rel="noreferrer"><strong>angular-vertical-tabs</strong></a>. This simply wraps <code>@angular/material</code>'s <a href="https://material.angular.io/components/list/overview#selection-lists" rel="noreferrer"><code>mat-selection-list</code></a>, and uses <code>@angular/flex-layout</code> to reorient for different screens sizes.</p> <h2>Usage</h2> <pre><code>&lt;vertical-tabs&gt; &lt;vertical-tab tabTitle="Tab 0"&gt; Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris tincidunt mattis neque lacinia dignissim. Morbi ex orci, bibendum et varius vel, porttitor et magna. &lt;/vertical-tab&gt; &lt;vertical-tab tabTitle="Tab b"&gt; Curabitur efficitur eleifend nulla, eget porta diam sodales in. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas vestibulum libero lacus, et porta ex tincidunt quis. &lt;/vertical-tab&gt; &lt;vertical-tab tabTitle="Tab 2"&gt; Sed dictum, diam et vehicula sollicitudin, eros orci viverra diam, et pretium risus nisl eget ex. Integer lacinia commodo ipsum, sit amet consectetur magna hendrerit eu. &lt;/vertical-tab&gt; &lt;/vertical-tabs&gt; </code></pre> <h2>Output</h2> <h3>Full width</h3> <p><a href="https://i.stack.imgur.com/fcofT.png" rel="noreferrer"><img src="https://i.stack.imgur.com/fcofT.png" alt="large"></a></p> <h3>Smaller screen</h3> <p><a href="https://i.stack.imgur.com/hdExY.png" rel="noreferrer"><img src="https://i.stack.imgur.com/hdExY.png" alt="small"></a></p>
35,963,128
Swift: Understanding // MARK
<p>What is the purpose of writing comments in Swift as:</p> <pre class="lang-c prettyprint-override"><code>// MARK: This is a comment </code></pre> <p>When you can also do:</p> <pre class="lang-c prettyprint-override"><code>// This is a comment </code></pre> <p>What does the <code>// MARK</code> achieve?</p>
35,963,262
2
0
null
2016-03-12 20:48:27.503 UTC
61
2019-11-10 10:16:04.337 UTC
2019-11-10 10:16:04.337 UTC
null
5,660,517
null
47,281
null
1
202
xcode|swift|comments
81,136
<p>The <code>// MARK:</code> and <code>// MARK: -</code> syntax in Swift functions identically to the <code>#pragma mark</code> and <code>#pragma mark -</code> syntax in Objective-C. </p> <p>When using this syntax (plus <code>// TODO:</code> and <code>// FIXME:</code>), you can get some extra information to show up in the quick jump bar.</p> <p>Consider these few lines of source code:</p> <pre><code>// MARK: A mark comment lives here. func isPrime(_ value: UInt) -&gt; Bool { return true } </code></pre> <p><a href="https://i.stack.imgur.com/jhEvZ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/jhEvZ.png" alt="enter image description here"></a></p> <p>And for reference, the quick jump bar is at the top in Xcode:</p> <p><a href="https://i.stack.imgur.com/DzzuS.png" rel="noreferrer"><img src="https://i.stack.imgur.com/DzzuS.png" alt="enter image description here"></a></p> <p>It exists mostly to help with quick navigation within the file.</p> <p>Note that the dash (<code>// MARK: -</code>) causes a nice separation line to show up. Consider this <code>MARK</code> comment:</p> <pre><code>// MARK: - A mark comment lives here. </code></pre> <p><a href="https://i.stack.imgur.com/nd6Ta.png" rel="noreferrer"><img src="https://i.stack.imgur.com/nd6Ta.png" alt="enter image description here"></a></p> <p>The darker gray separator line just above the bolded option in that menu comes from the dash.</p> <p>Additionally, we can achieve this separator line without a comment by simply not having any text after the dash:</p> <pre><code>// MARK: - </code></pre> <p><a href="https://i.stack.imgur.com/NsTdo.png" rel="noreferrer"><img src="https://i.stack.imgur.com/NsTdo.png" alt="enter image description here"></a></p> <p>As mentioned, <code>// TODO:</code> and <code>// FIXME:</code> comments will also appear here.</p> <pre><code>// MARK: - Prime functions func isPrime(_ value: UInt) -&gt; Bool { // TODO: Actually implement the logic for this method return true } func nthPrime(_ value: UInt) -&gt; Int { // FIXME: Returns incorrect values for some arguments return 2 } </code></pre> <p><a href="https://i.stack.imgur.com/DIq8c.png" rel="noreferrer"><img src="https://i.stack.imgur.com/DIq8c.png" alt="enter image description here"></a></p> <ul> <li>FIXMEs get a little band-aid icon that help them standout.</li> <li>MARK icon looks like a table of contents</li> <li>TODO icons look more like a checklist</li> </ul> <p>Clicking on any line in the quick jump bar takes you directly to that line in the source code.</p>
44,627,008
Show git branch in Visual Studio Code
<p>I have a project folder structure like this : <code>Code/Repo/&lt;repo_folder_name&gt;/..subfolders</code> and in the <code>&lt;repo_folder_name&gt;</code> i have the hidden <code>.git</code> folder because i cloned from Sourcetree to this folder . </p> <p>Eclipse does show the current branch , but when i open this folder in Visual Studio Code , i know it must show the current branch name , in the bottom left side . </p> <p>Does anybody know how to do this ? To show the branch name in Visual Studio Code ? </p> <p>Thank you very much.</p> <p>-- > I added Sourcetree`s bin folder to the PATH and now everything is working ok :D . Sourcetree uses embed git so you have to add it to the window path</p>
45,654,861
5
1
null
2017-06-19 09:36:38.543 UTC
null
2022-08-19 19:03:41.743 UTC
2017-06-19 09:52:48.34 UTC
null
2,660,765
null
2,660,765
null
1
15
visual-studio-code
65,063
<p>In the <a href="https://code.visualstudio.com/docs/editor/versioncontrol" rel="nofollow noreferrer">docs</a> it says:</p> <blockquote> <p>Note: VS Code will leverage your machine's Git installation, so you need to install Git first before you get these features. Make sure you install at least version 2.0.0.</p> </blockquote> <p>So there needs to be a Git on your system to get it working. Using the embedded Git from your Sourcetree installation will probably work, but might not be the cleanest solution. The Git in my Sourcetree installation (on a Mac) is about 3 years old (2.2.1). On a Mac there is also a Git preinstalled though (2.11.0), so here it works out of the box.</p>
21,363,334
How to Add Font size in subtitles in ffmpeg video filter
<p>I'm using this command to crop,scale, and then add subtitles as overlay</p> <pre><code>ffmpeg -i input.avi -vf "[in]crop=in_w:in_h-20:0:0 [crop]; [crop]scale=320:240 [scale];[scale]subtitles=srt.srt" -aspect 16:9 -vcodec libx264 -crf 23 oq.mp4 </code></pre> <p>how can we set font size/color of subtitle ?</p>
21,369,850
3
0
null
2014-01-26 12:29:50.077 UTC
17
2022-01-14 11:52:34.503 UTC
2020-08-16 22:34:21.94 UTC
null
3,082,718
null
1,116,335
null
1
23
ffmpeg|video-processing|subtitle
48,321
<p>There are two methods to use subtitles: hardsubs and softsubs.</p> <h1>Hardsubs</h1> <p>The <a href="https://ffmpeg.org/ffmpeg-filters.html#subtitles" rel="noreferrer"><code>subtitles</code></a> video filter can be used to hardsub, or burn-in, the subtitles. This requires re-encoding and the subtitles become part of the video itself.</p> <h2><code>force_style</code> option</h2> <p>To customize the subtitles you can use the <code>force_style</code> option in the <code>subtitles</code> filter. Example using subtitles file <code>subs.srt</code> and making font size of 24 with red font color.</p> <pre><code>ffmpeg -i video.mp4 -vf &quot;subtitles=subs.srt:force_style='Fontsize=24,PrimaryColour=&amp;H0000ff&amp;'&quot; -c:a copy output.mp4 </code></pre> <ul> <li><p><code>force_style</code> uses the <a href="https://fileformats.fandom.com/wiki/SubStation_Alpha#Fields" rel="noreferrer">SubStation Alpha (ASS) style fields</a>.</p> </li> <li><p><code>PrimaryColour</code> is in hexadecimal in Blue Green Red order. Note that this is the opposite order of HTML color codes. Color codes must always start with <code>&amp;H</code> and end with <code>&amp;</code>.</p> </li> </ul> <h2>Aegisub</h2> <p>Alternatively, you can use <a href="http://www.aegisub.org/" rel="noreferrer">Aegisub</a> to create and stylize your subtitles. Save as <a href="https://en.wikipedia.org/wiki/SubStation_Alpha" rel="noreferrer">SubStation Alpha</a> (ASS) format as it can support font size, font color, shadows, outlines, scaling, angle, etc.</p> <hr /> <h1>Softsubs</h1> <p>These are additional streams within the file. The player simply renders them upon playback. More flexible than hardsubbing because:</p> <ul> <li>You do not need to re-encode the video.</li> <li>You can have multiple subtitles (various languages) and switch between them.</li> <li>You can toggle them on/off during playback.</li> <li>They can be resized with any player worth using.</li> </ul> <p>Of course sometimes hardsubs are needed if the device or player is unable to utilize softsubs.</p> <p>To mux subtitles into a video file using <a href="http://ffmpeg.org/ffmpeg.html#Stream-copy" rel="noreferrer">stream copy</a> mode:</p> <pre><code>ffmpeg -i input.mkv -i subtitles.ass -codec copy -map 0 -map 1 output.mkv </code></pre> <p>Nothing is re-encoded, so the whole process will be quick and the quality and formats will be preserved.</p> <p>Using SubStation Alpha (ASS) subtitles will allow you to format the subtitles however you like. These can be created/converted with Aegisub.</p> <hr /> <h1>Also see</h1> <ul> <li><a href="http://ffmpeg.org/ffmpeg-filters.html#subtitles" rel="noreferrer"><code>subtitles</code> video filter documentation</a></li> <li><a href="https://trac.ffmpeg.org/wiki/HowToBurnSubtitlesIntoVideo" rel="noreferrer">How to burn subtitles into the video</a></li> <li><a href="https://trac.ffmpeg.org/wiki/HowToConvertSubtitleToASS" rel="noreferrer">How to convert subtitle from SRT to ASS format</a></li> </ul>
26,344,590
How to specify javax.xml.accessExternalSchema for the JAXB2 Maven plugin
<p>I have a maven plugin (jaxb2) and I need to supply a jvm arg to it. I don't think there is a tag to add jvm args in the pom for it.</p> <p>I know I can pass in jvm args on the command line eg: <code>mvn clean install -Djavax.xml.accessExternalSchema=all</code></p> <p>Is it possible to set this jvm arg in the pom so that I don't have to type it into the command line every time?</p> <p>(As aside - this jvm arg is required in order for it to work with JAVA-8. It works fine with JAVA-7)</p>
26,349,908
6
0
null
2014-10-13 16:24:19.86 UTC
2
2016-05-02 09:00:03.83 UTC
2014-10-13 22:48:02.943 UTC
null
303,810
null
1,038,172
null
1
28
java|maven|maven-jaxb2-plugin
35,732
<p>This is relevant to the new <a href="http://docs.oracle.com/javase/tutorial/jaxp/properties/properties.html" rel="noreferrer">XML security properties in JAXB 1.5</a>, introduced in Java 8. This is why your builds now fail on Java 8 but work with Java 7.</p> <p>If you're using my <code>maven-jaxb2-plugin</code>, please upgrade to the version <code>0.9.0</code> or later (current is <code>0.10.0</code>). It has now a <a href="https://github.com/highsource/maven-jaxb2-plugin/wiki/Configuring-Extension-Validation-and-XML-Security" rel="noreferrer"><code>accessExternalSchema</code></a> switch (default is <code>all</code>).</p> <p>This sets precisely <code>javax.xml.accessExternalSchema=all</code>.</p> <p>Please see the <a href="https://github.com/highsource/maven-jaxb2-plugin/wiki/Configuring-Extension-Validation-and-XML-Security" rel="noreferrer">documentation</a>.</p>
7,456,817
django - when should I use media_root or static_root?
<p>I'm confused about static files and media files in django. I've seen elsewhere that people use it interchangeably.</p> <p>When should I use <code>media_root</code> and when should I use <code>static_root</code>?</p> <p>If I have site images should I put it in static? And if I have product images do I put it in media?</p>
7,456,960
1
0
null
2011-09-17 18:09:06.007 UTC
10
2011-09-17 18:41:40.363 UTC
2011-09-17 18:10:49.91 UTC
null
489,560
null
851,920
null
1
25
django
6,446
<p><code>MEDIA_ROOT</code> is the directory where file uploads are placed, as well as where generated files are usually stored. For example, one of my Django apps allows users to upload images. In one of the model classes, I use the <code>ImageField</code> type from <a href="https://github.com/sorl/sorl-thumbnail">sorl-thumbnail</a> with <code>upload_to='%Y-%m'</code>. Whenever a user uploads an image, the file is stored in <code>MEDIA_ROOT/%Y-%m/</code> (with <code>%Y</code> replaced with the current year and <code>%m</code> replaced with the current month number). Also, when sorl-thumbnail generates a thumbnail for an uploaded image, it places the thumbnail <a href="http://thumbnail.sorl.net/reference/settings.html#thumbnail-prefix">by default</a> somewhere in <code>MEDIA_ROOT/cache/</code>.</p> <p><code>STATIC_ROOT</code> is used to configure the directory where static assets are placed. For example, site stylesheets, JavaScript files, and images used in the design of web pages are the types of files that go into <code>STATIC_ROOT</code>. If you have multiple installed apps, each app that uses static files can have its own static files directory. You use the <code>collectstatic</code> management function (invoked via <code>python manage.py collectstatic</code>) to copy all of the apps' static files into <code>STATIC_ROOT</code>.</p>
56,324,070
With GitLab CI how to disable repository clone for one job?
<p>I need to speed up job 'deploy'. It does not need sources of project but needs ONLY ARTIFACTS.</p> <h3>How to disable project cloning for the only job?</h3> <p>Typical <code>.gitlab-ci.yml</code> (pseudo) looks like:</p> <pre><code>image: gcc build: stage: build script: - ./configure - mkdir build &amp;&amp; cd $_ - cmake .. - make -sj8 artifacts: paths: - "build/*.elf" deploy: image: artifactory variables: - DO_NOT_CLONE: 1 ## WANT THIS OPTION stage: deploy script: - push_artifacts build/*.elf </code></pre>
56,324,782
1
0
null
2019-05-27 10:16:43.91 UTC
3
2022-08-16 08:11:56.807 UTC
2021-05-09 21:23:13.703 UTC
null
3,743,145
null
3,743,145
null
1
29
yaml|gitlab-ci
9,385
<p>Checkout the variable <code>GIT_STRATEGY</code>:</p> <pre><code>variables: GIT_STRATEGY: none </code></pre> <p>From the documentation:</p> <blockquote> <p><em>none</em> also re-uses the project workspace, but skips all Git operations (including GitLab Runner’s pre-clone script, if present). It is mostly useful for jobs that operate exclusively on artifacts (e.g., deploy).</p> </blockquote> <p><a href="https://docs.gitlab.com/ee/ci/runners/configure_runners.html#git-strategy" rel="nofollow noreferrer">https://docs.gitlab.com/ee/ci/runners/configure_runners.html#git-strategy</a></p>
41,843,266
Microsoft Windows Python-3.6 PyCrypto installation error
<p><code>pip install pycrypto</code> works fine with python3.5.2 but fails with python3.6 with the following error:</p> <blockquote> <p>inttypes.h(26): error C2061: syntax error: identifier 'intmax_t'</p> </blockquote>
41,843,310
9
0
null
2017-01-25 04:14:26.847 UTC
22
2022-05-17 17:31:49.317 UTC
2021-04-24 20:47:36.733 UTC
null
704,329
null
2,290,413
null
1
43
windows|visual-studio|pycrypto|python-3.6
56,234
<p>The file include\pyport.h in Python installation directory does not have <strong>#include &lt; stdint.h ></strong> anymore. This leaves <strong>intmax_t</strong> undefined.</p> <p>A workaround for Microsoft VC compiler is to force include <strong>stdint.h</strong> via OS environment variable <strong>CL</strong>:</p> <ol> <li>Open command prompt</li> <li>Setup VC environment by runing vcvars*.bat (choose file name depending on VC version and architecture)</li> <li>set CL=-FI"Full-Path\stdint.h" (use real value for Full-Path for the environment)</li> <li>pip install pycrypto</li> </ol>
45,754,739
How to import an entire folder of SVG images (or how to load them dynamically) into a React Web App?
<p>I have a component that takes in an :itemName and spits out an html bundle containing an image. The image is different for each bundle.</p> <p>Here's what I have:</p> <pre><code>import React, { Component } from 'react'; import { NavLink } from 'react-router-dom'; import SVGInline from "react-svg-inline"; export default (props) =&gt; ( &lt;NavLink className="hex" activeClassName="active" to={'/hex/' + props.itemName}&gt; {React.createElement(SVGInline, {svg: props.itemName})} &lt;/NavLink&gt; ) </code></pre> <p>How could I make this component work?</p> <p>I know that if I just imported all my images explicitly, I could just call my images like so...</p> <pre><code>import SVGInline from "react-svg-inline"; import SASSSVG from "./images/sass.svg"; &lt;NavLink className="hex" activeClassName="active" to="/hex/sass"&gt;&lt;SVGInline svg={ SASSSVG } /&gt;&lt;/NavLink&gt; </code></pre> <p>This would work, but since I need to include ~60 svgs, it adds A LOT of excess code.</p> <p>Also, I found <a href="https://stackoverflow.com/questions/41086081/importing-all-files-from-a-folder-in-react">in this question</a> this code...</p> <pre><code>import * as IconID from './icons'; </code></pre> <p>But that doesn't seem to work (it was part of the question, not the answer), and the answer was a bit too nonspecific to answer the question I'm asking.</p> <p>I also found <a href="https://stackoverflow.com/questions/40852337/dynamically-importing-an-svg-in-react">this question</a> but again there's an answer (although unapproved) that possess more questions than it answers. So, after installing react-svg, I set up a test to see if the answer works like so...</p> <pre><code>import React, { Component } from 'react'; import ReactDOM from 'react-dom' import { NavLink } from 'react-router-dom'; import ReactSVG from 'react-svg' export default (props) =&gt; ( &lt;NavLink className="hex" activeClassName="active" to={'/hex/' + props.itemName}&gt; &lt;ReactSVG path={"images/" + props.itemName + ".svg"} callback={svg =&gt; console.log(svg)} className="example" /&gt; &lt;/NavLink&gt; ) </code></pre> <p>But, just as the OP of that question was asking, the page can't find my svg even after copying my entire image folder into my build folder. I've also tried "./images/"</p> <p>I feel like I'm just missing one last key piece of information and after searching for the past day, I was hoping someone could identify the piece I'm missing.</p>
46,210,355
5
0
null
2017-08-18 10:42:12.497 UTC
7
2020-01-03 00:25:31.207 UTC
null
null
null
null
1,299,780
null
1
28
javascript|reactjs|svg|dynamic|import
21,933
<p>If using React, I strongly suspect you are also using Webpack. You can use <a href="https://webpack.js.org/guides/dependency-management/#require-context" rel="noreferrer"><code>require.context</code></a> instead of es6 <code>import</code> and Webpack will resolve it for you when building. </p> <blockquote> <pre><code>require.context ( folder, recurse, pattern ) </code></pre> <ul> <li>folder - String - Path to folder to begin scanning for files.</li> <li>recurse - Boolean - Whether to recursively scan the folder.</li> <li>pattern - RegExp - Matching pattern describing which files to include. </li> </ul> </blockquote> <p>The first line of each example ...</p> <pre><code>const reqSvgs = require.context ( './images', true, /\.svg$/ ) </code></pre> <p>... creates a Require Context mapping all the <code>*.svg</code> file paths in the <code>images</code> folder to an import. This gives us a specialized Require Function named <code>reqSvgs</code> with some attached properties.</p> <p>One of the properties of <code>reqSvgs</code> is a <code>keys</code> method, which returns a list of all the valid filepaths. </p> <pre><code>const allSvgFilepaths = reqSvgs.keys () </code></pre> <p>We can pass one of those filepaths into <code>reqSvgs</code> to get an imported image.</p> <pre><code>const imagePath = allSvgFilePaths[0] const image = reqSvgs ( imagePath ) </code></pre> <p>This api is constraining and unintuitive for this use case, so I suggest converting the collection to a more common JavaScript data structure to make it easier to work with. </p> <p><em>Every image will be imported during the conversion. Take care, as this could be a foot-gun. But it provides a reasonably simple mechanism for copying multiple files to the build folder which might never be explicitly referenced by the rest of your source code.</em></p> <p>Here are 3 example conversions that might be useful.</p> <hr> <h3>Array</h3> <p>Create an array of the imported files.</p> <pre><code>const reqSvgs = require.context ( './images', true, /\.svg$/ ) const paths = reqSvgs.keys () const svgs = paths.map( path =&gt; reqSvgs ( path ) ) </code></pre> <h3>Array of Objects</h3> <p>Create an array of objects, with each object being <code>{ path, file }</code> for one image.</p> <pre><code>const reqSvgs = require.context ( './images', true, /\.svg$/ ) const svgs = reqSvgs .keys () .map ( path =&gt; ({ path, file: reqSvgs ( path ) }) ) </code></pre> <h3>Plain Object</h3> <p>Create an object where each path is a key to its matching file. </p> <pre><code>const reqSvgs = require.context ('./images', true, /\.svg$/ ) const svgs = reqSvgs .keys () .reduce ( ( images, path ) =&gt; { images[path] = reqSvgs ( path ) return images }, {} ) </code></pre> <hr> <p>SurviveJS gives a more generalized example of <code>require.context</code> here <a href="https://survivejs.com/webpack/techniques/dynamic-loading/" rel="noreferrer">SurviveJS Webpack Dynamic Loading</a>.</p>
39,195,957
Write formula to Excel with Python
<p>I am in the process of brain storming how to best tackle the below problem. Any input is greatly appreciated.</p> <p>Sample Excel sheet columns:</p> <pre><code>Column A | Column B | Column C Apple | Apple | Orange | Orange | Pear | Banana | </code></pre> <p>I want Excel to tell me whether items in column A and B match or mismatch and display results in column C. The formula I enter in column C would be <code>=IF(A1=B1, "Match", "Mismatch")</code></p> <p>On excel, I would just drag the formula to the rest of the cells in column C to apply the formula to them and the result would be:</p> <pre><code>Column A | Column B | Column C Apple | Apple | Match Orange | Orange | Match Pear | Banana | Mismatch </code></pre> <p>To automate this using a python script, I tried:</p> <pre><code>import openpyxl wb = openpyxl.load_workbook('test.xlsx') Sheet = wb.get_sheet_by_name('Sheet1') for cellObj in Sheet.columns[2]: cellObj.value = '=IF($A$1=$B$1, "Match", "Mismatch") wb.save('test.xlsx') </code></pre> <p>This wrote the formula to all cells in column C, however the formula only referenced cell A1 and B1, so result in all cells in column C = Match.</p> <pre><code>Column A | Column B | Column C Apple | Apple | Match Orange | Orange | Match Pear | Banana | Match </code></pre> <p>How would you handle this?</p>
39,196,008
2
0
null
2016-08-28 21:31:53.033 UTC
4
2021-08-11 17:38:35.7 UTC
null
null
null
null
6,023,749
null
1
14
python|excel|openpyxl
43,485
<p>You probably want to make the creation of the formula dynamic so each row of <code>C</code> takes from the corresponding rows of <code>A</code> and <code>B</code>:</p> <pre><code>for i, cellObj in enumerate(Sheet.columns[2], 1): cellObj.value = '=IF($A${0}=$B${0}, "Match", "Mismatch")'.format(i) </code></pre>
56,726,663
How to add a TextField to Alert in SwiftUI?
<p>Anyone an idea how to create an Alert in SwiftUI that contains a TextField?</p> <p><img src="https://i.stack.imgur.com/LrUAM.png" alt="sample_image" /></p>
61,902,990
13
0
null
2019-06-23 18:18:22.92 UTC
14
2022-07-25 12:39:28.38 UTC
2020-11-09 22:36:43.36 UTC
null
8,697,793
null
11,689,145
null
1
67
alert|textfield|swiftui
36,561
<p>As the <code>Alert</code> view provided by <code>SwiftUI</code> doesn't do the job you will need indeed to use <code>UIAlertController</code> from <code>UIKit</code>. Ideally we want a <code>TextFieldAlert</code> view that we can presented in the same way we would present the <code>Alert</code> provided by <code>SwiftUI</code>:</p> <pre><code>struct MyView: View { @Binding var alertIsPresented: Bool @Binding var text: String? // this is updated as the user types in the text field var body: some View { Text("My Demo View") .textFieldAlert(isPresented: $alertIsPresented) { () -&gt; TextFieldAlert in TextFieldAlert(title: "Alert Title", message: "Alert Message", text: self.$text) } } } </code></pre> <p>We can achieve this writing a couple of classes and adding a modifier in a <code>View</code> extension.</p> <p>1) <code>TextFieldAlertViewController</code> creates a <code>UIAlertController</code> (with a text field of course) and presents it when it appears on screen. User changes to the text field are reflected into a <code>Binding&lt;String&gt;</code> that is passed during initializazion. </p> <pre><code>class TextFieldAlertViewController: UIViewController { /// Presents a UIAlertController (alert style) with a UITextField and a `Done` button /// - Parameters: /// - title: to be used as title of the UIAlertController /// - message: to be used as optional message of the UIAlertController /// - text: binding for the text typed into the UITextField /// - isPresented: binding to be set to false when the alert is dismissed (`Done` button tapped) init(title: String, message: String?, text: Binding&lt;String?&gt;, isPresented: Binding&lt;Bool&gt;?) { self.alertTitle = title self.message = message self._text = text self.isPresented = isPresented super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Dependencies private let alertTitle: String private let message: String? @Binding private var text: String? private var isPresented: Binding&lt;Bool&gt;? // MARK: - Private Properties private var subscription: AnyCancellable? // MARK: - Lifecycle override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) presentAlertController() } private func presentAlertController() { guard subscription == nil else { return } // present only once let vc = UIAlertController(title: alertTitle, message: message, preferredStyle: .alert) // add a textField and create a subscription to update the `text` binding vc.addTextField { [weak self] textField in guard let self = self else { return } self.subscription = NotificationCenter.default .publisher(for: UITextField.textDidChangeNotification, object: textField) .map { ($0.object as? UITextField)?.text } .assign(to: \.text, on: self) } // create a `Done` action that updates the `isPresented` binding when tapped // this is just for Demo only but we should really inject // an array of buttons (with their title, style and tap handler) let action = UIAlertAction(title: "Done", style: .default) { [weak self] _ in self?.isPresented?.wrappedValue = false } vc.addAction(action) present(vc, animated: true, completion: nil) } } </code></pre> <p>2) <code>TextFieldAlert</code> wraps <code>TextFieldAlertViewController</code> using the <code>UIViewControllerRepresentable</code> protocol so that it can be used within SwiftUI.</p> <pre><code>struct TextFieldAlert { // MARK: Properties let title: String let message: String? @Binding var text: String? var isPresented: Binding&lt;Bool&gt;? = nil // MARK: Modifiers func dismissable(_ isPresented: Binding&lt;Bool&gt;) -&gt; TextFieldAlert { TextFieldAlert(title: title, message: message, text: $text, isPresented: isPresented) } } extension TextFieldAlert: UIViewControllerRepresentable { typealias UIViewControllerType = TextFieldAlertViewController func makeUIViewController(context: UIViewControllerRepresentableContext&lt;TextFieldAlert&gt;) -&gt; UIViewControllerType { TextFieldAlertViewController(title: title, message: message, text: $text, isPresented: isPresented) } func updateUIViewController(_ uiViewController: UIViewControllerType, context: UIViewControllerRepresentableContext&lt;TextFieldAlert&gt;) { // no update needed } } </code></pre> <p>3) <code>TextFieldWrapper</code> is a simple <code>ZStack</code> with a <code>TextFieldAlert</code> on the back (only if <code>isPresented</code> is true) and a presenting view on the front. The presenting view is the only one visibile.</p> <pre><code>struct TextFieldWrapper&lt;PresentingView: View&gt;: View { @Binding var isPresented: Bool let presentingView: PresentingView let content: () -&gt; TextFieldAlert var body: some View { ZStack { if (isPresented) { content().dismissable($isPresented) } presentingView } } } </code></pre> <p>4) The <code>textFieldAlert</code> modifier allows us to smoothly wrap any SwiftUI view in a <code>TextFieldWrapper</code> and obtain the desired behaviour.</p> <pre><code>extension View { func textFieldAlert(isPresented: Binding&lt;Bool&gt;, content: @escaping () -&gt; TextFieldAlert) -&gt; some View { TextFieldWrapper(isPresented: isPresented, presentingView: self, content: content) } } </code></pre>
36,329,944
How to determine path to deep outdated/deprecated packages (NPM)?
<p>How to determine, which packages (<strong>deep</strong>-dependencies, not top-level) are outdated in my local NPM installation?</p> <p>I run the following command:</p> <pre><code>npm install </code></pre> <p>having this in my <code>package.json</code>:</p> <pre class="lang-js prettyprint-override"><code>"dependencies": { "bluebird": "^3.3.4", "body-parser": "~1.15.0", "connect-flash": "^0.1.1", "cookie-parser": "~1.4.1", "debug": "~2.2.0", "express": "~4.13.1", "express-session": "^1.13.0", "hbs": "~4.0.0", "lodash": "^4.6.1", "mkdirp-bluebird": "^1.0.0", "morgan": "~1.7.0", "opener": "^1.4.1", "sequelize": "^3.19.3", "serve-favicon": "~2.3.0", "sqlite3": "^3.1.1" }, </code></pre> <p>and get the following output:</p> <pre><code>$ npm install npm WARN deprecated [email protected]: graceful-fs version 3 and before will fail on newer node releases. Please update to graceful-fs@^4.0.0 as soon as possible. npm WARN deprecated [email protected]: lodash@&lt;3.0.0 is no longer maintained. Upgrade to lodash@^4.0.0. npm WARN deprecated [email protected]: graceful-fs version 3 and before will fail on newer node releases. Please update to graceful-fs@^4.0.0 as soon as possible. </code></pre> <p>In my <code>package.json</code> all packages are fresh, but some of deep dependencies are outdated, and I don't know, how to determine <strong>WHICH</strong> of them.. And I want to do it quickly;)</p>
36,335,866
2
0
null
2016-03-31 09:52:52.87 UTC
8
2022-05-29 18:45:36.39 UTC
2017-04-25 18:06:09.21 UTC
null
1,115,187
null
1,115,187
null
1
9
javascript|node.js|npm
16,843
<p>you want ...</p> <pre><code>npm install -g npm-check-updates </code></pre> <p>then to show available updates</p> <pre><code>ncu </code></pre> <p>also ...</p> <pre><code>ncu -u </code></pre> <p>which actually change <code>package.json</code> to reflect the output of <code>ncu</code>.</p> <p>And if that wasn't enough ...</p> <pre><code>ncu -m bower </code></pre> <p>check for new bower packages too!</p> <p>Package <code>npm-check-updates</code> and more documentation <a href="https://www.npmjs.com/package/npm-check-updates" rel="noreferrer"><strong>is here</strong></a></p> <h2>Edit for DEEP dependencies</h2> <p><code>npm-check-updates</code> does not provide a depth option. With further research I found that npm <a href="https://docs.npmjs.com/cli/outdated" rel="noreferrer">now provides</a> a CLI utitility to do what you want.</p> <p>This essentially allows you to do ...</p> <pre><code>npm outdated --depth=5 </code></pre> <p>which provides a similar output to <code>npm-check-updates</code> <strong>but</strong> also checks depth.</p> <p>Note the default depth is 0 viz top level packages only. Also note that <code>npm outdated</code> only lists</p> <ul> <li>current version</li> <li>wanted version</li> <li>latest version</li> </ul> <p>it does not actually do the update.</p> <p>To update packages use:</p> <pre><code>npm update --depth=5 </code></pre> <p><em>npm warns against using the depth option in conjunction with <a href="https://docs.npmjs.com/cli/update" rel="noreferrer">npm-update</a></em></p>
36,455,305
Accessing root Angular 2 injector instance globally
<p>How to access an instance of root Angular 2 injector globally (say, from browser console).</p> <p>In Angular 1 it was <code>angular.element(document).injector()</code>.</p> <p>It can be useful during testing and exploration, to use browser console to get injector to then access instances of different components, directives, services etc.</p>
36,455,408
3
0
null
2016-04-06 15:14:14.27 UTC
9
2020-04-17 12:50:52.33 UTC
2017-04-24 16:21:49.33 UTC
null
2,545,680
null
2,075,565
null
1
12
angular|dependency-injection
13,010
<p>You must set it into a service after bootstrapping the application:</p> <pre><code>export var applicationInjector: Injector; bootstrap([AppComponent]).then((componentRef: ComponentRef) =&gt; { applicationInjector = componentRef.injector; }); </code></pre> <p>Then you can import it into other parts of your application:</p> <pre><code>import {applicationInjector} from './bootstrap'; </code></pre> <p>See this question for more details:</p> <ul> <li><a href="https://stackoverflow.com/questions/35190844/good-way-to-secure-multiple-angular-2-components/35190965#35190965">Good way to secure multiple Angular 2 components</a></li> </ul> <p><strong>Edit</strong></p> <p>You can inject the <code>ApplicationRef</code> into components and have access to the root injector through it:</p> <pre><code>@Component({ (...) }) export class SomeComponent { constructor(private app:ApplicationRef) { var rootInjector = app.injector; } } </code></pre> <p>You need to leverage dependency injection to get it.</p>
60,172,282
How to run/debug a streamlit application from an IDE
<p>I really like streamlit as an environment for research. Mixing a notebook/dashboard-like output I can design quickly with pure code for its definition (no cells etc.) as well as the ability to influence my code through widgets while it runs is a game changer.</p> <p>For this purpose, I was looking for a way to run or even debug a streamlit application, since the tutorials only show it being started via the commandline:</p> <pre class="lang-sh prettyprint-override"><code>streamlit run code.py </code></pre> <p>Is there a way to do either running or debugging from an IDE?</p>
60,172,283
6
0
null
2020-02-11 15:26:22.493 UTC
7
2022-08-28 01:12:14.343 UTC
2022-02-07 14:00:26.66 UTC
null
4,563,947
null
4,563,947
null
1
33
debugging|intellij-idea|pycharm|ide|streamlit
14,234
<p>I found a way to at least run the code from the IDE (PyCharm in my case). The <code>streamlit run code.py</code> command can directly be called from your IDE. (The <code>streamlit run code.py</code> command actually calls <code>python -m streamlit.cli run code.py</code>, which was the former solution to run from the IDE.)</p> <p>The <code>-m streamlit run</code> goes into the interpreter options field of the Run/Debug Configuration (this is supported by Streamlit, so has guarantees to not be broken in the future<sup>1</sup>), the code.py goes into the Script path field as expected. In past versions, it was also working to use <code>-m streamlit.cli run</code> in the interpreter options field of the Run/Debug Configuration, but this option might break in the future.</p> <p><a href="https://i.stack.imgur.com/DaKb9.png" rel="noreferrer"><img src="https://i.stack.imgur.com/DaKb9.png" alt="PyCharm Run configuration shown here" /></a></p> <p>Unfortunately, debugging that way does not seem to work since the parameters appended by PyCharm are passed to streamlit instead of the pydev debugger.</p> <p>Edit: Just found a way to debug your own scripts. Instead of debugging your script, you debug the <code>streamlit.cli</code> module which runs your script. To do so, you need to change from <code>Script path:</code> to <code>Module name:</code> in the top-most field (there is a slightly hidden dropdown box there...). Then you can insert <code>streamlit.cli</code> into the field. As the parameters, you now add <code>run code.py</code> into the <code>Parameters:</code> field of the Run/Debug Configuration. <a href="https://i.stack.imgur.com/rePKV.png" rel="noreferrer"><img src="https://i.stack.imgur.com/rePKV.png" alt="Run/Debug configuration shown here" /></a></p> <p>EDIT: adding @sismo 's comment</p> <p>If your script needs to be run with some args you can easily add them as</p> <p><code>run main.py -- --option1 val1 --option2 val2</code></p> <p>Note the first <code>--</code> with blank: it is needed to stop streamlit argument parsing and pass to <code>main.py</code> argument parsing.</p> <hr /> <p><sup><sup>1</sup> <a href="https://discuss.streamlit.io/t/run-streamlit-from-pycharm/21624/3" rel="noreferrer">https://discuss.streamlit.io/t/run-streamlit-from-pycharm/21624/3</a></sup></p>
142,944
How do you implement a Highpass filter for the IPhone accelerometer?
<p>I remember seeing the code for a Highpass filter a few days back somewhere in the samples, however I can't find it anywhere now! Could someone remember me where the Highpass filter implementation code was?</p> <p>Or better yet post the algorithm?</p> <p>Thanks!</p>
142,962
3
0
null
2008-09-27 03:59:42.08 UTC
20
2016-05-04 20:33:22.497 UTC
null
null
null
Robert Gould
15,124
null
1
15
iphone
16,941
<p><a href="http://idevkit.com/forums/tutorials-code-samples-sdk/171-accelerometer-high-pass-filter-incorrect-apple-code.html" rel="nofollow noreferrer">From the idevkit.com forums:</a></p> <pre><code>#define kFilteringFactor 0.1 static UIAccelerationValue rollingX=0, rollingY=0, rollingZ=0; - (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration { // Calculate low pass values rollingX = (acceleration.x * kFilteringFactor) + (rollingX * (1.0 - kFilteringFactor)); rollingY = (acceleration.y * kFilteringFactor) + (rollingY * (1.0 - kFilteringFactor)); rollingZ = (acceleration.z * kFilteringFactor) + (rollingZ * (1.0 - kFilteringFactor)); // Subtract the low-pass value from the current value to get a simplified high-pass filter float accelX = acceleration.x - rollingX; float accelY = acceleration.y - rollingY; float accelZ = acceleration.z - rollingZ; // Use the acceleration data. } </code></pre>
523,627
Storing passwords in iPhone applications
<p>I have a simple application, based of the "Utility Application" template. It retrieves a password-protected XML file (via NSXMLParser).</p> <p>I want to allow the user to set a username and password in the "FlipsideView", how would I go about this?</p> <p>I have the basics in place, the two UITextField boxes, the value of which gets set to a fixed value when the view loads (using the <code>viewWillAppear</code> method), and NSLog'd when the view is closed (the <code>NSLog</code> is just for testing, obviously, in the <code>viewWillDisappear</code> method)</p> <p>How do I store the data? I've had a look at the Developer documentation, and it seems like I should be using <code>NSUserDefaults</code>..?</p>
524,144
3
0
null
2009-02-07 11:32:17.93 UTC
16
2012-10-24 12:08:35.173 UTC
null
null
null
dbr
745
null
1
25
iphone|passwords
15,951
<p>I agree with Ben. This is <em>exactly</em> what the Keychain is for.</p> <p>I would not, under any circumstances simply store passwords in the defaults as dbr suggests. This is highly insecure. You're essentially storing your passwords in the open.</p> <p>In addition to Apple's sample code, I also recommend Buzz Anderson's Keychain code: <a href="http://log.scifihifi.com/post/55837387/simple-iphone-keychain-code" rel="noreferrer">iPhone Keychain Code</a></p>
869,001
How to serve all existing static files directly with NGINX, but proxy the rest to a backend server.
<pre><code>location / { proxy_set_header X-Real-IP $remote_addr; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; if (-f $request_filename) { access_log off; expires 30d; break; } if (!-f $request_filename) { proxy_pass http://127.0.0.1:8080; # backend server listening break; } } </code></pre> <p>Above will serve all existing files directly using Nginx (e.g. Nginx just displays PHP source code), otherwise forward a request to Apache. I need to exclude *.php files from the rule so that requests for *.php are also passed to Apache and processed.</p> <p>I want Nginx to handle all static files and Apache to process all dynamic stuff.</p> <p>EDIT: There is white list approach, but it is not very elegant, See all those extensions, I don't want this.</p> <pre><code>location ~* ^.+.(jpg|jpeg|gif|png|ico|css|zip|tgz|gz|rar|bz2|doc|xls|exe|pdf|ppt|txt|tar|mid|midi|wav|bmp|rtf|js)$ { access_log off; expires 30d; } location / { proxy_set_header X-Real-IP $remote_addr; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://127.0.0.1:8080; } </code></pre> <p>EDIT 2: On newer versions of Nginx use <code>try_files</code> instead <a href="http://wiki.nginx.org/HttpCoreModule#try_files" rel="noreferrer">http://wiki.nginx.org/HttpCoreModule#try_files</a></p>
15,467,555
3
1
null
2009-05-15 14:24:27.66 UTC
64
2016-07-04 07:50:56.207 UTC
2016-07-04 07:50:56.207 UTC
null
3,772,221
null
90,263
null
1
93
nginx|reverse-proxy|static-files
136,816
<p>Use <a href="http://nginx.org/en/docs/http/ngx_http_core_module.html#try_files">try_files</a> and named location block ('@apachesite'). This will remove unnecessary regex match and if block. More efficient.</p> <pre><code>location / { root /path/to/root/of/static/files; try_files $uri $uri/ @apachesite; expires max; access_log off; } location @apachesite { proxy_set_header X-Real-IP $remote_addr; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://127.0.0.1:8080; } </code></pre> <p><strong>Update:</strong> The assumption of this config is that there doesn't exist any php script under <code>/path/to/root/of/static/files</code>. This is common in most modern php frameworks. In case your legacy php projects have both php scripts and static files mixed in the same folder, you may have to whitelist all of the file types you want nginx to serve.</p>
41,825,868
Update python dictionary (add another value to existing key)
<p>I have simple dictionary with key, value:</p> <pre><code>d = {'word': 1, 'word1': 2} </code></pre> <p>I need to add another value (to make a list from values):</p> <pre><code>d = {'word': [1, 'something'], 'word1': [2, 'something1']} </code></pre> <p>I can't deal with it. Any clues?</p>
41,825,922
8
2
null
2017-01-24 10:33:14.04 UTC
9
2021-04-25 02:29:12.137 UTC
2017-01-24 10:38:11.157 UTC
null
67,579
null
889,778
null
1
17
python
105,553
<p>Well you can simply use:</p> <pre><code>d['word'] = [1,'something'] </code></pre> <p>Or in case the <code>1</code> needs to be fetched:</p> <pre><code>d['word'] = [d['word'],'something'] </code></pre> <p>Finally say you want to update a sequence of keys with new values, like:</p> <pre><code>to_add = {'word': 'something', 'word1': 'something1'} </code></pre> <p>you could use:</p> <pre><code>for key,val in to_add.items(): if key in d: d[key] = [d[key],val] </code></pre>
41,476,063
TypeScript: remove key from type/subtraction type
<p>I want to define a generic type <code>ExcludeCart&lt;T&gt;</code> that is essentially <code>T</code> but with a given key (in my case, <code>cart</code>) removed. So, for instance, <code>ExcludeCart&lt;{foo: number, bar: string, cart: number}&gt;</code> would be <code>{foo: number, bar: string}</code>. Is there a way to do this in TypeScript?</p> <p>Here's why I want to do this, in case I'm barking up the wrong tree: I'm converting an existing JavaScript codebase to TypeScript, which contains a decorator function called <code>cartify</code> that takes a React component class <code>Inner</code> and returns another component class <code>Wrapper</code>.</p> <p><code>Inner</code> should take a <code>cart</code> prop, and zero or more other props. <code>Wrapper</code> accepts a <code>cartClient</code> prop (which is used to generate the <code>cart</code> prop to pass to <code>Inner</code>), and any prop that <code>Inner</code> accepts, <em>except</em> <code>cart</code>.</p> <p>In other words, once I can figure out how to define <code>ExcludeCart</code>, I want to do this with it:</p> <pre><code>function cartify&lt;P extends {cart: any}&gt;(Inner: ComponentClass&lt;P&gt;) : ComponentClass&lt;ExcludeCart&lt;P&gt; &amp; {cartClient: any}&gt; </code></pre>
47,643,102
6
1
null
2017-01-05 01:43:12.313 UTC
6
2021-02-27 01:05:39.197 UTC
2017-12-04 22:32:25.587 UTC
null
1,980,909
null
445,398
null
1
47
reactjs|generics|typescript|decorator|higher-order-components
41,764
<p>While there isn't a built-in subtraction type, you can currently hack it in:</p> <pre><code>type Sub0&lt; O extends string, D extends string, &gt; = {[K in O]: (Record&lt;D, never&gt; &amp; Record&lt;string, K&gt;)[K]} type Sub&lt; O extends string, D extends string, // issue 16018 Foo extends Sub0&lt;O, D&gt; = Sub0&lt;O, D&gt; &gt; = Foo[O] type Omit&lt; O, D extends string, // issue 16018 Foo extends Sub0&lt;keyof O, D&gt; = Sub0&lt;keyof O, D&gt; &gt; = Pick&lt;O, Foo[keyof O]&gt; </code></pre> <p>In the question's case, you would do:</p> <pre><code>type ExcludeCart&lt;T&gt; = Omit&lt;T, 'cart'&gt; </code></pre> <p>With TypeScript >= 2.6, you can simplify it to:</p> <pre><code>/** * for literal unions * @example Sub&lt;'Y' | 'X', 'X'&gt; // === 'Y' */ export type Sub&lt; O extends string, D extends string &gt; = {[K in O]: (Record&lt;D, never&gt; &amp; Record&lt;string, K&gt;)[K]}[O] /** * Remove the keys represented by the string union type D from the object type O. * * @example Omit&lt;{a: number, b: string}, 'a'&gt; // === {b: string} * @example Omit&lt;{a: number, b: string}, keyof {a: number}&gt; // === {b: string} */ export type Omit&lt;O, D extends string&gt; = Pick&lt;O, Sub&lt;keyof O, D&gt;&gt; </code></pre> <p><a href="https://www.typescriptlang.org/play/#src=%2F**%0D%0A%20*%20for%20literal%20unions%0D%0A%20*%20%40example%20Sub%3C&#39;Y&#39;%20%7C%20&#39;X&#39;%2C%20&#39;X&#39;%3E%20%2F%2F%20%3D%3D%3D%20&#39;Y&#39;%0D%0A%20*%2F%0D%0Aexport%20type%20Sub%3C%0D%0A%20%20%20%20O%20extends%20string%2C%0D%0A%20%20%20%20D%20extends%20string%0D%0A%20%20%20%20%3E%20%3D%20%7B%5BK%20in%20O%5D%3A%20(Record%3CD%2C%20never%3E%20%26%20Record%3Cstring%2C%20K%3E)%5BK%5D%7D%5BO%5D%0D%0A%0D%0Atype%20A%20%3D%20Sub%3C&#39;Y&#39;%20%7C%20&#39;X&#39;%2C%20&#39;X&#39;%3E%0D%0A%0D%0A%2F**%0D%0A%20*%20Remove%20the%20keys%20represented%20by%20the%20string%20union%20type%20D%20from%20the%20object%20type%20O.%0D%0A%20*%0D%0A%20*%20%40example%20Omit%3C%7Ba%3A%20number%2C%20b%3A%20string%7D%2C%20&#39;a&#39;%3E%20%2F%2F%20%3D%3D%3D%20%7Bb%3A%20string%7D%0D%0A%20*%20%40example%20Omit%3C%7Ba%3A%20number%2C%20b%3A%20string%7D%2C%20keyof%20%7Ba%3A%20number%7D%3E%20%2F%2F%20%3D%3D%3D%20%7Bb%3A%20string%7D%0D%0A%20*%2F%0D%0Aexport%20type%20Omit%3CO%2C%20D%20extends%20string%3E%20%3D%20Pick%3CO%2C%20Sub%3Ckeyof%20O%2C%20D%3E%3E%0D%0A%0D%0Atype%20X%20%3D%20Omit%3C%7Ba%3A%20number%2C%20b%3A%20string%7D%2C%20keyof%20%7Ba%3A%20number%7D%3E" rel="noreferrer">test it on the playground</a></p>
6,088,817
How to access Firefox Sync bookmarks without Firefox
<p>Firefox 4 syncs bookmarks and other settings to a host run by mozilla. </p> <ul> <li>How do I access my bookmarks there (without Firefox)?</li> <li>Is there a documented API?</li> </ul> <p>It seems <a href="https://developer.mozilla.org/en/Firefox_Sync" rel="noreferrer">https://developer.mozilla.org/en/Firefox_Sync</a> should contain the neccessary documentation but all links except the first point to empty pages. </p> <p>I found a script called weave.py here <a href="https://github.com/mozilla/weaveclient-python/blob/master/weave.py" rel="noreferrer">https://github.com/mozilla/weaveclient-python/blob/master/weave.py</a> that is supposed to be able to access those bookmarks but it is unable to use my credentials. It seems to expect usernames without "@" characters. </p> <p>Is there any documentation out there on how to access Firefox sync data. Preferably with examples. </p> <p>Right now I don't even know the entry point to this supposed web service.</p> <p>When I go to <a href="https://services.mozilla.com/" rel="noreferrer">https://services.mozilla.com/</a> I can change my password and presumably remove everything.</p>
6,089,132
3
0
null
2011-05-22 15:14:49.07 UTC
9
2011-09-23 20:10:48.477 UTC
null
null
null
null
199,972
null
1
16
api|firefox|sync
8,110
<p>If you look at <a href="https://wiki.mozilla.org/Services/Sync" rel="noreferrer">https://wiki.mozilla.org/Services/Sync</a>, I think that's the documentation you want. More detail is at <a href="https://wiki.mozilla.org/Labs/Weave/Sync/1.1/API" rel="noreferrer">https://wiki.mozilla.org/Labs/Weave/Sync/1.1/API</a>.</p>
5,811,425
Dummy SMTP server for development purposes
<p>I've been using a dummy smtp server called DevNull SMTP so that I can test my app which sends out notification emails. It has a nice simple GUI, very helpful, but can't be scripted easily. I can't even start it listening to port 25. I have to run the app and then click on the start button...</p> <p>Is there a similar app that can be scripted easily? Scripted in the sense that I can control it from a bash script or windows batch file and possibly even query the emails from my unit/functional tests.</p>
6,344,240
3
3
null
2011-04-27 22:32:12.46 UTC
21
2021-01-16 13:23:16.993 UTC
2011-04-29 07:54:53.987 UTC
null
326,389
null
326,389
null
1
42
scripting|smtp|batch-file|email
20,881
<p>there is a nice trick with python: <a href="http://muffinresearch.co.uk/archives/2010/10/15/fake-smtp-server-with-python/" rel="noreferrer">http://muffinresearch.co.uk/archives/2010/10/15/fake-smtp-server-with-python/</a></p> <p>Just one liner can do the job (listens on port <code>2500</code>):</p> <pre><code>python -m smtpd -n -c DebuggingServer localhost:2500 </code></pre>
5,864,160
Code to loop through all records in MS Access
<p>I need a code to loop through all the records in a table so I can extract some data. In addition to this, is it also possible to loop through filtered records and, again, extract data? Thanks!</p>
5,869,361
3
0
null
2011-05-03 01:27:06.61 UTC
20
2018-08-31 11:05:47.42 UTC
null
null
null
null
724,575
null
1
46
ms-access|vba
357,753
<p>You should be able to do this with a pretty standard DAO recordset loop. You can see some examples at the following links:<br> <a href="http://msdn.microsoft.com/en-us/library/bb243789%28v=office.12%29.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/bb243789%28v=office.12%29.aspx</a><br> <a href="http://www.granite.ab.ca/access/email/recordsetloop.htm" rel="noreferrer">http://www.granite.ab.ca/access/email/recordsetloop.htm</a> </p> <p>My own standard loop looks something like this:</p> <pre><code>Dim rs As DAO.Recordset Set rs = CurrentDb.OpenRecordset("SELECT * FROM Contacts") 'Check to see if the recordset actually contains rows If Not (rs.EOF And rs.BOF) Then rs.MoveFirst 'Unnecessary in this case, but still a good habit Do Until rs.EOF = True 'Perform an edit rs.Edit rs!VendorYN = True rs("VendorYN") = True 'The other way to refer to a field rs.Update 'Save contact name into a variable sContactName = rs!FirstName &amp; " " &amp; rs!LastName 'Move to the next record. Don't ever forget to do this. rs.MoveNext Loop Else MsgBox "There are no records in the recordset." End If MsgBox "Finished looping through records." rs.Close 'Close the recordset Set rs = Nothing 'Clean up </code></pre>
1,964,996
Specify input() type in Python?
<p>Is it possible to define input times, like time, date, currency or that should be verified manually? Like for example:</p> <pre><code>morning = input('Enter morning Time:') evening = input('Enter evening Time:') </code></pre> <p>.. I need (only) time here, how do I make sure that user enters input in xx:xx format where xx are integers only.</p>
1,964,998
2
0
null
2009-12-27 02:46:30.73 UTC
1
2018-08-16 17:22:28.247 UTC
2018-08-16 17:22:28.247 UTC
null
6,862,601
null
172,637
null
1
3
python|input|types
39,047
<p><a href="http://docs.python.org/library/functions.html#input" rel="noreferrer"><code>input</code></a> (in Python 2.any) will return the type of whatever expression the user types in. Better (in Python 2.any) is to use <a href="http://docs.python.org/library/functions.html#raw_input" rel="noreferrer"><code>raw_input</code></a>, which returns a string, and do the conversion yourself, catching the <code>TypeError</code> if the conversion fails.</p> <p>Python 3.any's <code>input</code> works like 2.any's <code>raw_input</code>, i.e., it returns a string.</p>
56,891,083
When moving a unique_ptr into a lambda, why is it not possible to call reset?
<p>When moving <code>std::unique_ptr</code> into the lambda, it is not possible to call <code>reset()</code> on it, because it seems to be const then:</p> <pre><code>error C2662: void std::unique_ptr&lt;int,std::default_delete&lt;_Ty&gt;&gt;::reset(int *) noexcept': cannot convert 'this' pointer from 'const std::unique_ptr&lt;int,std::default_delete&lt;_Ty&gt;&gt;' to 'std::unique_ptr&lt;int,std::default_delete&lt;_Ty&gt;&gt; &amp; </code></pre> <pre><code>#include &lt;memory&gt; int main() { auto u = std::unique_ptr&lt;int&gt;(); auto l = [v = std::move(u)]{ v.reset(); // this doesn't compile }; } </code></pre> <ol> <li>Why does this happen?</li> <li>Is it possible to capture the <code>std::unique_ptr</code> in another way which allows calling <code>reset()</code> within the lambda (with C++17 or later)?</li> </ol>
56,891,115
4
2
null
2019-07-04 15:37:24.13 UTC
1
2019-07-05 23:50:13.947 UTC
2019-07-05 23:50:13.947 UTC
null
963,864
null
4,566,599
null
1
35
c++|c++11|lambda|unique-ptr|capture-list
2,893
<blockquote> <ol> <li>Why does this happen?</li> </ol> </blockquote> <p>Because the function-call operator of a <a href="https://en.cppreference.com/w/cpp/language/lambda" rel="noreferrer">lambda</a>,</p> <blockquote> <p>Unless the keyword <code>mutable</code> was used in the lambda-expression, the function-call operator is const-qualified and the objects that were captured by copy are non-modifiable from inside this <code>operator()</code>. </p> </blockquote> <p>and</p> <blockquote> <ol start="2"> <li>Is it possible to capture the <code>std::unique_ptr</code> in another way which allows to call <code>reset()</code> within the lambda</li> </ol> </blockquote> <p>You need to mark it <code>mutable</code>.</p> <blockquote> <p>mutable: allows body to modify the parameters captured by copy, and to call their non-const member functions</p> </blockquote> <p>e.g.</p> <pre><code>auto l = [v = std::move(u)]() mutable { v.reset(); }; </code></pre>
5,674,333
How to enable/disable WiFi from an application?
<p>I want to enable/disable wifi from my Android application. How can I do that?</p>
5,674,562
6
0
null
2011-04-15 08:44:49.823 UTC
13
2021-12-24 10:01:50.283 UTC
2021-12-24 10:01:50.283 UTC
null
1,731,626
null
587,674
null
1
33
java|android|kotlin|wifi|android-wifi
52,972
<pre><code>WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE); wifi.setWifiEnabled(false); // true or false to activate/deactivate wifi </code></pre> <p>You also need to request the permission in your AndroidManifest.xml :</p> <pre><code>&lt;uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /&gt; </code></pre>
5,836,881
stateless protocol and stateful protocol
<p>How to understand stateless protocol and stateful protocol? HTTP is a stateless protocol and FTP is a stateful protocol. For the web applications requiring a lot of interactions, the underlying protocol should be stateful ones. Is my understanding right? </p>
5,836,990
7
0
null
2011-04-29 20:09:20.077 UTC
21
2020-02-27 05:51:47.76 UTC
null
null
null
null
288,609
null
1
41
http|networking|network-protocols
64,802
<p>Since you're asking about a Web application, the protocol will always be stateless -- the protocol for the Web is http (or https), and that's all she wrote.</p> <p>I think what you're thinking of is providing a state mechanism in your Web application itself. The typical approach to this is that you create a unique identifier for the user's session in your Web application (a sessionID of one form or another is the common practice) which is handed back and forth between browser and server. That's typically done in a cookie, though it can be done, with a bit more hassle for you depending on your platform/framework, on the URL as well.</p> <p>Your server-side code stores stateful information (again, typically called the user's session) however it wants to using the sessionID to look it up. The http traffic simply hands back the sessionID. As long as that identifier is there, each http transaction is completely independent of all others, hence the protocol traffic itself is stateless.</p>
5,930,300
How to find the sum of all the multiples of 3 or 5 below 1000 in Python?
<p>Not sure if I should've posted this on math.stackexchange instead, but it includes more programming so I posted it here.</p> <p>The question seems really simple, but I've sat here for at least one hour now not figuring it out. I've tried different solutions, and read math formulas for it etc but it won't gives me the right answer when coding it! I made two different solutions for it, which both gives me the wrong answer. The first solution gives me 265334 while the second one gives me 232169. The answer is 233168, so the second solution is closer.</p> <p>I should mention this is a question from <a href="http://projecteuler.net/index.php?section=problems&amp;id=1" rel="noreferrer">Project Euler, the first one</a> to be precise.</p> <p>Here's my code. Any ideas what's wrong?</p> <pre><code>nums = [3, 5] max = 999 result = 0 for num in nums: for i in range(1,max): if num*i &lt; max: result += num*i print result result = 0 for i in range(0,max): if i%3 == 0 or i%5 == 0: result += i print result </code></pre>
5,930,337
19
6
null
2011-05-08 20:51:26.617 UTC
6
2021-04-26 15:02:47.023 UTC
2018-01-09 16:00:25.78 UTC
null
55,075
null
729,313
null
1
12
python|algorithm
74,302
<p><code>range(k,max)</code> does not include <code>max</code>, so you're really checking up to and including 998 (while 999 is a multiple of 3). Use <code>range(1,1000)</code> instead.</p>
39,023,360
Git squash commits in the middle of a branch
<p>I want to squash several commits together in the middle of a branch without modifying the commits before and after.</p> <p>I have :</p> <pre><code>A -- B -- C -- D -- E -- F -- G | | master dev origin/master </code></pre> <p>I want to squash that into</p> <pre><code>A -- H -- E -- F -- G | | master dev origin/master </code></pre> <p>Where <code>H</code> is equivalent to <code>B -- C -- D</code>. And I want to be able to specify the commit message of <code>H</code>. <code>A</code> is the last commit that has been pushed so all commits after that can be rewritten without messing up the server. The idea is to clean up the history before I fast forward <code>master</code>.</p> <p>How can I do that ?</p> <p>PS: Note that in my case I actually have a lot more than 3 commits to squash in the middle, but if I can do it with 3, I should be able to do it with more.</p> <p>PPS: Also, if possible, I would prefer a solution where <code>E</code>, <code>F</code> and <code>G</code> remain untouched (mostly regarding the commit date).</p>
39,023,568
1
1
null
2016-08-18 16:35:19.633 UTC
12
2016-08-18 17:31:37.257 UTC
2016-08-18 16:42:49.39 UTC
null
4,062,250
null
4,062,250
null
1
47
git|git-squash
14,218
<p>You can do an interactive rebase and hand select the commits which you want to squash. This will rewrite the history of your <code>dev</code> branch, but since you have not pushed these commits, there should not be any negative aftermath from this besides what might happen on your own computer.</p> <p>Start with the following:</p> <pre><code>git checkout dev git rebase -i HEAD~6 </code></pre> <p>This should bring up a window showing you the following list of 7 commits, going back 6 steps from the HEAD of your <code>dev</code> branch:</p> <pre><code>pick 07c5abd message for commit A pick dl398cn message for commit B pick 93nmcdu message for commit C pick lst28e4 message for commit D pick 398nmol message for commit E pick 9kml38d message for commit F pick 02jmdmp message for commit G </code></pre> <p>The first commit shown (<code>A</code> above) is the <em>oldest</em> and the last is the most recent. You can see that by default, the option for each commit is <code>pick</code>. If you finished the rebase now, you would just be retaining each commit as it is, which is effectively a no-op. But since you want to squash certain middle commits, edit and change the list to this:</p> <pre><code>pick 07c5abd message for commit A pick dl398cn new commit message for "H" goes here squash 93nmcdu message for commit C squash lst28e4 message for commit D pick 398nmol message for commit E pick 9kml38d message for commit F pick 02jmdmp message for commit G </code></pre> <p>Note carefully what is happening above. By typing <code>squash</code> you are telling Git to merge that commit into the one <em>above</em> it, which is the commit which came immediately <em>before</em> it. So this says to squash commit <code>D</code> backwards into commit <code>C</code>, and then to squash <code>C</code> into <code>B</code>, leaving you with just one commit for commits <code>B</code>, <code>C</code>, and <code>D</code>. The other commits remain as is.</p> <p>Save the file (<kbd>: wq</kbd> on Git Bash in Windows), and the rebase is complete. Keep in mind you can get merge conflicts from this as you might expect, but there is nothing special about resolving them and you can carry on as you would with any regular rebase or merge.</p> <p>If you inspect the branch after the rebase, you will notice that the <code>E</code>, <code>F</code>, and <code>G</code> commits now have new hashes, dates, etc. This is because these commits have actually been replaced by new commits. The reason for this is that you rewrote history, and therefore the commits in general can no longer be the same as they were previously.</p>
43,970,866
How to change language default in Firebase console web?
<p>I'm trying to change the language from French to English but I don't see what I need! Who can tell me how? Really need a link. Please help me, thanks! "<a href="https://console.firebase.google.com/" rel="noreferrer">https://console.firebase.google.com/</a>"</p>
43,976,071
4
0
null
2017-05-15 02:42:10.6 UTC
6
2019-12-16 15:35:29.763 UTC
2019-12-16 15:35:29.763 UTC
null
3,572,546
null
6,496,843
null
1
58
firebase
49,595
<p>You need to change your google account settings from French to English.</p> <p>If you don't want to change it just add URL parameter as <code>?hl=en</code> <a href="https://console.firebase.google.com/?hl=en" rel="noreferrer">https://console.firebase.google.com/?hl=en</a></p>
25,041,325
AngularJS ui-router : Could not resolve___ from state ___ Error
<p>I am following along on this year old ui-router tutorial <a href="http://txt.fliglio.com/2013/05/angularjs-state-management-with-ui-router/" rel="noreferrer">http://txt.fliglio.com/2013/05/angularjs-state-management-with-ui-router/</a> and I'm getting the following error:</p> <pre><code>Error: Could not resolve 'settings/quotes' from state 'settings' </code></pre> <p><img src="https://i.stack.imgur.com/LpbXU.png" alt="enter image description here"></p> <p>I am fitting this tutorial app into my Express.JS setup and I'm using Jade for my templates. </p> <p>All the Jade templates seem to be rendering properly but I am noticing that there is no <code>href</code> being created for the <strong>User Quotes</strong> (<code>settings/quotes</code> URL) <code>ui-sref</code> link. Maybe there is a clue there. You can see this in the below screenshot:</p> <p><img src="https://i.stack.imgur.com/wTQLC.png" alt="enter image description here"></p> <p>I will post all key files below. </p> <hr> <h2>AngularJS Files</h2> <p><strong>app.js</strong></p> <pre><code>'use strict'; var app = angular.module('app', ['ui.router']); app.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) { $urlRouterProvider.otherwise('/'); var settings = { name: 'settings', url: '/settings', abstract: true, templateUrl: '/partials/settings', controller: 'SettingsController' }; var details = { name: 'settings.details', parent: settings, url: '', templateUrl: '/partials/settings-details' }; var quotes = { name: 'settings.quotes', parent: settings, url: '/quotes', templateUrl: '/partials/settings-quotes' }; $stateProvider .state(settings) .state(details) .state(quotes); }]) .controller('SettingsController', ['$scope', function($scope) { $scope.user = { name: "Bob Loblaw", email: "[email protected]", password: "semi secret", quotes: "I am making it happen now!" }; }]); </code></pre> <h2>Jade Templates</h2> <p><strong>layout.jade</strong></p> <pre><code>doctype html html include head body(ng-app='app') p From the layout.jade file &lt;div ui-view&gt;&lt;/div&gt; include scripts </code></pre> <p><strong>settings.jade</strong></p> <pre><code>ul li Settings li a(ui-sref="settings") User Details li a(ui-sref="settings/quotes") User Quotes div(ui-view="") </code></pre> <p><strong>settings-details.jade</strong></p> <pre><code>h3 {{user.name}}\'s Quotes hr div label Quotes textarea(type="text", ng-model="user.quotes") button(ng-click="done()") Save </code></pre> <p><strong>settings-quotes.jade</strong></p> <pre><code>h3 {{user.name}}\'s Details hr div label Name input(type="text", ng-model="user.name") div label Email input(type="text", ng-model="user.email") button(ng-click="done()") Save </code></pre> <h2>ExpressJS Server</h2> <p><strong>server.js</strong></p> <pre><code>var express = require('express'), mongoose = require('mongoose'), morgan = require('morgan'), bodyParser = require('body-parser'), path = require('path'); </code></pre> <p>var env = process.env.NODE_ENV = process.env.NODE_ENV || 'development';</p> <p>var app = express();</p> <pre><code>// configuration app.set('views', path.join(__dirname, '/app/views')); app.set('view engine', 'jade'); app.use(morgan('dev')); // logs every request to console app.use(bodyParser()); // pull information from html in POST app.use(express.static(__dirname + '/public')); // connect to mongodb via mongoose if(env === 'development') { mongoose.connect('mongodb://localhost/3lf'); } else { mongoose.connect('mongodb://maxmythic:[email protected]:33307/3lf'); } var db = mongoose.connection; db.on('error', console.error.bind(console, 'connection error ...')); db.once('open', function(callback) { console.log('3lf db is open for business ...'); }); // create mongoose schema and retrieve data var messageSchema = mongoose.Schema({message: String}); var Message = mongoose.model('Message', messageSchema); var mongoMessage; Message.findOne().exec(function(err, messageDoc){ mongoMessage = messageDoc.message; }); // define routes // make sure to coordinate client side and server side routes app.get('/partials/:partialPath', function(req, res) { res.render('partials/' + req.params.partialPath); }); app.get('*', function(req, res) { res.render('index', { mongoMessage: mongoMessage }); }); var port = process.env.PORT || 3030; app.listen(port); console.log('Listening on port ' + port + '...'); </code></pre>
25,041,362
1
2
null
2014-07-30 15:50:59 UTC
4
2014-07-30 15:59:18.237 UTC
null
null
null
user883807
null
null
1
26
angularjs|pug|angular-ui-router|mean-stack
49,973
<p>You are almost there, ui-router needs this:</p> <pre><code>&lt;a ui-sref="settings.details"&gt;... </code></pre> <p>this says <code>ui-sref</code> navigate to state named <code>'settings.details'</code>, in case we would need to pass params, it is very similar like $state.go...</p> <pre><code>&lt;a ui-sref="settings.details({param1:value1, param2:value2})"&gt;... </code></pre> <p>if we want to use url defined for states, we still can, but we must use href</p> <pre><code>&lt;a href="#/settings"&gt;...to get to details &lt;a href="#/settings/quotes"&gt;...to get to quotes </code></pre> <p>if the child url is empty string like in our case</p> <pre><code> var settings = { name: 'settings', url: '/settings', abstract: true, ... }; var details = { name: 'settings.details', parent: settings, url: '', ... }; var quotes = { name: 'settings.quotes', parent: settings, url: '/quotes', ... }; </code></pre> <p>See documentation: </p> <h3><a href="https://github.com/angular-ui/ui-router/wiki/Quick-Reference#ui-sref">ui-sref</a></h3> <p>or <a href="http://angular-ui.github.io/ui-router/site/#/api/ui.router.state.directive:ui-sref">new doc</a> <em>(cite)</em></p> <blockquote> <p><code>ui-sref='stateName'</code> - Navigate to state, no params. <code>'stateName'</code> can be any valid absolute or relative state, following the same syntax rules as $state.go() </p> </blockquote>