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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
17,868,232 | How to use Tomcat 8 in Eclipse? | <p><strong>EDIT 2014-02-07: Eclipse Luna is here, and support for Tomcat 8 is included in the bundled WTP : ) Happy days!</strong></p>
<p>Tomcat 8 is still in development, but you can get it <a href="https://repository.apache.org/content/repositories/snapshots/org/apache/tomcat/tomcat/8.0-SNAPSHOT/">here</a>. Now there is a RC version on the main Apache Tomcat page. Update 2/27/14: 8 is released now, and adapters built for WTP, just not integrated into eclipse bundles yet. Soon!</p>
<p>In Eclipse Kepler though, there is no supported adapter in the add server list for Tomcat 8. the Tomcat 7 adapter doesn't work, and it doesn't look like there's a new extension for it to download in the "Install new Extension" dialog.</p>
<p>Is my only option to get it (Tomcat 8) running locally outside of Eclipse and maybe hook a remote debugger into it for stepping through code? Will that even work for Eclipse Kepler + Tomcat 8? IntelliJ IDEA 12 couldn't do it in the 30 minutes of time I put into that path.</p>
<p>If you're wondering why I'm trying to do this at all, I'm playing around with Spring 4.0.0.M1 and 4.0.0.M2 WebSocket stuff. They (per Rossen Stoyanchev's Spring 4.0 <a href="http://blog.springsource.org/2013/05/23/spring-framework-4-0-m1-websocket-support/">blog post</a> and examples) use JSR-356, which is implemented in Tomcat 8, theoretically to be back-ported at some point to Tomcat 7.</p>
<p>An answer to the broader question of "How can I easily get a development environment going for Spring 4 WebSocket support?" would be nice, but it would also still be nice to know how to plug in unsupported web servers to Eclipse.</p>
<p>Cheers,
E</p>
<p>**Update 8/7/13 - Rossen Stoyanchev updated the Spring <a href="http://blog.springsource.org/2013/07/24/spring-framework-4-0-m2-websocket-messaging-architectures">4.0.0.M2 blog</a> and added some jpda wisdom and shared that yeah, he's using remote debugging:</p>
<blockquote>
<p>That said, it's not very hard to debug with Tomcat 8 inside Eclipse. Just change the last line in bin/startup.sh to be (note the addition of "jpda"):</p>
<pre><code> exec "$PRGDIR"/"$EXECUTABLE" jpda start "$@"
</code></pre>
<p>Inside Eclipse create a remote debugging configuration for localhost port 80, launch it after starting Tomcat, and you can put breakpoints in the source code.</p>
</blockquote>
<p>Thanks Rossen!</p>
<p>**Update 9/29/13 - Eclipse Kepler SR1 just arrived, but alas! No WTP support for Tomcat 8. Tomcat 8 is up to RC3.</p>
<p>**Updates 12/5/13 </p>
<ul>
<li>Blog url fix.</li>
<li>Tomcat 8 up to RC5.</li>
<li>Bug to track WTP fix in Eclipse to support Tomcat 8 <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=422340">HERE</a>.</li>
<li>IntelliJ IDEA new version 13 says it now supports Tomcat 8. Haven't tried yet personally.</li>
</ul> | 21,912,109 | 11 | 1 | null | 2013-07-25 20:33:22.233 UTC | 17 | 2017-07-12 06:51:13.667 UTC | 2014-08-03 14:12:53.573 UTC | null | 589,259 | null | 2,620,121 | null | 1 | 51 | eclipse|tomcat|websocket|eclipse-kepler | 173,296 | <p><strong><em>UPDATE</em>: Eclipse Mars EE and later have native support for Tomcat8. Use this only if you have an earlier version of eclipse.</strong></p>
<hr>
<p>The latest version of Eclipse still does not support Tomcat 8, but you can add the new version of WTP and Tomcat 8 support will be added natively. To do this:</p>
<ul>
<li>Download the latest version of Eclipse for <a href="https://www.eclipse.org/downloads/packages/eclipse-ide-java-ee-developers/keplersr2" rel="noreferrer"><strong>Java EE</strong></a></li>
<li>Go to the <a href="http://download.eclipse.org/webtools/downloads/" rel="noreferrer">WTP downloads page</a>, select the latest version (currently 3.6), and download the zip (under
Traditional Zip Files...Web App Developers). <a href="http://www.eclipse.org/downloads/download.php?file=/webtools/downloads/drops/R3.6.0/I-3.6.0-20140213154746/wtp4x-I-3.6.0-20140213154746.zip" rel="noreferrer">Here's the current link</a>.</li>
<li>Copy the all of the files in features and plugins directories of the downloaded WTP into the corresponding Eclipse directories in your Eclipse folder (overwriting the existing files).</li>
</ul>
<p>Start Eclipse and you should have a Tomcat 8 option available when you go to deploy.
<img src="https://i.stack.imgur.com/F9d35.png" alt="enter image description here"></p> |
6,909,314 | Is it possible to replace values in SQL query? | <p>I would like to know if it is possible in an SQL query to replace some values by something else, or if I need to do that in post-processing.</p>
<p>Let me explain. I have this table:</p>
<pre><code>|username| accepted |
|--------|----------|
| toto | NULL |
|--------|----------|
| foo | 0 |
|--------|----------|
| Rick | 1 |
|--------|----------|
| bar | 1 |
|--------|----------|
</code></pre>
<p>I want to know the numbers of row per value of <code>accepted</code> (nullable bit). I'm running this query:</p>
<pre><code>SELECT [accepted], count(*) FROM my_table GROUP BY [accepted]
</code></pre>
<p>Which should return:</p>
<pre><code>NULL 1
false 1
true 2
</code></pre>
<p>Is there some way to replace the <code>accepted</code> values by more meaningful labels? Ideally I would like to have something like:</p>
<pre><code>not_available 1
not_accepted 1
accepted 2
</code></pre>
<p>Is that feasible with SQL server 2008 R2?</p>
<p>Thx.</p> | 6,909,390 | 4 | 1 | null | 2011-08-02 08:39:15.153 UTC | 1 | 2011-08-02 14:14:39.133 UTC | 2011-08-02 09:03:26.263 UTC | null | 67,392 | null | 29,568 | null | 1 | 5 | sql|sql-server|tsql | 39,249 | <p>If you have a few values:</p>
<pre><code>SELECT CASE [accepted]
WHEN 0 THEN 'not_accepted'
WHEN 1 THEN 'accepted '
ELSE 'not_available' END AS accepted
, count(*)
FROM my_table
GROUP BY CASE [accepted]
WHEN 0 THEN 'not_accepted'
WHEN 1 THEN 'accepted '
ELSE 'not_available' END
</code></pre> |
23,742,626 | What exactly does '__weak typeof(self)weakSelf = self;' mean | <p>This is used in the weakify pattern of Objective-C</p>
<p>My guess is that it means: assign a weak reference to self with the name 'weakSelf' and the typeof self (e.g. MyViewController)</p>
<p>If it's correct and looks obvious to you: I want to be absolutely sure to get this right. Thanks.</p> | 23,742,765 | 4 | 4 | null | 2014-05-19 16:18:26.027 UTC | 12 | 2022-08-16 07:29:55.583 UTC | 2022-08-16 07:29:55.583 UTC | null | 624,459 | null | 624,459 | null | 1 | 30 | objective-c|typeof|weak | 21,842 | <blockquote>
<p>My guess is that it means: assign a weak reference to self with the name <code>weakSelf</code> and the <code>typeof</code> self (e.g. <code>MyViewController</code>)</p>
</blockquote>
<p>Yes, that is almost exactly what it means. The type of <code>self</code> would be <code>MyViewController*</code> (with an asterisk) not <code>MyViewController</code>.</p>
<p>The idea behind using this syntax instead of simply writing</p>
<pre><code>MyViewController __weak *weakSelf = self;
</code></pre>
<p>is making it easier to refactor the code. The use of <code>typeof</code> also makes it possible to define a code snippet that can be pasted anywhere in your code.</p> |
18,701,984 | Displaying the hex value of a string from a oracle varchar2? | <p>We are having problems with text that is encoded in some different ways but kept in a single column in a table. Long story. On MySQL, I can do "select hex(str) from table where" and I see the bytes of the string exactly as I set them.</p>
<p>On Oracle, I have a string which starts with the Turkish character İ, which is the Unicode character 0x0130 "LATIN CAPITAL LETTER WITH DOT ABOVE". This is in my printed copy of the Unicode Version 2.0 book. In UTF-8, this character is 0xc4b0.</p>
<p>We have very old client apps we need to support. They would send us this text in "windows-1254". We used to just close our eyes, store it, and hand it back later. Now we need the Unicode, or are being given the Unicode.</p>
<p>So I have:</p>
<pre><code>SQL> select id, name from table where that thing;
ID NAME
------ ------------------------
746 Ý
</code></pre>
<p>This makes sense because the "İ" is 0xdd in windows-1254 and 0xdd in wondows-1252 is "Ý". My terminal is presumably set to the usual windows-1252.</p>
<p>But:</p>
<pre><code>SQL> select id, rawtohex(name) from table where that thing;
ID RAWTOHEX(NAME)
------ ------------------------
746 C39D
</code></pre>
<p>There seems to be no equivalent to the hex(name) function in MySQL. But I <em>must</em> be missing something. What am I missing here?</p>
<p>My java code has to take the utf8 that I am supplied and save a utf8 copy and a windows-1252 copy. The java code gives me:</p>
<pre><code>bytes (utf8): c4 b0
bytes (1254): dd
</code></pre>
<p>Yet, when I save it, the client does not get the correct character. And when I try to see what Oracle has actually stored, i get the garbage seen above. I have <em>no</em> idea where the C39D is coming from. Any suggestions?</p>
<p>We have ojdbc14.jar built into all of our applications and we are connecting to a database that says it is "Oracle Database 11g Enterprise Edition Release 11.2.0.2.0 - 64bit Production".</p> | 18,702,627 | 2 | 0 | null | 2013-09-09 15:39:37.3 UTC | 4 | 2016-03-23 16:02:42.24 UTC | null | null | null | null | 869,809 | null | 1 | 21 | oracle|unicode|utf-8|turkish|ojdbc | 109,154 | <p>Use the <a href="http://docs.oracle.com/cd/E11882_01/server.112/e41084/functions055.htm" rel="noreferrer"><code>dump</code></a> function to see how Oracle stores data internally.</p>
<p>You seem to have a misunderstanding on how Oracle treats <code>VARCHAR2</code> characters set conversions: you can't influence how Oracle stores its data <strong>physically</strong>. (Also if you haven't already, it's helpful to read: <a href="http://www.joelonsoftware.com/articles/Unicode.html" rel="noreferrer">The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets</a>).</p>
<p>Your client speaks to Oracle only in binary. In fact all systems exchange information in binary only. To understand each others, it is necessary that both systems know what language (character set) is being used.</p>
<p>In your case we can reconstruct what happens:</p>
<ol>
<li>Your client sends the byte <code>dd</code> to Oracle and says it is <code>windows-1252</code> (instead of <code>1254)</code>. </li>
<li>Oracle looks up its character set table and sees that this data is translated to the symbol <code>Ý</code> in this character set.</li>
<li>Oracle <strong>logically</strong> stores this information in its table.</li>
<li><p>Since Oracle is setup in <code>UTF-8</code>, it converts this data to the <code>UTF-8</code> binary reprensentation of <code>Ý</code>:</p>
<pre><code>SQL> SELECT rawtohex('Ý') FROM dual;
RAWTOHEX('Ý')
--------------
C39D
</code></pre></li>
<li><p>Oracle stores <code>C39D</code> internally.</p></li>
</ol>
<p>As you can see, the problem comes from the first step: there is a problem of setup. As long as you don't fix this, the systems won't be able to successfully dialogue.</p>
<p>The conversion is <strong>automatic</strong> when you use <code>VARCHAR2</code> because this datatype is a logical text symbol interface (you have next to no control over forcing the actual binary data being stored).</p> |
41,196,027 | What is the difference between void and static void function in C? | <p>I have a two <strong>C</strong> files.</p>
<p>file1.c</p>
<pre><code>int main()
{
func();
return 0;
}
</code></pre>
<p>file2.c</p>
<pre><code>static void func(void)
{
puts("func called");
}
</code></pre>
<p>But, if I compile the above code with command <code>cc file2.c file1.c</code>, I got the below, </p>
<pre><code>undefined reference to `func'
collect2: error: ld returned 1 exit status
</code></pre>
<p>But, If I remove <code>static</code> keyword inside <strong>file2.c</strong> and compile the above code with command <code>cc file2.c file1.c</code>, It's succesfully run. </p>
<p>So, I have a question, <strong>What is the difference between void and static void function in C?</strong></p> | 41,196,173 | 1 | 4 | null | 2016-12-17 06:35:44.607 UTC | 13 | 2016-12-17 10:05:39.59 UTC | 2016-12-17 10:05:39.59 UTC | null | 5,612,562 | null | 5,612,562 | null | 1 | 27 | c|static | 58,961 | <blockquote>
<p>What is the difference between void and static void function in C?</p>
</blockquote>
<p>The real question should be what is the difference between <code>static</code> and <code>non-static</code> function? (the return type <code>void</code> is irrelevant, it can be <code>int</code> or anything else).</p>
<p>The <code>static</code> keyword is somewhat over used. When it applies to function, it means that the function has <a href="https://stackoverflow.com/questions/1358400/what-is-external-linkage-and-internal-linkage-in-c">internal linkage</a>, ie its scope is limited to within a <a href="https://stackoverflow.com/questions/8342185/translation-unit-in-c-and-c">translation unit</a> (simply as a source file).</p>
<p>By default, function is non-static and has external linkage. The function can be used by a different source file.</p>
<p>In your case, the error manifests itself because <code>static func</code> cannot be used in other source file.</p>
<hr>
<p>When should <code>static</code> functions be used?</p>
<p><code>static</code> functions are normally used to avoid name conflicts in bigger project. If you inspect Linux kernel source, example in <code>drivers/net</code> you would see many <code>static void</code> functions in there. Drivers are developed by different vendors and the usage of <code>static</code> functions ensure that they can name the functions the way they want without worrying of name conflicts with other non-related driver developers.</p> |
877,943 | how to configure a rails app (redmine) to run as a service on windows? | <p>I'm using redmine as a ticket manager, and I'd like to configure it to be run automatically when windows starts up.</p>
<p>How can I configure it to be run as a service?</p>
<p>--</p>
<p>Just asked the question to document it, I hope somebody may find it useful...</p> | 878,049 | 7 | 0 | null | 2009-05-18 14:10:37.41 UTC | 14 | 2018-08-23 13:04:57.927 UTC | 2009-05-18 14:31:00.3 UTC | null | 47,633 | null | 47,633 | null | 1 | 16 | ruby-on-rails|windows|service|redmine | 19,129 | <p><strong>1. using webrick:</strong></p>
<p>ref: <a href="http://www.redmine.org/boards/1/topics/4123" rel="nofollow noreferrer">http://www.redmine.org/boards/1/topics/4123</a></p>
<ul>
<li><p>Download and install the Windows NT Resource Kit from
<a href="http://www.microsoft.com/downloads/details.aspx?familyid=9d467a69-57ff-4ae7-96ee-b18c4790cffd&displaylang=en" rel="nofollow noreferrer">http://www.microsoft.com/downloads/details.aspx?familyid=9d467a69-57ff-4ae7-96ee-b18c4790cffd&displaylang=en</a></p></li>
<li><p>Create the service by running this command:</p>
<pre><code>path\INSTSRV.EXE your_service_name path\SRVANY.EXE
</code></pre>
<p>in my case <code>path</code> is:</p>
<pre><code>"C:\Program Files\Windows NT Resource Kit\INSTSRV.EXE" redmine_webrick "C:\Program Files\Windows NT Resource Kit\SRVANY.EXE"
</code></pre>
<p>could be also <code>C:\Program Files\Windows Resource Kits\Tools\</code>.</p></li>
<li><p>Run regedit (Start -> Run -> regedit)</p>
<ul>
<li><p>Add the following registry key if it's not already there:</p>
<p>HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\your_service_name</p></li>
<li><p>Right click on this registry key and select New -> Key. Name it <code>Parameters</code>.</p></li>
<li><p>Add two values to the <code>Parameters</code> key. Right click on the parameters key, New -> String Value. Name it <code>Application</code>. Now create another one named <code>AppParameters</code>. Give them the following values:</p>
<ul>
<li>Application: <code>PathToRuby.exe</code>, eg. <code>C:\ruby\bin\Ruby.exe</code></li>
<li>AppParameters: <code>C:\RUBYAPP\script\server -e production</code>, where <code>RUBYAPP</code> is the directory that contains the redmine website.</li>
</ul>
<p>Example: <code>C:\redmine\script\server -p 2000 -e production</code> (-p indicates the port webrick will be listening to, and -e the environment used)</p></li>
</ul></li>
</ul>
<p>Now you can go to Administrative Tools -> Services. There you can start your service (the one with name <code>your_service_name</code>) and test whether or not it is working properly. It should be noted that the service will be marked as started prior to WEBrick finishing its boot procedure. You should give it 1min or so before trying to hit the service to verify that it is working correctly.</p>
<p><strong>2. using mongrel:</strong></p>
<p>ref: <a href="http://mongrel.rubyforge.org/wiki" rel="nofollow noreferrer">http://mongrel.rubyforge.org/wiki</a>
ref: <a href="http://mongrel.rubyforge.org/wiki/Win32" rel="nofollow noreferrer">http://mongrel.rubyforge.org/wiki/Win32</a></p>
<p>first install mongrel and mongrel_service gem</p>
<pre><code>gem install mongrel
gem install mongrel_service
</code></pre>
<p>then create the service</p>
<pre><code>mongrel_rails service::install -N redmine_mongrel -c c:\redmine -p 3000 -e production
</code></pre>
<p><strong>3. using thin:</strong></p>
<p>References: </p>
<ul>
<li><a href="http://code.macournoyer.com/thin/" rel="nofollow noreferrer">http://code.macournoyer.com/thin/</a></li>
<li><a href="http://www.astarbe.com/es/trucos/windows/srvany_convierte_una_aplicacion_en_servicio" rel="nofollow noreferrer">http://www.astarbe.com/es/trucos/windows/srvany_convierte_una_aplicacion_en_servicio</a></li>
</ul>
<p>Instructions:</p>
<ol>
<li><p>First install thin (you'll need to install rack gem, if not already
installed)</p>
<pre><code>gem install rack
gem install thin
</code></pre></li>
<li><p>Follow the same steps indicated for webrick, but add another value named "AppDirectory". This is needed in order to avoid using c:\ruby\bin\thin.bat If I just pointed to the bat file, I couldn't stop the service.</p>
<p>In <code>HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\redmine_thin\Parameters</code> add the following keys:</p>
<blockquote>
<p>Application: c:\ruby\bin\ruby.exe </p>
<p>AppDirectory: c:\redmine</p>
<p>AppParameters: c:\ruby\bin\thin start -p 4000 -e production</p>
</blockquote></li>
</ol>
<h2>------------------------------------------------------------------------------------------</h2>
<p>You can control any of your service with the following commands:</p>
<blockquote>
<p>net start redmine_xxx</p>
<p>net stop redmine_xxx</p>
<p>sc config redmine_xxx start= auto</p>
<p>sc config redmine_xxx start= auto dependency= MySql</p>
<p>sc delete redmine_xxx</p>
</blockquote> |
185,444 | Why is MPI considered harder than shared memory and Erlang considered easier, when they are both message-passing? | <p>There's a lot of interest these days in Erlang as a language for writing parallel programs on multicore. I've heard people argue that Erlang's message-passing model is easier to program than the dominant shared-memory models such as threads. </p>
<p>Conversely, in the high-performance computing community the dominant parallel programming model has been MPI, which also implements a message-passing model. But in the HPC world, this message-passing model is generally considered very difficult to program in, and people argue that shared memory models such as OpenMP or UPC are easier to program in. </p>
<p>Does anybody know why there is such a difference in the perception of message-passing vs. shared memory in the IT and HPC worlds? Is it due to some fundamental difference in how Erlang and MPI implement message passing that makes Erlang-style message-passing much easier than MPI? Or is there some other reason? </p> | 256,120 | 7 | 1 | null | 2008-10-09 00:10:25.713 UTC | 17 | 2012-06-19 10:39:04.937 UTC | null | null | null | lorin | 742 | null | 1 | 34 | erlang|multicore|parallel-processing|mpi | 10,560 | <p>I agree with all previous answers, but I think a key point that is not made totally clear is that one reason that MPI might be considered hard and Erlang easy is the match of model to the domain. </p>
<p>Erlang is based on a concept of local memory, asynchronous message passing, and shared state solved by using some form of global database that all threads can get to. It is designed for applications that do not move a whole lot of data around, and that is not supposed to explode out to a 100k separate nodes that need coordination.</p>
<p>MPI is based on local memory and message passing, and is intended for problems where moving data around is a key part of the domain. High-performance computing is very much about taking the dataset for a problem, and splitting it up among a host of compute resources. And that is pretty hard work in a message-passing system as data has to be explicitly distributed with balancing in mind. Essentially, MPI can be viewed as a grudging admittance that shared memory does not scale. And it is targeting high-performance computation spread across 100k processors or more. </p>
<p>Erlang is not trying to achieve the highest possible performance, rather to decompose a naturally parallel problem into its natural threads. It was designed with a totally different type of programming tasks in mind compared to MPI. </p>
<p>So Erlang is best compared to pthreads and other rather local heterogeneous thread solutions, rather than MPI which is really aimed at a very different (and to some extent inherently harder) problem set.</p> |
152,834 | Default port for SQL Server | <p>I need to know the default port settings for the following services</p>
<ol>
<li>SQL Server</li>
<li>SQL Browser</li>
<li>SQL Reporting services</li>
<li>SQL Analysis services</li>
</ol>
<p>I need to know the port settings for these services for different versions of SQL Server (2000,2005,2008)</p>
<p>Also let me know whether the default port setting will change based on sql server versions.</p> | 152,892 | 7 | 2 | null | 2008-09-30 12:32:40.463 UTC | 9 | 2022-06-03 03:22:59.217 UTC | 2022-06-03 03:22:59.217 UTC | balaweblog | 19,123,103 | balaweblog | 22,162 | null | 1 | 64 | asp.net|sql|sql-server | 121,995 | <ol>
<li><p>The default SQL Server port is 1433 but only if it's a default install. Named instances get a random port number.</p></li>
<li><p>The browser service runs on port UDP 1434.</p></li>
<li><p>Reporting services is a web service - so it's port 80, or 443 if it's SSL enabled.</p></li>
<li><p>Analysis services is 2382 but only if it's a default install. Named instances get a random port number.</p></li>
</ol> |
1,065,168 | Does disposing streamreader close the stream? | <p>I am sending a stream to methods to write on, and in those methods I am using a binary reader/wrtier. When the reader/writer gets disposed, either by <code>using</code> or just when it is not referenced, is the stream closed as well??</p>
<p>I would send a BinaryReader/Writer, but I am using a StreamReader too (maybe I should go around that. I am only using that for GetLine and ReadLine). This is quite troublesome if it closes the stream each time a writer/reader gets closed.</p> | 1,065,196 | 7 | 0 | null | 2009-06-30 18:17:55.253 UTC | 33 | 2021-08-16 20:56:05.713 UTC | 2009-06-30 18:34:05.49 UTC | null | 18,907 | null | 112,830 | null | 1 | 178 | c#|stream|streamreader | 78,235 | <p>Yes, <code>StreamReader</code>, <code>StreamWriter</code>, <code>BinaryReader</code> and <code>BinaryWriter</code> all close/dispose their underlying streams when you call <code>Dispose</code> on them. They <em>don't</em> dispose of the stream if the reader/writer is just garbage collected though - you should always dispose of the reader/writer, preferrably with a <code>using</code> statement. (In fact, none of these classes have finalizers, nor should they have.)</p>
<p>Personally I prefer to have a using statement for the stream as well. You can nest <code>using</code> statements without braces quite neatly:</p>
<pre><code>using (Stream stream = ...)
using (StreamReader reader = new StreamReader(stream, Encoding.Whatever))
{
}
</code></pre>
<p>Even though the <code>using</code> statement for the stream is somewhat redundant (unless the <code>StreamReader</code> constructor throws an exception) I consider it best practice as then if you get rid of the <code>StreamReader</code> and just use the stream directly at a later date, you'll already have the right disposal semantics.</p> |
1,070,974 | yield return works only for IEnumerable<T>? | <p>Can I use <code>yield return</code> when the return type is an <code>IGrouping<TKey, TElement></code> or an <code>IDictionary<TKey, TValue></code>?</p> | 1,071,008 | 8 | 1 | null | 2009-07-01 19:46:34.23 UTC | 2 | 2022-05-22 22:24:29.17 UTC | 2015-10-02 07:27:25.84 UTC | null | 1,087,135 | null | 48,465 | null | 1 | 36 | c#|.net|ienumerable | 18,140 | <p><code>yield return</code> works for exactly 4 cases:</p>
<ul>
<li><code>IEnumerable</code></li>
<li><code>IEnumerable<T></code></li>
<li><code>IEnumerator</code></li>
<li><code>IEnumerator<T></code></li>
</ul>
<p>This is because it has to build a state machine internally; a dictionary (etc) wouldn't be possible with this. You can of course just <code>return</code> a suitable type instead.</p> |
1,159,087 | Inlining in Java | <p>In C++ I can declare a method "inline" and the compiler is likely to inline it. As far as I understand there is no such keyword in Java.</p>
<p>Inlining is done if the JVM decides to do so? Can I influence this decision somehow?</p> | 1,159,118 | 8 | 0 | null | 2009-07-21 13:11:55.047 UTC | 6 | 2015-02-18 21:48:05.227 UTC | 2015-02-18 21:48:05.227 UTC | null | 3,001,761 | null | 141,456 | null | 1 | 40 | java|jvm|inlining|inline-method | 13,186 | <p>A couple of the other answers have suggested that only final methods can be inlined - this is not true, as HotSpot is smart enough to be able to inline non-final methods so long as they haven't been overridden <em>yet</em>. When a class is loaded which overrides the method, it can undo its optimisation. Obviously making the method final mean that's never required...</p>
<p>Basically let the JVM do its job - it's likely to be a lot better at working out where to inline than you are.</p>
<p>Do you have a situation where you're convinced that the JVM isn't doing a good job? Assuming you're using HotSpot, have you tried using the server version instead of client? That can make a <em>huge</em> difference.</p> |
12,702 | Returning DataTables in WCF/.NET | <p>I have a WCF service from which I want to return a DataTable. I know that this is often a highly-debated topic, as far as whether or not returning DataTables is a good practice. Let's put that aside for a moment.</p>
<p>When I create a DataTable from scratch, as below, there are no problems whatsoever. The table is created, populated, and returned to the client, and all is well:</p>
<pre><code>[DataContract]
public DataTable GetTbl()
{
DataTable tbl = new DataTable("testTbl");
for(int i=0;i<100;i++)
{
tbl.Columns.Add(i);
tbl.Rows.Add(new string[]{"testValue"});
}
return tbl;
}
</code></pre>
<p>However, as soon as I go out and hit the database to create the table, as below, I get a CommunicationException "The underlying connection was closed: The connection was closed unexpectedly."</p>
<pre><code>[DataContract]
public DataTable GetTbl()
{
DataTable tbl = new DataTable("testTbl");
//Populate table with SQL query
return tbl;
}
</code></pre>
<p>The table is being populated correctly on the server side. It is significantly smaller than the test table that I looped through and returned, and the query is small and fast - there is no issue here with timeouts or large data transfer. The same exact functions and DataContracts/ServiceContracts/BehaviorContracts are being used.</p>
<p>Why would the way that the table is being populated have any bearing on the table returning successfully?</p> | 42,332 | 8 | 0 | null | 2008-08-15 20:26:01.447 UTC | 12 | 2016-12-19 04:49:58.767 UTC | 2015-07-25 21:48:51.883 UTC | Chris Fournier | 63,550 | theprise | 940 | null | 1 | 51 | c#|.net|wcf|web-services|datatable | 56,529 | <p>For anyone having similar problems, I have solved my issue. It was several-fold.</p>
<ul>
<li>As Darren suggested and Paul backed up, the Max..Size properties in the configuration needed to be enlarged. The SvcTraceViewer utility helped in determining this, but it still does not always give the most helpful error messages. </li>
<li>It also appears that when the Service Reference is updated on the client side, the configuration will sometimes not update properly (e.g. Changing config values on the server will not always properly update on the client. I had to go in and change the Max..Size properties multiple times on both the client and server sides in the course of my debugging)</li>
<li><p>For a DataTable to be serializable, it needs to be given a name. The default constructor does not give the table a name, so:</p>
<pre><code>return new DataTable();
</code></pre>
<p>will not be serializable, while:</p>
<pre><code>return new DataTable("someName");
</code></pre>
<p>will name the table whatever is passed as the parameter. </p>
<p>Note that a table can be given a name at any time by assigning a string to the <code>TableName</code> property of the DataTable.</p>
<pre><code>var table = new DataTable();
table.TableName = "someName";
</code></pre></li>
</ul>
<p>Hopefully that will help someone.</p> |
699,468 | Remove HTML tags not on an allowed list from a Python string | <p>I have a string containing text and HTML. I want to remove or otherwise disable some HTML tags, such as <code><script></code>, while allowing others, so that I can render it on a web page safely. I have a list of allowed tags, how can I process the string to remove any other tags?</p> | 699,483 | 9 | 3 | null | 2009-03-30 23:25:29.423 UTC | 67 | 2021-04-06 13:08:03.08 UTC | 2019-02-04 20:34:24.57 UTC | user212218 | 400,617 | null | 25,991 | null | 1 | 77 | python|html | 44,120 | <p>Here's a simple solution using <a href="http://www.crummy.com/software/BeautifulSoup/" rel="noreferrer">BeautifulSoup</a>:</p>
<pre><code>from bs4 import BeautifulSoup
VALID_TAGS = ['strong', 'em', 'p', 'ul', 'li', 'br']
def sanitize_html(value):
soup = BeautifulSoup(value)
for tag in soup.findAll(True):
if tag.name not in VALID_TAGS:
tag.hidden = True
return soup.renderContents()
</code></pre>
<p>If you want to remove the contents of the invalid tags as well, substitute <code>tag.extract()</code> for <code>tag.hidden</code>.</p>
<p>You might also look into using <a href="http://codespeak.net/lxml/" rel="noreferrer">lxml</a> and <a href="http://utidylib.berlios.de/" rel="noreferrer">Tidy</a>.</p> |
920,646 | Uncaught SoapFault exception: [HTTP] Error Fetching http headers | <p>I'm trying to create a soap connection to Magento's web services, however I'm getting an error when I try and create an instance of the soap client class. I can view the wsdl file in firefox without problems and I can watch php make the request for the wsdl in apaches logs but it still fails. Nusoap can connect. </p>
<pre><code>$proxy = new SoapClient('someaddress?wsdl');
</code></pre>
<p>The error is </p>
<pre><code><b>Fatal error</b>: Uncaught SoapFault exception: [HTTP] Error Fetching http headers in /home/sites/xxx/xxx_main/system/application/views/contentpage_templates/gift_service.php:29
Stack trace:
[internal function]: SoapClient-&gt;__doRequest('&lt;?xml version=&quot;...', 'http://cornishw...', 'urn:Mage_Api_Mo...', 1, 0)
[internal function]: SoapClient-&gt;__call('call', Array)
/home/sites/xxx/xxx_main/system/application/views/contentpage_templates/gift_service.php(29): SoapClient-&gt;call(NULL, 'catalog_categor...', 5, 'giftshop')
/home/sites/xxx/xxx_main/system/application/libraries/MY_Loader.php(586): include('/home/sites/cor...')
/home/sites/xxx/xxx_main/system/application/libraries/MY_Loader.php(228): MY_Loader-&gt;_ci_load(Array, '')
/home/sites/xxx/xxx_main/system/application/modules/contentpage/controllers/contentpage.php(44): MY_Loader-&gt;view('contentpage_tem...', false, true)
[internal function]: Contentpage-&gt;index()
/home/sites/xxx in <b>/home/sites/xxx/xxx_main/system/application/views/contentpage_templates/gift_service.php</b> on line <b>29</b>
</code></pre>
<p>Thanks</p> | 1,152,603 | 10 | 1 | null | 2009-05-28 12:44:52.833 UTC | 6 | 2018-05-26 10:21:01.19 UTC | 2011-01-07 16:54:44.107 UTC | null | 1,288 | null | 113,721 | null | 1 | 26 | php|soap|magento|wsdl | 103,366 | <p>Try to set :</p>
<pre><code>default_socket_timeout = 120
</code></pre>
<p>in your <code>php.ini</code> file.</p> |
55,342 | How can I kill all sessions connecting to my oracle database? | <p>I need to quickly (and forcibly) kill off all external sessions connecting to my oracle database without the supervision of and administrator.</p>
<p>I don't want to just lock the database and let the users quit gracefully.</p>
<p>How would I script this?</p> | 55,359 | 10 | 0 | null | 2008-09-10 21:16:10.613 UTC | 16 | 2016-03-30 04:47:34.46 UTC | 2016-02-29 14:52:09.66 UTC | CodeSlave | 685 | CodeSlave | 685 | null | 1 | 29 | oracle|session|sqlplus|kill|database-administration | 133,723 | <p>This answer is heavily influenced by a conversation here: <a href="http://www.tek-tips.com/viewthread.cfm?qid=1395151&page=3" rel="noreferrer">http://www.tek-tips.com/viewthread.cfm?qid=1395151&page=3</a></p>
<pre><code>ALTER SYSTEM ENABLE RESTRICTED SESSION;
begin
for x in (
select Sid, Serial#, machine, program
from v$session
where
machine <> 'MyDatabaseServerName'
) loop
execute immediate 'Alter System Kill Session '''|| x.Sid
|| ',' || x.Serial# || ''' IMMEDIATE';
end loop;
end;
</code></pre>
<p>I skip killing sessions originating on the database server to avoid killing off Oracle's connections to itself.</p> |
1,125,226 | Styling checkboxes, radio buttons and dropdowns | <p>How can I style HTML checkboxes, radio buttons and dropdowns? Or can I?</p>
<p>I'd like to use an image for checkboxes or radiobuttons, and the same for lists - the dropdown arrow doesn't look nice most of the time.</p> | 1,125,320 | 11 | 0 | null | 2009-07-14 13:01:09.113 UTC | 7 | 2020-01-08 21:19:07.72 UTC | 2012-05-05 15:51:54.507 UTC | null | 707,111 | null | 119,032 | null | 1 | 16 | css | 47,146 | <p>see this 2 links for jQuery Plugins for Styling Checkbox & Radio Buttons:</p>
<p><a href="http://line25.com/articles/jquery-plugins-for-styling-checkbox-radio-buttons" rel="noreferrer">http://line25.com/articles/jquery-plugins-for-styling-checkbox-radio-buttons</a></p>
<p><a href="http://www.queness.com/post/204/25-jquery-plugins-that-enhance-and-beautify-html-form-elements" rel="noreferrer">http://www.queness.com/post/204/25-jquery-plugins-that-enhance-and-beautify-html-form-elements</a></p> |
232,435 | How do I restrict foreign keys choices to related objects only in django | <p>I have a two way foreign relation similar to the following</p>
<pre><code>class Parent(models.Model):
name = models.CharField(max_length=255)
favoritechild = models.ForeignKey("Child", blank=True, null=True)
class Child(models.Model):
name = models.CharField(max_length=255)
myparent = models.ForeignKey(Parent)
</code></pre>
<p>How do I restrict the choices for Parent.favoritechild to only children whose parent is itself? I tried</p>
<pre><code>class Parent(models.Model):
name = models.CharField(max_length=255)
favoritechild = models.ForeignKey("Child", blank=True, null=True, limit_choices_to = {"myparent": "self"})
</code></pre>
<p>but that causes the admin interface to not list any children.</p> | 252,087 | 11 | 2 | null | 2008-10-24 03:52:50.317 UTC | 27 | 2020-10-28 21:42:50.427 UTC | null | null | null | Jeff Mc | 25,521 | null | 1 | 72 | python|django|django-models | 66,085 | <p>I just came across <a href="http://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.limit_choices_to" rel="noreferrer">ForeignKey.limit_choices_to</a> in the Django docs.
Not sure yet how this works, but it might just be the right thing here.</p>
<p><strong>Update:</strong> ForeignKey.limit_choices_to allows to specify either a constant, a callable or a Q object to restrict the allowable choices for the key. A constant obviously is of no use here, since it knows nothing about the objects involved.</p>
<p>Using a callable (function or class method or any callable object) seems more promising. However, the problem of how to access the necessary information from the HttpRequest object remains. Using <a href="https://stackoverflow.com/questions/160009/django-model-limitchoicestouser-user">thread local storage</a> may be a solution.</p>
<p><strong>2. Update:</strong> Here is what has worked for me:</p>
<p>I created a middleware as described in the link above. It extracts one or more arguments from the request's GET part, such as "product=1", and stores this information in the thread locals.</p>
<p>Next there is a class method in the model that reads the thread local variable and returns a list of ids to limit the choice of a foreign key field.</p>
<pre><code>@classmethod
def _product_list(cls):
"""
return a list containing the one product_id contained in the request URL,
or a query containing all valid product_ids if not id present in URL
used to limit the choice of foreign key object to those related to the current product
"""
id = threadlocals.get_current_product()
if id is not None:
return [id]
else:
return Product.objects.all().values('pk').query
</code></pre>
<p>It is important to return a query containing all possible ids if none was selected so that the normal admin pages work ok.</p>
<p>The foreign key field is then declared as:</p>
<pre><code>product = models.ForeignKey(
Product,
limit_choices_to={
id__in=BaseModel._product_list,
},
)
</code></pre>
<p>The catch is that you have to provide the information to restrict the choices via the request. I don't see a way to access "self" here.</p> |
342,181 | What's the best way to validate currency input in UITextField? | <p>My application allows the user to enter a numeric value (currency) in a <code>UITextField</code> control, but the keyboard layout that I wish was available is unfortunately not one of the built-in options, so I had to choose the "Numbers & Punctuation" option in Interface Builder. Here's the corresponding dialog window in IB:</p>
<p><a href="https://i.stack.imgur.com/FbnvH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FbnvH.png" alt="enter image description here"></a></p>
<p>So when my application asks the user for the input, it is displaying the following:</p>
<p><a href="https://i.stack.imgur.com/u9tbB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/u9tbB.png" alt="enter image description here"></a></p>
<p>Which is perfectly fine, but look at all of the extra keys available to the user! One could easily enter "12;56!" in the text field, and I assume I have to validate that somehow.</p>
<p>So my question is: how do I validate currency values entered into a <code>UITextField</code>?</p> | 342,231 | 13 | 0 | null | 2008-12-04 21:40:08.773 UTC | 13 | 2018-09-28 13:03:00.727 UTC | 2018-09-28 13:03:00.727 UTC | Chris Hanson | 123,632 | jpm | 35,478 | null | 1 | 18 | iphone|cocoa-touch | 21,111 | <p>Perhaps you could attach a <strong><code>UITextFieldDelegate</code></strong> on the control and have it implement <strong><code>textField:shouldChangeCharactersInRange:replacementString:</code></strong> That way, if it sees any characters that you don't want in the field, it can reject them.</p> |
355,650 | C++ HTML template framework, templatizing library, HTML generator library | <p>I am looking for template/generator libraries for C++ that are similar to eg. Ruby's Erb, Haml, PHP's Smarty, etc.</p>
<p>It would be great if I it would sport some basic features like loops, if/else, int conversion to strings, etc.</p>
<p>Parameter passing to template rendering engine is also important if I could pass all of them in a hash map instead of calling some function for each of parameters.</p>
<p>Do you have any recommendations?</p>
<p>I can see also the possibility of embedding languages like Lua, however I haven't found a templatizing library for that either.</p> | 412,985 | 13 | 2 | null | 2008-12-10 10:41:54.027 UTC | 49 | 2019-12-29 22:07:12.627 UTC | 2016-06-03 06:31:39.297 UTC | null | 264,325 | Marcin Gil | 5,731 | null | 1 | 64 | c++|template-engine | 42,342 | <p>A quick review of the mentioned project.</p>
<p><a href="http://rgrz.tumblr.com/post/13808947359/review-of-html-template-engines-in-c-language" rel="nofollow noreferrer">http://rgrz.tumblr.com/post/13808947359/review-of-html-template-engines-in-c-language</a></p>
<h2>ClearSilver</h2>
<ul>
<li>Site: <a href="http://www.clearsilver.net" rel="nofollow noreferrer">http://www.clearsilver.net</a></li>
<li>Project: <a href="https://code.google.com/p/clearsilver/" rel="nofollow noreferrer">https://code.google.com/p/clearsilver/</a></li>
<li>Group: <a href="http://tech.groups.yahoo.com/group/ClearSilver" rel="nofollow noreferrer">http://tech.groups.yahoo.com/group/ClearSilver</a></li>
<li>License: New BSD License</li>
<li>Language: C</li>
<li>Last Update: Nov 28, 2011</li>
<li>Last Release: 0.10.5 on July 12, 2007</li>
<li>Document: Rich</li>
<li>Community: Medium (<10 discussion per month)</li>
</ul>
<h2>Teng</h2>
<ul>
<li>Site: <a href="http://teng.sourceforge.net" rel="nofollow noreferrer">http://teng.sourceforge.net</a></li>
<li>Code: <a href="http://teng.svn.sourceforge.net/teng/" rel="nofollow noreferrer">http://teng.svn.sourceforge.net/teng/</a></li>
<li>Group: <a href="http://sourceforge.net/projects/teng/" rel="nofollow noreferrer">http://sourceforge.net/projects/teng/</a></li>
<li>License: New BSD License</li>
<li>Language: C++</li>
<li>Binding: php, python</li>
<li>Last Update: Mar 8, 2011</li>
<li>Last Release: 2.1.1 on Mar 8, 2011</li>
<li>Document: Rich</li>
<li>Community: Low (rare discussion since 2010)</li>
</ul>
<h2>Templatizer</h2>
<ul>
<li>Site: <a href="http://www.lazarusid.com/libtemplate.shtml" rel="nofollow noreferrer">http://www.lazarusid.com/libtemplate.shtml</a></li>
<li>Project: download only</li>
<li>Group: none</li>
<li>License: free to use</li>
<li>Language: C (low level)/C++ (interface) mixed</li>
<li>Last Update: unknown</li>
<li>Last Release: unknown</li>
<li>Document: none</li>
<li>Community: none</li>
</ul>
<h2>HTML Template C++</h2>
<ul>
<li>Site: <a href="http://nulidex.com/code/docs/html_template/" rel="nofollow noreferrer">http://nulidex.com/code/docs/html_template/</a></li>
<li>Project: <a href="http://sourceforge.net/projects/htmltemplatec" rel="nofollow noreferrer">http://sourceforge.net/projects/htmltemplatec</a> </li>
<li>Group: <a href="http://sourceforge.net/projects/htmltemplatec" rel="nofollow noreferrer">http://sourceforge.net/projects/htmltemplatec</a></li>
<li>License: GPL</li>
<li>Language: C++</li>
<li>Last Update: Mar 27, 2011</li>
<li>Last Release: Beta 0.7.4, Mar 27, 2011</li>
<li>Document: Medium</li>
<li>Community: none</li>
</ul>
<h2>ctpp</h2>
<ul>
<li>Site: <a href="http://ctpp.havoc.ru/en/" rel="nofollow noreferrer">http://ctpp.havoc.ru/en/</a></li>
<li>Project: download only</li>
<li>Group: none</li>
<li>License: BSD License</li>
<li>Language: C++ with C API</li>
<li>Last Update: Oct 5, 2011</li>
<li>Last Release: Version 2.7.2 on Oct 5, 2011</li>
<li>Document: Rich</li>
<li>Community: none</li>
</ul>
<h2>Wt</h2>
<ul>
<li>Site: <a href="http://www.webtoolkit.eu/wt/" rel="nofollow noreferrer">http://www.webtoolkit.eu/wt/</a></li>
<li>Project: <a href="http://www.webtoolkit.eu/wt/" rel="nofollow noreferrer">http://www.webtoolkit.eu/wt/</a></li>
<li>Group: <a href="http://www.webtoolkit.eu/wt/community" rel="nofollow noreferrer">http://www.webtoolkit.eu/wt/community</a></li>
<li>License: GPL and Commercial</li>
<li>Language: C++</li>
<li>Last Update: Nov 29, 2011</li>
<li>Last Release: 3.2.0 on Nov 29, 2011</li>
<li>Document: Rich</li>
<li>Community: Low (rare activity)</li>
</ul>
<h2>Flate</h2>
<ul>
<li>Site: <a href="http://flate.dead-inside.org/" rel="nofollow noreferrer">http://flate.dead-inside.org/</a></li>
<li>Project: none</li>
<li>Group: none</li>
<li>License: LGPL v2.1</li>
<li>Language: C</li>
<li>Last Update: Sep 4, 2010</li>
<li>Last Release: 2.0 on Sep 4, 2010</li>
<li>Document: Poor</li>
<li>Community: none</li>
</ul>
<h2>Jinja2C++</h2>
<ul>
<li>Site: <a href="https://jinja2cpp.dev" rel="nofollow noreferrer">https://jinja2cpp.dev</a></li>
<li>Project: <a href="https://github.com/jinja2cpp" rel="nofollow noreferrer">https://github.com/jinja2cpp</a></li>
<li>Group: <a href="https://gitter.im/Jinja2Cpp/Lobby" rel="nofollow noreferrer">https://gitter.im/Jinja2Cpp/Lobby</a></li>
<li>Conan packages: <a href="https://bintray.com/beta/#/flexferrum/conan-packages/jinja2cpp:flexferrum?tab=overview" rel="nofollow noreferrer">https://bintray.com/beta/#/flexferrum/conan-packages/jinja2cpp:flexferrum?tab=overview</a></li>
<li>License: MPL-2.0</li>
<li>Language: C++14/17</li>
<li>Last Update: Oct 01, 2019</li>
<li>Last Release: 1.0.0 on Oct 01, 2019</li>
<li>Document: Moderate</li>
<li>Community: none</li>
</ul> |
1,119,289 | How to show the "Are you sure you want to navigate away from this page?" when changes committed? | <p>Here in stackoverflow, if you started to make changes then you attempt to navigate away from the page, a javascript confirm button shows up and asks: "Are you sure you want to navigate away from this page?" blee blah bloo...</p>
<p>Has anyone implemented this before, how do I track that changes were committed?
I believe I could do this myself, I am trying to learn the good practices from you the experts.</p>
<p>I tried the following but still doesn't work:</p>
<pre><code><html>
<body>
<p>Close the page to trigger the onunload event.</p>
<script type="text/javascript">
var changes = false;
window.onbeforeunload = function() {
if (changes)
{
var message = "Are you sure you want to navigate away from this page?\n\nYou have started writing or editing a post.\n\nPress OK to continue or Cancel to stay on the current page.";
if (confirm(message)) return true;
else return false;
}
}
</script>
<input type='text' onchange='changes=true;'> </input>
</body>
</html>
</code></pre>
<p>Can anyone post an example?</p> | 1,119,324 | 18 | 2 | null | 2009-07-13 12:57:09.073 UTC | 127 | 2021-04-01 06:22:17.937 UTC | 2014-04-30 13:29:10.753 UTC | null | 90,674 | null | 75,500 | null | 1 | 304 | javascript|html|message|onbeforeunload|confirm | 262,187 | <h2>Update (2017)</h2>
<p>Modern browsers now consider displaying a custom message to be a security hazard and it has therefore been <a href="https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload#Browser_compatibility" rel="noreferrer">removed</a> from all of them. Browsers now only display generic messages. Since we no longer have to worry about setting the message, it is as simple as:</p>
<pre><code>// Enable navigation prompt
window.onbeforeunload = function() {
return true;
};
// Remove navigation prompt
window.onbeforeunload = null;
</code></pre>
<p>Read below for legacy browser support.</p>
<h2>Update (2013)</h2>
<p>The orginal answer is suitable for IE6-8 and FX1-3.5 (which is what we were targeting back in 2009 when it was written), but is rather out of date now and won't work in most current browsers - I've left it below for reference.</p>
<p>The <code>window.onbeforeunload</code> is not treated consistently by all browsers. It should be a function reference and not a string (as the original answer stated) but that will work in older browsers because the check for most of them appears to be whether anything is assigned to <code>onbeforeunload</code> (including a function that returns <code>null</code>).</p>
<p>You set <code>window.onbeforeunload</code> to a function reference, but in older browsers you have to set the <code>returnValue</code> of the event instead of just returning a string:</p>
<pre><code>var confirmOnPageExit = function (e)
{
// If we haven't been passed the event get the window.event
e = e || window.event;
var message = 'Any text will block the navigation and display a prompt';
// For IE6-8 and Firefox prior to version 4
if (e)
{
e.returnValue = message;
}
// For Chrome, Safari, IE8+ and Opera 12+
return message;
};
</code></pre>
<p>You can't have that <code>confirmOnPageExit</code> do the check and return null if you want the user to continue without the message. You still need to remove the event to reliably turn it on and off:</p>
<pre><code>// Turn it on - assign the function that returns the string
window.onbeforeunload = confirmOnPageExit;
// Turn it off - remove the function entirely
window.onbeforeunload = null;
</code></pre>
<h2>Original answer (worked in 2009)</h2>
<p>To turn it on:</p>
<pre><code>window.onbeforeunload = "Are you sure you want to leave?";
</code></pre>
<p>To turn it off:</p>
<pre><code>window.onbeforeunload = null;
</code></pre>
<p>Bear in mind that this isn't a normal event - you can't bind to it in the standard way.</p>
<p>To check for values? That depends on your validation framework.</p>
<p>In jQuery this could be something like (very basic example):</p>
<pre><code>$('input').change(function() {
if( $(this).val() != "" )
window.onbeforeunload = "Are you sure you want to leave?";
});
</code></pre> |
624,926 | How do I detect whether a Python variable is a function? | <p>I have a variable, <code>x</code>, and I want to know whether it is pointing to a function or not.</p>
<p>I had hoped I could do something like:</p>
<pre><code>>>> isinstance(x, function)
</code></pre>
<p>But that gives me:</p>
<pre class="lang-none prettyprint-override"><code>Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'function' is not defined
</code></pre>
<p>The reason I picked that is because</p>
<pre><code>>>> type(x)
<type 'function'>
</code></pre> | 624,939 | 28 | 8 | null | 2009-03-09 03:31:30.623 UTC | 135 | 2022-01-15 07:35:40.63 UTC | 2018-02-24 11:38:54.78 UTC | null | 63,550 | Daniel H | 14,799 | null | 1 | 911 | python | 357,291 | <p>If this is for Python 2.x or for Python 3.2+, you can use <a href="https://docs.python.org/3/library/functions.html#callable" rel="noreferrer"><code>callable()</code></a>. It used to be deprecated, but is now undeprecated, so you can use it again. You can read the discussion here: <a href="http://bugs.python.org/issue10518" rel="noreferrer">http://bugs.python.org/issue10518</a>. You can do this with:</p>
<pre><code>callable(obj)
</code></pre>
<p>If this is for Python 3.x but before 3.2, check if the object has a <code>__call__</code> attribute. You can do this with:</p>
<pre><code>hasattr(obj, '__call__')
</code></pre>
<p>The oft-suggested <a href="https://docs.python.org/3/library/types.html#types.FunctionType" rel="noreferrer"><code>types.FunctionTypes</code></a> or <a href="https://docs.python.org/3/library/inspect.html#inspect.isfunction" rel="noreferrer"><code>inspect.isfunction</code></a> approach (both do <a href="https://github.com/python/cpython/blob/ea46c7bc503d1103d60c0ec7023bb52c5defa11d/Lib/inspect.py#L159-L170" rel="noreferrer">the exact same thing</a>) comes with a number of caveats. It returns <code>False</code> for non-Python functions. Most <a href="https://docs.python.org/3/library/functions.html" rel="noreferrer">builtin functions</a>, for example, are implemented in C and not Python, so they return <code>False</code>:</p>
<pre><code>>>> isinstance(open, types.FunctionType)
False
>>> callable(open)
True
</code></pre>
<p>so <code>types.FunctionType</code> might give you surprising results. The proper way to check properties of duck-typed objects is to ask them if they quack, not to see if they fit in a duck-sized container.</p> |
34,545,354 | "Internal error in the expression evaluator" | <p>I've encountered a problem in expression evaluator of visual studio 2015 that says "Internal error in the expression evaluator", after some investigations I found that this is caused by an assembly that is loaded using reflection. This assembly wouldn't throw any exceptions but after that, vs exp evaluator will fail.
This is not the only assembly that I load, there are some good working ones that don't influent the evaluator.</p>
<p>To overcome this issue I had to check 'Menu > options > debugging > Use Managed Compatibility Mode' but this disables the 'Edit & Continue' feature, what can I do?</p>
<p>Properties of the causer assembly:</p>
<ul>
<li>its name is the same as the main assembly
(i changed its name but nothing happened)</li>
<li>all of my projects are using dotNet 4.5</li>
<li>all root namespaces are same
(all of the assemblies are so)</li>
</ul>
<p>Thanks!</p> | 34,550,540 | 11 | 5 | null | 2015-12-31 10:55:14.98 UTC | 16 | 2022-04-20 08:04:20.703 UTC | 2017-03-16 12:18:46.833 UTC | null | 6,357,360 | null | 5,733,707 | null | 1 | 66 | c#|debugging|visual-studio-2015 | 44,542 | <p>That sounds like a bug in the expression evaluator. For a better workaround, instead of checking "Use Managed Compatibility Mode", check "Use the legacy C# and VB expression evaluators". This should enable you to continue using Edit and Continue as well as other features added within the last few releases.</p>
<p>In terms of the "Internal error in expression evaluator", can you please open an issue by going to Help -> Send Feedback -> Report a problem? That will help us fix the problem in future releases.</p> |
6,692,706 | Reading DataSet in C# | <p>If we have filled a DataSet using a select query in C#, how can we read the column values?</p>
<p>I want to do something like this:</p>
<pre><code>string name = DataSetObj.rows[0].columns["name"]
</code></pre>
<p>What would the correct syntax look like to achieve my goal?</p> | 6,692,720 | 5 | 0 | null | 2011-07-14 11:52:50.47 UTC | 4 | 2018-03-12 12:36:56.37 UTC | 2018-03-12 12:34:34.69 UTC | null | 397,817 | null | 277,581 | null | 1 | 5 | c#|dataset | 47,710 | <pre><code>foreach(var row in DataSetObj.Tables[0].Rows)
{
Console.WriteLine(row["column_name"]);
}
</code></pre> |
6,334,592 | One DbContext per request in ASP.NET MVC (without IOC container) | <p>Apologies if this has already been answered, but how do you guarantee one Entity Framework DbContext per request if you are not using an IOC container? (The answers I've come across so far deal with IOC container solutions.)</p>
<p>It seems like most solutions hook into the <code>HttpContext.Current.Items</code> dictionary, but how do you guarantee disposal of the DbContext when the request is finished? (Or is disposal not absolutely necessary with an EF <code>DbContext</code>?)</p>
<p><strong>Edit</strong></p>
<p>I'm currently instantiating and disposing my DbContext in my controllers, but I also have several separate instantiations of my DbContext in ActionFilters and my MembershipProvider (and I just noticed, also a couple validators). So, I thought it might be a good idea to centralize instantiation and storage of my DbContext to reduce overhead.</p> | 6,334,865 | 6 | 1 | null | 2011-06-13 18:29:36.9 UTC | 44 | 2013-12-23 14:30:37.237 UTC | 2011-06-13 20:11:01.353 UTC | null | 129,164 | null | 129,164 | null | 1 | 51 | asp.net-mvc|entity-framework|asp.net-mvc-3|entity-framework-4.1|ef-code-first | 25,634 | <p>I would use the BeginRequest/EndRequest method, this helps ensure that your context is disposed of properly when the request is over with.</p>
<pre><code>protected virtual void Application_BeginRequest()
{
HttpContext.Current.Items["_EntityContext"] = new EntityContext();
}
protected virtual void Application_EndRequest()
{
var entityContext = HttpContext.Current.Items["_EntityContext"] as EntityContext;
if (entityContext != null)
entityContext.Dispose();
}
</code></pre>
<p>And in your EntityContext class...</p>
<pre><code>public class EntityContext
{
public static EntityContext Current
{
get { return HttpContext.Current.Items["_EntityContext"] as EntityContext; }
}
}
</code></pre> |
6,497,685 | How do I detect non-ASCII characters in a string? | <p>If I have a PHP string, how can I determine if it contains at least one non-ASCII character or not, in an efficient way? And by non-ASCII character, I mean any character that is not part of this table, <a href="http://www.asciitable.com/" rel="noreferrer">http://www.asciitable.com/</a>, positions 32 - 126 inclusive.</p>
<p>So not only does it have to be part of the ASCII table, but it also has to be printable. I want to detect a string that contains at least one character that does not meet these specifications (either non-printable ASCII, or a different character altogether, such as a Unicode character that is not part of that table.</p> | 6,497,946 | 9 | 4 | null | 2011-06-27 19:09:31.233 UTC | 10 | 2020-08-18 12:07:56.973 UTC | 2011-06-27 19:23:09.407 UTC | null | 732,284 | null | 732,284 | null | 1 | 42 | php|string | 51,516 | <p>I found it more useful to detect if any character falls out of the list</p>
<pre><code>if(preg_match('/[^\x20-\x7e]/', $string))
</code></pre> |
6,453,640 | How to include external font in WPF application without installing it | <p>How to include external font in WPF application without installing it</p>
<p>I tried this code </p>
<pre><code> System.Drawing.Text.PrivateFontCollection privateFonts = new System.Drawing.Text.PrivateFontCollection();
privateFonts.AddFontFile("C:\\Documents and Settings\\somefont.ttf");
System.Drawing.Font font = new Font(privateFonts.Families[0], 12);
this.label1.Font = font;
</code></pre>
<p>It working correctly in Windows Form Application but not in WPF.</p> | 6,856,459 | 13 | 0 | null | 2011-06-23 12:00:48.897 UTC | 46 | 2021-05-07 14:27:06.687 UTC | null | null | null | null | 606,144 | null | 1 | 75 | c#|wpf|fonts | 90,746 | <p>I use such XAML code:</p>
<pre><code><Style x:Key="Hatten">
<Setter Property="TextElement.FontFamily" Value="Resources/#HATTEN" />
</Style>
</code></pre>
<p>#HATTEN - reference to hatten.tft in Resources.</p>
<p>Using the Style:</p>
<pre><code> <TextBlock x:Name="lblTitle" Style="{DynamicResource Hatten}" FontSize="72"></TextBlock>
</code></pre> |
42,324,317 | You must pass a component to the function returned by connect. Instead received undefined | <p>The code below gives </p>
<blockquote>
<p>Uncaught Error: You must pass a component to the function returned by connect. Instead received undefined</p>
</blockquote>
<p><strong>List.js</strong></p>
<pre><code>import React from 'react';
import { connect, bindActionCreators } from 'react-redux';
import PostList from '../components/PostList'; // Component I wish to wrap with actions and state
import postList from '../Actions/PostList' //Action Creator defined by me
const mapStateToProps = (state, ownProps) => {
return state.postsList
}
const mapDispatchToProps = (dispatch) => {
return bindActionCreators({"postsList":postList},dispatch)
}
export default connect(mapStateToProps, mapDispatchToProps)(PostList);
</code></pre>
<p><strong>PostList.js</strong></p>
<pre><code>import React from 'react'
export const PostList = (props) => {
return <div>List</div>
}
</code></pre>
<p>Please help me with a solution?</p> | 42,329,949 | 5 | 7 | null | 2017-02-19 06:24:39.843 UTC | 3 | 2020-11-23 10:36:14.813 UTC | 2017-02-19 06:32:25.62 UTC | null | 295,783 | null | 7,584,211 | null | 1 | 24 | javascript|reactjs|redux|react-redux | 45,154 | <p>You are doing <code>import PostList from '../components/PostList';</code> so you need to use <code>export default</code> in your PostList.js file.</p>
<p>Otherwise you need to do <code>import { PostList } from '../components/PostList';</code>.</p>
<p>To whoever is interested, here is a nice article about es6 import/export syntax: <a href="http://www.2ality.com/2014/09/es6-modules-final.html" rel="noreferrer">http://www.2ality.com/2014/09/es6-modules-final.html</a></p> |
15,678,467 | how to add padding between menu items in android? | <p><img src="https://i.stack.imgur.com/wi9CI.png" alt="enter image description here"></p>
<p>I'm having menu items being inflated from res/menu/menu.xml on to ActionBar, how do I add padding between menu items using android?</p>
<p></p>
<pre><code><item
android:id="@+id/home"
android:showAsAction="always"
android:title="Home"
android:icon="@drawable/homeb"/>
<item
android:id="@+id/location"
android:showAsAction="always"
android:title="Locations"
android:icon="@drawable/locationb"/>
<item
android:id="@+id/preQualify"
android:showAsAction="always"
android:title="Pre-Qualify"
android:icon="@drawable/prequalityb"/>
<item
android:id="@+id/products"
android:showAsAction="always"
android:title="Products"
android:icon="@drawable/productb"/>
</code></pre>
<p></p>
<p>Java file:</p>
<pre><code>@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_store_locator, menu);
return true;
}
</code></pre> | 15,679,629 | 3 | 0 | null | 2013-03-28 09:40:40.557 UTC | 3 | 2014-09-09 13:22:44.107 UTC | 2013-03-28 10:11:28.517 UTC | null | 1,716,809 | null | 1,716,809 | null | 1 | 15 | android|android-layout|android-actionbar | 47,739 | <p>Found solution, added following lines in styles.xml file and it worked!!</p>
<pre><code><style name="AppTheme" parent="AppBaseTheme">
<item name="android:actionButtonStyle">@style/MyActionButtonStyle</item>
</style>
<style name="MyActionButtonStyle" parent="AppBaseTheme">
<item name="android:minWidth">20dip</item>
<item name="android:padding">0dip</item>
</style>
</code></pre> |
15,624,236 | Is there a way in sbt to convert compiler warnings to errors so the build fails? | <p>I want to "ban" some or all compiler warnings. </p> | 15,624,502 | 3 | 1 | null | 2013-03-25 20:34:49.837 UTC | 1 | 2021-04-07 12:40:17.683 UTC | null | null | null | null | 945,819 | null | 1 | 29 | scala|sbt | 5,886 | <p>You can pass options from sbt to the scala compiler, including the one that turns warnings into errors.</p>
<p>I usually add these:</p>
<pre><code>scalacOptions ++= Seq("-unchecked", "-deprecation", "-feature", "-Xfatal-warnings"),
</code></pre> |
15,968,911 | How to clear text area with a button in html using javascript? | <p>I have button in html</p>
<pre><code><input type="button" value="Clear">
<textarea id='output' rows=20 cols=90></textarea>
</code></pre>
<p>If I have an external javascript (.js) function, what should I write?</p> | 15,968,947 | 5 | 1 | null | 2013-04-12 10:24:01.423 UTC | 9 | 2022-02-14 14:29:05.173 UTC | 2020-06-27 04:41:08.853 UTC | null | 8,422,953 | null | 2,270,858 | null | 1 | 35 | javascript|html|button|textarea | 169,809 | <p>Change in your html with adding the function on the button click</p>
<pre><code> <input type="button" value="Clear" onclick="javascript:eraseText();">
<textarea id='output' rows=20 cols=90></textarea>
</code></pre>
<p>Try this in your js file:</p>
<pre><code>function eraseText() {
document.getElementById("output").value = "";
}
</code></pre> |
15,994,603 | How to sleep in the Linux kernel? | <p>Can I use the msleep() function to sleep for a specified amount of time in kernel space? If so, which header files do I need to include? <code>#include <linux/time.h></code> doesn't seem to be the right one. Is there perhaps a better function for this purpose?</p> | 15,994,682 | 2 | 0 | null | 2013-04-14 00:58:12.227 UTC | 6 | 2021-03-02 16:18:18.433 UTC | 2017-05-24 06:15:51.177 UTC | null | 895,245 | null | 850,271 | null | 1 | 36 | c|linux|linux-kernel|sleep | 69,395 | <p>I needed to include <code><linux/delay.h></code> to use msleep in kernel space.</p> |
15,490,658 | How to handle XML services in AngularJS? | <p>My company has thousands of existing xml web services and is starting to adopt AngularJs for new projects.</p>
<p>The tutorial over at <a href="http://angularjs.org/">http://angularjs.org/</a> uses json services exclusively. It looks like they make a service call in the controller, parse the resulting JSON, and pass the resulting object directly to the view.</p>
<p>What do I do with XML? I see four options:</p>
<ol>
<li><p>Parse it and pass the DOM object directly to the UI(view).</p></li>
<li><p>Put a JSON wrapper around my XML services on the server side.</p></li>
<li><p>convert the DOM object to JSON with some library on the client side and convert it back when I make the post/put requests.</p></li>
<li><p>Convert the DOM object to a JavaScript object manually on the client side.</p></li>
</ol>
<p>What the correct approach and why?</p> | 15,492,222 | 5 | 0 | null | 2013-03-19 02:45:44.253 UTC | 13 | 2016-11-08 11:24:15.29 UTC | 2016-05-24 14:33:17.48 UTC | null | 2,333,214 | null | 1,267,413 | null | 1 | 53 | xml|service|angularjs|backend | 83,907 | <p>If option 2 is relatively easy for you (like adding one-line JSON conversions in your back-end controllers, for example), then it's probably a good investment, as the JSON is leaner over the wire, far less work on the client side and generally preferred by RESTful API consumers (in case there are other consumers).</p>
<p>Having recently done this kind of work, I'd say the next best path (if option 2 is difficult) would be to use response and request <a href="http://docs.angularjs.org/api/ng.$http" rel="noreferrer">transformers</a> to perform conversions between your XML and JavaScript objects, which is a variation somewhere between your options 3 and 4. The DOMParser object is native code, so it parses XML plenty fast. Transforming the XML DOM to JavaScript objects and generating XML from JavaScript objects are both fairly straightforward recursive algorithms. This approach decouples all of the rest of your client-side code from the back-end representation, which would not be the case if you went with your option 1. Such decoupling would allow you to make direct use of a JSON-based RESTful interface, should such an opportunity arise.</p>
<p>Selecting any option that involves JSON/JavaScript objects will often involve dealing with impedance mismatch issues like XML attributes, XML collections vs. JS arrays and XML mixed content representation. If your data models are simple enough, or you don't mind living with the solutions provided by out-of-the-box transformers between XML and JSON (e.g., redundant object containment, numbered text properties to represent disjoint text mixed with elements), then this may not be an issue for you. Otherwise, there are opportunities for customizing transformation behavior at either end of the request imperatively (though sadly not declaratively, as far as I've seen).</p> |
56,577,201 | Why is --isolatedModules error fixed by any import? | <p>In a create-react-app typescript project, I tried to write this just to test some stuff quickly:</p>
<pre class="lang-js prettyprint-override"><code>// experiment.test.ts
it('experiment', () => {
console.log('test');
});
</code></pre>
<p>But it gives me the following error, with a red squiggly beneath <code>it</code>:</p>
<blockquote>
<p>All files must be modules when the '--isolatedModules' flag is provided.</p>
</blockquote>
<p>However, if I change the file to the following, then everything apparently is fine (except for the unused import of course):</p>
<pre class="lang-js prettyprint-override"><code>// experiment.test.ts
import { Component} from 'react'; // literally anything, don't even have to use it
it('test', () => {
console.log('test');
});
</code></pre>
<p>Why? What is happening here? What does <code>--isolatedModules</code> actually mean/do?</p> | 56,577,324 | 7 | 3 | null | 2019-06-13 09:15:42.71 UTC | 22 | 2022-01-19 17:47:42.483 UTC | 2019-06-13 09:19:36.747 UTC | null | 184,201 | null | 39,321 | null | 1 | 231 | typescript | 190,098 | <p>Typescript treats files without import/exports as legacy script files. As such files are not modules and any definitions they have get merged in the global namespace. <code>isolatedModules</code> forbids such files.</p>
<p>Adding any import or export to a file makes it a module and the error disappears.</p>
<p><strong>Also <code>export {}</code> is a handy way</strong> to make a file a module without importing anything.</p> |
33,773,296 | Is there or isn't there an integer type in JavaScript? | <p>I am just starting to learn Javascript and I immediately got confused by seemingly contradictory statements in Mozilla's <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript" rel="noreferrer">A re-introduction to JavaScript (JS tutorial)</a>.</p>
<p>One one hand:</p>
<blockquote>
<p>"<strong>There's no such thing as an integer</strong> in JavaScript, so you have to
be a little careful with your arithmetic if you're used to math in C
or Java."</p>
</blockquote>
<p>On the other hand (immediately after that paragraph):</p>
<blockquote>
<p>"In practice, integer values are treated as 32-bit ints (and are
stored that way in some browser implementations), which can be
important for bit-wise operations."</p>
</blockquote>
<p>and</p>
<blockquote>
<p>"You can convert a string to an integer using the built-in parseInt()
function."</p>
</blockquote>
<p>So, is there such thing as integer in JavaScript or isn't there?</p> | 33,774,009 | 4 | 10 | null | 2015-11-18 06:35:24.953 UTC | 9 | 2022-09-23 05:50:50.853 UTC | 2015-11-24 15:03:48.42 UTC | null | 2,200,659 | null | 5,556,250 | null | 1 | 59 | javascript|integer | 38,933 | <p><strong>UPDATE</strong>: with a new ES2020 standard released this answer is not entirely correct anymore, see <a href="https://stackoverflow.com/a/51149434/251311">the other answer</a> (from <a href="https://stackoverflow.com/users/553609/mathias-lykkegaard-lorenzen">@Mathias Lykkegaard Lorenzen</a>) about <code>BigInt</code> details.</p>
<p>There is only the <a href="http://www.ecma-international.org/ecma-262/6.0/index.html#sec-ecmascript-language-types-number-type" rel="noreferrer">Number</a> data type in JS that represents numbers.</p>
<p>Internally it is implemented as <a href="http://www.ecma-international.org/ecma-262/6.0/index.html#sec-terms-and-definitions-number-value" rel="noreferrer">IEEE 754</a> double precision floating point number.</p>
<p>What it means is that - technically there is no dedicated data type that represents integer numbers.</p>
<p>Practically it means that we can safely use only numbers that are safely representable by the aforementioned standard. And it includes integer values in the range: <code>[-9007199254740991; 9007199254740991]</code>. Both values are defined as constants: <a href="http://www.ecma-international.org/ecma-262/6.0/index.html#sec-number.min_safe_integer" rel="noreferrer"><code>Number.MIN_SAFE_INTEGER</code></a> and <a href="http://www.ecma-international.org/ecma-262/6.0/index.html#sec-number.max_safe_integer" rel="noreferrer"><code>Number.MAX_SAFE_INTEGER</code></a> correspondingly.</p> |
22,798,934 | Pandas long to wide reshape, by two variables | <p>I have data in long format and am trying to reshape to wide, but there doesn't seem to be a straightforward way to do this using melt/stack/unstack:</p>
<pre><code>Salesman Height product price
Knut 6 bat 5
Knut 6 ball 1
Knut 6 wand 3
Steve 5 pen 2
</code></pre>
<p>Becomes:</p>
<pre><code>Salesman Height product_1 price_1 product_2 price_2 product_3 price_3
Knut 6 bat 5 ball 1 wand 3
Steve 5 pen 2 NA NA NA NA
</code></pre>
<p>I think Stata can do something like this with the reshape command.</p> | 22,799,916 | 6 | 3 | null | 2014-04-01 23:37:44.7 UTC | 36 | 2022-02-01 19:14:19.62 UTC | 2021-10-12 16:25:26.213 UTC | null | 10,714,156 | null | 2,985,049 | null | 1 | 94 | python|pandas|stata|reshape | 152,291 | <p>A simple pivot might be sufficient for your needs but this is what I did to reproduce your desired output:</p>
<pre><code>df['idx'] = df.groupby('Salesman').cumcount()
</code></pre>
<p>Just adding a within group counter/index will get you most of the way there but the column labels will not be as you desired:</p>
<pre><code>print df.pivot(index='Salesman',columns='idx')[['product','price']]
product price
idx 0 1 2 0 1 2
Salesman
Knut bat ball wand 5 1 3
Steve pen NaN NaN 2 NaN NaN
</code></pre>
<p>To get closer to your desired output I added the following:</p>
<pre><code>df['prod_idx'] = 'product_' + df.idx.astype(str)
df['prc_idx'] = 'price_' + df.idx.astype(str)
product = df.pivot(index='Salesman',columns='prod_idx',values='product')
prc = df.pivot(index='Salesman',columns='prc_idx',values='price')
reshape = pd.concat([product,prc],axis=1)
reshape['Height'] = df.set_index('Salesman')['Height'].drop_duplicates()
print reshape
product_0 product_1 product_2 price_0 price_1 price_2 Height
Salesman
Knut bat ball wand 5 1 3 6
Steve pen NaN NaN 2 NaN NaN 5
</code></pre>
<p>Edit: if you want to generalize the procedure to more variables I think you could do something like the following (although it might not be efficient enough):</p>
<pre><code>df['idx'] = df.groupby('Salesman').cumcount()
tmp = []
for var in ['product','price']:
df['tmp_idx'] = var + '_' + df.idx.astype(str)
tmp.append(df.pivot(index='Salesman',columns='tmp_idx',values=var))
reshape = pd.concat(tmp,axis=1)
</code></pre>
<blockquote>
<p>@Luke said:</p>
<p>I think Stata can do something like this with the reshape command.</p>
</blockquote>
<p>You can but I think you also need a within group counter to get the reshape in stata to get your desired output:</p>
<pre><code> +-------------------------------------------+
| salesman idx height product price |
|-------------------------------------------|
1. | Knut 0 6 bat 5 |
2. | Knut 1 6 ball 1 |
3. | Knut 2 6 wand 3 |
4. | Steve 0 5 pen 2 |
+-------------------------------------------+
</code></pre>
<p>If you add <code>idx</code> then you could do reshape in <code>stata</code>:</p>
<pre><code>reshape wide product price, i(salesman) j(idx)
</code></pre> |
13,560,001 | Length of an object array | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/5950155/java-arrays-length">Java Arrays - length</a> </p>
</blockquote>
<p>How do you determine the length of an array that is not an String array or an integer array? It won't let me use <code>.length()</code>, but only <code>.length</code>? </p>
<p>Why and is there another way of determining this?</p> | 13,560,125 | 4 | 2 | null | 2012-11-26 06:54:10.777 UTC | 1 | 2022-09-13 03:30:55.977 UTC | 2017-05-23 12:01:42.21 UTC | null | -1 | null | 1,852,563 | null | 1 | 7 | java|arrays | 48,317 | <p>Arrays in Java are not resizable. Once an array is instantiated, its length cannot change. That's why the <code>length</code> attribute (<code>myArray.length</code>) can always be trusted to contain the array's length.</p> |
13,577,473 | BETWEEN Versus >= and <= in DB2 SQL Query - Performance | <p>I have the following querys: </p>
<pre><code>SELECT ID, ADDRESS
FROM EMPLOYEE A
WHERE ID=12345
AND CURRENT DATE BETWEEN A.EFF_DT AND A.EXP_DT
SELECT ID, ADDRESS
FROM EMPLOYEE A
WHERE ID=12345
AND CURRENT DATE >= A.EFF_DT AND CURRENT DATE <= A.EXP_DT
</code></pre>
<p>Out of these two queries which query yields better performance. </p>
<p>Here I am using operators >= and <= instead of BETWEEN. </p>
<p>Please suggest. </p>
<p>Thanks in advance.</p> | 13,577,573 | 2 | 1 | null | 2012-11-27 04:37:41.423 UTC | 2 | 2012-11-27 04:55:08.937 UTC | 2012-11-27 04:42:44.7 UTC | null | 1,164,885 | null | 1,164,885 | null | 1 | 8 | db2|query-optimization | 52,179 | <p>Both those should give you exactly the same execution profile, based on my knowledge of DB2/z (the LUW product may be different but I doubt it).</p>
<p>If you're really concerned, you should run an <a href="http://publib.boulder.ibm.com/infocenter/db2luw/v9/index.jsp?topic=/com.ibm.db2.udb.admin.doc/doc/r0000952.htm" rel="noreferrer">EXPLAIN</a> on the two queries to see if there are any differences.</p> |
13,329,445 | How to read image from in memory buffer (StringIO) or from url with opencv python library | <p>Just share a way to create opencv image object from in memory buffer or from url to improve performance.</p>
<p>Sometimes we get image binary from url, to avoid additional file IO, we want to <strong>imread</strong> this image from in memory buffer or from url, but imread only supports read image from file system with path.</p> | 13,329,446 | 2 | 0 | null | 2012-11-11 07:42:46.31 UTC | 7 | 2019-03-26 15:40:20.83 UTC | null | null | null | null | 1,401,309 | null | 1 | 28 | image|opencv|numpy|urllib2|stringio | 33,131 | <p>To create an OpenCV image object with in memory buffer(StringIO), we can use OpenCV API imdecode, see code below:</p>
<pre><code>import cv2
import numpy as np
from urllib2 import urlopen
from cStringIO import StringIO
def create_opencv_image_from_stringio(img_stream, cv2_img_flag=0):
img_stream.seek(0)
img_array = np.asarray(bytearray(img_stream.read()), dtype=np.uint8)
return cv2.imdecode(img_array, cv2_img_flag)
def create_opencv_image_from_url(url, cv2_img_flag=0):
request = urlopen(url)
img_array = np.asarray(bytearray(request.read()), dtype=np.uint8)
return cv2.imdecode(img_array, cv2_img_flag)
</code></pre> |
13,642,381 | C/C++ Why to use unsigned char for binary data? | <p>Is it really necessary to use <code>unsigned char</code> to hold binary data as in some libraries which work on character encoding or binary buffers? To make sense of my question, have a look at the code below -</p>
<pre><code>char c[5], d[5];
c[0] = 0xF0;
c[1] = 0xA4;
c[2] = 0xAD;
c[3] = 0xA2;
c[4] = '\0';
printf("%s\n", c);
memcpy(d, c, 5);
printf("%s\n", d);
</code></pre>
<p>both the <code>printf's</code> output <code></code> correctly, where <code>f0 a4 ad a2</code> is the encoding for the Unicode code-point <code>U+24B62 ()</code> in hex.</p>
<p>Even <code>memcpy</code> also correctly copied the bits held by a char.</p>
<p>What reasoning could possibly advocate the use of <code>unsigned char</code> instead of a <code>plain char</code>?</p>
<p>In other related questions <code>unsigned char</code> is highlighted because it is the only (byte/smallest) data type which is guaranteed to have no padding by the C-specification. But as the above example showed, the output doesn't seem to be affected by any padding as such.</p>
<p>I have used VC++ Express 2010 and MinGW to compile the above. Although VC gave the warning </p>
<p><code>warning C4309: '=' : truncation of constant value</code></p>
<p>the output doesn't seems to reflect that.</p>
<p>P.S. This could be marked a possible duplicate of <a href="https://stackoverflow.com/questions/653336/should-a-buffer-of-bytes-be-signed-or-unsigned-char-buffer?rq=1">Should a buffer of bytes be signed or unsigned char buffer?</a> but my intent is different. I am asking why something which seems to be working as fine with <code>char</code> should be typed <code>unsigned char</code>?</p>
<p><strong>Update:</strong> To quote from N3337, </p>
<p><code>Section 3.9 Types</code></p>
<blockquote>
<p>2 For any object (other than a base-class subobject) of trivially
copyable type T, whether or not the object holds a valid value of type
T, the underlying bytes (1.7) making up the object can be copied into
an array of char or unsigned char. If the content of the array of char
or unsigned char is copied back into the object, the object shall
subsequently hold its original value.</p>
</blockquote>
<p>In view of the above fact and that my original example was on Intel machine where <code>char</code> defaults to <code>signed char</code>, am still not convinced if <code>unsigned char</code> should be preferred over <code>char</code>.</p>
<p>Anything else?</p> | 13,642,984 | 8 | 10 | null | 2012-11-30 09:33:40.083 UTC | 32 | 2020-02-04 23:16:49.257 UTC | 2017-05-23 12:32:01.897 UTC | null | -1 | null | 1,363,471 | null | 1 | 56 | c++|c|character-encoding|bytebuffer|rawbytestring | 30,585 | <p>In C the <code>unsigned char</code> data type is the only data type that has all the following three properties simultaneously </p>
<ul>
<li>it has no padding bits, that it where all storage bits contribute to the value of the data</li>
<li>no bitwise operation starting from a value of that type, when converted back into that type, can produce overflow, trap representations or undefined behavior</li>
<li>it may alias other data types without violating the "aliasing rules", that is that access to the same data through a pointer that is typed differently will be guaranteed to see all modifications</li>
</ul>
<p>if these are the properties of a "binary" data type you are looking for, you definitively should use <code>unsigned char</code>.</p>
<p>For the second property we need a type that is <code>unsigned</code>. For these all conversion are defined with modulo arihmetic, here modulo <code>UCHAR_MAX+1</code>, <code>256</code> in most 99% of the architectures. All conversion of wider values to <code>unsigned char</code> thereby just corresponds to truncation to the least significant byte.</p>
<p>The two other character types generally don't work the same. <code>signed char</code> is signed, anyhow, so conversion of values that don't fit it is not well defined. <code>char</code> is not fixed to be signed or unsigned, but on a particular platform to which your code is ported it might be signed even it is unsigned on yours.</p> |
13,239,325 | How to find the reason for a failed Build without any error or warning | <p>I have a WebApplication which contains reference to WCF services.</p>
<p>While building using Visual Studio 2010, Build fails without any error or warning. However building the <code>.csproj</code> using <code>MsBuild</code> is successful.</p>
<p>Can't figure out what should I try in Visual Studio, to resolve / diagnose the issue. Can you please help out?</p>
<p>I find out that the build has been failing,</p>
<ol>
<li><p>From text displayed in status Bar.<br />
<img src="https://i.stack.imgur.com/ZLAz9.jpg" alt="enter image description here" /></p>
</li>
<li><p>From output window:</p>
<pre><code> ========== Build: 0 succeeded or up-to-date, 1 failed, 0 skipped ==========
</code></pre>
<p>The output tab includes configuration details.</p>
<pre><code>------ Build started: Project: <projectName here> Configuration: Debug Any CPU
</code></pre>
</li>
</ol> | 27,425,455 | 10 | 6 | null | 2012-11-05 19:53:04.27 UTC | 27 | 2022-09-05 15:51:36.443 UTC | 2022-09-05 15:51:36.443 UTC | null | 2,756,409 | null | 1,431,250 | null | 1 | 215 | c#|asp.net|.net|visual-studio | 175,450 | <p>I just ran into a similar situation. In my case, a custom action (from the MSBuildVersioning package available on Nuget.org - <a href="http://www.nuget.org/packages/MSBuildVersioning/" rel="noreferrer">http://www.nuget.org/packages/MSBuildVersioning/</a>) which appeared in the csproj file's BeforeBuild target was failing without triggering any error message in the normal place.</p>
<p>I was able to determine this by setting the <strong>"MSBuild project build output verbosity"</strong> (in the latest Visual Studio's Tools tab [Path: <strong>Tools > Options > Build and Run</strong>]) to "<strong>Diagnostic</strong>" as shown below. This then showed that the custom action (in my case HgVersionFile) was what had failed.</p>
<p><img src="https://i.stack.imgur.com/kLoTy.png" alt="Screen capture from Visual Studio showing the modified setting." /></p> |
39,550,732 | Is there a way to have conditional markdown chunk execution in Rmarkdown? | <p>I am an instructor looking to make a homework assignment and homework solution guide from the same Rmarkdown file by changing a document parameter I created called <code>soln</code>. When <code>soln=FALSE</code> the assignment document is generated, and when <code>soln=TRUE</code> the homework solution guide is generated. I can control R code chunk execution using the document parameter, but I would also like conditional inclusion of markdown text.</p>
<p>My current workaround is ugly:</p>
<pre><code>---
title: "Homework"
output: word_document
params:
soln: TRUE
---
Fit the linear regression model $Y \sim X$ with the following data.
Interpret the coefficient estimates.
```{r promptchunk, include = TRUE, echo = TRUE}
# R code I want to show in the question prompt goes here
# This executes in both assignment and solution versions
set.seed(123)
X <- c(1, 1, 0, 0)
Y <- rnorm(4)
```
```{r, include = params$soln, echo = FALSE, results = "asis"}
cat("
**ANSWER**
")
```
```{r, echo = params$soln, include = params$soln, eval = params$soln}
# R code corresponding to the solution
fit1 <- lm(Y ~ X)
summary(fit1)
```
```{r, include = params$soln, echo = FALSE, eval = params$soln, results = "asis"}
cat("
The interpretation of the intercept is....
Our estimate $\\hat{\\beta}_0$ is ",coef(fit1)[1],".
The estimated X coefficient $\\hat{\\beta}_1$ is ",coef(fit1)[2],"
This can be interpreted as....
You can imagine that for more difficult questions, this section could be quite long.
")
```
</code></pre>
<p>What I would like to do is to replace the chunks containing <code>cat</code> functions with something more elegant and readable for the person writing the solutions guide. My current approach works enough for me, but it is not something that I could ask my co-instructors to use because it is so unpleasant to write the solutions inside of the <code>cat</code> function. (As a LaTeX user, it is also annoying to need double slashes for everything inside the math commands.)</p>
<p>Is there another way to do this?</p> | 39,552,048 | 2 | 4 | null | 2016-09-17 19:12:17.35 UTC | 14 | 2018-04-23 20:14:55.387 UTC | 2016-09-17 21:22:46.033 UTC | null | 4,418,571 | null | 4,418,571 | null | 1 | 29 | r|markdown|knitr|r-markdown|pandoc | 11,295 | <p>Instead of using <code>cat</code> to print the solution from within an R code chunk, you could write the solution as you usually would in <code>rmarkdown</code> (i.e., with the usual combination of text, <code>latex</code>, and R code chunks), and use the parameter <code>soln</code> to comment out that section when you don't want to include the solution in the final document. </p>
<p>In the sample <code>rmarkdown</code> document below, if the parameter <code>soln</code> is <code>FALSE</code>, then the line <code>r if(!params$soln) {"\\begin{comment}"}</code> inserts <code>\begin{comment}</code> to comment out the solution (with matching code at the end to insert <code>\end{comment}</code>). I've also indented everything with two tabs, so that the question numbers are formatted with a hanging-indent. (If you like this format, you don't have to type the double-tab for each new paragraph or chunk. If you do this for one line, then each subsequent time you press the <code>Enter</code> key, the new line will automatically be formatted with the double-tab. Or, just type in all your text and code for a given question, then when you're done, highlight all of it and type <code>tab</code> twice.)</p>
<pre><code>---
title: "Homework"
output: word_document
header-includes:
- \usepackage{comment}
params:
soln: TRUE
---
1. Fit the linear regression model $Y \sim X$ with the following data. Interpret the coefficient estimates.
```{r promptchunk, echo = TRUE}
set.seed(123)
X <- c(1, 1, 0, 0)
Y <- rnorm(4)
```
`r if(!params$soln) {"\\begin{comment}"}`
**Solution:**
Run the following R code to fit the linear regression model:
```{r, include = params$soln, echo = TRUE, results = "asis"}
fit1 = lm(Y ~ X)
```
To see a summary of the regression results, run the following code and review the output:
```{r, include = params$soln, echo=TRUE}
summary(fit1)
```
The interpretation of the intercept is....
Our estimate $\hat{\beta}_0$ is `r round(coef(fit1)[1], 2)`.
The estimated X coefficient $\hat{\beta}_1$ is `r round(coef(fit1)[2], 2)`.
This can be interpreted as....
`r if(!params$soln) {"\\end{comment}"}`
</code></pre>
<p>Also, instead of knitting the file above interactively, you can render both versions by running the <code>render</code> function in a separate R script. For example, assuming the file above is called <code>hw.Rmd</code>, open a separate R script file and run the following:</p>
<pre><code>for (i in c(TRUE, FALSE)) {
rmarkdown::render("hw.Rmd",
params = list(soln = i),
output_file=ifelse(i, "Solutions.doc", "Homework.doc"))
}
</code></pre>
<p>Below is what <code>Solutions.doc</code> looks like. <code>Homework.doc</code> is similar, except everything from the bold word <strong><code>Solution:</code></strong> onward is excluded:</p>
<p><a href="https://i.stack.imgur.com/W5PAT.png" rel="noreferrer"><img src="https://i.stack.imgur.com/W5PAT.png" alt="enter image description here"></a></p> |
20,762,662 | What's the correct way to sort Python `import x` and `from x import y` statements? | <p>The <a href="http://www.python.org/dev/peps/pep-0008/#imports">python style guide</a> suggests to group imports like this:</p>
<blockquote>
<p>Imports should be grouped in the following order:</p>
<ol>
<li>standard library imports</li>
<li>related third party imports</li>
<li>local application/library specific imports</li>
</ol>
</blockquote>
<p>However, it does not mention anything how the two different ways of imports should be laid out:</p>
<pre><code>from foo import bar
import foo
</code></pre>
<p>There are multiple ways to sort them (let's assume all those import belong to the same group):</p>
<ul>
<li><p>first <code>from..import</code>, then <code>import</code></p>
<pre><code>from g import gg
from x import xx
import abc
import def
import x
</code></pre></li>
<li><p>first <code>import</code>, then <code>from..import</code></p>
<pre><code>import abc
import def
import x
from g import gg
from x import xx
</code></pre></li>
<li><p>alphabetic order by module name, ignoring the kind of import</p>
<pre><code>import abc
import def
from g import gg
import x
from xx import xx
</code></pre></li>
</ul>
<p>PEP8 does not mention the preferred order for this and the "cleanup imports" features some IDEs have probably just do whatever the developer of that feature preferred.</p>
<p><strong>I'm looking for another PEP clarifying this or a relevant comment/email from the <a href="http://en.wikipedia.org/wiki/Guido_van_Rossum">BDFL</a></strong> (or another Python core developer). <em>Please don't post subjective answers stating your own preference.</em></p> | 20,763,446 | 6 | 2 | null | 2013-12-24 14:37:57.05 UTC | 55 | 2021-05-29 02:21:40.81 UTC | 2013-12-25 00:59:03.353 UTC | null | 216,074 | null | 298,479 | null | 1 | 239 | python|coding-style|python-import|pep8 | 105,777 | <p>Imports are generally sorted alphabetically and described in various places besides PEP 8.</p>
<p><strong>Alphabetically sorted modules are quicker to read and searchable</strong>. After all, Python is all about readability.
Also, it is easier to verify that something is imported, and avoids duplicate imports.</p>
<p>There is nothing available in PEP 8 regarding sorting. So it's all about choosing what you use.</p>
<p>According to few references from reputable sites and repositories, also popularity, Alphabetical ordering is the way.</p>
<p>for e.g. like this:</p>
<pre><code>import httplib
import logging
import random
import StringIO
import time
import unittest
from nova.api import openstack
from nova.auth import users
from nova.endpoint import cloud
</code></pre>
<p>OR</p>
<pre><code>import a_standard
import b_standard
import a_third_party
import b_third_party
from a_soc import f
from a_soc import g
from b_soc import d
</code></pre>
<p>Reddit official repository also states that In general PEP-8 import ordering should be used. However, there are a few additions which are that for each imported group the order of imports should be:</p>
<pre><code>import <package>.<module> style lines in alphabetical order
from <package>.<module> import <symbol> style in alphabetical order
</code></pre>
<p>References:</p>
<ul>
<li><a href="https://code.google.com/p/soc/wiki/PythonStyleGuide" rel="noreferrer">https://code.google.com/p/soc/wiki/PythonStyleGuide</a></li>
<li><a href="https://github.com/reddit/reddit/wiki/PythonImportGuidelines" rel="noreferrer">https://github.com/reddit/reddit/wiki/PythonImportGuidelines</a></li>
<li><a href="http://docs.openstack.org/developer/hacking/" rel="noreferrer">http://docs.openstack.org/developer/hacking/</a></li>
<li><a href="http://developer.plone.org/reference_manuals/external/plone.api/contribute/conventions.html#grouping-and-sorting" rel="noreferrer">http://developer.plone.org/reference_manuals/external/plone.api/contribute/conventions.html#grouping-and-sorting</a></li>
</ul>
<p>PS: the <a href="https://pypi.python.org/pypi/isort/" rel="noreferrer">isort utility</a> automatically sorts your imports.</p> |
20,586,525 | getMeasuredWidth returns totally wrong value | <p>I have to measure a <code>View</code> for spacing others. I use this code for that:</p>
<pre><code>ViewGroup view = ...;
view.setPadding(10, 0, 10, 0);
int wrapContent = RelativeLayout.LayoutParams.WRAP_CONTENT;
int specWidth = MeasureSpec.makeMeasureSpec(wrapContent, MeasureSpec.AT_MOST);
view.measure(specWidth, specWidth);
int questionWidth = view.getMeasuredWidth();
</code></pre>
<p>This works as expected on an Android 4.3 emulator.</p>
<p>However the returned measured width on a Samsung Galaxy XCover 2 (S7710) Android 4.1.2 phone, is <strong>16777214</strong>...
I tried everything, masking with <code>View.MEASURED_SIZE_MASK</code>, but nothing helped.</p>
<p>Could you provide some help with this? Thanks in advance!</p> | 21,761,151 | 1 | 3 | null | 2013-12-14 18:05:37.21 UTC | 14 | 2015-10-20 19:47:18.583 UTC | 2014-04-03 20:37:32.913 UTC | null | 375,929 | null | 747,412 | null | 1 | 28 | android|android-layout|view|measure | 11,084 | <p>Passing <code>WRAP_CONTENT</code> instead of an actual value to <code>makeMeasureSpec()</code> won't do any good, I don't think those were meant to be used together.</p>
<p>Use actual constraint value as first parameter (e.g. size of the parent view or dimensions of the screen) with the <code>MeasureSpec.AT_MOST</code> mode, which is basically <code>Math.min()</code> -- with arguments being the value you put in the spec and the view's desired dimension.</p>
<p><code>MeasureSpec.EXACTLY</code> will make it use the spec value, <code>MeasureSpec.UNSPECIFIED</code> will make it use the view's desired value. So if you don't have any constraints (like if you put your view into a <code>ScrollView</code>) your option is <code>MeasureSpec.UNSPECIFIED</code> -- and any value as first argument.</p>
<p>So, <i>{gurus, correct me if I'm wrong}</i> you get <code>WRAP_CONTENT</code> behavior with any mode other than <code>MeasureSpec.EXACTLY</code></p>
<p>That being said, try:</p>
<pre><code>ViewGroup view = ...;
view.setPadding(10, 0, 10, 0);
// Either this
int specWidth = MeasureSpec.makeMeasureSpec(parentWidth, MeasureSpec.AT_MOST);
// Or this
int specWidth = MeasureSpec.makeMeasureSpec(0 /* any */, MeasureSpec.UNSPECIFIED);
view.measure(specWidth, specWidth);
int questionWidth = view.getMeasuredWidth();
</code></pre>
<p><strong>PS</strong> Funny thing about <strong>16777214</strong>, take a look at the number in binary: <a href="https://www.google.ru/search?q=16777214+in+binary" rel="noreferrer">https://www.google.ru/search?q=16777214+in+binary</a> It's <strong>-2</strong> (which is the constant value of <code>LayoutParams.WRAP_CONTENT</code>) but with 8 most significant bits truncated with a logical operation (hence no minus), there's something in call stack of <code>measure()</code> that does this :) I wonder if this is a bug. Maybe it should be checking the argument for being negative and throwing an exception or something.</p> |
24,314,687 | Slide down animation from display:none to display:block? | <p>Is there a way to animate display:none to display:block using CSS so that the hidden div slides down instead of abruptly appearing, or should I go about this a different way?</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>$(document).ready(function() {
$('#box').click(function() {
$(this).find(".hidden").toggleClass('open');
});
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>#box {
height:auto;
background:#000;
color:#fff;
cursor:pointer;
}
.hidden {
height:200px;
display:none;
}
.hidden.open {
display:block;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="box">
Initial Content
<div class="hidden">
This is hidden content
</div>
</div></code></pre>
</div>
</div>
</p>
<h1>And a <a href="http://jsfiddle.net/6C42Q/" rel="nofollow noreferrer">JSFiddle</a></h1> | 24,314,932 | 7 | 2 | null | 2014-06-19 19:21:58.003 UTC | 9 | 2022-01-28 14:55:50.797 UTC | 2021-09-27 19:55:48.787 UTC | null | 16,444,630 | null | 2,827,407 | null | 1 | 31 | javascript|jquery|html|css|css-transitions | 119,278 | <p>Yes, there is a way:
<a href="http://jsfiddle.net/6C42Q/12/" rel="noreferrer">http://jsfiddle.net/6C42Q/12/</a></p>
<p>By using CSS3 transitions, and manipulate height, rather than display property:</p>
<pre><code>.hidden {
height: 0px;
-webkit-transition: height 0.5s linear;
-moz-transition: height 0.5s linear;
-ms-transition: height 0.5s linear;
-o-transition: height 0.5s linear;
transition: height 0.5s linear;
}
.hidden.open {
height: 200px;
-webkit-transition: height 0.5s linear;
-moz-transition: height 0.5s linear;
-ms-transition: height 0.5s linear;
-o-transition: height 0.5s linear;
transition: height 0.5s linear;
}
</code></pre>
<p>More here: <a href="https://stackoverflow.com/questions/13412054/slide-down-div-on-click-pure-css">Slide down div on click Pure CSS?</a></p> |
3,938,278 | Close Window for button click | <p>I have been trying to close the window on button click but am unable to do so.</p>
<p>I have added javascript <code>window.close()</code></p>
<p>added on the code behind page on button click event all in vain. Language <code>c#</code> or <code>vb.net</code> </p> | 3,938,297 | 2 | 1 | null | 2010-10-14 23:05:25.13 UTC | 1 | 2016-02-09 13:48:46.69 UTC | 2016-02-09 13:48:46.69 UTC | null | 4,946,896 | null | 428,747 | null | 1 | 5 | javascript|asp.net | 67,128 | <p>That needs to be on the client side, try something like this:</p>
<pre><code><input type="button" id="close" onclick="window.close()" />
</code></pre>
<p>If you want an asp.net button you can do:</p>
<pre><code><asp:Button ID="close" runat="server" OnClientClick="javascript:window.close()" />
</code></pre>
<p>Although that would be a bit pointless. =)</p> |
9,146,651 | Trigger an event on `click` and `enter` | <p>I have a searchbox on my site that. Currently, users must click the submit button next to the box to search via jquery's post. I would like to let users also press enter to search. How can i do this?</p>
<p>JQUERY:</p>
<pre><code>$('document').ready(function(){
$('#searchButton').click(function(){
var search = $('#usersSearch').val();
$.post('../searchusers.php',{search: search},function(response){
$('#userSearchResultsTable').html(response);
});
});
});
</code></pre>
<p>HTML:</p>
<pre><code><input type='text' id='usersSearch' /><input type='button' id='searchButton' value='search' />
</code></pre> | 9,146,661 | 7 | 2 | null | 2012-02-05 03:19:53.613 UTC | 24 | 2018-03-12 06:24:24.53 UTC | 2012-02-05 03:26:17.61 UTC | null | 1,113,246 | null | 802,370 | null | 1 | 77 | jquery|jquery-selectors | 134,254 | <p>Use <code>keypress</code> event on <code>usersSearch</code> textbox and look for <kbd>Enter</kbd> button. If enter button is pressed then trigger the search button click event which will do the rest of work. Try this.</p>
<pre><code>$('document').ready(function(){
$('#searchButton').click(function(){
var search = $('#usersSearch').val();
$.post('../searchusers.php',{search: search},function(response){
$('#userSearchResultsTable').html(response);
});
})
$('#usersSearch').keypress(function(e){
if(e.which == 13){//Enter key pressed
$('#searchButton').click();//Trigger search button click event
}
});
});
</code></pre>
<p><strong><a href="http://jsfiddle.net/ShankarSangoli/ambCG/">Demo</a></strong></p> |
29,502,052 | Template specialization and enable_if problems | <p>I am running into a problem regarding the appropriate usage of enable_if and template specialization.</p>
<p>After modifying the example (for confidentiality reasons), here's a comparable example:</p>
<blockquote>
<p>I have function called "less" that checks if 1st arg is less than 2nd
arg. Let's say I want to have 2 different kinds of implementations
depending on the type of input - 1 implementation for integer and
another for double.</p>
</blockquote>
<p>The code that I have so far looks like this -</p>
<pre><code>#include <type_traits>
#include <iostream>
template <class T,
class = typename std::enable_if<std::is_floating_point<T>::value>::type>
bool less(T a, T b) {
// ....
}
template <class T,
class = typename std::enable_if<std::is_integral<T>::value>::type>
bool less(T a, T b) {
// ....
}
int main() {
float a;
float b;
less(a,b);
return 0;
}
</code></pre>
<p>The above code does not compile because - It says that I am re-defining the less method.</p>
<p>Errors are:</p>
<pre><code>Z.cpp:15:19: error: template parameter redefines default argument
class = typename std::enable_if<std::is_integral<T>::value>::type>
^
Z.cpp:9:19: note: previous default template argument defined here
class = typename std::enable_if<std::is_floating_point<T>::value>::type>
^
Z.cpp:16:11: error: redefinition of 'less'
bool less(T a, T b) {
^
Z.cpp:10:11: note: previous definition is here
bool less(T a, T b) {
^
Z.cpp:23:5: error: no matching function for call to 'less'
less(a,b);
^~~~
Z.cpp:15:43: note: candidate template ignored: disabled by 'enable_if'
[with T = float]
class = typename std::enable_if<std::is_integral<T>::value>::type>
^
3 errors generated.
</code></pre>
<p>Can someone point out what's the mistake here?</p> | 29,502,338 | 1 | 3 | null | 2015-04-07 21:54:35.873 UTC | 8 | 2015-11-04 16:39:24.487 UTC | 2015-11-04 16:39:24.487 UTC | null | 241,631 | null | 211,528 | null | 1 | 23 | c++|templates|c++11|sfinae|enable-if | 12,914 | <p>Default template arguments are not part of the signature of a function template. So in your example you have two identical overloads of <code>less</code>, which is illegal. clang complains about the redefinition of the default argument (which is also illegal according to §14.1/12 [temp.param]), while gcc produces the following error message:</p>
<blockquote>
<p>error: redefinition of '<code>template<class T, class> bool less(T, T)</code>'</p>
</blockquote>
<p>To fix the error move the <code>enable_if</code> expression from default argument to a dummy template parameter</p>
<pre><code>template <class T,
typename std::enable_if<std::is_floating_point<T>::value, int>::type* = nullptr>
bool less(T a, T b) {
// ....
}
template <class T,
typename std::enable_if<std::is_integral<T>::value, int>::type* = nullptr>
bool less(T a, T b) {
// ....
}
</code></pre>
<hr>
<p>Another option is to use <code>enable_if</code> in the return type, though I feel this is harder to read.</p>
<pre><code>template <class T>
typename std::enable_if<std::is_floating_point<T>::value, bool>::type
less(T a, T b) {
// ....
}
template <class T>
typename std::enable_if<std::is_integral<T>::value, bool>::type
less(T a, T b) {
// ....
}
</code></pre> |
16,419,144 | get picture object from facebook post with graph api | <p>I'm able to get a picture-url from a specific facebook-post through the facebook graph-api (ie <a href="https://developers.facebook.com/tools/explorer?method=GET&path=196118303833398_362048290573731" rel="noreferrer">https://developers.facebook.com/tools/explorer?method=GET&path=196118303833398_362048290573731</a>), but when I need to get a picture-object (for getting bigger sized en specific crops as described in the documentation) I try</p>
<p><a href="https://developers.facebook.com/tools/explorer?method=GET&path=196118303833398_362048290573731/picture" rel="noreferrer">https://developers.facebook.com/tools/explorer?method=GET&path=196118303833398_362048290573731/picture</a> </p>
<p>I get the response message "(#100) No node specified"... what do I forget?</p> | 16,419,450 | 5 | 1 | null | 2013-05-07 12:32:34.663 UTC | 5 | 2017-01-22 07:44:26.023 UTC | 2013-05-07 12:42:28.527 UTC | null | 2,358,298 | null | 2,358,298 | null | 1 | 15 | facebook-graph-api | 54,399 | <p>Only users and pages have a <code>picture</code> <em>connection</em> – posts don’t. (A <code>field</code> is something different.)</p>
<p>But I guess the <code>full_picture</code> field is what you want: <a href="https://developers.facebook.com/tools/explorer?method=GET&path=196118303833398_362048290573731%3Ffields%3Dfull_picture%2Cpicture">https://developers.facebook.com/tools/explorer?method=GET&path=196118303833398_362048290573731%3Ffields%3Dfull_picture%2Cpicture</a></p> |
16,208,121 | java create date object using a value string | <p>I am using this to get the current time :</p>
<pre><code>java.util.Calendar cal = java.util.Calendar.getInstance();
System.out.println(new java.text.SimpleDateFormat("EEEE, dd/MM/yyyy/hh:mm:ss")
.format(cal.getTime()));
</code></pre>
<p>I want to put the value (which I print it) into a date object, I tried this:</p>
<pre><code>Date currentDate = new Date(value);
</code></pre>
<p>but eclipse tells me that this function is not good.</p>
<p><strong>Edit</strong>
the <code>value</code> is the value that I printed to you using system.out.println</p> | 16,208,179 | 9 | 6 | null | 2013-04-25 06:45:41.787 UTC | 7 | 2021-02-09 11:14:42.683 UTC | 2016-05-10 21:14:43.23 UTC | null | 1,718,174 | null | 2,038,257 | null | 1 | 27 | java|date | 167,033 | <p>Whenever you want to convert a String to Date object then use <code>SimpleDateFormat#parse</code><br>
Try to use <br></p>
<pre><code>String dateInString = new java.text.SimpleDateFormat("EEEE, dd/MM/yyyy/hh:mm:ss")
.format(cal.getTime())
SimpleDateFormat formatter = new SimpleDateFormat("EEEE, dd/MM/yyyy/hh:mm:ss");
Date parsedDate = formatter.parse(dateInString);
</code></pre>
<p>.Additional thing is if you want to convert a <code>Date</code> to <code>String</code> then you should use <code>SimpleDateFormat#format</code> function.<br>Now the Point for you is
<code>new Date(String)</code> is deprecated and not recommended now.Now whenever anyone wants to parse , then he/she should use <code>SimpleDateFormat#parse</code>.</p>
<p>refer the <a href="https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html" rel="noreferrer">official doc</a> for more Date and Time Patterns used in SimpleDateFormat options.</p> |
16,174,469 | Unprotect VBProject from VB code | <p>How can i unprotect my VB project from a vb macro ?
i have found this code:</p>
<pre><code> Sub UnprotectVBProject(ByRef WB As Workbook, ByVal Password As String)
Dim VBProj As Object
Set VBProj = WB.VBProject
Application.ScreenUpdating = False
'Ne peut procéder si le projet est non-protégé.
If VBProj.Protection <> 1 Then Exit Sub
Set Application.VBE.ActiveVBProject = VBProj
'Utilisation de "SendKeys" Pour envoyer le mot de passe.
SendKeys Password & "~"
SendKeys "~"
'MsgBox "Après Mot de passe"
Application.VBE.CommandBars(1).FindControl(ID:=2578, recursive:=True).Execute
Application.Wait (Now + TimeValue("0:00:1"))
End Sub
</code></pre>
<p>But this solution doesn't work for Excel 2007. It display the authentification's window and print password in my IDE.</p>
<p>Then, my goal is to unprotect my VBproject without displaying this window.</p>
<p>Thanks for any help. </p> | 16,176,557 | 3 | 3 | null | 2013-04-23 16:24:22.96 UTC | 24 | 2022-01-07 07:01:08.5 UTC | 2013-04-24 09:36:44.367 UTC | null | 1,140,579 | null | 1,591,681 | null | 1 | 29 | vba|excel|excel-2007 | 72,710 | <p><strong>EDIT</strong>:</p>
<p>Converted this to a <a href="http://www.siddharthrout.com/index.php/2019/01/20/unprotect-vbproject-from-vb-code/" rel="nofollow noreferrer">BLOG post</a> for VBA and VB.Net.</p>
<p>I have never been in favor of <code>Sendkeys</code>. They are reliable in some case but not always. I have a soft corner for API's though.</p>
<p>What you want can be achieved, however you have to ensure that workbook for which you want to un-protect the VBA has to be opened in a separate Excel Instance.</p>
<p>Here is an example</p>
<p>Let's say we have a workbook who's VBA project looks like this currently.</p>
<p><img src="https://i.stack.imgur.com/AzlJ6.png" alt="enter image description here" /></p>
<p><strong>LOGIC</strong>:</p>
<ol>
<li><p>Find the Handle of the "VBAProject Password" window using <code>FindWindow</code></p>
</li>
<li><p>Once that is found, find the handle of the Edit Box in that window using <code>FindWindowEx</code></p>
</li>
<li><p>Once the handle of the Edit Box is found, simply use <code>SendMessage</code> to write to it.</p>
</li>
<li><p>Find the handle of the <code>Buttons</code> in that window using <code>FindWindowEx</code></p>
</li>
<li><p>Once the handle of the <code>OK</code> button is found, simply use <code>SendMessage</code> to click it.</p>
</li>
</ol>
<p><strong>RECOMMENDATION</strong>:</p>
<ol>
<li><p>For API's <a href="http://allapi.mentalis.org/apilist/apilist.php" rel="nofollow noreferrer">THIS</a> is the best link I can recommend.</p>
</li>
<li><p>If you wish to become good at API's like <code>FindWindow</code>, <code>FindWindowEx</code> and <code>SendMessage</code> then get a tool that gives you a graphical view of the system’s processes, threads, windows, and window messages. For Ex: uuSpy or Spy++.</p>
</li>
</ol>
<p>Here is what Spy++ will show you for "VBAProject Password" window</p>
<p><img src="https://i.stack.imgur.com/LEcu9.png" alt="enter image description here" /></p>
<p><strong>TESTING</strong>:</p>
<p>Open a new Excel instance and paste the below code in a module.</p>
<p><strong>CODE</strong>:</p>
<p>I have commented the code so you shouldn't have any problem understanding it.</p>
<pre><code>Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" _
(ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Private Declare Function FindWindowEx Lib "user32" Alias "FindWindowExA" _
(ByVal hWnd1 As Long, ByVal hWnd2 As Long, ByVal lpsz1 As String, _
ByVal lpsz2 As String) As Long
Private Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" _
(ByVal hwnd As Long, ByVal lpString As String, ByVal cch As Long) As Long
Private Declare Function GetWindowTextLength Lib "user32" Alias _
"GetWindowTextLengthA" (ByVal hwnd As Long) As Long
Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" _
(ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long
Dim Ret As Long, ChildRet As Long, OpenRet As Long
Dim strBuff As String, ButCap As String
Dim MyPassword As String
Const WM_SETTEXT = &HC
Const BM_CLICK = &HF5
Sub UnlockVBA()
Dim xlAp As Object, oWb As Object
Set xlAp = CreateObject("Excel.Application")
xlAp.Visible = True
'~~> Open the workbook in a separate instance
Set oWb = xlAp.Workbooks.Open("C:\Sample.xlsm")
'~~> Launch the VBA Project Password window
'~~> I am assuming that it is protected. If not then
'~~> put a check here.
xlAp.VBE.CommandBars(1).FindControl(ID:=2578, recursive:=True).Execute
'~~> Your passwword to open then VBA Project
MyPassword = "Blah Blah"
'~~> Get the handle of the "VBAProject Password" Window
Ret = FindWindow(vbNullString, "VBAProject Password")
If Ret <> 0 Then
'MsgBox "VBAProject Password Window Found"
'~~> Get the handle of the TextBox Window where we need to type the password
ChildRet = FindWindowEx(Ret, ByVal 0&, "Edit", vbNullString)
If ChildRet <> 0 Then
'MsgBox "TextBox's Window Found"
'~~> This is where we send the password to the Text Window
SendMess MyPassword, ChildRet
DoEvents
'~~> Get the handle of the Button's "Window"
ChildRet = FindWindowEx(Ret, ByVal 0&, "Button", vbNullString)
'~~> Check if we found it or not
If ChildRet <> 0 Then
'MsgBox "Button's Window Found"
'~~> Get the caption of the child window
strBuff = String(GetWindowTextLength(ChildRet) + 1, Chr$(0))
GetWindowText ChildRet, strBuff, Len(strBuff)
ButCap = strBuff
'~~> Loop through all child windows
Do While ChildRet <> 0
'~~> Check if the caption has the word "OK"
If InStr(1, ButCap, "OK") Then
'~~> If this is the button we are looking for then exit
OpenRet = ChildRet
Exit Do
End If
'~~> Get the handle of the next child window
ChildRet = FindWindowEx(Ret, ChildRet, "Button", vbNullString)
'~~> Get the caption of the child window
strBuff = String(GetWindowTextLength(ChildRet) + 1, Chr$(0))
GetWindowText ChildRet, strBuff, Len(strBuff)
ButCap = strBuff
Loop
'~~> Check if we found it or not
If OpenRet <> 0 Then
'~~> Click the OK Button
SendMessage ChildRet, BM_CLICK, 0, vbNullString
Else
MsgBox "The Handle of OK Button was not found"
End If
Else
MsgBox "Button's Window Not Found"
End If
Else
MsgBox "The Edit Box was not found"
End If
Else
MsgBox "VBAProject Password Window was not Found"
End If
End Sub
Sub SendMess(Message As String, hwnd As Long)
Call SendMessage(hwnd, WM_SETTEXT, False, ByVal Message)
End Sub
</code></pre> |
16,471,636 | Bean injection inside a JPA @Entity | <p>Is it possible to inject beans to a JPA <code>@Entity</code> using Spring's dependency injection?</p>
<p>I attempted to @Autowire ServletContext but, while the server did start successfully, I received a NullPointerException when trying to access the bean property.</p>
<pre><code>@Autowired
@Transient
ServletContext servletContext;
</code></pre> | 17,688,178 | 3 | 1 | null | 2013-05-09 21:43:37.57 UTC | 9 | 2017-11-17 08:49:49.533 UTC | 2017-11-17 08:49:49.533 UTC | null | 100,297 | null | 1,747,491 | null | 1 | 41 | spring|spring-mvc|jpa | 41,745 | <p>You can inject dependencies into objects not managed by the Spring container using <code>@Configurable</code> as explained here: <a href="http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/aop.html#aop-atconfigurable" rel="noreferrer">http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/aop.html#aop-atconfigurable</a>.</p>
<p>As you've realized by now, unless using the <code>@Configurable</code> and appropriate AspectJ weaving configuration, Spring does not inject dependencies into objects created using the <code>new</code> operator. In fact, it doesn't inject dependencies into objects unless you've retrieved them from the <code>ApplicationContext</code>, for the simple reason that it simply doesn't know about their existence. Even if you annotate your entity with <code>@Component</code>, instantiation of that entity will still be performed by a <code>new</code> operation, either by you or a framework such as Hibernate. Remember, annotations are just metadata: if no one interprets that metadata, it does not add any behaviour or have any impact on a running program.</p>
<p>All that being said, I strongly advise against injecting a <code>ServletContext</code> into an entity. Entities are part of your domain model and should be decoupled from any delivery mechanism, such as a Servlet-based web delivery layer. How will you use that entity when it's accessed by a command-line client or something else not involving a ServletContext? You should extract the necessary data from that ServletContext and pass it through traditional method arguments to your entity. You will achieve a much better design through this approach.</p> |
16,287,963 | Navigation bar disappeared from my storyboard items | <p>From one day to another the navigation bar disappeared from my storyboard items in XCode 4.6.2. I can't restore them (cleaning, rebuilding, closing, reopening etc)</p>
<p>When running my app on my device or in simulator, everything works ok, the navigation bar is there. But I need them on my storyboard during design time, I have buttons, labels there those must be changed now. (pls. don't advise to do it from code, I want to do it on the storyboard graphically, I think that's why it is there)</p>
<p>How can I get my navigation bars back? I hope the solution won't be to delete/do them again as I read in some places, because I have dozens of navigation controllers.</p>
<p>Thanks in advance!</p> | 16,288,036 | 7 | 0 | null | 2013-04-29 20:48:46.993 UTC | 11 | 2022-01-22 17:26:02.087 UTC | null | null | null | null | 582,211 | null | 1 | 44 | ios|xcode|uinavigationcontroller|storyboard | 32,895 | <p>Try this:</p>
<p>Select the view controller with the missing navigation bar and view the attributes inspector (This is the fourth tab over in the right side window). Under the simulated metrics section, change the "Top Bar" from the default "inferred" to "Navigation Bar".</p>
<p>Hopefully that solves your problem.</p> |
16,202,348 | numpy divide row by row sum | <p>How can I divide a numpy array row by the sum of all values in this row?</p>
<p>This is one example. But I'm pretty sure there is a fancy and much more efficient way of doing this:</p>
<pre><code>import numpy as np
e = np.array([[0., 1.],[2., 4.],[1., 5.]])
for row in xrange(e.shape[0]):
e[row] /= np.sum(e[row])
</code></pre>
<p>Result:</p>
<pre><code>array([[ 0. , 1. ],
[ 0.33333333, 0.66666667],
[ 0.16666667, 0.83333333]])
</code></pre> | 16,202,486 | 3 | 0 | null | 2013-04-24 21:16:31.543 UTC | 17 | 2020-07-15 17:38:34.577 UTC | null | null | null | null | 869,402 | null | 1 | 67 | python|multidimensional-array|numpy | 51,634 | <p>Method #1: use <code>None</code> (or <code>np.newaxis</code>) to add an extra dimension so that broadcasting will behave:</p>
<pre><code>>>> e
array([[ 0., 1.],
[ 2., 4.],
[ 1., 5.]])
>>> e/e.sum(axis=1)[:,None]
array([[ 0. , 1. ],
[ 0.33333333, 0.66666667],
[ 0.16666667, 0.83333333]])
</code></pre>
<p>Method #2: go transpose-happy:</p>
<pre><code>>>> (e.T/e.sum(axis=1)).T
array([[ 0. , 1. ],
[ 0.33333333, 0.66666667],
[ 0.16666667, 0.83333333]])
</code></pre>
<p>(You can drop the <code>axis=</code> part for conciseness, if you want.)</p>
<p>Method #3: (promoted from Jaime's comment)</p>
<p>Use the <code>keepdims</code> argument on <code>sum</code> to preserve the dimension:</p>
<pre><code>>>> e/e.sum(axis=1, keepdims=True)
array([[ 0. , 1. ],
[ 0.33333333, 0.66666667],
[ 0.16666667, 0.83333333]])
</code></pre> |
41,791,413 | Indexes with included columns, what's the difference? | <p>I've never really understood the difference between these two indexes, can someone please explain what the difference is (performance-wise, how the index structure will look like in db, storage-wise etc)?</p>
<p><strong>Included index</strong></p>
<pre><code>CREATE NONCLUSTERED INDEX IX_Address_PostalCode
ON Person.Address (PostalCode)
INCLUDE (AddressLine1, AddressLine2, City, StateProvinceID);
</code></pre>
<p><strong>'Normal' index</strong></p>
<pre><code>CREATE NONCLUSTERED INDEX IX_Address_PostalCode
ON Person.Address (PostalCode, AddressLine1, AddressLine2, City, StateProvinceID);
</code></pre> | 41,791,921 | 3 | 6 | null | 2017-01-22 13:22:29.61 UTC | 9 | 2020-11-13 15:20:39.893 UTC | 2020-11-13 15:20:39.893 UTC | null | 62,600 | null | 2,808,645 | null | 1 | 23 | sql|sql-server|tsql|database-indexes|sql-server-performance | 18,065 | <p>The internal storage of indexes uses a B-Tree structure and consists of "index pages" (the root and all intermediate pages) and "index data pages" (the leaf pages only).</p>
<blockquote>
<p>Note do not confuse "index data pages" with the "data pages" (leaf pages of clustered indexes) which store most of the columns of actual data.</p>
</blockquote>
<ul>
<li>Only the index columns are stored on the index pages.</li>
<li>By placing some columns in the <code>INCLUDE</code> section, less data per index key is stored on each page.</li>
<li>Meaning fewer pages are needed to hold the index keys. (<em>Making it easier to cache these frequently used pages in memory for longer.</em>)</li>
<li>And possibly fewer levels in the tree. (<em>In such a case performance benefits can be much bigger because every tree level traversal is another disk access.</em>)</li>
</ul>
<p>When an index is used, the index key is used to navigate through the index pages to the correct index data page.</p>
<ul>
<li>If the index has <code>INCLUDE</code> columns, that data is immediately available should the query need it.</li>
<li>If the query requires columns not available in either the index keys or the <code>INCLUDE</code> columns, then an additional "bookmark lookup" is required to the correct row in the clustered index (or heap if no clustered index defined).</li>
</ul>
<p>Some things to note that hopefully addresses some of your confusion:</p>
<ul>
<li>If the keys of your index and filters in your query are not <em>selective</em> enough, then the index will be ignored (regardless of what's in your <code>INCLUDE</code> columns).</li>
<li>Every index you create has overhead for INSERT and UPDATE statements; more so for "bigger" indexes. (Bigger applies to <code>INCLUDE</code> columns as well.)</li>
<li>So while you could in theory create a multitude of big indexes with include columns to match all the permutations of access paths: it would be very counter-productive.</li>
</ul>
<hr>
<p>It's worth noting that before <code>INCLUDE</code> columns were added as a feature:</p>
<ul>
<li>It was a common index tuning 'trick' to expand the keys of an index to include columns that weren't needed in the index/filter. (Known as a covering index.)</li>
<li>These columns were commonly required in output columns or as reference columns for joins to other tables.</li>
<li>This would avoid the infamous "bookmark lookups", but had the disadvantage of making the index 'wider' than strictly necessary.</li>
<li>In fact very often the earlier columns in the index would already identify a <strong><em>unique row</em></strong> meaning the extra included columns would be completely redundant if not for the "avoiding bookmark lookups" benefit.</li>
<li><code>INCLUDE</code> columns basically allow the same benefit more efficiently.</li>
</ul>
<blockquote>
<p><strong>NB</strong> Something very important to point out. You generally get zero benefit out of <code>INCLUDE</code> columns in your indexes if you're in the lazy habit of always writing your queries as <code>SELECT * ...</code>. By returning <strong><em>all columns</em></strong> you're basically ensuring a bookmark lookup is required in any case.</p>
</blockquote> |
17,496,175 | Reading XML from Stream | <p>I'm working with ASP.NET, and am importing an XML file from a form. Right now I convert that into a <code>Stream</code>: </p>
<pre><code>Stream inputStream = XmlFileUploadControl.PostedFile.InputStream;
</code></pre>
<p>because I may need this version later.</p>
<p>I'd like to first check to make make sure that the XML file has the correct format, and, if it is, then display some information: </p>
<pre><code>if (CorrectFileFormat(inputStream))
{
DisplayLicenseInfo(inputStream);
}
else
{
StatusLabel.Text = "Selected file is not a LicensingDiag XML file";
}
</code></pre>
<p>The <code>CorrectFileFormat()</code> method: </p>
<pre><code>protected Boolean CorrectFileFormat(Stream inputStream)
{
XmlReader reader = XmlReader.Create(inputStream);
if (reader.MoveToContent() == XmlNodeType.Element && reader.Name == "DiagReport")
{
return true;
}
}
</code></pre>
<p>The <code>DisplayLicenseInfo()</code> method: </p>
<pre><code>protected void DisplayLicenseInfo(Stream inputStream)
{
XmlReader reader = XmlReader.Create(inputStream);
if (reader.MoveToContent() == XmlNodeType.Element && reader.Name == "LicensingStatus")
{
StatusLabel.Text += ("Licensing Status: " + reader.ReadString() + "<br><br>");
}
}
</code></pre>
<p>However, I'm encountering an <code>XmlException</code> that says "Data at the root level is invalid. Line 1, position 1". Is this because I've already read through the input stream once, and need to reset it? If so, how do I do that?</p> | 17,496,240 | 2 | 1 | null | 2013-07-05 20:06:04.157 UTC | null | 2016-02-28 14:19:23.353 UTC | 2013-08-21 00:30:16.37 UTC | null | 41,071 | null | 823,859 | null | 1 | 9 | c#|xml|stream|xmlreader | 43,537 | <p>The first time you create an <code>XmlReader</code> around the stream, it is at position 0. But the second time you create an <code>XmlReader</code>, the stream has already been partially read, so it is no longer at position 0, so the <code>XmlReader</code> can't read the XML document.</p>
<p>Instead, you should create the <code>XmlReader</code> only once:</p>
<pre><code>using (XmlReader reader = XmlReader.Create(inputStream)
{
if (CorrectFileFormat(reader))
{
DisplayLicenseInfo(reader);
}
else
{
StatusLabel.Text = "Selected file is not a LicensingDiag XML file";
}
}
</code></pre>
<p>If the file is small, you could also consider loading the entire XML document using <code>XmlDocument</code> or <code>XDocument</code> (Linq to XML)</p> |
17,232,714 | Add a custom attribute to a Laravel / Eloquent model on load? | <p>I'd like to be able to add a custom attribute/property to an Laravel/Eloquent model when it is loaded, similar to how that might be achieved with <a href="http://redbeanphp.com/manual/models_and_fuse">RedBean's</a> <code>$model->open()</code> method.</p>
<p>For instance, at the moment, in my controller I have:</p>
<pre><code>public function index()
{
$sessions = EventSession::all();
foreach ($sessions as $i => $session) {
$sessions[$i]->available = $session->getAvailability();
}
return $sessions;
}
</code></pre>
<p>It would be nice to be able to omit the loop and have the 'available' attribute already set and populated.</p>
<p>I've tried using some of the model events described in the documentation to attach this property when the object loads, but without success so far.</p>
<p><em>Notes:</em></p>
<ul>
<li>'available' is not a field in the underlying table.</li>
<li><code>$sessions</code> is being returned as a JSON object as part of an API, and therefore calling something like <code>$session->available()</code> in a template isn't an option</li>
</ul> | 17,250,429 | 9 | 2 | null | 2013-06-21 10:13:20.887 UTC | 75 | 2020-03-27 03:35:16.353 UTC | 2014-05-02 10:12:20.437 UTC | null | 248,567 | null | 921,476 | null | 1 | 273 | php|orm|laravel|eloquent | 295,519 | <p>The problem is caused by the fact that the <code>Model</code>'s <code>toArray()</code> method ignores any accessors which do not directly relate to a column in the underlying table.</p>
<p>As Taylor Otwell mentioned <a href="https://github.com/laravel/framework/issues/112#issuecomment-12530987">here</a>, "This is intentional and for performance reasons." However there is an easy way to achieve this:</p>
<pre><code>class EventSession extends Eloquent {
protected $table = 'sessions';
protected $appends = array('availability');
public function getAvailabilityAttribute()
{
return $this->calculateAvailability();
}
}
</code></pre>
<p>Any attributes listed in the $appends property will automatically be included in the array or JSON form of the model, provided that you've added the appropriate accessor.</p>
<p><strong>Old answer (for Laravel versions < 4.08):</strong></p>
<p>The best solution that I've found is to override the <code>toArray()</code> method and either explicity set the attribute:</p>
<pre><code>class Book extends Eloquent {
protected $table = 'books';
public function toArray()
{
$array = parent::toArray();
$array['upper'] = $this->upper;
return $array;
}
public function getUpperAttribute()
{
return strtoupper($this->title);
}
}
</code></pre>
<p>or, if you have lots of custom accessors, loop through them all and apply them:</p>
<pre><code>class Book extends Eloquent {
protected $table = 'books';
public function toArray()
{
$array = parent::toArray();
foreach ($this->getMutatedAttributes() as $key)
{
if ( ! array_key_exists($key, $array)) {
$array[$key] = $this->{$key};
}
}
return $array;
}
public function getUpperAttribute()
{
return strtoupper($this->title);
}
}
</code></pre> |
11,942,083 | Using OpenQuery With INSERT INTO Statement | <p>I currently use the following to data warehouse a table everday:</p>
<pre><code>DROP TABLE mytable
SELECT firstcolumn, secondcolumn INTO mytable
FROM OPENQUERY (mylinkedserver, 'SELECT firstcolumn, secondcolumn FROM linkedtable')
</code></pre>
<p>I would like to start using TRUNCATE going forward (to perserve system resources and indexes):</p>
<pre><code>TRUNCATE TABLE mytable
INSERT INTO mytable (firstcolumn, secondcolumn)
?
</code></pre>
<p>How do I use OpenQuery with the INSERT INTO statement? </p> | 11,942,165 | 2 | 0 | null | 2012-08-13 20:49:02.427 UTC | null | 2012-08-13 20:55:26.783 UTC | null | null | null | null | 1,423,787 | null | 1 | 3 | sql|sql-server|sql-server-2008|tsql | 45,748 | <p>I believe the syntax is:</p>
<pre><code>TRUNCATE TABLE mytable
INSERT INTO mytable (firstcolumn, secondcolumn)
SELECT firstcolumn, secondcolumn
FROM OPENQUERY (mylinkedserver, 'SELECT firstcolumn, secondcolumn FROM linkedtable')
</code></pre> |
22,121,056 | How to make a website run the index.html file? | <p>I just hosted a website. But, when i want to run the website it opens the index of the website (list of files what i added using FTP and not the Index.html page). How to fix that?</p>
<p>Please help...</p> | 22,121,740 | 5 | 2 | null | 2014-03-01 22:11:03.473 UTC | 8 | 2019-08-13 19:25:09.917 UTC | 2017-12-08 11:28:20.11 UTC | null | 2,682,835 | null | 2,682,835 | null | 1 | 12 | html|ftp | 88,259 | <p>If you want to display the contents of an index.html file when a request is made to your website domain, let's say it is domain.com, then all you have to do is to upload the index.html file to the correct <strong>document root directory</strong> on your server.</p>
<p>The <strong>document root</strong> is the folder where the website files for a domain name are stored. </p>
<p>Document root directories might be named differently depending on your server configuration, however, they're conventionally named as such:</p>
<pre><code>/www/
/public_html/
</code></pre>
<p>They also might live within another directory such as</p>
<pre><code>/home/myusername/public_html/
</code></pre>
<p>Your primary domain is generally rooted in the <strong>www</strong> or <strong>public_html</strong> folder.</p>
<p>When someone tries to load your website and does not manually type in a file name (such as index.php or index.html), the server attempts to load the "directory index". The directory index is a listing of files it should load.</p>
<p>For example, if you type in domain.com (i.e: not domain.com/index.php), the server will attempt to load files in the following order. If a file is not found, then it tries to load the next file in the list:</p>
<pre><code>http://domain.com/index.html
http://domain.com/index.htm
http://domain.com/index.php
</code></pre>
<p>...and finally, if your server does not find any of these files, it then simply returns a listing of all of the files in the directory. <a href="http://i.stack.imgur.com/bwFND.jpg">See Image</a></p>
<p>To prevent this, one should create an <strong>index.html</strong> file and upload it to the server's document root directory as we mentioned before. </p>
<p>Try creating your first .html file with a simple text editor by copying the html markup below into a new file and then save it as index.html or <a href="http://cl.ly/2H370E0B3m1U">download the file here</a></p>
<pre><code><html>
<head>
<title>My website's first HTML5 page</title>
</head>
<body>
<h1>Welcome!</h1>
<p>Sorry, but our website is under development.</p>
</body>
</html>
</code></pre>
<p>Proceed and upload the <strong>index.html</strong> file to your server's document root directory, and then try to access your website domain. It will probably load your <strong>index.html</strong> and your server will now display the contents of index.html file instead of the "DirectoryIndex listing of files".</p>
<p><strong>WHEN IT DOES NOT WORK:</strong></p>
<p>If you've just placed an index.html or index.php file on your server's document root folder, for example: /public_html/ and you're still not getting it to load these files upon a request to your domain, chances are your server is missing a specific configuration for the "DirectoryIndex Directive".</p>
<p>If that fails to happen, you can use the DirectoryIndex directive in an .htaccess file to specify a custom file or files that the web server looks for when a visitor requests a directory. To enable the DirectoryIndex directive, use a text editor to create/modify the .htaccess file as follows. Replace filename with the file that you want to display whenever a user requests the server's document root directory:</p>
<pre><code>DirectoryIndex filename
</code></pre>
<p>You can also specify multiple filenames, and the web server will search for each file until it finds a match.</p>
<p><strong>Open a text editor and copy the following example directive, then paste it on the new file:</strong></p>
<pre><code>DirectoryIndex index.php index.html index.htm
</code></pre>
<p><strong>Save the file as .htaccess</strong></p>
<p><strong>No file extension, just name it as .htaccess placing a dot (.) in front of it to ensure it is a hidden file.</strong></p>
<p>In this directive, when a visitor requests the directory name, the web server looks first for an index.php file. If it does not find an index.php file, it looks for an index.html file, and so on until it finds a match or runs out of files to search.</p>
<p><strong>Now upload the .htaccess file to your server's document root directory.</strong></p>
<p>It is recommended to restart the server in order to changes to take effect, although you could just try to refresh the directory to see if it works.</p>
<p>If you've got full control over your server you might find it easy restart/reload it. However, if you rely on a shared hosting service, maybe you'll not have enough permission to create an .htaccess file or to restart the server on your own, meaning that you would have to contact your hosting provider support team and request them to do that for you.</p>
<p>I hope it helps you. Good luck.</p> |
22,257,726 | EACCES Error with Bower install? | <p>I've read a few answers on StackOverflow & some other sites but none seem to fix the issue I'm having.</p>
<p>I'm installing AppGyver Add-ons, via terminal. Getting the following error:</p>
<pre><code>BradMacBookPro:SparksInSpain breadadams$ bower install https://##MY-DOWNLOAD-CODE##@addons.appgyver.com/steroids-addons.js?version=3.1.0 --save
bower not-cached https://##MY-DOWNLOAD-CODE##@addons.appgyver.com/steroids-addons.js?version=3.1.0#*
bower resolve https://##MY-DOWNLOAD-CODE##@addons.appgyver.com/steroids-addons.js?version=3.1.0#*
bower download https://##MY-DOWNLOAD-CODE##@addons.appgyver.com/steroids-addons.js?version=3.1.0
bower EACCES EACCES, mkdir '/Users/breadadams/.cache/bower/packages/7480e059b318750565b4b25c2556c9c4'
Stack trace:
Error: EACCES, mkdir '/Users/breadadams/.cache/bower/packages/7480e059b318750565b4b25c2556c9c4'
Console trace:
Trace
at StandardRenderer.error (/usr/local/lib/node_modules/bower/lib/renderers/StandardRenderer.js:74:17)
at Logger.updateNotifier.packageName (/usr/local/lib/node_modules/bower/bin/bower:109:18)
at Logger.EventEmitter.emit (events.js:95:17)
at Logger.emit (/usr/local/lib/node_modules/bower/node_modules/bower-logger/lib/Logger.js:29:39)
at /usr/local/lib/node_modules/bower/lib/commands/install.js:27:16
at _rejected (/usr/local/lib/node_modules/bower/node_modules/q/q.js:808:24)
at /usr/local/lib/node_modules/bower/node_modules/q/q.js:834:30
at Promise.when (/usr/local/lib/node_modules/bower/node_modules/q/q.js:1079:31)
at Promise.promise.promiseDispatch (/usr/local/lib/node_modules/bower/node_modules/q/q.js:752:41)
at /usr/local/lib/node_modules/bower/node_modules/q/q.js:574:44
System info:
Bower version: 1.2.8
Node version: 0.10.25
OS: Darwin 13.1.0 x64
</code></pre>
<p>I'm not sudo, I've tried --allow-root, cleaned the bower cache, always get the same error on install. Some local permission problem?</p> | 26,104,460 | 8 | 2 | null | 2014-03-07 18:19:59.017 UTC | 13 | 2017-08-18 11:34:14.433 UTC | 2017-08-18 11:34:14.433 UTC | null | 2,553,600 | null | 2,553,600 | null | 1 | 47 | terminal|bower|steroids | 41,160 | <p>I had a similar issue that I couldn't resolve using these suggestions. I was successful when I ran Bower with root privileges, like so:</p>
<pre><code>sudo bower install --allow-root
</code></pre> |
37,565,793 | How to let the user select an input from a finite list? | <p>Is it possible to ask for selection between multiple choices in Python, without an if loop?</p>
<p>Example:</p>
<pre><code>print "Do you want to enter the door"
raw_input ("Yes or not")
</code></pre>
<p>And the user can only choose between the selections.</p> | 37,567,304 | 6 | 4 | null | 2016-06-01 10:16:02.02 UTC | 12 | 2022-04-11 15:58:47.457 UTC | 2021-10-18 21:28:23.38 UTC | null | -1 | null | 2,980,075 | null | 1 | 16 | python|user-input | 75,457 | <p>If you need to do this on a regular basis, there is a convenient library for this purpose that may help you achieve better user experience easily : <a href="https://pypi.python.org/pypi/inquirer" rel="noreferrer">inquirer</a></p>
<p><strong>Disclaimer : As far as i know, it won't work on Windows without some hacks.</strong></p>
<p>You can install inquirer with pip :</p>
<pre><code>pip install inquirer
</code></pre>
<p><strong>Example 1 : Multiple choices</strong></p>
<p>One of inquirer's feature is to let users select from a list with the keyboard arrows keys, not requiring them to write their answers. This way you can achieve better UX for your console application.</p>
<p>Here is an example taken from the <a href="https://pypi.python.org/pypi/inquirer" rel="noreferrer">documentation</a> :</p>
<pre><code>import inquirer
questions = [
inquirer.List('size',
message="What size do you need?",
choices=['Jumbo', 'Large', 'Standard', 'Medium', 'Small', 'Micro'],
),
]
answers = inquirer.prompt(questions)
print answers["size"]
</code></pre>
<p><a href="https://i.stack.imgur.com/zSB7F.png" rel="noreferrer"><img src="https://i.stack.imgur.com/zSB7F.png" alt="Inquirer example"></a></p>
<p><strong>Example 2 : Yes/No questions :</strong></p>
<p>For "Yes/No" questions such as yours, you can even use inquirer's Confirm :</p>
<pre><code>import inquirer
confirm = {
inquirer.Confirm('confirmed',
message="Do you want to enter the door ?" ,
default=True),
}
confirmation = inquirer.prompt(confirm)
print confirmation["confirmed"]
</code></pre>
<p><a href="https://i.stack.imgur.com/uZNAi.png" rel="noreferrer"><img src="https://i.stack.imgur.com/uZNAi.png" alt="Yes no questions with Inquirer"></a></p>
<p><strong>Others useful links :</strong></p>
<p><a href="https://github.com/magmax/python-inquirer" rel="noreferrer">Inquirer's Github repo</a></p> |
37,392,166 | Firebase "Run firebase use default to activate project APP_NAME" | <p>It was successfully when deployed first time, now im trying to deploy again, shows an error:</p>
<pre><code>Run firebase use default to activate project MY_APP_NAME
</code></pre>
<p><strong>Error:</strong></p>
<blockquote>
<p>No project active, but a project alias is available.</p>
</blockquote> | 37,464,231 | 9 | 5 | null | 2016-05-23 13:20:55.813 UTC | 1 | 2020-12-24 03:42:14.737 UTC | 2016-05-23 14:08:19.813 UTC | null | 2,873,538 | null | 1,468,908 | null | 1 | 29 | firebase | 26,504 | <p>At first should <code>firebase use</code> to make default alias. </p>
<p>After <code>firebase use default</code> to use default. </p>
<p>Then <code>firebase deploy</code> yahoo.. you can deploy</p> |
19,663,704 | Understanding how .Internal C functions are handled in R | <p>I wonder if anyone can illustrate to me how R executes a <code>C</code> call from an R command typed at the console prompt. I am particularly confused by <code>R</code>'s treatment of a) function arguments and b) the function call itself. </p>
<p>Let's take an example, in this case <code>set.seed()</code>. Wondering how it works I type the name in at the prompt, get the source (<a href="https://stackoverflow.com/q/19226816/1478381"><strong>look here for more on that</strong></a>), see there is eventually a <code>.Internal(set.seed(seed, i.knd, normal.kind)</code>, so dutifully look up the relevant function name in the <code>.Internals</code> section of <code>/src/names.c</code>, find it is called <code>do_setseed</code> and is in <code>RNG.c</code> which leads me to...</p>
<pre><code>SEXP attribute_hidden do_setseed (SEXP call, SEXP op, SEXP args, SEXP env)
{
SEXP skind, nkind;
int seed;
checkArity(op, args);
if(!isNull(CAR(args))) {
seed = asInteger(CAR(args));
if (seed == NA_INTEGER)
error(_("supplied seed is not a valid integer"));
} else seed = TimeToSeed();
skind = CADR(args);
nkind = CADDR(args);
//...
//DO RNG here
//...
return R_NilValue;
}
</code></pre>
<ul>
<li>What are <code>CAR</code>, <code>CADR</code>, <code>CADDR</code>? My research leads me to believe they are a <code>Lisp</code> influenced construct concerning lists but beyond that I do not understand what these functions do or <em>why they are needed</em>.</li>
<li>What does <code>checkArity()</code> do?</li>
<li><code>SEXP args</code> seems self explanatory, but is this a list of the
arguments that is passed in the function call?</li>
<li>What does <code>SEXP op</code> represent? I take this to mean operator (like in binary functions such as <code>+</code>), but then what is the <code>SEXP call</code> for?</li>
</ul>
<p>Is anyone able to flow through what happens when I type</p>
<pre><code>set.seed(1)
</code></pre>
<p>at the R console prompt, up to the point at which <code>skind</code> and <code>nkind</code> are defined? I find I am not able to well understand the source code at this level and path from interpreter to C function.</p> | 19,664,351 | 2 | 4 | null | 2013-10-29 16:16:33.103 UTC | 16 | 2013-10-29 23:11:01.9 UTC | 2017-05-23 11:47:21.377 UTC | null | -1 | null | 1,478,381 | null | 1 | 39 | c|r|syntax|internals | 1,618 | <p><code>CAR</code> and <code>CDR</code> are how you access pairlist objects, as explained in <a href="http://cran.r-project.org/doc/manuals/R-lang.html#Pairlist-objects">section 2.1.11 of <em>R Language Definition</em></a>. <code>CAR</code> contains the first element, and <code>CDR</code> contains the remaining elements. An example is given in <a href="http://cran.r-project.org/doc/manuals/R-exts.html#Calling-_002eExternal">section 5.10.2 of <em>Writing R Extensions</em></a>:</p>
<pre><code>#include <R.h>
#include <Rinternals.h>
SEXP convolveE(SEXP args)
{
int i, j, na, nb, nab;
double *xa, *xb, *xab;
SEXP a, b, ab;
a = PROTECT(coerceVector(CADR(args), REALSXP));
b = PROTECT(coerceVector(CADDR(args), REALSXP));
...
}
/* The macros: */
first = CADR(args);
second = CADDR(args);
third = CADDDR(args);
fourth = CAD4R(args);
/* provide convenient ways to access the first four arguments.
* More generally we can use the CDR and CAR macros as in: */
args = CDR(args); a = CAR(args);
args = CDR(args); b = CAR(args);
</code></pre>
<p>There's also a <code>TAG</code> macro to access the names given to the actual arguments.</p>
<p><code>checkArity</code> ensures that the number of arguments passed to the function is correct. <code>args</code> are the actual arguments passed to the function. <code>op</code> is offset pointer "used for C functions that deal with more than one R function" (quoted from <code>src/main/names.c</code>, which also contains the table showing the offset and arity for each function).</p>
<p>For example, <code>do_colsum</code> handles <code>col/rowSums</code> and <code>col/rowMeans</code>.</p>
<pre><code>/* Table of .Internal(.) and .Primitive(.) R functions
* ===== ========= ==========
* Each entry is a line with
*
* printname c-entry offset eval arity pp-kind precedence rightassoc
* --------- ------- ------ ---- ----- ------- ---------- ----------
{"colSums", do_colsum, 0, 11, 4, {PP_FUNCALL, PREC_FN, 0}},
{"colMeans", do_colsum, 1, 11, 4, {PP_FUNCALL, PREC_FN, 0}},
{"rowSums", do_colsum, 2, 11, 4, {PP_FUNCALL, PREC_FN, 0}},
{"rowMeans", do_colsum, 3, 11, 4, {PP_FUNCALL, PREC_FN, 0}},
</code></pre>
<p>Note that <code>arity</code> in the above table is 4 because (even though <code>rowSums</code> et al only have 3 arguments) <code>do_colsum</code> has 4, which you can see from the <code>.Internal</code> call in <code>rowSums</code>:</p>
<pre><code>> rowSums
function (x, na.rm = FALSE, dims = 1L)
{
if (is.data.frame(x))
x <- as.matrix(x)
if (!is.array(x) || length(dn <- dim(x)) < 2L)
stop("'x' must be an array of at least two dimensions")
if (dims < 1L || dims > length(dn) - 1L)
stop("invalid 'dims'")
p <- prod(dn[-(1L:dims)])
dn <- dn[1L:dims]
z <- if (is.complex(x))
.Internal(rowSums(Re(x), prod(dn), p, na.rm)) + (0+1i) *
.Internal(rowSums(Im(x), prod(dn), p, na.rm))
else .Internal(rowSums(x, prod(dn), p, na.rm))
if (length(dn) > 1L) {
dim(z) <- dn
dimnames(z) <- dimnames(x)[1L:dims]
}
else names(z) <- dimnames(x)[[1L]]
z
}
</code></pre> |
19,720,711 | Git warning: push.default is unset; its implicit value is changing | <p>When I push to remote in Git, I get this warning:</p>
<pre><code>warning: push.default is unset; its implicit value is changing in
Git 2.0 from 'matching' to 'simple'. To squelch this message
and maintain the current behavior after the default changes, use:
git config --global push.default matching
To squelch this message and adopt the new behavior now, use:
git config --global push.default simple
See 'git help config' and search for 'push.default' for further information.
(the 'simple' mode was introduced in Git 1.7.11. Use the similar mode
'current' instead of 'simple' if you sometimes use older versions of Git)
To **********************************
6b9a6d2..3ab1eab master -> master
</code></pre>
<p>What does this warning mean and what should be done about it?</p> | 19,723,478 | 4 | 5 | null | 2013-11-01 04:17:39.537 UTC | 22 | 2021-07-17 16:39:15.473 UTC | 2016-10-23 11:23:17.55 UTC | null | 492,336 | null | 2,215,537 | null | 1 | 70 | git|push | 64,075 | <p>This warning was introduced in Git 1.7.11 along with the <code>simple</code> style of pushing. The issue is that the current default, <code>matching</code>, can result in inexperienced users force pushing when some branches are behind their remote equivalent because the branches simply aren't up-to-date. The end result is that they end up rewinding the branch and potentially losing their work or someone else's. The <code>simple</code> mode was introduced as a new <code>push.default</code> behavior and will become the default in Git 2.0 (which should hopefully be out sometime early next year).</p>
<p>The new <code>simple</code> behavior is a lot like the <code>upstream</code> setting: it only pushes the current branch that you're currently on, if it has a remote branch that it's tracking. It adds one extra criteria: the remote branch must have the same name as the local one.</p>
<p>As you discovered, the way to get rid of the message is to set <code>push.default</code>. To get the new behavior, use:</p>
<pre><code>git config --global push.default simple
</code></pre>
<p>To get Git's default behavior but without the warning message, use:</p>
<pre><code>git config --global push.default matching
</code></pre>
<p>I'd really advise <em>against</em> using matching though. In general, most people really want the new <code>simple</code> behavior, or <code>upstream</code>.</p> |
19,376,735 | How to return a specific element of an array? | <p>I want to return odd numbers of an array yet Eclipse doesn't seem to accept my return <code>array[i];</code> code. I think it requires returning a whole array since I set an array as a parameter to my method.
As I said before, I need to pass an array and get a specific element of that array in return. Even if I make that array static, how do I return a single element?</p>
<p>Edit : Alright then, here it is:</p>
<pre><code>public class newClass{
public static void main(String[] args)
{
int [] newArray= new int [4];
int [] array = {4,5,6,7};
newArray[0] = array[0]+array[1]+array[2]+array[3];
newArray[1] = array[0]*array[1]*array[2]*array[3];
newArray[2] = findOut(array);
}
public static int findOut (int [] array3)
{
int e1=0;
int e2=0;
for (int i=0; i<array3.length; i++)
{
if (array3[i]%2==0)
{
e1+=array3[i];
array3[i]=e1
return array3[i];
}
else
{
e2+=array3[i];
array3[i]=e2;
return array3[i];
}
}
}
}
</code></pre>
<p>I know there are probably more than a few mistakes here but I'm working on it and I'm not only returning odd numbers, I also add them together.</p> | 19,376,865 | 4 | 6 | null | 2013-10-15 08:41:40.72 UTC | 1 | 2013-10-15 10:34:11.57 UTC | 2013-10-15 09:11:05.397 UTC | null | 2,858,004 | null | 2,858,004 | null | 1 | 2 | java|arrays|parameters|elements | 159,145 | <p>You code should look like this:</p>
<pre><code>public int getElement(int[] arrayOfInts, int index) {
return arrayOfInts[index];
}
</code></pre>
<p>Main points here are method return type, it should match with array elements type and if you are working from <code>main()</code> - this method must be static also.</p> |
21,865,041 | In C, what exactly happens when you pass a NULL pointer to strcmp()? | <p>I have read that the following results in undefined behavior. </p>
<pre><code>strcmp(foo, NULL);
</code></pre>
<p>But what exactly happens "underneath the hood," so to speak? Is <code>foo</code> compared to garbage data? Is <code>NULL</code> dereferenced? What are the details that cause "undefined behavior"?</p> | 21,865,119 | 4 | 9 | null | 2014-02-18 20:51:58.44 UTC | 1 | 2016-02-22 19:13:11.237 UTC | 2016-02-22 19:13:11.237 UTC | null | 754,842 | null | 754,842 | null | 1 | 29 | c | 40,827 | <p>It depends on the implementation, which is free to assume your parameters are valid (i.e. not null in this case). The behaviour may or may not be reproducible from execution to execution, or from one implementation/platform to another.</p> |
17,658,216 | Extract last word in string in R | <p>What's the most elegant way to extract the last word in a sentence string?</p>
<p>The sentence does not end with a "."
Words are seperated by blanks.</p>
<pre><code>sentence <- "The quick brown fox"
TheFunction(sentence)
</code></pre>
<p>should return: "fox"</p>
<p>I do not want to use a package if a simple solution is possible.
If a simple solution based on package exists, that is also fine.</p> | 17,658,506 | 5 | 3 | null | 2013-07-15 15:41:33.267 UTC | 8 | 2020-03-08 13:45:44.31 UTC | 2013-07-15 15:59:14.577 UTC | null | 906,490 | null | 2,030,503 | null | 1 | 35 | r | 42,976 | <pre><code>tail(strsplit('this is a sentence',split=" ")[[1]],1)
</code></pre>
<p>Basically as suggested by @Señor O.</p> |
17,223,851 | sort list by date in descending order - groovy madness | <p>I'm not able to sort a list of Objects by a Date in descending order</p>
<p>Let's say this is my class <code>Thing</code></p>
<pre><code>class Thing {
Profil profil
String status = 'ready'
Date dtCreated = new Date()
}
</code></pre>
<p>Inside the method I'm creating the <code>List things</code></p>
<pre><code> List profiles = profil.xyz?.collect { Profil.collection.findOne(_id:it) }
List things = []
</code></pre>
<p>and then I populate the list with each associated <code>Thing</code> of each profile</p>
<pre><code> profiles.each() { profile,i ->
if(profile) {
things += Thing.findAllByProfilAndStatus(profile, "ready", [sort: 'dtCreated', order: 'desc']) as
}
</code></pre>
<p>Alright, now <code>things</code> has a lot of things in it, unfortunately the <code>[order: 'desc']</code> was applied to each set of things and iI need to sort the whole list by <code>dtCreated</code>. That works wonderful like</p>
<pre><code> things.sort{it.dtCreated}
</code></pre>
<p>Fine, now all the things are sorted by date but in the wrong order, the most recent thing is the last thing in the list</p>
<p>So I need to sort in the opposite direction, I didn't find anything on the web that brought me forward, I tried stuff like</p>
<pre><code> things.sort{-it.dtCreated} //doesnt work
things.sort{it.dtCreated}.reverse() //has no effect
</code></pre>
<p>and I'm not finding any groovy approach for such a standard operation, maybe someone has a hint how I can sort my things by date in descending order ? There must be something like orm I used above <code>[sort: 'dtCreated', order: 'desc']</code>
or isn't it?</p> | 17,224,150 | 3 | 1 | null | 2013-06-20 21:10:22.933 UTC | 5 | 2021-04-14 16:08:20.903 UTC | 2021-04-14 16:08:20.903 UTC | null | 3,964,927 | null | 1,712,905 | null | 1 | 44 | java|date|sorting|grails|groovy | 85,659 | <p>Instead of</p>
<pre><code>things.sort{-it.dtCreated}
</code></pre>
<p>you might try </p>
<pre><code>things.sort{a,b-> b.dtCreated<=>a.dtCreated}
</code></pre>
<p>reverse() does nothing because it creates a new list instead of mutating the existing one.</p>
<pre><code>things.sort{it.dtCreated}
things.reverse(true)
</code></pre>
<p>should work</p>
<pre><code>things = things.reverse()
</code></pre>
<p>as well.</p> |
17,456,671 | To what level does MongoDB lock on writes? (or: what does it mean by "per connection" | <p>In the mongodb documentation, it says:</p>
<blockquote>
<p>Beginning with version 2.2, MongoDB implements locks on a per-database basis for most read and write operations. Some global operations, typically short lived operations involving multiple databases, still require a global “instance” wide lock. Before 2.2, there is only one “global” lock per mongod instance.</p>
</blockquote>
<p>Does this mean that in the situation that I Have, say, 3 connections to mongodb://localhost/test from different apps running on the network - only one could be writing at a time? Or is it just per connection? </p>
<p>IOW: Is it per connection, or is the whole /test database locked while it writes?</p> | 17,456,923 | 4 | 2 | null | 2013-07-03 19:35:24.333 UTC | 65 | 2021-07-03 09:20:41.783 UTC | 2013-12-17 09:19:53.69 UTC | null | 2,096,752 | null | 570,259 | null | 1 | 65 | mongodb|concurrency|locking | 63,191 | <p>It is not per connection, it is per <code>mongod</code>. In other words the lock will exist across all connections to the <code>test</code> database on that server.</p>
<p>It is also a read/write lock so if a write is occuring then a read must wait, otherwise how can MongoDB know it is a consistent read?</p>
<p>However I should mention that MongoDB locks are very different to SQL/normal transactional locks you get and normally a lock will be held for about a microsecond between average updates.</p> |
26,037,744 | Efficiency of findViewById | <p>Probably most Android devs know that <code>findViewById</code> is not a cheap operation. Another thing that most of us know, is that you can boost the performance by using the smallest sub-tree of the view hierarchy to find views by their id, example:</p>
<pre><code><LinearLayout
android:id="@+id/some_id_0">
<LinearLayout
android:id="@+id/some_id_1">
<LinearLayout
android:id="@+id/some_id_2">
<TextView android:id="@+id/textview" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</code></pre>
<p>In this case you probably want to search in the <code>LinearLayout</code> with the <code>id == @id/textview</code></p>
<p>But what is the case when the hierarchy is not cascading, but rather branching on every level, and you want to find the views on the "leaves" let's say? Do you perform the <code>findViewById</code> to get to the bottom of the branch by finding parents, OR do you perform the <code>findViewById</code> on a larger subset? I think a simple answer would be that it depends on the case, but maybe we could generalize a bit on what it really depends?</p>
<p>Thanks</p>
<h1><b>EDIT:</b></h1>
<p>By a larger subset I mean something like this:</p>
<pre><code><RelativeLayout android:id="@+id/r0">
<RelativeLayout
android:id="@+id/r1">
<LinearLayout
android:id="@+id/some_id_0">
<LinearLayout
android:id="@+id/some_id_1">
<LinearLayout
android:id="@+id/some_id_2">
<TextView android:id="@+id/textview0" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="@+id/some_id_3">
<LinearLayout
android:id="@+id/some_id_4">
<LinearLayout
android:id="@+id/some_id_5">
<TextView android:id="@+id/textview1" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</RelativeLayout>
<LinearLayout
android:id="@+id/some_id_6">
<LinearLayout
android:id="@+id/some_id_7">
<LinearLayout
android:id="@+id/some_id_8">
<TextView android:id="@+id/textview2" />
<TextView android:id="@+id/textview3" />
<TextView android:id="@+id/textview4" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</RelativeLayout>
</code></pre>
<p>So the question would be if I want to <code>findViewById</code> the <code>TextView</code> views in <code>LinearLayout</code> with <code>@+id/some_id_8</code>, should I perform this operation on the whole container, or I should <code>findViewById</code> the <code>LinearLayout</code> with <code>@+id/some_id_8</code> and on this view <code>findViewById</code> all the <code>TextViews</code>?</p> | 26,118,335 | 2 | 4 | null | 2014-09-25 11:41:59.28 UTC | 8 | 2016-06-11 00:23:17.243 UTC | 2014-09-30 09:35:03.167 UTC | null | 954,474 | null | 954,474 | null | 1 | 14 | android|performance|android-layout|findviewbyid | 8,997 | <p>It makes absolutely no difference if you look for the <code>View</code> directly or if you look for a parent first and then the child. But if you for example want to retrieve the three <code>TextViews</code> in the <code>LinearLayout</code> with the id <code>some_id_8</code> then it would be better for performance if you first look for the <code>LinearLayout</code> and then for the <code>TextViews</code>. But the difference is miniscule. The real problem is <strong>the layout itself</strong> (more on that further down).</p>
<p>And generally <code>findViewById()</code> is not the source of all evil. It can be a problem in a <code>ListView</code> if you have to call <code>findViewById()</code> possibly even several times during each <code>getView()</code> call, but that's what the view holder pattern is for. </p>
<p>When performance is critical see to it that you call <code>findViewById()</code> as little as possible. In a <code>Fragment</code> or <code>Activity</code> you can look for all the <code>Views</code> you will ever need in <code>onCreateView()</code> or <code>onCreate()</code>. If you save the references in a few member variables you will never have to call it again.</p>
<hr>
<p>Now to explain why <code>findViewById()</code> can be a performance problem we have to look at its implementation, <a href="http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.4.4_r1/android/view/View.java#View.findViewById%28int%29"><strong>this link leads to the Android 4.4.4 View source code</strong></a>:</p>
<pre><code>public final View findViewById(int id) {
if (id < 0) {
return null;
}
return findViewTraversal(id);
}
</code></pre>
<p>So <code>findViewById()</code> just checks if the id is valid, and if it is then the protected method <code>findViewTraversal()</code> is called. In a <code>View</code> it is implemented like this:</p>
<pre><code>protected View findViewTraversal(int id) {
if (id == mID) {
return this;
}
return null;
}
</code></pre>
<p>It just checks if the passed in id is equal to the id of the <code>View</code> and returns <code>this</code> if it does, otherwise <code>null</code>. The interesting part is the <code>findViewTraversal()</code> implementation of <code>ViewGroup</code>, <a href="http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.4.4_r1/android/view/ViewGroup.java#ViewGroup.findViewTraversal%28int%29"><strong>this links leads to the Android 4.4.4 ViewGroup source code</strong></a>:</p>
<pre><code>protected View findViewTraversal(int id) {
if (id == mID) {
return this;
}
final View[] where = mChildren;
final int len = mChildrenCount;
for (int i = 0; i < len; i++) {
View v = where[i];
if ((v.mPrivateFlags & PFLAG_IS_ROOT_NAMESPACE) == 0) {
v = v.findViewById(id);
if (v != null) {
return v;
}
}
}
return null;
}
</code></pre>
<p>The first if at the top of this method is the same as in the <code>View</code> implementation, it just checks if the passed in id equals the id of the <code>ViewGroup</code> and if it does it returns itself. After that it loops through all the children and calls <code>findViewById()</code> on each of the children, if the return value of this call is not <code>null</code> then the <code>View</code> we are looking for has been found and will be returned. </p>
<p><sub>If you want more details about how <code>Views</code> or <code>ViewGroups</code> work I suggest you study the source code yourself!</sub></p>
<hr>
<p>So this all seems pretty straight forward. The view hierarchy is essentially traversed like a tree. And that can make it pretty expensive or pretty fast depending on how many <code>Views</code> are in your layout. It doesn't matter if your layout looks like this:</p>
<pre><code><LinearLayout android:id="@+id/some_id_0">
<LinearLayout android:id="@+id/some_id_1">
<LinearLayout android:id="@+id/some_id_2">
<TextView android:id="@+id/textview0" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</code></pre>
<p>Or if it looks like this:</p>
<pre><code><LinearLayout android:id="@+id/some_id_0">
<LinearLayout android:id="@+id/some_id_1" />
<LinearLayout android:id="@+id/some_id_2" />
<TextView android:id="@+id/textview0" />
</LinearLayout>
</code></pre>
<p>Because the amount of <code>Views</code> is the same in both cases, and the performance of <code>findViewById()</code> scales with the amount of the <code>Views</code>. </p>
<p><strong>BUT</strong> the general rule is that you should try to reduce the complexity of the layout to increase performance and that you should often use a <code>RelativeLayout</code>. And that works just because if you reduce the complexity you also reduce the amount of <code>Views</code> in the layout and <code>RelativeLayouts</code> are very good at reducing complexity. Let me illustrate that, image you have a layout like this:</p>
<pre><code><LinearLayout android:id="@+id/some_id_0">
<RelativeLayout android:id="@+id/some_id_5">
<LinearLayout android:id="@+id/some_id_1" />
<LinearLayout android:id="@+id/some_id_2" />
</RelativeLayout>
<RelativeLayout android:id="@+id/some_id_6">
<LinearLayout android:id="@+id/some_id_3" />
<LinearLayout android:id="@+id/some_id_4" />
</RelativeLayout>
</LinearLayout>
</code></pre>
<p>Imagine that in this case both of the <code>RelativeLayouts</code> above are just there to position the inner <code>LinearLayouts</code> in some special way and the outer <code>LinearLayout</code> is just there to position the <code>RelativeLayouts</code> below each other. You can very easily build the same layout with just a <code>RelativeLayout</code> as a root and the four <code>LinearLayouts</code> as children:</p>
<pre><code><RelativeLayout android:id="@+id/some_id_0">
<LinearLayout android:id="@+id/some_id_1" />
<LinearLayout android:id="@+id/some_id_2" />
<LinearLayout android:id="@+id/some_id_3" />
<LinearLayout android:id="@+id/some_id_4" />
</RelativeLayout>
</code></pre>
<p>And the performance of that layout will be better than the layout above not because the <code>RelativeLayout</code> is somehow performance-wise better than a <code>LinearLayout</code> and not because the layout is flatter, but simply because the amount of <code>Views</code> in the layout is lower. The same applies for almost all other view-related processes like drawing, layouting, measuring. Everything will be faster just because the amount of <code>Views</code> in the layout is lower.</p>
<hr>
<p>And to return to your original question: If you want a performance increase than reduce the complexity of your layout. There is absolutely no reason to have so many nested <code>LinearLayouts</code>. Your "large subset" can almost certainly be reduced to this:</p>
<pre><code><RelativeLayout android:id="@+id/r0">
<TextView android:id="@+id/textview0" />
<TextView android:id="@+id/textview1" />
<TextView android:id="@+id/textview2" />
<TextView android:id="@+id/textview3" />
<TextView android:id="@+id/textview4" />
</RelativeLayout>
</code></pre>
<p>And such a layout would definitely yield a big performance boost.</p> |
22,989,500 | Is RestTemplate thread safe? | <p>Is a Spring <code>RestTemplate</code> thread-safe? That is</p>
<ul>
<li>Is a <code>RestTemplate</code> a Strategy object that multiple connections can safely share. <strong>or</strong></li>
<li>Is a <code>RestTemplate</code> a connection object (like a data-base connection), which can not be shared while in use, and requires creation afresh, or pooling, for each connection.</li>
</ul> | 22,989,501 | 4 | 4 | null | 2014-04-10 13:30:02.903 UTC | 19 | 2019-09-05 15:47:48.753 UTC | null | null | null | null | 545,127 | null | 1 | 77 | java|spring|rest|thread-safety | 49,881 | <p><code>RestTemplate</code> <a href="https://spring.io/blog/2009/03/27/rest-in-spring-3-resttemplate" rel="noreferrer">is thread safe</a> (emphasis added):</p>
<blockquote>
<p>Conceptually, it is very similar to the <code>JdbcTemplate</code>, <code>JmsTemplate</code>, and the various other templates found in the Spring Framework and other portfolio projects. This means, for instance, that the <strong><code>RestTemplate</code> is thread-safe once constructed</strong></p>
</blockquote>
<hr>
<p>Objects of the <code>RestTemplate</code> class do not change any of their state information to process HTTP: the class is an instance of the Strategy design pattern, rather than being like a connection object. With no state information, there is no possibility of different threads corrupting or racing state information if they share a <code>RestTemplate</code> object. This is why it is possible for threads to share these objects.</p>
<p>If you examine <a href="https://github.com/spring-projects/spring-framework/blob/master/spring-web/src/main/java/org/springframework/web/client/RestTemplate.java" rel="noreferrer">the source code of <code>RestTemplate</code></a> you will see that it does not use <code>synchronized</code> methods or <code>volatile</code> fields to provide thread-safety after construction of the object. So it is <em>not</em> safe to modify a <code>RestTemplate</code> object after construction. In particular, it is unsafe to add a message converter.</p>
<p>To provide it with a list of message converters you must do one of the following:</p>
<ul>
<li>Use the <code>RestTemplate(List<HttpMessageConverter<?>> messageConverters)</code> constructor. As the internal list of <code>messageConverters</code> is <code>final</code>, this <a href="https://stackoverflow.com/questions/33785455/does-mutation-of-an-non-thread-safe-collection-in-a-constructor-need-to-be-synch">safely publishes the list of message converters</a>.</li>
<li>Use the <code>setMessageConverters(List<HttpMessageConverter<?>> messageConverters)</code> mutator <strong>and</strong> then <a href="https://stackoverflow.com/questions/801993/java-multi-threading-safe-publication?">safely-publish</a> the changed <code>RestTemplate</code> object. Using a Spring bean definition that has a <code><property name="messageConverters"><list>...</code> does this, as the bean <a href="https://stackoverflow.com/questions/18510395/does-spring-publish-beans-in-thread-safe-manner">will be safely published by the thread setting up the container</a> in most practical use cases.</li>
<li>Use <code>List.add</code> on the reference returned by <code>getMessageConverters()</code> and then safely publish the changed <code>RestTemplate</code> object. However, the documentation for <code>RestTemplate</code> does not explicitly state that it returns a reference that can be used to alter the list of message converters. The current implementation does, but possibly the implementation might be changed to return a <code>Collections.unmodifiableList</code> or a copy of the list. So it might be better not to change it this way.</li>
</ul>
<p>Note that the first case is the only means of setting up the message converters when constructing the object, so it <strong>is</strong> correct to say that it "is thread safe once constructed".</p>
<p>The class is part of the Spring Framework, so in almost all practical cases objects of the class will be set up as part of a Spring Application Context, using the first (dependency injection using a constructor) or second (dependency injection using a setter) methods, and so would be guaranteed to be safely published to multiple threads.</p> |
43,089,058 | Entity Framework Core jsonb column type | <p>I am using Entity Framework Core with npgsql postgresql for Entity Framework Core.</p>
<p>My question is, using migrations, how do I mark a class property to generate a JSONB column type?</p>
<p>For example:</p>
<pre><code>public class MyTableClass
{
public int Id { get; set; }
// My JSONB column
public string Data { get; set; }
}
</code></pre>
<p>Thanks in advance.</p> | 43,115,883 | 2 | 3 | null | 2017-03-29 09:05:58.29 UTC | 7 | 2021-04-09 02:32:33.817 UTC | 2017-04-04 16:02:05.577 UTC | null | 13,302 | null | 1,582,065 | null | 1 | 30 | c#|postgresql|entity-framework-core|npgsql | 27,248 | <p>Based on H. Herzl comment:</p>
<p>My final solution was something like this:</p>
<pre><code>public class MyTableClass
{
public int Id { get; set; }
[Column(TypeName = "jsonb")]
public string Data { get; set; }
}
</code></pre>
<p>Migrations generated this:</p>
<pre><code>Data = table.Column<string>(type: "jsonb", nullable: true),
</code></pre>
<p>When updated the database with migrations, the Data column was created correctly with jsonb type.</p>
<p>Thank you H. Herzl!</p> |
9,260,159 | Java 7 Automatic Resource Management JDBC (try-with-resources statement) | <p>How to integrate the common JDBC idiom of creating/receiving a connection, querying the database and possibly processing the results with Java 7's automatic resource management, the try-with-resources statement? (<a href="http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html">Tutorial</a>)</p>
<p>Before Java 7, the usual pattern was something like this:</p>
<pre><code>Connection con = null;
PreparedStatement prep = null;
try{
con = getConnection();
prep = prep.prepareStatement("Update ...");
...
con.commit();
}
catch (SQLException e){
con.rollback();
throw e;
}
finally{
if (prep != null)
prep.close();
if (con != null)
con.close();
}
</code></pre>
<p>With Java 7 you can go for:</p>
<pre><code>try(Connection con = getConnection(); PreparedStatement prep = con.prepareConnection("Update ..."){
...
con.commit();
}
</code></pre>
<p>This will close the <code>Connection</code> and the <code>PreparedStatement</code>, but what about the rollback? I cannot add a catch clause containing the rollback, because the connection is only available within the try block.</p>
<p>Do you still define the connection outside of the try block? What is the best practice here, especially if connection pooling is used?</p> | 9,260,565 | 3 | 3 | null | 2012-02-13 12:01:31.783 UTC | 17 | 2019-12-17 12:39:01.297 UTC | 2015-07-31 00:18:15.413 UTC | null | 642,706 | null | 1,070,957 | null | 1 | 37 | java|jdbc|java-7|try-with-resources | 18,986 | <pre><code>try(Connection con = getConnection()) {
try (PreparedStatement prep = con.prepareConnection("Update ...")) {
//prep.doSomething();
//...
//etc
con.commit();
} catch (SQLException e) {
//any other actions necessary on failure
con.rollback();
//consider a re-throw, throwing a wrapping exception, etc
}
}
</code></pre>
<p>According to the <a href="http://www.oracle.com/technetwork/articles/java/trywithresources-401775.html">oracle documentation</a>, you can combine a try-with-resources block with a regular try block. IMO, the above example captures the correct logic, which is:</p>
<ul>
<li>Attempt to close the PreparedStatement if nothing goes wrong</li>
<li>If something goes wrong in the inner block, (no matter what is is) roll back the current transaction</li>
<li>Attempt to close the connection no matter what</li>
<li>If something goes wrong closing the connection, you can't rollback the transaction (as that's a method on the connection, which is now in indeterminate state), so don't try</li>
</ul>
<p>In java 6 and earlier, I would do this with a triply nested set of try blocks (outer try-finally, middle try-catch, inner try-finally). ARM syntax does make this terser.</p> |
9,596,652 | How to escape apostrophe (') in MySql? | <p>The <a href="http://dev.mysql.com/doc/refman/5.0/en/string-literals.html#character-escape-sequences">MySQL documentation</a> says that it should be <code>\'</code>. However, both scite and mysql shows that <code>''</code> works. I saw that and it works. What should I do?</p> | 9,596,819 | 10 | 3 | null | 2012-03-07 06:09:41.213 UTC | 22 | 2021-02-03 16:37:15.113 UTC | 2012-03-07 06:11:03.313 UTC | null | 23,897 | null | 700,663 | null | 1 | 185 | mysql|escaping | 328,804 | <p>The MySQL documentation you cite actually says a little bit more than you mention. It also says, </p>
<blockquote>
<p>A “<code>'</code>” inside a string quoted with “<code>'</code>” may be written as “<code>''</code>”. </p>
</blockquote>
<p>(Also, you linked to the <a href="http://dev.mysql.com/doc/refman/5.0/en/string-literals.html#character-escape-sequences" rel="noreferrer">MySQL 5.0 version of Table 8.1. <em>Special Character Escape Sequences</em></a>, and the current version is 5.6 — but the current <a href="http://dev.mysql.com/doc/refman/5.6/en/string-literals.html#character-escape-sequences" rel="noreferrer">Table 8.1. <em>Special Character Escape Sequences</em></a> looks pretty similar.)</p>
<p>I think the <a href="http://www.postgresql.org/docs/8.2/static/runtime-config-compatible.html#GUC-BACKSLASH-QUOTE" rel="noreferrer">Postgres note on the <code>backslash_quote (string)</code> parameter</a> is informative:</p>
<blockquote>
<p>This controls whether a quote mark can be represented by <code>\'</code> in a string literal. The preferred, SQL-standard way to represent a quote mark is by doubling it (<code>''</code>) but PostgreSQL has historically also accepted <code>\'</code>. However, use of <code>\'</code> creates security risks...</p>
</blockquote>
<p>That says to me that using a doubled single-quote character is a better overall and long-term choice than using a backslash to escape the single-quote.</p>
<p>Now if you also want to add choice of language, choice of SQL database and its non-standard quirks, and choice of query framework to the equation, then you might end up with a different choice. You don't give much information about your constraints.</p> |
18,371,351 | Python - Pymongo Insert and Update Documents | <p>Using PyMongo, I have a set of dict's in a list that I'd like to submit to my MongoDB. Some of the items in the list are new entries, and some are to update.</p>
<p>Example:</p>
<p><strong>On Server Database:</strong></p>
<pre><code>[{"_id" : 1, "foo" : "bar}]
</code></pre>
<p><strong>To send to database:</strong></p>
<pre><code>[{"_id" : 1, "foo" : "HELLO"}, {"_id" : 2, "Blah" : "Bloh"}]
</code></pre>
<p>I'm currently using the following to insert documents, but how would I do something like stated above? Any help is appreciated!</p>
<pre><code>collection.insert(myDict)
</code></pre> | 18,372,494 | 4 | 0 | null | 2013-08-22 03:48:45.967 UTC | 4 | 2020-01-31 03:05:02.1 UTC | null | null | null | null | 721,386 | null | 1 | 19 | python|mongodb|pymongo | 57,008 | <p>Use <a href="https://docs.mongodb.com/manual/reference/method/db.collection.update/#update-upsert" rel="noreferrer"><code>upsert</code></a> option:</p>
<pre><code>from pymongo import MongoClient
cl = MongoClient()
coll = cl["local"]["test2"]
data = [{"_id" : 1, "foo" : "HELLO"}, {"_id" : 2, "Blah" : "Bloh"}]
for d in data:
coll.update({'_id':d['_id']}, d, True)
</code></pre> |
18,693,639 | Change background color of edittext in android | <p>If I change the background color of my <code>EditText</code> using the below code, it looks like the box is shrunken and it doesn't maintain the ICS theme of a blue bottom border that exists for a default <code>EditText</code>.</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#99000000"
>
<EditText
android:id="@+id/id_nick_name"
android:layout_marginTop="80dip"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ffffff"
/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dip"
android:layout_marginLeft="20dip"
android:layout_marginRight="20dip"
android:orientation="horizontal"
android:layout_below="@+id/id_nick_name">
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="add"
android:layout_weight="1"
/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="cancel"
android:layout_weight="1"
/>
</LinearLayout>
</RelativeLayout>
</code></pre>
<p>Here is what it looks like:</p>
<p><img src="https://i.stack.imgur.com/G3YO0.png" alt="Image of EditText"></p> | 18,694,067 | 10 | 0 | null | 2013-09-09 07:47:08.323 UTC | 9 | 2019-08-23 23:37:14.56 UTC | 2014-12-22 17:18:30.603 UTC | null | 4,015,623 | null | 164,683 | null | 1 | 31 | android|android-layout|android-edittext | 139,096 | <p>What you should do is to create a 9 patch image for edittext and set that image as edit text background. You can create 9 patches using <a href="http://romannurik.github.io/AndroidAssetStudio/nine-patches.html" rel="nofollow noreferrer">this</a> website</p>
<p>I am attaching a sample 9 patch image for your reference.Use it as edittext background and you will get an idea.Right click the image and select "save image as". When you save the image dont forget to give its extension as "9.png"</p>
<p><img src="https://i.stack.imgur.com/JCpQB.png" alt="enter image description here"></p> |
15,027,280 | Prevent submit button with onclick event from submitting | <p>I want to prevent a submit button with onclick event from submitting:</p>
<pre><code>$j('form#userForm .button').click(function(e) {
if ($j("#zip_field").val() > 1000){
$j('form#userForm .button').attr('onclick','').unbind('click');
alert('Sorry we leveren alleen inomstreken hijen!');
e.preventDefault();
return false;
}
});
</code></pre>
<p>This is the submit button:</p>
<pre><code><button class="button vm-button-correct" type="submit"
onclick="javascript:return myValidator(userForm, 'savecartuser');">Opslaan</button>
</code></pre>
<p>It will show the "alert" function and also removes the onclick event, but the form is submitted anyway. Manually remove the onclick event before submitting will solve the problem. However this is core functionality of and I dont want to remove it.</p>
<p><strong>EDIT:</strong></p>
<p>It's definitely caused by the onclick selector.. How can I force my jQuery script to instantly reload the onclick event? adding before jquery code: <code>$j('form#userForm .button').attr('onclick','');</code> will solve issue.. however my validation won't work an anymore...</p> | 15,027,290 | 5 | 1 | null | 2013-02-22 15:16:10.243 UTC | 2 | 2017-09-12 20:35:49.037 UTC | 2017-09-12 20:35:49.037 UTC | null | 3,995,261 | user1054080 | null | null | 1 | 19 | jquery|submit|preventdefault | 83,204 | <p>You'll need to add the event as a parameter:</p>
<pre><code>$j('form#userForm .button').click(function(event) { // <- goes here !
if ( parseInt($j("#zip_field").val(), 10) > 1000){
event.preventDefault();
$j('form#userForm .button').attr('onclick','').unbind('click');
alert('Sorry we leveren alleen inomstreken hijen!');
}
});
</code></pre>
<p>Also, <code>val()</code> always returns a string, so a good practice would be to convert it to a number before you compare it to a number, and I'm not sure if you're really targeting all <code>.button</code> elements inside <code>#userForm</code> inside the function, or if you should use <code>this</code> instead?</p>
<p>If you're using jQuery 1.7+, you should really consider using <code>on()</code> and <code>off()</code> for this.</p> |
15,203,534 | Convert.ToDateTime: how to set format | <p>I use convert like:</p>
<pre><code>Convert.ToDateTime(value)
</code></pre>
<p>but i need convert date to format like "mm/yy".<br>
I'm looking for something like this:</p>
<pre><code>var format = "mm/yy";
Convert.ToDateTime(value, format)
</code></pre> | 15,203,567 | 5 | 1 | null | 2013-03-04 14:13:45.217 UTC | 1 | 2019-01-21 12:41:22.67 UTC | 2013-03-04 14:15:59.487 UTC | null | 15,541 | null | 1,916,002 | null | 1 | 20 | c#|.net|datetime | 160,084 | <p>You should probably use either <a href="http://msdn.microsoft.com/en-us/library/7ee1y0t7.aspx"><code>DateTime.ParseExact</code></a> or <a href="http://msdn.microsoft.com/en-us/library/system.datetime.tryparseexact.aspx"><code>DateTime.TryParseExact</code></a> instead. They allow you to specify specific formats. I personally prefer the <code>Try</code>-versions since I think they produce nicer code for the error cases.</p> |
15,018,372 | How to take partial screenshot with Selenium WebDriver in python? | <p>I have searched a lot for this but couldn't find a solution. Here's <a href="https://stackoverflow.com/questions/10848900/how-to-take-partial-screenshot-frame-with-selenium-webdriver">a similar question</a> with a possible solution in java.</p>
<p>Is there a similar solution in Python?</p> | 15,870,708 | 8 | 0 | null | 2013-02-22 06:41:47.24 UTC | 50 | 2021-02-27 19:16:19.797 UTC | 2017-05-23 10:31:02.473 UTC | null | -1 | null | 2,098,273 | null | 1 | 86 | python|selenium | 79,898 | <p>Other than Selenium, this example also requires the PIL Imaging library. Sometimes this is put in as one of the standard libraries and sometimes it's not, but if you don't have it you can install it with <code>pip install Pillow</code></p>
<pre><code>from selenium import webdriver
from PIL import Image
from io import BytesIO
fox = webdriver.Firefox()
fox.get('http://stackoverflow.com/')
# now that we have the preliminary stuff out of the way time to get that image :D
element = fox.find_element_by_id('hlogo') # find part of the page you want image of
location = element.location
size = element.size
png = fox.get_screenshot_as_png() # saves screenshot of entire page
fox.quit()
im = Image.open(BytesIO(png)) # uses PIL library to open image in memory
left = location['x']
top = location['y']
right = location['x'] + size['width']
bottom = location['y'] + size['height']
im = im.crop((left, top, right, bottom)) # defines crop points
im.save('screenshot.png') # saves new cropped image
</code></pre>
<p>and finally the output is... the Stackoverflow logo!!!</p>
<p><img src="https://i.stack.imgur.com/L85Z2.png" alt="enter image description here"></p>
<p>Now of course this would be overkill for just grabbing a static image but if your want to grab something that requires Javascript to get to this could be a viable solution.</p> |
38,168,973 | How to programmatically get the list of registered users in Firebase | <p>I am working on an android app based on <a href="https://firebase.google.com/" rel="noreferrer">Firebase</a> and I am creating registration using authentication of users with their email addresses and passwords with method <code>signInWithEmailAndPassword</code>, I am able register multiple users and also able to see user on Firebase console. But, I want to get the list of all the registered users on Firebase Auth. I can get the current user using <code>FirebaseAuth.getInstance().getCurrentUser()</code>. But, I want to list all the registered users. So, is there anyway I can get the list of registered users?</p> | 38,170,753 | 1 | 4 | null | 2016-07-03 10:24:23.213 UTC | 4 | 2016-12-27 08:25:17.753 UTC | 2016-12-27 08:25:17.753 UTC | null | 2,058,547 | null | 726,863 | null | 1 | 23 | android|firebase|firebase-authentication | 45,748 | <p>You can't</p>
<p>The explanation is here <a href="https://stackoverflow.com/questions/14673708/how-do-i-return-a-list-of-users-if-i-use-the-firebase-simple-username-password">How do I return a list of users if I use the Firebase simple username & password authentication</a></p>
<p>You can instead set the user's uid to <code>users</code> node in your database, I use that node to store other user's information. then you can get the number of childs under that node.</p> |
28,306,288 | RemovedInDjango18Warning: Creating a ModelForm without either the 'fields' attribute or the 'exclude' attribute is deprecated | <p>I am doing a Django project and when I tried to access 127.0.0.1:8000/articles/create, I got the following error in my Ubuntu terminal: </p>
<pre><code>/home/(my name)/django_test/article/forms.py:4: RemovedInDjango18Warning: Creating a ModelForm without either the 'fields' attribute or the 'exclude' attribute is deprecated - form ArticleForm needs updating
class ArticleForm(forms.ModelForm):
</code></pre>
<p>In addition, I also got the following error when visiting my actual localhost site: </p>
<pre><code>ValueError at /articles/create/
The view article.views.create didn't return an HttpResponse object. It returned None instead.
</code></pre>
<p>Here is my forms.py file: </p>
<pre><code>from django import forms
from models import Article
class ArticleForm(forms.ModelForm):
class Meta:
model = Article
</code></pre>
<p>And here is my views.py file: </p>
<pre><code>from django.shortcuts import render_to_response
from article.models import Article
from django.http import HttpResponse
from forms import ArticleForm
from django.http import HttpResponseRedirect
from django.core.context_processors import csrf
#import pdb; pdb.set_trace()
# Create your views here.
def articles(request):
language = 'en-us'
session_language = 'en-us'
if 'lang' in request.COOKIES:
language = request.COOKIES['lang']
if 'lang' in request.session:
session_language = request.session['lang']
return render_to_response('articles.html',
{'articles':
Article.objects.all(), 'language' : language,
'session_language' : session_language})
def article(request, article_id=1):
return render_to_response('article.html', {'article':
Article.objects.get(id=article_id) })
def language(request, language='en-us'):
response = HttpResponse("setting language to %s" %
language)
response.set_cookie('lang', language)
response.session['lang'] = language
return response
def create(request):
if request.POST:
form = ArticleForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/articles/all')
else:
form = ArticleForm()
args = {}
args.update(csrf(request))
args['form'] = form
return render_to_response('create_article.html', args)
</code></pre>
<p>I'm not sure how to fix this problem. I looked at the Django documentation but I couldn't find a solution to my problem so any help would be appreciated.</p> | 28,306,347 | 4 | 4 | null | 2015-02-03 18:36:42.253 UTC | 18 | 2015-04-04 22:19:20.643 UTC | 2015-02-03 18:48:36.927 UTC | null | 3,849,798 | null | 3,849,798 | null | 1 | 40 | python|django | 54,022 | <p>For your form, it's a warning, not an error, telling you that in django 1.8, you will need to change your form to </p>
<pre><code>from django import forms
from models import Article
class ArticleForm(forms.ModelForm):
class Meta:
model = Article
fields = '__all__' # Or a list of the fields that you want to include in your form
</code></pre>
<p>Or add an <code>exclude</code> to list fields to exclude instead</p>
<p>Which wasn't required up till 1.8</p>
<p><a href="https://docs.djangoproject.com/en/1.8/topics/forms/modelforms/#selecting-the-fields-to-use">https://docs.djangoproject.com/en/1.8/topics/forms/modelforms/#selecting-the-fields-to-use</a></p>
<p>As for the error with your views, your return is inside of an <code>if</code> statement: <code>if request.POST:</code> so when it receives a get request, nothing is returned.</p>
<pre><code>def create(request):
if request.POST:
form = ArticleForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/articles/all')
else:
form = ArticleForm()
args = {}
args.update(csrf(request))
args['form'] = form
return render_to_response('create_article.html', args)
</code></pre>
<p>Just dedent the <code>else</code> block so that it's applying to the correct <code>if</code> statement.</p> |
7,729,905 | What is local/remote and no-interface view in EJB? | <p>I am trying to understand what the purpose and why we need the different client views in EJB. Could someone try to explain? </p> | 7,729,969 | 2 | 0 | null | 2011-10-11 17:18:16.077 UTC | 39 | 2017-06-20 10:55:34.193 UTC | 2013-09-24 09:05:40.287 UTC | null | 2,390,083 | null | 454,049 | null | 1 | 84 | java|jakarta-ee|ejb | 44,799 | <p><strong>Remote client view</strong></p>
<p>When your EJB and its clients will be in a distributed environment - meaning EJBs and clients will reside on separate Java virtual machines. Example : EJBs hosted on a WebSphere Application Server and Servlets that consume EJB APIs hosted on a Tomcat server.</p>
<p><strong>Local client view</strong></p>
<p>Only when it is guaranteed that other enterprise beans or clients will only address the bean within a single JVM. Example, EJBs as well as the Servlets deployed on the same WebSphere server.</p>
<p><strong>No-Interface view</strong></p>
<p>Is almost same as local client view, but there are differences. Your bean class is not required to implement client view interfaces in this case. All public methods of the bean class are automatically exposed to the caller. no-interface view always acquires an EJB reference - just like local or remote views - either through injection or JNDI lookup; but, Java type of the EJB reference is the bean class type rather than the type of a local interface. This is a convenience introduced as part of Java EE6.</p>
<p><strong>Difference between local client view and no-interface view</strong> </p>
<p>In case of no-interface view, the client and the target bean must be packaged in the same application (EAR). In case of local view, client can be packaged in a separate application than the enterprise application. So, this gives more flexibility in terms of fine-graining your components.</p>
<p>You may use local client view vs no-interface view depending on your API usage scenario. It is very likely for no-interface view to receive flexible features in future specs.</p>
<p><strong>Reason</strong> </p>
<p>Historically or otherwise, a client wishing to use EJB services was supposed to "look up" the bean on the container ( with certain initial contexts ). That was because all invocations are made through a special EJB reference(proxy) provided by the container. This allows the container to provide all the additional bean services such as pooling, container-managed transactions etc. So, a client can not explicitly instantiate an EJB with <code>new</code> operator. The client view is provided via certain interfaces that the client would have access to. The proxy realization at server side is done based on these interfaces. Different client views are defined to suite different deployment scenarios as mentioned above.</p> |
9,371,658 | Convert DateTime to a specified Format | <p>I have this date format <code>yy/MM/dd HH:mm:ss</code> ex: <code>12/02/21 10:56:09</code>. The problem is, when i try to convert it to different format using this code:</p>
<pre><code>CDate("12/02/21 10:56:09").ToString("MMM. dd, yyyy HH:mm:ss")
</code></pre>
<p>It displays <code>Dec. 12, 2021 10:56:09</code>.</p>
<p>How can i correctly format it to: <code>Feb. 21, 2012 10:56:09</code>? This format is returned when i check balance inquiry fro my SMS based application.</p> | 9,371,683 | 5 | 6 | null | 2012-02-21 03:18:13.007 UTC | 5 | 2017-01-24 15:19:15.307 UTC | 2012-02-21 06:10:30.163 UTC | null | 787,016 | null | 491,243 | null | 1 | 20 | c#|.net|vb.net|datetime-format | 174,086 | <p>Use <a href="http://msdn.microsoft.com/en-us/library/w2sa9yss.aspx"><code>DateTime.ParseExact</code></a>, e.g.:</p>
<pre><code>DateTime.ParseExact("12/02/21 10:56:09", "yy/MM/dd HH:mm:ss",
CultureInfo.InvariantCulture
).ToString("MMM. dd, yyyy HH:mm:ss")
</code></pre> |
23,516,958 | ON DUPLICATE KEY + AUTO INCREMENT issue mysql | <p>I have table structure like this</p>
<p><img src="https://i.stack.imgur.com/jSr9u.png" alt="enter image description here"></p>
<p>when I insert row to the table I'm using this query:</p>
<p><code>INSERT INTO table_blah ( material_item, ... hidden ) VALUES ( data, ... data ) ON DUPLICATE KEY UPDATE id = id, material_item = data, ... hidden = data;</code></p>
<p>when I first insert data without triggering the <code>ON DUPLICATE KEY</code> the id increments fine:</p>
<p><img src="https://i.stack.imgur.com/v8NNN.png" alt="enter image description here"></p>
<p>but when the <code>ON DUPLICATE KEY</code> triggers and i <strong>INSERT A NEW ROW</strong> the id looks odd to me:</p>
<p><img src="https://i.stack.imgur.com/WrlCz.png" alt="enter image description here"></p>
<p>How can I keep the <code>auto increment</code>, increment properly even when it triggers <code>ON DUPLICATE KEY</code>?</p> | 23,517,191 | 10 | 8 | null | 2014-05-07 11:46:49.36 UTC | 8 | 2021-12-07 02:58:53.373 UTC | 2014-05-07 11:50:36.763 UTC | null | 2,202,702 | null | 2,761,390 | null | 1 | 40 | mysql | 54,340 | <p>This behavior <a href="https://dev.mysql.com/doc/refman/8.0/en/insert-on-duplicate.html" rel="noreferrer">is documented</a> (paragraph in parentheses):</p>
<blockquote>
<p>If you specify ON DUPLICATE KEY UPDATE, and a row is inserted that
would cause a duplicate value in a UNIQUE index or PRIMARY KEY, MySQL
performs an UPDATE of the old row. For example, if column a is
declared as UNIQUE and contains the value 1, the following two
statements have similar effect:</p>
<pre><code> INSERT INTO table (a,b,c) VALUES (1,2,3) ON DUPLICATE KEY UPDATE c=c+1;
UPDATE table SET c=c+1 WHERE a=1;
</code></pre>
<p>(The effects are not identical for
an InnoDB table where a is an auto-increment column. With an
auto-increment column, an INSERT statement increases the
auto-increment value but UPDATE does not.)</p>
</blockquote>
<p>Here is a simple explanation. MySQL attempts to do the insert first. This is when the id gets auto incremented. Once incremented, it stays. Then the duplicate is detected and the update happens. But the value gets missed.</p>
<p>You should not depend on <code>auto_increment</code> having no gaps. If that is a requirement, the overhead on the updates and inserts is much larger. Essentially, you need to put a lock on the entire table, and renumber everything that needs to be renumbered, typically using a trigger. A better solution is to calculate incremental values on output.</p> |
8,648,369 | How to change the time in apache server so it matches the computer's time (PHP)? | <p>In my particular case, both the server and the client are the same computer, I'm on localhost. When i echo out the date from the date() function, it displays a totally wrong value, a 11 hours earlier time. I also tried gmdate(), but it displays the date in AM not PM. Is there any way to change the apache server time, so everytime I get it in php, it displays the same as the time on my computer? </p>
<p>EDIT: Sorry for the late edit. I have already set the timezone in the php.ini but it still doesn't work. And I'm sure that my timezone is correct, since I got it from the manual and checked from phpinfo().</p> | 8,648,408 | 4 | 4 | null | 2011-12-27 19:18:08.847 UTC | 3 | 2019-07-04 15:49:38.61 UTC | 2011-12-27 19:40:32.587 UTC | null | 924,233 | null | 924,233 | null | 1 | 19 | php|apache | 105,266 | <p>I believe you are looking for: <code>date_default_timezone_set ( string $timezone_identifier )</code></p>
<p><a href="http://php.net/manual/en/function.date-default-timezone-set.php" rel="noreferrer">Link</a></p>
<p>You can also set this in your php.ini config.</p> |
8,395,269 | what do <form action="#"> and <form method="post" action="#"> do? | <p>I'm reading a book on html development (which I'm fairly new at) and despite the fact that the book just had its 1st publishing one month ago (Nov. 2011), the author is an experienced coder and maybe using <code>#</code> for the action in a form is old school? </p>
<p>Because I'm trying to get the gist of the sample code and I cannot find an explanation of <code>form action="#"</code> despite searching for</p>
<pre><code><form action="#">
</code></pre>
<p>on google, on SO, and in www.w3schools.com.</p>
<p>Anyone know what the <code>#</code> action means for forms?</p> | 8,395,283 | 4 | 5 | null | 2011-12-06 04:14:59.45 UTC | 35 | 2020-01-30 01:09:07.097 UTC | 2019-09-19 11:49:39.447 UTC | null | 1,587,329 | null | 1,082,520 | null | 1 | 77 | html | 264,887 | <p>Action normally specifies the file/page that the form is submitted to (using the method described in the method paramater (post, get etc.))</p>
<p>An action of <code>#</code> indicates that the form stays on the same page, simply suffixing the url with a <code>#</code>. Similar use occurs in anchors. <code><a href=#">Link</a></code> for example, will stay on the same page.</p>
<p>Thus, the form is submitted to the same page, which then processes the data etc.</p> |
5,508,033 | SPAN next to each other WITHOUT float | <p>How would you get three span's to sit side by side instead of going to the next line without using float in CSS? So I need all three of these to appear next to each other..or if there is another method without using float.
Thanks!</p>
<pre class="lang-html prettyprint-override"><code><span style="display:block; width:33%;">Test1</span>
<span style="display:block; width:33%;">Test2</span>
<span style="display:block; width:33%;">Test3</span>
</code></pre> | 5,508,047 | 4 | 3 | null | 2011-04-01 00:39:08.703 UTC | 1 | 2022-08-23 05:26:38.067 UTC | 2022-08-23 05:26:38.067 UTC | null | 872,328 | null | 676,028 | null | 1 | 15 | css|html | 40,715 | <p><code>display: inline-block;</code> or their natural (default) display of inline.. though you can give the inline-block a width and height</p> |
4,956,346 | How can I add remote repositories in Mercurial? | <p>I am working with Git repositories in the following way:</p>
<ul>
<li>I have the master repository and several remotes on the different production machines. </li>
<li>I am pushing the production code to the remotes and restart the services for the changes to take effect. </li>
</ul>
<p>I am about to switch from Git to Mercurial and I would like to know ahead how I can achieve something like that.</p> | 4,959,205 | 4 | 0 | null | 2011-02-10 11:13:14 UTC | 18 | 2022-02-12 13:34:47.377 UTC | 2018-10-09 19:58:59.467 UTC | null | 1,429,387 | null | 226,394 | null | 1 | 105 | mercurial|repository|hg-paths | 38,403 | <p>You add entries to the <code>[paths]</code> section of your local clone's <code>.hg/hgrc</code> file. Here's an example of a section that would go in the <code>.hg/hgrc</code> file:</p>
<pre><code>[paths]
remote1 = http://path/to/remote1
remote2 = http://path/to/remote2
</code></pre>
<p>You can then use commands like <code>hg push remote1</code> to send changesets to that repo. If you want that remote repo to update is working directory you'd need to put a <code>changegroup</code> hook in place at that remote location that does an update. That would look something like:</p>
<pre><code>[hooks]
changegroup = hg update 2>&1 > /dev/null && path/to/script/restart-server.sh
</code></pre>
<p>Not everyone is a big fan of having remote repos automatically update their working directories on push, and it's certainly not the default.</p> |
5,017,582 | PHP Looping Template Engine - From Scratch | <p>For a group project I am trying to create a template engine for PHP for the people less experienced with the language can use tags like {name} in their HTML and the PHP will replace that tag with a predefined variable from an array. As well as supporting loops.</p>
<p>This is well beyond the expectations of the project, but as I have experience with PHP I thought it would be a good challenge to keep me busy!</p>
<p>My main questions are, how do I do the loop part of the parser and is this the best way to implement such a system. Before you just recommend an existing template system, I would prefer to create it myself for experience and because everything in our project has to be our own.</p>
<p>At the moment the basic parsing is done with regex and preg_replace_callback, it checks if $data[name] exists and if it does replaces it.</p>
<p>I have tried to do the loop a variety of different ways but am not sure if I am on the correct track!</p>
<p>An example if the data the parsing engine was given is:</p>
<pre><code>Array
(
[title] => The Title
[subtitle] => Subtitle
[footer] => Foot
[people] => Array
(
[0] => Array
(
[name] => Steve
[surname] => Johnson
)
[1] => Array
(
[name] => James
[surname] => Johnson
)
[2] => Array
(
[name] => josh
[surname] => Smith
)
)
[page] => Home
)
</code></pre>
<p>And the page it was parsing was something like:</p>
<pre><code><html>
<title>{title}</title>
<body>
<h1>{subtitle}</h1>
{LOOP:people}
<b>{name}</b> {surname}<br />
{ENDLOOP:people}
<br /><br />
<i>{footer}</i>
</body>
</html>
</code></pre>
<p>It would produce something similar to:</p>
<pre><code><html>
<title>The Title</title>
<body>
<h1>Subtitle</h1>
<b>Steve</b> Johnson<br />
<b>James</b> Johnson<br />
<b>Josh</b> Smith<br />
<br /><br />
<i>Foot</i>
</body>
</html>
</code></pre>
<p>Your time is incredibly appreciated with this!</p>
<p>Many thanks,</p>
<p>P.s. I completely disagree that because I am looking to create something similar to what already exists for experience, my well formatted and easy to understand question gets down voted.</p>
<p>P.p.s It seems there is a massive spread of opinions for this topic, please don't down vote people because they have a different opinion to you. Everyone is entitled to their own!</p> | 5,018,400 | 6 | 0 | null | 2011-02-16 14:24:21.033 UTC | 11 | 2011-02-16 16:36:48.953 UTC | 2011-02-16 16:36:48.953 UTC | null | 193,376 | null | 193,376 | null | 1 | 16 | php|parsing|templates|nested-loops | 15,045 | <p>A simple approach is to convert the template into PHP and run it.</p>
<pre><code>$template = preg_replace('~\{(\w+)\}~', '<?php $this->showVariable(\'$1\'); ?>', $template);
$template = preg_replace('~\{LOOP:(\w+)\}~', '<?php foreach ($this->data[\'$1\'] as $ELEMENT): $this->wrap($ELEMENT); ?>', $template);
$template = preg_replace('~\{ENDLOOP:(\w+)\}~', '<?php $this->unwrap(); endforeach; ?>', $template);
</code></pre>
<p>For example, this converts the template tags to embedded PHP tags.</p>
<p>You'll see that I made references to <code>$this->showVariable()</code>, <code>$this->data</code>, <code>$this->wrap()</code> and <code>$this->unwrap()</code>. That's what I'm going to implement.</p>
<p>The <code>showVariable</code> function shows the variable's content. <code>wrap</code> and <code>unwrap</code> is called on each iteration to provide closure.</p>
<p>Here is my implementation:</p>
<pre><code>class TemplateEngine {
function showVariable($name) {
if (isset($this->data[$name])) {
echo $this->data[$name];
} else {
echo '{' . $name . '}';
}
}
function wrap($element) {
$this->stack[] = $this->data;
foreach ($element as $k => $v) {
$this->data[$k] = $v;
}
}
function unwrap() {
$this->data = array_pop($this->stack);
}
function run() {
ob_start ();
eval (func_get_arg(0));
return ob_get_clean();
}
function process($template, $data) {
$this->data = $data;
$this->stack = array();
$template = str_replace('<', '<?php echo \'<\'; ?>', $template);
$template = preg_replace('~\{(\w+)\}~', '<?php $this->showVariable(\'$1\'); ?>', $template);
$template = preg_replace('~\{LOOP:(\w+)\}~', '<?php foreach ($this->data[\'$1\'] as $ELEMENT): $this->wrap($ELEMENT); ?>', $template);
$template = preg_replace('~\{ENDLOOP:(\w+)\}~', '<?php $this->unwrap(); endforeach; ?>', $template);
$template = '?>' . $template;
return $this->run($template);
}
}
</code></pre>
<p>In <code>wrap()</code> and <code>unwrap()</code> function, I use a stack to keep track of current state of variables. Precisely, <code>wrap($ELEMENT)</code> saves the current data to the stack, and then add the variables inside <code>$ELEMENT</code> into current data, and <code>unwrap()</code> restores the data from the stack back.</p>
<p>For extra security, I added this extra bit to replace <code><</code> with PHP echos:</p>
<pre><code>$template = str_replace('<', '<?php echo \'<\'; ?>', $template);
</code></pre>
<p>Basically to prevent any kind of injecting PHP codes directly, either <code><?</code>, <code><%</code>, or <code><script language="php"></code>.</p>
<p>Usage is something like this:</p>
<pre><code>$engine = new TemplateEngine();
echo $engine->process($template, $data);
</code></pre>
<p>This isn't the best method, but it is one way it could be done.</p> |
5,329,472 | Conversion between absolute and relative paths in Delphi | <p>Are there standard functions to perform absolute <--> relative path conversion in Delphi?</p>
<p>For example:</p>
<ul>
<li>'Base' path is <code>'C:\Projects\Project1\'</code></li>
<li>Relative path is <code>'..\Shared\somefile.pas'</code></li>
<li>Absolute path is <code>'C:\Projects\Shared\somefile.pas'</code></li>
</ul>
<p>I am looking for something like this:</p>
<pre><code>function AbsToRel(const AbsPath, BasePath: string): string;
// '..\Shared\somefile.pas' =
// AbsToRel('C:\Projects\Shared\somefile.pas', 'C:\Projects\Project1\')
function RelToAbs(const RelPath, BasePath: string): string;
// 'C:\Projects\Shared\somefile.pas' =
// RelToAbs('..\Shared\somefile.pas', 'C:\Projects\Project1\')
</code></pre> | 5,329,520 | 10 | 2 | null | 2011-03-16 17:47:08.05 UTC | 14 | 2022-05-01 09:28:54.647 UTC | 2011-12-11 00:18:55.957 UTC | null | 988,445 | null | 246,408 | null | 1 | 39 | delphi|path | 20,913 | <p>I would use <a href="http://msdn.microsoft.com/en-us/library/bb773740(VS.85).aspx" rel="noreferrer"><code>PathRelativePathTo</code></a> as the first function and <a href="http://msdn.microsoft.com/en-us/library/bb773569(VS.85).aspx" rel="noreferrer"><code>PathCanonicalize</code></a> as the second. In the latter case, as argument you pass the string sum of the base path and the relative path.</p>
<pre><code>function PathRelativePathTo(pszPath: PChar; pszFrom: PChar; dwAttrFrom: DWORD;
pszTo: PChar; dwAtrTo: DWORD): LongBool; stdcall; external 'shlwapi.dll' name 'PathRelativePathToW';
function AbsToRel(const AbsPath, BasePath: string): string;
var
Path: array[0..MAX_PATH-1] of char;
begin
PathRelativePathTo(@Path[0], PChar(BasePath), FILE_ATTRIBUTE_DIRECTORY, PChar(AbsPath), 0);
result := Path;
end;
function PathCanonicalize(lpszDst: PChar; lpszSrc: PChar): LongBool; stdcall;
external 'shlwapi.dll' name 'PathCanonicalizeW';
function RelToAbs(const RelPath, BasePath: string): string;
var
Dst: array[0..MAX_PATH-1] of char;
begin
PathCanonicalize(@Dst[0], PChar(IncludeTrailingBackslash(BasePath) + RelPath));
result := Dst;
end;
procedure TForm4.FormCreate(Sender: TObject);
begin
ShowMessage(AbsToRel('C:\Users\Andreas Rejbrand\Desktop\file.txt', 'C:\Users\Andreas Rejbrand\Pictures'));
ShowMessage(RelToAbs('..\Videos\movie.wma', 'C:\Users\Andreas Rejbrand\Desktop'));
end;
</code></pre>
<p>Of course, if you use a non-Unicode version of Delphi (that is, <= Delphi 2007), you need to use the Ansi functions (<code>*A</code>) instead of the Unicode functions (<code>*W</code>).</p> |
29,347,790 | Difference between IOError and OSError? | <p>I am always getting confused on whether a function would raise an IOError or OSError (or both?). What is the principle rule behind these exception types, what is the difference between them and when is which raised?</p>
<p>I've initially thought OSError is for things like permission denial, but opening a file without permissions will raise an IOError.</p> | 29,347,946 | 2 | 6 | null | 2015-03-30 13:42:14.41 UTC | 7 | 2020-09-13 20:58:36.56 UTC | 2015-03-30 13:44:23.87 UTC | null | 791,713 | null | 791,713 | null | 1 | 46 | python|exception|python-2.x | 40,903 | <p>There is very little difference between the two types. In fact, even the core Python developers agreed that there is no real difference and removed <code>IOError</code> in Python 3 (it is now an alias for <code>OSError</code>). See <a href="https://www.python.org/dev/peps/pep-3151/#confusing-set-of-os-related-exceptions" rel="noreferrer">PEP 3151 - Reworking the OS and IO exception hierarchy</a>:</p>
<blockquote>
<p>While some of these distinctions can be explained by implementation considerations, they are often not very logical at a higher level. The line separating <code>OSError</code> and <code>IOError</code>, for example, is often blurry. Consider the following:</p>
<pre><code>>>> os.remove("fff")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OSError: [Errno 2] No such file or directory: 'fff'
>>> open("fff")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: [Errno 2] No such file or directory: 'fff'
</code></pre>
</blockquote>
<p>Yes, that's two different exception types with the <em>exact same error message</em>.</p>
<p>For your own code, stick to throwing <code>OSError</code>. For existing functions, check the documentation (it should detail what you need to catch), but you can safely catch both:</p>
<pre><code>try:
# ...
except (IOError, OSError):
# handle error
</code></pre>
<p>Quoting the PEP again:</p>
<blockquote>
<p>In fact, it is hard to think of any situation where <code>OSError</code> should be caught but not <code>IOError</code>, or the reverse.</p>
</blockquote> |
41,577,597 | sequelize "findbyid" is not a function but apparently "findAll" is | <p>I am getting a very strange problem with sequelize, When I try to call the function findAll it works fine (same for create and destroy), but when I try to call function "findById", it throws "findById is not a function" (same for "FindOne").</p>
<pre><code>//works fine
var gammes = models.gamme.findAll().then(function(gammes) {
res.render('admin/gammes/gestion_gamme',{
layout: 'admin/layouts/structure' ,
gammes : gammes,
js: "gammes"
});
});
// throws models.gamme.findById is not a function
models.gamme.findById(req.params.id).then(function(gamme) {
gamme.update({
nom: req.body.nom
}).then(function () {
res.redirect("/gammes");
})
});
</code></pre>
<p>Gamme.js model</p>
<pre><code>module.exports = function (sequelize, DataTypes) {
"use strict";
var gamme = sequelize.define('gamme', {
id_gamme: {
type: DataTypes.INTEGER.UNSIGNED,
autoIncrement: true,
primaryKey: true
},
nom: {
type: DataTypes.STRING,
allowNull: false
}
}, {
classMethods: {},
timestamps: false
});
return gamme;
};
</code></pre> | 53,252,755 | 3 | 3 | null | 2017-01-10 20:16:54.373 UTC | 4 | 2020-07-10 06:40:44.59 UTC | null | null | null | null | 5,085,426 | null | 1 | 53 | node.js|orm|sequelize.js | 29,200 | <p>With Sequelize v5, findById() was replaced by findByPk(). Replace findById using findByPk and everything should work fine. You can find query doc <a href="https://sequelize.org/master/manual/model-querying-finders.html" rel="noreferrer">here</a></p> |
12,382,771 | mysql pivot/crosstab query | <p><strong>Question 1:</strong> I have a table with the below structure and data:</p>
<pre><code>app_id transaction_id mobile_no node_id customer_attribute entered_value
100 111 9999999999 1 Q1 2
100 111 9999999999 2 Q2 1
100 111 9999999999 3 Q3 4
100 111 9999999999 4 Q4 3
100 111 9999999999 5 Q5 2
100 222 8888888888 4 Q4 1
100 222 8888888888 3 Q3 2
100 222 8888888888 2 Q2 1
100 222 8888888888 1 Q1 3
100 222 8888888888 5 Q5 4
</code></pre>
<p>I want to display these records in the below format:</p>
<pre><code>app_id | transaction_id | mobile | Q1 | Q2 | Q3 | Q4 | Q5 |
100 | 111 | 9999999999 | 2 | 1 | 4 | 3 | 2 |
100 | 222 | 8888888888 | 3 | 1 | 2 | 1 | 4 |
</code></pre>
<p>I know I need to use crosstab/pivot query to get this display. For this I tried it based on the limited knowledge that I have about it. Following is my query:</p>
<pre><code>SELECT app_id, transaction_id, mobile_no,
(CASE node_id WHEN 1 THEN entered_value ELSE '' END) AS user_input1,
(CASE node_id WHEN 2 THEN entered_value ELSE '' END) AS user_input2,
(CASE node_id WHEN 3 THEN entered_value ELSE '' END) AS user_input3,
(CASE node_id WHEN 4 THEN entered_value ELSE '' END) AS user_input4,
(CASE node_id WHEN 5 THEN entered_value ELSE '' END) AS user_input5
FROM trn_user_log
GROUP BY app_id, transaction_id, mobile_no, node_id
</code></pre>
<p>And based on this query I got the below display:</p>
<pre><code>app_id transaction_id mobile_no user_input1 user_input2 user_input3 user_input4 user_input5
100 111 9999999999 2
100 111 9999999999 1
100 111 9999999999 4
100 111 9999999999 3
100 111 9999999999 2
100 222 8888888888 3
100 222 8888888888 1
100 222 8888888888 2
100 222 8888888888 1
100 222 8888888888 4
</code></pre>
<p>Can anyone help me with the proper changes that I need to make to my query to get the records in one single row and not multiple rows as above.</p>
<p><strong>Question 2:</strong> Also is there a way to get the value of a particular field as the NAME of the column. As you can see above I have <code>user_input1</code>, <code>user_input2</code>,... as the header. Instead of that I want to have the values in <code>customer_attribute</code> as the header of the columns. </p>
<p>For this I checked <code>NAME_CONST(name,value)</code> as below:</p>
<pre><code>SELECT app_id, transaction_id, mobile_no,
NAME_CONST(customer_attribute, (CASE node_id WHEN 1 THEN entered_value ELSE '' END))
FROM trn_user_log
</code></pre>
<p>But it gives an error </p>
<pre><code>Error Code : 1210 Incorrect arguments to NAME_CONST
</code></pre>
<p>Help required.</p> | 12,386,127 | 3 | 0 | null | 2012-09-12 07:02:39.013 UTC | 9 | 2017-03-06 16:23:23.903 UTC | 2013-05-03 11:28:12.643 UTC | null | 573,261 | null | 1,586,706 | null | 1 | 13 | mysql|sql|pivot | 28,048 | <p>While @John's static answer works great, if you have an unknown number of columns that you want to transform, I would consider using prepared statements to get the results:</p>
<pre><code>SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'GROUP_CONCAT((CASE node_id when ',
node_id,
' then entered_value else NULL END)) AS user_input',
node_id
)
) INTO @sql
FROM trn_user_log;
SET @sql = CONCAT('SELECT app_id, transaction_id, mobile_no, ', @sql, '
FROM trn_user_log
GROUP BY app_id, transaction_id, mobile_no');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
</code></pre>
<p>see <a href="http://sqlfiddle.com/#!2/7cbde/29" rel="noreferrer">SQL Fiddle with Demo</a></p>
<p>As far as your second, please clarify what you are trying to do it is not clear.</p> |
12,177,801 | What's the difference in Qt between setVisible, setShown and show/hide | <p>Please excuse this potentially noobish question but when trying to hide a QWidget what is the difference between calling setVisible(False), setShown(False) and hide()?</p> | 12,178,039 | 2 | 1 | null | 2012-08-29 12:19:36.623 UTC | 4 | 2015-12-07 06:43:33.403 UTC | null | null | null | null | 779,135 | null | 1 | 31 | qt|pyqt|hide|show|visible | 28,252 | <p><code>show()</code> is just a convenience function for <code>setVisible(true)</code>.</p>
<p>Similarly <code>hide()</code> is equivalent to <code>setVisible(false)</code></p>
<p>Internally, the same code is used to render your view.</p>
<p>See <a href="http://doc.qt.io/archives/qt-4.7/qwidget.html#show">http://doc.qt.io/archives/qt-4.7/qwidget.html#show</a> as an example. According to it,</p>
<blockquote>
<p>void QWidget::show () [slot] Shows the widget and its child widgets.
This function is equivalent to setVisible(true).</p>
</blockquote>
<p>You'll find lots of such functions in Qt to just make things more <strong>intuitive</strong>, especially when it comes to widgets and views.</p> |
12,519,074 | scrape websites with infinite scrolling | <p>I have written many scrapers but I am not really sure how to handle infinite scrollers. These days most website etc, Facebook, Pinterest has infinite scrollers.</p> | 26,814,351 | 3 | 2 | null | 2012-09-20 18:56:22.697 UTC | 20 | 2019-09-17 11:06:39.673 UTC | null | null | null | null | 200,317 | null | 1 | 31 | python|screen-scraping|scraper | 30,056 | <p>You can use selenium to scrap the infinite scrolling website like twitter or facebook. </p>
<p>Step 1 : Install Selenium using pip </p>
<pre><code>pip install selenium
</code></pre>
<p>Step 2 : use the code below to automate infinite scroll and extract the source code</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import NoAlertPresentException
import sys
import unittest, time, re
class Sel(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
self.driver.implicitly_wait(30)
self.base_url = "https://twitter.com"
self.verificationErrors = []
self.accept_next_alert = True
def test_sel(self):
driver = self.driver
delay = 3
driver.get(self.base_url + "/search?q=stckoverflow&src=typd")
driver.find_element_by_link_text("All").click()
for i in range(1,100):
self.driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(4)
html_source = driver.page_source
data = html_source.encode('utf-8')
if __name__ == "__main__":
unittest.main()
</code></pre>
<p>Step 3 : Print the data if required.</p> |
12,393,231 | Break statement inside two while loops | <p>Let's say I have this:</p>
<pre class="lang-java prettyprint-override"><code>while (a) {
while (b) {
if (b == 10) {
break;
}
}
}
</code></pre>
<p><strong>Question:</strong> Will the break statement take me out of both loops or only from the inner one? Thank you.</p> | 12,393,289 | 11 | 1 | null | 2012-09-12 17:12:25.697 UTC | 7 | 2021-06-01 18:28:00.37 UTC | 2021-06-01 18:28:00.37 UTC | null | 8,976 | null | 778,076 | null | 1 | 31 | java|while-loop|break | 100,501 | <p>In your example break statement will take you out of while(b) loop </p>
<pre><code>while(a) {
while(b) {
if(b == 10) {
break;
}
}
// break will take you here.
}
</code></pre> |
12,179,633 | Make shopt change local to function | <p>I'm trying to write a bash function that uses <code>nocasematch</code> without changing the callers setting of the option. The function definition is:</p>
<pre><code>is_hello_world() {
shopt -s nocasematch
[[ "$1" =~ "hello world" ]]
}
</code></pre>
<p>Before I call it:</p>
<pre><code>$ shopt nocasematch
nocasematch off
</code></pre>
<p>Call it:</p>
<pre><code>$ is_hello_world 'hello world' && echo Yes
Yes
$ is_hello_world 'Hello World' && echo Yes
Yes
</code></pre>
<p>As expected, but now <code>nocasematch</code> of the caller has changed:</p>
<pre><code>$ shopt nocasematch
nocasematch on
</code></pre>
<p><strong>Is there any easy way to make the option change local to the function?</strong></p>
<p>I know I can check the return value of <code>shopt -q</code> but that still means the function should remember this and reset it before exit.</p> | 12,179,705 | 4 | 0 | null | 2012-08-29 13:56:17.483 UTC | 6 | 2021-02-07 23:40:39.927 UTC | 2018-10-25 05:16:11.867 UTC | null | 6,862,601 | null | 1,331,399 | null | 1 | 31 | bash|shopt | 4,558 | <p>The function body can be any compound command, not just a group command ( <code>{}</code> ). Use a sub-shell:</p>
<pre><code>is_hello_world() (
shopt -s nocasematch
[[ "$1" =~ "hello world" ]]
)
</code></pre> |
12,618,321 | What pool of characters do MD5 and SHA have? | <p>Does MD5 and SHA only contain alphanumeric characters? (i.e., from A to Z and 0 to 9, or do they exclude some characters?)</p> | 12,618,366 | 1 | 0 | null | 2012-09-27 09:34:16.5 UTC | 5 | 2015-05-04 11:15:53.42 UTC | null | null | null | null | 748,789 | null | 1 | 45 | hash|cryptography|md5|sha | 34,291 | <p>MD5 and SHA hashes in raw form are binary, however their common representation is a hex-encoded string, which contains characters <code>[a-fA-F0-9]</code>.</p>
<p>So if this is what you meant, then characters G-Z, g-z are "excluded".</p>
<p>Another, less common, representation is Base64 encoding [0-9a-zA-Z+/].</p> |
12,606,196 | What is the alternative to using the Deprecated Hamcrest method is()? | <p>I use the following code at the moment to assert on a <code>boolean</code> value, however the method <code>org.hamcrest.Matchers.is()</code> is deprecated.</p>
<pre><code>assertThat(someValue, is(false));
</code></pre>
<p>Is there a simple alternative syntax to test for boolean values without resorting to <code>assertTrue()</code> which gives you poor failure messages like "java.lang.AssertionError"</p>
<hr>
<p><strong>Edit</strong> after receiving comments/answers</p>
<p>My initial concerns were raised because Eclipse shows the following import statement as deprecated </p>
<p><img src="https://i.stack.imgur.com/2fvDL.png" alt="enter image description here"></p>
<p>On viewing the <a href="http://www.jarvana.com/jarvana/view/org/hamcrest/hamcrest-library/1.2.1/hamcrest-library-1.2.1-javadoc.jar!/org/hamcrest/Matchers.html" rel="noreferrer">Hamcrest API</a> docs there are 3 overloaded variations of the <code>is()</code> method, only one of which is deprecated.</p>
<p>Therefore, to clarify the comment from @mark and the answer from @matt, the use of <code>is()</code> that I have posted above is valid and not deprecated.</p> | 12,606,235 | 5 | 6 | null | 2012-09-26 16:23:19.783 UTC | 7 | 2022-03-06 23:14:17.637 UTC | 2012-09-27 08:01:18.147 UTC | null | 713,106 | null | 713,106 | null | 1 | 57 | java|unit-testing|hamcrest | 41,989 | <p>Have you tried <code>equalTo(T)</code>?</p>
<pre><code>assertThat(someValue, equalTo(false));
</code></pre>
<p>I don't see that <a href="http://hamcrest.org/JavaHamcrest/javadoc/1.3/org/hamcrest/Matchers.html#is%28T%29" rel="noreferrer"><code>is(T)</code></a> is deprecated - <a href="http://hamcrest.org/JavaHamcrest/javadoc/1.3/org/hamcrest/Matchers.html#is%28java.lang.Class%29" rel="noreferrer">is(Class) is deprecate</a>d however.</p> |
12,140,844 | java.lang.RuntimeException: WakeLock under-locked C2DM_LIB | <p>I have uploaded my application on google play but users have reported the following exception</p>
<p><strong>java.lang.RuntimeException: WakeLock under-locked C2DM_LIB</strong>. This exception occurs when I try to release the <code>WakeLock</code>. Can anyone tell what could be the problem.</p> | 12,142,013 | 4 | 0 | null | 2012-08-27 11:08:44.91 UTC | 10 | 2014-07-12 19:17:30.397 UTC | 2012-11-15 08:04:14.983 UTC | null | 810,368 | null | 944,457 | null | 1 | 63 | android|android-service|android-c2dm|google-cloud-messaging | 42,013 | <p>I have traced same exception in new GCM Library too. Actually old C2DM Android library have same error, same crash, and Google hasn't fixed it yet. As I can see by our statistics, about 0.1% of users experiencing this crash.</p>
<p>My investigations shows that problem is in incorrect releasing of network <code>WakeLock</code> in GCM library, when library tries to release <code>WakeLock</code> that holds nothing (internal lock counter becomes negative).</p>
<p>I was satisfied with simple solution - just catch this exception and do nothing, because we don't need to do any extra job then our wakelock hold nothing.</p>
<p>In order to do this you need to import GCM library sources in your project, rather than already compiled <code>.jar</code> file. You can find GCM library sources under "<em>$Android_SDK_Home$/extras/google/gcm/gcm-client/src</em>" folder (you need to download it first using Android SDK Manager).</p>
<p>Next open <code>GCMBaseIntentService</code> class, find line</p>
<pre><code>sWakeLock.release();
</code></pre>
<p>and surround it with try-catch.</p>
<p>It should look like this:</p>
<pre><code> synchronized (LOCK) {
// sanity check for null as this is a public method
if (sWakeLock != null) {
Log.v(TAG, "Releasing wakelock");
try {
sWakeLock.release();
} catch (Throwable th) {
// ignoring this exception, probably wakeLock was already released
}
} else {
// should never happen during normal workflow
Log.e(TAG, "Wakelock reference is null");
}
}
</code></pre>
<p><strong>UPDATE:</strong>
Alternativally, as suggested @fasti in <a href="https://stackoverflow.com/a/14949367/810368">his answer</a>, you can use <code>mWakeLock.isHeld()</code> method to check if wakelock actually holding this lock.</p> |
12,540,282 | Is Joda-Time DateTimeFormatter class thread safe? | <p>Is the <a href="http://www.joda.org/joda-time/">Joda-Time</a> <code>DateTimeFormatter</code> class <a href="https://en.wikipedia.org/wiki/Thread_safety">thread safe</a>? Once I get an instance from <code>DateTimeFormat.forPattern</code>, can its various parse methods be called by multiple threads? DateTimeFormatter's <a href="http://www.joda.org/joda-time/apidocs/org/joda/time/format/DateTimeFormatter.html">Javadocs</a> makes no mention of thread safety.</p> | 12,540,298 | 3 | 0 | null | 2012-09-22 02:49:11.5 UTC | 7 | 2017-08-15 13:44:57.223 UTC | 2014-02-28 21:58:28.11 UTC | null | 642,706 | null | 24,396 | null | 1 | 64 | java|thread-safety|jodatime|date-format | 26,200 | <p><a href="http://www.joda.org/joda-time/apidocs/org/joda/time/format/DateTimeFormat.html" rel="noreferrer">Yes, it is</a>:</p>
<blockquote>
<p>DateTimeFormat is thread-safe and immutable, and the <strong>formatters</strong> it
returns are as well.</p>
</blockquote>
<p>and so is the <a href="http://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html" rel="noreferrer">Java 8 version</a></p>
<blockquote>
<p><strong>Implementation Requirements:</strong> This class is immutable and thread-safe.</p>
</blockquote> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.