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
5,268,041
Xcode 4 Instruments doesn't show source lines
<p>I've just started playing with Xcode 4, and found that, no matter how I setup debugging symbols in the project, Instruments refuses to display source lines for stack trace items that correspond to my code. In only shows hex offsets and identifies my executable as the owning module. Turning on "Source Location" draws a blank too. This occurs even for the skeleton OpenGL ES project generated by Xcode (File &rarr; New &rarr; New Project... &rarr; iOS &rarr; Application &rarr; OpenGL ES Application).</p> <p>This problem only occurs in Instruments (I've tried CPU and OpenGL tracing so far). Gdb picks up debug symbols just fine.</p> <p>Do I have to do something special to see the source code for stack traces in Instruments, or is this a bug in Xcode 4?</p> <p>So far, I've:</p> <ul> <li>Changed <code>Debug Information Format</code> from <code>DWARF with dSYM File</code> to <code>DWARF</code>.</li> <li>Changed <code>Strip Debug Symbols During Copy</code> from <code>Yes</code> to <code>No</code>.</li> <li>Changed the build scheme to use the Debug build instead of the Release build with Instruments.</li> </ul>
8,702,682
8
0
null
2011-03-11 01:34:02.667 UTC
15
2017-05-18 20:46:02.15 UTC
2011-03-11 01:49:50.55 UTC
null
9,990
null
9,990
null
1
28
xcode|debug-symbols|xcode-instruments
18,784
<p>The other answers are good long-term fixes. If you'd rather not wait for Spotlight to rebuild its index and just need to get symbols for one Instruments session, you can ask Instruments to symbolicate the current session.</p> <ol> <li>Choose File → Re-Symbolicate Document… <img src="https://i.stack.imgur.com/hkvDL.png" alt="screenshot of re-symbolicate menu item"></li> <li>Locate your binary in the list that appears. It should be the same name you see on the Springboard. Select your binary and click "Locate." <img src="https://i.stack.imgur.com/V8t1y.png" alt="enter image description here"></li> <li>Go back to Xcode. Control-click on your .app build product and choose "Show in Finder".<img src="https://i.stack.imgur.com/GpBWF.png" alt="right-click menu screenshot showing show in finder item"></li> <li>This will reveal the directory containing your binary as well as its <code>dSYM</code> file. Go back to Instruments, navigate to this directory, and select your <code>dSYM</code> file. The easiest way is to just drag the <code>dSYM</code> file straight from the Finder to the "Select dSYM" dialog in Instruments.</li> <li>Finally, click "Symbolicate" in Instruments. You should now see symbols in the traces rather than hex offsets.</li> </ol>
5,588,855
Standard alternative to GCC's ##__VA_ARGS__ trick?
<p>There is a <a href="https://stackoverflow.com/questions/4054085/gcc-appending-to-va-args">well-known</a> <a href="http://gcc.gnu.org/onlinedocs/cpp/Variadic-Macros.html" rel="noreferrer">problem</a> with empty args for variadic macros in C99.</p> <p>example:</p> <pre><code>#define FOO(...) printf(__VA_ARGS__) #define BAR(fmt, ...) printf(fmt, __VA_ARGS__) FOO("this works fine"); BAR("this breaks!"); </code></pre> <p>The use of <code>BAR()</code> above is indeed incorrect according to the C99 standard, since it will expand to:</p> <pre><code>printf("this breaks!",); </code></pre> <p>Note the trailing comma - not workable.</p> <p>Some compilers (eg: Visual Studio 2010) will quietly get rid of that trailing comma for you. Other compilers (eg: GCC) support putting <code>##</code> in front of <code>__VA_ARGS__</code>, like so:</p> <pre><code>#define BAR(fmt, ...) printf(fmt, ##__VA_ARGS__) </code></pre> <p>But is there a standards-compliant way to get this behavior? Perhaps using multiple macros?</p> <p>Right now, the <code>##</code> version seems fairly well-supported (at least on my platforms), but I'd really rather use a standards-compliant solution.</p> <p>Pre-emptive: I know I could just write a small function. I'm trying to do this using macros.</p> <p><strong>Edit</strong>: Here is an example (though simple) of why I would want to use BAR():</p> <pre><code>#define BAR(fmt, ...) printf(fmt "\n", ##__VA_ARGS__) BAR("here is a log message"); BAR("here is a log message with a param: %d", 42); </code></pre> <p>This automatically adds a newline to my BAR() logging statements, assuming <code>fmt</code> is always a double-quoted C-string. It does NOT print the newline as a separate printf(), which is advantageous if the logging is line-buffered and coming from multiple sources asynchronously.</p>
5,589,364
12
7
null
2011-04-07 23:39:28.717 UTC
73
2022-02-26 21:33:11.227 UTC
2017-05-23 11:47:15.357 UTC
null
-1
null
567,650
null
1
163
c|c99|c-preprocessor|variadic-macros
91,891
<p>It is possible to avoid the use of GCC's <code>,##__VA_ARGS__</code> extension if you are willing to accept some hardcoded upper limit on the number of arguments you can pass to your variadic macro, as described in <a href="https://stackoverflow.com/a/11172679/388520">Richard Hansen's answer to this question</a>. If you do not want to have any such limit, however, to the best of my knowledge it is not possible using only C99-specified preprocessor features; you must use some extension to the language. clang and icc have adopted this GCC extension, but MSVC has not. </p> <p>Back in 2001 I wrote up the GCC extension for standardization (and the related extension that lets you use a name other than <code>__VA_ARGS__</code> for the rest-parameter) in <a href="http://www.open-std.org/jtc1/sc22/wg14/www/docs/n976.htm" rel="noreferrer">document N976</a>, but that received no response whatsoever from the committee; I don't even know if anyone read it. In 2016 it was proposed again in <a href="http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2023.pdf" rel="noreferrer">N2023</a>, and I encourage anyone who knows how that proposal is going to let us know in the comments.</p>
5,330,277
What are examples of TCP and UDP in real life?
<p>I know the difference between the two on a technical level.</p> <p>But in real life, can anyone provide examples (the more the better) of applications (uses) of TCP and UDP to demonstrate the difference?</p>
5,330,367
17
0
null
2011-03-16 18:52:19.98 UTC
42
2019-11-28 06:59:50.87 UTC
2014-03-10 11:29:45.91 UTC
null
87,861
null
594,026
null
1
85
tcp|udp
310,698
<p>UDP: Anything where you don't care too much if you get all data always</p> <ul> <li>Tunneling/VPN (lost packets are ok - the tunneled protocol takes care of it)</li> <li>Media streaming (lost frames are ok)</li> <li>Games that don't care if you get <em>every</em> update</li> <li>Local broadcast mechanisms (same application running on different machines "discovering" each other)</li> </ul> <p>TCP: Almost anything where you have to get all transmitted data</p> <ul> <li>Web </li> <li>SSH, FTP, telnet</li> <li>SMTP, sending mail</li> <li>IMAP/POP, receiving mail</li> </ul> <p>EDIT: I'm not going to bother explaining the differences, since you state that you already know and every other answer explains it anyway :)</p>
12,118,866
How do I create an F# Type Provider that can be used from C#?
<p>If I use the F# Type Providers from the assembly FSharp.Data.TypeProviders 4.3.0.0, I am able to create types in a very simple F# library. I am then able to use those types without any dependency on the assembly FSharp.Data.TypeProviders. That is pretty sweet! Here is an example:</p> <p>I created an F# library project called TryTypeProviders. I put this in the .fs:</p> <pre><code>module TryTypeProviders type Northwind = Microsoft.FSharp.Data.TypeProviders.ODataService</code></pre> <p>I then am able to use the F# library from a C# project:</p> <pre><code>public static void Main() { var c = new TryTypeProviders.Northwind(); foreach (var cust in c.Customers) Console.WriteLine("Customer is: " + cust.ContactName); Console.ReadKey(true); }</code></pre> <p>I haven't been able to find any working examples of how to create a type provider like this. The type providers in FSharpx.TypeProviders are not accessible from C#. My guess is that they are erased types and not generated types. I'm still a little fuzzy on which is which, but it is <a href="https://stackoverflow.com/questions/7458028/f-type-provider-only-return-generated-types">defined here as</a>: </p> <ol> <li>Generated types are real .NET types that get embedded into the assembly that uses the type provider (this is what the type providers that wrap code generation tools like sqlmetal use) </li> <li>Erased types are simulated types which are represented by some other type when the code is compiled.</li> </ol> <p>The samples from the <a href="http://fsharp3sample.codeplex.com/" rel="nofollow noreferrer">F# 3.0 Sample Pack</a> mentioned in the MSDN <a href="http://msdn.microsoft.com/en-us/library/hh361034" rel="nofollow noreferrer">tutorial</a> are not working for me. They build, but when I try to use them I get errors.</p> <pre><code>open Samples.FSharp.RegexTypeProvider<br/>type PhoneNumberRegEx = CheckedRegexProvider&lt; @&quot;(?&lt;AreaCode&gt;^\d{3})-(?&lt;PhoneNumber&gt;\d{3}-\d{4}$)&quot;&gt;</code></pre> <pre><code>open Samples.FSharp.MiniCsvProvider<br/>type csv = MiniCsvProvider&lt;&quot;a.csv&quot;&gt;</code></pre> <p>It was last released in March of 2011 and my guess is that they don't yet reflect the final version of type providers that shipped with Visual Studio 2012. </p> <p>F# Type Providers look like a great technology, but we need help building them. Any help is appreciated.</p>
12,118,966
1
0
null
2012-08-25 03:14:47.853 UTC
9
2012-08-25 20:46:26.107 UTC
2017-05-23 12:26:15.053 UTC
null
-1
null
23,059
null
1
28
f#|type-providers
4,293
<p>The reason why standard type providers (for OData, LINQ to SQL and WSDL) work with C# is that they generate real .NET types behind the cover. This is called <strong>generative type provider</strong>. In fact, they simply call the code generation tool that would be called if you were using these technologies from C# in a standard way. So, these type providers are just wrappers over some standard .NET tools.</p> <p>Most of the providers that are newly written are written as <strong>erasing type providers</strong>. This means that they only generate "fake" types that tell the F# compiler what members can be called (etc.) but when the compiler compiles them, the "fake" types are replaced with some other code. This is the reason why you cannot see any types when you're using the library from C# - none of the types actually exist in the compiled code.</p> <p>Unless you're wrapping existing code-generator, it is easier to write <em>erased type provider</em> and so most of the examples are written in this way. Erasing type providers have other beneftis - i.e. they can generate huge number of "fake" types without generating excessively big assemblies.</p> <p>Anyway, there is a brief note <a href="http://msdn.microsoft.com/en-us/library/hh361034" rel="noreferrer">"Providing Generated Types" in the MSDN tutorial</a>, which has some hints on writing generative providers. However, I'd expect most of the new F# type providers to be written as erasing. It notes that you must have a real .NET assembly (with the generated types) and getting that is not simplified by the F# helpers for building type providers - so you'll need to emit the IL for the assembly or generate C#/F# code and compile that (i.e. using CodeDOM or Roslyn).</p>
12,091,971
How to start and end transaction in mysqli?
<p>As far as I understood transaction starts once we call <code>$mysqli-&gt;autocommit(FALSE);</code> statement and ends after calling <code>$mysqli-&gt;commit();</code> command like in the example below.</p> <pre><code>&lt;?php //Start transaction $mysqli-&gt;autocommit(FALSE); $mysqli-&gt;query('UPDATE `table` SET `col`=2'); $mysqli-&gt;query('UPDATE `table1` SET `col1`=3;'); $mysqli-&gt;commit(); //End transaction //Executing other queries without transaction control $mysqli-&gt;query("Select * from table1"); $mysqli-&gt;query("Update table1 set col1=2"); //End of executing other queries without transaction control //Start transaction $mysqli-&gt;autocommit(FALSE); $mysqli-&gt;query('UPDATE `table` SET `col`=2'); $mysqli-&gt;query('UPDATE `table1` SET `col1`=3;'); $mysqli-&gt;commit(); //End transaction ?&gt; </code></pre> <p>Have I understood correctly? If not could you please correct me, because it is actually my first time using transactions in real life.</p> <p>Thank you.</p>
12,092,151
5
0
null
2012-08-23 12:48:55.743 UTC
23
2021-11-29 15:45:18.773 UTC
2018-03-25 17:50:04.32 UTC
null
3,536,236
null
282,887
null
1
44
php|transactions|mysqli
61,943
<p><strong>Update Novembre 2020</strong>: <a href="https://stackoverflow.com/users/1839439/dharman">@Dharman</a> gave a better answer with more details about transactions in mysqli, just check it instead: <a href="https://stackoverflow.com/a/63764001/569101">https://stackoverflow.com/a/63764001/569101</a> </p> <hr /> <p>Well according to <a href="http://www.php.net/manual/en/mysqli.commit.php" rel="nofollow noreferrer">the php doc</a>, you're right.</p> <pre><code>&lt;?php $mysqli = new mysqli(&quot;localhost&quot;, &quot;my_user&quot;, &quot;my_password&quot;, &quot;world&quot;); /* check connection */ if (mysqli_connect_errno()) { printf(&quot;Connect failed: %s\n&quot;, mysqli_connect_error()); exit(); } $mysqli-&gt;query(&quot;CREATE TABLE Language LIKE CountryLanguage&quot;); /* set autocommit to off */ $mysqli-&gt;autocommit(FALSE); /* Insert some values */ $mysqli-&gt;query(&quot;INSERT INTO Language VALUES ('DEU', 'Bavarian', 'F', 11.2)&quot;); $mysqli-&gt;query(&quot;INSERT INTO Language VALUES ('DEU', 'Swabian', 'F', 9.4)&quot;); /* commit transaction */ $mysqli-&gt;commit(); /* drop table */ $mysqli-&gt;query(&quot;DROP TABLE Language&quot;); /* close connection */ $mysqli-&gt;close(); ?&gt; </code></pre> <p>In the example above:</p> <ul> <li>the <code>CREATE TABLE</code> is auto committed because it's the default behaviour.</li> <li>the <code>INSERT INTO</code> <strong>aren't</strong> auto committed because of the <code>autocommit(FALSE)</code>.</li> <li>the <code>DROP TABLE</code> is auto committed because the <code>autocommit(FALSE)</code> was <em>reset</em> by the <code>-&gt;commit();</code>.</li> </ul>
12,483,720
adb - How to reinstall an app, without retaining the data?
<pre><code>adb install foo.apk </code></pre> <p>When using this command, if the apk exists, I should get the error *Failure [INSTALL_FAILED_ALREADY_EXISTS]*</p> <pre><code> adb install -r myapp-release.apk </code></pre> <p>In this case,the existing apk will be replaced, by retaining old data according to the docs, </p> <blockquote> <p>'-r' means reinstall the app, keeping its data</p> </blockquote> <p>Now how do I reinstall the app, but all previous data should be erased?</p> <p><strong>EDIT</strong></p> <p>I know we can do this</p> <pre><code>adb uninstall com.package.foo &amp; adb install foo.apk </code></pre> <p>I just wanted to know if there is a command or something in adb itself.</p>
17,341,882
5
1
null
2012-09-18 19:31:37.687 UTC
15
2018-11-02 07:00:14.027 UTC
2012-09-18 19:38:45.643 UTC
null
1,137,788
null
1,137,788
null
1
50
android|apk|adb|command-prompt
68,221
<p>Before the installation <strong>clean the data</strong> like this:</p> <pre><code>adb shell pm clear com.package.foo </code></pre> <p>then you can install normally using:</p> <pre><code>adb install foo.apk </code></pre> <p>or just run through your IDE</p>
12,100,634
Changing default syntax based on filename
<p>In Sublime Text 2, I've seen ways of basing the syntax off of the extension. But what about a filename with no extension? For example, I often have a file called "Vagrantfile" which is in ruby, yet Sublime Text 2 always wants to start off in plain text. Is there a way to have it default to "ruby" for a file if it is called "Vagrantfile"?</p>
12,240,279
2
0
null
2012-08-23 22:02:07.737 UTC
11
2014-07-01 05:46:16.263 UTC
null
null
null
null
299,216
null
1
50
sublimetext2
5,268
<p>With Sublime Text 2.0.1, build 2217, look in the lower right of the window, where it says "Plain Text" for the Vagrantfile that is open. </p> <p><img src="https://i.stack.imgur.com/T3wT3.png" alt="enter image description here"></p> <p>Click that and in the menu that opens, at the top, there will be an "Open all with current extension as ..." sub-menu. Go into that sub-menu and choose Ruby.</p> <p>Even though the Vagrantfile has no extension, Sublime will remember this and open Vagrantfiles with the Ruby syntax as expected. This does not spread to all files with no extension.</p>
19,065,666
How to include system dependencies in war built using maven
<p>I've searched on internet for quite some time and I'm unable to figure out how to configure the maven-war plugin or something alike so that the system dependencies are included in the built-war (WEB-INF/lib folder)</p> <p>I use the maven dependency plugin in case of a jar-build as : </p> <pre><code>&lt;plugin&gt; &lt;artifactId&gt;maven-dependency-plugin&lt;/artifactId&gt; &lt;executions&gt; &lt;execution&gt; &lt;phase&gt;install&lt;/phase&gt; &lt;goals&gt; &lt;goal&gt;copy-dependencies&lt;/goal&gt; &lt;/goals&gt; &lt;configuration&gt; &lt;outputDirectory&gt;${project.build.directory}/lib&lt;/outputDirectory&gt; &lt;/configuration&gt; &lt;/execution&gt; &lt;/executions&gt; &lt;/plugin&gt; </code></pre> <p>but I'm unable to understand what is to be done in case of a war build. I've tried using the maven-war plugin, but it's not including system-dependencies in the build.</p> <p>[UPDATE]</p> <p>I'm having depedencies of type : </p> <pre><code>&lt;dependency&gt; &lt;groupId&gt;LoginRadius&lt;/groupId&gt; &lt;artifactId&gt;LoginRadius&lt;/artifactId&gt; &lt;scope&gt;system&lt;/scope&gt; &lt;version&gt;1.0&lt;/version&gt; &lt;systemPath&gt;${basedir}\lib\LoginRadius-1.0.jar&lt;/systemPath&gt; &lt;/dependency&gt; </code></pre> <p>in my POM and these dependencies are not included in WEB-INF/lib when the war is build.</p>
19,066,828
7
4
null
2013-09-28 10:00:10.73 UTC
14
2019-06-05 14:50:21.183 UTC
2016-03-04 11:33:02.193 UTC
null
694,325
null
566,092
null
1
43
java|eclipse|maven
68,339
<p>Let me try to summarise the options I tried : </p> <pre><code>&lt;packagingIncludes&gt;${java.home}/lib/jfxrt.jar&lt;/packagingIncludes&gt; </code></pre> <p>This doesn't work! Also, only having the jar name, excludes everything else, so if you are willing to try then try </p> <pre><code>&lt;packagingIncludes&gt;${java.home}/lib/jfxrt.jar,**/*&lt;/packagingIncludes&gt; </code></pre> <p>Jatin's answer seemed a bit complex and I tried going through the POM again &amp; again to figure out where exactly were the system jars mentioned to be included in WEB-INF POM.</p> <p>Anyways, I ended up using this solution, which wasn't working at first but after some time and some corrections worked : </p> <p>I installed the jar in my local repository using the below command : </p> <pre><code>mvn install:install-file -Dfile="C:\Users\hp\Documents\NetBeansProjects\TwitterAndLoginRadiusMaven\lib\LoginRadius-1.0.jar" -DgroupId=LoginRadius -DartifactId=LoginRadius -Dversion=1.0 -Dpackaging=jar` </code></pre> <p>After running the above command, I changed the dependency in POM to</p> <pre><code>&lt;dependency&gt; &lt;groupId&gt;LoginRadius&lt;/groupId&gt; &lt;artifactId&gt;LoginRadius&lt;/artifactId&gt; &lt;!--&lt;scope&gt;system&lt;/scope&gt;--&gt; &lt;version&gt;1.0&lt;/version&gt; &lt;!--&lt;systemPath&gt;${basedir}\lib\LoginRadius-1.0.jar&lt;/systemPath&gt;--&gt; &lt;/dependency&gt; </code></pre> <p>NOTE - See I've commented the system scope &amp; systemPath. </p> <p>Building the war now, includes this LoginRadius-1.0.jar in WEB-INF/lib</p>
18,937,651
PHP session IDs -- how are they generated?
<p>When I call <code>session_start()</code> or <code>session_regenerate_id()</code>, PHP generates what appears to be a random string for the session ID. What I want to know is, is it just a random sequence of characters, or is it like the <code>uniqid()</code> function?</p> <p>Because if it's just random characters, couldn't you theoretically run into a conflict? If User A logged in and then User B logged in and, though highly unlikely, User B generated the same session ID, then User B would end up accessing User A's account.</p> <p>Even if PHP checks to see if a session with the same ID already exists and, if so, regenerates an ID again... I don't think I want a system that EVER produces the same ID twice, even after garbage collection -- maybe I want to store a table of them and check against them for possible hijacking or whatever.</p> <p>If it isn't unique, how should I go about enforcing uniqueness? I'd rather implement it using PHP configuration than in every script I make. Nice thing about PHP sessions is not worrying about the technical details behind the scenes.</p>
18,937,956
2
6
null
2013-09-21 21:08:57.45 UTC
11
2015-08-26 01:53:06.25 UTC
null
null
null
null
546,657
null
1
21
php|session|cookies|uniqueidentifier
35,658
<p>If you want to know how PHP generates a session ID by default check out the source code on <a href="https://github.com/php/php-src/blob/d9bfe06194ae8f760cb43a3e7120d0503f327398/ext/session/session.c#L284">Github</a>. <strong>It is certainly not random</strong> and is based on a hash (default: md5) of these ingredients (see line 310 of code snippet):</p> <ol> <li><strong>IP address</strong> of the client</li> <li><strong>Current time</strong></li> <li><strong>PHP Linear Congruence Generator</strong> - a pseudo random number generator (PRNG)</li> <li><strong>OS-specific random source</strong> - if the OS has a random source available (e.g. /dev/urandom)</li> </ol> <p>If the OS has a random source available then strength of the generated ID for the purpose of being a session ID is high (<em>/dev/urandom and other OS random sources are (usually) cryptographically secure PRNGs</em>). If however it does not then it is satisfactory. </p> <p>The goal with session identification generation is to: </p> <ol> <li><em>minimise the probability of generating two session IDs with the same value</em></li> <li><em>make it very challenging computationally to generate random keys and hit an in use one</em>. </li> </ol> <p>This is achieved by PHP's approach to session generation.</p> <p><strong>You cannot absolutely guarantee uniqueness</strong>, but the probabilities are so low of hitting the same hash twice that it is, generally speaking, not worth worrying about.</p>
22,542,882
SQL Error: ORA-01861: literal does not match format string 01861
<p>I am trying to insert data into an existing table and keep receiving an error.</p> <pre><code>INSERT INTO Patient ( PatientNo, PatientFirstName, PatientLastName, PatientStreetAddress, PatientTown, PatientCounty, PatientPostcode, DOB, Gender, PatientHomeTelephoneNumber, PatientMobileTelephoneNumber ) VALUES ( 121, 'Miles', 'Malone', '64 Zoo Lane', 'Clapham', 'United Kingdom', 'SW4 9LP', '1989-12-09', 'M', 02086950291, 07498635200 ); </code></pre> <p>Error:</p> <pre><code>Error starting at line : 1 in command - INSERT INTO Patient (PatientNo,PatientFirstName,PatientLastName,PatientStreetAddress,PatientTown,PatientCounty,PatientPostcode,DOB,Gender,PatientHomeTelephoneNumber,PatientMobileTelephoneNumber) VALUES (121, 'Miles', 'Malone', '64 Zoo Lane', 'Clapham', 'United Kingdom','SW4 9LP','1989-12-09','M',02086950291,07498635200) Error report - SQL Error: ORA-01861: literal does not match format string 01861. 00000 - "literal does not match format string" *Cause: Literals in the input must be the same length as literals in the format string (with the exception of leading whitespace). If the "FX" modifier has been toggled on, the literal must match exactly, with no extra whitespace. *Action: Correct the format string to match the literal. </code></pre> <p>Just not sure why this keeps happening I am learning SQL at the moment, any help will be greatly appreciated!</p>
22,543,299
7
4
null
2014-03-20 19:11:31.623 UTC
13
2020-12-17 14:16:17.837 UTC
2014-03-20 19:16:28.57 UTC
null
22,225
null
3,443,561
null
1
92
sql|oracle|sql-insert
538,110
<p>Try replacing the string literal for date <code>'1989-12-09'</code> with <code>TO_DATE('1989-12-09','YYYY-MM-DD')</code></p>
8,506,753
AutoReconnect exception "master has changed"
<p>Having some trouble understanding the right approach here.</p> <p>I have a connection to a mongodb replica set with three members (standard master-slave-slave). Everything is working fine with the connection when the master remains consistent.</p> <pre><code>pymongo.Connection(['host1:27017','host2:27018','host3:27019']).database_test </code></pre> <p>For some reason, when the replica set primary steps down, this starts to throw an autoreconnect exception that <strong>doesn't go away even after a new primary is elected.</strong></p> <p>Now I am aware that this exception needs to be caught and handled, most likely by waiting for the new primary to be elected. The problem I am having seems to be that it doesn't care at all once the new primary has been chosen. This "master has changed" exception just keeps coming up.</p> <p>Printing the connection with <code>__dict__</code> shows all three hosts.</p> <p>I've tried passing the <code>replicaset</code> kwarg to the connection, but this comes up as an unexpected argument. </p> <p>Is there a reason why this kind of connection wouldn't just start querying against the new primary?</p> <p><strong>EDIT:</strong></p> <p>This same problem is apparently now manifesting on the deployment server. The autoreconnect exception is thrown if the master changes at all and never goes away even after a new primary is elected.</p> <p>Pymongo is version 2.2 and mongodb version 2.0.2. Changing the manner in which the connection is defined in the pymongo code (mongouri vs. list of hosts) has no effect. The only way to revive the service is to <code>rs.stepDown()</code> the other hosts until the original master is primary once more.</p>
12,968,755
1
6
null
2011-12-14 15:07:58.56 UTC
1
2012-10-19 06:42:18.68 UTC
2012-06-18 12:48:01.063 UTC
null
1,288
null
215,608
null
1
38
mongodb|pymongo
2,102
<p>The behavior you describe is a bug. The best possible course of action is to make sure there is a bug logged for it and link to it from your question. Since the question is almost a year old, I am expecting the bug to be closed (check jira.mongodb.org/browse/SERVER-4405 to see if it applies).</p> <p>If you upgrade to MongoDB 2.2 or later, the problem should go away.</p>
20,694,062
Can a TCP c# client receive and send continuously/consecutively without sleep?
<p>This is to a degree a "basics of TCP" question, yet at the same time I have yet to find a convincing answer elsewhere and believe i have a ok/good understanding of the basics of TCP. I am not sure if the combination of questions (or the one questions and while i'm at it the request for confirmation of a couple of points) is against the rules. Hope not.</p> <p>I am trying to write a C# implementation of a TCP client, that communicates with an existing app containing a TCP server (I don't have access to its code, so no WCF). How do I connect to it, send and receive as needed as new info comes in or out, and ultimately disconnect. Using <a href="http://msdn.microsoft.com/en-us/library/bew39x2a%28v=vs.110%29.aspx" rel="noreferrer">the following MSDN code</a> as an example where they list "Send" and "Receive" asynchronous methods (or just TcpClient), and ignoring the connect and disconnect as trivial, how can I best go about continuously checking for new packets received and at the same time send when needed?</p> <p>I initially used TCPClient and GetStream(), and the msdn code still seems to require the loop and sleep described in a bit (counter intuitively), where I run the receive method in a loop in a separate thread with a sleep(10) milliseconds, and Send in the main (or third) thread as needed. This allows me to send fine, and the receive method effectively polls at regular intervals to find new packets. The received packets are then added to a queue.</p> <p><strong>Is this really the best solution? Shouldn't there be a DataAvailable event equivalent (or something i'm missing in the msdn code) that allows us to receive when, and only when, there is new data available?</strong> </p> <p>As an afterthought I noticed that the socket could be cut from the other side without the client becoming aware till the next botched send. To clarify then, the client is obliged to send regular keepalives (and receive isn't sufficient, only send) to determine if the socket is still alive. And the frequency of the keepalive determines how soon I will know that link is down. Is that correct? I tried Poll, socket.connected etc only to discover why each just doesn't help.</p> <p>Lastly, to confirm (i believe not but good to make sure), in the above scenario of sending on demand and receiving if tcpclient.DataAvailable every ten seconds, can there be data loss if sending and receiving at the same time? If at the same time I am receiving I try and send will one fail, overwrite the other or any other such unwanted behaviour?</p>
20,698,153
1
5
null
2013-12-20 00:05:18.01 UTC
36
2017-03-29 19:39:24.61 UTC
2014-12-17 13:32:48.2 UTC
null
1,480,391
null
459,109
null
1
39
c#|sockets|asynchronous|tcp
51,934
<p>There's nothing wrong necessarily with grouping questions together, but it does make answering the question more challenging... :)</p> <p>The MSDN article you linked shows how to do a one-and-done TCP communication, that is, one send and one receive. You'll also notice it uses the <a href="http://msdn.microsoft.com/en-us/library/system.net.sockets.socket%28v=vs.110%29.aspx" rel="noreferrer"><code>Socket</code></a> class directly where most people, including myself, will suggest using the <a href="http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient%28v=vs.110%29.aspx" rel="noreferrer"><code>TcpClient</code></a> class instead. You can always get the underlying <code>Socket</code> via the <a href="http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.client%28v=vs.110%29.aspx" rel="noreferrer"><code>Client</code></a> property should you need to configure a certain socket for example (e.g., <a href="http://msdn.microsoft.com/en-us/library/System.Net.Sockets.Socket.SetSocketOption%28v=vs.110%29.aspx" rel="noreferrer"><code>SetSocketOption()</code></a>).</p> <p>The other aspect about the example to note is that while it uses threads to execute the <a href="http://msdn.microsoft.com/en-us/library/system.asynccallback%28v=vs.110%29.aspx" rel="noreferrer"><code>AsyncCallback</code></a> delegates for both <a href="http://msdn.microsoft.com/en-us/library/7h44aee9%28v=vs.110%29.aspx" rel="noreferrer"><code>BeginSend()</code></a> and <a href="http://msdn.microsoft.com/en-us/library/dxkwh6zw%28v=vs.110%29.aspx" rel="noreferrer"><code>BeginReceive()</code></a>, it is essentially a single-threaded example because of how the <a href="http://msdn.microsoft.com/en-us/library/system.threading.manualresetevent%28v=vs.110%29.aspx" rel="noreferrer">ManualResetEvent</a> objects are used. For repeated exchange between a client and server, this is not what you want.</p> <p>Alright, so you want to use <code>TcpClient</code>. Connecting to the server (e.g., <a href="http://msdn.microsoft.com/en-us/library/system.net.sockets.tcplistener%28v=vs.110%29.aspx" rel="noreferrer"><code>TcpListener</code></a>) should be straightforward - use <a href="http://msdn.microsoft.com/en-us/library/System.Net.Sockets.TcpClient.Connect%28v=vs.110%29.aspx" rel="noreferrer"><code>Connect()</code></a> if you want a blocking operation or <a href="http://msdn.microsoft.com/en-us/library/System.Net.Sockets.TcpClient.BeginConnect%28v=vs.110%29.aspx" rel="noreferrer"><code>BeginConnect()</code></a> if you want a non-blocking operation. Once the connection is establish, use the <a href="http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.getstream%28v=vs.110%29.aspx" rel="noreferrer"><code>GetStream()</code></a> method to get the <a href="http://msdn.microsoft.com/en-us/library/system.net.sockets.networkstream%28v=vs.110%29.aspx" rel="noreferrer"><code>NetworkStream</code></a> object to use for reading and writing. Use the <a href="http://msdn.microsoft.com/en-us/library/system.net.sockets.networkstream.read%28v=vs.110%29.aspx" rel="noreferrer"><code>Read()</code></a>/<a href="http://msdn.microsoft.com/en-us/library/system.net.sockets.networkstream.write%28v=vs.110%29.aspx" rel="noreferrer"><code>Write()</code></a> operations for blocking I/O and the <a href="http://msdn.microsoft.com/en-us/library/system.net.sockets.networkstream.beginread%28v=vs.110%29.aspx" rel="noreferrer"><code>BeginRead()</code></a>/<a href="http://msdn.microsoft.com/en-us/library/system.net.sockets.networkstream.beginwrite%28v=vs.110%29.aspx" rel="noreferrer"><code>BeginWrite()</code></a> operations for non-blocking I/O. Note that the <code>BeginRead()</code> and <code>BeginWrite()</code> use the same <code>AsyncCallback</code> mechanism employed by the <code>BeginReceive()</code> and <code>BeginSend()</code> methods of the <code>Socket</code> class.</p> <p>One of the key things to note at this point is this little blurb in the MSDN documentation for <code>NetworkStream</code>:</p> <blockquote> <p>Read and write operations can be performed simultaneously on an instance of the NetworkStream class without the need for synchronization. <strong>As long as there is one unique thread for the write operations and one unique thread for the read operations</strong>, there will be <em>no cross-interference between read and write threads</em> and no synchronization is required.</p> </blockquote> <p>In short, because you plan to read and write from the same <code>TcpClient</code> instance, you'll need two threads for doing this. Using separate threads will ensure that no data is lost while receiving data at the same time someone is trying to send. The way I've approached this in my projects is to create a top-level object, say <code>Client</code>, that wraps the <code>TcpClient</code> and its underlying <code>NetworkStream</code>. This class also creates and manages two <a href="http://msdn.microsoft.com/en-us/library/system.threading.thread%28v=vs.110%29.aspx" rel="noreferrer"><code>Thread</code></a> objects, passing the <code>NetworkStream</code> object to each during construction. The first thread is the <code>Sender</code> thread. Anyone wanting to send data does so via a public <code>SendData()</code> method on the <code>Client</code>, which routes the data to the <code>Sender</code> for transmission. The second thread is the <code>Receiver</code> thread. This thread publishes all received data to interested parties via a public event exposed by the <code>Client</code>. It looks something like this:</p> <h2>Client.cs</h2> <pre><code>public sealed partial class Client : IDisposable { // Called by producers to send data over the socket. public void SendData(byte[] data) { _sender.SendData(data); } // Consumers register to receive data. public event EventHandler&lt;DataReceivedEventArgs&gt; DataReceived; public Client() { _client = new TcpClient(...); _stream = _client.GetStream(); _receiver = new Receiver(_stream); _sender = new Sender(_stream); _receiver.DataReceived += OnDataReceived; } private void OnDataReceived(object sender, DataReceivedEventArgs e) { var handler = DataReceived; if (handler != null) DataReceived(this, e); // re-raise event } private TcpClient _client; private NetworkStream _stream; private Receiver _receiver; private Sender _sender; } </code></pre> <p><br></p> <h2>Client.Receiver.cs</h2> <pre><code>private sealed partial class Client { private sealed class Receiver { internal event EventHandler&lt;DataReceivedEventArgs&gt; DataReceived; internal Receiver(NetworkStream stream) { _stream = stream; _thread = new Thread(Run); _thread.Start(); } private void Run() { // main thread loop for receiving data... } private NetworkStream _stream; private Thread _thread; } } </code></pre> <p><br></p> <h2>Client.Sender.cs</h2> <pre><code>private sealed partial class Client { private sealed class Sender { internal void SendData(byte[] data) { // transition the data to the thread and send it... } internal Sender(NetworkStream stream) { _stream = stream; _thread = new Thread(Run); _thread.Start(); } private void Run() { // main thread loop for sending data... } private NetworkStream _stream; private Thread _thread; } } </code></pre> <p>Notice that these are three separate .cs files but define different aspects of the same <code>Client</code> class. I use the Visual Studio trick described <a href="https://stackoverflow.com/questions/3617539/group-files-in-visual-studio">here</a> to nest the respective <code>Receiver</code> and <code>Sender</code> files under the <code>Client</code> file. In a nutshell, that's the way I do it.</p> <p>Regarding the <a href="http://msdn.microsoft.com/en-us/library/system.net.sockets.networkstream.dataavailable%28v=vs.110%29.aspx" rel="noreferrer"><code>NetworkStream.DataAvailable</code></a>/<a href="http://msdn.microsoft.com/en-us/library/System.Threading.Thread.Sleep%28v=vs.110%29.aspx" rel="noreferrer"><code>Thread.Sleep()</code></a> question. I would agree that an event would be nice, but you can effectively achieve this by using the <code>Read()</code> method in combination with an infinite <a href="http://msdn.microsoft.com/en-us/library/bk6w7hs8%28v=vs.110%29.aspx" rel="noreferrer"><code>ReadTimeout</code></a>. This will have no adverse impact on the rest of your application (e.g., UI) since it's running in its own thread. However, this complicates shutting down the thread (e.g., when the application closes), so you'd probably want to use something more reasonable, say 10 milliseconds. But then you're back to polling, which is what we're trying to avoid in the first place. Here's how I do it, with comments for explanation:</p> <pre><code>private sealed class Receiver { private void Run() { try { // ShutdownEvent is a ManualResetEvent signaled by // Client when its time to close the socket. while (!ShutdownEvent.WaitOne(0)) { try { // We could use the ReadTimeout property and let Read() // block. However, if no data is received prior to the // timeout period expiring, an IOException occurs. // While this can be handled, it leads to problems when // debugging if we are wanting to break when exceptions // are thrown (unless we explicitly ignore IOException, // which I always forget to do). if (!_stream.DataAvailable) { // Give up the remaining time slice. Thread.Sleep(1); } else if (_stream.Read(_data, 0, _data.Length) &gt; 0) { // Raise the DataReceived event w/ data... } else { // The connection has closed gracefully, so stop the // thread. ShutdownEvent.Set(); } } catch (IOException ex) { // Handle the exception... } } } catch (Exception ex) { // Handle the exception... } finally { _stream.Close(); } } } </code></pre> <p>As far as 'keepalives' are concerned, there is unfortunately not a way around the problem of knowing when the other side has exited the connection silently except to try sending some data. In my case, since I control both the sending and receiving sides, I've added a tiny <code>KeepAlive</code> message (8 bytes) to my protocol. This is sent every five seconds from both sides of the TCP connection unless other data is already being sent.</p> <p>I think I've addressed all the facets that you touched on. I hope you find this helpful.</p>
26,403,334
How to pass API keys in environment variables to Ember CLI using process.env?
<p>How do I pass environment variables from bashrc to Ember CLI. I imagine a situation where you need stripe api keys or pusher api-keys and you have them in your environment variables in bashrc. How do you pass the api-keys to Ember CLI. </p> <p>I tried using Node.js <code>process.env</code> in both the <code>brocfile.js</code> and <code>environment.js</code>, but when I try to access it in the Ember JS controller, the property is null.</p> <p>In my <code>environment.js</code> file I added,</p> <pre><code>APP: { apiKey: process.env.KEY } </code></pre> <p>In My Ember JS controller I tried accessing it with:</p> <pre><code>import config from '../config/environment'; </code></pre> <p>And setting the controller property <code>lkey</code> as shown below, which didn't work:</p> <pre><code>lkey: config.App.KEY </code></pre> <p>Next in my <code>brocfile.js</code>, I added:</p> <pre><code>var limaKey = process.env.Key; var app = new EmberApp({key: limaKey}); </code></pre> <p>This still didn't work.</p>
26,425,078
4
5
null
2014-10-16 11:31:47.58 UTC
10
2017-08-14 02:28:22.31 UTC
2015-12-03 03:48:46.567 UTC
null
117,259
null
529,289
null
1
26
ember.js|ember-cli|ember-router
20,445
<p>I finally resolved this issue. I was faced with two options. Option 1 was to use XHR to fetch the api-keys from an end-point on the server. Option 2 is get the api-key directly from environment variables using Nodejs process.env. I prefer option 2 because it saves me from doing XHR request.</p> <p>You can get option 2 by using this ember-cli-addOn which depends on Nodejs Dotenv project</p> <ul> <li><a href="https://github.com/fivetanley/ember-cli-dotenv" rel="noreferrer">https://github.com/fivetanley/ember-cli-dotenv</a> </li> <li><a href="https://github.com/motdotla/dotenv" rel="noreferrer">https://github.com/motdotla/dotenv</a></li> </ul> <p>In my case I choose to do it without any addOn.</p> <ol> <li>First add the api-key to your <code>.bashrc</code> if you are Ubuntu or the approapriate place for your own linux distro.</li> </ol> <pre><code>export API_KEY=NwPyhL5 </code></pre> <ol start="2"> <li>Reload the <code>.bashrc</code> file, so your setting are picked up:</li> </ol> <pre><code>source ~/.bashrc </code></pre> <ol start="3"> <li>In Ember CLI add a property to the <code>ENV</code> object in <code>config/environment.js</code>. The default looks like this</li> </ol> <pre><code>module.exports = function(environment) { var ENV = { modulePrefix: 'rails-em-cli', environment: environment, baseURL: '/', locationType: 'auto', EmberENV: { } } </code></pre> <p>Now to that <code>ENV</code> object, we can add a new property <strong>myApiKey</strong> like this:</p> <pre><code>module.exports = function(environment) { var ENV = { modulePrefix: 'rails-em-cli', environment: environment, baseURL: '/', locationType: 'auto', myApikey: null, EmberENV: { } //assign a value to the myApiKey if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; ENV.myApiKey = process.env.API_KEY; } } </code></pre> <p>Note that <strong>process.env.API_KEY</strong> is fetching the setting we added to <code>.bashrc</code> and assigning it to <strong>myApiKey</strong>. You will need to have Nodejs installed on your server for <strong>process.env</strong> to work.</p> <p>Finally to access that variable in your controller you do</p> <pre><code>import config from '../config/environment'; import Ember from 'ember'; export default Ember.Controller.extend({ yourKey: config.myApikey, }); </code></pre> <p>That's it.</p>
43,542,373
Angular2 add class to body tag
<p>How can I add a <strong>class</strong> to the <strong>body</strong> tag without making the <strong>body</strong> as the app selector and using host binding?</p> <p>I tried the using the Renderer but it changes the whole body </p> <p><a href="https://stackoverflow.com/questions/34430666/angular-2-x-bind-class-on-body-tag">Angular 2.x bind class on body tag</a></p> <p>I'm working on a big angular2 app and changing the root selector will impact a lot of code, I will have to change a lot of code</p> <p>My use case is this:</p> <p>When I open a modal component (created dynamically) I want the document scrollbar to hide</p>
43,552,385
2
10
null
2017-04-21 12:09:49.097 UTC
33
2022-04-05 07:28:40.293 UTC
2018-03-27 12:25:15.457 UTC
null
2,172,547
null
1,543,885
null
1
123
angular
94,248
<p>I would love to comment. But due to missing reputation I write an answer. Well I know two possibilities to solve this issue.</p> <ol> <li>Inject the Global Document. Well it might not be the best practice as I don't know if nativescript etc supports that. But it is at least better than use pure JS.</li> </ol> <pre class="lang-js prettyprint-override"><code>constructor(@Inject(DOCUMENT) private document: Document) {} ngOnInit(){ this.document.body.classList.add('test'); } </code></pre> <p>Well and perhaps even better. You could inject the renderer or renderer 2 (on NG4) and add the class with the renderer.</p> <pre class="lang-js prettyprint-override"><code>export class myModalComponent implements OnDestroy { constructor(private renderer: Renderer) { this.renderer.setElementClass(document.body, 'modal-open', true); } ngOnDestroy(): void { this.renderer.setElementClass(document.body, 'modal-open', false); } } </code></pre> <p><strong>EDIT FOR ANGULAR4:</strong></p> <pre class="lang-js prettyprint-override"><code>import { Component, OnDestroy, Renderer2 } from '@angular/core'; export class myModalComponent implements OnDestroy { constructor(private renderer: Renderer2) { this.renderer.addClass(document.body, 'modal-open'); } ngOnDestroy(): void { this.renderer.removeClass(document.body, 'modal-open'); } } </code></pre>
11,058,811
wget not working
<p>On Ubuntu, I am trying to download a file (from a script) using wget. Buildling a program to download this file everyday and load to a hadoop cluster.</p> <p>however, the wget fails, with the following message.</p> <pre><code>wget http://www.nseindia.com/content/historical/EQUITIES/2012/JUN/cm15JUN2012bhav.csv.zip --2012-06-16 03:37:30-- http://www.nseindia.com/content/historical/EQUITIES/2012/JUN/cm15JUN2012bhav.csv.zip Resolving www.nseindia.com... 122.178.225.48, 122.178.225.18 Connecting to www.nseindia.com|122.178.225.48|:80... connected. HTTP request sent, awaiting response... 403 Forbidden 2012-06-16 03:37:30 ERROR 403: Forbidden. </code></pre> <p>when I try the same url in firefox or equivalent, it works just fine. And yes, there is no license agreement kind of thing involved...</p> <p>Am I missing something basic regarding wget ??</p>
11,058,856
5
2
null
2012-06-15 22:11:44.44 UTC
5
2014-07-19 05:41:09.313 UTC
null
null
null
null
459,222
null
1
13
ubuntu
51,547
<p>The site blocks wget because wget uses an uncommon user-agent by default. To use a different user-agent in wget, try:</p> <pre><code>wget -U Mozilla/5.0 http://www.nseindia.com/content/historical/EQUITIES/2012/JUN/cm15JUN2012bhav.csv.zip </code></pre>
11,162,740
where I can find the little red dot image used in google map?
<p>I am looking for the red dots showing <a href="https://maps.google.com/maps?f=q&amp;source=s_q&amp;hl=en&amp;geocode=&amp;q=restaurant,%20dallas,%20tx&amp;sll=37.0625,-95.677068&amp;sspn=47.617464,93.076172&amp;ie=UTF8&amp;hq=restaurant,&amp;hnear=Dallas,%20Texas&amp;z=13" rel="noreferrer">here</a> I can find find plenty of push pins and shadows in various place. But cannot find this little dot.... Could someone help me?</p>
11,162,887
5
3
null
2012-06-22 19:18:45.667 UTC
18
2017-09-18 16:56:11.267 UTC
2014-04-18 17:52:39.143 UTC
null
3,476,320
null
884,871
null
1
18
google-maps|marker
32,959
<p>Are you just trying to copy out the style of the markers?</p> <p>If you are using Chrome just press F12 for developer tools, go to resources, then choose Frames->Maps->Images.</p> <p>All of the images are shown there along with their locations.</p> <p><a href="https://maps.gstatic.com/mapfiles/markers2/red_markers_A_J2.png" rel="noreferrer">https://maps.gstatic.com/mapfiles/markers2/red_markers_A_J2.png</a></p> <p>I believe those are what you are talking about?</p> <p>If you are talking about the really tiny little red dots, they appear to be part of the map images themselves.</p> <p>However, there is a little blue dot that looks to be exactly the same, <a href="https://maps.gstatic.com/intl/en_us/mapfiles/markers2/measle_blue.png" rel="noreferrer">https://maps.gstatic.com/intl/en_us/mapfiles/markers2/measle_blue.png</a></p>
10,935,026
How to clear interval and set it again?
<p>This is what i am trying to accomplish: when the last slide is reached fadeOut last slide and then fadeIn first slide, and then clearInterval <b><i>(everything works with this part)</i></b>. Now my problem is that i want to setInterval <b>again</b> if it doesn't exists but I don't know how to make it happen:( <br/>I have tried to solve this with if statment but then my script doesn't work at all! <br/>So how can I RESTART my interval again? THANK YOU!! <br/><b>Without</b> if statement like this it's working fine:</p> <pre><code>if(!intervalID){ intervalID = setInterval(animate,5000); } </code></pre> <p>This is what I have so far: </p> <pre><code>$(document).ready(function() { /*check if intervalID don't exists messes UP!!*/ if (!intervalID) { intervalID = setInterval(animate, 5000); } //Hide everything except first slide and controls $('.slidewrap div:not(.slidewrap div:first,.slidewrap .slide_controls)').hide(); var animate = function() { /*if .pagination_active is last removeClass and addClass to .pagination_active first li tag*/ if ($('.pagination_active').is($('.slide_controls ul li:last'))) { $('.pagination_active').removeClass('pagination_active'); $('.slide_controls ul li:first').addClass('pagination_active'); } else { $('.pagination_active').removeClass('pagination_active').next().addClass('pagination_active'); } /*if div.active is last fadeOut and add .active class to the first div and fadeIn FIRST div then CLEAR INTERVAL and set intervalID to zero */ if ($('.active').is($('.slidewrap div:last'))) { $('.active').fadeOut(1000).removeClass('active'); $('.slidewrap div:first').addClass('active').fadeIn(1000, function() { clearInterval(intervalID); intervalID = 0; }); } //OR .active fadeOut and next div fadeIn else { $('.active').fadeOut(1000).next().fadeIn(1000, function() { $('.slidewrap div.active').removeClass('active').next('div').addClass('active'); }); } } var intervalID; intervalID = setInterval(animate, 3000); }); </code></pre>
10,935,062
5
2
null
2012-06-07 15:33:59.713 UTC
5
2022-02-27 08:28:23.71 UTC
2016-01-10 10:53:31.69 UTC
null
1,479,535
null
1,053,949
null
1
19
javascript|jquery
38,007
<p>After clear an interval you need to start it again with <code>setInterval()</code>.</p> <p>It would be better to make function for your <code>setInterval()</code></p> <pre><code>var intervalID = null; function intervalManager(flag, animate, time) { if(flag) intervalID = setInterval(animate, time); else clearInterval(intervalID); } </code></pre> <p>Here <code>flag</code> is a <code>boolean</code> variable with value <code>true/ false</code>. <code>true</code> will execute <code>setInterval()</code> and <code>false</code> will <code>clearInterval()</code>;</p> <p>Now you can use above function as you need.</p> <p>For example:</p> <pre><code>intervalManager(true, animate, 300); // for setInterval intervalManager(false); // for clearInterval </code></pre>
11,018,076
Splitting delimited values in a SQL column into multiple rows
<p>I would really like some advice here, to give some background info I am working with inserting Message Tracking logs from Exchange 2007 into SQL. As we have millions upon millions of rows per day I am using a Bulk Insert statement to insert the data into a SQL table.</p> <p>In fact I actually Bulk Insert into a temp table and then from there I MERGE the data into the live table, this is for test parsing issues as certain fields otherwise have quotes and such around the values.</p> <p>This works well, with the exception of the fact that the recipient-address column is a delimited field seperated by a ; character, and it can be incredibly long sometimes as there can be many email recipients.</p> <p>I would like to take this column, and split the values into multiple rows which would then be inserted into another table. Problem is anything I am trying is either taking too long or not working the way I want.</p> <p>Take this example data:</p> <pre><code>message-id recipient-address 2D5E558D4B5A3D4F962DA5051EE364BE06CF37A3A5@Server.com user1@domain1.com E52F650C53A275488552FFD49F98E9A6BEA1262E@Server.com user2@domain2.com 4fd70c47.4d600e0a.0a7b.ffff87e1@Server.com user3@domain3.com;user4@domain4.com;user5@domain5.com </code></pre> <p>I would like this to be formatted as followed in my Recipients table:</p> <pre><code>message-id recipient-address 2D5E558D4B5A3D4F962DA5051EE364BE06CF37A3A5@Server.com user1@domain1.com E52F650C53A275488552FFD49F98E9A6BEA1262E@Server.com user2@domain2.com 4fd70c47.4d600e0a.0a7b.ffff87e1@Server.com user3@domain3.com 4fd70c47.4d600e0a.0a7b.ffff87e1@Server.com user4@domain4.com 4fd70c47.4d600e0a.0a7b.ffff87e1@Server.com user5@domain5.com </code></pre> <p>Does anyone have any ideas about how I can go about doing this?</p> <p>I know PowerShell pretty well, so I tried in that, but a foreach loop even on 28K records took forever to process, I need something that will run as quickly/efficiently as possible.</p> <p>Thanks!</p>
11,018,339
4
1
null
2012-06-13 15:17:15.903 UTC
10
2021-08-31 23:21:55.16 UTC
2012-06-18 22:39:37.633 UTC
null
61,305
null
1,257,600
null
1
27
sql|sql-server|sql-server-2008|tsql|sql-server-2005
100,754
<h2>If you are on SQL Server 2016+</h2> <p>You can use the new <code>STRING_SPLIT</code> function, which I've blogged about <a href="https://sqlperformance.com/2016/03/sql-server-2016/string-split" rel="noreferrer">here</a>, and Brent Ozar has blogged about <a href="https://www.brentozar.com/archive/2016/03/splitting-strings-sql-server-2016-rescue/" rel="noreferrer">here</a>.</p> <pre><code>SELECT s.[message-id], f.value FROM dbo.SourceData AS s CROSS APPLY STRING_SPLIT(s.[recipient-address], ';') as f; </code></pre> <h2>If you are still on a version prior to SQL Server 2016</h2> <p>Create a split function. This is just one of many examples out there:</p> <pre><code>CREATE FUNCTION dbo.SplitStrings ( @List NVARCHAR(MAX), @Delimiter NVARCHAR(255) ) RETURNS TABLE AS RETURN (SELECT Number = ROW_NUMBER() OVER (ORDER BY Number), Item FROM (SELECT Number, Item = LTRIM(RTRIM(SUBSTRING(@List, Number, CHARINDEX(@Delimiter, @List + @Delimiter, Number) - Number))) FROM (SELECT ROW_NUMBER() OVER (ORDER BY s1.[object_id]) FROM sys.all_objects AS s1 CROSS APPLY sys.all_objects) AS n(Number) WHERE Number &lt;= CONVERT(INT, LEN(@List)) AND SUBSTRING(@Delimiter + @List, Number, 1) = @Delimiter ) AS y); GO </code></pre> <p>I've discussed a few others <a href="https://sqlperformance.com/2012/07/t-sql-queries/split-strings" rel="noreferrer">here</a>, <a href="https://sqlperformance.com/2012/08/t-sql-queries/splitting-strings-follow-up" rel="noreferrer">here</a>, and a better approach than splitting in the first place <a href="https://sqlperformance.com/2012/08/t-sql-queries/splitting-strings-now-with-less-t-sql" rel="noreferrer">here</a>.</p> <p>Now you can extrapolate simply by:</p> <pre><code>SELECT s.[message-id], f.Item FROM dbo.SourceData AS s CROSS APPLY dbo.SplitStrings(s.[recipient-address], ';') as f; </code></pre> <p>Also I suggest not putting dashes in column names. It means you always have to put them in <code>[square brackets]</code>.</p>
11,005,279
How do I unit test code which calls the Jersey Client API?
<p>I wrote code which calls the Jersey client API which in turn calls a web service which is out of my control. I do not want my unit test to call the actual web service.</p> <p>What is the best approach for writing a unit test for code which calls the Jersey client API? Should I use the Jersey server API to write a JAX-RS web service and then use the Jersey Test Framework for the unit test? Or should I mock out the Jersey web service calls? I have access to JMock. Or should I try another approach?</p> <p>During my research, I found <a href="http://jersey.576304.n2.nabble.com/Unit-Testing-code-that-uses-the-Jersey-Client-API-td7071519.html" rel="noreferrer">this discussion</a> describing various options, but I did find a complete solution. Are there any code examples available showing a suggested JUnit approach? I could not find any in the Jersey documentation.</p> <p>Here is the relevant source code:</p> <pre><code>public String getResult(URI uri) throws Exception { // error handling code removed for clarity ClientConfig clientConfig = new DefaultClientConfig(); Client client = Client.create(clientConfig); WebResource service = client.resource(uri); String result = service.accept(accept).get(String.class); return result; } </code></pre> <p>Here are examples of test code I would like to pass. I would like to test (1) passing in a valid URI and getting a valid string back and (2) passing in an invalid (for whatever reason -- unreachable or unauthorized) URI and getting an exception back.</p> <pre><code>@Test public void testGetResult_ValidUri() throws Exception { String xml = retriever.getResult(VALID_URI); Assert.assertFalse(StringUtils.isBlank(xml)); } @Test(expected = IllegalArgumentException.class) public void testGetResult_InvalidUri() throws Exception { retriever.getResult(INVALID_URI); } </code></pre> <p>Everything above is the simple description of what my code does. In reality, there is a layer on top of that that accepts two URIs, first tries calling the first URI, and if that URI fails then it tries calling the second URI. I would like to have unit tests covering (1) the first URI succeeds, (2) the first URI fails and the second URI succeeds, and (3) both URIs fail. This code is sufficiently complex that I want to test these different scenarios using JUnit, but to do this I either need to run actual stand-in web services or mock out the Jersey client API calls.</p>
11,005,771
3
3
null
2012-06-12 21:39:57.387 UTC
5
2018-10-25 12:55:49.617 UTC
2012-06-12 22:10:20.26 UTC
null
364,029
null
364,029
null
1
28
java|unit-testing|junit|jersey|jax-rs
19,052
<p>Try to use Mockito or Easymock for mocking service calls. You need to mock only these methods which are actually used - no need to mock every method. You can creat mock object for WebResource class, then mock accept method call.</p> <p>In @BeforeClass/@Before JUnit test method write something like (Mockito example)</p> <pre><code>WebResource res = mock(WebResource.class); when(res.accept(something)).thenReturn(thatWhatYouWant); </code></pre> <p>Then in your tests you can use res object as if it was real object and call mock method on it. Instead of returning value you can also throw exceptions. <a href="http://code.google.com/p/mockito/" rel="noreferrer">Mockito</a> is pretty cool.</p>
11,115,899
Failed to install due to Timeout in Emulator
<p>When attempting to install an .apk from Eclipse, whether to an android emulator or to a physical device (via USB), I get a "Failed to install *.apk on device '*': timeout" error. The .apk is not found on the emulator nor physcial device (Samsung Galaxy S2, rooted).</p> <p>If I avoid eclipse, and just use the command line, I'm also unable to install an .apk.</p> <h1>Why a new post on this?</h1> <p>There are several other stackoverflow posts that reference the "Failed to install..." error. I've created a new post for a few reasons:</p> <ul> <li>Most of the other posts are not detailed.</li> <li>The prominent relevant post, <a href="https://stackoverflow.com/questions/4775603/android-error-failed-to-install-apk-on-device-timeout">Android error: Failed to install *.apk on device *: timeout</a>, for the original poster, applies only to physical device connections. So it is a different case, albeit with similar symptoms.</li> <li>All of the candidate solutions in that post, and several others, I have tried. These are listed bellow under "Candidate solutions i've tried".</li> </ul> <p>This post is lengthy as the steps I've taken are lengthy, as was warranted by the bug. If you don't want to read, or at least scan, this post please do not comment.</p> <h1>My Environment</h1> <p>HOST OS: Windows XP SP3</p> <p>JAVA: Java SDK version 1.6.0_32</p> <p>WINDOWS ENVIRONMENT VARIABLES:</p> <p><code>JAVA_HOME=C:\Program Files\Java\jdk1.6.0_33;</code></p> <p><code>PATH=...;%JAVA_HOME%\bin\;C:\android\android-sdk\tools;C:\android\android-sdk\platform-tools\;...;C:\Program Files\apache-ant-1.8.2\bin;...;</code></p> <p>IDE: Eclipse (installed classic) Indigo. Version 3.7.2</p> <p>ANDROID SDK</p> <ul> <li>Android SDK Tools Revision: 20. (Chiefly tested with revision 19).</li> <li>Android SDK Platform-tools: 11.</li> <li>ADT plug-in ("Android Development Toolkit", Eclipse Plugin) version: 20.0.0.v201206010423-369331 (also with prior version 18.0.0.v201203301501-306762).</li> <li>Platform targeted by your project &amp; Version of the platform running in the emulator. Tried each off: <ul> <li>Android 4.0.3 (API 15)</li> <li>Android 2.2 (API 8)</li> <li>Andorid 2.1 (API 7)</li> </ul></li> </ul> <p>MOBILE: Samsung Galaxy S2 running Android Ice Cream Sandwhich (ICS) 4.0.3</p> <p>ANT: 1.8.2</p> <h1>Steps I go through to produce the errors.</h1> <p>Using Eclipse to attempt to install an .apk to the emulator:</p> <ul> <li>Open eclipse (which loads my workspace with a single android application in it).</li> <li>Run my android application using a previously configured Run configuration.</li> <li>The "Android Device Chooser" launches (I have set my Run configuration to launch this manually).</li> <li>In the Android Device Chooser I select my avd (targeting Android 2.2), and click OK.</li> <li>The emulator opens with "5554:jlbavd2_2". My AVD name is "jlbavd2_2".</li> <li>I leave the emulator open. In Eclipse I open the DDMS view. In the "Devices" pane I click on the white triangle and choose "Reset adb".</li> </ul> <p>In the Eclipse console, Android view, I get</p> <pre><code>[2012-06-19 19:20:52 - MyApp] Starting full Post Compiler. [2012-06-19 19:20:52 - MyApp] ------------------------------ [2012-06-19 19:20:52 - MyApp] Android Launch! [2012-06-19 19:20:52 - MyApp] adb is running normally. [2012-06-19 19:20:52 - MyApp] Performing au.com.myorg.myapp.MyAppActivity activity launch [2012-06-19 19:20:52 - MyApp] Refreshing resource folders. [2012-06-19 19:20:52 - MyApp] Starting incremental Pre Compiler: Checking resource changes. [2012-06-19 19:20:52 - MyApp] Nothing to pre compile! [2012-06-19 19:20:53 - MyApp] Starting incremental Package build: Checking resource changes. [2012-06-19 19:20:53 - MyApp] Skipping over Post Compiler. [2012-06-19 19:20:59 - MyApp] Launching a new emulator with Virtual Device 'jlbavd' [2012-06-19 19:22:29 - MyApp] New emulator found: emulator-5554 [2012-06-19 19:22:29 - MyApp] Waiting for HOME ('android.process.acore') to be launched... [2012-06-19 19:22:44 - MyApp] HOME is up on device 'emulator-5554' [2012-06-19 19:22:44 - MyApp] Uploading MyApp.apk onto device 'emulator-5554' [2012-06-19 19:22:49 - MyApp] Failed to install MyApp.apk on device 'emulator-5554': timeout [2012-06-19 19:22:49 - MyApp] Launch canceled! </code></pre> <p>In the Eclipse console, DDMS output, I get:</p> <pre><code>... [2012-06-19 19:22:44 - ddm-hello] handling HELO [2012-06-19 19:22:44 - ddm-hello] HELO: v=1, pid=150, vm='Dalvik v1.2.0', app='android.process.acore' [2012-06-19 19:22:44 - MyApp.apk] Uploading MyApp.apk onto device 'emulator-5554' [2012-06-19 19:22:44 - Device] Uploading file onto device 'emulator-5554' [2012-06-19 19:22:49 - ddms] write: timeout [2012-06-19 19:22:49 - Device] Error during Sync: timeout. [2012-06-19 19:22:49 - ddms] Removing req 0x4000002d from set </code></pre> <p>Sometimes (perhaps I do slightly different steps) I get:</p> <pre><code>[2012-06-16 14:20:02 - MyFirstApp02] Starting full Post Compiler. [2012-06-16 14:20:02 - MyFirstApp02] ------------------------------ [2012-06-16 14:20:02 - MyFirstApp02] Android Launch! [2012-06-16 14:20:02 - MyFirstApp02] adb is running normally. [2012-06-16 14:20:02 - MyFirstApp02] Performing au.com.myorg.MyFirstApp02Activity activity launch [2012-06-16 14:20:08 - MyFirstApp02] Launching a new emulator with Virtual Device 'jlbavd2_2' [2012-06-16 14:20:17 - Emulator] bind: Unknown error [2012-06-16 14:20:17 - MyFirstApp02] New emulator found: emulator-5556 [2012-06-16 14:20:17 - MyFirstApp02] Waiting for HOME ('android.process.acore') to be launched... [2012-06-16 14:20:38 - MyFirstApp02] HOME is up on device 'emulator-5556' [2012-06-16 14:20:38 - MyFirstApp02] Uploading MyFirstApp02.apk onto device 'emulator-5556' [2012-06-16 14:20:50 - MyFirstApp02] Failed to install MyFirstApp02.apk on device 'emulator-5556': timeout [2012-06-16 14:20:50 - MyFirstApp02] Launch canceled! </code></pre> <p>Note the "bind: Unknown error". Sometimes this error happens, sometimes it does not.</p> <p>If I unplug my ethernet cable to my hardware router I get the following:</p> <pre><code>[2012-06-19 23:27:29 - MyApp] Android Launch! [2012-06-19 23:27:29 - MyApp] adb is running normally. [2012-06-19 23:27:29 - MyApp] Performing au.com.softmake.myapp.MyAppActivity activity launch [2012-06-19 23:27:29 - MyApp] Refreshing resource folders. [2012-06-19 23:27:29 - MyApp] Starting incremental Pre Compiler: Checking resource changes. [2012-06-19 23:27:29 - MyApp] Nothing to pre compile! [2012-06-19 23:27:33 - MyApp] Launching a new emulator with Virtual Device 'jlbavd' [2012-06-19 23:27:40 - Emulator] Warning: No DNS servers found [2012-06-19 23:27:44 - Emulator] emulator: emulator window was out of view and was recentered [2012-06-19 23:27:44 - Emulator] [2012-06-19 23:28:29 - MyApp] New emulator found: emulator-5554 [2012-06-19 23:28:29 - MyApp] Waiting for HOME ('android.process.acore') to be launched... [2012-06-19 23:28:36 - MyApp] HOME is up on device 'emulator-5554' [2012-06-19 23:28:36 - MyApp] Uploading MyApp.apk onto device 'emulator-5554' [2012-06-19 23:28:42 - MyApp] Failed to install MyApp.apk on device 'emulator-5554': timeout [2012-06-19 23:28:42 - MyApp] Launch canceled! </code></pre> <p>Note the "Warning: No DNS servers found"</p> <p>Using Eclipse to attempt to install an .apk to a physical device (rooted Samsung Galaxy S2. 4.0.3 with USB debugging enabled), and after going through similar steps as above, I get in the Eclipse console, Android Output:</p> <pre><code>[2012-06-15 22:40:34 - MyFirstApp] Starting full Post Compiler. [2012-06-15 22:40:34 - MyFirstApp] ------------------------------ [2012-06-15 22:40:34 - MyFirstApp] Android Launch! [2012-06-15 22:40:34 - MyFirstApp] adb is running normally. [2012-06-15 22:40:34 - MyFirstApp] Performing au.com.myorg.myfirstapp.MyFirstAppActivity activity launch [2012-06-15 22:40:39 - MyFirstApp] Uploading MyFirstApp.apk onto device '0019adf659f24e' [2012-06-15 22:40:51 - MyFirstApp] Failed to install MyFirstApp.apk on device '0019adf659f24e': timeout [2012-06-15 22:40:51 - MyFirstApp] Launch canceled! </code></pre> <p>The same sort of error as when attempting to install to the emulator.</p> <p>When using the command line only, and thereby avoiding Eclipse, I go through the following steps:</p> <ul> <li><p>Open a windows command prompt in my working directory (I'm using C:\Data\Sda\Code\Mobile\Android\Examples>").</p> <blockquote> <p>android list targets.</p> </blockquote></li> <li><p>I obtain my target id (I choose Android 2.2).</p> <blockquote> <p>android create project --target 3 --name MyAppCmd --path ./MyAppCmd --activity MyAppCmdActivity --package au.com.myorg.myappcmd</p> </blockquote></li> <li><p>I get a series of healthy looking output "Created project directory ...", "Added file ..."</p></li> <li>In windows I double click "AVD Manager.exe".</li> <li>I launch my avd (which targets Android 2.2)</li> <li><p>Back to my command window</p> <blockquote> <p>cd MyAppCmd</p> <p>ant debug</p> </blockquote></li> <li><p>After a list of output I get "BUILD SUCCESSFUL ..." (On a prior occasion I had to edit C:\android\android-sdk\platform-tools\dx.bat to change "set defaultXmx=-Xmx1024M" to "set defaultMx=-Xmx512M" to make the build successful ). I observe that bin/MyAppCmd-debug.apk exists.</p></li> <li><p>I attempt an install with</p> <blockquote> <p>adb install bin/MyAppCmd-debug.apk</p> </blockquote></li> <li><p>Output:</p> <pre><code>* daemon not running. starting it now on port 5037 * * daemon started successfully * error: device offline </code></pre> <blockquote> <p>adb devices</p> </blockquote> <pre><code>List of devices attached emulator-5554 device </code></pre> <blockquote> <p>adb install bin/MyAppCmd-debug.apk</p> </blockquote></li> <li><p>There is no further output in the command window. No error message. Just a blinking cursor, no error or success message, and no return to the command prompt ">".</p></li> <li><p>I shut down the command line and open a new one.</p></li> <li><p>I get the same result (a blinking cursor, etc.) if I try a push command (temp.txt has been previously created on my windows system) ...</p> <blockquote> <p>adb push temp.txt /sdcard/temp.txt</p> </blockquote></li> </ul> <h1>Candidate solutions i've tried</h1> <p>Eclipse related:</p> <ul> <li>Followed the steps from <a href="http://developer.android.com/resources/faq/troubleshooting.html#eclipse" rel="noreferrer">Eclipse isn't talking to the emulator</a></li> <li>Increased the ADB connection time out. Eclipse > Window > Preferences > Android > DDMS > " ADB connection time out(ms):" = 10000 (I've also tried 60000).</li> <li>Running the application twice (and choosing the currently running emulator or mobile phone again).</li> <li>Cleaned my project: Eclipse > Project > Clean ...</li> <li>Rebooted Eclipse.</li> <li>Downgraded Eclipse from Indigo (2.7.x) to Helios (2.6.x).</li> </ul> <p>Android related:</p> <ul> <li>Reset the adb in several ways: "Reset ADB" command from the Eclipse DDMS perspective (from the Devices window triangle); command line with "adb kill-server" and "adb start-server"; and using the Windows Task manager to kill adb.exe.</li> <li>Reinstalling my Samsung OEM USB drivers (By using KIES > Tools > Troubleshoot connection error).</li> <li>Installing my Android SDK to a directory without spaces anywhere in the paths. Namely C:\Android\android-sdk. This entailed a reinstall of the SDK, formerly located at C:\Program files\Android\android-sdk</li> <li>My Android Project is installed in a directory without spaces anywhere in the the path.</li> <li>Deleting and recreating the avd (both from the Android AVD Manager and using Windows Explorer).</li> <li>Using different AVDs that target different platfroms (Android 2.2 and Android 4.0.3).</li> <li>Just after the Emulator opens but before it times out: unlocking the phone V waiting till it times out with the phone locked (in the emulator).</li> <li><p>Verified I have in my AndroidManifest.xml:</p> <pre><code> &lt;uses-sdk android:minSdkVersion="8" android:targetSdkVersion="8" /&gt; </code></pre></li> </ul> <p>Environment related (PC and Phone):</p> <ul> <li>Rebooted My Phone.</li> <li>Rebooted my development PC.</li> <li>Turning off my software and hardware firewall.</li> <li>Turning of MS Security Essentials Real Time Protection.</li> <li>Disabled my hosts list.</li> <li>Reinstalled Java.</li> <li>Booting into Windows safe mode and running Eclipse.</li> <li>Manually killing most other application TCP/IP Processes (E.g GoogleDesk.exe, Apache Server PunkBuster, etc) by seeing what is available in <a href="http://technet.microsoft.com/en-gb/sysinternals/bb897437" rel="noreferrer">Sysinternals TCPView</a>.</li> <li>Disconnected the Ethernet cable from my PC.</li> </ul> <h1>Other information</h1> <p>Some adb commands work.</p> <p>For example the following makes the emulator screen dance about (as is expected).</p> <blockquote> <p>adb shell monkey -v 100</p> </blockquote> <p>I can list the devices, and correctly retrieve their state with</p> <blockquote> <p>adb devices.</p> </blockquote> <p>So there is partial communication between an adb client and adb daemon (via an adb server).</p> <p>I am relatively new to Android development. However, I have successfully installed .apks to the emulator and my device about 6 months ago (from the WinXP PC I'm now trying to make work). I have ignored Android since then. When I came back to it recently I had some problem building my .apks which was fixed by deleting my debug.key and allowing eclipse to generate a new one.</p> <p>In the intervening 6 months my development machine has changed in all sorts of ways. Installing new servers and apps, changing firewall settings etc. So there could well be some change I'm overlooking.</p> <p>I also have a Win7 Laptop from which I have successfully installed .apks to the emulator and USB connected physical device. That is, I have a copy of the Android SDK, Eclipse, JAVA, etc installed on the Win7 machine. So I know I have a general handle on the correct procedure for setting it all up correctly.</p> <p>I can install the .apk manually by double clicking the file through ES File Explorer from my Phone (which connects to my development machine wirelessly).</p> <h1>Final thoughts</h1> <p>It seems that there is some problem with the adb client, adb server, or adb daemon in talking to each other fully.</p> <p>I have three hypothesis:</p> <ul> <li>It is my fault. That there is some kind of TCP/IP conflict which breaks some of the connections between the adb client, adb server, or adb daemon. This is due to some freakish setting on my PC (like any developer I change various settings on my system all the time). However, I have tried disabling security and other potentially conflicting TCP/IP processes (as far as I can tell).</li> <li>Some simple issue I keep overlooking.</li> <li>It is google's/Android's fault. That is, there is a bug in the Android adb which requires an update to the android SDK platform tools. I think this less likely since I'd expect it to have surfaced by now.</li> </ul> <h1>Updates to post</h1> <p>2012-06-22 18:55 (UTC): </p> <p>Complete reinstall (again) of Java, Eclipse, and the Android SDK with some variations in the install (e.g. Installed Java to root; Android SDK to the default "Program Files\"; and turning off all security software during install). </p> <p>I note an error "Stopping ADB server failed (code -1)." in the Android SDK Manager Log during and install of the various parts of the platform/tools (via the Manager).</p> <p>2012-06-30 06:15 (UTC):</p> <p>Readjusted "My Environment" specs to reflect latest tests.</p>
14,785,531
13
15
null
2012-06-20 08:47:11.21 UTC
6
2019-04-01 10:31:37.793 UTC
2017-05-23 10:31:29.493 UTC
null
-1
null
872,154
null
1
32
android|android-emulator|timeout
23,585
<p>I've solved the problem, many months later, by upgrading to a completely new environment. Specifically, a new machine with a fresh install of Windows 8. I've also avoided installing the Comodo suite (I don't know that this was causing the problem).</p> <p>So while this is not a direct solution to the problem (it's still not clear what was causing it) perhaps it might serve as another example where a workaround or lateral resolution to a problem is sometimes a good last resort option.</p>
11,443,669
How to interpret "Connection: keep-alive, close"?
<p>From what I understand, a HTTP connection could either be <code>keep-alive</code> or <code>close</code>.</p> <p>I sent a HTTP request to a server:</p> <pre><code>GET /page1/ HTTP/1.1 Host: server.com Connection: keep-alive </code></pre> <p>And it responded with:</p> <pre><code>HTTP/1.1 200 OK Connection: keep-alive, close </code></pre> <p>Essentially, I believe the server is bugged because a response like <code>keep-alive, close</code> is ambiguous.</p> <p>However, as the <strong>receiver</strong>, how should we <strong>handle</strong> such a message? Should we <strong>interpret</strong> this header value as <code>keep-alive</code> or <code>close</code>? </p>
22,143,279
4
3
null
2012-07-12 00:53:13.933 UTC
9
2022-04-29 11:08:37.877 UTC
2015-03-08 23:51:57.637 UTC
null
632,951
null
632,951
null
1
40
http|standards
64,952
<p><strong>TL; DR: Chrome interprets this response header as <code>keep-alive</code> and maintain a peristent connection while Firefox closes each connection.</strong></p> <p>I stumbled over this question as I tried to optimize the page loading time for my website.</p> <p>In the referenced RFC I didn't find anything about how multiple entries in the <code>Connection</code> header may be properly handled. It seemed to me like the implementation may choose from two possibilites: </p> <ol> <li>If there are multiple entries, you may choose that fits best to your needs</li> <li>If there is a <code>close</code> inside, you may close the connection after transmission</li> </ol> <p>So, I needed to find out. Let's make some deeper investigation:</p> <p>I noticed that Chrome was always sending a HTTP/1.1 request with <code>Connection: keep-alive</code> and my Apache default configuration was always responding with a <code>Connection: close</code> header. So I began investigating and took a look at the TCP segments with Wireshark.</p> <p>Chrome has to fetch 14 elements to display the website, mostly of them static things like images or css files. And it took in complete 14 TCP connections and that took a lot of time (approximately 1,2 seconds). After each request for an image (e.g.) there came a TCP segment with the <code>FIN</code> flag set to 1.</p> <p>So what about Chrome vs. Firefox? Chrome seems to have a maximum number of concurrent connections to one server of 6. Firefox has a more granular configuration and distinguishs persistent (maxium of 6, seen in about:config) and non-persistent (the maximum numbers differed a lot in different sources). But wait... Both, Chrome and Firefox are sending HTTP/1.1 request headers with <code>Connection: keep-alive</code>, so both should be limited to 6 (as this is a request for opening up a persistent connection).</p> <p>I decided to try a simple trick and added the following lines to my <code>.htaccess</code> in the web root folder:</p> <pre><code>&lt;ifModule mod_headers.c&gt; Header set Connection keep-alive &lt;/ifModule&gt; </code></pre> <p>The server now responds with:</p> <pre><code>Connection: keep-alive, close </code></pre> <p>Now I took a look at the TCP segments again: There were only 9 connections from Chrome to my server now and only 3 with the <code>FIN</code> flag set to 1. So this trick seemed to work. But why were there those 3 connections, that closed the connection after data transmission? These were the PHP requests, as the HTTP header <code>X-Powered-By: PHP/5.4.11</code> confirmed.</p> <p>And what about Firefox? There were still those 14 requests! </p> <p>How to fix that and get the fcgi processes to work with keep-alive too?</p> <p>I added the following lines to my virtualhost section of the httpd.conf configuration:</p> <pre><code>KeepAlive On KeepAliveTimeout 5 MaxKeepAliveRequests 100 </code></pre> <p>and removed the ones added in the <code>.htaccess</code>. Now the server isn't sending any confusing - <code>Connection: keep-alive, close</code>, but only <code>Connection: keep-alive</code> and everything works fine!</p> <p><strong>Conclusion:</strong></p> <p>A header with the connection field set to</p> <pre><code>HTTP/1.1 200 OK Connection: keep-alive, close </code></pre> <p>will be interpreted by Chrome as <code>keep-alive</code> while Firefox seems to close each connection. It seems to depend on the actual implementation.</p> <p>So if you're willing to implement a client for handling response headers that contain <code>Connection: keep-alive, close</code>, I would propose to try using keep-alive if you need more than one request. The worst thing that may happen: The server will close the connection and you need to connect again (that's exactly the other option you would have had!)</p>
11,191,764
Renaming a file in NERDTREE
<p>Is it possible to rename a file in NERDTree? I know about the m menu but there is no rename option. </p>
11,191,847
2
0
null
2012-06-25 14:56:25.123 UTC
5
2022-03-30 18:34:04.877 UTC
2013-04-02 22:10:58.467 UTC
null
897,221
null
897,221
null
1
50
vim|rename|nerdtree
12,420
<p>Use <code>Move</code>, <code>(m)ove the current node</code> in the m menu to rename.</p>
13,022,677
Save state of activity when orientation changes android
<p>I have an aacplayer app and I want to save the state of my activity when orientation changes from portrait to landscape. The TextViews do not appear to be empty, I tried to freeze my textview using this:</p> <pre><code>android:freezesText="true" </code></pre> <p>my manifest:</p> <pre><code>android:configChanges="orientation" </code></pre> <p>I also tried this:</p> <pre><code>@Override public void onConfigurationChanged(Configuration newConfig){ super.onConfigurationChanged(newConfig); setContentView(R.layout.main2); </code></pre> <p>So when orientation changes to landscape I can see my layout-land main2.xml, that works but my textview goes out and appears empty. Streaming music works great. I can listen to it when orientation changes, but the text inside textviews are gone each time I change the orientation of my device.</p> <p>What should I do to fix this so I can save the state?</p> <pre><code>@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); .... .... </code></pre> <p>Thank you very much.</p>
55,601,860
4
3
null
2012-10-23 02:20:00.39 UTC
11
2020-04-27 13:17:49.367 UTC
2016-05-23 21:40:30.917 UTC
null
2,291,915
null
626,611
null
1
21
android
51,588
<p>I use in <strong>KOTLIN</strong> static var / val : </p> <pre><code>class MyFragment : Fragment() { //all my code //access to static vars -&gt; MyStaticClass.hello } class MyStaticClass { companion object { var hello: String = "Static text" var number_static: Int = 0 } } </code></pre>
12,875,203
Is there a better way of getting parent node of XPath query result?
<p>Having markup like this:</p> <pre><code>&lt;div class="foo"&gt; &lt;div&gt;&lt;span class="a1"&gt;&lt;/span&gt;&lt;a href="..."&gt;...&lt;/a&gt;&lt;/div&gt; &lt;div&gt;&lt;span class="a2"&gt;&lt;/span&gt;&lt;a href="..."&gt;...&lt;/a&gt;&lt;/div&gt; &lt;div&gt;&lt;span class="a1"&gt;&lt;/span&gt;some text&lt;/div&gt; &lt;div&gt;&lt;span class="a3"&gt;&lt;/span&gt;some text&lt;/div&gt; &lt;/div&gt; </code></pre> <p>I am interested in getting all <code>&lt;a&gt;</code> and <code>some text</code> <strong>ONLY</strong> if adjacent <code>span</code> is of class <code>a1</code>. So at the end of the whole code my result should be <code>&lt;a&gt;</code> from first <code>div</code> and <code>some text</code> from third one. It'd be easy if <code>&lt;a&gt;</code> and <code>some text</code> were inside <code>span</code> or <code>div</code> would have <code>class</code> attribute, but no luck.</p> <p>What I am doing now is look for <code>span</code> with <code>a1</code> class:</p> <pre><code>//div[contains(@class,'foo')]/div/span[contains(@class,'a1')] </code></pre> <p>then I get its parent and do another <code>query()</code> with that parent as context node. This simply looks far from being efficient so the question clearly is if there is any better way to accomplish my goal?</p> <hr> <p><strong>THE ANSWER ADDENDUM</strong></p> <p>As per @MarcB <a href="https://stackoverflow.com/a/12875226/1235698">accepted answer</a>, the right query to use is:</p> <pre><code>//div[contains(@class,'foo')]/div/span[contains(@class,'a1')]/.. </code></pre> <p>but for <code>&lt;a&gt;</code> it may be better to use:</p> <pre><code>//div[contains(@class,'foo')]/div/span[contains(@class,'a1')]/../a </code></pre> <p>the get the <code>&lt;a&gt;</code> instead of its container.</p>
12,875,226
2
0
null
2012-10-13 17:32:45.253 UTC
3
2018-11-12 23:26:26.967 UTC
2018-11-12 23:26:26.967 UTC
null
1,235,698
null
1,235,698
null
1
25
xml|dom|xpath
38,171
<p>The nice thing about xpath queries is that you can essentially treat them like a file system path, so simply having</p> <pre><code>//div[contains(@class,'foo')]/div/span[contains(@class,'a1')]/.. ^^ </code></pre> <p>will find all your .a1 nodes that are below a .foo node, then move up one level to the a1 nodes' parents.</p>
12,644,075
How to set python variables to true or false?
<p>I want to set a variable in Python to true or false. But the words <code>true</code> and <code>false</code> are interpreted as undefined variables:</p> <pre><code>#!/usr/bin/python a = true; b = true; if a == b: print("same"); </code></pre> <p>The error I get:</p> <pre><code>a = true NameError: global name 'true' is not defined </code></pre> <p>What is the python syntax to set a variable true or false?</p> <p>Python 2.7.3</p>
12,644,128
4
0
null
2012-09-28 16:42:08.993 UTC
8
2020-07-13 19:57:15.03 UTC
2014-02-25 01:14:10.297 UTC
null
3,063,884
null
1,050,619
null
1
44
python-2.7|boolean|constants
267,601
<p>First to answer your question, you set a variable to true or false by assigning <a href="http://docs.python.org/2/library/constants.html#True"><code>True</code></a> or <a href="http://docs.python.org/2/library/constants.html#False"><code>False</code></a> to it:</p> <pre><code>myFirstVar = True myOtherVar = False </code></pre> <p>If you have a condition that is basically like this though:</p> <pre><code>if &lt;condition&gt;: var = True else: var = False </code></pre> <p>then it is much easier to simply assign the result of the condition directly:</p> <pre><code>var = &lt;condition&gt; </code></pre> <p>In your case:</p> <pre><code>match_var = a == b </code></pre>
12,909,905
Saving image to file
<p>I am working on a basic drawing application. I want the user to be able to save the contents of the image.</p> <p><img src="https://i.stack.imgur.com/M20lJ.png" alt="enter image description here"></p> <p>I thought I should use </p> <pre><code>System.Drawing.Drawing2D.GraphicsState img = drawRegion.CreateGraphics().Save(); </code></pre> <p>but this does not help me for saving to file.</p>
12,910,029
4
1
null
2012-10-16 07:50:58.79 UTC
8
2022-03-28 20:10:27.757 UTC
2015-03-17 12:23:46.48 UTC
null
119,775
null
1,673,776
null
1
46
c#|winforms|image|gdi+|save
234,790
<p>You could try to save the image using this approach</p> <pre><code>SaveFileDialog dialog=new SaveFileDialog(); if (dialog.ShowDialog()==DialogResult.OK) { int width = Convert.ToInt32(drawImage.Width); int height = Convert.ToInt32(drawImage.Height); using(Bitmap bmp = new Bitmap(width, height)) { drawImage.DrawToBitmap(bmp, new Rectangle(0, 0, width, height)); bmp.Save(dialog.FileName, ImageFormat.Jpeg); } } </code></pre>
12,650,261
Git says local branch is behind remote branch, but it's not
<p>Scenario: </p> <ol> <li>I make a new branch<br></li> <li>hack on it<br></li> <li>commit it<br></li> <li>push it<br></li> <li>hack on it some more<br></li> <li>commit again<br></li> <li>try to push again<br></li> </ol> <p>Git responds:</p> <blockquote> <p>Updates were rejected because the tip of your current branch is behind its remote counterpart. etc.</p> </blockquote> <p>I'm the only one hacking on this branch - no one else is touching it. The remote branch is actually <em>behind</em> the local branch. I shouldn't have to pull at all.</p> <p>(And if I do pull, Git reports conflicts between the two, and forces me to merge the branch into itself)</p> <p>Why is this (likely) happening? And how can I diagnose/fix it?</p> <p>To be clear, I'm not branching anywhere, and <em>no one else</em> is working on it:</p> <pre><code>Remote: Commit A -------- Commit B Local: Commit A -------- Commit B -------- Commit C </code></pre> <p>C is a straight continuation of B, no branching involved. But git thinks C is a branch of A: </p> <pre><code>Remote: Commit A -------- Commit B ------- Commit C / Local: Commit A -------- Commit B </code></pre> <p>It's not; it's a straight continuation of B.</p>
12,651,399
4
1
null
2012-09-29 05:41:29.857 UTC
31
2017-08-14 10:43:32.233 UTC
2013-08-25 21:37:37.397 UTC
null
9,314
null
1,325,172
null
1
87
git|git-push
174,180
<p>You probably did some history rewriting? Your local branch diverged from the one on the server. Run this command to get a better understanding of what happened:</p> <pre><code>gitk HEAD @{u} </code></pre> <p>I would strongly recommend you try to understand where this error is coming from. To fix it, simply run:</p> <pre><code>git push -f </code></pre> <p><strong>The <code>-f</code> makes this a “forced push” and <em>overwrites</em> the branch on the server. That is very dangerous when you are working in team.</strong> But since you are on your own and sure that your local state is correct this should be fine. You risk losing commit history if that is not the case.</p>
17,087,446
How to calculate perspective transform for OpenCV from rotation angles?
<p>I want to calculate perspective transform (a matrix for warpPerspective function) starting from angles of rotation and distance to the object.</p> <p>How to do that?</p> <p>I found the code somewhere on OE. Sample program is below:</p> <pre><code>#include &lt;opencv2/objdetect/objdetect.hpp&gt; #include &lt;opencv2/highgui/highgui.hpp&gt; #include &lt;opencv2/imgproc/imgproc.hpp&gt; #include &lt;iostream&gt; #include &lt;math.h&gt; using namespace std; using namespace cv; Mat frame; int alpha_int; int dist_int; int f_int; double w; double h; double alpha; double dist; double f; void redraw() { alpha = (double)alpha_int/1000.; //dist = 1./(dist_int+1); //dist = dist_int+1; dist = dist_int-50; f = f_int+1; cout &lt;&lt; "alpha = " &lt;&lt; alpha &lt;&lt; endl; cout &lt;&lt; "dist = " &lt;&lt; dist &lt;&lt; endl; cout &lt;&lt; "f = " &lt;&lt; f &lt;&lt; endl; // Projection 2D -&gt; 3D matrix Mat A1 = (Mat_&lt;double&gt;(4,3) &lt;&lt; 1, 0, -w/2, 0, 1, -h/2, 0, 0, 1, 0, 0, 1); // Rotation matrices around the X axis Mat R = (Mat_&lt;double&gt;(4, 4) &lt;&lt; 1, 0, 0, 0, 0, cos(alpha), -sin(alpha), 0, 0, sin(alpha), cos(alpha), 0, 0, 0, 0, 1); // Translation matrix on the Z axis Mat T = (Mat_&lt;double&gt;(4, 4) &lt;&lt; 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, dist, 0, 0, 0, 1); // Camera Intrisecs matrix 3D -&gt; 2D Mat A2 = (Mat_&lt;double&gt;(3,4) &lt;&lt; f, 0, w/2, 0, 0, f, h/2, 0, 0, 0, 1, 0); Mat m = A2 * (T * (R * A1)); cout &lt;&lt; "R=" &lt;&lt; endl &lt;&lt; R &lt;&lt; endl; cout &lt;&lt; "A1=" &lt;&lt; endl &lt;&lt; A1 &lt;&lt; endl; cout &lt;&lt; "R*A1=" &lt;&lt; endl &lt;&lt; (R*A1) &lt;&lt; endl; cout &lt;&lt; "T=" &lt;&lt; endl &lt;&lt; T &lt;&lt; endl; cout &lt;&lt; "T * (R * A1)=" &lt;&lt; endl &lt;&lt; (T * (R * A1)) &lt;&lt; endl; cout &lt;&lt; "A2=" &lt;&lt; endl &lt;&lt; A2 &lt;&lt; endl; cout &lt;&lt; "A2 * (T * (R * A1))=" &lt;&lt; endl &lt;&lt; (A2 * (T * (R * A1))) &lt;&lt; endl; cout &lt;&lt; "m=" &lt;&lt; endl &lt;&lt; m &lt;&lt; endl; Mat frame1; warpPerspective( frame, frame1, m, frame.size(), INTER_CUBIC | WARP_INVERSE_MAP); imshow("Frame", frame); imshow("Frame1", frame1); } void callback(int, void* ) { redraw(); } void main() { frame = imread("FruitSample_small.png", CV_LOAD_IMAGE_COLOR); imshow("Frame", frame); w = frame.size().width; h = frame.size().height; createTrackbar("alpha", "Frame", &amp;alpha_int, 100, &amp;callback); dist_int = 50; createTrackbar("dist", "Frame", &amp;dist_int, 100, &amp;callback); createTrackbar("f", "Frame", &amp;f_int, 100, &amp;callback); redraw(); waitKey(-1); } </code></pre> <p>But unfortunately, this transform does something strange</p> <p><img src="https://i.stack.imgur.com/orhsl.jpg" alt="enter image description here"></p> <p>Why? What is another half of image above when <code>alpha&gt;0</code>? And how to rotate around other axes? Why <code>dist</code> works so strange?</p>
20,089,412
3
5
null
2013-06-13 12:45:27.223 UTC
18
2021-07-09 18:03:08.193 UTC
2013-06-13 14:35:39.15 UTC
null
1,171,620
null
1,171,620
null
1
22
c++|math|opencv|transformation|perspectivecamera
24,336
<p>I have had the luxury of time to think out both math and code. I did this a year or two ago. I even typeset this in beautiful LaTeX.</p> <p>I intentionally designed my solution so that no matter what rotation angles are provided, the entire input image is contained, centered, within the output frame, which is otherwise black. </p> <p>The arguments to my <code>warpImage</code> function are rotation angles in all 3 axes, the scale factor and the vertical field-of-view angle. The function outputs the warp matrix, the output image and the corners of the source image within the output image.</p> <h2>The Math (for code, look below)</h2> <p><img src="https://i.stack.imgur.com/bSP0W.jpg" alt="Page 1"> <img src="https://i.stack.imgur.com/7a9Jk.jpg" alt="enter image description here"></p> <p>The LaTeX source code is <a href="https://www.dropbox.com/s/72wngnybqtfs2ib/TaylorMath.zip?dl=0" rel="noreferrer">here</a>. </p> <h2>The Code (for math, look above)</h2> <p>Here is a test application that warps the camera</p> <pre><code>#include &lt;opencv2/core/core.hpp&gt; #include &lt;opencv2/imgproc/imgproc.hpp&gt; #include &lt;opencv2/highgui/highgui.hpp&gt; #include &lt;math.h&gt; using namespace cv; using namespace std; static double rad2Deg(double rad){return rad*(180/M_PI);}//Convert radians to degrees static double deg2Rad(double deg){return deg*(M_PI/180);}//Convert degrees to radians void warpMatrix(Size sz, double theta, double phi, double gamma, double scale, double fovy, Mat&amp; M, vector&lt;Point2f&gt;* corners){ double st=sin(deg2Rad(theta)); double ct=cos(deg2Rad(theta)); double sp=sin(deg2Rad(phi)); double cp=cos(deg2Rad(phi)); double sg=sin(deg2Rad(gamma)); double cg=cos(deg2Rad(gamma)); double halfFovy=fovy*0.5; double d=hypot(sz.width,sz.height); double sideLength=scale*d/cos(deg2Rad(halfFovy)); double h=d/(2.0*sin(deg2Rad(halfFovy))); double n=h-(d/2.0); double f=h+(d/2.0); Mat F=Mat(4,4,CV_64FC1);//Allocate 4x4 transformation matrix F Mat Rtheta=Mat::eye(4,4,CV_64FC1);//Allocate 4x4 rotation matrix around Z-axis by theta degrees Mat Rphi=Mat::eye(4,4,CV_64FC1);//Allocate 4x4 rotation matrix around X-axis by phi degrees Mat Rgamma=Mat::eye(4,4,CV_64FC1);//Allocate 4x4 rotation matrix around Y-axis by gamma degrees Mat T=Mat::eye(4,4,CV_64FC1);//Allocate 4x4 translation matrix along Z-axis by -h units Mat P=Mat::zeros(4,4,CV_64FC1);//Allocate 4x4 projection matrix //Rtheta Rtheta.at&lt;double&gt;(0,0)=Rtheta.at&lt;double&gt;(1,1)=ct; Rtheta.at&lt;double&gt;(0,1)=-st;Rtheta.at&lt;double&gt;(1,0)=st; //Rphi Rphi.at&lt;double&gt;(1,1)=Rphi.at&lt;double&gt;(2,2)=cp; Rphi.at&lt;double&gt;(1,2)=-sp;Rphi.at&lt;double&gt;(2,1)=sp; //Rgamma Rgamma.at&lt;double&gt;(0,0)=Rgamma.at&lt;double&gt;(2,2)=cg; Rgamma.at&lt;double&gt;(0,2)=-sg;Rgamma.at&lt;double&gt;(2,0)=sg; //T T.at&lt;double&gt;(2,3)=-h; //P P.at&lt;double&gt;(0,0)=P.at&lt;double&gt;(1,1)=1.0/tan(deg2Rad(halfFovy)); P.at&lt;double&gt;(2,2)=-(f+n)/(f-n); P.at&lt;double&gt;(2,3)=-(2.0*f*n)/(f-n); P.at&lt;double&gt;(3,2)=-1.0; //Compose transformations F=P*T*Rphi*Rtheta*Rgamma;//Matrix-multiply to produce master matrix //Transform 4x4 points double ptsIn [4*3]; double ptsOut[4*3]; double halfW=sz.width/2, halfH=sz.height/2; ptsIn[0]=-halfW;ptsIn[ 1]= halfH; ptsIn[3]= halfW;ptsIn[ 4]= halfH; ptsIn[6]= halfW;ptsIn[ 7]=-halfH; ptsIn[9]=-halfW;ptsIn[10]=-halfH; ptsIn[2]=ptsIn[5]=ptsIn[8]=ptsIn[11]=0;//Set Z component to zero for all 4 components Mat ptsInMat(1,4,CV_64FC3,ptsIn); Mat ptsOutMat(1,4,CV_64FC3,ptsOut); perspectiveTransform(ptsInMat,ptsOutMat,F);//Transform points //Get 3x3 transform and warp image Point2f ptsInPt2f[4]; Point2f ptsOutPt2f[4]; for(int i=0;i&lt;4;i++){ Point2f ptIn (ptsIn [i*3+0], ptsIn [i*3+1]); Point2f ptOut(ptsOut[i*3+0], ptsOut[i*3+1]); ptsInPt2f[i] = ptIn+Point2f(halfW,halfH); ptsOutPt2f[i] = (ptOut+Point2f(1,1))*(sideLength*0.5); } M=getPerspectiveTransform(ptsInPt2f,ptsOutPt2f); //Load corners vector if(corners){ corners-&gt;clear(); corners-&gt;push_back(ptsOutPt2f[0]);//Push Top Left corner corners-&gt;push_back(ptsOutPt2f[1]);//Push Top Right corner corners-&gt;push_back(ptsOutPt2f[2]);//Push Bottom Right corner corners-&gt;push_back(ptsOutPt2f[3]);//Push Bottom Left corner } } void warpImage(const Mat &amp;src, double theta, double phi, double gamma, double scale, double fovy, Mat&amp; dst, Mat&amp; M, vector&lt;Point2f&gt; &amp;corners){ double halfFovy=fovy*0.5; double d=hypot(src.cols,src.rows); double sideLength=scale*d/cos(deg2Rad(halfFovy)); warpMatrix(src.size(),theta,phi,gamma, scale,fovy,M,&amp;corners);//Compute warp matrix warpPerspective(src,dst,M,Size(sideLength,sideLength));//Do actual image warp } int main(void){ int c = 0; Mat m, disp, warp; vector&lt;Point2f&gt; corners; VideoCapture cap(0); while(c != 033 &amp;&amp; cap.isOpened()){ cap &gt;&gt; m; warpImage(m, 5, 50, 0, 1, 30, disp, warp, corners); imshow("Disp", disp); c = waitKey(1); } } </code></pre>
16,782,498
Looping Animation of text color change using CSS3
<p>I have text that I want to animate. Not on hover, for example but continually changing slowly from white to red and then back to white again.</p> <p>Here is my CSS code so far:</p> <pre><code>#countText{ color: #eeeeee; font-family: "League Gothic", Impact, sans-serif; line-height: 0.9em; letter-spacing: 0.02em; text-transform: uppercase; text-shadow: 0px 0px 6px ; font-size: 210px; } </code></pre>
16,782,559
3
3
null
2013-05-28 01:18:49.22 UTC
7
2022-04-18 08:55:08.1 UTC
2017-01-25 02:32:41.057 UTC
null
315,024
null
2,055,611
null
1
32
css|transition|css-animations
119,742
<p>Use <code>keyframes</code> and <code>animation</code> property</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>p { animation: color-change 1s infinite; } @keyframes color-change { 0% { color: red; } 50% { color: blue; } 100% { color: red; } }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;p&gt;Lorem ipsum dolor sit amet, consectetur adipisicing elit. Qui ad quos autem beatae nulla in.&lt;/p&gt;</code></pre> </div> </div> </p> <p><strong>CSS With Prefixes</strong></p> <pre><code>p { -webkit-animation: color-change 1s infinite; -moz-animation: color-change 1s infinite; -o-animation: color-change 1s infinite; -ms-animation: color-change 1s infinite; animation: color-change 1s infinite; } @-webkit-keyframes color-change { 0% { color: red; } 50% { color: blue; } 100% { color: red; } } @-moz-keyframes color-change { 0% { color: red; } 50% { color: blue; } 100% { color: red; } } @-ms-keyframes color-change { 0% { color: red; } 50% { color: blue; } 100% { color: red; } } @-o-keyframes color-change { 0% { color: red; } 50% { color: blue; } 100% { color: red; } } @keyframes color-change { 0% { color: red; } 50% { color: blue; } 100% { color: red; } } </code></pre>
16,937,459
Whats the difference between UInt8 and uint8_t
<p>What is the differnce between <code>UInt8</code> and <code>uint8_t</code>, or <code>UInt16</code> and <code>unit16_t</code>?</p> <p>What does the <code>_t</code> imply?</p>
16,937,843
3
2
null
2013-06-05 10:24:42.193 UTC
10
2017-05-29 15:27:31.007 UTC
2017-05-29 15:27:31.007 UTC
null
1,267,663
null
1,845,029
null
1
67
c++|objective-c|c
85,101
<p>In C99 the available basic integer types (the ones without _t) were deemed insufficient, because their actual sizes may vary across different systems. </p> <p>So, the C99 standard includes definitions of several new integer types to enhance the portability of programs. The new types are especially useful in embedded environments.</p> <p>All of the new types are suffixed with a _t and are guaranteed to be defined uniformly across all systems.</p> <p>For more info see the <a href="http://en.wikipedia.org/wiki/Stdint.h#stdint.h" rel="noreferrer">fixed-width integer types section of the wikipedia article on Stdint</a>. </p>
16,699,877
Rails optional belongs_to
<p>I'm writing a Rails frontend for inventory management. I want users to be able to register products, so I have:</p> <pre><code>class User &lt; ActiveRecord::Base has_many :products # &lt;snip&gt; end </code></pre> <p>and</p> <pre><code>class Product &lt; ActiveRecord::Base belongs_to :user # &lt;snip&gt; end </code></pre> <p>The problem is that products are created prior to being registered by a user. That is, it's perfectly acceptable to call <code>Product.create</code> and just have it set the <code>user_id</code> to <code>nil</code>. As you can imagine, though, Rails doesn't support this out of the box:</p> <pre><code>&gt; Product.create! (0.3ms) SELECT COUNT(*) FROM "products" WHERE "products"."type" IN ('Product') (0.1ms) begin transaction (0.1ms) rollback transaction ActiveRecord::RecordInvalid: Validation failed: User can't be blank from ~/.rvm/gems/ruby-2.0.0-p0/gems/activerecord-3.2.13/lib/active_record/validations.rb:56:in `save!' </code></pre> <p>I've thought about a bunch of kludgey workarounds, the most appealing of which is to have a <code>NullUser</code> subclassing <code>User</code> and use that to create products. But that still seems like a hack. What's the Rails Way with this?</p> <p>Thanks.</p> <hr> <p>The relevant migration:</p> <pre><code>class AddUseridToProducts &lt; ActiveRecord::Migration def change add_column :products, :user_id, :integer end end </code></pre> <p>and later:</p> <pre><code>class Changeuseridtobeoptionalforproducts &lt; ActiveRecord::Migration def change change_column :products, :user_id, :integer, null: true end end </code></pre>
16,700,016
3
1
null
2013-05-22 19:14:46.15 UTC
7
2019-05-05 19:41:48.003 UTC
2013-05-22 19:23:09.357 UTC
null
220,529
null
220,529
null
1
77
ruby-on-rails|ruby|activerecord
59,414
<p>Do you have a validation that requires user be present? If so, remove that.</p>
16,607,003
qmake: could not find a Qt installation of ''
<p>I have a software in ubuntu that requires me to run qmake to generate the Makefile.</p> <p>However, running qmake gives back this error,</p> <pre><code>qmake: could not find a Qt installation of '' </code></pre> <p>I have installed what I thought to be the required packages using,</p> <pre><code>sudo apt-get install qt4-qmake sudo apt-get install qt5-qmake </code></pre> <p>But the error didn't go away.</p> <p>Any help on this would be gladly appreciated!</p>
18,814,086
11
3
null
2013-05-17 10:38:53.77 UTC
18
2022-09-10 20:48:24.89 UTC
2016-09-16 20:42:01.88 UTC
null
1,248,073
null
1,248,073
null
1
158
qt|ubuntu|qmake
252,186
<p><code>sudo apt-get install qt5-default</code> works for me.</p> <pre><code>$ aptitude show qt5-default</pre></code> <p>tells that</p> <blockquote> <p>This package sets Qt 5 to be the default Qt version to be used when using development binaries like qmake. It provides a default configuration for qtchooser, but does not prevent alternative Qt installations from being used.</p> </blockquote>
10,154,476
ActionBarCompat - how to use it
<p>I'm trying to use ActionBarCompat on my own project. I've already opened the sample project (http://developer.android.com/resources/samples/ActionBarCompat/index.html), But I don't know how to implement it on my own.</p> <p>I can't find any tutorial of some kind. Should I make this project as a library? Can someone give me some directions, please.</p>
10,317,516
2
2
null
2012-04-14 14:47:09.743 UTC
8
2013-07-28 00:44:09.447 UTC
2012-12-29 12:23:00.817 UTC
null
165,674
null
1,263,997
null
1
11
android|android-actionbar|android-actionbar-compat
21,991
<p>As for implementation, just stick to the sample code provided under the <code>MainActivity.java</code> class. You can find it <a href="http://developer.android.com/resources/samples/ActionBarCompat/src/com/example/android/actionbarcompat/MainActivity.html" rel="noreferrer">here</a> or under <code>&lt;your local android-sdks folder&gt;/samples/android-15/ActionBarCompat/src/com/example/android/actionbarcompat/MainActivity.java</code>. In general, all you need to do is the following:</p> <ol> <li>Code a menu resource where you declare the items for the action bar (See <a href="http://developer.android.com/resources/samples/ActionBarCompat/res/menu/main.html" rel="noreferrer">http://developer.android.com/resources/samples/ActionBarCompat/res/menu/main.html</a>)</li> <li>Code an Activity that extends <code>ActionBarActivity</code> </li> <li>Override <code>onCreateOptionsMenu()</code> so that it inflates the menu you coded in step #1</li> <li>Override <code>onOptionsItemSelected()</code> so that you handle the event when the user taps any of the ActionBar items you defined in step #1.</li> </ol> <p>I think it makes sense to build an Android Library project out of the ActionBarCompat code; then you can just reference it from your custom Android project. Remember it's licensed under the <em>Apache License, Version 2.0</em>.</p>
9,904,080
How to get time and date from datetime stamp in PHP?
<p>I have one string like <code>8/29/2011 11:16:12 AM</code>. I want to save in variable like <code>$dat = '8/29/2011'</code> and <code>$tme = '11:16:12 AM'</code></p> <p>How to achieve that? Can you give me example?</p>
9,904,146
7
0
null
2012-03-28 08:51:33.477 UTC
5
2020-07-22 12:34:04.817 UTC
2020-07-22 12:34:04.817 UTC
null
4,217,744
null
1,153,176
null
1
42
php|date
105,211
<p>E.g.</p> <pre><code>&lt;?php $s = '8/29/2011 11:16:12 AM'; $dt = new DateTime($s); $date = $dt-&gt;format('m/d/Y'); $time = $dt-&gt;format('H:i:s'); echo $date, ' | ', $time; </code></pre> <p>see <a href="http://docs.php.net/class.datetime">http://docs.php.net/class.datetime</a></p> <hr> <p>edit: To keep the AM/PM format use</p> <pre><code>$time = $dt-&gt;format('h:i:s A'); </code></pre>
9,869,870
How to get a single column's values into an array
<p>Right now I'm doing something like this to select a single column of data:</p> <pre><code>points = Post.find_by_sql("select point from posts") </code></pre> <p>Then passing them to a method, I'd like my method to remain agnostic, and now have to call hash.point from within my method. How can I quickly convert this into an array and pass the data set to my method, or is there a better way? </p>
9,872,725
4
0
null
2012-03-26 09:43:09.61 UTC
25
2018-03-23 16:19:46.257 UTC
null
null
null
null
1,697,802
null
1
84
ruby-on-rails|ruby|ruby-on-rails-3
79,267
<p>In Rails 3.2 there is a <a href="http://apidock.com/rails/ActiveRecord/Calculations/pluck" rel="noreferrer">pluck method</a> for this</p> <p>Just like this:</p> <pre><code>Person.pluck(:id) # SELECT people.id FROM people Person.pluck(:role).uniq # unique roles from array of people Person.distinct.pluck(:role) # SELECT DISTINCT role FROM people SQL Person.where(:confirmed =&gt; true).limit(5).pluck(:id) </code></pre> <p><a href="https://stackoverflow.com/questions/39575398/rails-uniq-vs-distinct">Difference between uniq and distinct</a></p>
9,978,400
Git: auto pull from repository?
<p>Is there any way to set up git such that it listens for updates from a remote repo and will pull whenever something changes? The use case is I want to deploy a web app using git (so I get version control of the deployed application) but want to put the "central" git repo on Github rather than on the web server (Github's interface is just soooo nice). </p> <p>Has anyone gotten this working? How does Heroku do it? My Google-fu is failing to give me any relevant results.</p>
9,978,442
6
0
null
2012-04-02 14:38:11.163 UTC
15
2022-08-12 14:36:01.523 UTC
null
null
null
null
871,202
null
1
107
git|deployment
105,184
<p>Git has "hooks", actions that can be executed after other actions. What you seem to be looking for is "post-receive hook". In the github admin, you can set up a post-receive url that will be hit (with a payload containing data about what was just pushed) everytime somebody pushes to your repo.</p> <p>For what it's worth, I don't think auto-pull is a good idea -- what if something wrong was pushed to your branch ? I'd use a tool like <code>capistrano</code> (or an equivalent) for such things.</p>
9,695,902
How to break out of nested loops?
<p>If I use a <code>break</code> statement, it will only break inner loop and I need to use some flag to break the outer loop. But if there are many nested loops, the code will not look good.</p> <p>Is there any other way to break all of the loops? (Please don't use <code>goto stmt</code>.)</p> <pre><code>for (int i = 0; i &lt; 1000; i++) { for (int j = 0; j &lt; 1000; j++) { if (condition) { // both of the loops need to break and control will go to stmt2 } } } stmt2 </code></pre>
9,695,931
15
3
null
2012-03-14 04:23:27.543 UTC
44
2022-07-11 07:03:26.03 UTC
2022-07-11 07:03:26.03 UTC
null
1,564,946
null
966,379
null
1
127
c|nested-loops|break
255,334
<p>Use:</p> <pre><code>if (condition) { i = j = 1000; break; } </code></pre>
8,225,934
Exposing a C++ class instance to a python embedded interpreter
<p>I am looking for a simple way to expose a C++ class instance to a python embedded interpreter.</p> <ul> <li>I have a C++ library. This library is wrapped (using swig for the moment) and I am able to use it from the python interpreter</li> <li>I have a C++ main program which instanciates a Foo class from my library and embeds a python interpreter</li> </ul> <p>I would like to expose my C++ world instance of Foo to the python world (and seen as a Foo class).</p> <p><strong>Is this possible, if so, how?</strong></p> <p>I think it's almost like in the first answer of : <a href="https://stackoverflow.com/questions/5055443/boost-python-how-to-pass-a-c-class-instance-to-a-python-class">boost::python::ptr or PyInstance_New usage</a></p> <p><strong>I guess this means I should use <code>boost.Python</code> to wrap my library?</strong></p> <p>My only goal is to manipulate my C++ instance of Foo in the embedded python interpreter (not sure that it can be done with the previous method).</p> <p>In fact, I already have exposed my Foo class to python (with swig).</p> <p><strong>What I have:</strong></p> <p><em>my Foo class:</em></p> <pre><code>class Foo{...}; </code></pre> <p><em>my wrapped library (including the Foo class) exposed to python:</em> so I can start the python interpreter and do something like this :</p> <pre><code>import my_module foo=my_modulde.Foo() </code></pre> <p><strong>What I want:</strong></p> <p>Having a C++ main program which embeds a python interpreter and manipulates C++ world variables.</p> <pre><code>int main(int argc, char **argv) { Foo foo; // instanciates foo Py_Initialize(); Py_Main(argc, argv); // starts the python interpreter // and manipulates THE foo instance in it Py_Finalize(); return 0; } </code></pre>
8,226,377
3
0
null
2011-11-22 11:19:51.41 UTC
9
2022-05-04 04:18:21.58 UTC
2022-05-04 04:18:21.58 UTC
null
1,536,976
null
1,044,695
null
1
21
c++|python|boost|swig|boost-python
7,194
<p><a href="http://www.boost.org/doc/libs/release/libs/python/doc/" rel="noreferrer">Boost python</a> Allows you to expose c++ classes to python in a very tightly integrated way - you can even wrap them so that you can derive python classes from your c++ ones, and have virtual methods resolved to the python overrides.</p> <p>The <a href="http://www.boost.org/doc/libs/release/libs/python/doc/tutorial/doc/html/index.html" rel="noreferrer">boost python tutorial</a> is a good place to start.</p> <hr> <p><sub>edit:</sub></p> <p>You can create a c++ object and pass a reference to it to an internal python interpreter like this:</p> <pre><code>#include &lt;boost/shared_ptr.hpp&gt; #include &lt;boost/make_shared.hpp&gt; #include &lt;boost/python.hpp&gt; #include &lt;string&gt; #include &lt;iostream&gt; namespace bp = boost::python; struct Foo{ Foo(){} Foo(std::string const&amp; s) : m_string(s){} void doSomething() { std::cout &lt;&lt; "Foo:" &lt;&lt; m_string &lt;&lt; std::endl; } std::string m_string; }; typedef boost::shared_ptr&lt;Foo&gt; foo_ptr; BOOST_PYTHON_MODULE(hello) { bp::class_&lt;Foo, foo_ptr&gt;("Foo") .def("doSomething", &amp;Foo::doSomething) ; }; int main(int argc, char **argv) { Py_Initialize(); try { PyRun_SimpleString( "a_foo = None\n" "\n" "def setup(a_foo_from_cxx):\n" " print 'setup called with', a_foo_from_cxx\n" " global a_foo\n" " a_foo = a_foo_from_cxx\n" "\n" "def run():\n" " a_foo.doSomething()\n" "\n" "print 'main module loaded'\n" ); foo_ptr a_cxx_foo = boost::make_shared&lt;Foo&gt;("c++"); inithello(); bp::object main = bp::object(bp::handle&lt;&gt;(bp::borrowed( PyImport_AddModule("__main__") ))); // pass the reference to a_cxx_foo into python: bp::object setup_func = main.attr("setup"); setup_func(a_cxx_foo); // now run the python 'main' function bp::object run_func = main.attr("run"); run_func(); } catch (bp::error_already_set) { PyErr_Print(); } Py_Finalize(); return 0; } </code></pre>
8,200,853
How can I know if the request to the servlet was executed using HTTP or HTTPS?
<p>I wrote a servlet in Java and I would like to know if the request to that servlet was executed using HTTP or HTTPS.</p> <p>I thought I can use <code>request.getProtocol()</code> but it returns HTTP/1.1 on both methods.</p> <p>Any ideas?</p>
8,208,910
3
0
null
2011-11-20 10:15:55.08 UTC
23
2015-04-27 17:33:43.91 UTC
2015-04-27 17:33:43.91 UTC
null
3,885,376
null
80,932
null
1
73
java|servlets|ssl|https|http-protocols
53,152
<p><em><strong>HttpSerlvetRequest.isSecure()</em></strong> is the answer. The ServletContainer is responsible for returning true in the following cases:</p> <ul> <li>If the ServletContainer can itself accept requests on https.</li> <li>If there is a LoadBalancer in front of ServletContainer. And , the LoadBlancer has got the request on <strong>https</strong> and has dispatched the same to the ServletContainer on <strong>plain http</strong>. In this case, the LoadBalancer sends <strong><em>X-SSL-Secure : true</em></strong> header to the ServletContainer, which should be honored. </li> </ul> <p>The Container should also make this request attributes available when the request is received on <strong>https</strong>:</p> <ul> <li>javax.servlet.http.sslsessionid</li> <li>javax.servlet.request.key_size</li> <li>javax.servlet.request.X509Certificate</li> </ul>
11,691,456
SSIS with variable excel connection manager
<p>I am trying to do automatic package execution with a WMI Event Watcher Task within SSIS. The functionality I want is automatic package execution when excel files are dropped into a certain folder. However, these excel files will be the connection managers for populating a database.</p> <p>Currently SSIS will not allow me to do this because my excel connection manager does not have a path when I run the program, and only exists once the files are dropped in the folder.</p> <p>Is there a way for variable excel connection managers or the value of the connection string to be a variable?</p> <p>Also, how do I implement the usage of this variable in an expression?</p>
11,722,371
2
0
null
2012-07-27 15:57:20.323 UTC
null
2017-07-13 10:29:58.317 UTC
2017-07-13 10:29:58.317 UTC
null
1,000,551
null
1,104,823
null
1
7
excel|variables|ssis|connection
46,263
<p>You can use a variable for the connection string of you excel source: </p> <ol> <li>Click on your Connection manager of your excel source</li> <li>In properties window, add an expression(1) ConnectionString(2) and assign a variable(3)</li> </ol> <p><img src="https://i.stack.imgur.com/N3wBl.jpg" alt="enter image description here"></p> <p>There are alot of different things you can do with variables. They are used alot in combination with <code>for each loop containers</code> and <code>file system tasks</code>. Your normally do something like this</p> <ol> <li>create a variable in variable window</li> <li>Set a static value or one that gets changed during the package flow</li> <li>Map the variable to an expression</li> </ol> <p>There are alot howtos on the web, maybe have a look at this to get warm with it:</p> <p><a href="http://www.simple-talk.com/sql/ssis/working-with-variables-in-sql-server-integration-services/" rel="noreferrer">http://www.simple-talk.com/sql/ssis/working-with-variables-in-sql-server-integration-services/</a></p> <p><a href="http://www.rafael-salas.com/2007/03/ssis-file-system-task-move-and-rename.html" rel="noreferrer">http://www.rafael-salas.com/2007/03/ssis-file-system-task-move-and-rename.html</a></p>
11,550,797
Playing youtube video in Android app
<p>In my Android app I'd like the user to tap an image once, have a youtube video play automatically and when the video is done the user is immediately returned to the app. <strong>What's the best way to do this in Android?</strong></p> <p>I tried using intents. This works in that the video comes up on what I think is a youtube web page. However playing the video requires another tap. I'd like to avoid this if possible.</p> <p>I tried the whole MediaPlayer, prepareAsync, setOnPreparedListener and never got it to work. For some reason onPrepared was never called. No exceptions were thrown. I'm using the emulator to test and I'm new to Android so I'm not sure if the behavior will be different on physical devices.</p> <p>I got this working well on iOS by getting creative with webviews. I'm hoping it's more straightforward on Android. The <a href="http://developer.android.com/guide/topics/media/mediaplayer.html" rel="noreferrer">docs</a> sure make it sound straight forward.</p> <p>Cheers!</p>
11,551,203
1
0
null
2012-07-18 21:41:51.013 UTC
9
2013-08-08 21:12:11.193 UTC
null
null
null
null
879,664
null
1
8
android|android-intent|youtube|android-mediaplayer
22,241
<p><strong>Update:</strong> Everything below is still correct, but the <a href="https://developers.google.com/youtube/android/player/" rel="nofollow noreferrer">official YouTube API for Android</a> is now available.</p> <p>By far, the easiest way to play a YouTube video on Android is to simply fire an Intent to launch the native Android YouTube app. Of course, this will fail if you are not on a certified Google device, that doesn't have the complement of Google apps. (The Kindle Fire is probably the biggest example of such a device). The problem with this approach is that the user will not automatically wind up back at your app when the video finishes; they have to press the Back button, and at this point you've probably lost them.</p> <p>As a second option, you can use the MediaPlayer API to play YouTube videos. But there are three caveats with this approach:</p> <p>1) You need to make a call to YouTube's GData webservice API, passing it the ID of the video. You'll get back a ton of metadata, along with it the RTSP URL that you should pass to MediaPlayer to play back an H.264-encoded stream. This is probably the reason why your attempt to use MediaPlayer failed; you probably weren't using the correct URL to stream.</p> <p>2) The GData/MediaPlayer approach will only play back low-resolution content (176x144 or similar). This is a deliberate decision on the part of YouTube, to prevent theft of content. Of course, this doesn't provide a very satisfactory experience. There are back-door hacks to get higher resolution streams, but they aren't supported on all releases of Android and using them is a violation of YouTube's terms of service.</p> <p>3) The RTSP streams can be blocked by some internal networks/firewalls, so this approach may not work for all users.</p> <p>The third option is to embed a WebView in your application. There two approaches you can take here:</p> <p>1) You can embed a Flash object and run the standard desktop Flash player for YouTube. You can even use the Javascript API to control the player, and relay events back to the native Android app. This approach works well, but unfortunately Flash is being deprecated on the Android platform, and will not work for Android 4.1 and later.</p> <p>2) You can embed a <code>&lt;video&gt;</code> tag to play YouTube via HTML5. Support for this varies between various releases of Android. It works well on Android 4.0 and later; earlier releases have somewhat spotty HTML5 <code>&lt;video&gt;</code> support. So, depending upon what releases of Android your application must support, you can take a hybrid approach of embedding HTML5 on Android 4.x or later, and Flash for all earlier versions of Android.</p> <p>There are several threads here on StackOverflow about using HTML5 to play YouTube video; none of them really describe the entire process you must follow in one place. Here's links to a few of them:</p> <p><a href="https://stackoverflow.com/questions/9565533/android-how-to-play-youtube-video-in-webview?rq=1">Android - How to play Youtube video in WebView?</a></p> <p><a href="https://stackoverflow.com/questions/3458765/how-to-embed-a-youtube-clip-in-a-webview-on-android">How to embed a YouTube clip in a WebView on Android</a></p> <p><a href="https://stackoverflow.com/questions/6323169/play-youtube-html5-embedded-video-in-android-webview">Play Youtube HTML5 embedded Video in Android WebView</a></p> <p>All of this will get dramatically easier in the weeks/months to come; at Google I/O 2012, they presented/demoed a new YouTube API for Android that will support direct embedding of YouTube content in your application, with full support back to Android 2.2 (about 95% of the Android userbase as of this writing). It can't arrive fast enough.</p>
11,863,503
Whitespaces in java
<p>What are kinds of whitespaces in Java? I need to check in my code if the text contains any whitespaces.</p> <p>My code is:</p> <pre><code>if (text.contains(" ") || text.contains("\t") || text.contains("\r") || text.contains("\n")) { //code goes here } </code></pre> <p>I already know about <code>\n</code> ,<code>\t</code> ,<code>\r</code> and <code>space</code>.</p>
11,863,572
8
2
null
2012-08-08 11:26:01.8 UTC
5
2016-12-01 11:10:51.25 UTC
2015-12-26 13:53:52.853 UTC
null
3,824,919
null
1,488,740
null
1
17
java|whitespace
143,410
<pre><code>boolean containsWhitespace = false; for (int i = 0; i &lt; text.length() &amp;&amp; !containsWhitespace; i++) { if (Character.isWhitespace(text.charAt(i)) { containsWhitespace = true; } } return containsWhitespace; </code></pre> <p>or, using Guava,</p> <pre><code>boolean containsWhitespace = CharMatcher.WHITESPACE.matchesAnyOf(text); </code></pre>
11,915,255
Why are super columns in Cassandra no longer favoured?
<p>I have read in the latest release that super columns are not desirable due to "performance issues", but no where is this explained.</p> <p>Then I read articles such as <a href="http://pkghosh.wordpress.com/2011/03/02/cassandra-secondary-index-patterns/">this one</a> that give wonderful indexing patterns using super columns.</p> <p>This leave me with no idea of what is <strong>currently</strong> the best way to do indexing in Cassandra.</p> <ol> <li>What are the performance issues of super columns?</li> <li>Where can I find <strong>current</strong> best practices for indexing?</li> </ol>
11,918,557
1
1
null
2012-08-11 13:51:44.013 UTC
12
2017-11-08 18:38:10.053 UTC
2012-08-11 14:07:13.903 UTC
null
401,584
null
401,584
null
1
30
cassandra|indexing|database-indexes|super-columns
19,450
<p>Super columns suffer from a number of problems, not least of which is that it is necessary for Cassandra to deserialze all of the sub-columns of a super column when querying (even if the result will only return a small subset). As a result, there is a practical limit to the number of sub-columns per super column that can be stored before performance suffers.</p> <p>In theory, this could be fixed within Cassandra by properly indexing sub-columns, but consensus is that composite columns are a better solution, and they work without the added complexity.</p> <p>The easiest way to make use of composite columns is to take advantage of the abstraction that <a href="http://cassandra.apache.org/doc/cql3/CQL.html" rel="nofollow noreferrer">CQL 3</a> provides. Consider the following schema:</p> <pre><code>CREATE TABLE messages( username text, sent_at timestamp, message text, sender text, PRIMARY KEY(username, sent_at) ); </code></pre> <p>Username here is the row key, but we've used a PRIMARY KEY definition which creates a grouping of row key and the sent_at column. This is important as it has the effect of indexing that attribute.</p> <pre><code>INSERT INTO messages (username, sent_at, message, sender) VALUES ('bob', '2012-08-01 11:42:15', 'Hi', 'alice'); INSERT INTO messages (username, sent_at, message, sender) VALUES ('alice', '2012-08-01 11:42:37', 'Hi yourself', 'bob'); INSERT INTO messages (username, sent_at, message, sender) VALUES ('bob', '2012-08-01 11:43:00', 'What are you doing later?', 'alice'); INSERT INTO messages (username, sent_at, message, sender) VALUES ('bob', '2012-08-01 11:47:14', 'Bob?', 'alice'); </code></pre> <p>Behind the scenes Cassandra will store the above inserted data something like this:</p> <pre><code>alice: (2012-08-01 11:42:37,message): Hi yourself, (2012-08-01 11:42:37,sender): bob bob: (2012-08-01 11:42:15,message): Hi, (2012-08-01 11:42:15,sender): alice, (2012-08-01 11:43:00,message): What are you doing later?, (2012-08-01 11:43:00,sender): alice (2012-08-01 11:47:14,message): Bob?, (2012-08-01 11:47:14,sender): alice </code></pre> <p>But using CQL 3, we can query the "row" using a sent_at predicate, and get back a tabular result set.</p> <pre><code>SELECT * FROM messages WHERE username = 'bob' AND sent_at &gt; '2012-08-01'; username | sent_at | message | sender ----------+--------------------------+---------------------------+-------- bob | 2012-08-01 11:43:00+0000 | What are you doing later? | alice bob | 2012-08-01 11:47:14+0000 | Bob? | alice </code></pre>
11,773,115
Parallel for loop in openmp
<p>I'm trying to parallelize a very simple for-loop, but this is my first attempt at using openMP in a long time. I'm getting baffled by the run times. Here is my code:</p> <pre><code>#include &lt;vector&gt; #include &lt;algorithm&gt; using namespace std; int main () { int n=400000, m=1000; double x=0,y=0; double s=0; vector&lt; double &gt; shifts(n,0); #pragma omp parallel for for (int j=0; j&lt;n; j++) { double r=0.0; for (int i=0; i &lt; m; i++){ double rand_g1 = cos(i/double(m)); double rand_g2 = sin(i/double(m)); x += rand_g1; y += rand_g2; r += sqrt(rand_g1*rand_g1 + rand_g2*rand_g2); } shifts[j] = r / m; } cout &lt;&lt; *std::max_element( shifts.begin(), shifts.end() ) &lt;&lt; endl; } </code></pre> <p>I compile it with </p> <pre><code>g++ -O3 testMP.cc -o testMP -I /opt/boost_1_48_0/include </code></pre> <p>that is, no "-fopenmp", and I get these timings:</p> <pre><code>real 0m18.417s user 0m18.357s sys 0m0.004s </code></pre> <p>when I do use "-fopenmp", </p> <pre><code>g++ -O3 -fopenmp testMP.cc -o testMP -I /opt/boost_1_48_0/include </code></pre> <p>I get these numbers for the times:</p> <pre><code>real 0m6.853s user 0m52.007s sys 0m0.008s </code></pre> <p>which doesn't make sense to me. How using eight cores can only result in just 3-fold increase of performance? Am I coding the loop correctly?</p>
11,773,714
4
0
null
2012-08-02 07:46:17.473 UTC
15
2021-04-06 22:05:17.723 UTC
2021-04-06 22:05:17.723 UTC
null
1,366,871
null
296,827
null
1
34
c++|multithreading|performance|parallel-processing|openmp
82,063
<p>You should make use of the OpenMP <code>reduction</code> clause for <code>x</code> and <code>y</code>:</p> <pre><code>#pragma omp parallel for reduction(+:x,y) for (int j=0; j&lt;n; j++) { double r=0.0; for (int i=0; i &lt; m; i++){ double rand_g1 = cos(i/double(m)); double rand_g2 = sin(i/double(m)); x += rand_g1; y += rand_g2; r += sqrt(rand_g1*rand_g1 + rand_g2*rand_g2); } shifts[j] = r / m; } </code></pre> <p>With <code>reduction</code> each thread accumulates its own partial sum in <code>x</code> and <code>y</code> and in the end all partial values are summed together in order to obtain the final values.</p> <pre class="lang-none prettyprint-override"><code>Serial version: 25.05s user 0.01s system 99% cpu 25.059 total OpenMP version w/ OMP_NUM_THREADS=16: 24.76s user 0.02s system 1590% cpu 1.559 total </code></pre> <p>See - superlinear speed-up :)</p>
11,734,861
When can outer braces be omitted in an initializer list?
<p>I've got error C2078 in VC2010 when compiling the code below.</p> <pre><code>struct A { int foo; double bar; }; std::array&lt;A, 2&gt; a1 = // error C2078: too many initializers { {0, 0.1}, {2, 3.4} }; // OK std::array&lt;double, 2&gt; a2 = {0.1, 2.3}; </code></pre> <p>I found out that the correct syntax for <code>a1</code> is</p> <pre><code>std::array&lt;A, 2&gt; a1 = {{ {0, 0.1}, {2, 3.4} }}; </code></pre> <p>The question is: why extra braces are required for <code>a1</code> but not required for <code>a2</code>?</p> <p><strong>Update</strong></p> <p>The question seems to be not specific to std::array. Some examples:</p> <pre><code>struct B { int foo[2]; }; // OK B meow1 = {1,2}; B bark1 = {{1,2}}; struct C { struct { int a, b; } foo; }; // OK C meow2 = {1,2}; C bark2 = {{1,2}}; struct D { struct { int a, b; } foo[2]; }; D meow3 = {{1,2},{3,4}}; // error C2078: too many initializers D bark3 = {{{1,2},{3,4}}}; </code></pre> <p>I still don't see why <code>struct D</code> gives the error but B and C don't.</p>
11,735,045
1
12
null
2012-07-31 07:06:01.537 UTC
19
2017-04-14 05:07:37.27 UTC
2012-07-31 08:31:54.883 UTC
null
396,571
null
1,345,960
null
1
53
c++|c++11|visual-c++-2010
8,812
<p>The extra braces are needed because <code>std::array</code> is an aggregate and POD, unlike other containers in the standard library. <code>std::array</code> doesn't have a user-defined constructor. Its first data member is an array of size <code>N</code> (which you pass as a template argument), and this member is directly initialized with an initializer. The extra braces are needed for the <em>internal</em> array which is being directly initialized.</p> <p>The situation is same as:</p> <pre><code>//define this aggregate - no user-defined constructor struct Aarray { A data[2]; //data is an internal array }; </code></pre> <p>How would you initialize this? If you do this:</p> <pre><code>Aarray a1 = { {0, 0.1}, {2, 3.4} }; </code></pre> <p>it gives a <a href="http://ideone.com/z0ky3" rel="noreferrer">compilation error</a>:</p> <blockquote> <p>error: too many initializers for 'Aarray'</p> </blockquote> <p>This is the <em>same</em> error which you get in the case of a <code>std::array</code> (if you use GCC).</p> <p>So the correct thing to do is to use <em>braces</em> as follows:</p> <pre><code>Aarray a1 = { { //&lt;--this tells the compiler that initialization of `data` starts { //&lt;-- initialization of `data[0]` starts 0, 0.1 }, //&lt;-- initialization of `data[0]` ends {2, 3.4} //initialization of data[1] starts and ends, as above } //&lt;--this tells the compiler that initialization of `data` ends }; </code></pre> <p>which <a href="http://ideone.com/t7AdR" rel="noreferrer">compiles fine</a>. Once again, the extra braces are needed because you're initializing the <em>internal</em> array.</p> <p>--</p> <p>Now the question is why are extra braces not needed in case of <code>double</code>? </p> <p><strike>It is because <code>double</code> is not an aggregate, while <code>A</code> is. In other words, <code>std::array&lt;double, 2&gt;</code> is an aggregate of aggregate, while <code>std::array&lt;A, 2&gt;</code> is an aggregate of aggregate of aggregate<sup>1</sup>.</p> <p><sup>1. I think that extra braces are still needed in the case of double also (like <a href="http://ideone.com/wZkeo" rel="noreferrer">this</a>), to be completely conformant to the Standard, but the code works without them. It seems I need to dig through the spec again!</sup>. </strike></p> <h1>More on braces and extra braces</h1> <p>I dug through the spec. This section (§8.5.1/11 from C++11) is interesting and applies to this case:</p> <blockquote> <p>In a declaration of the form</p> </blockquote> <pre><code>T x = { a }; </code></pre> <blockquote> <p><strong>braces can be elided in an initializer-list as follows</strong>. If the initializer-list begins with a left brace, then the succeeding comma-separated list of initializer-clauses initializes the members of a subaggregate; it is erroneous for there to be more initializer-clauses than members. If, however, the initializer-list for a subaggregate does not begin with a left brace, then only enough initializer-clauses from the list are taken to initialize the members of the subaggregate; any remaining initializer-clauses are left to initialize the next member of the aggregate of which the current subaggregate is a member. [ Example:</p> </blockquote> <pre><code>float y[4][3] = { { 1, 3, 5 }, { 2, 4, 6 }, { 3, 5, 7 }, }; </code></pre> <blockquote> <p>is a completely-braced initialization: 1, 3, and 5 initialize the first row of the array <code>y[0]</code>, namely <code>y[0][0]</code>, <code>y[0][1]</code>, and <code>y[0][2]</code>. Likewise the next two lines initialize <code>y[1]</code> and <code>y[2]</code>. The initializer ends early and therefore <code>y[3]s</code> elements are initialized as if explicitly initialized with an expression of the form float(), that is, are initialized with 0.0. In the following example, braces in the initializer-list are elided; however the initializer-list has the same effect as the completely-braced initializer-list of the above example,</p> </blockquote> <pre><code>float y[4][3] = { 1, 3, 5, 2, 4, 6, 3, 5, 7 }; </code></pre> <blockquote> <p>The initializer for y begins with a left brace, but the one for <code>y[0]</code> does not, therefore three elements from the list are used. Likewise the next three are taken successively for <code>y[1]</code> and <code>y[2]</code>. —end example ]</p> </blockquote> <p>Based on what I understood from the above quote, I can say that the following should be allowed:</p> <pre><code>//OKAY. Braces are completely elided for the inner-aggregate std::array&lt;A, 2&gt; X = { 0, 0.1, 2, 3.4 }; //OKAY. Completely-braced initialization std::array&lt;A, 2&gt; Y = {{ {0, 0.1}, {2, 3.4} }}; </code></pre> <p>In the first one, braces for the inner-aggregate are completely elided, while the second has fully-braced initialization. In your case (the case of <code>double</code>), the initialization uses the first approach (braces are <em>completely</em> elided for the inner aggregate).</p> <p>But this should be disallowed:</p> <pre><code>//ILL-FORMED : neither braces-elided, nor fully-braced std::array&lt;A, 2&gt; Z = { {0, 0.1}, {2, 3.4} }; </code></pre> <p>It is neither braces-elided, nor are there enough braces to be completely-braced initialization. Therefore, it is ill-formed.</p>
3,553,875
Load an EXE file and run it from memory
<p>I'm trying to run an executable from memory such as outlined in <a href="http://www.codeproject.com/KB/cs/LoadExeIntoAssembly.aspx" rel="noreferrer">this</a> article. I can run any .net/managed exes quite easily. But I cannot run executables such as <code>notepad.exe</code> or <code>calc.exe</code>. How can I get it so I can also run unmanaged exes?</p>
3,553,911
4
1
null
2010-08-24 06:01:00.967 UTC
19
2018-12-07 16:34:01.3 UTC
2015-06-18 10:12:49.36 UTC
null
3,970,411
null
191,793
null
1
28
c#|.net
40,336
<p>In the case of running .NET executables from memory, the libraries and CLR itself are doing a lot of heavy lifting for you. For native executables like notepad.exe and calc.exe, you'll have to do a lot of manual work to get it to happen. Basically, you have to act like the Windows loader.</p> <p>There's probably pages of caveats here, but <a href="http://www.joachim-bauch.de/tutorials/loading-a-dll-from-memory/" rel="noreferrer">this in-depth article</a> has the steps you need to load a PE <sup><a href="https://en.wikipedia.org/wiki/Portable_Executable" rel="noreferrer">wiki</a></sup>, <sup><a href="https://docs.microsoft.com/en-us/windows/desktop/debug/pe-format" rel="noreferrer">msdn</a></sup> into memory and do the correct rebasing and fixups. Then, you should be able to find the entry point (like in the article) and run it.</p> <p>If you're really just wanting to run notepad.exe and calc.exe, the easiest way, of course, would be to use <a href="http://msdn.microsoft.com/en-us/library/0w4h05yb.aspx" rel="noreferrer"><code>Process.Start</code></a> and run them off disk. Otherwise, if you have an executable embedded as a resource in your process, then the next easiest way would be to just write the contents out to disk in a temporary location (see <a href="http://msdn.microsoft.com/en-us/library/system.io.path.gettempfilename.aspx" rel="noreferrer"><code>Path.GetTempFileName</code></a>) and then execute it from there.</p>
3,953,391
Why does (int)(object)10m throw "Specified cast is not valid" exception?
<p>Why this explicit cast does throw <code>Specified cast is not valid.</code> exception ?</p> <pre><code>decimal d = 10m; object o = d; int x = (int)o; </code></pre> <p>But this works:</p> <pre><code>int x = (int)(decimal)o; </code></pre>
3,953,684
4
2
null
2010-10-17 13:30:22.81 UTC
6
2018-10-19 09:04:22.133 UTC
2012-10-09 17:11:14.567 UTC
null
322,355
null
322,355
null
1
48
c#|casting
25,994
<p>A boxed value can only be unboxed to a variable of the exact same type. This seemingly odd restriction is a very important speed optimization that made .NET 1.x feasible before generics were available. You can read more about it in <a href="https://stackoverflow.com/questions/1583050/performance-surprise-with-as-and-nullable-types/3076525#3076525">this answer</a>.</p> <p>You don't want to jump through the multiple cast hoop, simple value types implement the IConvertible interface. Which you invoke by using the Convert class:</p> <pre><code> object o = 12m; int ix = Convert.ToInt32(o); </code></pre>
3,492,904
MySQL Select all columns from one table and some from another table
<p>How do you select all the columns from one table and just some columns from another table using JOIN? In MySQL.</p>
3,492,919
4
0
null
2010-08-16 12:04:03.617 UTC
67
2019-06-01 07:49:02.71 UTC
2015-12-07 10:34:36.08 UTC
null
895,245
null
198,836
null
1
364
select|mysql|join
328,207
<p>Just use the table name:</p> <pre><code>SELECT myTable.*, otherTable.foo, otherTable.bar... </code></pre> <p>That would select all columns from <code>myTable</code> and columns <code>foo</code> and <code>bar</code> from <code>otherTable</code>.</p>
3,936,844
finding the start day (Monday) of the current week
<p>Looking for a SQL query/queries that would determine the start day (Monday) of the current week.</p> <p>Example: If today is -> then the start of the week is</p> <pre><code>Sat Oct 09, 2010 -&gt; Start of the week is Monday Oct 04, 2010 Sun Oct 10, 2010 -&gt; Start of the week is Monday Oct 04, 2010 Mon Oct 11, 2010 -&gt; Start of the week is Monday Oct 11, 2010 Tue Oct 12, 2010 -&gt; Start of the week is Monday Oct 11, 2010 </code></pre> <p>I have seen many "solutions" on Google and StackOverflow. The look something like:</p> <pre><code>SET @pInputDate = CONVERT(VARCHAR(10), @pInputDate, 111) SELECT DATEADD(DD, 1 - DATEPART(DW, @pInputDate), @pInputDate) </code></pre> <p>This fails because: Sun Oct 10, 2010 -> start of week Monday Oct 11, 2010 (which is incorrect).</p>
3,936,891
5
2
null
2010-10-14 19:33:24.1 UTC
1
2021-02-02 22:35:38.847 UTC
2016-04-16 15:14:50.873 UTC
null
578,411
null
173,850
null
1
20
sql-server|tsql
41,848
<p>Try using <a href="http://msdn.microsoft.com/en-us/library/ms181598.aspx" rel="noreferrer"><code>DATEFIRST</code></a> to explicitly set the day of week to be regarded as the 'first'.</p> <pre><code>set DATEFIRST 1 --Monday select DATEADD(DD, 1 - DATEPART(DW, @pInputDate), @pInputDate) </code></pre> <p>This will return the Monday of the week the InputDate falls in.</p>
3,547,587
How to choose a Java-COM bridge?
<p>I have to create an application which automates Outlook and Word and I want to use Java for that task. (The only allowed alternative would be VB6, so...)</p> <p>After a quick Google survey I found several libraries, but I'm not sure which one to use:</p> <ul> <li><a href="http://j-interop.org/" rel="noreferrer">J-Interop</a></li> <li>SWT </li> <li><a href="http://danadler.com/jacob/" rel="noreferrer">JACOB</a></li> <li><a href="http://com4j.kohsuke.org/" rel="noreferrer">COM4J</a></li> <li><a href="http://www.infozoom.de/en_jacoZoom.shtml" rel="noreferrer">jacoZoom</a></li> <li>...</li> </ul> <p>I have no idea how to compare these libraries and make an informed decision. It seems that COM4J is a little bit outdated, JACOB leaks memory (allegedly) and jacoZoom is commercial. Each and every one seems to require a lot of boilerplate code to perform a simple method call. (Which might be unavoidable given the design of COM)</p> <p>Besides that I have no idea how to choose between one of them. Which one is the best? </p>
3,555,169
5
2
null
2010-08-23 12:41:56.057 UTC
13
2015-08-12 16:22:14.717 UTC
2015-08-12 16:22:14.717 UTC
null
23,368
null
23,368
null
1
25
java|com
18,928
<p>We use Jacob in production environment and it works out pretty well. Nevertheless the projects seems to be not very active.</p> <p>Speaking of which: Activity seems to be an advantage for J-Interop. We tried the project as well and it seems to work out pretty good with even better logging messages. I think we might choose J-Interop for new projects.</p> <p>COM4J seems to be outdated, you're right.</p>
3,415,683
Do I need to escape backslashes in PHP?
<p>Do I need to escape backslash in PHP?</p> <pre><code>echo 'Application\Models\User'; # Prints &quot;Application\Models\User&quot; echo 'Application\\Models\\User'; # Same output echo 'Application\Model\'User'; # Gives &quot;Application\Model'User&quot; </code></pre> <p>So it's an escape character. Shouldn't I need to escape it (<code>\</code>) if I want to refer to <code>Application\Models\User</code>?</p>
3,415,731
6
0
null
2010-08-05 14:26:35.62 UTC
2
2021-01-14 07:23:42.89 UTC
2021-01-11 08:35:22.937 UTC
null
63,550
null
292,291
null
1
18
php|string|escaping
57,618
<p>In <a href="http://php.net/language.types.string" rel="noreferrer">single quoted strings</a> only the escape sequences <code>\\</code> and <code>\'</code> are recognized; any other occurrence of <code>\</code> is interpreted as a plain character.</p> <p>So since <code>\M</code> and <code>\U</code> are no valid escape sequences, they are interpreted as they are.</p>
3,347,847
On Ruby on Rails, how do we print debug info inside of a controller?
<p>In PHP, CGI, or in RoR's View, we can easily print out debug information. How about in the Controller, how can we just say, <code>print "hello world"</code> (to the webpage output) and return to continue with the view, or stop the controller right there?</p>
3,347,983
6
0
null
2010-07-27 20:49:40.433 UTC
16
2021-09-23 04:27:04.933 UTC
2010-07-27 23:10:06.38 UTC
null
325,418
null
325,418
null
1
39
ruby-on-rails|debugging
61,532
<p>In the controller you can:</p> <pre><code>render :text =&gt; @some_object.inspect </code></pre> <p>But your view won't be rendered.</p> <p>You could also:</p> <pre><code>Rails.logger.debug("My object: #{@some_object.inspect}") </code></pre> <p>and run tail on log/development.log to see the output.</p> <p>In the view the recommeneded way is:</p> <pre><code>&lt;%= debug(@some_object) %&gt; </code></pre>
3,997,454
Help me understand linear separability in a binary SVM
<p>I'm cross-posting this from <a href="https://math.stackexchange.com/questions/7499/help-me-understand-linearly-separability-in-a-binary-svm">math.stackexchange.com</a> because I'm not getting any feedback and it's a time-sensitive question for me.</p> <hr> <p>My question pertains to linear separability with hyperplanes in a support vector machine.</p> <p>According to <a href="http://en.wikipedia.org/wiki/Support_vector_machineclassifier." rel="nofollow noreferrer">Wikipedia</a>:</p> <blockquote> <p>...formally, a support vector machine constructs a hyperplane or set of hyperplanes in a high or infinite dimensional space, which can be used for classification, regression or other tasks. Intuitively, a good separation is achieved by the hyperplane that has the largest distance to the nearest training data points of any class (so-called functional margin), since in general the larger the margin the lower the generalization error of the classifier.classifier.</p> </blockquote> <p>The linear separation of classes by hyperplanes intuitively makes sense to me. And I think I understand linear separability for two-dimensional geometry. However, I'm implementing an SVM using a popular SVM library (libSVM) and when messing around with the numbers, I fail to understand how an SVM can create a curve between classes, or enclose central points in category 1 within a circular curve when surrounded by points in category 2 if a hyperplane in an n-dimensional space V is a "flat" subset of dimension n − 1, or for two-dimensional space - a 1D line.</p> <h2>Here is what I mean:</h2> <p><img src="https://i.stack.imgur.com/wqZMd.png" alt="circularly enclosed class separation for a 2D binary SVM"></p> <p>That's not a hyperplane. That's circular. How does this work? Or are there more dimensions inside the SVM than the two-dimensional 2D input features?</p> <hr> <p>This example application can be downloaded <a href="http://www.matthewajohnson.org/software/svm.html" rel="nofollow noreferrer">here</a>.</p> <hr> <h2><strong>Edit:</strong></h2> <p>Thanks for your comprehensive answers. So the SVM can separate weird data well by using a kernel function. Would it help to linearize the data before sending it to the SVM? For example, one of my input features (a numeric value) has a turning point (eg. 0) where it neatly fits into category 1, but above and below zero it fits into category 2. Now, because I know this, would it help classification to send the absolute value of this feature for the SVM?</p>
3,997,704
7
3
null
2010-10-22 13:52:16.127 UTC
9
2013-02-19 22:24:41.94 UTC
2017-04-13 12:19:15.857 UTC
null
-1
null
198,927
null
1
5
algorithm|machine-learning|classification|svm|libsvm
5,205
<p>As mokus explained, support vector machines use a <em>kernel function</em> to implicitly map data into a feature space where they are linearly separable:</p> <p><img src="https://i.stack.imgur.com/7FyLd.jpg" alt="SVM mapping one feature space into another"></p> <p>Different kernel functions are used for various kinds of data. Note that an extra dimension (feature) is added by the transformation in the picture, although this feature is never materialized in memory.</p> <p>(Illustration from <a href="http://www.cogs.susx.ac.uk/courses/dm/lec10.html" rel="nofollow noreferrer">Chris Thornton, U. Sussex</a>.)</p>
3,304,463
How do I modify the PATH environment variable when running an Inno Setup Installer?
<p>Inno Setup lets you set environment variables via the [Registry] sections (by setting registry key which correspond to environment variable)</p> <p>However, sometimes you don't just wanna set an environment variable. Often, you wanna modify it. For example: upon installation, one may want to add/remove a directory to/from the PATH environment variable.</p> <p>How can I modify the PATH environment variable from within InnoSetup?</p>
3,431,379
7
0
null
2010-07-21 22:42:08.713 UTC
30
2021-01-27 20:58:56.18 UTC
2016-01-12 08:56:03.41 UTC
null
4,029,189
null
192,945
null
1
71
environment-variables|inno-setup
50,831
<p>The path in the registry key you gave is a value of type <code>REG_EXPAND_SZ</code>. As the Inno Setup documentation for the <strong>[Registry]</strong> section states there is a way to append elements to those:</p> <blockquote> <p>On a <code>string</code>, <code>expandsz</code>, or <code>multisz</code> type value, you may use a special constant called <code>{olddata}</code> in this parameter. <code>{olddata}</code> is replaced with the previous data of the registry value. The <code>{olddata}</code> constant can be useful if you need to append a string to an existing value, for example, <code>{olddata};{app}</code>. If the value does not exist or the existing value isn't a string type, the <code>{olddata}</code> constant is silently removed.</p> </blockquote> <p>So to append to the path a registry section similar to this may be used:</p> <pre><code>[Registry] Root: HKLM; Subkey: "SYSTEM\CurrentControlSet\Control\Session Manager\Environment"; \ ValueType: expandsz; ValueName: "Path"; ValueData: "{olddata};C:\foo" </code></pre> <p>which would append the "C:\foo" directory to the path.</p> <p>Unfortunately this would be repeated when you install a second time, which should be fixed as well. A <code>Check</code> parameter with a function coded in Pascal script can be used to check whether the path does indeed need to be expanded:</p> <pre><code>[Registry] Root: HKLM; Subkey: "SYSTEM\CurrentControlSet\Control\Session Manager\Environment"; \ ValueType: expandsz; ValueName: "Path"; ValueData: "{olddata};C:\foo"; \ Check: NeedsAddPath('C:\foo') </code></pre> <p>This function reads the original path value and checks whether the given directory is already contained in it. To do so it prepends and appends semicolon chars which are used to separate directories in the path. To account for the fact that the searched for directory may be the first or last element semicolon chars are prepended and appended to the original value as well:</p> <pre class="lang-pascal prettyprint-override"><code>[Code] function NeedsAddPath(Param: string): boolean; var OrigPath: string; begin if not RegQueryStringValue(HKEY_LOCAL_MACHINE, 'SYSTEM\CurrentControlSet\Control\Session Manager\Environment', 'Path', OrigPath) then begin Result := True; exit; end; { look for the path with leading and trailing semicolon } { Pos() returns 0 if not found } Result := Pos(';' + Param + ';', ';' + OrigPath + ';') = 0; end; </code></pre> <p>Note that you may need to expand constants before you pass them as parameter to the check function, see the documentation for details.</p> <p>Removing this directory from the path during uninstallation can be done in a similar fashion and is left as an exercise for the reader.</p>
3,678,255
centering a CGRect in a view
<p>I have an image displaying in a CGRect. how do I center the rect in the view?</p> <p>here's my code:</p> <pre><code>UIImage * image = [UIImage imageNamed:place.image]; CGRect rect = CGRectMake(10.0f, 90.0f, image.size.width, image.size.height); UIImageView * imageView = [[UIImageView alloc] initWithFrame:rect]; [imageView setImage:image]; </code></pre> <p>I've tried <strong>imageView.center</strong> but to no effect.</p> <p>thanks in advance.</p>
3,678,285
8
0
null
2010-09-09 15:53:13.317 UTC
11
2019-05-08 07:32:19.937 UTC
2010-09-09 15:53:45.063 UTC
null
224,671
null
388,458
null
1
23
iphone|objective-c|uiimage
34,127
<p>UIView's <code>center</code> is a property, not a method. </p> <p>You need to calculate the actual location you want to put it in. You can do this by setting the frame of the view, or by setting its center, which is simpler in your case.</p> <p>You don't say what view you then go make <code>imageView</code> a subview of. If you're putting it inside something called <code>superview</code>, you could do this:</p> <pre><code>CGPoint superCenter = CGPointMake(CGRectGetMidX([superview bounds]), CGRectGetMidY([superview bounds])); [imageView setCenter:superCenter]; </code></pre>
3,561,234
Where can I start with programmable Hardware?
<p>I've had a desire to learn at least a tiny bit about programming hardware for quite some time now and thought I'd ask here to get some starting points. I am a reasonably accomplished programmer with Delphi and Objective-c experience but have never even listened to a device port / interupt (I dont even know the terminology) let alone programmed a piece of hardware.</p> <p>To start with what I would like to be able to do is,</p> <ul> <li>Buy a simple bit of kit with 2,3 or 10 buttons</li> <li>Plug the device into my pc via USB</li> <li>Listen to the device and write some code to do something once the button is pressed.</li> </ul> <p>I reckon this is a good place to start, anyone got pointers on hardware to buy or how I could start this?</p>
3,561,268
9
0
null
2010-08-24 21:37:13.517 UTC
10
2010-09-12 19:08:54.453 UTC
2010-09-03 15:08:24.683 UTC
null
28,574
null
6,244
null
1
19
c++|c|embedded|hardware|usb
7,539
<p>I like the <a href="http://www.arduino.cc/" rel="noreferrer">Arduino</a>, easy to use, open source and a great community!</p> <p>Good to get started with, and uses a subset of C/C++.</p> <p>Also, has alot of addon hardware available, like GPS, Bluetooth, Wifi etc</p> <p>My experiences with Arduino have been nothing but good, from the point you get it out of it's box (and install the free compiler on either Windows / Mac / Linux), to building your first 'sketch' (a project or application for the Arduino).</p> <p>Making an application is easy, you have a <code>Setup</code> Method, which is called on startup, and then a <code>loop</code> method which is looped while the Arduino is running. </p> <p>Then all you have to do is hook either inputs or outputs up to the pins on the Arduino board, tell the code what they are and hopefully you'll get the desired output. </p> <p>One other really good thing about the Arduino (and others I'm sure) is that you now have a use for those old broken printers, or 2x CD-Rom's that no one wants, and every other little bit of out dated technology. It's amazing what you can find in a server room!</p> <p>Now, I have only worked on small projects, like plugging in an LCD, and reading the room temp and various projects like that. But based on what I have done, I am happy with the Ardunio, it gives a good base to embedded programming and if it's not enough, you can always go bigger!</p> <p>My 2 cents!</p>
3,790,191
php error: Class 'Imagick' not found
<p>I am getting the error "Class 'Imagick' not found". Somehow I need to make this library accessible to php. I am using Php 5.2.6 on Fedora 8. my php_info has no mention of ImageMagick.</p> <p>I have tried: yum install ImageMagick and restarted apache, which didn't work.</p> <p>I also added extension=imagick.ext to my php.ini file and restarted apache, which didn't work.</p>
3,794,896
10
3
null
2010-09-24 19:12:19.05 UTC
8
2022-08-14 19:11:41.983 UTC
null
null
null
null
400,648
null
1
56
php
124,218
<p>From: <a href="http://news.ycombinator.com/item?id=1726074" rel="noreferrer">http://news.ycombinator.com/item?id=1726074</a></p> <p>For RHEL-based i386 distributions:</p> <pre><code>yum install ImageMagick.i386 yum install ImageMagick-devel.i386 pecl install imagick echo "extension=imagick.so" &gt; /etc/php.d/imagick.ini service httpd restart </code></pre> <p>This may also work on other i386 distributions using yum package manager. For x86_64, just replace .i386 with .x86_64 </p>
7,699,200
What is the difference between OpenID and SAML?
<p>What is the difference between OpenID and SAML?</p>
7,699,311
4
0
null
2011-10-08 19:21:01.457 UTC
64
2021-06-30 09:54:31.097 UTC
2012-07-18 07:54:07.3 UTC
null
812,149
null
311,764
null
1
173
openid|saml
83,504
<h2>Original OpenID 2.0 vs SAML</h2> <p>They are two different protocols of authentication and they differ at the technical level.</p> <p>From a distance, differences start when users initiate the authentication. With OpenID, a user login is usually an HTTP address of the resource which is responsible for the authentication. On the other hand, SAML is based on an explicit trust between your site and the identity provider so it's rather uncommon to accept credentials from an unknown site.</p> <p>OpenID identities are easy to get around the net. As a developer you could then just accept users coming from very different OpenID providers. On the other hand, a SAML provider usually has to be coded in advance and you federate your application with only selected identity providers. It is possible to narrow the list of accepted OpenID identity providers but I think this would be against the general OpenID concept.</p> <p>With OpenID you accept identities coming from arbitrary servers. Someone claims to be <code>http://someopenid.provider.com/john.smith</code>. How you are going to match this with a user in your database? Somehow, for example by storing this information with a new account and recognizing this when user visits your site again. Note that any other information about the user (including his name or email) cannot be trusted!</p> <p>On the other hand, if there's an explicit trust between your application and the SAML Id Provider, you can get full information about the user including the name and email and this information can be trusted, just because of the trust relation. It means that you tend to believe that the Id Provider somehow validated all the information and you can trust it at the application level. If users come with SAML tokens issued by an unknown provider, your application just refuses the authentication.</p> <h2>OpenID Connect vs SAML</h2> <p>(section added 07-2017, expanded 08-2018)</p> <p>This answer dates 2011 and at that time OpenID stood for <a href="http://openid.net/specs/openid-authentication-2_0.html" rel="noreferrer">OpenID 2.0</a>. Later on, somewhere at 2012, <a href="https://www.rfc-editor.org/rfc/rfc6749" rel="noreferrer">OAuth2.0 </a>has been published and in 2014, <a href="http://openid.net/specs/openid-connect-core-1_0.html" rel="noreferrer">OpenID Connect</a> (a more detailed timeline <a href="https://security.stackexchange.com/a/130411/94186">here</a>).</p> <p>To anyone reading this nowadays - <strong>OpenID Connect is not the same OpenID the original answer refers to</strong>, rather it's a set of extensions to OAuth2.0.</p> <p>While <a href="https://security.stackexchange.com/a/44614/94186">this answer</a> can shed some light from the conceptual viewpoint, a very concise version for someone coming with OAuth2.0 background is that OpenID Connect <strong>is</strong> in fact OAuth2.0 but it adds a standard way of <a href="http://openid.net/specs/openid-connect-core-1_0.html#UserInfo" rel="noreferrer">querying the user info</a>, after the access token is available.</p> <p>Referring to the original question - what is the main difference between OpenID Connect (OAuth2.0) and SAML is how the trust relation is built between the application and the identity provider:</p> <ul> <li><p>SAML builds the trust relation on a digital signature, SAML tokens issued by the identity provider are signed XMLs, the application validates the signature itself and the certificate it presents. The user information is included in a SAML token, among other information.</p> </li> <li><p>OAuth2 builds the trust relation on a direct HTTPs call from the application to the identity. The request contains the access token (obtained by the application during the protocol flow) and the response contains the information about the user.</p> </li> <li><p>OpenID Connect further expands this to make it possible to obtain the identity <strong>without</strong> this extra step involving the call from the application to the identity provider. The idea is based on the fact that OpenID Connect providers in fact issue <strong>two</strong> tokens, the <code>access_token</code>, the very same one OAuth2.0 issues and the new one, the <code>id_token</code> which is a <strong>JWT</strong> token, <strong>signed</strong> by the identity provider. The application can use the <code>id_token</code> to establish a local session, based on claims included in the JWT token but the <code>id_token</code> <strong>cannot be used</strong> to further query other services, such calls to third party services should still use the <code>access_token</code>. You can think of the OpenID Connect then as a hybrid between the SAML2 (signed token) and OAuth2 (access token), as OpenID Connect just involves both.</p> </li> </ul>
7,715,594
How to reset cursor to the beginning of the same line in Python
<p>Most of questions related to this topics here in SO is as follows:</p> <blockquote> <p>How to print some information on the same line without introducing a new line</p> </blockquote> <p><a href="https://stackoverflow.com/questions/3249524">Q1</a> <a href="https://stackoverflow.com/questions/493386">Q2</a>.</p> <p>Instead, my question is as follows:</p> <p>I expect to see the following effect,</p> <pre><code>&gt;&gt; You have finished 10% </code></pre> <p>where the <code>10</code> keep increasing in the same time. I know how to do this in C++ but cannot find a good solution in python.</p>
7,715,670
6
2
null
2011-10-10 16:06:40.333 UTC
10
2019-12-02 18:09:36.357 UTC
2017-05-23 12:02:45.493 UTC
null
-1
null
391,104
null
1
39
python
60,666
<pre><code>import sys, time for i in xrange(0, 101, 10): print '\r&gt;&gt; You have finished %d%%' % i, sys.stdout.flush() time.sleep(2) print </code></pre> <p>The <code>\r</code> is the carriage return. You need the comma at the end of the <code>print</code> statement to avoid automatic newline. Finally <code>sys.stdout.flush()</code> is needed to flush the buffer out to stdout.</p> <p>For Python 3, you can use:</p> <pre><code>print("\r&gt;&gt; You have finished {}%".format(i), end='') </code></pre>
8,157,636
Can Json.NET serialize / deserialize to / from a stream?
<p>I have heard that Json.NET is faster than DataContractJsonSerializer, and wanted to give it a try... </p> <p>But I couldn't find any methods on JsonConvert that take a stream rather than a string. </p> <p>For deserializing a file containing JSON on WinPhone, for example, I use the following code to read the file contents into a string, and then deserialize into JSON. It appears to be about 4 times slower in my (very ad-hoc) testing than using DataContractJsonSerializer to deserialize straight from the stream... </p> <pre><code>// DCJS DataContractJsonSerializer dc = new DataContractJsonSerializer(typeof(Constants)); Constants constants = (Constants)dc.ReadObject(stream); // JSON.NET string json = new StreamReader(stream).ReadToEnd(); Constants constants = JsonConvert.DeserializeObject&lt;Constants&gt;(json); </code></pre> <p>Am I doing it wrong?</p>
8,158,220
6
0
null
2011-11-16 19:41:33.79 UTC
27
2022-07-19 07:34:06.063 UTC
2018-12-28 16:35:30.66 UTC
null
142,162
null
1,022,922
null
1
183
.net|serialization|json.net
230,099
<p><strong>UPDATE:</strong> This no longer works in the current version, see <a href="https://stackoverflow.com/a/17788118/973292">below</a> for correct answer (<strong>no need to vote down, this is correct on older versions</strong>).</p> <p>Use the <code>JsonTextReader</code> class with a <code>StreamReader</code> or use the <code>JsonSerializer</code> overload that takes a <code>StreamReader</code> directly:</p> <pre><code>var serializer = new JsonSerializer(); serializer.Deserialize(streamReader); </code></pre>
8,177,695
How to wait for a process to terminate to execute another process in batch file
<p>How to wait for a process to terminate before executing another process in a batch file? Let's say I have a process <code>notepad.exe</code> that I need to kill before executing <code>wordpad.exe</code>. Then, when <code>wordpad.exe</code> is terminated, I need to launch <code>notepad.exe</code> again. How do I do that?</p>
8,185,270
8
4
null
2011-11-18 04:15:22.607 UTC
12
2019-10-01 07:17:07.493 UTC
2017-05-29 18:52:36.643 UTC
null
6,395,052
null
261,842
null
1
56
windows|batch-file
189,775
<p>Try something like this...</p> <pre><code>@ECHO OFF PSKILL NOTEPAD START "" "C:\Program Files\Windows NT\Accessories\wordpad.exe" :LOOP PSLIST wordpad &gt;nul 2&gt;&amp;1 IF ERRORLEVEL 1 ( GOTO CONTINUE ) ELSE ( ECHO Wordpad is still running TIMEOUT /T 5 GOTO LOOP ) :CONTINUE NOTEPAD </code></pre> <p>I used <code>PSLIST</code> and <code>PSEXEC</code>, but you could also use <code>TASKKILL</code> and <code>TASKLIST</code>. The <code>&gt;nul 2&gt;&amp;1</code> is just there to hide all the output from <code>PSLIST</code>. The <code>SLEEP 5</code> line is not required, but is just there to restrict how often you check if WordPad is still running.</p>
8,108,980
Java using enum with switch statement
<p>I've looked at various Q&amp;As on SO similar to this question but haven't found a solution.</p> <p>What I have is an enum which represents different ways to view a TV Guide...</p> <p>In the NDroid <code>Application</code> class</p> <pre><code>static enum guideView { GUIDE_VIEW_SEVEN_DAY, GUIDE_VIEW_NOW_SHOWING, GUIDE_VIEW_ALL_TIMESLOTS } </code></pre> <p>...when the user changes the view an event handler receives an <code>int</code> from 0-2 and I'd like to do something like this...</p> <p>In an Android <code>Activity</code> <code>onClick(DialogInterface dialog, int which)</code> event handler</p> <pre><code>// 'which' is an int from 0-2 switch (which) { case NDroid.guideView.GUIDE_VIEW_SEVEN_DAY: ... break; } </code></pre> <p>I'm used to C# enums and select/case statements which would allow something like the above and I know Java does things differently but I just can't make sense of what I need to do.</p> <p>Am I going to have to resort to <code>if</code> statements? There will likely only ever be 3 choices so I could do it but I wondered how it could be done with switch-case in Java.</p> <p><strong>EDIT</strong> Sorry I didn't completely expand on the issue as I was looking at it as being a generic Java issue. I've added to the question to explain a bit further.</p> <p>There isn't anything that's Android specific which is why I didn't tag it as Android but the enum is defined in the <code>Application</code> class and the code where I wan't the switch is in an <code>Activity</code>. The enum is static as I need to access it from multiple Activities.</p>
8,109,098
8
6
null
2011-11-13 01:46:09.77 UTC
20
2018-01-22 21:59:23.407 UTC
2011-11-13 02:08:17.527 UTC
null
488,241
null
488,241
null
1
123
java|enums|switch-statement
346,349
<p>The part you're missing is converting from the integer to the type-safe enum. Java will not do it automatically. There's a couple of ways you can go about this:</p> <ol> <li>Use a list of static final ints rather than a type-safe enum and switch on the int value you receive (this is the pre-Java 5 approach)</li> <li>Switch on either a specified id value (as <a href="https://stackoverflow.com/questions/8108980/java-using-enum-with-switch-statement/8109035#8109035">described by heneryville</a>) or the ordinal value of the enum values; i.e. <code>guideView.GUIDE_VIEW_SEVEN_DAY.ordinal()</code></li> <li><p>Determine the enum value represented by the int value and then switch on the enum value.</p> <pre><code>enum GuideView { SEVEN_DAY, NOW_SHOWING, ALL_TIMESLOTS } // Working on the assumption that your int value is // the ordinal value of the items in your enum public void onClick(DialogInterface dialog, int which) { // do your own bounds checking GuideView whichView = GuideView.values()[which]; switch (whichView) { case SEVEN_DAY: ... break; case NOW_SHOWING: ... break; } } </code></pre> <p>You may find it more helpful / less error prone to write a custom <code>valueOf</code> implementation that takes your integer values as an argument to resolve the appropriate enum value and lets you centralize your bounds checking.</p></li> </ol>
4,141,643
How do I set expiration on CSS, JS and Images?
<p>I have recently analysed my website with pagespeed addon on firebug. It suggested me to set expiration on CSS, JS and image files.</p> <p>I am wondering, how do I do this?</p>
4,141,740
5
2
null
2010-11-10 05:57:19.7 UTC
19
2020-12-28 01:20:49.563 UTC
2020-12-28 01:20:49.563 UTC
null
1,783,163
null
178,301
null
1
41
html|apache|caching
80,562
<p>This is the one I use to fix the exact same thing when I ran the PageSpeed Addon:</p> <pre><code>&lt;FilesMatch "\.(jpg|jpeg|png|gif|swf)$"&gt; Header set Cache-Control "max-age=604800, public" &lt;/FilesMatch&gt; </code></pre> <p>This goes into your .htaccess file.</p> <p>Read up on this page for more information about how to set cache for additional file types and/or change the cache length:</p> <p><a href="http://www.askapache.com/htaccess/apache-speed-cache-control.html" rel="noreferrer">http://www.askapache.com/htaccess/apache-speed-cache-control.html</a></p>
4,556,184
Vim: Move window left/right?
<p>In Vim, is it possible to “move” a window to the left or right? Eg, similar to <code>&lt;c-w&gt; r</code> or <code>&lt;c-w&gt; x</code>, but left/right instead of up/down?</p> <p>For example, if I've got this layout:</p> <pre><code>+---+---+---+ | | +---+ | A +---+---+ | | | | +---+---+---+ </code></pre> <p>I'd like to turn it into this:</p> <pre><code>+---+---+---+ | | +---+ +---+ A +---+ | | | | +---+---+---+ </code></pre> <p>Which is difficult/annoying to do with <code>&lt;c-w&gt; {H,J,K,L}</code>.</p>
4,571,319
5
0
null
2010-12-29 17:16:42.553 UTC
129
2020-01-28 19:14:41.42 UTC
2010-12-29 17:29:34.7 UTC
null
71,522
null
71,522
null
1
253
vim
109,989
<p><kbd><kbd>Ctrl</kbd> <kbd>w</kbd></kbd> gives you the "windows command mode", allowing the following modifiers:</p> <ul> <li><p><kbd><kbd>Ctrl</kbd> <kbd>w</kbd></kbd> + <kbd>R</kbd> - To rotate windows up/left.</p></li> <li><p><kbd><kbd>Ctrl</kbd> <kbd>w</kbd></kbd> + <kbd>r</kbd> - To rotate windows down/right.</p></li> </ul> <p>You can also use the "windows command mode" with navigation keys to change a window's position:</p> <ul> <li><p><kbd><kbd>Ctrl</kbd> <kbd>w</kbd></kbd> + <kbd>L</kbd> - Move the current window to the "far right"</p></li> <li><p><kbd><kbd>Ctrl</kbd> <kbd>w</kbd></kbd> + <kbd>H</kbd> - Move the current window to the "far left"</p></li> <li><p><kbd><kbd>Ctrl</kbd> <kbd>w</kbd></kbd> + <kbd>J</kbd> - Move the current window to the "very bottom"</p></li> <li><p><kbd><kbd>Ctrl</kbd> <kbd>w</kbd></kbd> + <kbd>K</kbd> - Move the current window to the "very top"</p></li> </ul> <p>Check out <a href="http://vimdoc.sourceforge.net/htmldoc/windows.html#window-moving" rel="noreferrer"><code>:help window-moving</code></a> for more information</p>
4,307,770
Regular Expressions for file name matching
<p>In Bash, how does one match a regular expression with multiple criteria against a file name? For example, I'd like to match against all the files with .txt or .log endings.</p> <p>I know how to match one type of criteria:</p> <pre><code>for file in *.log do echo "${file}" done </code></pre> <p>What's the syntax for a logical or to match two or more types of criteria?</p>
4,307,812
6
0
null
2010-11-29 20:25:59.45 UTC
6
2010-11-30 06:12:15.437 UTC
null
null
null
null
385,897
null
1
15
regex|bash
44,987
<p>Do it the same way you'd invoke <code>ls</code>. You can specify multiple wildcards one after the other:</p> <pre><code>for file in *.log *.txt </code></pre>
4,574,176
Heroku push rejected, failed to install gems via Bundler
<p>I am struggling to push my code to Heroku. And after searching on Google and Stack Overflow questions, I have not been able to find the solution. Here is What I get when I try "git push heroku master" :</p> <pre><code>Heroku receiving push -----&gt; Rails app detected -----&gt; Detected Rails is not set to serve static_assets Installing rails3_serve_static_assets... done -----&gt; Gemfile detected, running Bundler version 1.0.3 Unresolved dependencies detected; Installing... Fetching source index for http://rubygems.org/ /usr/ruby1.8.7/lib/ruby/site_ruby/1.8/rubygems/remote_fetcher.rb:300:in `open_uri_or_path': bad response Not Found 404 (http://rubygems.org/quick/Marshal.4.8/mail-2.2.6.001.gemspec.rz) (Gem::RemoteFetcher::FetchError) from /usr/ruby1.8.7/lib/ruby/site_ruby/1.8/rubygems/remote_fetcher.rb:172:in `fetch_path' . .... </code></pre> <p>And finally:</p> <pre><code>FAILED: http://docs.heroku.com/bundler ! Heroku push rejected, failed to install gems via Bundler error: hooks/pre-receive exited with error code 1 To git@heroku.com:myapp.git ! [remote rejected] master -&gt; master (pre-receive hook declined) error: failed to push some refs to 'git@heroku.com:myapp.git' </code></pre> <p>Thanks for your help!</p>
4,576,816
13
0
null
2011-01-01 13:24:11.25 UTC
15
2022-04-04 12:05:59.133 UTC
null
null
null
null
307,708
null
1
64
ruby-on-rails|rubygems|heroku|ruby-on-rails-3|bundler
42,814
<p>I don't think it's a Rails version problem, nor is it specific to Heroku. (I hit the same problem today, when running <code>bundle install</code> on my local development machine, with Rails 3.0.3.)</p> <p>Running <code>bundle update</code> locally, as Andrew suggested, fixes the issue.</p> <p><strong><em>Edit</em></strong>: As suggested in the comments: remember to <code>git add .</code>, <code>git commit -m "message"</code></p>
4,161,022
How to track untracked content?
<p>See below the solid line for my original question.</p> <p>I have a folder in my local directory that is untracked. When I run <code>git status</code>, I get:</p> <pre><code>Changed but not updated: modified: vendor/plugins/open_flash_chart_2 (modified content, untracked content) </code></pre> <p>When I type <code>git add vendor/plugins/open_flash_chart_2</code> then try <code>git status</code> again, it still says untracked. What's going on? </p> <hr> <p>Here is a simple summary of my latest half hour:</p> <ul> <li><p>Discovered that my Github repo is not tracking my <code>vendor/plugins/open_flash_chart_2</code> plugin. Specifically, there's no content and it's showing a <b>green arrow</b> on the folder icon.</p></li> <li><p>Tried <code>git submodule init</code></p> <pre><code>No submodule mapping found in .gitmodules for path 'vendor/plugins/open_flash_chart_2' </code></pre></li> <li><p>Tried <code>git submodule add git://github.com/korin/open_flash_chart_2_plugin.git vendor/plugins/open_flash_chart_2</code></p> <pre><code>vendor/plugins/open_flash_chart_2 already exists in the index </code></pre></li> <li><p><code>git status</code> </p> <pre><code>modified: vendor/plugins/open_flash_chart_2 (untracked content) </code></pre></li> <li><p>Hunted for any file named <code>.gitmodules</code> in my repository/local directory but couldn't find one.</p></li> </ul> <p>What do I have to do to <b>get my submodules working</b> so git can start tracking properly?</p> <hr> <p>This may be unrelated (I include it in case it helps), but every time I type <code>git commit -a</code> rather than my usual <code>git commit -m "my comments"</code>, it throws up an error:</p> <pre><code>E325: ATTENTION Found a swap file by the name ".git\.COMMIT-EDITMSG.swp" dated: Thu Nov 11 19:45:05 2010 file name: c:/san/project/.git/COMMIT_EDITMSG modified: YES user name: San host name: San-PC process ID: 4268 While opening file ".git\COMMIT_EDITMSG" dated: Thu Nov 11 20:56:09 2010 NEWER than swap file! Swap file ".git\.COMMIT_EDITMSG.swp" already exists! [O]pen Read-Only, (E)dit anyway, (R)ecover, (D)elete it, (Q)uit, (A)bort: Swap file ".git\.COMMIT_EDITMSG.swp" already exists! [O]pen Read-Only, (E)dit anyway, (R)ecover, (D)elete it, (Q)uit, (A)bort: </code></pre> <p>I am a complete newbie at Github and despite trying to go through the documentation, I'm a bit stumped by these particular problems. Thank you.</p>
4,162,672
15
13
null
2010-11-12 02:04:54.853 UTC
99
2022-04-25 06:01:36.983 UTC
2018-01-12 19:00:34.1 UTC
null
55,075
null
341,583
null
1
165
git|git-submodules
162,420
<p>You have added <code>vendor/plugins/open_flash_chart_2</code> as “gitlink” entry, but never defined it as a submodule. Effectively you are using the internal feature that <em>git submodule</em> uses (gitlink entries) but you are not using the submodule feature itself.</p> <p>You probably did something like this:</p> <pre><code>git clone git://github.com/korin/open_flash_chart_2_plugin.git vendor/plugins/open_flash_chart_2 git add vendor/plugins/open_flash_chart_2 </code></pre> <p>This last command is the problem. The directory <code>vendor/plugins/open_flash_chart_2</code> starts out as an independent Git repository. Usually such sub-repositories are ignored, but if you tell <em>git add</em> to explicitly add it, then it will create an gitlink entry that points to the sub-repository’s HEAD commit instead of adding the contents of the directory. It might be nice if <em>git add</em> would refuse to create such “semi-submodules”.</p> <p>Normal directories are represented as tree objects in Git; tree objects give names, and permissions to the objects they contain (usually other tree and blob objects—directories and files, respectively). Submodules are represented as “gitlink” entries; gitlink entries only contain the object name (hash) of the HEAD commit of the submodule. The “source repository” for a gitlink’s commit is specified in the <code>.gitmodules</code> file (and the <code>.git/config</code> file once the submodule has been initialized).</p> <p>What you have is an entry that points to a particular commit, without recording the source repository for that commit. You can fix this by either making your gitlink into a proper submodule, or by removing the gitlink and replacing it with “normal” content (plain files and directories).</p> <h2>Turn It into a Proper Submodule</h2> <p>The only bit you are missing to properly define <code>vendor/plugins/open_flash_chart_2</code> as a submodule is a <code>.gitmodules</code> file. Normally (if you had not already added it as bare gitlink entry), you would just use <code>git submodule add</code>:</p> <pre><code>git submodule add git://github.com/korin/open_flash_chart_2_plugin.git vendor/plugins/open_flash_chart_2 </code></pre> <p>As you found, this will not work if the path already exists in the index. The solution is to temporarily remove the gitlink entry from the index and then add the submodule:</p> <pre><code>git rm --cached vendor/plugins/open_flash_chart_2 git submodule add git://github.com/korin/open_flash_chart_2_plugin.git vendor/plugins/open_flash_chart_2 </code></pre> <p>This will use your existing sub-repository (i.e. it will not re-clone the source repository) and stage a <code>.gitmodules</code> file that looks like this:</p> <pre><code>[submodule "vendor/plugins/open_flash_chart_2"] path = vendor/plugins/open_flash_chart_2 url = git://github.com/korin/open_flash_chart_2_plugin.git vendor/plugins/open_flash_chart_2 </code></pre> <p>It will also make a similar entry in your main repository’s <code>.git/config</code> (without the <code>path</code> setting).</p> <p>Commit that and you will have a proper submodule. When you clone the repository (or push to GitHub and clone from there), you should be able to re-initialize the submodule via <code>git submodule update --init</code>.</p> <h2>Replace It with Plain Content</h2> <p>The next step assumes that your sub-repository in <code>vendor/plugins/open_flash_chart_2</code> does not have any local history that you want to preserve (i.e. all you care about is the current working tree of the sub-repository, not the history).</p> <p><strong>If you have local history in the sub-repository that you care about, then you should backup the sub-repository’s <code>.git</code> directory before deleting it in the second command below.</strong> (Also consider the <em>git subtree</em> example below that preserves the history of the sub-repository’s HEAD).</p> <pre><code>git rm --cached vendor/plugins/open_flash_chart_2 rm -rf vendor/plugins/open_flash_chart_2/.git # BACK THIS UP FIRST unless you are sure you have no local changes in it git add vendor/plugins/open_flash_chart_2 </code></pre> <p>This time when adding the directory, it is not a sub-repository, so the files will be added normally. Unfortunately, since we deleted the <code>.git</code> directory there is no super-easy way to keep things up-to-date with the source repository.</p> <p>You might consider using a <a href="http://www.kernel.org/pub/software/scm/git/docs/howto/using-merge-subtree.html" rel="noreferrer">subtree merge</a> instead. Doing so will let you easily pull in changes from the source repository while keeping the files “flat” in your repository (no submodules). The third-party <a href="https://github.com/apenwarr/git-subtree" rel="noreferrer"><em>git subtree</em> command</a> is a nice wrapper around the subtree merge functionality.</p> <pre><code>git rm --cached vendor/plugins/open_flash_chart_2 git commit -m'converting to subtree; please stand by' mv vendor/plugins/open_flash_chart_2 ../ofc2.local git subtree add --prefix=vendor/plugins/open_flash_chart_2 ../ofc2.local HEAD #rm -rf ../ofc2.local # if HEAD was the only tip with local history </code></pre> <p>Later:</p> <pre><code>git remote add ofc2 git://github.com/korin/open_flash_chart_2_plugin.git git subtree pull --prefix=vendor/plugins/open_flash_chart_2 ofc2 master git subtree push --prefix=vendor/plugins/open_flash_chart_2 git@github.com:me/my_ofc2_fork.git changes_for_pull_request </code></pre> <p><em>git subtree</em> also has a <code>--squash</code> option that lets you avoid incorporating the source repository’s history into your history but still lets you pull in upstream changes.</p>
4,621,255
How do I run a Python program in the Command Prompt in Windows 7?
<p>I'm trying to figure out how to run Python programs with the Command Prompt on Windows 7. (I should have figured this out by now...)</p> <p>When I typed &quot;python&quot; into the command prompt, I got the following error:</p> <blockquote> <p>'python' is not recognized as an internal or external command, operable program or batch file.</p> </blockquote> <p>The first place I found when looking for help was this site: <a href="http://docs.python.org/faq/windows.html#how-do-i-run-a-python-program-under-windows" rel="noreferrer">http://docs.python.org/faq/windows.html#how-do-i-run-a-python-program-under-windows</a>.</p> <p>It was somewhat helpful, but the tutorial was written for Windows 2000 and older, so it was minimally helpful for my Windows 7 machine. I attempted the following:</p> <blockquote> <p>For older versions of Windows the easiest way to do this is to edit the C:\AUTOEXEC.BAT &gt;file. You would want to add a line like the following to AUTOEXEC.BAT:</p> </blockquote> <p>This file did not exist on my machine (unless I'm mistaken).</p> <p>Next, I tried this: (here: <a href="https://stackoverflow.com/questions/1522564/how-do-i-run-a-python-program">How do I run a Python program?</a>)</p> <blockquote> <p>Putting Python In Your Path</p> <p>Windows</p> <p>In order to run programs, your operating system looks in various places, and tries to match the name of the program / command you typed with some programs along the way.</p> <p>In windows:</p> <p>control panel &gt; system &gt; advanced &gt; |Environmental Variables| &gt; system variables -&gt; Path</p> <p>this needs to include: C:\Python26; (or equivalent). If you put it at the front, it will be the first place looked. You can also add it at the end, which is possibly saner.</p> <p>Then restart your prompt, and try typing 'python'. If it all worked, you should get a &quot;&gt;&gt;&gt;&quot; prompt.</p> </blockquote> <p>This was relevant enough for Windows 7, and I made my way to the System Variables. I added a variable &quot;python&quot; with the value &quot;C:\Python27&quot;</p> <p>I continued to get the error, even after restarting my computer.</p> <p>Anyone know how to fix this?</p>
4,621,277
24
0
null
2011-01-06 23:51:41.15 UTC
68
2022-06-01 22:13:53.787 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
566,233
null
1
166
python|windows-7
877,731
<p>You need to add <code>C:\Python27</code> to your system PATH variable, not a new variable named "python".</p> <p>Find the system PATH environment variable, and append to it a <code>;</code> (which is the delimiter) and the path to the directory containing python.exe (e.g. <code>C:\Python27</code>). See below for exact steps.</p> <p>The PATH environment variable lists all the locations that Windows (and <code>cmd.exe</code>) will check when given the name of a command, e.g. "python" (it also uses the PATHEXT variable for a list of executable file extensions to try). The first executable file it finds on the PATH with that name is the one it starts.</p> <p>Note that after changing this variable, there is no need to restart Windows, but only new instances of <code>cmd.exe</code> will have the updated PATH. You can type <code>set PATH</code> at the command prompt to see what the current value is.</p> <hr> <p>Exact steps for adding Python to the path on Windows 7+:</p> <ol> <li>Computer -> System Properties (or <kbd>Win+Break</kbd>) -> Advanced System Settings</li> <li>Click the <code>Environment variables...</code> button (in the Advanced tab)</li> <li>Edit PATH and append <code>;C:\Python27</code> to the end (substitute your Python version)</li> <li>Click OK. Note that changes to the PATH are only reflected in command prompts opened <em>after</em> the change took place.</li> </ol>
14,842,268
How to create static binary which runs on every distro?
<p>Some linux apps like supertuxkart or regnum online have static binaries, which after downloading just work without needing to install any shared library. On every distro. How can I make such an app?</p>
14,842,328
1
0
null
2013-02-12 21:34:44.433 UTC
5
2021-04-15 13:56:31.27 UTC
null
null
null
null
1,873,947
null
1
24
linux|gcc|g++|packaging
41,708
<p>Ensure that all your resources are contained in the executable and link the executable statically:</p> <pre><code>gcc -o foo main.o -static -lbaz -lbar </code></pre> <p>However, this also has drawbacks. Look up dynamic linking.</p>
14,468,733
Why I'm getting unexpected EOF for my cron job?
<p>I am receiving an error with my Cron job. The error I keep getting is: </p> <pre><code>/bin/sh: -c: line 0: unexpected EOF while looking for matching `'' /bin/sh: -c: line 1: syntax error: unexpected end of file </code></pre> <p>Here is my code:</p> <pre><code>mysqldump -u database_user -p']T%zw51' database &gt; /home/site/public_html/Secure/Cron/Database_Backup/database_backup.sql </code></pre>
14,468,892
1
0
null
2013-01-22 21:54:40.493 UTC
3
2015-03-26 16:35:12.497 UTC
2015-03-26 16:35:12.497 UTC
null
55,075
null
317,740
null
1
30
shell|cron
9,464
<p>You may need to escape the <code>%</code> with a <code>\</code>. <code>%</code> is a special character to the crontab, which gets translated to a newline, so your code was probably becoming </p> <pre><code> -p']T zw51' </code></pre> <p>Try:</p> <pre><code> -p']T\%zw51' </code></pre>
14,698,350
x86_64 ASM - maximum bytes for an instruction?
<p>What is the maximum number of bytes a complete instruction would require in x64 asm code?</p> <p>Something like a jump to address might occupy up to 9 bytes I suppose: <strong>FF 00 00 00 00 11 12 3F 1F</strong> but I don't know if that's the maximum number of bytes a x64 instruction can use</p>
14,698,559
3
3
null
2013-02-05 00:47:05.807 UTC
8
2017-09-01 14:17:00.623 UTC
null
null
null
null
1,494,037
null
1
36
c|assembly|x86|64-bit|x86-64
25,021
<p>The x86 instruction set (16, 32 or 64 bit, all variants/modes) guarantees / requires that instructions are at most 15 bytes. Anything beyond that will give an "invalid opcode". You can't achieve that without using redundant prefixes (e.g. multiple 0x66 or 0x67 prefixes, for example).</p> <p>The only instruction that actually takes 64-bits as a data item is the load constant to register (Intel syntax: <code>mov reg, 12345678ABCDEF00h</code>, at&amp;t syntax: <code>movabs $12345678ABCDEF00, %reg</code>) - so if you wanted to jump more than 31 bits forward/backward, it would be a move of the target location into a register, and then call/jump to the register. Using 32-bit immediates and displacements (in relative jumps and addressing modes) saves four bytes on many instructions in 64-bit mode.</p>
14,859,312
Last element in django template list variable
<p>I would like to know how to filter out the last element of a list variable from the context object.</p> <pre><code>{% for d in data %} {{ d }}, {% endfor %} </code></pre> <p>I don't want to have the <code>,</code> after the last element. Thank you.</p> <p><strong>NOTE</strong>: This is just a hypothetical example. I know we can use the join filter to achieve the same thing here</p>
14,860,220
3
1
null
2013-02-13 17:25:01.25 UTC
3
2016-04-30 17:11:19.353 UTC
null
null
null
null
1,684,058
null
1
38
django
20,848
<p>Do you mean -</p> <pre><code>{% for d in data %} {% if forloop.last %} {{ d }} {% else %} {{ d }}, {% endif %} {% endfor %} </code></pre> <p>have a look at the <a href="https://docs.djangoproject.com/en/1.9/ref/templates/builtins/#for" rel="noreferrer">django docs</a> on template for loops </p>
14,840,247
spannable on android for textView
<pre><code>Tweet o = tweets.get(position); TextView tt = (TextView) v.findViewById(R.id.toptext); //TextView bt = (TextView) v.findViewById(R.id.bottomtext); EditText bt =(EditText)findViewById(R.id.bottomtext); bt.setText(o.author); Spannable spn = (Spannable) bt.getText(); spn.setSpan(new StyleSpan(android.graphics.Typeface.BOLD_ITALIC) , 0, 100, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); //bt.setText(o.author); tt.setText(o.content); </code></pre> <p>I'm setting twitter data in my Android application. I want to make the font bold and italic using Spannable but it does not work, giving an error. How can I do it?</p>
14,840,432
3
3
null
2013-02-12 19:28:38.247 UTC
9
2020-06-12 18:25:52.373 UTC
2013-03-09 10:42:53.373 UTC
null
569,101
null
2,046,224
null
1
40
java|android|twitter|spannable
57,185
<blockquote> <p>I want to make the font bold and ıtalic with spannable</p> </blockquote> <p>for this u will need to make <code>o.content</code> text as <code>SpannableString</code> then set it to TextView as :</p> <pre><code>SpannableString spannablecontent=new SpannableString(o.content.toString()); spannablecontent.setSpan(new StyleSpan(android.graphics.Typeface.BOLD_ITALIC), 0,spannablecontent.length(), 0); // set Text here tt.setText(spannablecontent); </code></pre> <p><strong>EDIT :</strong> you can also use Html.fromHtml for making text Bold and Italic in textview as :</p> <pre><code>tt.setText(Html.fromHtml("&lt;strong&gt;&lt;em&gt;"+o.content+"&lt;/em&gt;&lt;/strong&gt;")); </code></pre>
14,660,037
Django Forms: pass parameter to form
<p>How do I pass a parameter to my form?</p> <pre><code>someView().. form = StylesForm(data_dict) # I also want to pass in site_id here. class StylesForm(forms.Form): # I want access to site_id here </code></pre>
14,660,051
3
0
null
2013-02-02 08:22:10.843 UTC
12
2020-11-25 13:18:23.623 UTC
2020-11-25 13:18:23.623 UTC
null
5,660,517
null
984,003
null
1
50
django|django-forms
65,010
<p>You should define the __init__ method of your form, like that:</p> <pre><code>class StylesForm(forms.Form): def __init__(self,*args,**kwargs): self.site_id = kwargs.pop('site_id') super(StylesForm,self).__init__(*args,**kwargs) </code></pre> <p>of course you cannot access self.site_id until the object has been created, so the line:</p> <pre><code> height = forms.CharField(widget=forms.TextInput(attrs={'size':site_id})) </code></pre> <p>makes no sense. You have to add the attribute to the widget after the form has been created. Try something like this:</p> <pre><code>class StylesForm(forms.Form): def __init__(self,*args,**kwargs): self.site_id = kwargs.pop('site_id') super(StylesForm,self).__init__(*args,**kwargs) self.fields['height'].widget = forms.TextInput(attrs={'size':site_id}) height = forms.CharField() </code></pre> <p>(not tested)</p>
14,551,194
How are parameters sent in an HTTP POST request?
<p>In an HTTP <strong>GET</strong> request, parameters are sent as a <strong><em>query string</em></strong>:</p> <pre>http://example.com/page<b><i>?parameter=value&also=another</i></b></pre> <p>In an HTTP <strong>POST</strong> request, the parameters are not sent along with the URI.</p> <p><strong><em>Where are the values?</em></strong> In the request header? In the request body? What does it look like?</p>
14,551,320
10
1
null
2013-01-27 19:19:07.627 UTC
552
2022-07-01 17:12:53.12 UTC
2016-12-17 10:21:39.113 UTC
null
3,618,581
null
124,119
null
1
1,678
http|post|parameters|request|uri
2,552,540
<p>The values are sent in the request body, in the format that the content type specifies.</p> <p>Usually the content type is <code>application/x-www-form-urlencoded</code>, so the request body uses the same format as the query string:</p> <pre><code>parameter=value&amp;also=another </code></pre> <p>When you use a file upload in the form, you use the <code>multipart/form-data</code> encoding instead, which has a different format. It's more complicated, but you usually don't need to care what it looks like, so I won't show an example, but it can be good to know that it exists.</p>
45,659,986
Django: Implementing a Form within a generic DetailView
<p>After working through several google search result pages, I am still desperately stuck at the same problem. I am trying to implement a comment field underneath a blog post. I am thankful for any hints and advice! </p> <p>I am working on a Blog in Django which is set up with a first, generic ListView to display briefly all available blog posts and with a second, generic DetailView to show the specific blog post in more detail. I now want to place an add_comment_field underneath the specific blog post with all other comments shown underneath. It works when the comment form is displayed on a separate page but not on the same page as the DetailView, which is the desired outcome. </p> <p>I suspect this has to do with the interplay between views.py and forms.py but I cannot figure out the problem. </p> <p>Again, thank you so much for your help!</p> <p>views.py</p> <pre><code>from django.shortcuts import render, get_object_or_404, redirect from .models import Post, Comment from .forms import CommentForm from django.views.generic.detail import DetailView class ParticularPost(DetailView): template_name='blog/post.html' model = Post def add_comment_to_post(self, pk): post = get_object_or_404(Post, pk=pk) if self.method == "POST": form = CommentForm(self.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() return redirect('post_detail', pk=post.pk) else: form = CommentForm() return {'form': form} </code></pre> <p>urls.py</p> <pre><code>from django.conf.urls import url, include from django.views.generic import ListView, DetailView from .models import Post, Comment from .views import ParticularPost urlpatterns = [ url(r'^$', ListView.as_view(queryset=Post.objects.all().order_by("-date")[:25], template_name="blog/blog.html")), url(r'^(?P&lt;pk&gt;\d+)$', ParticularPost.as_view(), name="post_detail"), ] </code></pre> <p>post.html</p> <pre><code>{% extends "personal/header.html" %} {% load staticfiles %} {% block content %} &lt;div class="container-fluid background_design2 "&gt; &lt;div class="header_spacing"&gt;&lt;/div&gt; &lt;div class="container post_spacing"&gt; &lt;div class="row background_design1 blog_post_spacing inline-headers"&gt; &lt;h3&gt;&lt;a href="/blog/{{post.id}}"&gt;{{ post.title }}&lt;/a&gt;&lt;/h3&gt; &lt;h6&gt; on {{ post.date }}&lt;/h6&gt; &lt;div class = "blog_text"&gt; {{ post.body|safe|linebreaks}} &lt;/div&gt; &lt;br&gt;&lt;br&gt; &lt;/div&gt; &lt;div&gt; &lt;form method="POST" class="post-form"&gt;{% csrf_token %} {{ form.as_p }} &lt;button type="submit" class="save btn btn-default"&gt;Send&lt;/button&gt; &lt;/form&gt; &lt;/div&gt; &lt;div class=" row post_spacing background_design1 "&gt; &lt;hr&gt; {% for comment in post.comments.all %} &lt;div class=" col-md-12 comment"&gt; &lt;div class="date"&gt;{{ comment.created_date }}&lt;/div&gt; &lt;strong&gt;{{ comment.author }}&lt;/strong&gt; &lt;p&gt;{{ comment.text|linebreaks }}&lt;/p&gt; &lt;/div&gt; {% empty %} &lt;p&gt;No comments here yet :(&lt;/p&gt; {% endfor %} &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; {% endblock %} </code></pre> <p>forms.py</p> <pre><code>from django import forms from .models import Comment class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('author', 'text',) </code></pre> <p>models.py</p> <pre><code>from django.db import models from django.utils import timezone class Post(models.Model): title = models.CharField(max_length=140) body = models.TextField() date = models.DateTimeField() def __str__(self): return self.title class Comment(models.Model): post = models.ForeignKey('blog.Post', related_name='comments') author = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) def __str__(self): return self.text </code></pre>
45,661,979
4
0
null
2017-08-13 11:46:40.127 UTC
8
2022-06-16 01:17:32.3 UTC
null
null
null
user8457857
null
null
1
13
django|forms|comments|blogs|detailview
11,875
<p>Use <a href="https://docs.djangoproject.com/en/1.11/topics/class-based-views/mixins/#using-formmixin-with-detailview" rel="nofollow noreferrer"><code>FormMixin</code></a> if you want combine <code>DetailView</code> and a form:</p> <pre><code>from django.shortcuts import render, get_object_or_404, redirect from django.views.generic.detail import DetailView from django.views.generic.edit import FormMixin from django.urls import reverse from .models import Post, Comment from .forms import CommentForm class ParticularPost(FormMixin, DetailView): template_name='blog/post.html' model = Post form_class = CommentForm def get_success_url(self): return reverse('post_detail', kwargs={'pk': self.object.id}) def get_context_data(self, **kwargs): context = super(ParticularPost, self).get_context_data(**kwargs) context['form'] = CommentForm(initial={'post': self.object}) return context def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): form.save() return super(ParticularPost, self).form_valid(form) </code></pre> <p>And don't forget to add the <code>post</code> field into the form (you can do it hidden):</p> <pre><code>class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('author', 'text', 'post',) </code></pre> <p>And the better way to add a creation date - use <a href="https://docs.djangoproject.com/en/1.11/ref/models/fields/#django.db.models.DateField.auto_now_add" rel="nofollow noreferrer"><code>auto_now_add=True</code></a>:</p> <pre><code>created_date = models.DateTimeField(auto_now_add=True) </code></pre>
2,621,395
More efficient way of updating UI from Service than intents?
<p>I currently have a Service in Android that is a sample VOIP client so it listens out for SIP messages and if it recieves one it starts up an Activity screen with UI components.</p> <p>Then the following SIP messages determine what the Activity is to display on the screen. For example if its an incoming call it will display Answer or Reject or an outgoing call it will show a dialling screen.</p> <p>At the minute I use Intents to let the Activity know what state it should display.</p> <p>An example is as follows:</p> <hr> <pre><code> Intent i = new Intent(); i.setAction(SIPEngine.SIP_TRYING_INTENT); i.putExtra("com.net.INCOMING", true); sendBroadcast(i); Intent x = new Intent(); x.setAction(CallManager.SIP_INCOMING_CALL_INTENT); sendBroadcast(x); Log.d("INTENT SENT", "INTENT SENT INCOMING CALL AFTER PROCESSINVITE"); </code></pre> <hr> <p>So the activity will have a broadcast reciever registered for these intents and will switch its state according to the last intent it received.</p> <p>Sample code as follows:</p> <hr> <pre><code> SipCallListener = new BroadcastReceiver(){ @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if(SIPEngine.SIP_RINGING_INTENT.equals(action)){ Log.d("cda ", "Got RINGING action SIPENGINE"); ringingSetup(); } if(CallManager.SIP_INCOMING_CALL_INTENT.equals(action)){ Log.d("cda ", "Got PHONE RINGING action"); incomingCallSetup(); } } }; IntentFilter filter = new IntentFilter(CallManager.SIP_INCOMING_CALL_INTENT); filter.addAction(CallManager.SIP_RINGING_CALL_INTENT); registerReceiver(SipCallListener, filter); </code></pre> <hr> <p>This works however it seems like it is not very efficient, the Intents will get broadcast system wide and Intents having to fire for different states seems like it could become inefficient the more I have to include as well as adding complexity.</p> <p>So I was wondering if there is a different more efficient and cleaner way to do this?</p> <p>Is there a way to keep Intents broadcasting only inside an application?</p> <p>Would callbacks be a better idea? If so why and in what way should they be implemented? </p>
2,622,473
2
0
null
2010-04-12 10:46:58.323 UTC
38
2015-06-15 21:21:14.75 UTC
2010-04-12 11:03:32.01 UTC
null
243,999
null
243,999
null
1
41
android|user-interface|service|performance|android-intent
22,890
<p><strong>UPDATE 2015:</strong></p> <p>This question/answer still gets a little bit of activity, but it is over 5 yrs old and things have changed quite a bit. 5 years ago, the answer below was how I would have handled it. Later I wrote a very lightweight dependency injection solution that I was using for a while (which I mentioned in the comments). Nowadays, I would answer this question using Dagger and RxAndroid. Dagger to inject a "mediator" class into both the Service and all Activities that need to be notified, the Service would push the status update to the mediator class, and the mediator class would expose an observable for the activities to consume the status update (in place of the OP's broadcast receiver). </p> <p><strong>Original answer</strong></p> <p>I usually subclass Application and let my in-app communication go through this class (or have a mediator owned by the Application do the work...regardless, the Application being the entry point for the service to communicate with). I have a bound service that needs to update the UI as well (much simpler than yours, but the same idea) and it basically tells the app its new state and the app can then pass this information along in one way or another to the currently active activity. You can also maintain a pointer to the currently active activity (if there is more than one), and make decisions whether or not to simply update the current activity, broadcast the intent to launch a different activity, ignore the message, etc. I would also subclass Activity and have your new activity base class tell the Application that it is currently the active one in onResume and that it is being paused in onPause (for cases where your service is running in the background and the activities are all paused).</p> <p><strong>EDIT:</strong></p> <p>In response to the comment, here's more specifics.</p> <p>Your application currently consists of Activity-derived and Service-derived classes for the most part. Inherently, you get functionality from an instance of the android.app.Application class. This is declared in your manifest (by default) with the following line:</p> <pre><code>&lt;application android:icon="@drawable/icon" android:label="@string/app_name"&gt; </code></pre> <p>The application element in your manifest doesn't use the android:name attribute, so it just creates an instance of the default android.app.Application class to represent your global application context.</p> <p>In my apps, I create a subclass of Application (ApplicationEx, for example) and I tell my app through the manifest that this is the class to instantiate as MY global application context. For example:</p> <pre><code>&lt;application android:name="com.mycompany.myapp.app.ApplicationEx" android:icon="@drawable/app_icon" android:label="@string/app_name"&gt; </code></pre> <p>I can now add methods to ApplicationEx for activities and services to use to communicate. There is always a single instance of your global application context, so this is your starting point if anything needs to be global for your app.</p> <p>A second piece of this is that instead of deriving my services and activities from Service and Activity, I create a subclass of each with a getAppContext method that casts the return value of getApplicationContext (which exists already in both of these classes because they derive from Context) to my ApplicationEx class.</p> <p>So........</p> <p>All that being said, you add a CurrentActivity property to your ApplicationEx class of type Activity (or ActivityBase if you subclass it as I do). In ActivityBase's onResume method, you pass yourself to ApplicationEx for it to set CurrentActivity to that activity. Now, you can expose methods on ApplicationEx to pass information directly to the current activity instead of relying on the Intent mechanisms.</p> <p>That's about as clear as I can make it</p>
39,482,131
Is it possible to use `impl Trait` as a function's return type in a trait definition?
<p>Is it at all possible to define functions inside of traits as having <code>impl Trait</code> return types? I want to create a trait that can be implemented by multiple structs so that the <code>new()</code> functions of all of them returns an object that they can all be used in the same way without having to write code specific to each one.</p> <pre><code>trait A { fn new() -&gt; impl A; } </code></pre> <p>However, I get the following error:</p> <pre class="lang-none prettyprint-override"><code>error[E0562]: `impl Trait` not allowed outside of function and inherent method return types --&gt; src/lib.rs:2:17 | 2 | fn new() -&gt; impl A; | ^^^^^^ </code></pre> <p>Is this a limitation of the current implementation of <code>impl Trait</code> or am I using it wrong?</p>
39,482,164
4
0
null
2016-09-14 03:38:25.693 UTC
8
2020-02-11 14:44:23.723 UTC
2019-11-06 17:02:22.773 UTC
null
155,423
null
3,833,068
null
1
67
rust|traits
22,128
<p>If you only need to return the specific type for which the trait is currently being implemented, you may be looking for <code>Self</code>.</p> <pre><code>trait A { fn new() -&gt; Self; } </code></pre> <p>For example, this will compile:</p> <pre><code>trait A { fn new() -&gt; Self; } struct Person; impl A for Person { fn new() -&gt; Person { Person } } </code></pre> <p>Or, a fuller example, demonstrating using the trait:</p> <pre><code>trait A { fn new&lt;S: Into&lt;String&gt;&gt;(name: S) -&gt; Self; fn get_name(&amp;self) -&gt; String; } struct Person { name: String } impl A for Person { fn new&lt;S: Into&lt;String&gt;&gt;(name: S) -&gt; Person { Person { name: name.into() } } fn get_name(&amp;self) -&gt; String { self.name.clone() } } struct Pet { name: String } impl A for Pet { fn new&lt;S: Into&lt;String&gt;&gt;(name: S) -&gt; Pet { Pet { name: name.into() } } fn get_name(&amp;self) -&gt; String { self.name.clone() } } fn main() { let person = Person::new("Simon"); let pet = Pet::new("Buddy"); println!("{}'s pets name is {}", get_name(&amp;person), get_name(&amp;pet)); } fn get_name&lt;T: A&gt;(a: &amp;T) -&gt; String { a.get_name() } </code></pre> <p><a href="https://play.rust-lang.org/?gist=ed91863c50da8404bdbbccd386260cea&amp;version=stable&amp;backtrace=0" rel="noreferrer">Playground</a></p> <p>As a side note.. I have used <code>String</code> here in favor of <code>&amp;str</code> references.. to reduce the need for explicit lifetimes and potentially a loss of focus on the question at hand. I believe it's generally the convention to return a <code>&amp;str</code> reference when borrowing the content and that seems appropriate here.. however I didn't want to distract from the actual example too much.</p>
31,370,333
custom django-user object has no attribute 'has_module_perms'
<p>My custom user model for login via email:</p> <pre><code>class MyUser(AbstractBaseUser): id = models.AutoField(primary_key=True) # AutoField? is_superuser = models.IntegerField(default=False) username = models.CharField(unique=True,max_length=30) first_name = models.CharField(max_length=30, default='') last_name = models.CharField(max_length=30, default='') email = models.EmailField(unique=True,max_length=75) is_staff = models.IntegerField(default=False) is_active = models.IntegerField(default=False) date_joined = models.DateTimeField(default=None) # Use default usermanager objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] class Meta: db_table = 'auth_user' </code></pre> <p>For which, I'm able to successfully create a superuser. However, when I try to login with email and password, I get this error:</p> <pre><code>'MyUser' object has no attribute 'has_module_perms' </code></pre> <p>Any idea what I'm doing wrong ?</p>
31,370,510
3
0
null
2015-07-12 17:05:19.83 UTC
5
2022-04-17 21:44:22.563 UTC
null
null
null
null
395,028
null
1
28
django|django-authentication|django-users
20,333
<p>Your User implementation is not providing the mandatory methods to be used with the Admin module.</p> <p>See <a href="https://docs.djangoproject.com/en/4.0/topics/auth/customizing/#custom-users-and-django-contrib-admin" rel="nofollow noreferrer">https://docs.djangoproject.com/en/4.0/topics/auth/customizing/#custom-users-and-django-contrib-admin</a>.</p> <p>In your case, add the permissions mixin (PermissionsMixin), as a superclass of your model:</p> <pre><code>from django.contrib.auth.models import PermissionsMixin class MyUser(AbstractBaseUser, PermissionsMixin): # ... </code></pre> <p>It is described here : <a href="https://docs.djangoproject.com/en/4.0/topics/auth/customizing/#custom-users-and-permissions" rel="nofollow noreferrer">https://docs.djangoproject.com/en/4.0/topics/auth/customizing/#custom-users-and-permissions</a></p> <p>It works with Django 1.x, 2.x, 3.x and 4.x.</p> <p>EDIT: updated links to django version 4.0</p>
40,382,319
How to programmatically close ng-bootstrap modal?
<p>I've got a modal:</p> <pre><code>&lt;template #warningModal let-c="close" let-d="dismiss"&gt; &lt;div class="modal-header"&gt; &lt;button type="button" class="close" aria-label="Close" (click)="d('Cross click')"&gt; &lt;span aria-hidden="true"&gt;&amp;times;&lt;/span&gt; &lt;/button&gt; &lt;h4 class="modal-title"&gt;Warning&lt;/h4&gt; &lt;/div&gt; &lt;div class="modal-body"&gt; The numbers you have entered result in negative expenses. We will treat this as $0.00. Do you want to continue? &lt;/div&gt; &lt;div class="modal-footer"&gt; &lt;button type="button" class="btn btn-secondary" (click)="c('Close click')"&gt;No&lt;/button&gt; &lt;button type="button" class="btn btn-secondary" (click)="submit()"&gt;Yes&lt;/button&gt; &lt;/div&gt; &lt;/template&gt; </code></pre> <p>Whenever I click yes, I want it to call a function and close itself.<br> In my controller, I have <code>@ViewChild('warningModal') warning;</code> and in <code>submit()</code>, I have <code>this.warning.close();</code>, but I get <code>this.warning.close is not a function</code> whenever I click Yes. </p> <p>How do I get this to work the way I want it to?</p>
40,382,909
10
1
null
2016-11-02 14:22:27.837 UTC
12
2022-06-09 15:47:05.613 UTC
2018-11-02 12:41:08.94 UTC
null
1,033,581
null
1,226,755
null
1
48
angular|ng-bootstrap
95,343
<p>If you are using <a href="https://ng-bootstrap.github.io/" rel="noreferrer">https://ng-bootstrap.github.io/</a> (as indicated in your question) things are extremely simple - you can just open a modal and either close it from a template (as in your code) <em>or</em> programmatically (by calling <code>close()</code> method on the returned Object of type <code>NgbModalRef</code>).</p> <p>Here is a minimal example showing this in action: <a href="http://plnkr.co/edit/r7watmQuyaUQ8onY17Z1?p=preview" rel="noreferrer">http://plnkr.co/edit/r7watmQuyaUQ8onY17Z1?p=preview</a></p> <p>You might be either confusing different libraries or maybe there is sth more to your question but it is hard to say more based just on the info provided.</p>
48,641,295
Async Computed in Components - VueJS?
<p>I'm finding a solution to async computed method in Components:</p> <p>Currently, my component is:</p> <pre><code>&lt;div class="msg_content"&gt; {{messages}} &lt;/div&gt; &lt;script&gt; export default { computed: { messages: { get () { return api.get(`/users/${this.value.username}/message/`, {'headers': { 'Authorization': 'JWT ...' }}) .then(response =&gt; response.data) } } }, } &lt;/script&gt; </code></pre> <p>Result: <code>{}</code></p> <p>How to rewrite it in <code>Promise</code> mode? Because I think we can async computed by writing into Promise mode.</p>
48,643,055
3
0
null
2018-02-06 10:54:23.32 UTC
4
2022-07-15 19:45:54.863 UTC
2020-05-27 14:36:23.373 UTC
null
7,095,029
null
7,155,095
null
1
46
javascript|vue.js|vuejs2|vue-component
91,232
<p>Computed properties are basically functions that cache their results so that they don't have to be calculated every time they are needed. They updated automatically <strong>based on the reactive values they use</strong>.</p> <p>Your computed does not use any reactive items, so there's no point in its being a computed. It returns a Promise now (assuming the usual behavior of <code>then</code>).</p> <p>It's not entirely clear what you want to achieve, but my best guess is that you should create a data item to hold <code>response.data</code>, and make your <code>api.get</code> call in the <a href="https://v2.vuejs.org/v2/api/#created" rel="nofollow noreferrer"><code>created</code> hook</a>. Something like</p> <pre><code>export default { data() { return { //... messages: [] }; }, created() { api.get(`/users/${this.value.username}/message/`, { 'headers': { 'Authorization': 'JWT ...' } }) .then(response =&gt; this.messages = response.data); } } </code></pre>
33,834,049
What is the difference between the initial and unset values?
<p>A simple example:</p> <p><strong>HTML</strong></p> <pre><code>&lt;p style="color:red!important"&gt; this text is red &lt;em&gt; this text is in the initial color (e.g. black) &lt;/em&gt; this is red again &lt;/p&gt; </code></pre> <p><strong>CSS</strong></p> <pre><code>em { color:initial; color:unset; } </code></pre> <p>What is the difference between <code>initial</code> and <code>unset</code>? Only supports browsers </p> <p><a href="http://caniuse.com/css-unset-value" rel="noreferrer">CanIUse: CSS unset value</a></p> <p><a href="https://developer.mozilla.org/en-US/docs/Web/CSS/initial" rel="noreferrer">Developer Mozilla Web CSS initial</a></p>
33,834,282
3
0
null
2015-11-20 18:54:32.96 UTC
21
2022-09-16 11:29:58.933 UTC
2020-04-15 10:59:55.803 UTC
null
515,189
null
1,673,376
null
1
115
css
65,313
<p>According to <a href="http://caniuse.com/#feat=css-unset-value" rel="noreferrer">your link</a>:</p> <blockquote> <p><code>unset</code> is a CSS value that's the same as "inherit" if a property is inherited or "initial" if a property is not inherited</p> </blockquote> <p>Here is an example:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>pre { color: #f00; } .initial { color: initial; } .unset { color: unset; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;pre&gt; &lt;span&gt;This text is red because it is inherited.&lt;/span&gt; &lt;span class="initial"&gt;[color: initial]: This text is the initial color (black, the browser default).&lt;/span&gt; &lt;span class="unset"&gt;[color: unset]: This text is red because it is unset (which means that it is the same as inherited).&lt;/span&gt; &lt;/pre&gt;</code></pre> </div> </div> </p> <p>A scenario where the difference matter is if you are trying to override some CSS in your stylesheet, but you would prefer the value is inherited rather than set back to the browser default.</p> <p>For instance:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>pre { color: #00f; } span { color: #f00; } .unset { color: unset; } .initial { color: initial; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;pre&gt; &lt;em&gt;Text in this 'pre' element is blue.&lt;/em&gt; &lt;span&gt;The span elements are red, but we want to override this.&lt;/span&gt; &lt;span class="unset"&gt;[color: unset]: This span's color is unset (blue, because it is inherited from the pre).&lt;/span&gt; &lt;span class="initial"&gt;[color: initial]: This span's color is initial (black, the browser default).&lt;/span&gt; &lt;/pre&gt;</code></pre> </div> </div> </p>
31,915,957
move_uploaded_file failed to open stream: Permission denied - Mac
<p>While i am trying to move_uploaded_file in php with following code :</p> <pre><code>if(is_uploaded_file($_FILES['fileupload2']['tmp_name'])){ move_uploaded_file($_FILES['fileupload2']['tmp_name'], "images/".$_FILES['fileupload2']['name']); } </code></pre> <p>I've got this error saying:</p> <pre><code>Warning: move_uploaded_file(images/VIDEO_TS.VOB): failed to open stream: Permission denied in /Applications/XAMPP/xamppfiles/htdocs/Week3/Lesson2/do_upload.php on line 24 </code></pre> <p>i tried in the terminal and didn't work: </p> <pre><code>sudo CHMOD 775 /Applications/XAMPP/xamppfiles/htdocs/Week3/Lesson2/do_upload.php sudo chmod -R 0755 /Applications/XAMPP/xamppfiles/htdocs/Week3/Lesson2/do_upload.php sudo chown nobody /Applications/XAMPP/xamppfiles/htdocs/Week3/Lesson2/do_upload.php </code></pre> <p>I am still getting the error and i am using Yosemite, any other solution ?</p>
31,919,367
8
0
null
2015-08-10 09:24:21.52 UTC
2
2021-09-28 13:27:31.42 UTC
2015-08-10 09:29:25.743 UTC
null
3,989,689
null
3,989,689
null
1
17
php|apache|file-upload|upload|xampp
54,556
<p>My solution was to give the permission for the images folder and the php file, by going to the file > Right click > Get info > and then change all the permissions to <code>read&amp;write</code> as the following picture.</p> <p><a href="https://i.stack.imgur.com/HvsMQ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/HvsMQ.png" alt="enter image description here"></a></p>
31,924,980
Filling entity links in custom @RepositoryRestController methods
<p>I am using Spring-data-rest to provide read APIs over some JPA entities. For writes I need to issue Command objects rather than directly write to the DB, so I added a custom controller using <code>@RepositoryRestController</code> and various command handling methods:</p> <pre><code>@RequestMapping(method = RequestMethod.POST) public @ResponseBody MyEntity post(@RequestBody MyEntity entity) { String createdId = commands.sendAndWait(new MyCreateCommand(entity)); return repo.findOne(createdId); } </code></pre> <p>I would like the output to be enriched just like any other response by the spring-data-rest controller, in particular I want it to add HATEOAS links to itself and its relations.</p>
31,927,590
1
0
null
2015-08-10 16:47:08.503 UTC
8
2015-08-28 10:40:09.697 UTC
null
null
null
null
1,938,607
null
1
10
java|spring|jpa|spring-data-rest|spring-hateoas
3,125
<p>This has recently been <a href="https://stackoverflow.com/a/31782016/3790806">answered</a> (see point 3.) by <a href="https://stackoverflow.com/users/18122/oliver-gierke">Oliver Gierke</a> himself (the question used quite different keywords though, so I won't flag this as duplicate).</p> <p>The example for a single entity would become:</p> <pre><code>@RequestMapping(method = RequestMethod.POST) public @ResponseBody PersistentEntityResource post(@RequestBody MyEntity entity, PersistentEntityResourceAssembler resourceAssembler)) { String createdId = commands.sendAndWait(new MyCreateCommand(entity)); return resourceAssembler.toResource(repo.findOne(createdId)); } </code></pre> <p>The example for a non-paginated listing:</p> <pre><code>@RequestMapping(method = RequestMethod.POST) public @ResponseBody Resources&lt;PersistentEntityResource&gt; post( @RequestBody MyEntity entity, PersistentEntityResourceAssembler resourceAssembler)) { List&lt;MyEntity&gt; myEntities = ... List&lt;&gt; resources = myEntities .stream() .map(resourceAssembler::toResource) .collect(Collectors.toList()); return new Resources&lt;PersistentEntityResource&gt;(resources); } </code></pre> <p>Finally, for a paged response one should use an injected PagedResourcesAssembler, passing in the method-injected ResourceAssembler and the Page, rather than instantiating Resources. More details about how to use <code>PersistentEntityResourceAssembler</code> and <code>PagedResourcesAssembler</code> can be found in <a href="https://stackoverflow.com/a/29924387/3790806">this answer</a>. Note that at the moment this requires to use raw types and unchecked casts.</p> <p>There is room for automation maybe, better solutions are welcome.</p> <p>P.S.: I also created a <a href="https://jira.spring.io/browse/DATAREST-633" rel="noreferrer">JIRA ticket</a> to add this to Spring Data's documentation.</p>
44,448,411
Default value for each type in typescript
<p>Where can I find the default value of each type in typescript? For example, where is mentioned the default value for <code>number</code> type is <code>null</code> or <code>0.</code>? Or about the <code>string</code>?</p> <p>The default value means the value of a variable that is defined, but not assigned. Like <code>let a : number;</code>. This happens a lot in object definitions. For example:</p> <pre><code> class A{ let a: number; let b: string; } let obj: A; </code></pre> <p>Therefore, the question is on the values of <code>a</code> and <code>b</code> for <code>obj</code>.</p>
44,448,478
2
0
null
2017-06-09 02:37:23.52 UTC
3
2021-02-17 18:40:32.253 UTC
2021-02-17 18:40:32.253 UTC
null
3,768,871
null
3,768,871
null
1
19
typescript
51,002
<p>The default value of every type is <code>undefined</code></p> <p>From: <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/undefined" rel="noreferrer">MDN - 'undefined'</a></p> <blockquote> <p>A variable that has not been assigned a value is of type undefined. </p> </blockquote> <p>For example, invoking the following will alert the value 'undefined', even though <code>greeting</code> is of type <code>String</code></p> <pre><code>let greeting: string; alert(greeting); </code></pre>
67,405,791
Gradle tasks are not showing in the gradle tool window in Android Studio 4.2
<p>I just updated Android Studio to version 4.2. I was surprised to not see the Gradle tasks in my project.</p> <p>In the previous version, 4.1.3, I could see the tasks as shown here:</p> <p><a href="https://i.stack.imgur.com/7fhMP.png" rel="noreferrer"><img src="https://i.stack.imgur.com/7fhMP.png" alt="working in version 4.1.3" /></a></p> <p>But now I only see the dependencies in version 4.2:</p> <p><a href="https://i.stack.imgur.com/ScuhS.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ScuhS.png" alt="Not working in 4.2" /></a></p> <p>I tried to clear Android Studio's cache and sync my project again, but there was no change.</p> <p>Is this a feature change?</p>
67,406,955
6
0
null
2021-05-05 17:07:28.16 UTC
40
2022-06-28 16:50:32.55 UTC
2021-05-16 15:41:48.847 UTC
null
4,424,400
null
4,424,400
null
1
242
android-studio|gradle|android-studio-4.2
71,274
<p>OK, I found why I got this behaviour in android studio 4.2.</p> <p>It is intended behaviour. I found the answer in this post: <a href="https://issuetracker.google.com/issues/185420705" rel="noreferrer">https://issuetracker.google.com/issues/185420705</a>.</p> <blockquote> <p>Gradle task list is large and slow to populate in Android projects. This feature by default is disabled for performance reasons. You can re-enable it in: Settings | Experimental | Do not build Gradle task list during Gradle sync.</p> </blockquote> <p>Reload the Gradle project by clicking the &quot;Sync Project with gradle Files&quot; icon and the tasks will appear.</p> <p>It could be cool that this experimental change is put in the release note of android studio <code>4.2</code>.</p> <p><a href="https://i.stack.imgur.com/ZBmQA.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ZBmQA.png" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/0T3V2.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/0T3V2.jpg" alt="enter image description here" /></a></p>
2,806,586
Reading file data during form's clean method
<p>So, I'm working on implementing the answer to <a href="https://stackoverflow.com/questions/2798670/processing-file-uploads-before-object-is-saved">my previous question</a>.</p> <p>Here's my model:</p> <pre><code>class Talk(models.Model): title = models.CharField(max_length=200) mp3 = models.FileField(upload_to = u'talks/', max_length=200) </code></pre> <p>Here's my form:</p> <pre><code>class TalkForm(forms.ModelForm): def clean(self): super(TalkForm, self).clean() cleaned_data = self.cleaned_data if u'mp3' in self.files: from mutagen.mp3 import MP3 if hasattr(self.files['mp3'], 'temporary_file_path'): audio = MP3(self.files['mp3'].temporary_file_path()) else: # What goes here? audio = None # setting to None for now ... return cleaned_data class Meta: model = Talk </code></pre> <p><a href="http://code.google.com/p/mutagen/wiki/Tutorial" rel="nofollow noreferrer">Mutagen</a> needs file-like objects or filenames on disk (I <em>think</em>) - the first case (where the uploaded file is larger than the size of file handled in memory) works fine, but I don't know how to handle <code>InMemoryUploadedFile</code> that I get otherwise. I've tried:</p> <pre><code># TypeError (coercing to Unicode: need string or buffer, InMemoryUploadedFile found) audio = MP3(self.files['mp3']) # TypeError (coercing to Unicode: need string or buffer, cStringIO.StringO found) audio = MP3(self.files['mp3'].file) # Hangs seemingly indefinitely on my test file (~800KB) audio = MP3(self.files['mp3'].file.read()) </code></pre> <p>Is there something wrong with mutagen, or am I doing it wrong?</p> <h2>After rebus' answer</h2> <p>Modifying the <code>FILE_UPLOAD_HANDLERS</code> setting on the fly in my <code>ModelAdmin</code> class like this:</p> <pre><code>def add_view(self, request, form_url='', extra_context=None): request.upload_handlers = [TemporaryFileUploadHandler()] return super(TalkAdmin, self).add_view(request, form_url, extra_context) </code></pre> <p>Gets me the following error 500 when I hit submit:</p> <blockquote> <p>You cannot set the upload handlers after the upload has been processed.</p> </blockquote> <p>even though I'm doing it as early as I possibly can!</p> <p>Also, I'm not sure I've got a <code>save</code> method on the object I'm getting back (I've looked in <code>dir(self.files['mp3'].file)</code> and <code>dir(self.files['mp3'])</code>).</p>
2,806,655
1
0
null
2010-05-10 21:30:13.79 UTC
11
2010-05-14 07:52:57.18 UTC
2017-05-23 10:31:31.273 UTC
null
-1
null
20,972
null
1
16
django|django-file-upload|mutagen
12,009
<p>You could try to change your <a href="http://docs.djangoproject.com/en/dev/topics/http/file-uploads/#upload-handlers" rel="noreferrer">FILE_UPLOAD_HANDLERS</a> in such a way so Django always uses temporay file handler:</p> <p><code>FILE_UPLOAD_HANDLERS</code> default:</p> <pre><code>("django.core.files.uploadhandler.MemoryFileUploadHandler", "django.core.files.uploadhandler.TemporaryFileUploadHandler",) </code></pre> <p>So you could leave only <code>TemporaryFileUploadHandler</code> by overriding the setting in your settings.py.</p> <p><strong>Edit:</strong></p> <p>Much simpler, should have thought of it at the first place :(:</p> <pre><code>from your.models import Talk mp3 = self.files['mp3'] f = Talk.mp3.save('somename.mp3', mp3) MP3(f.mp3.path) &gt;&gt;&gt; {'TRCK': TRCK(encoding=0, text=[u'5'])} </code></pre> <p>You can save <code>InMemoryUploadedFile</code> to the disk this way and then use the path to that file to work with <code>mutagen</code>.</p> <p><strong>Edit:</strong></p> <p>Same thing without a models instance.</p> <pre><code>import os from django.core.files.storage import default_storage from django.core.files.base import ContentFile from django.conf import settings from mutagen.mp3 import MP3 mp3 = request.FILES['mp3'] # or self.files['mp3'] in your form path = default_storage.save('tmp/somename.mp3', ContentFile(mp3.read())) MP3(os.path.join(settings.MEDIA_ROOT, path)) </code></pre> <p>Note that it's saving the file in MEDIA_ROOT, when i try to save it anywhere else i get <a href="http://docs.djangoproject.com/en/1.1/ref/exceptions/#suspiciousoperation" rel="noreferrer">SuspiciousOperation</a> since there are limits to where you can write... You should delete this file after examining it i guess, the real thing will be on your model...</p> <pre><code>path = default_storage.delete('tmp/somename.mp3') </code></pre>
2,435,253
A concise, clear list of what is new in JPA2?
<p>Does anybody know of a good list of what is new in JPA 2? Not what is new with Hibernate/TopLink in the version that supports JPA 2 but what is new in the actual spec.</p>
2,440,516
1
0
null
2010-03-12 19:28:54.903 UTC
6
2010-06-30 10:32:13.967 UTC
2010-05-06 09:31:41.87 UTC
null
70,604
null
97,901
null
1
29
java|orm|jpa|jakarta-ee|jpa-2.0
5,751
<p>The link mentioned in the accepted answer doesn't say anything about the second level cache so I decided to post a quick list to summarize "What's new in JPA 2.0 (JSR-317)":</p> <ul> <li><strong>Standard properties</strong> for <code>persistence.xml</code> - E.g. <code>javax.persistence.jdbc.driver</code>, etc instead of persistence provider specific properties.</li> <li>Mixed <strong>Access</strong> Type - <code>PROPERTY</code> and <code>FIELD</code> access type can be mixed in a hierarchy and combined in a single class.</li> <li><strong>Derived Identifiers</strong> - Identifiers can be derived from relationships.</li> <li><strong><code>@ElementCollection</code></strong>, <strong><code>@OrderColumn</code></strong> - For better collection support.</li> <li><strong>Unidirectional <code>@OneToMany</code></strong> / <strong><code>@OneToOne</code></strong> - For expanded mappings.</li> <li>Shared Cache API - <strong>Second level caching</strong> in JPA, <strong>yeah</strong>!</li> <li>Locking - Support for <strong>pessimistic</strong> locking added.</li> <li><strong>Enhanced JP QL</strong> - Timestamp literals, non-polymorphic queries, collection parameter in IN expression, ordered list index, CASE statement.</li> <li>Expression and Criteria API - <strong><code>QueryBuilder</code></strong> and <strong><code>CriteriaQuery</code></strong> for programmatic construction of type-safe queries.</li> <li>API additions - Additional API on <strong><code>EntityManager</code></strong> (supported properties, <code>detach</code> method, etc) and <strong><code>Query</code></strong> (query hints).</li> <li><strong>Validation</strong> - Transparent support of Bean Validation (JSR-303) if provider is present. (Validation is optional, the JPA 2.0 spec does not require a Bean Validation implementation).</li> </ul>
3,194,875
PHP DOM replace element with a new element
<p>I have a DOM object with loaded HTML markup. I'm trying to replace all embed tags that look like this:</p> <pre><code>&lt;embed allowfullscreen="true" height="200" src="path/to/video/1.flv" width="320"&gt;&lt;/embed&gt; </code></pre> <p>With a tag like this:</p> <pre><code>&lt;a href="path/to/video/1.flv" style="display:block;width:320px;height:200px;" id="player"&gt; &lt;/a&gt; </code></pre> <p>I'm having troubles figuring this out and I don't want to use regular expression for this. Could you help me out?</p> <p>EDIT:</p> <p>This is what I have so far:</p> <pre><code> // DOM initialized above, not important foreach ($dom-&gt;getElementsByTagName('embed') as $e) { $path = $e-&gt;getAttribute('src'); $width = $e-&gt;getAttribute('width') . 'px'; $height = $e-&gt;getAttribute('height') . 'px'; $a = $dom-&gt;createElement('a', ''); $a-&gt;setAttribute('href', $path); $a-&gt;setAttribute('style', "display:block;width:$width;height:$height;"); $a-&gt;setAttribute('id', 'player'); $dom-&gt;replaceChild($e, $a); // this line doesn't work } </code></pre>
3,195,048
1
3
null
2010-07-07 13:03:25.91 UTC
6
2012-07-10 14:26:08.79 UTC
2012-07-10 14:26:08.79 UTC
null
367,456
null
95,944
null
1
30
php|dom
32,212
<p>It's easy to find elements from a DOM using <code>getElementsByTagName</code>. Indeed you wouldn't want to go near regular expressions for this.</p> <p>If the DOM you are talking about is a PHP <code>DOMDocument</code>, you'd do something like:</p> <pre><code>$embeds= $document-&gt;getElementsByTagName('embed'); foreach ($embeds as $embed) { $src= $embed-&gt;getAttribute('src'); $width= $embed-&gt;getAttribute('width'); $height= $embed-&gt;getAttribute('height'); $link= $document-&gt;createElement('a'); $link-&gt;setAttribute('class', 'player'); $link-&gt;setAttribute('href', $src); $link-&gt;setAttribute('style', "display: block; width: {$width}px; height: {$height}px;"); $embed-&gt;parentNode-&gt;replaceChild($link, $embed); } </code></pre> <p>Edit re edit:</p> <pre><code>$dom-&gt;replaceChild($e, $a); // this line doesn't work </code></pre> <p>Yeah, <code>replaceChild</code> takes the new element to replace-with as the first argument and the child to-be-replaced as the second. This is not the way round you might expect, but it is consistent with all the other DOM methods. Also it's a method of the parent node of the child to be replaced.</p> <p>(I used <code>class</code> not <code>id</code>, as you can't have multiple elements on the same page all called <code>id="player"</code>.)</p>
21,363,302
RabbitMQ - Message order of delivery
<p>I need to choose a new Queue broker for my new project. </p> <p>This time I need a scalable queue that supports pub/sub, and keeping message ordering is a must. </p> <p>I read Alexis comment: He writes:</p> <blockquote> <p>"Indeed, we think RabbitMQ provides stronger ordering than Kafka"</p> </blockquote> <p>I read the message ordering section in rabbitmq docs:</p> <blockquote> <p>"Messages can be returned to the queue using AMQP methods that feature a requeue parameter (basic.recover, basic.reject and basic.nack), or due to a channel closing while holding unacknowledged messages...With release 2.7.0 and later it is still possible for individual consumers to observe messages out of order if the queue has multiple subscribers. This is due to the actions of other subscribers who may requeue messages. From the perspective of the queue the messages are always held in the publication order."</p> </blockquote> <p>If I need to handle messages by their order, I can only use rabbitMQ with an exclusive queue to each consumer? </p> <p>Is RabbitMQ still considered a good solution for ordered message queuing?</p>
21,363,518
4
0
null
2014-01-26 12:26:50.833 UTC
28
2018-09-12 14:18:15.543 UTC
2015-12-03 09:50:22.427 UTC
null
2,928,018
null
450,602
null
1
84
queue|rabbitmq|message-queue
67,889
<p>Well, let's take a closer look at the scenario you are describing above. I think it's important to paste <a href="https://www.rabbitmq.com/semantics.html" rel="noreferrer">the documentation</a> immediately prior to the snippet in your question to provide context:</p> <blockquote> <p>Section 4.7 of the AMQP 0-9-1 core specification explains the conditions under which ordering is guaranteed: messages published in one channel, passing through one exchange and one queue and one outgoing channel will be received in the same order that they were sent. RabbitMQ offers stronger guarantees since release 2.7.0.</p> <p>Messages can be returned to the queue using AMQP methods that feature a requeue parameter (basic.recover, basic.reject and basic.nack), or due to a channel closing while holding unacknowledged messages. Any of these scenarios caused messages to be requeued at the back of the queue for RabbitMQ releases earlier than 2.7.0. From RabbitMQ release 2.7.0, messages are always held in the queue in publication order, <em>even in the presence of requeueing or channel closure.</em> (emphasis added)</p> </blockquote> <p>So, it is clear that RabbitMQ, from 2.7.0 onward, is making a rather drastic improvement over the original AMQP specification with regard to message ordering. </p> <p><strong>With multiple (parallel) consumers, order of processing cannot be guaranteed.</strong><br> The third paragraph (pasted in the question) goes on to give a disclaimer, which I will paraphrase: "if you have multiple processors in the queue, there is no longer a guarantee that messages will be processed in order." All they are saying here is that RabbitMQ cannot defy the laws of mathematics.</p> <p>Consider a line of customers at a bank. This particular bank prides itself on helping customers in the order they came into the bank. Customers line up in a queue, and are served by the next of 3 available tellers. </p> <p>This morning, it so happened that all three tellers became available at the same time, and the next 3 customers approached. Suddenly, the first of the three tellers became violently ill, and could not finish serving the first customer in the line. By the time this happened, teller 2 had finished with customer 2 and teller 3 had already begun to serve customer 3.</p> <p>Now, one of two things can happen. (1) The first customer in line can go back to the head of the line or (2) the first customer can pre-empt the third customer, causing that teller to stop working on the third customer and start working on the first. This type of pre-emption logic is not supported by RabbitMQ, nor any other message broker that I'm aware of. In either case, the first customer actually does not end up getting helped first - the second customer does, being lucky enough to get a good, fast teller off the bat. The only way to guarantee customers are helped in order is to have one teller helping customers one at a time, which will cause major customer service issues for the bank.</p> <p>I hope this helps to illustrate the problem you are asking about. It is not possible to ensure that messages get handled in order in every possible case, given that you have multiple consumers. It doesn't matter if you have multiple queues, multiple exclusive consumers, different brokers, etc. - there is no way to guarantee <em>a priori</em> that messages are answered in order with multiple consumers. But RabbitMQ will make a best-effort.</p>
37,331,571
how to setup ssh keys for jenkins to publish via ssh
<p>Jenkins requires a certificate to use the <em>ssh</em> publication and <em>ssh</em> commands. It can be configured under <code>"manage jenkins" -&gt; "Configure System"-&gt; "publish over ssh"</code>.</p> <p>The question is: How does one create the certificates?</p> <p>I have two ubuntu servers, one running Jenkins, and one for running the app.</p> <p>Do I set up a Jenkins cert and put part of it on the deployment box, or set up a cert on the deployment box, and put part of it on Jenkins? Does the cert need to be in the name of a user called Jenkins, or can it be for any user? We don't have a Jenkins user on the development box.</p> <p>I know there are a number of incompatible ssh types, which does Jenkins require?</p> <p>Has anyone found a guide on how to set this all up (how to generate keys, where to put them etc.)?</p>
37,332,975
4
0
null
2016-05-19 18:40:51.3 UTC
22
2022-09-15 05:45:43.567 UTC
2018-07-05 14:49:56.983 UTC
null
2,884,309
null
1,072,187
null
1
37
jenkins|ssh
195,649
<p>You will need to create a public/private key as the Jenkins user on your Jenkins server, then copy the public key to the user you want to do the deployment with on your target server.</p> <p>Step 1, generate public and private key on build server as user <code>jenkins</code></p> <pre><code>build1:~ jenkins$ whoami jenkins build1:~ jenkins$ ssh-keygen Generating public/private rsa key pair. Enter file in which to save the key (/var/lib/jenkins/.ssh/id_rsa): Created directory '/var/lib/jenkins/.ssh'. Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in /var/lib/jenkins/.ssh/id_rsa. Your public key has been saved in /var/lib/jenkins/.ssh/id_rsa.pub. The key fingerprint is: [...] The key's randomart image is: [...] build1:~ jenkins$ ls -l .ssh total 2 -rw------- 1 jenkins jenkins 1679 Feb 28 11:55 id_rsa -rw-r--r-- 1 jenkins jenkins 411 Feb 28 11:55 id_rsa.pub build1:~ jenkins$ cat .ssh/id_rsa.pub ssh-rsa AAAlskdjfalskdfjaslkdjf... jenkins@myserver.com </code></pre> <p>Step 2, paste the pub file contents onto the target server.</p> <pre><code>target:~ bob$ cd .ssh target:~ bob$ vi authorized_keys (paste in the stuff which was output above.) </code></pre> <p>Make sure your .ssh dir has permissoins 700 and your authorized_keys file has permissions 644</p> <p>Step 3, configure Jenkins</p> <ol> <li>In the jenkins web control panel, nagivate to "Manage Jenkins" -> "Configure System" -> "Publish over SSH"</li> <li>Either enter the path of the file e.g. "var/lib/jenkins/.ssh/id_rsa", or paste in the same content as on the target server.</li> <li>Enter your passphrase, server and user details, and you are good to go!</li> </ol>
46,641,224
What is `<<` and `&` in yaml mean?
<p>When I review the <code>cryptogen</code>(<em>a fabric command</em>) config file . I saw there symbol.</p> <pre><code>Profiles: SampleInsecureSolo: Orderer: &lt;&lt;: *OrdererDefaults ## what is the `&lt;&lt;` Organizations: - *ExampleCom ## what is the `*` Consortiums: SampleConsortium: Organizations: - *Org1ExampleCom - *Org2ExampleCom </code></pre> <p>Above there a two symbol <code>&lt;&lt;</code> and <code>*</code>.</p> <pre><code>Application: &amp;ApplicationDefaults # what is the `&amp;` mean Organizations: </code></pre> <p>As you can see there is another symbol <code>&amp;</code>. I don't know what are there mean. I didn't get any information even by reviewing the source code (<em><code>fabric/common/configtx/tool/configtxgen/main.go</code></em>)</p>
46,644,785
1
0
null
2017-10-09 07:48:03.59 UTC
6
2020-04-10 14:25:46.227 UTC
2017-10-09 08:47:57.587 UTC
null
1,000,551
null
1,634,827
null
1
35
yaml|hyperledger-fabric
20,023
<p>Well, those are elements of the YAML file format, which is used here to provide a configuration file for <code>configtxgen</code>. The "&amp;" sign mean anchor and "*" reference to the anchor, this is basically used to avoid duplication, for example:</p> <pre><code>person: &amp;person name: "John Doe" employee: &amp;employee &lt;&lt; : *person salary : 5000 </code></pre> <p>will reuse fields of person and has similar meaning as:</p> <pre><code>employee: &amp;employee name : "John Doe" salary : 5000 </code></pre> <p>another example is simply reusing value:</p> <pre><code>key1: &amp;key some very common value key2: *key </code></pre> <p>equivalent to:</p> <pre><code>key1: some very common value key2: some very common value </code></pre> <p>Since <code>abric/common/configtx/tool/configtxgen/main.go</code> uses of the shelf YAML parser you won't find any reference to these symbols in <code>configtxgen</code> related code. I would suggest to read a bit more about <a href="https://learnxinyminutes.com/docs/yaml/" rel="noreferrer">YAML file format</a>.</p>
38,552,803
How to convert a bool to a string in Go?
<p>I am trying to convert a <code>bool</code> called <code>isExist</code> to a <code>string</code> (<code>true</code> or <code>false</code>) by using <code>string(isExist)</code> but it does not work. What is the idiomatic way to do this in Go?</p>
38,552,924
4
1
null
2016-07-24 13:56:32.633 UTC
8
2021-07-19 11:48:30.243 UTC
null
null
null
null
2,828,227
null
1
148
go|type-conversion
125,615
<p>use the strconv package</p> <p><a href="https://golang.org/pkg/strconv/#FormatBool">docs</a></p> <p><code>strconv.FormatBool(v)</code></p> <blockquote> <p>func FormatBool(b bool) string FormatBool returns "true" or "false"<br> according to the value of b</p> </blockquote>
24,748,303
Selecting child view at index using Espresso
<p>With Espresso when using a custom widget view with child image views, which Matcher type can I use to select the nth child? Example:</p> <pre><code>+---------&gt;NumberSlider{id=2131296844, res-name=number_slider, visibility=VISIBLE, width=700, height=95, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=10.0, y=0.0, child-count=7} | +----------&gt;NumberView{id=-1, visibility=VISIBLE, width=99, height=95, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=true, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0} | +----------&gt;NumberView{id=-1, visibility=VISIBLE, width=100, height=95, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=true, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=99.0, y=0.0} | +----------&gt;NumberView{id=-1, visibility=VISIBLE, width=100, height=95, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=true, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=199.0, y=0.0} | +----------&gt;NumberView{id=-1, visibility=VISIBLE, width=100, height=95, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=true, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=299.0, y=0.0} | +----------&gt;NumberView{id=-1, visibility=VISIBLE, width=100, height=95, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=true, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=399.0, y=0.0} | +----------&gt;NumberView{id=-1, visibility=VISIBLE, width=100, height=95, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=true, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=499.0, y=0.0} | +----------&gt;NumberView{id=-1, visibility=VISIBLE, width=100, height=95, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=true, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=599.0, y=0.0} </code></pre>
30,073,528
4
0
null
2014-07-15 00:44:49.013 UTC
13
2020-08-17 17:43:49.87 UTC
2014-07-29 21:45:40.727 UTC
null
1,675,568
null
2,840,267
null
1
39
android|android-espresso
29,264
<pre><code> public static Matcher&lt;View&gt; nthChildOf(final Matcher&lt;View&gt; parentMatcher, final int childPosition) { return new TypeSafeMatcher&lt;View&gt;() { @Override public void describeTo(Description description) { description.appendText("with "+childPosition+" child view of type parentMatcher"); } @Override public boolean matchesSafely(View view) { if (!(view.getParent() instanceof ViewGroup)) { return parentMatcher.matches(view.getParent()); } ViewGroup group = (ViewGroup) view.getParent(); return parentMatcher.matches(view.getParent()) &amp;&amp; group.getChildAt(childPosition).equals(view); } }; } </code></pre> <p>To use it</p> <pre><code>onView(nthChildOf(withId(R.id.parent_container), 0)).check(matches(withText("I am the first child"))); </code></pre>
37,700,730
How do I configure a Jenkins Pipeline to be triggered by polling SubVersion?
<p>We have been using Jenkins for Continuous Integration for some time. A typical build job specifies the SVN repository and credentials in the "Source Code Management" section, then in the "Build Triggers" section we enable "Poll SCM" with a polling schedule of every 10 minutes (H/10 * * * *). We have updated to the latest version of Jenkins and are looking to set up pipeline builds. A typical pipeline script looks like:</p> <pre><code>node { stage 'Build' build job: 'MyApplication Build' stage 'Deploy to test environment' build job: 'MyApplication Deploy', parameters: [ [$class: 'StringParameterValue', name: 'DatabaseServer', value: 'DatabaseServer1'], [$class: 'StringParameterValue', name: 'WebServer', value: 'WebServer1'] ] stage 'RunIntegrationTests' build job: 'MyApplication Test', parameters: [ [$class: 'StringParameterValue', name: 'DatabaseServer', value: 'DatabaseServer1'], [$class: 'StringParameterValue', name: 'WebServer', value: 'WebServer1'] ] } </code></pre> <p>When the pipeline job is triggered manually then everything runs fine, however we would like this pipeline to be run every time a new revision is checked in to the SVN repository. The pipeline configuration does have a "poll SCM" build trigger option, but does not have a "Source Code Management" section where you can specify your repository. How can we achieve this?</p>
37,742,811
6
0
null
2016-06-08 11:04:37.8 UTC
7
2019-09-12 11:48:40.037 UTC
2017-05-26 13:38:10.35 UTC
null
1,000,551
null
947,017
null
1
22
svn|jenkins|triggers|jenkins-pipeline
59,399
<p>The solution that I have found to work is:</p> <ol> <li>Move the pipeline script into a file (the default is JenkinsFile) and store this in the root of my project in SubVersion.</li> <li>Set my pipeline job definition source to "Pipeline script from SCM", enter the details of where to find my project in SubVersion as per a normal Jenkins build job, and set the Script Path to point at the JenkinsFile containing the pipeline script.</li> <li>Set the build trigger of the pipeline job to "Poll SCM" and enter a schedule.</li> <li>Manually run the pipeline job</li> </ol> <p>It seemed to be step 4, manually running the pipeline job that caused the poll trigger to pick up the correct repository to poll. Before that it didn't seem to know where to look.</p>
71,706,064
React 18: Hydration failed because the initial UI does not match what was rendered on the server
<p>I'm trying to get SSR working in my app but I get the error:</p> <blockquote> <p>Hydration failed because the initial UI does not match what was rendered on the server.</p> </blockquote> <p>Live demo code is <a href="https://stackblitz.com/edit/react-j94bwy" rel="noreferrer">here</a></p> <p>Live demo of problem is <a href="https://react-j94bwy.stackblitz.io/" rel="noreferrer">here</a> (open dev tools console to see the errors):</p> <p>// App.js</p> <pre><code> import React from &quot;react&quot;; class App extends React.Component { head() { return ( &lt;head&gt; &lt;meta charSet=&quot;utf-8&quot; /&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1, shrink-to-fit=no&quot; /&gt; &lt;meta name=&quot;theme-color&quot; content=&quot;#000000&quot; /&gt; &lt;title&gt;React App&lt;/title&gt; &lt;/head&gt; ); } body() { return ( &lt;body&gt; &lt;div className=&quot;App&quot;&gt; &lt;h1&gt;Client says Hello World&lt;/h1&gt; &lt;/div&gt; &lt;/body&gt; ); } render() { return ( &lt;React.Fragment&gt; {this.head()} {this.body()} &lt;/React.Fragment&gt; ) } } export default App; </code></pre> <p>// index.js</p> <pre><code>import React from &quot;react&quot;; import * as ReactDOM from &quot;react-dom/client&quot;; import { StrictMode } from &quot;react&quot;; import App from &quot;./App&quot;; // const container = document.getElementById(&quot;root&quot;); const container = document.getElementsByTagName(&quot;html&quot;)[0] ReactDOM.hydrateRoot( container, &lt;StrictMode&gt; &lt;App /&gt; &lt;/StrictMode&gt; ); </code></pre> <p>The Html template shown in the live demo is served by the backend and generated using the following code:</p> <pre><code>const ReactDOMServer = require('react-dom/server'); const clientHtml = ReactDOMServer.renderToString( &lt;StrictMode&gt; &lt;App /&gt; &lt;/StrictMode&gt; ) </code></pre> <p>// serve clientHtml to client</p> <p>I need to dynamically generate <code>&lt;head&gt;&lt;/head&gt; and &lt;body&gt;&lt;/body&gt;</code> section as shown in the App class</p>
71,870,995
31
0
null
2022-04-01 11:17:03.643 UTC
15
2022-09-12 23:02:27.553 UTC
2022-04-01 14:14:27.387 UTC
null
1,249,664
null
1,249,664
null
1
74
reactjs
75,321
<p>I have been experiencing the same problem lately with <strong>NextJS</strong> and i am not sure if my observations are applicable to other libraries. I had been wrapping my components with an improper tag that is, <strong>NextJS</strong> is not comfortable having a <strong>p</strong> tag wrapping your <strong>divs</strong>, <strong>sections</strong> etc so it will yell <em><strong>&quot;Hydration failed because the initial UI does not match what was rendered on the server&quot;</strong></em>. So I solved this problem by examining how my elements were wrapping each other. With <strong>material UI</strong> you would need to be cautious for example if you use a <strong>Typography</strong> component as a wrapper, the default value of the component prop is &quot;p&quot; so you will experience the error if you don't change the component value to something semantic. So in my own opinion based on my personal experience the problem is caused by improper arrangement of html elements and to solve the problem in the context of <strong>NextJS</strong> one will have to reevaluate how they are arranging their html element.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>import Image from 'next/image' /** * This might give that error */ export const IncorrectComponent = ()=&gt;{ return( &lt;p&gt; &lt;div&gt;This is not correct and should never be done because the p tag has been abused&lt;/div&gt; &lt;Image src='/vercel.svg' alt='' width='30' height='30'/&gt; &lt;/p&gt; ) } /** * This will work */ export const CorrectComponent = ()=&gt;{ return( &lt;div&gt; &lt;div&gt;This is correct and should work because a div is really good for this task.&lt;/div&gt; &lt;Image src='/vercel.svg' alt='' width='30' height='30'/&gt; &lt;/div&gt; ) }</code></pre> </div> </div> </p>
25,747,146
How to properly rebase in SourceTree?
<p>SourceTree 1.6.4.0 on Windows 7.</p> <p>Let's say the following is my starting point: </p> <p><img src="https://i.stack.imgur.com/dZNR5.jpg" alt="enter image description here"></p> <pre><code> C &lt;- master / - A - B &lt;- topic </code></pre> <p>I want to rebase <strong>topic</strong> onto <strong>master</strong>.<br> My goal is to have:</p> <pre><code> C - A - B ^ ^ master topic </code></pre> <p>but I end up with: </p> <p><img src="https://i.stack.imgur.com/Lggkr.jpg" alt="enter image description here"></p> <p>I can then do</p> <pre><code>git push origin topic -f </code></pre> <p>and I get the intended result, but what is the proper way to do this in SourceTree?</p>
25,747,616
3
0
null
2014-09-09 14:25:53.013 UTC
9
2018-06-03 16:03:20.333 UTC
2014-09-17 10:28:27.477 UTC
null
1,224,069
null
3,858,446
null
1
42
git|rebase|atlassian-sourcetree
41,782
<h1>Update: SourceTree 1.9.1</h1> <p>You can enable force push in Tools/Options/Git/Enable Force Push. After it is enabled you can check &quot;Force Push&quot; check box in the &quot;Push&quot; dialog.</p> <h1>Original answer</h1> <p>You have to do a force push, because topic branch is already published and you are rewriting history. Commits A and B from origin/topic are removed if you rebase.</p> <p>You should make a merge if you don't want to do a force push, specially if you have a team members already working on topic.</p> <p>You can't do a force push with SourceTree for Windows yet (see <a href="https://answers.atlassian.com/questions/54469/how-do-i-perform-a-forced-push-push-f-from-sourcetree" rel="noreferrer">answers at atlassian forums</a>). You can vote for this feature here: <a href="https://jira.atlassian.com/browse/SRCTREEWIN-338" rel="noreferrer">https://jira.atlassian.com/browse/SRCTREEWIN-338</a></p>
25,550,643
customAnimation when calling popBackStack on a FragmentManager
<p>In my activity, with the touch of a button, I replace the current fragment with a new fragment using a custom animation, like in this example.</p> <pre><code>@Override public boolean onOptionsItemSelected(MenuItem item) { // Handle presses on the action bar items switch (item.getItemId()) { case R.id.action_anomalie: Fragment contentFragment = getFragmentManager().findFragmentById(R.id.content); if(contentFragment instanceof AnomalieListFragment) { getFragmentManager().popBackStack(); return true; } else { FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out); anomalieFragment = new AnomalieListFragment(); ft.replace(R.id.content, anomalieFragment); ft.addToBackStack(null); ft.commit(); } ... </code></pre> <p>However, <a href="http://developer.android.com/reference/android/app/FragmentManager.html#popBackStack()">popping back the stack</a> doesn't show any animation. Is there a way to specify a custom animation like we do in a FragmentTransaction with the <a href="http://developer.android.com/reference/android/app/FragmentTransaction.html#setCustomAnimations(int,%20int)">setCustomAnimations</a> method? </p>
25,571,345
1
0
null
2014-08-28 13:56:35.077 UTC
7
2014-08-29 15:21:55.03 UTC
null
null
null
null
580,041
null
1
36
android|android-fragments|android-animation
16,951
<p>After further reading of the documentation, I found that using <a href="http://developer.android.com/reference/android/app/FragmentTransaction.html#setCustomAnimations(int,%20int,%20int,%20int)" rel="noreferrer">this</a> signature of <code>setCustomAnimation</code> allowed the animation to be played when pressing the back button or calling <code>getFragmentManager().popBackStack();</code> </p> <p>I modified my code like this</p> <pre><code>... FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out, android.R.animator.fade_in, android.R.animator.fade_out); anomalieFragment = new AnomalieListFragment(); ft.replace(R.id.content, anomalieFragment); ft.addToBackStack(null); ft.commit(); ... </code></pre>
43,422,488
Relationship between the dotnet cli and the new vs2017 msbuild
<p>With the move from <code>project.json</code> to the new <code>csproj</code> format introduced with VS2017, I'm struggling to understand the difference between the <code>dotnet</code> cli and the new <code>msbuild</code> and when to use one over the other.</p> <p>1) To build a new <code>csproj</code> netstandard library from the command line, should I be calling the <code>dotnet</code> cli (for example <code>dotnet restore</code> <code>dotnet build</code>) or use <code>msbuild</code> (for example <code>msbuild ExampleNetstandard.sln</code>).</p> <p>2) Also, my understanding is that there are two versions of <code>msbuild</code>, one built on the full framework and another targeting <code>dotnet core</code>. Is this correct? Should I always use the <code>dotnet version</code></p> <p>3) Is <code>dotnet cli</code> standalone or does it require <code>msbuild</code> to be installed?. For instance when you install the dotnet SDK does this install msbuild as well? If so is this different to the version that is installed with vs2017?</p>
43,455,110
1
0
null
2017-04-15 05:17:13.383 UTC
35
2021-08-07 00:40:36.29 UTC
2020-03-13 15:42:36.237 UTC
null
201,303
null
386,287
null
1
107
visual-studio|msbuild|visual-studio-2017|csproj|dotnet-cli
20,763
<h2>Questions</h2> <blockquote> <ol> <li>To build a new csproj netstandard library from the command line, should I be calling the dotnet cli (for example dotnet restore dotnet build) or use msbuild (for example msbuild ExampleNetstandard.sln).</li> </ol> </blockquote> <p>Both do fine as currently <code>dotnet</code> is built on top of <code>msbuild</code>. So it's a matter of taste. You could also call msbuild tasks by using the dotnet CLI. (<code>dotnet msbuild &lt;msbuild_arguments&gt;</code>)</p> <p>In the beginning, all the .NET core stuff was only in <code>dotnet</code> and not in <code>msbuild</code>. This was cumbersome as a lot of stuff that was already built on <code>msbuild</code> wasn't working well with <code>dotnet</code> out of the box (e.g. Xamarin). So they moved the stuff to <code>msbuild</code> and build <code>dotnet</code> on top of <code>msbuild</code>.</p> <p><code>dotnet</code> has some features that aren't in <code>msbuild</code>, like <code>dotnet new</code>. In my opinion, <code>dotnet</code> is easier to use than <code>msbuild</code>, so I prefer <code>dotnet</code>.</p> <p>To make it more clear, I have added a comparison between <code>msbuild</code> and <code>dotnet</code> at the end of my post.</p> <blockquote> <ol start="2"> <li>Also, my understanding is that there are two versions of msbuild, one built on the full framework and another targeting dotnet core. Is this correct? Should I always use the dotnet version</li> </ol> </blockquote> <p>There is only one msbuild. dotnet CLI is using msbuild:</p> <blockquote> <p>Since CLI uses MSBuild as its build engine, we recommend that these parts of the tool be written as custom MSBuild targets and tasks, since they can then take part in the overall build process</p> </blockquote> <p><a href="https://docs.microsoft.com/en-us/dotnet/articles/core/tools/extensibility" rel="noreferrer">https://docs.microsoft.com/en-us/dotnet/articles/core/tools/extensibility</a></p> <p>The older version of <code>msbuild</code> was lacking the .NET Core support. Maybe that's the other version ;)</p> <p>I agree it's confusing, as it was very different a few months ago.</p> <blockquote> <ol start="3"> <li>Is dotnet cli standalone or does it require msbuild to be installed?. For instance when you install the dotnet SDK does this install msbuild as well? If so is this different to the version that is installed with vs2017?</li> </ol> </blockquote> <p>I wasn't sure about this, but it was easy to test. I have removed all msbuild.exe and it still worked. Found out it's using the msbuild.dll in the SDK folder. e.g. &quot;C:\Program Files\dotnet\sdk\1.0.3\MSBuild.dll&quot;</p> <p>If you remove that one, there is a proof:</p> <p><a href="https://i.stack.imgur.com/qAUGL.png" rel="noreferrer"><img src="https://i.stack.imgur.com/qAUGL.png" alt="When msbuild.dll removed" /></a></p> <p>msbuild.dll is actually msbuild.exe, as you can see in the properties:</p> <p><a href="https://i.stack.imgur.com/unsi2.png" rel="noreferrer"><img src="https://i.stack.imgur.com/unsi2.png" alt="msbuild.dll properties of SDK 1.0.3" /></a></p> <h2>Some code</h2> <p>If you look into the code of the dotnet CLI, you can see it's generating <code>msbuild</code> commands.</p> <p>For example <code>dotnet restore</code>, is created by the <a href="https://github.com/dotnet/cli/blob/0eff67d20768cff90eb125ff0e16e52cfc40ced6/src/dotnet/commands/dotnet-restore/Program.cs" rel="noreferrer"><code>RestoreCommand</code> class inside dotnet CLI</a>.</p> <p>A stripped version:</p> <pre class="lang-cs prettyprint-override"><code>public class RestoreCommand : MSBuildForwardingApp { ... public static RestoreCommand FromArgs(string[] args, string msbuildPath = null) { var result = parser.ParseFrom(&quot;dotnet restore&quot;, args); ... var msbuildArgs = new List&lt;string&gt; { &quot;/NoLogo&quot;, &quot;/t:Restore&quot;, &quot;/ConsoleLoggerParameters:Verbosity=Minimal&quot; }; ... return new RestoreCommand(msbuildArgs, msbuildPath); } public static int Run(string[] args) { RestoreCommand cmd; try { cmd = FromArgs(args); } catch (CommandCreationException e) { return e.ExitCode; } return cmd.Execute(); } ... } </code></pre> <p>You can see <code>dotnet restore</code> is just calling <code>msbuild /NoLogo /t:Restore /ConsoleLoggerParameters:Verbosity=Minimal</code></p> <hr /> <p>If you check <a href="https://github.com/dotnet/cli/blob/6cde21225e18fc48eeab3f4345ece3e6bb122e53/src/dotnet/commands/dotnet-restore/Program.cs#L36" rel="noreferrer"><code>RestoreCommand</code> in the time of <code>dotnet v1.0.0 RC2</code></a>, it wasn't using <code>msbuild</code> but was calling <code>nuget</code> directly.</p> <pre><code>return NuGet3.Restore(args, quiet); </code></pre> <h2>Mapping between <code>dotnet</code> and <code>msbuild</code></h2> <p>I made a mapping between <code>dotnet</code> and <code>msbuild</code>. It's not complete, but the important commands are there.</p> <pre><code>Dotnet | Msbuild | Remarks -----------------------|--------------------------------------------|--------------------------------- Add | | -----------------------|--------------------------------------------|--------------------------------- Build | /t:Build | -----------------------|--------------------------------------------|--------------------------------- Build --no-incremental | /t:Rebuild | -----------------------|--------------------------------------------|--------------------------------- Clean | /t:clean | -----------------------|--------------------------------------------|--------------------------------- Complete | | -----------------------|--------------------------------------------|--------------------------------- Help | | Help! -----------------------|--------------------------------------------|--------------------------------- List | | -----------------------|--------------------------------------------|--------------------------------- Migrate | - | -----------------------|--------------------------------------------|--------------------------------- Msbuild | | Forwarding all -----------------------|--------------------------------------------|--------------------------------- New | | -----------------------|--------------------------------------------|--------------------------------- Nuget | | * -----------------------|--------------------------------------------|--------------------------------- Pack | /t:pack | -----------------------|--------------------------------------------|--------------------------------- Publish | /t:publish | -----------------------|--------------------------------------------|--------------------------------- Remove | | -----------------------|--------------------------------------------|--------------------------------- Restore | /NoLogo /t:Restore | | /ConsoleLoggerParameters:Verbosity=Minimal | -----------------------|--------------------------------------------|--------------------------------- Run | /nologo /verbosity:quiet | | /p:Configuration= /p:TargetFramework | -----------------------|--------------------------------------------|--------------------------------- Sln | | Not in msbuild -----------------------|--------------------------------------------|--------------------------------- Store | /t:ComposeStore | -----------------------|--------------------------------------------|--------------------------------- Test | /t:VSTest /v:quiet /nologo | -----------------------|--------------------------------------------|--------------------------------- Vstest | | Forwarding to vstest.console.dll </code></pre> <p><code>*</code> dotnet nuget: Adding/removing packages to csproj, also limited set of nuget.exe, see <a href="https://docs.microsoft.com/en-us/nuget/install-nuget-client-tools#feature-availability" rel="noreferrer">comparison</a></p> <p>PS <a href="https://meta.stackexchange.com/questions/73566/is-there-markdown-to-create-tables">no markdown tables in SO :(</a></p>
356,483
Python regex findall numbers and dots
<p>I'm using re.findall() to extract some version numbers from an HTML file:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; text = "&lt;table&gt;&lt;td&gt;&lt;a href=\"url\"&gt;Test0.2.1.zip&lt;/a&gt;&lt;/td&gt;&lt;td&gt;Test0.2.1&lt;/td&gt;&lt;/table&gt; Test0.2.1" &gt;&gt;&gt; re.findall("Test([\.0-9]*)", text) ['0.2.1.', '0.2.1', '0.2.1'] </code></pre> <p>but I would like to only get the ones that do not end in a dot. The filename might not always be .zip so I can't just stick .zip in the regex.</p> <p>I wanna end up with:</p> <pre><code>['0.2.1', '0.2.1'] </code></pre> <p>Can anyone suggest a better regex to use? :)</p>
356,494
1
0
null
2008-12-10 15:33:09.6 UTC
4
2020-06-11 09:58:45.413 UTC
null
null
null
Ashy
32,933
null
1
11
python|regex|findall
38,391
<pre><code>re.findall(r"Test([0-9.]*[0-9]+)", text) </code></pre> <p>or, a bit shorter:</p> <pre><code>re.findall(r"Test([\d.]*\d+)", text) </code></pre> <p>By the way - you do not need to escape the dot in a character class. Inside <code>[]</code> the <code>.</code> has no special meaning, it just matches a literal dot. Escaping it has no effect.</p>