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
18,096,378
full screen div that fits browser size
<p>I have a html document with div and css like this:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;&lt;/title&gt; &lt;style text="text/javascript"&gt; body { padding:0px; margin:0px; } .full { background-color: yellowgreen; width: 100%; height: 100%; } .menu { height: 50px; width: 100%; background-color: black; position: fixed; } .behindMenu { height: 50px; width: 100%; } .logo {width: 100%; height: 150px;} .content {background-color: yellow;} &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="menu"&gt;Menu&lt;/div&gt; &lt;div class="behindMenu"&gt;&lt;/div&gt; &lt;div class="logo"&gt;Logo&lt;/div&gt; &lt;div class="full"&gt;Full div&lt;/div&gt; &lt;div class="content"&gt;The rest content&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Menu is fixed, behindMenu is the same size as Menu and it is behind menu. Then I have logo and div with class full. After the full is div with class content.</p> <p>When visit that page I want that div full will be (size) between logo and bottom od the browser size. So the full must have a height between logo and bottom of the browser size, even if I resize window. When scroll down then user will see The rest of content.</p> <p>Something like this: <a href="http://strobedigital.com/" rel="noreferrer">http://strobedigital.com/</a></p> <p>Here is fiddle: <a href="http://jsfiddle.net/2963C/" rel="noreferrer">http://jsfiddle.net/2963C/</a></p>
18,097,296
5
0
null
2013-08-07 06:43:02.48 UTC
4
2017-10-27 13:05:46.497 UTC
null
null
null
null
1,045,769
null
1
9
css|html
86,009
<p>HTML</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;&lt;/title&gt; &lt;style text="text/css"&gt; body { padding:0px; margin:0px; } .full { background-color: yellowgreen; width: 100%; height: 100%; } .menu { height: 50px; width: 100%; background-color: black; position: fixed; } .behindMenu { height: 50px; width: 100%; } .logo {width: 100%; height: 150px;} .content {background-color: yellow;} &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="wrapper"&gt; &lt;div class="menu"&gt;Menu&lt;/div&gt; &lt;div class="behindMenu"&gt;&lt;/div&gt; &lt;div class="logo"&gt;Logo&lt;/div&gt; &lt;div class="full"&gt;Full div&lt;/div&gt; &lt;div class="content"&gt;The rest content&lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>CSS</p> <pre><code>html,body{height:100%;} .wrapper{min-height:100%; position:relative} .full{position:absolute; top:0; left:0; width:100%; height:100%;} </code></pre>
6,902,030
making CSR certificates in Windows (7)
<p>Closely related to <a href="https://stackoverflow.com/questions/6468741/windows-7-how-to-generate-csr-when-iis-is-not-installed">How to generate CSR when IIS is not installed</a>. </p> <p>I also do not have this installed. I am developing a mobile application for iOS, and i am trying to obtain a provisioning file so i can test my app locally. In the process of acquiring this, i am asked for a <code>.csr</code> file, and it instructs me on how to build this on my Mac. Except i don't have a mac, i have a PC, and my company exclusively uses PCs. I need this certificate, without having access to a Mac. </p> <p>i have seen and used <a href="http://www.gogetssl.com/eng/support/online_csr_generator/" rel="noreferrer">this</a> CSR generator, but it gives me the key and request in long strings of characters, and i need a <code>.csr</code> file to upload to Apple. </p> <p>Pasting it in notepad and changing the extension to .csr didn't work either :/</p> <p>Does anyone have any insights on this?</p>
10,275,712
3
6
null
2011-08-01 17:21:47.86 UTC
12
2020-09-12 07:20:18.65 UTC
2017-05-23 12:32:24.913 UTC
null
-1
null
704,131
null
1
19
ios|windows-7|ssl|csr|provisioning-profile
19,354
<p>You can install <a href="https://wiki.openssl.org/index.php/Binaries" rel="noreferrer">OpenSSL for windows</a> and generate CSR file with this command:</p> <pre><code>openssl req -nodes -newkey rsa:2048 -keyout private_key.key -out cer_sign_request.csr </code></pre> <p>You'll be asked for a few questions which are optional (press ENTER).</p> <p>This will generate a private key (such in keychain access) and a certification signing request as csr file.</p>
23,835,810
How to add X number of spaces to a string
<p>Probably an easy question that I couldn't quite find answer to before...</p> <p>I'm formatting a table (in text) to look like this:</p> <pre><code>Timestamp: Word Number </code></pre> <p>The number of characters between the : after timestamp and the beginning of Number is to be 20, including those in the Word (so it stays aligned). Using python I've done this:</p> <pre><code> offset = 20 - len(word) printer = timestamp + ' ' + word for i in range(0, offset): printer += ' ' printer += score </code></pre> <p>Which works, but python throws an error at me that i is never used ('cause it's not). While it's not a huge deal, I'm just wondering if there's a better way to do so.</p> <p>Edit:</p> <p>Since I can't add an answer to this (as it's marked duplicate) the better way to replace this whole thing is</p> <pre><code>printer = timestamp + ' ' + word.ljust(20) + score </code></pre>
23,835,830
3
2
null
2014-05-23 18:07:46.697 UTC
3
2016-03-11 15:46:29.87 UTC
2016-03-11 15:46:29.87 UTC
null
3,665,278
null
3,665,278
null
1
24
python|python-2.7
64,103
<p>You can multiply by strings by numbers to replicate them.</p> <pre><code> printer += ' ' * offset </code></pre>
15,486,246
XSD: default integer value range
<p>Is there an implied default value range when defining an element of a specific data type in an XSD file? For example if I define an element of type integer:</p> <pre><code>&lt;xs:element name="MyIntegerElement" type="xs:integer"/&gt; </code></pre> <p>Does this have an implied min and max value that it will validate to? I know I can explicitly define the valid ranges like so: </p> <pre><code>&lt;xs:element name="MyIntegerElement"&gt; &lt;xs:simpleType&gt; &lt;xs:restriction base="xs:integer"&gt; &lt;xs:minInclusive value="1"/&gt; &lt;xs:maxInclusive value="16"/&gt; &lt;/xs:restriction&gt; &lt;/xs:simpleType&gt; &lt;/xs:element&gt; </code></pre> <p>But if I don't do this when I validate an XML file against this will it default to a range of valid values? I've been digging around in the XSD documentation but haven't found the answer yet. </p>
15,486,673
1
0
null
2013-03-18 20:26:26.747 UTC
2
2013-03-18 20:50:13.17 UTC
2013-03-18 20:50:13.17 UTC
null
975,700
null
1,150,734
null
1
11
xml|xsd|xml-validation
39,622
<p>Well, it depends on the data type...</p> <p>If you look at the <a href="http://www.w3.org/TR/xmlschema-2/#integer">definition of <code>integer</code> at w3</a>:</p> <blockquote> <p>The value space of integer is the infinite set {...,-2,-1,0,1,2,...}</p> </blockquote> <p>In essence it means that, for integers, by default there is no min/max value range since any integer can be represented.</p> <p>On the other hand, <a href="http://www.w3.org/TR/xmlschema-2/#int">for an <code>int</code></a>:</p> <blockquote> <p>(...) maxInclusive to be 2147483647 and minInclusive to be -2147483648.</p> </blockquote> <p>The list goes on for <code>longs</code>, <code>shorts</code>, etc...</p> <p>You can read it in more detail here: <a href="http://www.w3.org/TR/xmlschema-2/#typesystem">http://www.w3.org/TR/xmlschema-2/#typesystem</a></p>
34,246,403
Performance of max() vs ORDER BY DESC + LIMIT 1
<p>I was troubleshooting a few slow SQL queries today and don't quite understand the performance difference below:</p> <p>When trying to extract the <code>max(timestamp)</code> from a data table based on some condition, using <code>MAX()</code> is slower than <code>ORDER BY timestamp LIMIT 1</code> if a matching row exists, but considerably faster if no matching row is found.</p> <pre><code>SELECT timestamp FROM data JOIN sensors ON ( sensors.id = data.sensor_id ) WHERE sensor.station_id = 4 ORDER BY timestamp DESC LIMIT 1; (0 rows) Time: 1314.544 ms SELECT timestamp FROM data JOIN sensors ON ( sensors.id = data.sensor_id ) WHERE sensor.station_id = 5 ORDER BY timestamp DESC LIMIT 1; (1 row) Time: 10.890 ms SELECT MAX(timestamp) FROM data JOIN sensors ON ( sensors.id = data.sensor_id ) WHERE sensor.station_id = 4; (0 rows) Time: 0.869 ms SELECT MAX(timestamp) FROM data JOIN sensors ON ( sensors.id = data.sensor_id ) WHERE sensor.station_id = 5; (1 row) Time: 84.087 ms </code></pre> <p>There are indexes on <code>(timestamp)</code> and <code>(sensor_id, timestamp)</code>, and I noticed that Postgres uses very different query plans and indexes for both cases:</p> <pre><code>QUERY PLAN (ORDER BY) -------------------------------------------------------------------------------------------------------- Limit (cost=0.43..9.47 rows=1 width=8) -&gt; Nested Loop (cost=0.43..396254.63 rows=43823 width=8) Join Filter: (data.sensor_id = sensors.id) -&gt; Index Scan using timestamp_ind on data (cost=0.43..254918.66 rows=4710976 width=12) -&gt; Materialize (cost=0.00..6.70 rows=2 width=4) -&gt; Seq Scan on sensors (cost=0.00..6.69 rows=2 width=4) Filter: (station_id = 4) (7 rows) QUERY PLAN (MAX) ---------------------------------------------------------------------------------------------------------- Aggregate (cost=3680.59..3680.60 rows=1 width=8) -&gt; Nested Loop (cost=0.43..3571.03 rows=43823 width=8) -&gt; Seq Scan on sensors (cost=0.00..6.69 rows=2 width=4) Filter: (station_id = 4) -&gt; Index Only Scan using sensor_ind_timestamp on data (cost=0.43..1389.59 rows=39258 width=12) Index Cond: (sensor_id = sensors.id) (6 rows) </code></pre> <p>So my two questions are:</p> <ol> <li>Where does this performance difference come from? I've seen the accepted answer here <a href="https://stackoverflow.com/questions/426731/min-max-vs-order-by-and-limit">MIN/MAX vs ORDER BY and LIMIT</a>, but that doesn't quite seem to apply here. Any good resources would be appreciated.</li> <li>Are there better ways to increase performance in all cases (matching row vs no matching row) than adding an <code>EXISTS</code> check?</li> </ol> <p><strong>EDIT</strong> to address the questions in the comments below. I kept the initial query plans above for future reference:</p> <p>Table definitions:</p> <pre><code> Table "public.sensors" Column | Type | Modifiers ----------------------+------------------------+----------------------------------------------------------------- id | integer | not null default nextval('sensors_id_seq'::regclass) station_id | integer | not null .... Indexes: "sensor_primary" PRIMARY KEY, btree (id) "ind_station_id" btree (station_id, id) "ind_station" btree (station_id) Table "public.data" Column | Type | Modifiers -----------+--------------------------+------------------------------------------------------------------ id | integer | not null default nextval('data_id_seq'::regclass) timestamp | timestamp with time zone | not null sensor_id | integer | not null avg | integer | Indexes: "timestamp_ind" btree ("timestamp" DESC) "sensor_ind" btree (sensor_id) "sensor_ind_timestamp" btree (sensor_id, "timestamp") "sensor_ind_timestamp_desc" btree (sensor_id, "timestamp" DESC) </code></pre> <p>Note that I added <code>ind_station_id</code> on <code>sensors</code> just now after @Erwin's suggestion below. Timings haven't really changed drastically, still <code>&gt;1200ms</code> in the <code>ORDER BY DESC + LIMIT 1</code> case and <code>~0.9ms</code> in the <code>MAX</code> case.</p> <p>Query Plans:</p> <pre><code>QUERY PLAN (ORDER BY) ---------------------------------------------------------------------------------------------------------- Limit (cost=0.58..9.62 rows=1 width=8) (actual time=2161.054..2161.054 rows=0 loops=1) Buffers: shared hit=3418066 read=47326 -&gt; Nested Loop (cost=0.58..396382.45 rows=43823 width=8) (actual time=2161.053..2161.053 rows=0 loops=1) Join Filter: (data.sensor_id = sensors.id) Buffers: shared hit=3418066 read=47326 -&gt; Index Scan using timestamp_ind on data (cost=0.43..255048.99 rows=4710976 width=12) (actual time=0.047..1410.715 rows=4710976 loops=1) Buffers: shared hit=3418065 read=47326 -&gt; Materialize (cost=0.14..4.19 rows=2 width=4) (actual time=0.000..0.000 rows=0 loops=4710976) Buffers: shared hit=1 -&gt; Index Only Scan using ind_station_id on sensors (cost=0.14..4.18 rows=2 width=4) (actual time=0.004..0.004 rows=0 loops=1) Index Cond: (station_id = 4) Heap Fetches: 0 Buffers: shared hit=1 Planning time: 0.478 ms Execution time: 2161.090 ms (15 rows) QUERY (MAX) ---------------------------------------------------------------------------------------------------------- Aggregate (cost=3678.08..3678.09 rows=1 width=8) (actual time=0.009..0.009 rows=1 loops=1) Buffers: shared hit=1 -&gt; Nested Loop (cost=0.58..3568.52 rows=43823 width=8) (actual time=0.006..0.006 rows=0 loops=1) Buffers: shared hit=1 -&gt; Index Only Scan using ind_station_id on sensors (cost=0.14..4.18 rows=2 width=4) (actual time=0.005..0.005 rows=0 loops=1) Index Cond: (station_id = 4) Heap Fetches: 0 Buffers: shared hit=1 -&gt; Index Only Scan using sensor_ind_timestamp on data (cost=0.43..1389.59 rows=39258 width=12) (never executed) Index Cond: (sensor_id = sensors.id) Heap Fetches: 0 Planning time: 0.435 ms Execution time: 0.048 ms (13 rows) </code></pre> <p>So just like in the earlier explains, <code>ORDER BY</code> does a <code>Scan using timestamp_in on data</code>, which is not done in the <code>MAX</code> case.</p> <p>Postgres version: Postgres from the Ubuntu repos: <code>PostgreSQL 9.4.5 on x86_64-unknown-linux-gnu, compiled by gcc (Ubuntu 5.2.1-21ubuntu2) 5.2.1 20151003, 64-bit</code></p> <p>Note that there are <code>NOT NULL</code> constraints in place, so <code>ORDER BY</code> won't have to sort over empty rows.</p> <p>Note also that I'm largely interested in where the difference comes from. While not ideal, I can retrieve data relatively quickly using <code>EXISTS (&lt;1ms)</code> and then <code>SELECT (~11ms)</code>.</p>
34,259,643
2
6
null
2015-12-12 23:54:55.567 UTC
11
2022-09-22 01:30:58.05 UTC
2017-05-23 10:34:05.533 UTC
null
-1
null
4,033,315
null
1
14
sql|postgresql|max|aggregate|sql-limit
18,888
<p>There does not seem to be an index on <code>sensor.station_id</code>, which is important here.</p> <p>There is an actual <strong>difference</strong> between <code>max()</code> and <code>ORDER BY DESC + LIMIT 1</code>. Many people seem to miss that. NULL values sort <em>first</em> in descending sort order. So <code>ORDER BY timestamp DESC LIMIT 1</code> returns a <code>NULL</code> value if one exists, while the aggregate function <code>max()</code> <em>ignores</em> <code>NULL</code> values and returns the latest not-null timestamp. <code>ORDER BY timestamp DESC NULLS LAST LIMIT 1</code> would be equivalent</p> <p>For your case, since your column <code>d.timestamp</code> is defined <code>NOT NULL</code> (as your update revealed), there is <em>no effective difference</em>. An index with <code>DESC NULLS LAST</code> and the same clause in the <code>ORDER BY</code> for the <code>LIMIT</code> query should still serve you best. I suggest these <strong>indexes</strong> (my query below builds on the 2nd one):</p> <pre>sensor(station_id, id) data(sensor_id, timestamp <b>DESC NULLS LAST</b>)</pre> <p>You can drop the other indexes <strike><code>sensor_ind_timestamp</code></strike> and <strike><code>sensor_ind_timestamp_desc</code></strike> unless they are in use otherwise (unlikely, but possible).</p> <p><strong>Much more importantly</strong>, there is another difficulty: The filter on the first table <code>sensors</code> returns few, but still (possibly) multiple rows. Postgres <em>expects</em> to find 2 rows (<code>rows=2</code>) in your added <code>EXPLAIN</code> output.<br /> The perfect technique would be an <em><strong>index-skip-scan</strong></em> (a.k.a. loose index scan) for the second table <code>data</code> - which is not currently implemented (up to at least Postgres 15). There are various workarounds. See:</p> <ul> <li><a href="https://stackoverflow.com/questions/25536422/optimize-group-by-query-to-retrieve-latest-record-per-user/25536748#25536748">Optimize GROUP BY query to retrieve latest row per user</a></li> </ul> <p>The best should be:</p> <pre class="lang-sql prettyprint-override"><code>SELECT d.timestamp FROM sensors s CROSS JOIN LATERAL ( SELECT timestamp FROM data WHERE sensor_id = s.id ORDER BY timestamp DESC NULLS LAST LIMIT 1 ) d WHERE s.station_id = 4 ORDER BY d.timestamp DESC NULLS LAST LIMIT 1; </code></pre> <p>The choice between <code>max()</code> and <code>ORDER BY</code> / <code>LIMIT</code> hardly matters in comparison. You might as well:</p> <pre class="lang-sql prettyprint-override"><code>SELECT max(d.timestamp) AS timestamp FROM sensors s CROSS JOIN LATERAL ( SELECT timestamp FROM data WHERE sensor_id = s.id ORDER BY timestamp DESC NULLS LAST LIMIT 1 ) d WHERE s.station_id = 4; </code></pre> <p>Or:</p> <pre class="lang-sql prettyprint-override"><code>SELECT max(d.timestamp) AS timestamp FROM sensors s CROSS JOIN LATERAL ( SELECT max(timestamp) AS timestamp FROM data WHERE sensor_id = s.id ) d WHERE s.station_id = 4; </code></pre> <p>Or even with a correlated subquery, <em>shortest</em> of all:</p> <pre class="lang-sql prettyprint-override"><code>SELECT max((SELECT max(timestamp) FROM data WHERE sensor_id = s.id)) AS timestamp FROM sensors s WHERE station_id = 4; </code></pre> <p>Note the double parentheses!</p> <p>The additional advantage of <code>LIMIT</code> in a <code>LATERAL</code> join is that you can retrieve arbitrary columns of the selected row, not just the latest timestamp (one column).</p> <p>Related:</p> <ul> <li><a href="https://stackoverflow.com/questions/20958679/why-do-null-values-come-first-when-ordering-desc-in-a-postgresql-query/20959470#20959470">Why do NULL values come first when ordering DESC in a PostgreSQL query?</a></li> <li><a href="https://stackoverflow.com/questions/28550679/what-is-the-difference-between-lateral-and-a-subquery-in-postgresql/28557803#28557803">What is the difference between a LATERAL JOIN and a subquery in PostgreSQL?</a></li> <li><a href="https://stackoverflow.com/questions/3800551/select-first-row-in-each-group-by-group/7630564#7630564">Select first row in each GROUP BY group?</a></li> <li><a href="https://stackoverflow.com/questions/24244026/optimize-groupwise-maximum-query/24377356#24377356">Optimize groupwise maximum query</a></li> </ul>
34,199,982
How to query all the GraphQL type fields without writing a long query?
<p>Assume you have a GraphQL type and it includes many fields. How to query all the fields without writing down a long query that includes the names of all the fields?</p> <p>For example, If I have these fields :</p> <pre><code> public function fields() { return [ 'id' =&gt; [ 'type' =&gt; Type::nonNull(Type::string()), 'description' =&gt; 'The id of the user' ], 'username' =&gt; [ 'type' =&gt; Type::string(), 'description' =&gt; 'The email of user' ], 'count' =&gt; [ 'type' =&gt; Type::int(), 'description' =&gt; 'login count for the user' ] ]; } </code></pre> <p>To query all the fields usually the query is something like this: </p> <pre><code>FetchUsers{users(id:"2"){id,username,count}} </code></pre> <p>But I want a way to have the same results without writing all the fields, something like this:</p> <pre><code>FetchUsers{users(id:"2"){*}} //or FetchUsers{users(id:"2")} </code></pre> <p>Is there a way to do this in GraphQL ??</p> <p>I'm using <em>Folkloreatelier/laravel-graphql</em> library.</p>
34,226,484
7
7
null
2015-12-10 10:50:43.647 UTC
46
2022-07-28 18:22:01.287 UTC
2017-11-07 16:24:15.57 UTC
null
617,950
null
1,334,945
null
1
294
php|laravel|graphql|graphql-php
227,270
<p>Unfortunately what you'd like to do is not possible. GraphQL requires you to be explicit about specifying which fields you would like returned from your query.</p>
27,574,805
Hiding views in RecyclerView
<p>I have code like this </p> <pre><code>public static class MyViewHolder extends RecyclerView.ViewHolder { @InjectView(R.id.text) TextView label; public MyViewHolder(View itemView) { super(itemView); ButterKnife.inject(this, itemView); } public void hide(boolean hide) { label.setVisibility(hide ? View.GONE : View.VISIBLE); } } </code></pre> <p>which maps to a single row in a <code>RecyclerView</code>. <code>R.id.text</code> is in fact the root view of the layout that gets inflated and passed in to the constructor here. </p> <p>I'm using the default implementation of <code>LinearLayoutManager</code>.</p> <p>In <code>bindViewHolder</code>, I call <code>hide(true)</code> on an instance of <code>MyViewHolder</code>, but instead of collapsing the row as expected, the row becomes invisible, maintaining its height and position in the <code>RecyclerView</code>. Has anyone else run into this issue? </p> <p>How do you hide items in a RecyclerView? </p>
27,586,376
6
3
null
2014-12-19 22:29:19.467 UTC
7
2017-02-27 22:57:55.423 UTC
null
null
null
null
1,476,372
null
1
43
android
60,175
<p>There is no built in way to hide a child in RV but of course if its height becomes 0, it won't be visible :). I assume your root layout does have some min height (or exact height) that makes it still take space even though it is GONE.</p> <p>Also, if you want to remove a view, remove it from the adapter, don't hide it. Is there a reason why you want to hide instead of remove ?</p>
780,349
Runtime optimization of static languages: JIT for C++?
<p>Is anyone using JIT tricks to improve the runtime performance of statically compiled languages such as C++? It seems like hotspot analysis and branch prediction based on observations made during runtime could improve the performance of any code, but maybe there's some fundamental strategic reason why making such observations and implementing changes during runtime are only possible in virtual machines. I distinctly recall overhearing C++ compiler writers mutter "you can do that for programs written in C++ too" while listening to dynamic language enthusiasts talk about collecting statistics and rearranging code, but my web searches for evidence to support this memory have come up dry. </p>
780,383
7
0
null
2009-04-23 04:42:50.217 UTC
14
2013-10-12 09:42:27.897 UTC
2009-08-12 18:29:47.3 UTC
null
13,295
null
29,403
null
1
21
c++|optimization|jit|performance
9,152
<p>Profile guided optimization is different than runtime optimization. The optimization is still done offline, based on profiling information, but once the binary is shipped there is no ongoing optimization, so if the usage patterns of the profile-guided optimization phase don't accurately reflect real-world usage then the results will be imperfect, and the program also won't adapt to different usage patterns.</p> <p>You may be interesting in looking for information on <a href="http://www.hpl.hp.com/techreports/1999/HPL-1999-78.html" rel="noreferrer">HP's Dynamo</a>, although that system focused on native binary -> native binary translation, although since C++ is almost exclusively compiled to native code I suppose that's exactly what you are looking for.</p> <p>You may also want to take a look at <a href="http://www.llvm.org" rel="noreferrer">LLVM</a>, which is a compiler framework and intermediate representation that supports JIT compilation and runtime optimization, although I'm not sure if there are actually any LLVM-based runtimes that can compile C++ and execute + runtime optimize it yet.</p>
758,256
PyQt4 Minimize to Tray
<p>Is there a way to minimize to tray in PyQt4? I've already worked with the QSystemTrayIcon class, but now I would like to minimize or "hide" my app window, and show only the tray icon.</p> <p>Has anybody done this? Any direction would be appreciated.</p> <p>Using Python 2.5.4 and PyQt4 on Window XP Pro</p>
758,352
7
0
null
2009-04-16 22:16:37.65 UTC
15
2020-05-13 09:37:38.86 UTC
null
null
null
null
91,873
null
1
23
python|pyqt4|system-tray|minimize
18,607
<p>It's pretty straightforward once you remember that there's no way to actually minimize to the <a href="https://web.archive.org/web/20070114154431/http://blogs.msdn.com/oldnewthing/archive/2003/09/10/54831.aspx" rel="nofollow noreferrer">system tray</a>. </p> <p>Instead, you fake it by doing this:</p> <ol> <li>Catch the minimize event on your window</li> <li>In the minimize event handler, create and show a QSystemTrayIcon</li> <li>Also in the minimize event handler, call hide() or setVisible(false) on your window</li> <li>Catch a click/double-click/menu item on your system tray icon</li> <li>In your system tray icon event handler, call show() or setVisible(true) on your window, and optionally hide your tray icon.</li> </ol>
615,625
TSQL Default Minimum DateTime
<p>Using Transact SQL is there a way to specify a default datetime on a column (in the create table statement) such that the datetime is the minimum possible value for datetime values?</p> <pre> create table atable ( atableID int IDENTITY(1, 1) PRIMARY KEY CLUSTERED, Modified datetime DEFAULT XXXXX?????? ) </pre> <p>Perhaps I should just leave it null.</p>
615,693
7
0
null
2009-03-05 16:48:11.32 UTC
2
2015-06-22 10:02:39.767 UTC
null
null
null
null
72,491
null
1
25
tsql
123,398
<p>As far as I am aware no function exists to return this, you will have to hard set it.</p> <p>Attempting to cast from values such as 0 to get a minimum date will default to 01-01-1900.</p> <p>As suggested previously best left set to NULL (and use ISNULL when reading if you need to), or if you are worried about setting it correctly you could even set a trigger on the table to set your modified date on edits.</p> <p>If you have your heart set on getting the minimum possible date then:</p> <pre> create table atable ( atableID int IDENTITY(1, 1) PRIMARY KEY CLUSTERED, Modified datetime DEFAULT '1753-01-01' ) </pre>
379,722
Is F# really better than C# for math?
<p>Unmanaged languages notwithstanding, is F# really better than C# for implementing math? And if that's the case, why?</p>
380,693
7
0
null
2008-12-18 23:39:07.84 UTC
6
2010-02-14 00:09:07.837 UTC
null
null
null
nesteruk
9,476
null
1
31
c#|math|f#
8,143
<p>I think most of the important points were already mentioned by someone else:</p> <ol> <li>F# lets you solve problems in a way mathematicians think about them</li> <li>Thanks to higher-order functions, you can use simpler concepts to solve difficult problems</li> <li>Everything is immutable by default, which makes the program easier to understand (and also easier to parallelize)</li> </ol> <p>It is definitely true that you can use some of the F# concepts in C# 3.0, but there are limitations. You cannot use any recursive computations (because C# doesn't have tail-recursion) and this is how you write primitive computations in functional/mathematical way. Also, writing complex higher order functions (that take other functions as arguments) in C# is difficult, because you have to write types explicitly (while in F#, types are inferred, but also automatically generalized, so you don't have to explicitly make a function generic).</p> <p>Also, I think the following point from Marc Gravell isn't a valid objection:</p> <blockquote> <p>From a maintenance angle, I'm of the view that suitably named properties etc are easier to use (over full life-cycle) than tuples and head/tail lists, but that might just be me.</p> </blockquote> <p>This is of course true. However, the great thing about F# is that you can start writing the program using tuples &amp; head/tail lists and later in the development process turn it into a program that uses .NET IEnumerables and types with properties (and that's how I believe typical F# programmer works*). Tuples etc. and F# interactive development tools give you a great way to quickly prototype solutions (and when doing something mathematical, this is essential because most of the development is just experimenting when you're looking for the best solution). Once you have the prototype, you can use simple source code transformations to wrap the code inisde an F# type (which can also be used from C# as an ordinary class). F# also gives you a lot of ways to optimize the code later in terms of performance.</p> <p>This gives you the benefits of easy to use langauges (e.g. Python), which many people use for prototyping phase. However, you don't have to rewrite the whole program later once you're done with prototyping using an efficient language (e.g. C++ or perhaps C#), because F# is both "easy to use" and "efficient" and you can fluently switch between these two styles.</p> <p>(*) I also use this style in my <a href="http://manning.com/petricek/" rel="noreferrer">functional programming book</a>.</p>
1,191,807
Facebook style JQuery autocomplete plugin
<p>Im after a plugin to do autocomplete like facebook does in that you can select multiple items - similar to how tagging a stackoverflow question works.</p> <p>Here are a couple I ran into:</p> <ul> <li><a href="http://wharsojo.wordpress.com/2008/02/18/jquery-facebook-autocomplete/" rel="noreferrer">http://wharsojo.wordpress.com/2008/02/18/jquery-facebook-autocomplete</a></li> <li><a href="http://www.emposha.com/javascript/fcbkcomplete.html" rel="noreferrer">http://www.emposha.com/javascript/fcbkcomplete.html</a></li> <li><a href="https://github.com/loopj/jquery-tokeninput" rel="noreferrer">https://github.com/loopj/jquery-tokeninput</a></li> </ul> <p>Have you tried any of these? Were they easy to implement and customize?</p>
1,192,028
7
3
null
2009-07-28 03:30:45.667 UTC
71
2016-09-22 20:29:10.597 UTC
2011-05-02 00:04:42.623 UTC
null
59,087
null
71,683
null
1
78
jquery|jquery-plugins|autocomplete
86,242
<p><a href="https://github.com/loopj/jquery-tokeninput" rel="noreferrer">https://github.com/loopj/jquery-tokeninput</a></p> <p>I just had a go at this one and it was really easy to implement using an asp.net page to output the JSON (from the search params) Then theres just a few lines of Javascript you need to create it (and the settings)</p> <pre><code>$(document).ready(function() { $("#Users").tokenInput("../Services/Job/UnassignedUsers.aspx?p=&lt;%= projectID %&gt;&amp;j=&lt;%= jobID %&gt;", { hintText: "Begin typing the user name of the person you wish to assign.", noResultsText: "No results", searchingText: "Searching..." }); }); </code></pre>
658,027
Logout with facebook
<p>How can I log a user out from my facebook connect website, without using the fb-login button? I would like to do it from codebehind (c#)?</p>
658,114
8
0
null
2009-03-18 12:19:00.523 UTC
2
2013-04-30 11:49:55.513 UTC
2013-04-30 11:49:55.513 UTC
null
79,465
Dofs
79,465
null
1
8
c#|.net|facebook
69,567
<p>I found out that there was only an option to do it from Javascript by <code>FB.logout()</code>. It seems kinda wird that there is no API from codebehind to do the same.</p>
4,622
SQL Case Expression Syntax?
<p>What is the <strong>complete</strong> and correct syntax for the SQL Case expression?</p>
4,626
8
1
null
2008-08-07 12:13:01.39 UTC
14
2021-06-13 20:18:21.767 UTC
2021-06-13 20:18:21.767 UTC
Mark Harrison
792,066
null
383
null
1
62
sql
161,939
<p>The <strong>complete</strong> syntax depends on the database engine you're working with:</p> <p>For SQL Server:</p> <pre><code>CASE case-expression WHEN when-expression-1 THEN value-1 [ WHEN when-expression-n THEN value-n ... ] [ ELSE else-value ] END </code></pre> <p>or:</p> <pre><code>CASE WHEN boolean-when-expression-1 THEN value-1 [ WHEN boolean-when-expression-n THEN value-n ... ] [ ELSE else-value ] END </code></pre> <p>expressions, etc:</p> <pre><code>case-expression - something that produces a value when-expression-x - something that is compared against the case-expression value-1 - the result of the CASE statement if: the when-expression == case-expression OR the boolean-when-expression == TRUE boolean-when-exp.. - something that produces a TRUE/FALSE answer </code></pre> <p>Link: <a href="http://msdn.microsoft.com/en-us/library/ms181765.aspx" rel="noreferrer">CASE (Transact-SQL)</a></p> <p>Also note that the ordering of the WHEN statements is important. You can easily write multiple WHEN clauses that overlap, and <strong>the first one that matches is used</strong>.</p> <p><strong>Note</strong>: If no ELSE clause is specified, and no matching WHEN-condition is found, the value of the CASE expression will be <em>NULL</em>.</p>
109,186
Bypass invalid SSL certificate errors when calling web services in .Net
<p>We are setting up a new SharePoint for which we don't have a valid SSL certificate yet. I would like to call the Lists web service on it to retrieve some meta data about the setup. However, when I try to do this, I get the exception:</p> <blockquote> <p>The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.</p> </blockquote> <p>The nested exception contains the error message:</p> <blockquote> <p>The remote certificate is invalid according to the validation procedure.</p> </blockquote> <p>This is correct since we are using a temporary certificate.</p> <p>My question is: how can I tell the .Net web service client (<em>SoapHttpClientProtocol</em>) to ignore these errors? </p>
109,340
8
0
null
2008-09-20 20:07:16.987 UTC
29
2017-02-12 13:06:59.047 UTC
null
null
null
jan.vdbergh
9,540
null
1
90
.net|web-services|sharepoint
145,909
<p>The approach I used when faced with this problem was to add the signer of the temporary certificate to the trusted authorities list on the computer in question.</p> <p>I normally do testing with certificates created with CACERT, and adding them to my trusted authorities list worked swimmingly.</p> <p>Doing it this way means you don't have to add any custom code to your application and it properly simulates what will happen when your application is deployed. As such, I think this is a superior solution to turning off the check programmatically. </p>
179,625
How to trim a string in SQL Server before 2017?
<p>In SQL Server 2017, you can use this syntax, but not in earlier versions:</p> <pre><code>SELECT Name = TRIM(Name) FROM dbo.Customer; </code></pre>
179,630
8
0
null
2008-10-07 17:54:18.483 UTC
14
2022-07-21 16:52:16.597 UTC
2022-02-19 09:41:13.7 UTC
Nigel Campbell
792,066
Eric Labashosky
6,522
null
1
157
sql|sql-server
353,664
<pre><code>SELECT LTRIM(RTRIM(Names)) AS Names FROM Customer </code></pre>
1,290,131
How to create an array of object literals in a loop?
<p>I need to create an array of object literals like this:</p> <pre><code>var myColumnDefs = [ {key:"label", sortable:true, resizeable:true}, {key:"notes", sortable:true,resizeable:true},...... </code></pre> <p>In a loop like this:</p> <pre><code>for (var i = 0; i &lt; oFullResponse.results.length; i++) { console.log(oFullResponse.results[i].label); } </code></pre> <p>The value of <code>key</code> should be <code>results[i].label</code> in each element of the array.</p>
1,290,138
9
0
null
2009-08-17 20:07:14.22 UTC
107
2021-11-28 13:33:45.433 UTC
2017-12-30 21:27:33.317 UTC
null
184,201
null
69,346
null
1
242
javascript|arrays|object-literal
651,491
<pre><code>var arr = []; var len = oFullResponse.results.length; for (var i = 0; i &lt; len; i++) { arr.push({ key: oFullResponse.results[i].label, sortable: true, resizeable: true }); } </code></pre>
116,090
How do I kill a process using Vb.NET or C#?
<p>I have a scenario where I have to check whether user has already opened Microsoft Word. If he has, then I have to kill the winword.exe process and continue to execute my code. </p> <p>Does any one have any straight-forward code for killing a process using vb.net or c#?</p>
116,098
10
0
null
2008-09-22 16:59:17.297 UTC
17
2021-08-28 13:31:51.56 UTC
2008-09-25 18:36:46.693 UTC
Mark Biek
305
MSONI
13,337
null
1
72
c#|vb.net|process|kill
172,735
<p>You'll want to use the <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.process.kill.aspx" rel="noreferrer">System.Diagnostics.Process.Kill</a> method. You can obtain the process you want using <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.process.getprocessesbyname.aspx" rel="noreferrer">System.Diagnostics.Proccess.GetProcessesByName</a>.</p> <p>Examples have already been posted here, but I found that the non-.exe version worked better, so something like:</p> <pre><code>foreach ( Process p in System.Diagnostics.Process.GetProcessesByName("winword") ) { try { p.Kill(); p.WaitForExit(); // possibly with a timeout } catch ( Win32Exception winException ) { // process was terminating or can't be terminated - deal with it } catch ( InvalidOperationException invalidException ) { // process has already exited - might be able to let this one go } } </code></pre> <p>You probably don't have to deal with <code>NotSupportedException</code>, which suggests that the process is remote.</p>
1,154,200
When restoring a backup, how do I disconnect all active connections?
<p>My SQL Server 2005 doesn't restore a backup because of active connections. How can I force it?</p>
1,154,209
10
1
null
2009-07-20 15:19:40.793 UTC
50
2020-01-11 14:10:56.78 UTC
2012-02-16 11:28:24.013 UTC
null
381,938
null
48,465
null
1
171
sql-server|sql-server-2005|backup|restore|disconnect
243,423
<h3>SQL Server Management Studio 2005</h3> <p>When you right click on a database and click <code>Tasks</code> and then click <code>Detach Database</code>, it brings up a dialog with the active connections.</p> <p><a href="https://i.stack.imgur.com/joVhh.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/joVhh.jpg" alt="Detach Screen" /></a></p> <p>By clicking on the hyperlink under &quot;Messages&quot; you can kill the active connections.</p> <p>You can then kill those connections without detaching the database.</p> <p>More information <a href="http://www.kodyaz.com/articles/kill-all-processes-of-a-database.aspx" rel="noreferrer">here</a>.</p> <h3>SQL Server Management Studio 2008</h3> <p>The interface has changed for SQL Server Management studio 2008, here are the steps (via: <a href="https://stackoverflow.com/questions/1154200/when-restoring-a-backup-how-do-i-disconnect-all-active-connections/1154209#comment12388892_1154209">Tim Leung</a>)</p> <ol> <li>Right-click the server in Object Explorer and select 'Activity Monitor'.</li> <li>When this opens, expand the Processes group.</li> <li>Now use the drop-down to filter the results by database name.</li> <li>Kill off the server connections by selecting the right-click 'Kill Process' option.</li> </ol>
75,704
How do I check to see if a value is an integer in MySQL?
<p>I see that within MySQL there are <code>Cast()</code> and <code>Convert()</code> functions to create integers from values, but is there any way to check to see if a value is an integer? Something like <code>is_int()</code> in PHP is what I am looking for.</p>
75,880
11
1
null
2008-09-16 18:56:53.83 UTC
34
2019-01-17 13:32:32.883 UTC
2014-04-16 06:28:39.087 UTC
null
2,021,046
Craig Nakamoto
8,224
null
1
140
mysql
173,617
<p>I'll assume you want to check a string value. One nice way is the REGEXP operator, matching the string to a regular expression. Simply do</p> <pre><code>select field from table where field REGEXP '^-?[0-9]+$'; </code></pre> <p>this is reasonably fast. If your field is numeric, just test for</p> <pre><code>ceil(field) = field </code></pre> <p>instead.</p>
432,385
SFTP in Python? (platform independent)
<p>I'm working on a simple tool that transfers files to a hard-coded location with the password also hard-coded. I'm a python novice, but thanks to ftplib, it was easy:</p> <pre><code>import ftplib info= ('someuser', 'password') #hard-coded def putfile(file, site, dir, user=(), verbose=True): """ upload a file by ftp to a site/directory login hard-coded, binary transfer """ if verbose: print 'Uploading', file local = open(file, 'rb') remote = ftplib.FTP(site) remote.login(*user) remote.cwd(dir) remote.storbinary('STOR ' + file, local, 1024) remote.quit() local.close() if verbose: print 'Upload done.' if __name__ == '__main__': site = 'somewhere.com' #hard-coded dir = './uploads/' #hard-coded import sys, getpass putfile(sys.argv[1], site, dir, user=info) </code></pre> <p>The problem is that I can't find any library that supports sFTP. What's the normal way to do something like this securely? </p> <p>Edit: Thanks to the answers here, I've gotten it working with Paramiko and this was the syntax.</p> <pre><code>import paramiko host = "THEHOST.com" #hard-coded port = 22 transport = paramiko.Transport((host, port)) password = "THEPASSWORD" #hard-coded username = "THEUSERNAME" #hard-coded transport.connect(username = username, password = password) sftp = paramiko.SFTPClient.from_transport(transport) import sys path = './THETARGETDIRECTORY/' + sys.argv[1] #hard-coded localpath = sys.argv[1] sftp.put(localpath, path) sftp.close() transport.close() print 'Upload done.' </code></pre> <p>Thanks again!</p>
432,403
11
4
null
2009-01-11 04:48:19.177 UTC
67
2022-04-13 21:19:30.48 UTC
2009-01-11 15:42:52.413 UTC
Mark Wilbur
1,464,733
Mark Wilbur
1,464,733
null
1
214
python|sftp
262,672
<p><a href="https://www.paramiko.org/" rel="noreferrer">Paramiko</a> supports SFTP. I've used it, and I've used Twisted. Both have their place, but you might find it easier to start with Paramiko.</p>
218,155
How do I change JPanel inside a JFrame on the fly?
<p>To put it simple, there's a simple java swing app that consists of JFrame with some components in it. One of the components is a JPanel that is meant to be replaced by another JPanel on user action.</p> <p>So, what's the correct way of doing such a thing? I've tried</p> <pre><code>panel = new CustomJPanelWithComponentsOnIt(); parentFrameJPanelBelongsTo.pack(); </code></pre> <p>but this won't work. What would you suggest?</p>
218,540
14
0
null
2008-10-20 11:53:41.517 UTC
14
2021-06-30 15:37:15.823 UTC
2014-02-26 06:17:12.61 UTC
John Topley
418,556
gsmd
15,187
null
1
46
java|swing|jpanel|layout-manager|cardlayout
160,872
<p>Your use case, seems perfect for <a href="http://java.sun.com/docs/books/tutorial/uiswing/layout/card.html" rel="noreferrer">CardLayout</a>.</p> <p>In card layout you can add multiple panels in the same place, but then show or hide, one panel at a time.</p>
670,488
How to manage Long Paths in Bash?
<p>I have a problem to manage long paths. How can I get quickly to paths like </p> <pre><code>/Users/User/.../.../.../.../.../Dev/C/card.c </code></pre> <p>I tried an alias</p> <pre><code>alias cd C='cd /Users/User/.../.../.../.../.../Dev/C' </code></pre> <p>but I am unable to do aliases for two separate words. I have long lists of Bash aliases and paths in CDPATH, so I am hesitating to make them more. How can manage long paths?</p> <p><strong>[Ideas for Replies]</strong></p> <p>The user litb's reply revealed some of my problems in the management. Things, such as "CTRL+R", "!-3:1:2:4:x" and "incremental search", are hard for me. They probably help in navigating long directories and, in the sense, management.</p>
670,493
17
0
2009-03-26 18:51:29.757 UTC
2009-03-22 03:02:54.95 UTC
13
2018-03-29 14:04:47.507 UTC
2009-03-25 21:03:20.447 UTC
UnixBasics
54,964
UnixBasics
54,964
null
1
9
bash|path
9,036
<p>Consider using symbolic links. I have a <code>~/work/</code> directory where I place symlinks to all my current projects.</p> <p>You may also use shell variables:</p> <pre><code>c='/Users/User/.../.../.../.../.../Dev/C' </code></pre> <p>Then:</p> <pre><code>cd "$c" </code></pre>
73,515
How to tell if .NET code is being run by Visual Studio designer
<p>I am getting some errors thrown in my code when I open a Windows Forms form in Visual Studio's designer. I would like to branch in my code and perform a different initialization if the form is being opened by designer than if it is being run for real. </p> <p>How can I determine at run-time if the code is being executed as part of designer opening the form?</p>
73,583
25
0
null
2008-09-16 15:23:21.597 UTC
17
2022-07-15 17:09:22.57 UTC
2012-08-18 22:34:58.627 UTC
null
63,550
Zvi
12,717
null
1
60
visual-studio|gui-designer
45,140
<p>To find out if you're in "design mode":</p> <ul> <li>Windows Forms components (and controls) have a <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.component.designmode.aspx" rel="noreferrer">DesignMode</a> property.</li> <li>Windows Presentation Foundation controls should use the <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.designerproperties.isindesignmode.aspx" rel="noreferrer">IsInDesignMode</a> attached property.</li> </ul>
990,221
Multiple lines of text in UILabel
<p>Is there a way to have multiple lines of text in <code>UILabel</code> like in the <code>UITextView</code> or should I use the second one instead?</p>
990,244
26
2
null
2009-06-13 07:28:38.743 UTC
99
2021-10-20 01:18:06.077 UTC
2017-10-06 10:37:20.797 UTC
user577537
5,638,630
null
77,449
null
1
471
ios|uilabel|uitextview|line-breaks|multiline
398,635
<p>Set the line break mode to word-wrapping and the number of lines to <code>0</code>:</p> <pre><code>// Swift textLabel.lineBreakMode = .byWordWrapping textLabel.numberOfLines = 0 // Objective-C textLabel.lineBreakMode = NSLineBreakByWordWrapping; textLabel.numberOfLines = 0; // C# (Xamarin.iOS) textLabel.LineBreakMode = UILineBreakMode.WordWrap; textLabel.Lines = 0; </code></pre> <p>Restored old answer (for reference and devs willing to support iOS below 6.0):</p> <pre><code>textLabel.lineBreakMode = UILineBreakModeWordWrap; textLabel.numberOfLines = 0; </code></pre> <p>On the side: both enum values yield to <code>0</code> anyway.</p>
6,625,148
How can I append a variable text to last line of file via command line?
<p>could you please tell me how I (a Linux-User) can add text to the last line of a text-file?</p> <p>I have this so far:</p> <pre><code>APPEND='Some/Path which is/variable' sed '${s/$/$APPEND/}' test.txt </code></pre> <p>It works, but $APPEND is added insted of the content of the variable. I know the reason for this is the singe quote (') I used for sed. But when I simply replace ' by ", no text gets added to the file.</p> <p>Do you know a solution for this? I don't insist on using <code>sed</code>, it's only the first command line tool that came in my mind. You may use every standard command line program you like.</p> <p>edit: I've just tried this:</p> <pre><code>$ sed '${s/$/'"$APPEND/}" test.txt sed: -e Ausdruck #1, Zeichen 11: Unbekannte Option für `s' </code></pre>
6,625,980
5
0
null
2011-07-08 13:30:04.727 UTC
1
2015-07-14 11:11:28.483 UTC
null
null
null
null
562,769
null
1
13
bash|sed
46,640
<pre><code>echo "$(cat $FILE)$APPEND" &gt; $FILE </code></pre> <p>This was what I needed.</p>
6,341,906
Read custom configuration file in C# (Framework 4.0)
<p>I am developing an application in C# under Framework 4.0.</p> <p>In my application I would like to create separate configuration file that is not the app.config file. The configuration file contains custom configuration sections we developed for the product.</p> <p>I don't want to reference this file from the app.config using the configSource. </p> <p>I want to load it at runtime and read it's content.</p> <p>An example to what I mean is the log4net that allow you to write the configuration in the log4net.config file.</p> <p>Can anyone help how to do that without writing code that mimcs the code that exists in the framework ?</p> <p><strong>UPDATE:</strong></p> <p>based on the answer from <strong>Kaido</strong> I wrote utility class that reads custom configuration file and has the ability to refresh the Config content when the file on the file system changes.</p> <p>The usage in this class is as follows:</p> <ol> <li><p>Get the configuration file content</p> <pre><code>// Create configuration reader that reads the files once var configFileReader = new CustomConfigurationFileReader("c:\\myconfig.config"); var config = configFileReader.Config; // Do any action you want with the config object like: config.GetSection("my.custom.section"); // or, var someVal = config.AppSettings.Settings["someKey"]; </code></pre></li> <li><p>Get notifications when the configuration file changes</p> <pre><code>// Create configuration reader that notifies when the configuraiton file changes var configFileReader = new CustomConfigurationFileReader("c:\\myconfig.config", true); // Register to the FileChanged event configFileReader.FileChanged += MyEventHandler; ... private void MyEventHanler(object sender, EventArgs e) { // You can safely access the Config property here, it is already contains the new content } </code></pre></li> </ol> <p>In the code I used PostSharp in order to validate the constructor input parameter to verify that the log file is not null and that the file exists. You can change the code to make those validation inline in the code (although I recomend to use PostSharp to seperate the application to aspects).</p> <p>Here is the code:</p> <pre><code> using System; using System.Configuration; using System.IO; using CSG.Core.Validation; namespace CSG.Core.Configuration { /// &lt;summary&gt; /// Reads customer configuration file /// &lt;/summary&gt; public class CustomConfigurationFileReader { // By default, don't notify on file change private const bool DEFAULT_NOTIFY_BEHAVIOUR = false; #region Fields // The configuration file name private readonly string _configFileName; /// &lt;summary&gt; /// Raises when the configuraiton file is modified /// &lt;/summary&gt; public event System.EventHandler FileChanged; #endregion Fields #region Constructor /// &lt;summary&gt; /// Initialize a new instance of the CustomConfigurationFileReader class that notifies /// when the configuration file changes. /// &lt;/summary&gt; /// &lt;param name="configFileName"&gt;The full path to the custom configuration file&lt;/param&gt; public CustomConfigurationFileReader(string configFileName) : this(configFileName, DEFAULT_NOTIFY_BEHAVIOUR) { } /// &lt;summary&gt; /// Initialize a new instance of the CustomConfigurationFileReader class /// &lt;/summary&gt; /// &lt;param name="configFileName"&gt;The full path to the custom configuration file&lt;/param&gt; /// &lt;param name="notifyOnFileChange"&gt;Indicate if to raise the FileChange event when the configuraiton file changes&lt;/param&gt; [ValidateParameters] public CustomConfigurationFileReader([NotNull, FileExists]string configFileName, bool notifyOnFileChange) { // Set the configuration file name _configFileName = configFileName; // Read the configuration File ReadConfiguration(); // Start watch the configuration file (if notifyOnFileChanged is true) if(notifyOnFileChange) WatchConfigFile(); } #endregion Constructor /// &lt;summary&gt; /// Get the configuration that represents the content of the configuration file /// &lt;/summary&gt; public System.Configuration.Configuration Config { get; set; } #region Helper Methods /// &lt;summary&gt; /// Watch the configuraiton file for changes /// &lt;/summary&gt; private void WatchConfigFile() { var watcher = new FileSystemWatcher(_configFileName); watcher.Changed += ConfigFileChangedEvent; } /// &lt;summary&gt; /// Read the configuration file /// &lt;/summary&gt; public void ReadConfiguration() { // Create config file map to point to the configuration file var configFileMap = new ExeConfigurationFileMap { ExeConfigFilename = _configFileName }; // Create configuration object that contains the content of the custom configuration file Config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None); } /// &lt;summary&gt; /// Called when the configuration file changed. /// &lt;/summary&gt; /// &lt;param name="sender"&gt;&lt;/param&gt; /// &lt;param name="e"&gt;&lt;/param&gt; private void ConfigFileChangedEvent(object sender, FileSystemEventArgs e) { // Check if the file changed event has listeners if (FileChanged != null) // Raise the event FileChanged(this, new EventArgs()); } #endregion Helper Methods } } </code></pre>
6,342,179
5
0
null
2011-06-14 10:00:45.373 UTC
10
2017-07-18 17:46:39.707 UTC
2017-07-18 17:46:39.707 UTC
null
2,840,103
null
738,162
null
1
37
c#|configuration|configuration-files
70,489
<pre><code> // Map the roaming configuration file. This // enables the application to access // the configuration file using the // System.Configuration.Configuration class ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap(); configFileMap.ExeConfigFilename = roamingConfig.FilePath; // Get the mapped configuration file. Configuration config = ConfigurationManager.OpenMappedExeConfiguration( configFileMap, ConfigurationUserLevel.None); </code></pre> <p>from <a href="http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.aspx</a></p>
6,602,036
QVector vs QList
<p>I have a list of integers that I need to iterate over but an array is inadequate. What are the differences between <code>vectors</code> and <code>lists</code> and is there anything I need to know before I pick a type?</p> <p>Just to be clear, I've read the QT docs but this is the extent of what I know:</p> <blockquote> <p><code>QList&lt;T&gt;</code>, <code>QLinkedList&lt;T&gt;</code>, and <code>QVector&lt;T&gt;</code> provide similar functionality. Here's an overview:</p> <ul> <li>For most purposes, <code>QList</code> is the right class to use. Its index-based API is more convenient than <code>QLinkedList's</code> iterator-based API, and it is usually faster than <code>QVector</code> because of the way it stores its items in memory. It also expands to less code in your executable.</li> <li>If you need a real linked list, with guarantees of constant time insertions in the middle of the list and iterators to items rather than indexes, use <code>QLinkedList</code>.</li> <li>If you want the items to occupy adjacent memory positions, use <code>QVector</code>.</li> </ul> </blockquote>
6,602,370
5
0
null
2011-07-06 19:47:04.49 UTC
24
2019-02-22 22:34:34.777 UTC
2019-02-22 22:34:34.777 UTC
null
8,464,442
null
123,415
null
1
82
c++|qt|list|vector
58,243
<p><code>QVector</code> is mostly analogous to <code>std::vector</code>, as you might guess from the name. <code>QList</code> is closer to <code>boost::ptr_deque</code>, despite the apparent association with <code>std::list</code>. It does not store objects directly, but instead stores pointers to them. You gain all the benefits of quick insertions at both ends, and reallocations involve shuffling pointers instead of copy constructors, but lose the spacial locality of an actual <code>std::deque</code> or <code>std::vector</code>, and gain a lot of heap allocations. It does have some decision making to avoid the heap allocations for small objects, regaining the spacial locality, but from what I understand it only applies to things smaller than an <code>int</code>.</p> <p><code>QLinkedList</code> is analogous to <code>std::list</code>, and has all the downsides of it. Generally speaking, this should be your last choice of a container.</p> <p>The QT library heavily favors the use of <code>QList</code> objects, so favoring them in your own code can sometimes avoid some unneccessary tedium. The extra heap use and the random positioning of the actual data can theoretically hurt in some circumstances, but oftentimes is unnoticable. So I would suggest using <code>QList</code> until profiling suggests changing to a <code>QVector</code>. If you expect contiguous allocation to be important [read: you are interfacing with code that expects a <code>T[]</code> instead of a <code>QList&lt;T&gt;</code>] that can also be a reason to start off with <code>QVector</code> right off the bat.</p> <hr> <p>If you are asking about containers in general, and just used the QT documents as a reference, then the above information is less useful.</p> <p>An <code>std::vector</code> is an array that you can resize. All the elements are stored next to each other, and you can access individual elements quickly. The downside is that insertions are only efficient at one end. If you put something in the middle, or at the beginning, you have to copy the other objects to make room. In big-oh notation, insertion at the end is O(1), insertion anywhere else is O(N), and random access is O(1).</p> <p>An <code>std::deque</code> is similar, but does not guarentee objects are stored next to each other, and allows insertion at both ends to be O(1). It also requires smaller chunks of memory to be allocated at a time, which can sometimes be important. Random access is O(1) and insertion in the middle is O(N), same as for a <code>vector</code>. Spacial locality is worse than <code>std::vector</code>, but objects tend to be clustered so you gain some benefits.</p> <p>An <code>std::list</code> is a linked list. It requires the most memory overhead of the three standard sequential containers, but offers fast insertion anywhere... provided you know in advance where you need to insert. It does not offer random access to individual elements, so you have to iterate in O(N). But once there, the actual insertion is O(1). The biggest benefit to <code>std::list</code> is that you can splice them together quickly... if you move an entire range of values to a different <code>std::list</code>, the entire operation is O(1). It is also much harder to invalidate references into the list, which can sometimes be important.</p> <p>As a general rule, I prefer <code>std::deque</code> to <code>std::vector</code>, unless I need to be able to pass the data to a library that expects a raw array. <code>std::vector</code> is guaranteed contiguous, so <code>&amp;v[0]</code> works for this purpose. I don't remember the last time I used a <code>std::list</code>, but it was almost certainly because I needed the stronger guaretee about references remaining valid. </p>
6,451,866
Why use functors over functions?
<p>Compare</p> <pre><code>double average = CalculateAverage(values.begin(), values.end()); </code></pre> <p>with</p> <pre><code>double average = std::for_each(values.begin(), values.end(), CalculateAverage()); </code></pre> <p>What are the benefits of using a functor over a function? Isn't the first a lot easier to read (even before the implementation is added)?</p> <p>Assume the functor is defined like this:</p> <pre><code>class CalculateAverage { private: std::size_t num; double sum; public: CalculateAverage() : num (0) , sum (0) { } void operator () (double elem) { num++; sum += elem; } operator double() const { return sum / num; } }; </code></pre>
6,451,911
7
6
null
2011-06-23 09:21:22.74 UTC
33
2019-07-03 14:35:53.783 UTC
2011-06-23 14:50:09.587 UTC
null
141,985
null
141,985
null
1
61
c++|stl|functor
31,953
<p>At least four good reasons:</p> <p><strong>Separation of concerns</strong></p> <p>In your particular example, the functor-based approach has the advantage of separating the iteration logic from the average-calculation logic. So you can use your functor in other situations (think about all the other algorithms in the STL), and you can use other functors with <code>for_each</code>.</p> <p><strong>Parameterisation</strong></p> <p>You can parameterise a functor more easily. So for instance, you could have a <code>CalculateAverageOfPowers</code> functor that takes the average of the squares, or cubes, etc. of your data, which would be written thus:</p> <pre><code>class CalculateAverageOfPowers { public: CalculateAverageOfPowers(float p) : acc(0), n(0), p(p) {} void operator() (float x) { acc += pow(x, p); n++; } float getAverage() const { return acc / n; } private: float acc; int n; float p; }; </code></pre> <p>You could of course do the same thing with a traditional function, but then makes it difficult to use with function pointers, because it has a different prototype to <code>CalculateAverage</code>.</p> <p><strong>Statefulness</strong></p> <p>And as functors can be stateful, you could do something like this:</p> <pre><code>CalculateAverage avg; avg = std::for_each(dataA.begin(), dataA.end(), avg); avg = std::for_each(dataB.begin(), dataB.end(), avg); avg = std::for_each(dataC.begin(), dataC.end(), avg); </code></pre> <p>to average across a number of different data-sets.</p> <p>Note that almost all STL algorithms/containers that accept functors require them to be "pure" predicates, i.e. have no observable change in state over time. <code>for_each</code> is a special case in this regard (see e.g. <a href="http://drdobbs.com/184403769" rel="noreferrer">Effective Standard C++ Library - for_each vs. transform</a>).</p> <p><strong>Performance</strong></p> <p>Functors can often be inlined by the compiler (the STL is a bunch of templates, after all). Whilst the same is theoretically true of functions, compilers typically won't inline through a function pointer. The canonical example is to compare <code>std::sort</code> vs <code>qsort</code>; the STL version is often 5-10x faster, assuming the comparison predicate itself is simple.</p> <p><strong>Summary</strong></p> <p>Of course, it's possible to emulate the first three with traditional functions and pointers, but it becomes a great deal simpler with functors.</p>
6,974,684
How to send FormData objects with Ajax-requests in jQuery?
<p>The <a href="http://www.w3.org/TR/XMLHttpRequest2/" rel="noreferrer">XMLHttpRequest Level 2</a> standard (still a working draft) defines the <code>FormData</code> interface. This interface enables appending <code>File</code> objects to XHR-requests (Ajax-requests).</p> <p>Btw, this is a new feature - in the past, the "hidden-iframe-trick" was used (read about that in <a href="https://stackoverflow.com/questions/6718664/is-it-possible-to-peform-an-asynchronous-cross-domain-file-upload/6963843">my other question</a>).</p> <p>This is how it works (example):</p> <pre><code>var xhr = new XMLHttpRequest(), fd = new FormData(); fd.append( 'file', input.files[0] ); xhr.open( 'POST', 'http://example.com/script.php', true ); xhr.onreadystatechange = handler; xhr.send( fd ); </code></pre> <p>where <code>input</code> is a <code>&lt;input type="file"&gt;</code> field, and <code>handler</code> is the success-handler for the Ajax-request.</p> <p>This works beautifully in all browsers (again, except IE).</p> <p>Now, I would like to make this functionality work with jQuery. I tried this:</p> <pre><code>var fd = new FormData(); fd.append( 'file', input.files[0] ); $.post( 'http://example.com/script.php', fd, handler ); </code></pre> <p>Unfortunately, that won't work (an "Illegal invocation" error is thrown - <a href="https://i.imgur.com/Uy8Xu.png" rel="noreferrer">screenshot is here</a>). I assume jQuery expects a simple key-value object representing form-field-names / values, and the <code>FormData</code> instance that I'm passing in is apparently incompatible.</p> <p>Now, since it is possible to pass a <code>FormData</code> instance into <code>xhr.send()</code>, I hope that it is also possible to make it work with jQuery.</p> <hr> <p><strong>Update:</strong></p> <p>I've created a "feature ticket" over at jQuery's Bug Tracker. It's here: <a href="http://bugs.jquery.com/ticket/9995" rel="noreferrer">http://bugs.jquery.com/ticket/9995</a></p> <p>I was suggested to use an "Ajax prefilter"...</p> <hr> <p><strong>Update:</strong></p> <p>First, let me give a demo demonstrating what behavior I would like to achieve. </p> <p>HTML:</p> <pre><code>&lt;form&gt; &lt;input type="file" id="file" name="file"&gt; &lt;input type="submit"&gt; &lt;/form&gt; </code></pre> <p>JavaScript:</p> <pre><code>$( 'form' ).submit(function ( e ) { var data, xhr; data = new FormData(); data.append( 'file', $( '#file' )[0].files[0] ); xhr = new XMLHttpRequest(); xhr.open( 'POST', 'http://hacheck.tel.fer.hr/xml.pl', true ); xhr.onreadystatechange = function ( response ) {}; xhr.send( data ); e.preventDefault(); }); </code></pre> <p>The above code results in this HTTP-request:</p> <p><img src="https://i.stack.imgur.com/YJYPm.png" alt="multipartformdata"></p> <p><strong>This is what I need</strong> - I want that "multipart/form-data" content-type!</p> <hr> <p>The proposed solution would be like so:</p> <pre><code>$( 'form' ).submit(function ( e ) { var data; data = new FormData(); data.append( 'file', $( '#file' )[0].files[0] ); $.ajax({ url: 'http://hacheck.tel.fer.hr/xml.pl', data: data, processData: false, type: 'POST', success: function ( data ) { alert( data ); } }); e.preventDefault(); }); </code></pre> <p>However, this results in:</p> <p><img src="https://i.stack.imgur.com/uU2Gi.png" alt="wrongcontenttype"></p> <p>As you can see, the content type is wrong...</p>
8,244,082
8
11
null
2011-08-07 18:06:39.973 UTC
231
2020-04-18 12:32:23.67 UTC
2017-05-23 12:34:44.877 UTC
null
-1
null
425,275
null
1
557
javascript|jquery|ajax|html|multipartform-data
1,007,401
<p>I believe you could do it like this : </p> <pre class="lang-js prettyprint-override"><code>var fd = new FormData(); fd.append( 'file', input.files[0] ); $.ajax({ url: 'http://example.com/script.php', data: fd, processData: false, contentType: false, type: 'POST', success: function(data){ alert(data); } }); </code></pre> <p>Notes:</p> <ul> <li><p>Setting <code>processData</code> to <code>false</code> lets you prevent jQuery from automatically transforming the data into a query string. See <a href="http://api.jquery.com/jQuery.ajax/" rel="noreferrer">the docs</a> for more info.</p></li> <li><p>Setting the <code>contentType</code> to <code>false</code> is imperative, since otherwise jQuery <a href="https://stackoverflow.com/a/5976031/33080">will set it incorrectly</a>.</p></li> </ul>
57,710,254
Idiomatic way to create an immutable and efficient class in C++
<p>I am looking to do something like this (C#).</p> <pre><code>public final class ImmutableClass { public readonly int i; public readonly OtherImmutableClass o; public readonly ReadOnlyCollection&lt;OtherImmutableClass&gt; r; public ImmutableClass(int i, OtherImmutableClass o, ReadOnlyCollection&lt;OtherImmutableClass&gt; r) : i(i), o(o), r(r) {} } </code></pre> <p>The potential solutions and their associated problems I've encountered are:</p> <p><strong>1. Using <code>const</code> for the class members</strong>, but this means the default copy assignment operator is deleted.</p> <p>Solution 1:</p> <pre><code>struct OtherImmutableObject { const int i1; const int i2; OtherImmutableObject(int i1, int i2) : i1(i1), i2(i2) {} } </code></pre> <p>Problem 1:</p> <pre><code>OtherImmutableObject o1(1,2); OtherImmutableObject o2(2,3); o1 = o2; // error: use of deleted function 'OtherImmutableObject&amp; OtherImmutableObject::operator=(const OtherImmutableObject&amp;)` </code></pre> <p><strong>EDIT:</strong> This is important as I would like to store immutable objects in a <code>std::vector</code> but receive <code>error: use of deleted function 'OtherImmutableObject&amp; OtherImmutableObject::operator=(OtherImmutableObject&amp;&amp;)</code></p> <p><strong>2. Using get methods and returning values</strong>, but this means that large objects would have to be copied which is an inefficiency I'd like to know how to avoid. <a href="https://stackoverflow.com/questions/26858518/idiomatic-way-to-declare-c-immutable-classes">This thread</a> suggests the get solution, but it doesn't address how to handle passing non-primitive objects without copying the original object.</p> <p>Solution 2:</p> <pre><code>class OtherImmutableObject { int i1; int i2; public: OtherImmutableObject(int i1, int i2) : i1(i1), i2(i2) {} int GetI1() { return i1; } int GetI2() { return i2; } } class ImmutableObject { int i1; OtherImmutableObject o; std::vector&lt;OtherImmutableObject&gt; v; public: ImmutableObject(int i1, OtherImmutableObject o, std::vector&lt;OtherImmutableObject&gt; v) : i1(i1), o(o), v(v) {} int GetI1() { return i1; } OtherImmutableObject GetO() { return o; } // Copies a value that should be immutable and therefore able to be safely used elsewhere. std::vector&lt;OtherImmutableObject&gt; GetV() { return v; } // Copies the vector. } </code></pre> <p>Problem 2: The unnecessary copies are inefficient.</p> <p><strong>3. Using get methods and returning <code>const</code> references or <code>const</code> pointers</strong> but this could leave hanging references or pointers. <a href="https://stackoverflow.com/questions/8005514/is-returning-references-of-member-variables-bad-practice">This thread</a> talks about the dangers of references going out of scope from function returns.</p> <p>Solution 3:</p> <pre><code>class OtherImmutableObject { int i1; int i2; public: OtherImmutableObject(int i1, int i2) : i1(i1), i2(i2) {} int GetI1() { return i1; } int GetI2() { return i2; } } class ImmutableObject { int i1; OtherImmutableObject o; std::vector&lt;OtherImmutableObject&gt; v; public: ImmutableObject(int i1, OtherImmutableObject o, std::vector&lt;OtherImmutableObject&gt; v) : i1(i1), o(o), v(v) {} int GetI1() { return i1; } const OtherImmutableObject&amp; GetO() { return o; } const std::vector&lt;OtherImmutableObject&gt;&amp; GetV() { return v; } } </code></pre> <p>Problem 3:</p> <pre><code>ImmutableObject immutable_object(1,o,v); // elsewhere in code... OtherImmutableObject&amp; other_immutable_object = immutable_object.GetO(); // Somewhere else immutable_object goes out of scope, but not other_immutable_object // ...and then... other_immutable_object.GetI1(); // The previous line is undefined behaviour as immutable_object.o will have been deleted with immutable_object going out of scope </code></pre> <p>Undefined behaviour can occur due to returning a reference from any of the <code>Get</code> methods.</p>
57,710,729
8
23
null
2019-08-29 12:29:46.347 UTC
4
2020-08-15 15:24:27.993 UTC
2019-09-01 05:57:44.653 UTC
null
4,515,663
null
4,515,663
null
1
38
c++|constants|immutability|const-cast
4,072
<ol> <li><p>You truly want immutable objects of some type plus value semantics (as you care about runtime performance and want to avoid the heap). Just define a <code>struct</code> with all data members <code>public</code>.</p> <pre><code>struct Immutable { const std::string str; const int i; }; </code></pre> <p>You can instantiate and copy them, read data members, but that's about it. Move-constructing an instance from an rvalue reference of another one still copies.</p> <pre><code>Immutable obj1{"...", 42}; Immutable obj2 = obj1; Immutable obj3 = std::move(obj1); // Copies, too obj3 = obj2; // Error, cannot assign </code></pre> <p>This way, you really make sure every usage of your class respects the immutability (assuming no one does bad <code>const_cast</code> things). Additional functionality can be provided through free functions, there is no point in adding member functions to a read-only aggregation of data members.</p></li> <li><p>You want 1., still with value semantics, but slightly relaxed (such that the objects aren't really immutable anymore) and you're also concerned that you need move-construction for the sake of runtime performance. There is no way around <code>private</code> data members and getter member functions:</p> <pre><code>class Immutable { public: Immutable(std::string str, int i) : str{std::move(str)}, i{i} {} const std::string&amp; getStr() const { return str; } int getI() const { return i; } private: std::string str; int i; }; </code></pre> <p>Usage is the same, but the move construction really does move.</p> <pre><code>Immutable obj1{"...", 42}; Immutable obj2 = obj1; Immutable obj3 = std::move(obj1); // Ok, does move-construct members </code></pre> <p>Whether you want assignment to be allowed or not is under your control now. Just <code>= delete</code> the assignment operators if you don't want it, otherwise go with the compiler-generated one or implement your own.</p> <pre><code>obj3 = obj2; // Ok if not manually disabled </code></pre></li> <li><p>You don't care about value semantics and/or atomic reference count increments are ok in your scenario. Use the solution depicted in <a href="https://stackoverflow.com/a/57710605/9593596">@NathanOliver's answer</a>.</p></li> </ol>
16,026,048
Pretty file size in Ruby?
<p>I'm trying to make a method that converts an integer that represents bytes to a string with a 'prettied up' format.</p> <p>Here's my half-working attempt:</p> <pre><code>class Integer def to_filesize { 'B' =&gt; 1024, 'KB' =&gt; 1024 * 1024, 'MB' =&gt; 1024 * 1024 * 1024, 'GB' =&gt; 1024 * 1024 * 1024 * 1024, 'TB' =&gt; 1024 * 1024 * 1024 * 1024 * 1024 }.each_pair { |e, s| return "#{s / self}#{e}" if self &lt; s } end end </code></pre> <p>What am I doing wrong?</p>
16,026,123
8
0
null
2013-04-15 23:02:35.127 UTC
10
2022-08-23 19:31:39.56 UTC
null
null
null
null
816,475
null
1
24
ruby|integer|byte|filesize
22,981
<p>How about the Filesize gem ? It seems to be able to convert from bytes (and other formats) into pretty printed values:</p> <p>example:</p> <pre><code>Filesize.from("12502343 B").pretty # =&gt; "11.92 MiB" </code></pre> <p><a href="http://rubygems.org/gems/filesize" rel="noreferrer">http://rubygems.org/gems/filesize</a></p>
32,905,183
How do you get elements from a javascript HTMLCollection
<p>I can't understand why I cant get elements from a HtmlCollection. This code example:</p> <pre><code> var col = (document.getElementsByClassName("jcrop-holder")); console.log(col); </code></pre> <p>produces this output on console:</p> <p><a href="https://i.stack.imgur.com/yjZUC.png" rel="noreferrer"><img src="https://i.stack.imgur.com/yjZUC.png" alt="enter image description here"></a></p> <p>I'm trying to get the dic.jcrop-holder object but i cant get it from my variable col. None of this works:</p> <pre><code> console.log(col[0]); // undefined console.log(col.item(0)); // null // check length of collection console.log(col.length); // 0 </code></pre> <p>So if the length is 0 why does the console show a length of 1, as well as objects inside? When I open the node it contains children. What's going on?</p> <p>Here are some expanded nodes. I didn't expand div.jcrop.holder because it is too long. Here are children elements:</p> <p><a href="https://i.stack.imgur.com/RAzCz.png" rel="noreferrer"><img src="https://i.stack.imgur.com/RAzCz.png" alt="enter image description here"></a></p>
42,713,254
3
6
null
2015-10-02 10:24:20.233 UTC
3
2019-03-03 02:44:50.307 UTC
2018-02-01 05:19:11.14 UTC
null
7,663,531
null
2,965,619
null
1
20
javascript
45,852
<p>Taken from : <a href="https://stackoverflow.com/questions/32222255/cant-access-the-value-of-htmlcollection">Can&#39;t access the value of HTMLCollection</a></p> <p>The problem is you have placed the script in the header which gets executed before the html elements are loaded, so getElementsByClassName() will not return any elements.</p> <p>One solution is to wait for the html elements to be loaded then execute your script, for that you can use the window objects load event</p> <pre><code>window.addEventListener('load', function () { var eles = document.getElementsByClassName('review'); console.log(eles); console.log(eles.length); console.log(eles[0]); }) </code></pre> <p>Or you can place your script at the bottom of the body element instead of in head so that by the time the script is parsed and executed the elements are loaded in the dom</p>
10,392,952
How to design for a future additional enum value in protocol buffers?
<p>One of the attractive features of protocol buffers is that it allows you extend the message definitions without breaking code that uses the older definition. In the case of an enum <a href="https://developers.google.com/protocol-buffers/docs/proto#enum">according to the documentation</a>: </p> <blockquote> <p>a field with an enum type can only have one of a specified set of constants as its value (if you try to provide a different value, the parser will treat it like an unknown field)</p> </blockquote> <p>therefore if you extend the enum and use the new value then a field with that type in old code will be undefined or have its default value, if there is one.</p> <p>What is a good strategy to deal with this, knowing that in future the enum may have additional values added?</p> <p>One way that comes to mind is to define an "undefined" member of the enum and make that the default, then old code will know it has been sent something that it can't interpret. Is that sensible, are there better ways to deal with this situation?</p>
17,164,524
2
3
null
2012-05-01 02:45:38.867 UTC
12
2021-10-22 18:31:57.83 UTC
2012-05-01 04:19:21.783 UTC
null
278,403
null
278,403
null
1
37
protocol-buffers
17,275
<p>Yes, the best approach is to make the first value in the enum something like <code>UNKNOWN = 0</code>. Then old programs reading a protobuf with an enum value they don't recognize will see it as <code>UNKNOWN</code> and hopefully they can handle that reasonably, eg by skipping that element.</p> <p>If you want to do this you'll also want to make the enum be <code>optional</code> not <code>required</code>.</p> <p><code>required</code>, generally, means "I'd rather the program just abort than handle something it doesn't understand." </p> <p><em>Note that it must be the first value declared in the proto source</em> - just being the zero value doesn't make it the default.</p>
10,852,744
Android ViewPager Prev/Next Button
<p>Okay, so I'm developing an Android app that utilises a ViewPager to display pages.</p> <p>Within each page, I have a set of buttons to use for navigating between pages (in addition to the swiping between pages). These buttons are for "first page", "previous page", "next page" and "last page".</p> <p>What I can't figure out how to do is engineer a mechanism to enable a page change on a button click.</p> <p>Anyone have any ideas?</p> <p>ETA: To better explain the setup, the buttons are declared within each page's layout, and are inflated with the rest of the layout within the PagerAdapter. My problem is that I can't reference the ViewPager from within the PagerAdapter. Or at least, I can't think of a way to do it.</p>
13,285,950
9
3
null
2012-06-01 15:03:03.12 UTC
11
2019-12-18 07:23:44.347 UTC
2012-06-01 16:38:30.637 UTC
null
1,430,973
null
1,430,973
null
1
52
android|button|navigation|android-viewpager
76,662
<p>Button:</p> <pre><code>Button yourButton = (Button)findViewById(R.id.button1); yourButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { mViewPager.setCurrentItem(getItem(+1), true); //getItem(-1) for previous } }); </code></pre> <p>Function:</p> <pre><code>private int getItem(int i) { return mViewPager.getCurrentItem() + i; } </code></pre> <p>Hope this helps :)</p>
22,720,739
Pandas Left Outer Join results in table larger than left table
<p>From what I understand about a left outer join, the resulting table should never have more rows than the left table...Please let me know if this is wrong... </p> <p>My left table is 192572 rows and 8 columns.</p> <p>My right table is 42160 rows and 5 columns.</p> <p>My Left table has a field called 'id' which matches with a column in my right table called 'key'.</p> <p>Therefore I merge them as such:</p> <pre><code>combined = pd.merge(a,b,how='left',left_on='id',right_on='key') </code></pre> <p>But then the combined shape is 236569.</p> <p>What am I misunderstanding? </p>
22,720,823
5
2
null
2014-03-28 18:39:48.923 UTC
21
2022-04-10 15:06:54.557 UTC
null
null
null
null
1,455,043
null
1
118
python|pandas
96,331
<p>You can expect this to increase if keys match more than one row in the other DataFrame:</p> <pre><code>In [11]: df = pd.DataFrame([[1, 3], [2, 4]], columns=['A', 'B']) In [12]: df2 = pd.DataFrame([[1, 5], [1, 6]], columns=['A', 'C']) In [13]: df.merge(df2, how='left') # merges on columns A Out[13]: A B C 0 1 3 5 1 1 3 6 2 2 4 NaN </code></pre> <p>To avoid this behaviour <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop_duplicates.html">drop the duplicates</a> in df2:</p> <pre><code>In [21]: df2.drop_duplicates(subset=['A']) # you can use take_last=True Out[21]: A C 0 1 5 In [22]: df.merge(df2.drop_duplicates(subset=['A']), how='left') Out[22]: A B C 0 1 3 5 1 2 4 NaN </code></pre>
13,613,538
Making Thread sleep for random amount of MS
<p>Hey so I have 3 threads which have certain conditions when they print out something. this works fine. What I want to do now is make the thread just before it outputs something to send it to sleep for random amount of ms. I was thinking using the math class but not sure how.</p> <p>the random() should generate random double greater than or equal to 0.0 and less than 1.0 right ?</p> <p>will I just write something like</p> <pre><code>Thread.sleep(random()); </code></pre> <p>^ that doesn't work though tried it</p>
13,613,564
3
0
null
2012-11-28 20:08:33.64 UTC
2
2012-11-28 20:17:27.16 UTC
null
null
null
null
1,809,582
null
1
21
java|multithreading|concurrency
46,018
<p><a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#sleep%28long%29" rel="noreferrer"><code>Thread.sleep()</code></a> takes a <code>long</code> value not <code>double</code>. You would need a typecast here: -</p> <pre><code>Thread.sleep((long)(Math.random() * 1000)); </code></pre>
13,310,678
Passing format as parameter to rake spec
<p>My question is similar to <a href="https://stackoverflow.com/questions/2890521/how-to-pass-f-specdoc-option-through-rake-task">this </a>, where they want to override <code>rake spec</code>'s output format. The resolution to that question is to use the .rspec config file, which is limiting. I would like this to be a command line argument because I want this to vary on different machines.</p> <p>The rspec executable has the <code>-f</code> option be defining format. <code>rake spec</code> has <code>-f</code> defining a rakefile. <code>rake spec --format</code> is invalid. Is this an oversight in <code>rake spec</code>? "Format" really isn't an option?</p>
13,500,459
2
1
null
2012-11-09 15:15:33.17 UTC
9
2014-10-28 12:42:46.28 UTC
2017-05-23 12:25:51.473 UTC
null
-1
null
965,161
null
1
30
ruby|rspec|rake
6,007
<p>ANSWER: I'm self answering my question here. rake spec will take the SPEC_OPTS environment variable.</p> <pre><code>rake spec SPEC_OPTS="--format documentation" </code></pre>
13,750,428
Resize UICollectionView cells after their data has been set
<p>My UICollectionView cells contain UILabels with multiline text. I don't know the height of the cells until the text has been set on the label. </p> <pre><code>-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath; </code></pre> <p>This was the initial method I looked at to size the cells. However, this is called BEFORE the cells are created out of the storyboard.</p> <p>Is there a way to layout the collection and size the cells AFTER they have been rendered, and I know the actual size of the cell?</p>
13,786,856
4
1
null
2012-12-06 18:48:47.53 UTC
17
2018-05-21 02:45:49.003 UTC
2018-05-21 02:45:49.003 UTC
null
1,402,846
null
1,838,454
null
1
49
objective-c|uicollectionview|uicollectionviewcell
60,554
<p>I think your are looking for the <code>invalidateLayout</code> method you can call on the <code>.collectionViewLayout</code> property of your UICollectionView. This method regenerates your layout, which in your case means also calling <code>-collectionView: layout: sizeForItemAtIndexPath:</code>, which is the right place to reflect your desired item size. Jirune points the right direction on how to calculate them.</p> <p>An example for the usage of <code>invalidateLayout</code> can be found <a href="https://stackoverflow.com/questions/13780153/uicollectionview-animate-cell-size-change-on-selection">here</a>. Also consult the UICollectionViewLayout documentation on that method:</p> <blockquote> <p>Invalidates the current layout and triggers a layout update.</p> <p><strong>Discussion:</strong></p> <p>You can call this method at any time to update the layout information. This method invalidates the layout of the collection view itself and returns right away. Thus, you can call this method multiple times from the same block of code without triggering multiple layout updates. The actual layout update occurs during the next view layout update cycle.</p> </blockquote> <p><strong>Edit:</strong></p> <p>For storyboard collection view which contains auto layout constraints, you need to override <code>viewDidLayoutSubviews</code> method of <code>UIViewController</code> and call <code>invalidateLayout</code> collection view layout in this method.</p> <pre><code>- (void)viewDidLayoutSubviews { [super viewDidLayoutSubviews]; [yourCollectionView.collectionViewLayout invalidateLayout]; } </code></pre>
13,667,827
CSS transition from `display: none` on class change?
<p>I've started using transitions to "modernise" the feel of a site. So far, <code>:hover</code> transitions are working great. Now I'm wondering if it's possible to trigger a transition based on other things, such as when a class changes.</p> <p>Here's the relevant CSS:</p> <pre><code>#myelem { opacity: 0; display: none; transition: opacity 0.4s ease-in, display 0.4s step-end; -ms-transition: opacity 0.4s ease-in, display 0.4s step-end; -moz-transition: opacity 0.4s ease-in, display 0.4s step-end; -webkit-transition: opacity 0.4s ease-in, display 0.4s step-end; } #myelem.show { display: block; opacity: 1; transition: opacity 0.4s ease-out, display 0.4s step-start; -ms-transition: opacity 0.4s ease-out, display 0.4s step-start; -moz-transition: opacity 0.4s ease-out, display 0.4s step-start; -webkit-transition: opacity 0.4s ease-out, display 0.4s step-start; } </code></pre> <p>The JavaScript to trigger the change is:</p> <pre><code>document.getElementById('myelem').className = "show"; </code></pre> <p>But the transition doesn't seem to be happening - it's just jumping from one state to the other.</p> <p>What am I doing wrong?</p>
13,668,066
4
2
null
2012-12-02 09:01:55.04 UTC
6
2016-04-14 15:11:41.297 UTC
2016-04-14 15:11:41.297 UTC
null
2,619,939
null
507,674
null
1
50
css|css-transitions
46,366
<p>It does work when you remove the <code>display</code> properties.</p> <pre><code>#myelem { opacity: 0; transition: opacity 0.4s ease-in; -ms-transition: opacity 0.4s ease-in; -moz-transition: opacity 0.4s ease-in; -webkit-transition: opacity 0.4s ease-in; } #myelem.show { opacity: 1; transition: opacity 0.4s ease-out; -ms-transition: opacity 0.4s ease-out; -moz-transition: opacity 0.4s ease-out; -webkit-transition: opacity 0.4s ease-out; }​ </code></pre> <p><strong><a href="http://jsfiddle.net/ks8jD/">JSFiddle</a></strong>.</p> <p>The reason for this is that only CSS properties with numbers can be transitioned. What do you think the "50% state" should be between "<code>display: none;</code>" and "<code>display: block;</code>"? Since that can't be calculated, you can't animate the <code>display</code> property.</p>
39,863,317
How to force Angular2 to POST using x-www-form-urlencoded
<p>I have a project that needs to use Angular2 (final) to post to an old, legacy Tomcat 7 server providing a somewhat REST-ish API using .jsp pages.</p> <p>This worked fine when the project was just a simple JQuery app performing AJAX requests. However, the scope of the project has grown such that it will need to be rewritten using a more modern framework. Angular2 looks fantastic for the job, with one exception: It refuses to perform POST requests using anything option but as form-data, which the API doesn't extract. The API expects everything to be urlencoded, relying on Java's <code>request.getParameter(&quot;param&quot;)</code> syntax to extract individual fields.</p> <p>This is a snipped from my user.service.ts:</p> <pre class="lang-js prettyprint-override"><code>import { Injectable } from '@angular/core'; import { Headers, Response, Http, RequestOptions } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map'; @Injectable() export class UserService { private loggedIn = false; private loginUrl = 'http://localhost:8080/mpadmin/api/login.jsp'; private headers = new Headers({'Content-Type': 'application/x-www-form-urlencoded'}); constructor(private http: Http) {} login(username, password) { return this.http.post(this.loginUrl, {'username': username, 'password': password}, this.headers) .map((response: Response) =&gt; { let user = response.json(); if (user) { localStorage.setItem('currentUser', JSON.stringify(user)); } } ); } } </code></pre> <p>No matter what I set the header content type to be, it always ends up arriving as non-encoded form-data. It's not honoring the header I'm setting.</p> <p>Has anyone else encountered this? How do you go about forcing Angular2 to POST data in a format that can be read by an old Java API using <code>request.getParameter(&quot;param&quot;)</code>?</p>
39,864,307
12
3
null
2016-10-04 23:36:28.353 UTC
25
2022-07-24 17:49:55.763 UTC
2022-07-24 17:49:55.763 UTC
null
3,001,761
null
2,013,712
null
1
92
javascript|angular
103,606
<p><strong>UPDATE June 2020: This answer is 4 years old and no longer valid due to API changes in Angular. Please refer to more recent answers for the current version approach.</strong></p> <hr> <p>You can do this using <code>URLSearchParams</code> as the body of the request and angular will automatically set the content type to <code>application/x-www-form-urlencoded</code> and encode the body properly.</p> <pre><code>let body = new URLSearchParams(); body.set('username', username); body.set('password', password); this.http.post(this.loginUrl, body).map(...); </code></pre> <p>The reason it's not currently working for you is you're not encoding the body data in the correct format and you're not setting the header options correctly.</p> <p>You need to encode the body like this:</p> <pre><code>let body = `username=${username}&amp;password=${password}`; </code></pre> <p>You need to set the header options like this:</p> <pre><code>this.http.post(this.loginUrl, body, { headers: headers }).map(...); </code></pre>
3,497,804
HTML5 Geolocation, GPS Only
<p>Is there a way to make HTML5's Geolocation only work, if it is using a GPS device to get the location?</p>
3,497,987
2
0
null
2010-08-16 22:08:24.867 UTC
10
2012-03-26 17:33:03.243 UTC
null
null
null
null
226,818
null
1
23
html|mobile|geolocation|gps
12,475
<p>I don't believe it's possible, the best you can do is pass <code>true</code> for <a href="http://dev.w3.org/geo/api/spec-source.html#high-accuracy" rel="noreferrer">enableHighAccuracy</a> and use a heuristic based on the <a href="http://dev.w3.org/geo/api/spec-source.html#accuracy" rel="noreferrer">accuracy</a> value.</p> <p>--Edit</p> <p>I saw a presentation by <a href="http://introducinghtml5.com/" rel="noreferrer">Remy Sharp</a> last month and he had a useful suggestion: if you use <code>watchPosition</code> instead of <code>getCurrentPosition</code> then you can wait until the location information becomes accurate enough; GPS often takes some time to lock on to satellites so usually <code>getCurrentPosition</code> will just return something from one of the less accurate but more responsive methods.</p>
3,618,049
how to detect 64bit platform by script
<p>is there code to detect 64 platform e.g. </p> <pre><code>if X86 then ... if X64 then ... </code></pre>
3,618,096
2
0
null
2010-09-01 12:41:36.017 UTC
11
2012-03-16 21:41:14.313 UTC
null
null
null
null
20,979
null
1
28
inno-setup
26,766
<p>Yes.</p> <p>Use</p> <pre><code>if IsWin64 then // Do sth else // Do sth else </code></pre> <p>There is also a <code>Is64BitInstallMode</code> function. Indeed, a 32-bit setup can run on a 64-bit OS. Hence, <code>Is64BitInstallMode</code> implies <code>IsWin64</code>, but <code>IsWin64</code> does not imply <code>Is64BitInstallMode</code>.</p>
28,571,035
Is there a workaround for the lack of type class backtracking?
<p>In <a href="https://www.youtube.com/watch?feature=player_detailpage&amp;v=hIZxTQP1ifo#t=4830" rel="nofollow">this talk around the 1:20 mark</a>, Edward Kmett mentions the lack of "type class backtracking" in Haskell. Consider the problem of "set equality" (where order and multiplicity are disregarded) implemented on lists:</p> <pre><code>equals :: [a] -&gt; [a] -&gt; Bool </code></pre> <p>By the nature of type classes I cannot provide an inefficient O(n²) comparison if all we have is <code>Eq a</code> but efficiently compare the lists in O(n log n) if we have <code>Ord a</code>.</p> <p>I did understand why such a facility would be problematic. At the same time, Edward says that there are "tricks you could play" mentioning for instance type families.</p> <p>Hence my question is, what would be a workaround to achieve the same effect:</p> <ul> <li>an (inefficient) default implementation is provided</li> <li>if the user can provide some additional information about the type, we "unlock" a more efficient implementation</li> </ul> <p>This workaround does not necessarily need to use type classes.</p> <p><strong>Edit</strong>: Some people suggested simply providing <code>equals</code> and <code>efficientEquals</code> as two distinct methods. In general I agree that this is the more Haskell-idiomatic approach. However, I am not convinced that this is always possible. For instance, what if the equals method above is itself part of a type class:</p> <pre><code>class SetLike s where equals :: Eq a =&gt; s a -&gt; s a -&gt; Bool </code></pre> <p>Assume that this class has been provided by someone else so I cannot simply add a new function to the typeclass. I now want to define the instance for <code>[]</code>. I know that <code>[]</code> can always provide an implementation of <code>equals</code> no matter what constraints there are on <code>a</code> but I cannot tell my instance to use the more efficient version if more information about <code>a</code> is available.</p> <p>Maybe I could wrap the list in a newtype and tag it with some additional type information?</p>
28,590,508
1
10
null
2015-02-17 21:01:48.77 UTC
11
2015-02-18 17:55:47.51 UTC
2015-02-18 08:56:04.83 UTC
null
2,393,937
null
2,393,937
null
1
15
haskell|typeclass
376
<p>In the scenario from your edit, you could use a <code>GADT</code> as proof of your <code>Ord</code> constraint:</p> <pre><code>{-# LANGUAGE GADTs #-} import Data.List class SetLike s where equals :: Eq a =&gt; s a -&gt; s a -&gt; Bool data OrdList a where OrdList :: Ord a=&gt; [a] -&gt; OrdList a instance SetLike OrdList where equals (OrdList a) (OrdList b) = sort a == sort b </code></pre> <p>And for fun here's something that uses makes use of the <code>OverlappingInstances</code> trick I mention in my comment. There are lots of ways to do this sort of thing:</p> <pre><code>{-# LANGUAGE DefaultSignatures, OverlappingInstances, UndecidableInstances, MultiParamTypeClasses, FlexibleInstances #-} import Data.List class Equals a where equals :: [a] -&gt; [a] -&gt; Bool default equals :: Ord a=&gt; [a] -&gt; [a] -&gt; Bool equals as bs = sort as == sort bs instance Equals Int instance Equals Integer instance Equals Char -- etc. instance (Eq a)=&gt; Equals a where equals = error "slow version" </code></pre>
9,606,340
Get a PHP object property that is a number
<p>I'm trying to get a property from JSON data decoded into a PHP object. It's just a YouTube data API request that returns a video object that has a content object liks so;</p> <pre><code>[content] =&gt; stdClass Object ( [5] =&gt; https://www.youtube.com/v/r4ihwfQipfo?version=3&amp;f=videos&amp;app=youtube_gdata [1] =&gt; rtsp://v4.cache7.c.youtube.com/CiILENy73wIaGQn6pSL0waGIrxMYDSANFEgGUgZ2aWRlb3MM/0/0/0/video.3gp [6] =&gt; rtsp://v6.cache3.c.youtube.com/CiILENy73wIaGQn6pSL0waGIrxMYESARFEgGUgZ2aWRlb3MM/0/0/0/video.3gp ) </code></pre> <p>Doing</p> <pre><code>$object-&gt;content-&gt;5 </code></pre> <p>Throws "unexpected T_DNUMBER" - which makes perfect sense. But how do I get the value of a property that is a number?</p> <p>I'm sure I should know this. Thanks in advance.</p>
9,606,356
3
2
null
2012-03-07 17:29:52.787 UTC
4
2015-05-29 20:51:04.807 UTC
null
null
null
null
698,857
null
1
35
php|json|object|properties
19,825
<p>This should work:</p> <p><code>$object-&gt;content-&gt;{'5'}</code></p>
16,541,438
In Java, how to get strings of days of week (Sun, Mon, ..., Sat) with system's default Locale (language)
<p>The simplest way:</p> <pre><code>String[] namesOfDays = new String[7] { "SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT" }; </code></pre> <p>This method does not use Locale. Therefore, if the system's language is not English, this method does not work properly.</p> <p>Using Joda time, we can do like this:</p> <pre><code>String[] namesOfDays = new String[7]; LocalDate now = new LocalDate(); for (int i=0; i&lt;7; i++) { /* DateTimeConstants.MONDAY = 1, TUESDAY = 2, ..., SUNDAY = 7 */ namesOfDays[i] = now.withDayOfWeek((DateTimeConstants.SUNDAY + i - 1) % 7 + 1) .dayOfWeek().getAsShortText(); } </code></pre> <p>However, this method uses today's date and calendar calculations, which are useless for the final purpose. Also, it is a little complicated.</p> <p>Is there an easy way to get Strings like <code>"Sun"</code>, <code>"Mon"</code>, ..., <code>"Sat"</code> with system's default locale?</p>
16,541,525
7
1
null
2013-05-14 10:59:47.103 UTC
3
2020-06-27 23:49:37.12 UTC
2018-02-28 09:12:51.61 UTC
null
869,330
null
869,330
null
1
31
java|android|calendar|jodatime|dayofweek
40,740
<p>If I have not misunderstood you</p> <pre><code> calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.US); </code></pre> <p>is what you are looking for. <a href="http://developer.android.com/reference/java/util/Calendar.html#getDisplayName(int,%20int,%20java.util.Locale)" rel="noreferrer">Here</a> you can find the documentation,</p> <p>Or you can also use, <a href="http://developer.android.com/reference/java/text/DateFormatSymbols.html#getShortWeekdays()" rel="noreferrer">getShortWeekdays()</a></p> <pre><code>String[] namesOfDays = DateFormatSymbols.getInstance().getShortWeekdays() </code></pre>
16,096,192
How to programmatically extract / unzip a .7z (7-zip) file with R
<p>I'm trying to automate the extraction of a number of files compressed with 7-zip. I need to automate this process, because a) there are many years of data I'd like to unlock and b) I'd like to share my code with others and prevent them from repeating the process by hand.</p> <p>I have both WinRAR and 7-zip installed on my computer, and I can individually open these files easily with either program.</p> <p>I've looked around at the <code>unzip</code> <code>untar</code> and <code>unz</code> commands, but I don't believe any of them do what I need.</p> <p>I don't know anything about compression, but if it makes any difference: each of these files only contains <em>one</em> file and it's <em>just a text file</em>.</p> <p>I would strongly prefer a solution that does not require the user to install additional software (like WinRAR or 7-Zip) and execute a command with <code>shell</code>, although I acknowledge this task might be impossible with just R and CRAN packages. I actually believe running <code>shell.exec</code> on these files with additional parameters might work on computers with WinRAR installed, but again, I'd like to avoid that installation if possible. :)</p> <p>Running the code below will load the files I am trying to extract -- the .7z files in <code>files.data</code> are what needs to be unlocked.</p> <pre><code># create a temporary file and temporary directory, download the file, extract the file to the temporary directory tf &lt;- tempfile() ; td &lt;- tempdir() file.path &lt;- "ftp://ftp.ibge.gov.br/Orcamentos_Familiares/Pesquisa_de_Orcamentos_Familiares_2008_2009/Microdados/Dados.zip" download.file( file.path , tf , mode = "wb" ) files.data &lt;- unzip( tf , exdir = td ) # how do i unzip ANY of these .7z files? files.data </code></pre> <p>Thanks!!! :)</p>
16,098,709
2
3
null
2013-04-19 02:22:35.397 UTC
14
2019-05-08 12:30:10.977 UTC
2019-05-08 12:30:10.977 UTC
null
2,204,410
null
1,759,499
null
1
36
r|zip|unzip|7zip|rar
23,580
<p>If you have <code>7z</code> executable in your path, you can simple use <code>system</code> command</p> <p><code>system('7z e -o &lt;output_dir&gt; &lt;archive_name&gt;')</code></p>
16,255,605
Svg path position
<p>I have an SVG path, defined as follows:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="200px" height="280px" viewBox="0 0 850.39 850.39" enable-background="new 0 0 850.39 850.39" xml:space="preserve" class="hand"&gt; &lt;g&gt; &lt;path fill-rule="evenodd" clip-rule="evenodd" fill="#0D0D0D" d="M480.366,674.977c-1.345-36.176,16.102-91.082,42.928-100.447 s99.269-89.711,108.649-100.418c9.381-10.734,14.758-17.416,24.139-45.541c9.409-28.123,54.996-69.638,54.996-69.638 c18.79-20.072,36.236-25.44,45.616-25.44c9.381,0,29.515-5.368,34.863-14.733c5.377-9.365,6.721-30.779-26.826-44.199 c-33.519-13.362-54.997-24.098-127.411,36.176c-72.442,60.245-97.925,3.997-97.925,3.997c-30.859-54.877-16.102-137.906,0-199.522 c16.102-61.587,20.105-172.74,12.069-190.157c-8.037-17.389-34.12-19.33-45.617-10.707c-12.212,9.193-22.793,89.739-32.174,124.544 c-9.409,34.805-25.482,97.763-25.482,97.763c-4.032,42.856-36.236,28.124-46.96,20.072c-10.725-8.023-17.446-73.636-16.102-84.343 c1.344-10.735,0-41.515-1.344-49.566c-1.315-8.023-21.45-97.762-25.482-128.542c-4.004-33.492-29.515-40.173-42.928-38.831 c-13.384,1.313-22.794,13.391-22.794,25.44c0,12.049,9.41,115.151,6.721,123.203c-2.688,8.023,1.344,73.636,6.692,83.029 c1.344,12.049,9.38,68.268,4.032,70.952c-5.348,2.684-17.446-13.391-25.482-38.831c-8.065-25.44-24.138-73.636-24.138-73.636 c-9.409-21.443-14.757-79.032-20.134-104.472c-5.348-25.44-20.105-34.805-38.895-32.15c-16.102,2.684-26.827,28.152-24.138,40.202 c5.348,9.365,18.761,155.323,24.138,167.373c5.348,12.049,26.826,80.345,25.482,85.713c-1.344,5.339-8.065,8.023-20.134,3.998 c-12.041-3.998-71.07-113.809-71.07-113.809c-21.45-37.489-25.482-72.323-60.374-57.59c-22.793,12.049-9.38,34.833-4.004,57.59 c8.037,36.147,84.512,166.059,79.135,180.792c-5.377,14.733,28.17,176.737,28.17,176.737c0,26.783,65.722,156.695,68.381,164.719 c2.717,8.051,2.145,84.17,0,113.836c-1.916,27.012-6.635,164.547-9.123,239.324c-0.257,8.023,2.431,15.018,8.037,20.785 c5.577,5.768,12.498,8.709,20.534,8.709H469.87c8.265,0,15.387-3.111,20.992-9.164c5.634-6.082,8.179-13.42,7.521-21.643 C490.919,872.699,481.396,702.414,480.366,674.977L480.366,674.977z" /&gt; &lt;/g&gt; &lt;/svg&gt;</code></pre> </div> </div> </p> <p>I need to give this path an absolute position. I have tried setting <code>cx</code> and <code>cy</code> attributes, but this did not work.</p> <p>What can I do to set an absolute position?</p>
16,287,313
4
1
null
2013-04-27 18:39:19.067 UTC
2
2021-06-17 15:24:49.92 UTC
2016-08-11 16:18:02.263 UTC
null
103,647
null
2,327,481
null
1
50
html|svg
52,544
<p>Use the <code>transform</code> attribute to position the path, like</p> <pre><code>transform="translate(50,80)" </code></pre> <p>Other transformations like <code>scale</code> or <code>rotate</code> are also available. <a href="http://www.w3.org/TR/SVG/coords.html#EstablishingANewUserSpace">See the specs</a>.</p>
42,007,826
Downgrade Gradle from 3.3 to 2.14.1
<p>Long story short: My android phone keeps disconnecting from ADB. I was told to update android studio, did that. I open my project in Intellij and try to run on android and I get an error: </p> <pre><code>BUILD FAILED Total time: 48.986 secs Error: /Users/me/Desktop/comp/Development/comp-ionic/platforms/android/gradlew: Command failed with exit code 1 Error output: FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':compileDebugJavaWithJavac'. &gt; java.lang.NullPointerException (no error message) </code></pre> <p>My first thought is that my gradle is the wrong version. For this specific app, I need to use gradle version <code>2.14.1</code>. </p> <p>When I type <code>gradle -v</code> I'm getting version 3.3.</p> <p>Is there a way to delete/downgrade gradle from 3.3 to 2.14.1?</p> <p>Or is this another problem?</p>
42,008,086
5
7
null
2017-02-02 16:49:20.153 UTC
2
2019-06-19 09:46:43.973 UTC
null
null
null
null
821,488
null
1
20
android|intellij-idea|gradle
52,524
<p>If you're using the gradle wrapper, then there'll be a folder in your project named "gradle" with a subfolder named "wrapper", inside that, there are 2 files:<br> - gradle-wrapper.jar<br> - gradle-wrapper.properties </p> <p>Open "gradle-wrapper.properties" and change the place where it says "3.3" to "2.14.1". Then sync gradle, and it will automatically download 2.14.1.</p> <p>If you're using the new 2.3 Android Studio, you HAVE to use gradle wrapper 3.3, as its the minimum supported gradle wrapper version. If so, then you'll have to download Android Studio 2.2, or fix whatever issue you have in your project that needs gradle wrapper version 2.14.1.</p> <p>To get more information about whatever the issue is, try running this: ./gradlew clean assemble -stacktrace</p> <p>That will clean your project, try and compile it, and if/when it fails, it will show you a stacktrace of the error.</p>
15,068,132
Change language of site with a html button
<p>In PHP, I want to change the language (English, German, etc) of the site when clicking a button. Is this the right way to approach that problem? </p> <pre><code>&lt;?php $language; if ($language == "en") { include("headerEn.php"); } else { include("header.php"); } ?&gt; &lt;a href="index.php"&gt;&lt;?php $language = "en"; ?&gt; &lt;img src="images/language/languageNO.png"&gt;&lt;/a&gt; &lt;a href="index.php"&gt;&lt;?php $language = "no"; ?&gt; &lt;img src="images/language/languageEN.png"&gt;&lt;/a&gt; </code></pre> <p>What is the best way to change the language of the site and have it persist when the user returns?</p>
15,068,175
7
0
null
2013-02-25 13:29:32.06 UTC
8
2020-08-14 13:01:32.21 UTC
2017-09-01 14:08:25.403 UTC
null
2,088,624
null
2,088,624
null
1
7
php|html|variables|button
43,595
<p>you can do this by </p> <pre><code>&lt;a href="index.php?language=en"&gt; &lt;a href="index.php?language=no"&gt; </code></pre> <p>and get the languages and store them in cookie and include file according to cookie like</p> <pre><code>if ( !empty($_GET['language']) ) { $_COOKIE['language'] = $_GET['language'] === 'en' ? 'en' : 'nl'; } else { $_COOKIE['language'] = 'nl'; } setcookie('language', $_COOKIE['language']); </code></pre> <p>and than </p> <pre><code>if ( $_COOKIE['language'] == "en") { include("headerEn.php"); } else { include("header.php"); } ?&gt; </code></pre>
17,519,411
How to load a PHP page into a div with jQuery and AJAX?
<p>I am trying to write a function that will call <code>getproduct.php?id=xxx</code> when clicked. I can get the <code>innerHTML</code> portion to appear, but how do I also call the <code>php</code> page that actually does the work?</p> <pre><code>var id = id; document.getElementById("digital_download").innerHTML = "Downloading...Please be patient. The process can take a few minutes."; url = getproduct.php?id=id; </code></pre>
17,519,439
6
6
null
2013-07-08 04:55:13.08 UTC
8
2017-03-30 10:37:45.497 UTC
2013-07-08 05:03:13.897 UTC
null
1,838,763
null
389,882
null
1
7
php|javascript|jquery|ajax
66,402
<p>You can do it with jQuery for example.</p> <pre><code>var id = 1; $('#digital_download').html('Downloading...'); // Show "Downloading..." // Do an ajax request $.ajax({ url: "getproduct.php?id="+id }).done(function(data) { // data what is sent back by the php page $('#digital_download').html(data); // display data }); </code></pre>
17,520,348
Open PDF in the PhoneGap App that is made in HTML and CSS
<p>I have a strange problem with my iPad App in Phone Gap. The problem is that I have to open PDF document in my app through links and when I click the link which opens the PDF, it shows me the PDF document with no back link.</p> <p>Hence, when I open the PDF document in my app through a link, it takes me to a dead end and there is no way I can go back to the main page of my app.</p> <p>My question is that how can I have a Top-Bar, when I open a PDF which could take me back to my home page? Any internal element for the iPad may be?</p> <p>Thanks a lot.</p>
17,520,422
5
0
null
2013-07-08 06:30:22.02 UTC
7
2015-12-14 12:22:21.877 UTC
null
null
null
null
2,292,197
null
1
8
css|html|cordova
39,799
<p>Try using the In App Browser plugin.</p> <p>If you're using a later Phonegap / Cordova version (2.8.0, 2.9.0 etc) it should come with it - nothing else to install.</p> <p><a href="http://docs.phonegap.com/en/2.9.0/cordova_inappbrowser_inappbrowser.md.html#InAppBrowser" rel="noreferrer">http://docs.phonegap.com/en/2.9.0/cordova_inappbrowser_inappbrowser.md.html#InAppBrowser</a></p> <p>It will allow you to open the PDF in the a new 'window' that overlays your app. It has a 'Done' button that users can use to close it and return to your app when they are finished.</p> <p>You would open the PDF using the In-App Browser, using something like this:</p> <pre><code>window.open('http://whitelisted-url.com/pdftoopen.pdf', '_blank'); </code></pre> <p>I.e. the <code>_blank</code> option triggers the In-App Browser plugin. If you were to use <code>_system</code> instead it <em>might</em> open it in iBooks (just guessing there - not 100% sure if it would use iBooks).</p>
17,140,408
If statement to check whether a string has a capital letter, a lower case letter and a number
<p>Can someone give an idea on how to test a string that:</p> <ul> <li>contains at least one upper case letter</li> <li>contains at least one lower case letter</li> <li>contains at least one number</li> <li>has a minimal length of 7 characters</li> </ul>
17,140,466
2
5
null
2013-06-17 04:28:01.297 UTC
8
2019-01-25 15:07:53.453 UTC
2019-01-25 15:07:53.453 UTC
null
-1
null
2,492,061
null
1
18
python
83,973
<pre><code>if (any(x.isupper() for x in s) and any(x.islower() for x in s) and any(x.isdigit() for x in s) and len(s) &gt;= 7): </code></pre> <p>Another way is to express your rules as a list of (lambda) functions</p> <pre><code>rules = [lambda s: any(x.isupper() for x in s), # must have at least one uppercase lambda s: any(x.islower() for x in s), # must have at least one lowercase lambda s: any(x.isdigit() for x in s), # must have at least one digit lambda s: len(s) &gt;= 7 # must be at least 7 characters ] if all(rule(s) for rule in rules): ... </code></pre> <p>Regarding your comment. To build an error message</p> <pre><code>errors = [] if not any(x.isupper() for x in password): errors.append('Your password needs at least 1 capital.') if not any(x.islower() for x in password): errors.append(...) ... if errors: print " ".join(errors) </code></pre>
27,313,872
Auto focus is not working for input field
<p>When I Press Login button one popup is shown.</p> <p>In that popup I need default autofocus on Login Input field. Can I achieve that with HTML5/CSS only?</p> <p><a href="http://jsfiddle.net/Raghava0330/6f9ge64f/" rel="noreferrer">jsfiddle</a></p> <pre><code>&lt;div class="main"&gt; &lt;div class="panel"&gt; &lt;a href="#login_form" id="login_pop" onclick=""&gt;Log In&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- popup form #1 --&gt; &lt;a href="#x" class="overlay" id="login_form"&gt;&lt;/a&gt; &lt;div class="popup"&gt; &lt;h2&gt;Welcome Guest!&lt;/h2&gt; &lt;p&gt;Please enter your login and password here&lt;/p&gt; &lt;div&gt; &lt;label for="login"&gt;Login&lt;/label&gt; &lt;input type="text" id="login" value="" autofocus /&gt; &lt;/div&gt; &lt;div&gt; &lt;label for="password"&gt;Password&lt;/label&gt; &lt;input type="password" id="password" value="" /&gt; &lt;/div&gt; &lt;input type="button" value="Log In" /&gt; &lt;a class="close" href="#close"&gt;&lt;/a&gt; &lt;/div&gt; </code></pre>
27,314,070
5
5
null
2014-12-05 10:32:15.137 UTC
5
2021-01-06 19:46:10.57 UTC
2014-12-05 10:36:47.447 UTC
null
295,783
null
3,982,787
null
1
31
html|css
65,815
<p><strong>The Answer is not really effectively (with certainty).</strong></p> <p>I would suggest Javascript, as <strong>UnskilledFreak</strong> mentioned, on every click the focus is set</p> <pre class="lang-html prettyprint-override"><code>... &lt;a href="#login_form" id="login_pop" onmouseup="document.getElementById('login').select();"&gt;Log In&lt;/a&gt; ... &lt;!-- not javascript library needed --&gt; &lt;!-- tested on Win7 and Chrome 37+ --&gt; </code></pre> <p>Here is your fiddle updated: <strong><a href="http://jsfiddle.net/6f9ge64f/2/" rel="noreferrer">http://jsfiddle.net/6f9ge64f/2/</a></strong></p> <p>You should probably also check key-input for people that don't use a mouse.</p> <p><strong>Update:</strong></p> <p>it's a bit hacky, but you could try</p> <pre class="lang-html prettyprint-override"><code>... &lt;a href="PATH-TO-FILE?c=1#login_form" id="login_pop" onmouseup="document.getElementById('login').select();"&gt;Log In&lt;/a&gt; ... &lt;input type="text" id="login" value="" autofocus /&gt; ... &lt;a class="close" href="PATH-TO-FILE?c=2#close"&gt;&lt;/a&gt; ... &lt;!-- tested with on Win7 and Chrome 37+ --&gt; </code></pre> <p>where the <code>PATH-TO-FILE</code> is for example <code>http://www.test.com/default.html</code> (absolute or relative), and the <code>?c=1</code> and <code>?c=2</code> is any parameter, just to provoke a reload. like this you could use <code>autofocus</code>.</p> <p>THIS WONT WORK IN JSFIDDLE since the HTML is embedded, but it works in the <strong>"real-world"</strong>.</p> <p><strong>Update 2:</strong></p> <pre class="lang-html prettyprint-override"><code>... &lt;a href="#login_form" id="login_pop" onmouseup="setTimeout(function(){document.getElementById('login').focus()},10);"&gt;Log In&lt;/a&gt; &lt;!-- tested with on Win7 and Chrome 37+ --&gt; ... </code></pre> <p>Here is the fiddle <strong><a href="http://jsfiddle.net/6f9ge64f/6/" rel="noreferrer">http://jsfiddle.net/6f9ge64f/6/</a></strong></p>
19,319,345
Dynamically get structure of a dynamic table
<p>I want to dynamically get the structure of a dynamic table. Getting the table is no problem, but I stuck with getting the structure of the table.</p> <pre><code>DATA: lo_dynamic_table TYPE REF TO data. FIELD-SYMBOLS: &lt;lt_table_structure&gt; TYPE table, &lt;ls_table_structure&gt; TYPE any. CREATE DATA lo_dynamic_table TYPE TABLE OF (lv_my_string_of_table). ASSIGN lo_dynamic_table-&gt;* TO &lt;lt_table_structure&gt;. // some code assigning the structure </code></pre> <p>Now I want to execute this command:</p> <pre><code>SELECT SINGLE * FROM (lv_my_string_of_table) INTO &lt;ls_table_structure&gt; WHERE (lv_dynamid_where_field). </code></pre> <p>If there is any other solution, I will be okay with that. </p>
19,362,055
3
4
null
2013-10-11 13:25:34.313 UTC
2
2020-12-26 18:43:33.03 UTC
2020-12-26 18:43:33.03 UTC
null
9,150,270
null
1,979,703
null
1
3
abap|internal-tables|rtts
45,090
<p>This code worked for my case:</p> <pre><code>DATA: table_name type string, lo_dynamic_table TYPE REF TO data, lo_dynamic_line TYPE REF TO data. FIELD-SYMBOLS: &lt;lt_table_structure&gt; TYPE table, &lt;ls_table_structure&gt; TYPE any. table_name = 'yourtablename'. CREATE DATA lo_dynamic_table TYPE TABLE OF (table_name). ASSIGN lo_dynamic_table-&gt;* TO &lt;lt_table_structure&gt;. CREATE DATA lo_dynamic_line LIKE LINE OF &lt;lt_table_structure&gt;. ASSIGN lo_dynamic_line-&gt;* TO &lt;ls_table_structure&gt;. </code></pre>
19,726,663
How to save the Pandas dataframe/series data as a figure?
<p>It sounds somewhat weird, but I need to save the Pandas console output string to png pics. For example:</p> <pre><code>&gt;&gt;&gt; df sales net_pft ROE ROIC STK_ID RPT_Date 600809 20120331 22.1401 4.9253 0.1651 0.6656 20120630 38.1565 7.8684 0.2567 1.0385 20120930 52.5098 12.4338 0.3587 1.2867 20121231 64.7876 13.2731 0.3736 1.2205 20130331 27.9517 7.5182 0.1745 0.3723 20130630 40.6460 9.8572 0.2560 0.4290 20130930 53.0501 11.8605 0.2927 0.4369 </code></pre> <p>Is there any way like <code>df.output_as_png(filename='df_data.png')</code> to generate a pic file which just display above content inside?</p>
39,358,752
7
4
null
2013-11-01 12:22:13.153 UTC
29
2022-01-21 15:40:48.78 UTC
null
null
null
null
1,072,888
null
1
47
python|matplotlib|pandas
73,541
<p><strong>Option-1:</strong> use matplotlib table functionality, with some additional styling:</p> <pre><code>import pandas as pd import numpy as np import matplotlib.pyplot as plt df = pd.DataFrame() df['date'] = ['2016-04-01', '2016-04-02', '2016-04-03'] df['calories'] = [2200, 2100, 1500] df['sleep hours'] = [8, 7.5, 8.2] df['gym'] = [True, False, False] def render_mpl_table(data, col_width=3.0, row_height=0.625, font_size=14, header_color='#40466e', row_colors=['#f1f1f2', 'w'], edge_color='w', bbox=[0, 0, 1, 1], header_columns=0, ax=None, **kwargs): if ax is None: size = (np.array(data.shape[::-1]) + np.array([0, 1])) * np.array([col_width, row_height]) fig, ax = plt.subplots(figsize=size) ax.axis('off') mpl_table = ax.table(cellText=data.values, bbox=bbox, colLabels=data.columns, **kwargs) mpl_table.auto_set_font_size(False) mpl_table.set_fontsize(font_size) for k, cell in mpl_table._cells.items(): cell.set_edgecolor(edge_color) if k[0] == 0 or k[1] &lt; header_columns: cell.set_text_props(weight='bold', color='w') cell.set_facecolor(header_color) else: cell.set_facecolor(row_colors[k[0]%len(row_colors) ]) return ax.get_figure(), ax fig,ax = render_mpl_table(df, header_columns=0, col_width=2.0) fig.savefig(&quot;table_mpl.png&quot;) </code></pre> <p><a href="https://i.stack.imgur.com/5582G.png" rel="noreferrer"><img src="https://i.stack.imgur.com/5582G.png" alt="enter image description here" /></a></p> <p><strong>Options-2</strong> Use Plotly + kaleido</p> <pre><code>import plotly.figure_factory as ff import pandas as pd df = pd.DataFrame() df['date'] = ['2016-04-01', '2016-04-02', '2016-04-03'] df['calories'] = [2200, 2100, 1500] df['sleep hours'] = [8, 7.5, 8.2] df['gym'] = [True, False, False] fig = ff.create_table(df) fig.update_layout( autosize=False, width=500, height=200, ) fig.write_image(&quot;table_plotly.png&quot;, scale=2) fig.show() </code></pre> <p><a href="https://i.stack.imgur.com/56khh.png" rel="noreferrer"><img src="https://i.stack.imgur.com/56khh.png" alt="enter image description here" /></a></p> <p>For the above, the <a href="https://plotly.com/python-api-reference/generated/plotly.graph_objects.Layout.html#plotly.graph_objects.layout.Annotation.font%0A" rel="noreferrer">font size</a> can be changed using the <code>font</code> attribute:</p> <pre><code>fig.update_layout( autosize=False, width=500, height=200, font={'size':8} ) </code></pre>
17,299,364
Insert row into Excel spreadsheet using openpyxl in Python
<p>I'm looking for the best approach for inserting a row into a spreadsheet using openpyxl.</p> <p>Effectively, I have a spreadsheet (Excel 2007) which has a header row, followed by (at most) a few thousand rows of data. I'm looking to insert the row as the first row of actual data, so after the header. My understanding is that the append function is suitable for adding content to <em>the end</em> of the file.</p> <p>Reading the documentation for both openpyxl and xlrd (and xlwt), I can't find any clear cut ways of doing this, beyond looping through the content manually and inserting into a new sheet (after inserting the required row). </p> <p>Given my so far limited experience with Python, I'm trying to understand if this is indeed the best option to take (the most pythonic!), and if so could someone provide an explicit example. Specifically can I read and write rows with openpyxl or do I have to access cells? Additionally can I (over)write the same file(name)?</p>
17,322,999
12
2
null
2013-06-25 14:00:19.8 UTC
4
2022-06-02 20:08:01.867 UTC
null
null
null
null
52,889
null
1
19
python|excel|xlrd|xlwt|openpyxl
95,410
<p>Answering this with the code that I'm now using to achieve the desired result. Note that I am manually inserting the row at position 1, but that should be easy enough to adjust for specific needs. You could also easily tweak this to insert more than one row, and simply populate the rest of the data starting at the relevant position.</p> <p>Also, note that due to downstream dependencies, we are manually specifying data from 'Sheet1', and the data is getting copied to a new sheet which is inserted at the beginning of the workbook, whilst renaming the original worksheet to 'Sheet1.5'.</p> <p>EDIT: I've also added (later on) a change to the format_code to fix issues where the default copy operation here removes all formatting: <code>new_cell.style.number_format.format_code = 'mm/dd/yyyy'</code>. I couldn't find any documentation that this was settable, it was more of a case of trial and error!</p> <p>Lastly, don't forget this example is saving over the original. You can change the save path where applicable to avoid this.</p> <pre><code> import openpyxl wb = openpyxl.load_workbook(file) old_sheet = wb.get_sheet_by_name('Sheet1') old_sheet.title = 'Sheet1.5' max_row = old_sheet.get_highest_row() max_col = old_sheet.get_highest_column() wb.create_sheet(0, 'Sheet1') new_sheet = wb.get_sheet_by_name('Sheet1') # Do the header. for col_num in range(0, max_col): new_sheet.cell(row=0, column=col_num).value = old_sheet.cell(row=0, column=col_num).value # The row to be inserted. We're manually populating each cell. new_sheet.cell(row=1, column=0).value = 'DUMMY' new_sheet.cell(row=1, column=1).value = 'DUMMY' # Now do the rest of it. Note the row offset. for row_num in range(1, max_row): for col_num in range (0, max_col): new_sheet.cell(row = (row_num + 1), column = col_num).value = old_sheet.cell(row = row_num, column = col_num).value wb.save(file) </code></pre>
36,876,158
Gradle DSL method not found: 'apt()'
<p>I am trying to add the latest version of butterknife and I get this error from gradle:</p> <blockquote> <p>Error:(31, 0) Gradle DSL method not found: 'apt()' Possible causes:<li>The project 'MyProject' may be using a version of Gradle that does not contain the method. Gradle settings</li><li>The build file may be missing a Gradle plugin. Apply Gradle plugin</li></p> </blockquote> <p>Where my gradle <code>mobile</code> <code>build.gradle</code> is:</p> <pre><code>plugins { id "net.ltgt.apt" version "0.6" } apply plugin: 'com.android.application' android { compileSdkVersion 23 buildToolsVersion "23.0.2" defaultConfig { applicationId "com.mynamspace.myproject" minSdkVersion 19 targetSdkVersion 23 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) wearApp project(':wear') testCompile 'junit:junit:4.12' compile 'com.jakewharton:butterknife:8.0.0' apt 'com.jakewharton:butterknife-compiler:8.0.0' compile 'com.android.support:appcompat-v7:23.3.0' compile 'com.google.android.gms:play-services:8.4.0' compile 'com.android.support:design:23.3.0' compile 'com.android.support:support-v4:23.3.0' compile 'com.android.support:recyclerview-v7:23.3.0' } </code></pre> <p><strong>What's wrong with the gradle-apt-plugin?</strong></p>
36,876,597
5
3
null
2016-04-26 21:31:50.08 UTC
6
2017-12-04 10:32:00.19 UTC
null
null
null
null
1,227,166
null
1
46
android|gradle|butterknife
25,656
<p>It's entirely possible that there's a way to get your <code>plugins</code> to work. Given your error, I'd start by following what the ButterKnife project uses, get that working, then see if there is a recipe for what you're trying.</p> <p>First, in <a href="https://github.com/JakeWharton/butterknife/blob/master/build.gradle" rel="noreferrer">your top-level <code>build.gradle</code> file</a>, include <code>classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'</code> in the <code>buildscript</code> <code>dependencies</code>, such as:</p> <pre><code> buildscript { repositories { mavenCentral() } dependencies { classpath 'com.android.tools.build:gradle:2.0.0' classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8' } } </code></pre> <p>Then, in <a href="https://github.com/JakeWharton/butterknife/blob/master/butterknife-sample/build.gradle" rel="noreferrer">your module's <code>build.gradle</code> file</a>, include <code>apply plugin: 'com.neenbedankt.android-apt'</code> towards the top.</p> <p>The links are to the relevant files from the ButterKnife GitHub repo, from the project and the dedicated sample app.</p>
18,371,883
How to create modal dialog box in android
<p>i want create modal dialog box for my application.</p> <p>so when modal dialog box open the other activities are blocked. no event are done like back button press or home button press.</p> <p>and put two option button in that dialog box cancel and ok.</p> <p>Thank you...</p>
18,371,940
4
5
null
2013-08-22 04:50:15.767 UTC
8
2014-06-04 05:03:42.723 UTC
null
null
null
null
1,835,231
null
1
21
android|modal-dialog|android-ui
62,485
<p>There are many kind of <code>Dialogs</code> in Android. Please take a look at <a href="http://developer.android.com/guide/topics/ui/dialogs.html" rel="noreferrer">Dialogs</a>. I guess what you are looking for is something like <code>AlertDialog</code> . This is the example of how you can implement on <code>BackPress</code> button. </p> <pre><code>@Override public void onBackPressed() { AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.setTitle("Do you want to logout?"); // alert.setMessage("Message"); alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { //Your action here } }); alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }); alert.show(); } </code></pre>
18,698,481
Error in SQL script: Only one statement is allowed per batch
<p>I have 4 sql scripts that I want to run in a DACPAC in PostDeployment, but when I try to build the VS project for 3 of them I get this error:</p> <pre><code>Only one statement is allowed per batch. A batch separator, such as 'GO', might be required between statements. </code></pre> <p>The scripts contain only <code>INSERT</code> statements in different tables on the DB. And all of them are structured like so</p> <pre><code>IF NOT EXISTS (SELECT 1 FROM dbo.Criteria WHERE Name = 'Mileage') INSERT INTO dbo.Criteria(Name) VALUES ('Mileage'); </code></pre> <p>only on different tables and with different data.</p> <p>My question is why is VS complaining about 3 of them when all the scripts are the same in terms of syntax and operations?</p> <p>PS: Adding 'GO' between statements as the error suggests doesn't do anything.</p>
18,698,850
4
0
null
2013-09-09 12:42:35.663 UTC
14
2020-11-20 20:39:56.597 UTC
2014-02-05 11:56:09.14 UTC
null
1,047,998
null
2,208,114
null
1
161
sql|sql-server|visual-studio-2012|dacpac
56,400
<p>I have found the problem. When I added the file in VS I forgot to set <code>Build Action = None</code> from the file properties. So changing that fixed the problem and the project now compiles.</p>
18,733,965
Annoying message when opening windows from Python on OS X 10.8
<p>Whenever I run a Python script that opens any kind of window on OS X 10.8, whether it's a GLUT window or a QT one or anything else, I get a message that looks like this:</p> <pre><code>2013-09-11 14:36:53.321 Python[3027:f07] ApplePersistenceIgnoreState: Existing state will not be touched. New state will be written to /var/folders/0x/25_70mj17tb1ypm1c_js8jd40000gq/T/org.python.python.savedState </code></pre> <p>I use python2.7 installed via MacPorts.</p> <p>This is a minor annoyance, but I'm curious to know what the message means, and whether there's anything I can do to prevent it. Is it due to a misconfiguration of my system, or does everyone get this?</p>
21,567,601
4
5
null
2013-09-11 06:18:46.81 UTC
19
2022-03-10 16:06:30.347 UTC
null
null
null
null
1,119,340
null
1
34
python|macos|osx-mountain-lion
18,525
<p>Answering my own question, with thanks to @Steve Barnes for giving me a hint. It seems this problem can be solved with the terminal command</p> <pre><code>$ defaults write org.python.python ApplePersistenceIgnoreState NO </code></pre> <p>In the comments, Greg Coladonato reports that, in 2020, running Python 3, this may need to be changed to</p> <pre><code>$ defaults write org.python.python3 ApplePersistenceIgnoreState NO </code></pre> <p>I am not sure exactly how this command operates, but having done it some time ago I have observed no ill effects.</p> <p>Note however, that another user has pointed out that this can cause a bug with python 3.4 on mountain lion where tkinter dialogs do not close when a button is pressed as one would expect.</p> <pre><code>$ defaults write org.python.python ApplePersistenceIgnoreState YES </code></pre> <p>will undo the command if you experience problems. (Replacing <code>org.python.python</code> with <code>org.python.python3</code> if needed.)</p>
12,099,170
Set session/cookie for 24hs to show something only once per day to users
<p>I've been searching for the last hour how to do this... I think it's pretty easy, but couldn't make it work. </p> <p>I want to show something (AdSense) only once per day.</p> <p>I don't know what would be the best way, if using cookies or PHP Sessions. In any case, can you help me and tell me how could I do this?</p> <p>Thanks in advance!</p> <p>Santiago</p> <p>Edit: I think this way I can create the Session, but I don't know how to "recreate" it each 24 hours and how to check for that session in order to show what I want to show once a day.</p> <pre><code>if (!isset($_SESSION['adSense']) $_SESSION['adSense'] = time(); if (time() - $_SESSION['adSense'] &lt;= 60*60*24 ) { return true; } else { return false; } </code></pre>
12,099,238
3
3
null
2012-08-23 20:06:51.7 UTC
3
2016-12-12 15:48:02.083 UTC
2016-12-12 15:48:02.083 UTC
null
1,593,322
null
466,318
null
1
4
php|session|cookies
42,370
<p>Sessions will expire when the user leaves the site, using cookies is what you want:</p> <pre><code>&lt;? if (!isset($_COOKIE['showstuff'])): ?&gt; &lt;!-- replace this whatever you want to show --&gt; &lt;? setcookie('showstuff', true, time()+86400); // 1 day ?&gt; &lt;? endif; ?&gt; </code></pre>
5,039,324
Creating a procedure in mySql with parameters
<p>I am trying to make a stored procedure using mySQL. This procedure will validate a username and a password. I'm currently running mySQL 5.0.32 so it should be possible to create procedures.</p> <p>Heres the code I've used. All I get is an SQL syntax error. </p> <pre><code> GO CREATE PROCEDURE checkUser (IN @brugernavn varchar(64)),IN @password varchar(64)) BEGIN SELECT COUNT(*) FROM bruger WHERE bruger.brugernavn=@brugernavn AND bruger.pass=@Password; END; </code></pre> <p>Thank you in advance</p>
5,039,488
3
0
null
2011-02-18 08:59:15.087 UTC
7
2019-01-09 03:23:56.643 UTC
2014-04-06 19:51:07.383 UTC
null
615,421
null
615,421
null
1
46
mysql|parameters|procedure
149,533
<p>I figured it out now. Here's the correct answer</p> <pre><code>CREATE PROCEDURE checkUser ( brugernavn1 varchar(64), password varchar(64) ) BEGIN SELECT COUNT(*) FROM bruger WHERE bruger.brugernavn=brugernavn1 AND bruger.pass=password; END; </code></pre> <p>@ points to a global var in mysql. The above syntax is correct.</p>
9,128,737
Fastest way to set all values of an array?
<p>I have a <code>char []</code>, and I want to set the value of every index to the same <code>char</code> value.<br> There is the obvious way to do it (iteration):</p> <pre><code> char f = '+'; char [] c = new char [50]; for(int i = 0; i &lt; c.length; i++){ c[i] = f; } </code></pre> <p>But I was wondering if there's a way that I can utilize <code>System.arraycopy</code> or something equivalent that would bypass the need to iterate. Is there a way to do that?</p> <p><strong>EDIT :</strong> From <code>Arrays.java</code></p> <pre><code>public static void fill(char[] a, int fromIndex, int toIndex, char val) { rangeCheck(a.length, fromIndex, toIndex); for (int i = fromIndex; i &lt; toIndex; i++) a[i] = val; } </code></pre> <p>This is exactly the same process, which shows that there might not be a better way to do this. <br>+1 to everyone who suggested <code>fill</code> anyway - you're all correct and thank you.</p>
9,128,762
14
5
null
2012-02-03 12:33:00.307 UTC
16
2020-03-06 09:07:09.95 UTC
2012-02-03 12:41:33.47 UTC
null
828,867
null
828,867
null
1
88
java|arrays
207,878
<p>Try <code>Arrays.fill(c, f)</code> : <a href="http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#fill%28char%5B%5D,%20char%29">Arrays javadoc</a></p>
18,495,672
How to iterate over worksheets in workbook, openpyxl
<p>I've been using the openpyxl module to do some processing on some .xlsx files. I've been trying to figure out how to iterate over sheets in a workbook. I'm not sure if I can get it figured out. I've tried the 2 codes below which both return empty results. My .xlsx file has about 20 sheets, so something should return. </p> <p>The one thing I couldn't find on the internet, is how to set a workbook to an actual workbook. Usually I am writing to a workbook, so I just initialize it by setting a variable to en empty workbook <code>workbook = Workbook()</code> but in this case, I am unsure if I can open a workbook by doing <code>workbook = Workbook(r"C:\Excel\LOOKUP_TABLES_edited.xlsx")</code></p> <p>If anyone can identify what it is I am doing wrong, I would appreciate it.</p> <p>Here is my code:</p> <pre><code>workbook = Workbook(r"C:\Excel\LOOKUP_TABLES_edited.xlsx") for sheet in workbook.worksheets: print sheet # or for sheet in workbook.worksheets: print sheet.title </code></pre>
18,495,707
4
0
null
2013-08-28 18:34:30.76 UTC
3
2022-05-20 02:40:01.667 UTC
2013-08-28 18:42:31.773 UTC
null
771,848
null
820,088
null
1
22
python|excel|openpyxl
50,624
<p>Open the workbook via <a href="https://openpyxl.readthedocs.io/en/stable/usage.html#read-an-existing-workbook" rel="nofollow noreferrer">load_workbook()</a> and iterate over <code>worksheets</code>:</p> <pre><code>from openpyxl import load_workbook wb = load_workbook(r&quot;C:\Excel\LOOKUP_TABLES_edited.xlsx&quot;) for sheet in wb.worksheets: print(sheet) </code></pre>
18,266,637
Why does System.IO.File.Exists(string path) return false?
<pre><code>System.IO.File.Exists(string path) </code></pre> <p>returns always false, even when the file exists on the specified path. What could be the possible solution?</p>
18,266,662
13
2
null
2013-08-16 05:51:28.053 UTC
9
2022-08-23 14:43:52.837 UTC
2016-01-15 15:46:20.263 UTC
null
63,550
null
2,572,551
null
1
44
c#|file|io
76,387
<p>It could well be a permission problem. From the <a href="http://msdn.microsoft.com/en-us/library/system.io.file.exists.aspx" rel="noreferrer">documentation</a>:</p> <blockquote> <p>The Exists method returns false if any error occurs while trying to determine if the specified file exists. This can occur in situations that raise exceptions such as passing a file name with invalid characters or too many characters, a failing or missing disk, or if the caller does not have permission to read the file.</p> </blockquote> <p>One way of seeing what's happening is to just try to read the file (e.g. with <code>File.OpenRead</code>). I'd be surprised if that <em>succeeds</em> - but if it fails, the exception should give you more information.</p>
20,277,449
Bootstrap 3: Set custom width with input-group/input-group-addon and horizontal labels
<p>I would like to control the size of my input elements using the class <code>.col-lg-*</code> outlined <a href="http://getbootstrap.com/css/#forms-control-sizes" rel="noreferrer">here</a> on the bootstrap website. However, putting the <code>&lt;span&gt;</code> element inside of a div completely messes it up:</p> <p><strong>HTML with div:</strong></p> <pre><code>&lt;div class="input-group input-group-lg"&gt; &lt;label for="" class="control-label"&gt;Paycheck&lt;/label&gt; &lt;div class="col-lg-10"&gt; &lt;span class="input-group-addon"&gt;$&lt;/span&gt; &lt;input type="text" class="form-control" id=""&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p><img src="https://i.stack.imgur.com/GdLbP.png" alt="HTML with div"></p> <p><strong>How can I set the width of the input elements so that they are all the same?</strong> </p> <p>I want the left margin of each input element to be flush like so:</p> <p><img src="https://i.stack.imgur.com/UnaSk.png" alt="lined-up input elements"></p> <p>This is what it looks like now:</p> <p><img src="https://i.stack.imgur.com/poCAM.png" alt="current state"></p> <p>This is my current HTML:</p> <pre><code> &lt;div class="col-md-6"&gt; &lt;div class="content"&gt; &lt;h2&gt;Income&lt;/h2&gt; &lt;form class="form-income form-horizontal" role="form"&gt; &lt;div class="input-group input-group-lg"&gt; &lt;label for="" class="control-label"&gt;Paycheck&lt;/label&gt; &lt;span class="input-group-addon"&gt;$&lt;/span&gt; &lt;input type="text" class="form-control" id=""&gt; &lt;/div&gt; &lt;div class="input-group input-group-lg"&gt; &lt;label for="" class="control-label"&gt;Investments&lt;/label&gt; &lt;span class="input-group-addon"&gt;$&lt;/span&gt; &lt;input type="text" class="form-control" id=""&gt; &lt;/div&gt; &lt;div class="input-group input-group-lg"&gt; &lt;label for="" class="control-label"&gt;Other&lt;/label&gt; &lt;span class="input-group-addon"&gt;$&lt;/span&gt; &lt;input type="text" class="form-control" id=""&gt; &lt;/div&gt; &lt;button class="btn btn-lg btn-primary btn-block" type="submit"&gt;Update&lt;/button&gt; &lt;/form&gt; &lt;/div&gt; </code></pre> <h2>LIVE EXAMPLE: <a href="http://jsfiddle.net/jfXUr/" rel="noreferrer">http://jsfiddle.net/jfXUr/</a></h2>
20,278,063
1
2
null
2013-11-29 02:26:40.64 UTC
2
2013-11-29 03:48:43.92 UTC
2013-11-29 02:59:32.283 UTC
null
1,751,883
null
1,751,883
null
1
7
html|css|forms|twitter-bootstrap|twitter-bootstrap-3
41,429
<p>As per my comment above, try grouping the label and <code>.input-group</code> together with a <code>.form-group</code> container.</p> <pre><code>&lt;div class="form-group"&gt; &lt;label for="" class="control-label"&gt;Paycheck&lt;/label&gt; &lt;div class="input-group input-group-lg"&gt; &lt;span class="input-group-addon"&gt;$&lt;/span&gt; &lt;input type="text" class="form-control" id=""&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Demo here - <a href="http://jsfiddle.net/jfXUr/1/" rel="noreferrer">http://jsfiddle.net/jfXUr/1/</a></p>
19,918,213
WCF Exception: Could not find a base address that matches scheme http for the endpoint
<p>I'm trying to host a WCF web service on a separate Website in IIS with https at 443 as the only binding. </p> <p>The following configurations works well when I use it in a website which uses both the bindings (http(80) / https(443)). If I remove the http binding, it starts throwing the following error.</p> <p><em><strong>Could not find a base address that matches scheme http for the endpoint with binding BasicHttpBinding. Registered base address schemes are [https].</em></strong></p> <p><strong>How do I make it work in an IIS website with https binding only?</strong></p> <pre><code> &lt;system.serviceModel&gt; &lt;bindings&gt; &lt;basicHttpBinding&gt; &lt;binding name="defaultBasicHttpBinding"&gt; &lt;security mode="Transport"&gt; &lt;transport clientCredentialType="None" proxyCredentialType="None" realm=""/&gt; &lt;message clientCredentialType="Certificate" algorithmSuite="Default" /&gt; &lt;/security&gt; &lt;/binding&gt; &lt;/basicHttpBinding&gt; &lt;/bindings&gt; &lt;client&gt; &lt;endpoint address="http://localhost/ERPService/retailPayment.svc" binding="basicHttpBinding" bindingConfiguration="defaultBasicHttpBinding" contract="RetailPaymentService.RetailPayment.SVRetailPaymentService" name="EnterpriseRetailPayment" /&gt; &lt;/client&gt; &lt;behaviors&gt; &lt;serviceBehaviors&gt; &lt;behavior name="MyServiceTypeBehaviors"&gt; &lt;serviceMetadata httpGetEnabled="true" /&gt; &lt;serviceDebug includeExceptionDetailInFaults="true" /&gt; &lt;/behavior&gt; &lt;behavior&gt; &lt;serviceMetadata httpGetEnabled="true" /&gt; &lt;serviceDebug includeExceptionDetailInFaults="true" /&gt; &lt;/behavior&gt; &lt;/serviceBehaviors&gt; &lt;endpointBehaviors&gt; &lt;behavior name="MyEndPointBehavior"&gt; &lt;!--&lt;SchemaValidator enabled="true"/&gt;--&gt; &lt;/behavior&gt; &lt;/endpointBehaviors&gt; &lt;/behaviors&gt; &lt;services&gt; &lt;service name="SettlementSalesCollection.SaleItemService" behaviorConfiguration="MyServiceTypeBehaviors"&gt; &lt;endpoint behaviorConfiguration="MyEndPointBehavior" binding="basicHttpBinding" name="SettlementSalesCollection" contract="SettlementSalesCollection.CITransactionSettlementListenerService" /&gt; &lt;endpoint name="mexEndpoint" contract="IMetadataExchange" binding="mexHttpBinding" address="mex" /&gt; &lt;/service&gt; &lt;/services&gt; &lt;extensions&gt; &lt;behaviorExtensions&gt; &lt;add name="SchemaValidator" type="SettlementSalesCollection.SchemaValidation.SchemaValidationBehavior+CustomBehaviorSection, SettlementSalesCollectionService, Version=1.0.0.0, Culture=neutral" /&gt; &lt;/behaviorExtensions&gt; &lt;/extensions&gt; &lt;protocolMapping&gt; &lt;add binding="basicHttpsBinding" scheme="https" /&gt; &lt;/protocolMapping&gt; &lt;serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" /&gt; &lt;/system.serviceModel&gt; </code></pre>
19,920,676
9
3
null
2013-11-11 23:41:46.86 UTC
4
2021-10-18 07:41:33.993 UTC
null
null
null
null
424,279
null
1
31
c#|wcf|web-services
170,560
<p>Your configuration should look similar to that. You may have to change <code>&lt;transport clientCredentialType="None" proxyCredentialType="None" /&gt;</code> depending on your needs for authentication. The config below doesn't require any authentication.</p> <pre><code>&lt;bindings&gt; &lt;basicHttpBinding&gt; &lt;binding name="basicHttpBindingConfiguration"&gt; &lt;security mode="Transport"&gt; &lt;transport clientCredentialType="None" proxyCredentialType="None" /&gt; &lt;/security&gt; &lt;/binding&gt; &lt;/basicHttpBinding&gt; &lt;/bindings&gt; &lt;services&gt; &lt;service name="XXX"&gt; &lt;endpoint name="AAA" address="" binding="basicHttpBinding" bindingConfiguration="basicHttpBindingConfiguration" contract="YourContract" /&gt; &lt;/service&gt; &lt;services&gt; </code></pre> <p>That will allow a WCF service with <code>basicHttpBinding</code> to use HTTPS.</p>
15,421,669
Set Jquery ui active tab on page load/reload
<p>I'm using a basic implementation of Jquery UI Tabs that are working fine but I want to set (or reset) the active tab dynamically based on a user action. </p> <ol> <li><p>How can I set the active tab based on a querystring value? With my previous tab solution I was able to pass a querystring value and set the active tab when the page loaded. (I had to abandon this older solution due to other technical challenges.)</p></li> <li><p>When the user selects the Save button in my browser application, and the browser page reloads, how can I maintain focus on the tab they were on before they pressed save?</p></li> <li><p>How can I set the active tab when a user returns to the Tasks page of my browser application? For example, all within my web application, if the user browses to the Projects page and then returns to the Task page, how can I reset the tab they were previously on?</p></li> </ol> <p>Javascript:</p> <pre><code>$(function() { $("#tabs").tabs(); }); </code></pre> <p>HTML Example code:</p> <pre><code>&lt;div id="tabs"&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="#tabs-1"&gt;Description&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#tabs-2"&gt;Action&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#tabs-3"&gt;Resources&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#tabs-4"&gt;Settings&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;div id="tabs-1"&gt; &lt;p&gt;Description content&lt;/p&gt; &lt;/div&gt; &lt;div id="tabs-2"&gt; &lt;p&gt;Action content&lt;/p&gt; &lt;/div&gt; &lt;div id="tabs-3"&gt; &lt;p&gt;Resources content&lt;/p&gt; &lt;/div&gt; &lt;div id="tabs-4"&gt; &lt;p&gt;Settings &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; </code></pre>
15,549,826
3
1
null
2013-03-14 22:48:11.84 UTC
3
2015-02-18 17:44:25.323 UTC
null
null
null
null
1,405,736
null
1
9
javascript|jquery|jsp
57,014
<p>I solved my own jQuery tab issues after additional research and trial and error. Here's a working example. I don't know if this is the most elegant solution but it works. I hope this helps.</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;link rel="stylesheet" type="text/css" href="css/redmond/jquery-ui-1.10.1.custom.min.css"&gt; &lt;script language="javascript" type="text/javascript" src="js/jquery/jquery-1.9.1.js"&gt;&lt;/script&gt; &lt;script language="javascript" type="text/javascript" src="js/jquery/jquery-ui-1.10.1.custom.min.js"&gt;&lt;/script&gt; &lt;script language="javascript" type="text/javascript"&gt; $(document).ready(function() { $("#tabs").tabs({active: document.tabTest.currentTab.value}); $('#tabs a').click(function(e) { var curTab = $('.ui-tabs-active'); curTabIndex = curTab.index(); document.tabTest.currentTab.value = curTabIndex; }); }); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;form name="tabTest" method="post" action="tab"&gt; &lt;!-- default tab value 2 for Tab 3 --&gt; &lt;input type="hidden" name="currentTab" value="2"/&gt; &lt;div id="tabs"&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="#tabs-1"&gt;Tab 1&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#tabs-2"&gt;Tab 2&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#tabs-3"&gt;Tab 3&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;div id="tabs-1"&gt;Tab 1 Content&lt;/div&gt; &lt;div id="tabs-2"&gt;Tab 2 Content&lt;/div&gt; &lt;div id="tabs-3"&gt;Tab 3 Content&lt;/div&gt; &lt;/div&gt; &lt;/form&gt; &lt;/body&gt; </code></pre> <p></p> <p>Here's how I answered each of my previous questions.</p> <p><strong>1. How can I set the active tab based on a querystring value?</strong> I ended up not needing to use a querystring. I added the #tabs-x to the end of my url. For example, if I wanted a link directly to Tab 3 I coded a link as:</p> <pre><code>localhost:8080/pm/detail?prjID=2077#tabs-3 </code></pre> <p><strong>2. When the user selects the Save button in my browser application, and the browser page reloads, how can I maintain focus on the tab they were on before they pressed save?</strong></p> <p>I solved this by capturing the click event, getting the current tab index and then setting a hidden forms element "currentTab" to store the current tab value. Then back in the Java Servlet I retrieved the hidden forms elements and reset it when the page reloads.</p> <pre><code>$(document).ready(function() { // Set active tab on page load $("#tabs").tabs({active: document.tabTest.currentTab.value}); // Capture current tab index. Remember tab index starts at 0 for tab 1. $('#tabs a').click(function(e) { var curTab = $('.ui-tabs-active'); curTabIndex = curTab.index(); document.tabTest.currentTab.value = curTabIndex; }); }); </code></pre> <p><strong>3. How can I set the active tab when a user returns to the Project page of my browser application? For example, all within my web application, if the user browses to the Task page and then returns to the Project page, how can I reset the tab they were previously on?</strong></p> <p>This is solved by setting a session variable in my Java Servlet to store the hidden forms element "currentTab". That way when I return the Project page, I can reset the "currentTab" value the same way I set it in the Save forms action.</p> <p>I hope this example can help someone else with their jQuery tab issues!</p>
15,138,406
How can I replace or remove HTML entities like "&nbsp;" using BeautifulSoup 4
<p>I am processing HTML using Python and the BeautifulSoup 4 library and I can't find an obvious way to replace <code>&amp;nbsp;</code> with a space. Instead it seems to be converted to a Unicode non-breaking space character.</p> <p>Am I missing something obvious? What is the best way to replace &amp;nbsp; with a normal space using BeautifulSoup?</p> <p>Edit to add that I am using the latest version, BeautifulSoup 4, so the <code>convertEntities=BeautifulSoup.HTML_ENTITIES</code> option in Beautiful Soup 3 isn't available.</p>
15,138,729
5
2
null
2013-02-28 14:47:15.257 UTC
7
2021-06-08 13:19:54.697 UTC
2013-02-28 14:49:57.967 UTC
null
274,350
null
274,350
null
1
23
python|beautifulsoup
44,151
<p>See <a href="http://www.crummy.com/software/BeautifulSoup/bs4/doc/#entities" rel="noreferrer">Entities</a> in the documentation. BeautifulSoup 4 produces proper Unicode for all entities:</p> <blockquote> <p>An incoming HTML or XML entity is always converted into the corresponding Unicode character.</p> </blockquote> <p>Yes, <code>&amp;nbsp;</code> is turned into a non-breaking space character. If you really want those to be space characters instead, you'll have to do a unicode replace.</p>
45,101,045
Why use purrr::map instead of lapply?
<p>Is there any reason why I should use</p> <pre><code>map(&lt;list-like-object&gt;, function(x) &lt;do stuff&gt;) </code></pre> <p>instead of</p> <pre><code>lapply(&lt;list-like-object&gt;, function(x) &lt;do stuff&gt;) </code></pre> <p>the output should be the same and the benchmarks I made seem to show that <code>lapply</code> is slightly faster (it should be as <code>map</code> needs to evaluate all the non-standard-evaluation input).</p> <p>So is there any reason why for such simple cases I should actually consider switching to <code>purrr::map</code>? I am not asking here about one's likes or dislikes about the syntax, other functionalities provided by purrr etc., but strictly about comparison of <code>purrr::map</code> with <code>lapply</code> assuming using the standard evaluation, i.e. <code>map(&lt;list-like-object&gt;, function(x) &lt;do stuff&gt;)</code>. Is there any advantage that <code>purrr::map</code> has in terms of performance, exception handling etc.? The comments below suggest that it does not, but maybe someone could elaborate a little bit more?</p>
47,123,420
4
15
null
2017-07-14 10:45:36.643 UTC
125
2022-08-08 06:14:12.407 UTC
2022-08-08 06:14:12.407 UTC
null
14,853,907
null
3,986,320
null
1
232
r|lapply|purrr
48,419
<p>If the only function you're using from purrr is <code>map()</code>, then no, the advantages are not substantial. As Rich Pauloo points out, the main advantage of <code>map()</code> is the helpers which allow you to write compact code for common special cases:</p> <ul> <li><p><code>~ . + 1</code> is equivalent to <code>function(x) x + 1</code> (and <code>\(x) x + 1</code> in R-4.1 and newer)</p> </li> <li><p><code>list(&quot;x&quot;, 1)</code> is equivalent to <code>function(x) x[[&quot;x&quot;]][[1]]</code>. These helpers are a bit more general than <code>[[</code> - see <code>?pluck</code> for details. For <a href="https://speakerdeck.com/jennybc/data-rectangling" rel="noreferrer">data rectangling</a>, the <code>.default</code> argument is particularly helpful.</p> </li> </ul> <p>But most of the time you're not using a single <code>*apply()</code>/<code>map()</code> function, you're using a bunch of them, and the advantage of purrr is much greater consistency between the functions. For example:</p> <ul> <li><p>The first argument to <code>lapply()</code> is the data; the first argument to <code>mapply()</code> is the function. The first argument to all map functions is always the data.</p> </li> <li><p>With <code>vapply()</code>, <code>sapply()</code>, and <code>mapply()</code> you can choose to suppress names on the output with <code>USE.NAMES = FALSE</code>; but <code>lapply()</code> doesn't have that argument.</p> </li> <li><p>There's no consistent way to pass consistent arguments on to the mapper function. Most functions use <code>...</code> but <code>mapply()</code> uses <code>MoreArgs</code> (which you'd expect to be called <code>MORE.ARGS</code>), and <code>Map()</code>, <code>Filter()</code> and <code>Reduce()</code> expect you to create a new anonymous function. In map functions, constant argument always come after the function name.</p> </li> <li><p>Almost every purrr function is type stable: you can predict the output type exclusively from the function name. This is not true for <code>sapply()</code> or <code>mapply()</code>. Yes, there is <code>vapply()</code>; but there's no equivalent for <code>mapply()</code>.</p> </li> </ul> <p>You may think that all of these minor distinctions are not important (just as some people think that there's no advantage to stringr over base R regular expressions), but in my experience they cause unnecessary friction when programming (the differing argument orders always used to trip me up), and they make functional programming techniques harder to learn because as well as the big ideas, you also have to learn a bunch of incidental details.</p> <p>Purrr also fills in some handy map variants that are absent from base R:</p> <ul> <li><p><code>modify()</code> preserves the type of the data using <code>[[&lt;-</code> to modify &quot;in place&quot;. In conjunction with the <code>_if</code> variant this allows for (IMO beautiful) code like <code>modify_if(df, is.factor, as.character)</code></p> </li> <li><p><code>map2()</code> allows you to map simultaneously over <code>x</code> and <code>y</code>. This makes it easier to express ideas like <code>map2(models, datasets, predict)</code></p> </li> <li><p><code>imap()</code> allows you to map simultaneously over <code>x</code> and its indices (either names or positions). This is makes it easy to (e.g) load all <code>csv</code> files in a directory, adding a <code>filename</code> column to each.</p> <pre><code>dir(&quot;\\.csv$&quot;) %&gt;% set_names() %&gt;% map(read.csv) %&gt;% imap(~ transform(.x, filename = .y)) </code></pre> </li> <li><p><code>walk()</code> returns its input invisibly; and is useful when you're calling a function for its side-effects (i.e. writing files to disk).</p> </li> </ul> <p>Not to mention the other helpers like <code>safely()</code> and <code>partial()</code>.</p> <p>Personally, I find that when I use purrr, I can write functional code with less friction and greater ease; it decreases the gap between thinking up an idea and implementing it. But your mileage may vary; there's no need to use purrr unless it actually helps you.</p> <h2>Microbenchmarks</h2> <p>Yes, <code>map()</code> is slightly slower than <code>lapply()</code>. But the cost of using <code>map()</code> or <code>lapply()</code> is driven by what you're mapping, not the overhead of performing the loop. The microbenchmark below suggests that the cost of <code>map()</code> compared to <code>lapply()</code> is around 40 ns per element, which seems unlikely to materially impact most R code.</p> <pre><code>library(purrr) n &lt;- 1e4 x &lt;- 1:n f &lt;- function(x) NULL mb &lt;- microbenchmark::microbenchmark( lapply = lapply(x, f), map = map(x, f) ) summary(mb, unit = &quot;ns&quot;)$median / n #&gt; [1] 490.343 546.880 </code></pre>
8,172,246
what is the meaning of "warning : No new line at end of file"?
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/72271/no-newline-at-end-of-file-compiler-warning">&ldquo;No newline at end of file&rdquo; compiler warning</a> </p> </blockquote> <p>i am a Linux user and use gcc at work But at home i have installed cygwin package and using its <code>gcc</code> on my windows machine.</p> <p>when ever i make any .c file and run its shows following warning </p> <pre><code>Warning : No new line at end of file </code></pre> <p>when i add extra new line at the end of that c file warning disappeared. i haven't faced such warning while working with gcc in Linux.</p> <p>so </p> <p><strong>why i am getting this warning? what does it mean ?</strong></p> <p><strong>Edit</strong> </p> <p>Whats the need or whats the advantage of doing this ?</p> <p>if it is part of c programming standard then why it doesnt give any error while working in linux ?</p>
8,172,281
2
4
null
2011-11-17 18:20:13.813 UTC
3
2011-11-17 18:55:48.463 UTC
2017-05-23 12:00:28.85 UTC
null
-1
null
775,964
null
1
6
c|windows|linux|gcc|cygwin
43,744
<p>The C language requires that every source file must end with a newline (from C99 5.1.1.2/1):</p> <blockquote> <p>A source file that is not empty shall end in a new-line character, which shall not be immediately preceded by a backslash character before any such splicing takes place.</p> </blockquote> <p>(C++ also had this requirement prior to C++11)</p>
7,706,449
Android App Strategy for keeping track of a login session
<p>I have some PHP script that logs in and returns a JSON array with a session ID if the login was successful.</p> <p>In my app, I want to login at the front page and continue out through the app being logged in. I created a singleton class that holds a session ID (along with a few other fields) received from the JSON from the PHP page. This singleton object's field "session_id" gets checked depending on what the user does. </p> <p>If the user wants to log out, then the session_id just gets set to null thus logging out. </p> <p>I also use the HttpURLConnection library to POST the username/password when logging in.</p> <p>Is this a decent enough approach for handling this situation? </p>
7,706,667
2
1
null
2011-10-09 20:45:36.77 UTC
9
2013-11-14 13:10:55.86 UTC
2013-11-14 13:10:55.86 UTC
null
675,552
null
838,092
null
1
8
java|android|session|authentication|httpurlconnection
15,179
<p>Here are some things you should think about:</p> <ul> <li>Once you have authenticated the user and stored the session_id locally, send the session_id in the header of each of your http requests. That way, you're not sending the credentials with each request, but the session id. And if something happens on the server side to the session, the transaction will not be allowed.</li> <li>When logging out, don't just delete the session_id on your app (client) side. Send a logout to the server as well so that the session can be killed server side.</li> <li>If the session is killed on the server side, you'll want to do 1 of 2 things A) prompt the user to re-login. B) Use the store credentials to log back in, create a new session id and store it again in your singleton.</li> </ul> <p>This will guarantee a bit more security and functionality than just clearing the session id on your app side.</p>
7,790,141
Is security-constraint configuration for Tomcat mandatory?
<p>In order to do an SSL Configuration testing under Tomcat, is this all mandatory?</p> <p>This below line is taken from a <a href="https://oliverniu.wordpress.com/2012/01/17/setting-up-ssl-on-tomcat-in-3-easy-steps/" rel="noreferrer">website</a>:</p> <blockquote> <p>In order to do this for our test, take any application which has already been deployed successfully in Tomcat and first access it through http and https to see if it works fine. If yes, then open the web.xml of that application and just add this XML fragment before web-app ends i.e <code>&lt;/web-app&gt;</code>:</p> <pre><code>&lt;security-constraint&gt; &lt;web-resource-collection&gt; &lt;web-resource-name&gt;securedapp&lt;/web-resource-name&gt; &lt;url-pattern&gt;/*&lt;/url-pattern&gt; &lt;/web-resource-collection&gt; &lt;user-data-constraint&gt; &lt;transport-guarantee&gt;CONFIDENTIAL&lt;/transport-guarantee&gt; &lt;/user-data-constraint&gt; &lt;/security-constraint&gt; </code></pre> </blockquote> <p>Is this configuration is mandatory to do inside a web.xml file ??</p>
7,793,684
2
1
null
2011-10-17 06:33:44.777 UTC
11
2018-03-08 11:12:27.557 UTC
2015-04-08 21:12:27.387 UTC
null
55,075
null
784,597
null
1
28
tomcat|web.xml|security-constraint
61,863
<p>No, it's not necessary. It means that your web application <strong>only</strong> available through HTTPS (and not available through HTTP).</p> <p>If you omit the <code>&lt;transport-guarantee&gt;CONFIDENTIAL&lt;/transport-guarantee&gt;</code> tag (or the whole <code>&lt;security-constraint&gt;</code>) your application will be available through both HTTP and HTTPS. If your <code>web.xml</code> contains <code>&lt;transport-guarantee&gt;CONFIDENTIAL&lt;/transport-guarantee&gt;</code> Tomcat automatically redirects the requests to the SSL port if you try to use HTTP.</p> <p>Please note that the default Tomcat configuration does not enable the SSL connector, you have to enable it manually. Check the <a href="http://tomcat.apache.org/tomcat-7.0-doc/ssl-howto.html#Configuration" rel="noreferrer">SSL Configuration HOW-TO</a> for the details.</p>
9,384,227
Retrieving an enum using 'valueOf' throws RuntimeException - What to use instead?
<p>I have the following enum</p> <pre><code>enum Animal implements Mammal { CAT, DOG; public static Mammal findMammal(final String type) { for (Animal a : Animal.values()) { if (a.name().equals(type)) { return a; } } } } </code></pre> <p>I had originally used the <code>Enum.valueOf(Animal.class, "DOG");</code> to find a particular Animal. However, I was unaware that if a match is not found, an <code>IllegalArgumentException</code> is thrown. I thought that maybe a null was returned. So this gives me a problem. I don't want to catch this <code>IllegalArgumentException</code> if a match is not found. I want to be able to search all enums of type <code>Mammal</code> and I don't want to have to implement this static '<code>findMammal</code>' for each enum of type <code>Mammal</code>. So my question is, what would be the most auspicious design decision to implement this behaviour? I will have calling code like this:</p> <pre><code>public class Foo { public Mammal bar(final String arg) { Mammal m = null; if (arg.equals("SomeValue")) { m = Animal.findMammal("CAT"); } else if (arg.equals("AnotherValue") { m = Human.findMammal("BILL"); } // ... etc } } </code></pre> <p>As you can see, I have different types of Mammal - 'Animal', 'Human', which are enums. I don't want to have to implement 'findMammal' for each Mammal enum. I suppose the best bet is just create a utility class which takes a Mammal argument and searches that? Maybe there's a neater solution. </p>
9,384,347
7
8
null
2012-02-21 19:55:11.87 UTC
3
2020-10-14 14:41:16.367 UTC
2016-10-19 16:00:33.317 UTC
null
167,745
null
543,220
null
1
13
java|enums
46,294
<p>How about creating a <code>HashMap&lt;String, Mammal&gt;</code>? You only need to do it once...</p> <pre><code>public class Foo { private static final Map&lt;String, Mammal&gt; NAME_TO_MAMMAL_MAP; static { NAME_TO_MAMMAL_MAP = new HashMap&lt;String, Mammal&gt;(); for (Human human : EnumSet.allOf(Human.class)) { NAME_TO_MAMMAL_MAP.put(human.name(), human); } for (Animal animal : EnumSet.allOf(Animal.class)) { NAME_TO_MAMMAL_MAP.put(animal.name(), animal); } } public static Mammal bar(final String arg) { return NAME_TO_MAMMAL_MAP.get(arg); } } </code></pre> <p>Notes:</p> <ul> <li>This will return <code>null</code> if the name doesn't exist</li> <li>This won't detect a name collision</li> <li>You may want to use an immutable map of some description (e.g. via <a href="http://guava-libraries.googlecode.com" rel="noreferrer">Guava</a>)</li> <li>You may wish to write a utility method to create an immutable name-to-value map for a general enum, then just merge the maps :)</li> </ul>
9,519,841
Why does this CSS margin-top style not work?
<p>I try to add <code>margin</code> values on a <code>div</code> inside another <code>div</code>. All works fine except the top value, it seems to be ignored. But why?</p> <p><strong>What I expected:</strong><br /> <img src="https://i.stack.imgur.com/WFkp8.jpg" alt="What I expected with margin:50px 50px 50px 50px;" /></p> <p><strong>What I get:</strong><br /> <img src="https://i.stack.imgur.com/I3xJz.jpg" alt="What I get with margin:50px 50px 50px 50px;" /></p> <p><strong>Code:</strong></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>#outer { width: 500px; height: 200px; background: #FFCCCC; margin: 50px auto 0 auto; display: block; } #inner { background: #FFCC33; margin: 50px 50px 50px 50px; padding: 10px; display: block; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="outer"&gt; &lt;div id="inner"&gt; Hello world! &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p><a href="http://www.w3schools.com/css/css_margin.asp" rel="nofollow noreferrer">W3Schools</a> have no explanation to why <code>margin</code> behaves this way.</p>
9,519,933
14
8
null
2012-03-01 16:17:34.087 UTC
193
2022-07-15 09:11:44.023 UTC
2022-07-15 08:58:14.577 UTC
null
15,288,641
null
266,642
null
1
406
html|margin|css
323,256
<p>You're actually seeing the top margin of the <code>#inner</code> element <a href="http://www.w3.org/TR/CSS21/box.html#collapsing-margins" rel="noreferrer">collapse</a> into the top edge of the <code>#outer</code> element, leaving only the <code>#outer</code> margin intact (albeit not shown in your images). The top edges of both boxes are flush against each other because their margins are equal.</p> <p>Here are the relevant points from the W3C spec:</p> <blockquote> <h3>8.3.1 Collapsing margins</h3> <p>In CSS, the adjoining margins of two or more boxes (which might or might not be siblings) can combine to form a single margin. Margins that combine this way are said to <em>collapse</em>, and the resulting combined margin is called a <em>collapsed margin</em>.</p> <p>Adjoining vertical margins collapse <em>[...]</em></p> </blockquote> <blockquote> <p>Two margins are <em>adjoining</em> if and only if:</p> <ul> <li>both belong to in-flow block-level boxes that participate in the same block formatting context</li> <li>no line boxes, no clearance, no padding and no border separate them</li> <li>both belong to vertically-adjacent box edges, i.e. form one of the following pairs: <ul> <li>top margin of a box and top margin of its first in-flow child</li> </ul></li> </ul> </blockquote> <p><strong>You can do any of the following to prevent the margin from collapsing:</strong></p> <blockquote> <ul> <li>Float either of your <code>div</code> elements</li> <li>Make either of your <code>div</code> elements <a href="https://stackoverflow.com/a/9519896/106224">inline blocks</a></li> <li>Set <a href="https://stackoverflow.com/a/9519937/106224"><code>overflow</code> of <code>#outer</code> to <code>auto</code></a> (or any value other than <code>visible</code>)</li> </ul> </blockquote> <p><strong>The reason the above options prevent the margin from collapsing is because:</strong></p> <blockquote> <ul> <li>Margins between a floated box and any other box do not collapse (not even between a float and its in-flow children).</li> <li>Margins of elements that establish new block formatting contexts (such as floats and elements with 'overflow' other than 'visible') do not collapse with their in-flow children.</li> <li>Margins of inline-block boxes do not collapse (not even with their in-flow children).</li> </ul> </blockquote> <p><strong>The left and right margins behave as you expect because:</strong></p> <blockquote> <p>Horizontal margins never collapse.</p> </blockquote>
8,720,897
how to save DOMPDF generated content to file?
<p>I am using Dompdf to create PDF file but I don't know why it doesn't save the created PDF to server.</p> <p>Any ideas?</p> <pre><code>require_once("./pdf/dompdf_config.inc.php"); $html = '&lt;html&gt;&lt;body&gt;'. '&lt;p&gt;Put your html here, or generate it with your favourite '. 'templating system.&lt;/p&gt;'. '&lt;/body&gt;&lt;/html&gt;'; $dompdf = new DOMPDF(); $dompdf-&gt;load_html($html); $dompdf-&gt;render(); file_put_contents('Brochure.pdf', $dompdf-&gt;output()); </code></pre>
8,721,817
3
3
null
2012-01-04 01:14:46.787 UTC
20
2015-10-15 09:35:01.89 UTC
2012-01-07 19:57:00.02 UTC
null
344,570
null
1,079,810
null
1
69
php|file|pdf-generation|save|dompdf
129,064
<p>I have just used dompdf and the code was a little different but it worked.</p> <p>Here it is:</p> <pre><code>require_once("./pdf/dompdf_config.inc.php"); $files = glob("./pdf/include/*.php"); foreach($files as $file) include_once($file); $html = '&lt;html&gt;&lt;body&gt;'. '&lt;p&gt;Put your html here, or generate it with your favourite '. 'templating system.&lt;/p&gt;'. '&lt;/body&gt;&lt;/html&gt;'; $dompdf = new DOMPDF(); $dompdf-&gt;load_html($html); $dompdf-&gt;render(); $output = $dompdf-&gt;output(); file_put_contents('Brochure.pdf', $output); </code></pre> <p>Only difference here is that all of the files in the include directory are included.</p> <p>Other than that my only suggestion would be to specify a full directory path for writing the file rather than just the filename.</p>
8,652,948
Using port number in Windows host file
<p>After installing TeamViewer, I have changed the wampserver port to 8080, so the address is <code>http://localhost:8080.</code></p> <p>For the host file located at C:\WINDOWS\system32\drivers\etc\, I have also made the change as below</p> <p>BEFORE<br> <code>127.0.0.1 www.example.com</code></p> <p>AFTER<br> <code>127.0.0.1:8080 www.example.com</code></p> <p>When I access www.example.com, it doesn't redirect to my wampserver, how can I fix it?</p>
8,652,991
11
4
null
2011-12-28 07:09:05.807 UTC
104
2022-02-17 11:40:28.98 UTC
2019-08-20 15:11:21.97 UTC
null
462,971
null
495,452
null
1
269
windows
373,350
<p>The <code>hosts</code> file is for host name resolution only (on Windows as well as on Unix-like systems). You cannot put port numbers in there, and there is no way to do what you want with generic OS-level configuration - the browser is what selects the port to choose.</p> <p>So use bookmarks or something like that.<br> (Some firewall/routing software might allow outbound port redirection, but that doesn't really sound like an appealing option for this.)</p>
5,353,184
Fixing maps library data for Pacific centred (0°-360° longitude) display
<p>I'm plotting some points on a map of the world using the R <code>maps</code> package, something like:</p> <p><img src="https://i.stack.imgur.com/vmtDo.png" alt="Map of the world, -180° to 180° longitude"></p> <p>The command to draw the base map is:</p> <pre><code>map("world", fill=TRUE, col="white", bg="gray", ylim=c(-60, 90), mar=c(0,0,0,0)) </code></pre> <p>But I need to display Pacific centred map. I use <code>map("world2",</code> etc to use the Pacific centred basemap from the maps package, and convert the coordinates of the data points in my dataframe (<code>df</code>) with:</p> <pre><code>df$longitude[df$longitude &lt; 0] = df$longitude[df$longitude &lt; 0] + 360 </code></pre> <p>This works if I don't use the <code>fill</code> option, but with <code>fill</code> the polygons which cross 0° cause problems.</p> <p><img src="https://i.stack.imgur.com/H2Goo.png" alt="Map of the world, 0° to 360° longitude"></p> <p>I guess I need to transform the polygon data from the <code>maps</code> library somehow to sort this out, but I have no idea how to get at this.</p> <p>My ideal solution would be to draw a maps with a left boundary at -20° and a right boundary at -30° (i.e. 330°). The following gets the correct points and coastlines onto the map, but the crossing-zero problem is the same</p> <pre><code>df$longitude[df$longitude &lt; -20] = df$longitude[d$longitude &lt; -20] + 360 map("world", fill=TRUE, col="white", bg="gray", mar=c(0,0,0,0), ylim=c(-60, 90), xlim=c(-20, 330)) map("world2", add=TRUE, col="white", bg="gray", fill=TRUE, xlim=c(180, 330)) </code></pre> <p>Any help would be greatly appreciated.</p>
5,538,551
4
6
null
2011-03-18 14:10:40.983 UTC
10
2021-09-15 07:38:32.863 UTC
null
null
null
null
188,595
null
1
21
r|maps
14,963
<p>You could use the fact that internally, a <code>map</code> object returned by the <code>map()</code> function can be recalculated and used again in the <code>map()</code> function. I'd create a list with individual polygons, check which ones have very different longitude values, and rearrange those ones. I gave an example of this approach in the function below*, which allows something like :</p> <pre><code>plot.map("world", center=180, col="white",bg="gray", fill=TRUE,ylim=c(-60,90),mar=c(0,0,0,0)) </code></pre> <p>to get</p> <p><img src="https://i.stack.imgur.com/DbcO5.png" alt="Corrected map center 180"></p> <p>If I were you, I'd shift everything a bit more, like in :</p> <pre><code>plot.map("world", center=200, col="white",bg="gray", fill=TRUE,ylim=c(-60,90),mar=c(0,0,0,0)) </code></pre> <p><img src="https://i.stack.imgur.com/YviUz.png" alt="Corrected map center 200"></p> <p>The function :</p> <pre><code>plot.map&lt;- function(database,center,...){ Obj &lt;- map(database,...,plot=F) coord &lt;- cbind(Obj[[1]],Obj[[2]]) # split up the coordinates id &lt;- rle(!is.na(coord[,1])) id &lt;- matrix(c(1,cumsum(id$lengths)),ncol=2,byrow=T) polygons &lt;- apply(id,1,function(i){coord[i[1]:i[2],]}) # split up polygons that differ too much polygons &lt;- lapply(polygons,function(x){ x[,1] &lt;- x[,1] + center x[,1] &lt;- ifelse(x[,1]&gt;180,x[,1]-360,x[,1]) if(sum(diff(x[,1])&gt;300,na.rm=T) &gt;0){ id &lt;- x[,1] &lt; 0 x &lt;- rbind(x[id,],c(NA,NA),x[!id,]) } x }) # reconstruct the object polygons &lt;- do.call(rbind,polygons) Obj[[1]] &lt;- polygons[,1] Obj[[2]] &lt;- polygons[,2] map(Obj,...) } </code></pre> <p>*Note that this function only takes positive center values. It's easily adapted to allow for center values in both directions, but I didn't bother anymore as that's trivial.</p>
5,526,059
What is call-by-need?
<p>I want to know what is call-by-need.</p> <p>Though I searched in wikipedia and found it here: <a href="http://en.wikipedia.org/wiki/Evaluation_strategy" rel="noreferrer">http://en.wikipedia.org/wiki/Evaluation_strategy</a>, but could not understand properly. If anyone can explain with an example and point out the difference with call-by-value, it would be a great help.</p>
5,526,150
4
0
null
2011-04-02 21:37:09.583 UTC
9
2021-12-22 00:21:34.33 UTC
2019-06-25 16:50:05.41 UTC
null
849,891
null
1,747,257
null
1
21
programming-languages|evaluation|call-by-value|evaluation-strategy|call-by-need
13,051
<p>Imagine a function:</p> <pre><code>fun add(a, b) { return a + b } </code></pre> <p>And then we call it:</p> <pre><code> add(3 * 2, 4 / 2) </code></pre> <p>In a call-by-name language this will be evaluated so:</p> <ol> <li><code>a = 3 * 2 = 6</code></li> <li><code>b = 4 / 2 = 2</code></li> <li><code>return a + b = 6 + 2 = 8</code></li> </ol> <p>The function will return the value <code>8</code>.</p> <p>In a call-by-need (also called a lazy language) this is evaluated like so:</p> <ol> <li><code>a = 3 * 2</code></li> <li><code>b = 4 / 2</code></li> <li><code>return a + b = 3 * 2 + 4 / 2</code></li> </ol> <p>The function will return the expression <code>3 * 2 + 4 / 2</code>. So far almost no computational resources have been spent. The whole expression will be computed only if its value is needed - say we wanted to print the result.</p> <p><em>Why is this useful?</em> Two reasons. First if you accidentally include dead code it doesn't weigh your program down and thus can be a lot more efficient. Second it allows to do very cool things like efficiently calculating with infinite lists:</p> <pre><code>fun takeFirstThree(list) { return [list[0], list[1], list[2]] } takeFirstThree([0 ... infinity]) </code></pre> <p>A call-by-name language would hang there trying to create a list from 0 to infinity. A lazy language will simply return <code>[0,1,2]</code>.</p>
5,519,007
How do I make git merge's default be --no-ff --no-commit?
<p>Company policy is to use <code>--no-ff</code> for merge commits. I personally like to adjust merge log messages so I use <code>--no-commit</code>. Plus I like to actually compile and test before I let the commit go.</p> <p>How do I make <code>--no-ff</code> and <code>--no-commit</code> the default for me for all branches?</p> <p>(and I've learned in the years since asking this, I almost always am happy with the commit, so it is simpler to allow it to commit by default and so long as I amend or otherwise fix things up before doing a push things are all good...)</p>
5,519,141
4
1
null
2011-04-01 21:21:16.453 UTC
34
2016-08-11 18:32:59.59 UTC
2014-05-02 00:06:40.477 UTC
null
431,272
null
431,272
null
1
102
git|merge
30,581
<p>Put this in $HOME/.gitconfig:</p> <pre><code>[merge] ff = no commit = no </code></pre> <p>You can use git-config to do this:</p> <pre><code> git config --global merge.commit no git config --global merge.ff no </code></pre>
5,120,391
Python find object in a list
<p>I have a list of people:</p> <pre><code>[ {'name' : 'John', 'wins' : 10 }, {'name' : 'Sally', 'wins' : 0 }, {'name' : 'Fred', 'wins' : 3 }, {'name' : 'Mary', 'wins' : 6 } ] </code></pre> <p>I am adding wins using a list of names (<code>['Fred', 'Mary', 'Sally']</code>). I don't know if the name is in the list of people already, and I need to insert a new record if not. Currently I'm doing the following:</p> <pre><code>name = 'John' person = None pidx = None for p in people_list: if p['name'] == name: person = p pidx = people_list.index(p) break if person is None: person = {'name' : name, 'wins' : 0} person['wins'] += 1 if pidx is None: people_list.append(person) else people_list[pidx] = person </code></pre> <p>Is there a better way to do this with a list? Given that I'm saving this to MongoDB I can't use a <code>dict</code> as it will save as an object and I want to use native array functions for sorting and mapping that aren't available for objects.</p>
5,120,509
5
0
null
2011-02-25 17:16:44.677 UTC
4
2011-07-12 02:35:41.12 UTC
2011-02-25 17:29:08.177 UTC
null
185,657
null
185,657
null
1
11
python|list|search|indexing
46,708
<p>I'm assuming here that you don't want to use any structure other than the list. Your code should work, although you unnecessarily write the dictionary back to the list after updating it. Dictionaries are copied by reference, so once you update it, it stays updated in the list. After a little housekeeping, your code could look like this:</p> <pre><code>def add_win(people_list, name): person = find_person(people_list, name) person['wins'] += 1 def find_person(people_list, name): for person in people_list: if person['name'] == name: return person person = {'name': name, 'wins': 0} people_list.append(person) return person </code></pre>
5,507,168
java.lang.NumberFormatException: For input string: " "
<p>When I try to do this:</p> <p><code>total = Integer.parseInt(dataValues_fluid[i]) + total;</code></p> <p>It will give me an error message</p> <pre><code>java.lang.NumberFormatException: For input string: " " </code></pre> <p>Some of the values are " ". So thats why it gives me. But I tried </p> <pre><code>int total = 0; for(int i=0; i&lt;counter5; i++){ if(dataValues_fluid[i]==" "){dataValues_fluid[i]="0";} total = Integer.parseInt(dataValues_fluid[i]) + total; } </code></pre> <p>I still get the same <code>java.lang.NumberFormatException</code> error.</p>
5,507,208
6
1
null
2011-03-31 22:32:26.333 UTC
1
2019-09-09 08:20:23.767 UTC
2017-05-14 18:43:25.687 UTC
null
3,675,035
null
484,478
null
1
5
java|numberformatexception
82,340
<p>I'm assuming that <code>dataValues_fluid[]</code> is an array of <code>String</code>s. If this is the case, you can't use the <code>==</code> comparison operator - you need to use <code>if(dataValues_fluid[i].equals(" "))</code>.</p> <p>So your <code>parseInt()</code> is attempting to parse the space character, which results in your <code>NumberFormatException</code>.</p>
5,055,068
Within a C# instance method, can 'this' ever be null?
<p>I have a situation where very rarely a Queue of Objects is dequeuing a null. The only call to Enqueue is within the class itself:</p> <pre><code>m_DeltaQueue.Enqueue(this); </code></pre> <p>Very rarely, a null is dequeued from this queue in the following code (a static method):</p> <pre><code>while (m_DeltaQueue.Count &gt; 0 &amp;&amp; index++ &lt; count) if ((m = m_DeltaQueue.Dequeue()) != null) m.ProcessDelta(); else if (nullcount++ &lt; 10) { Core.InvokeBroadcastEvent(AccessLevel.GameMaster, "A Rougue null exception was caught, m_DeltaQueue.Dequeue of a null occurred. Please inform an developer."); Console.WriteLine("m_DeltaQueue.Dequeue of a null occurred: m_DeltaQueue is not null. m_DeltaQueue.count:{0}", m_DeltaQueue.Count); } </code></pre> <p>This is the error report that was generated:</p> <blockquote> <p>[Jan 23 01:53:13]: m_DeltaQueue.Dequeue of a null occurred: m_DeltaQueue is not null. m_DeltaQueue.count:345</p> </blockquote> <p>I'm very confused as to how a null value could be present in this queue. </p> <p>As I'm writing this, I'm wondering if this could be a failure of thread synchronization; this is a multi threaded application and It's possible the enqueue or dequeue could be happening simultaneously in another thread.</p> <p>This is currently under .Net 4.0, but it previously occurred in 3.5/2.0</p> <p><strong>Update:</strong></p> <p>This is my (hopefully correct) solution to the problem which was made clear though the great answers below as being a synchronization problem.</p> <pre><code>private static object _lock = new object(); private static Queue&lt;Mobile&gt; m_DeltaQueue = new Queue&lt;Mobile&gt;(); </code></pre> <p>Enqueue:</p> <pre><code> lock (_lock) m_DeltaQueue.Enqueue(this); </code></pre> <p>Dequeue:</p> <pre><code> int count = m_DeltaQueue.Count; int index = 0; if (m_DeltaQueue.Count &gt; 0 &amp;&amp; index &lt; count) lock (_lock) while (m_DeltaQueue.Count &gt; 0 &amp;&amp; index++ &lt; count) m_DeltaQueue.Dequeue().ProcessDelta(); </code></pre> <p>I'm still trying to get a handle on proper syncronization, so any comments on the correctness of this would be very appreciated. I initially chose to use the queue itself as a syncronization object because it's private, and introduces less clutter into what is already a very large class. Based on John's suggestion I changed this to lock on a new private static object, _lock.</p>
5,055,086
6
8
null
2011-02-20 03:30:19.293 UTC
2
2017-02-22 18:38:05.583 UTC
2011-02-20 17:42:21.747 UTC
null
561,759
null
561,759
null
1
31
c#|.net|multithreading|thread-safety
4,747
<p><code>this</code> can never be null, unless the method was called using a <code>call</code> instruction in hand-written IL.</p> <p>However, if you use the same <code>Queue</code> instance on multiple threads simultaneously, the queue will become corrupted and lose data.</p> <p>For example, if two items are added simultaneously to a near-capacity queue, the first item might be added to the array after the second thread resizes it, which will end up copying a <code>null</code> to the resized array and adding the first item to the old array.</p> <p>You should protect your queues with locks or use .Net 4's <code>ConcurrentQueue&lt;T&gt;</code>.</p>
5,142,065
@Valid annotation is not validating the list of child objects
<p>Main model classes are as follows :</p> <pre><code>public class UserAddressesForm { @NotEmpty private String firstName; @NotEmpty private String lastName; private List&lt;AddressForm&gt; addresses; // setters and getters } </code></pre> <hr /> <pre><code>public class AddressForm { @NotEmpty private String customName; @NotEmpty private String city; @NotEmpty private String streetAn; @NotEmpty private String streetHn; @NotEmpty private String addressCountry; @NotEmpty private String postCode; // setters and getters } </code></pre> <p>An endpoint in one of my controllers :</p> <pre><code>@RequestMapping(value = &quot;/up&quot;, method = RequestMethod.POST) public String completeForm(@Valid @ModelAttribute(&quot;userAddressesForm&quot;) UserAddressesForm userAddressesForm, BindingResult result, HttpServletRequest req) { // logic here } </code></pre> <p>A <code>.jsp</code> page :</p> <pre><code>&lt;form:form commandName=&quot;userAddressesForm&quot; action=&quot;registered&quot;&gt; &lt;table&gt; &lt;tr&gt; &lt;td class=&quot;formLabels&quot;&gt;&lt;form:label path=&quot;firstName&quot;&gt; &lt;spring:message code=&quot;label.name&quot; /&gt; &lt;/form:label&gt;&lt;/td&gt; &lt;td&gt;&lt;form:input path=&quot;firstName&quot; /&gt;&lt;/td&gt; &lt;td&gt;&lt;form:errors path=&quot;firstName&quot; cssClass=&quot;error&quot; /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td class=&quot;formLabels&quot;&gt;&lt;form:label path=&quot;lastName&quot;&gt; &lt;spring:message code=&quot;label.surname&quot; /&gt; &lt;/form:label&gt;&lt;/td&gt; &lt;td&gt;&lt;form:input path=&quot;lastName&quot; /&gt;&lt;/td&gt; &lt;td&gt;&lt;form:errors path=&quot;lastName&quot; cssClass=&quot;error&quot; /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;c:forEach items=&quot;${userAddressesForm.addresses}&quot; varStatus=&quot;gridRow&quot;&gt; &lt;div id=&quot;main_address&quot; class=&quot;address_data_form&quot;&gt; &lt;fieldset&gt; &lt;legend&gt;&lt;spring:message code=&quot;label.stepThreeMainAddressInfo&quot; /&gt;&lt;/legend&gt; &lt;a href=&quot;#&quot; class=&quot;deleteItem&quot;&gt;&lt;/a&gt; &lt;table&gt; &lt;tr&gt; &lt;td class=&quot;formLabels&quot;&gt; &lt;spring:message code=&quot;label.address.custom.name&quot; /&gt; &lt;/td&gt; &lt;td&gt; &lt;spring:bind path=&quot;addresses[${gridRow.index}].customName&quot;&gt; &lt;input type=&quot;input&quot; name=&quot;&lt;c:out value=&quot;${status.expression}&quot;/&gt;&quot; id=&quot;&lt;c:out value=&quot;${status.expression}&quot;/&gt;&quot; value=&quot;&lt;c:out value=&quot;${status.value}&quot;/&gt;&quot; /&gt; &lt;form:errors path=&quot;${status.expression}&quot;/&gt; &lt;/spring:bind&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td class=&quot;formLabels&quot;&gt; &lt;spring:message code=&quot;label.streetAnStreetHn&quot; /&gt; &lt;/td&gt; &lt;td&gt; &lt;spring:bind path=&quot;addresses[${gridRow.index}].streetAn&quot;&gt; &lt;input type=&quot;input&quot; name=&quot;&lt;c:out value=&quot;${status.expression}&quot;/&gt;&quot; id=&quot;&lt;c:out value=&quot;${status.expression}&quot;/&gt;&quot; value=&quot;&lt;c:out value=&quot;${status.value}&quot;/&gt;&quot; /&gt; &lt;/spring:bind&gt; &lt;spring:bind path=&quot;addresses[${gridRow.index}].streetHn&quot;&gt; &lt;input type=&quot;input&quot; name=&quot;&lt;c:out value=&quot;${status.expression}&quot;/&gt;&quot; id=&quot;&lt;c:out value=&quot;${status.expression}&quot;/&gt;&quot; value=&quot;&lt;c:out value=&quot;${status.value}&quot;/&gt;&quot; &gt; &lt;form:errors path=&quot;addresses[${gridRow.index}].streetHn&quot;/&gt; &lt;/spring:bind&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td class=&quot;formLabels&quot;&gt; &lt;spring:message code=&quot;label.postCode&quot; /&gt; &lt;/td&gt; &lt;td&gt; &lt;spring:bind path=&quot;addresses[${gridRow.index}].postCode&quot;&gt; &lt;input type=&quot;input&quot; name=&quot;&lt;c:out value=&quot;${status.expression}&quot;/&gt;&quot; id=&quot;&lt;c:out value=&quot;${status.expression}&quot;/&gt;&quot; value=&quot;&lt;c:out value=&quot;${status.value}&quot;/&gt;&quot; /&gt; &lt;/spring:bind&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td class=&quot;formLabels&quot;&gt; &lt;spring:message code=&quot;label.city&quot; /&gt; &lt;/td&gt; &lt;td&gt; &lt;spring:bind path=&quot;addresses[${gridRow.index}].city&quot;&gt; &lt;input type=&quot;input&quot; name=&quot;&lt;c:out value=&quot;${status.expression}&quot;/&gt;&quot; id=&quot;&lt;c:out value=&quot;${status.expression}&quot;/&gt;&quot; value=&quot;&lt;c:out value=&quot;${status.value}&quot;/&gt;&quot; /&gt; &lt;form:errors path=&quot;addresses[${gridRow.index}].city&quot; cssClass=&quot;error&quot; /&gt; &lt;/spring:bind&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/fieldset&gt; &lt;/div&gt; &lt;/c:forEach&gt; </code></pre> <p>Why <code>@Valid</code> is not validating the <code>List&lt;AddressForm&gt; addresses</code> present in <code>UserAddressesForm</code> class ?</p>
5,142,960
6
0
null
2011-02-28 12:36:04.2 UTC
17
2022-03-02 14:06:12.467 UTC
2021-01-06 14:07:25.17 UTC
null
8,340,997
null
612,925
null
1
110
java|spring|spring-mvc|jsr
67,773
<p>You need to decorate <code>addresses</code> member of <code>UserAddressesForm</code> with <code>@Valid</code> annotation. See section 3.1.3 and 3.5.1 of <a href="http://beanvalidation.org/1.0/spec/#constraintdeclarationvalidationprocess" rel="noreferrer">JSR 303: Bean Validation</a>. As I explained in my answer to the question <a href="https://stackoverflow.com/questions/4900077/is-there-a-standard-way-to-enable-jsr-303-bean-validation-using-annotated-method">Is there a standard way to enable JSR 303 Bean Validation using annotated method</a>, this is the real use of <code>@Valid</code> annotation as per JSR 303.</p> <p><strong>Edit</strong> Example code: <a href="http://docs.jboss.org/hibernate/validator/4.1/reference/en-US/html/validator-usingvalidator.html#d0e410" rel="noreferrer">Hibernate Validator- Object Graph</a>. (The list of passengers in Car)</p> <p><strong>Edit</strong> From <a href="https://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/?v=6.1#section-object-graph-validation" rel="noreferrer">Hibernate Validator 6</a> Reference doc:</p> <blockquote> <p>In versions prior to 6, Hibernate Validator supported cascaded validation for a subset of container elements and it was implemented at the container level (e.g. you would use <code>@Valid private List&lt;Person&gt;</code> to enable cascaded validation for <code>Person</code>).</p> <p>This is still supported but is not recommended. Please use container element level <code>@Valid</code> annotations instead as it is more expressive.</p> </blockquote> <p>Example:</p> <pre><code>public class Car { private List&lt;@NotNull @Valid Person&gt; passengers = new ArrayList&lt;Person&gt;(); private Map&lt;@Valid Part, List&lt;@Valid Manufacturer&gt;&gt; partManufacturers = new HashMap&lt;&gt;(); //... } </code></pre> <p>Also see what's new in <a href="https://beanvalidation.org/2.0/spec/#whatsnew-20" rel="noreferrer">Bean Validation 2.0/Jakarta Bean Validation</a>.</p>
5,162,784
'uint32_t' identifier not found error
<p>I'm porting code from Linux C to Visual C++ for windows.</p> <p>Visual C++ doesn't know <code>#include &lt;stdint.h&gt;</code> so I commented it out.</p> <p>Later, I found a lot of those <code>'uint32_t': identifier not found</code> errors. How can it be solved?</p>
5,162,801
7
6
null
2011-03-02 02:29:41.747 UTC
17
2022-09-08 08:47:07.777 UTC
2013-08-02 20:15:30.61 UTC
null
1,237,747
null
631,733
null
1
111
c++|c|visual-c++
314,310
<p>This type is defined in the C header <code>&lt;stdint.h&gt;</code> which is part of the C++11 standard but not standard in C++03. According to <a href="http://en.wikipedia.org/wiki/Stdint.h" rel="noreferrer">the Wikipedia page on the header</a>, it hasn't shipped with Visual Studio until VS2010.</p> <p>In the meantime, you could probably fake up your own version of the header by adding <code>typedef</code>s that map <a href="http://msdn.microsoft.com/en-us/library/29dh1w7z.aspx" rel="noreferrer">Microsoft's custom integer types</a> to the types expected by C. For example:</p> <pre><code>typedef __int32 int32_t; typedef unsigned __int32 uint32_t; /* ... etc. ... */ </code></pre> <p>Hope this helps!</p>
5,156,561
Should I favour IEnumerable<T> or Arrays?
<p>In many projects I work on, whenever I have to return a read only collection, I use the <code>IEnumerable&lt;T&gt;</code> interface and make it type specific like so:</p> <pre><code>Public ReadOnly Property GetValues() As IEnumerable(Of Integer) Get 'code to return the values' End Get End Property </code></pre> <p>Most of the time, I return a List but in some functions and read only properties I return an array which also serves the purpose alright by kind courtesy of Extension Methods.</p> <p>My question is <em>am I violating any design principles by returning <code>IEnumerable&lt;T&gt;</code>s instead of specific types (e.g.: <code>List&lt;T&gt;</code>, <code>HashSet&lt;T&gt;</code>, <code>Stack&lt;T&gt;</code> or <code>Array</code>s)</em>?</p>
5,156,618
8
1
null
2011-03-01 15:30:43.543 UTC
4
2016-03-15 06:31:40.55 UTC
2011-03-01 15:45:22.047 UTC
null
456,188
null
117,870
null
1
31
c#|.net|vb.net|design-principles
16,588
<p>I generally prefer <code>IEnumerable&lt;T&gt;</code> as well. The main thing is to ask yourself what actual (even minimum) functionality is being returned from the method (or passed to it, in the case of a method argument).</p> <p>If all you need to do is enumerate over a result set, then <code>IEnumerable&lt;T&gt;</code> does exactly that. No more, no less. This leaves you the flexibility to return more specific types in certain cases if need be without breaking the footprint of the method.</p>
5,275,410
What is the correct way to do a CSS Wrapper?
<p>I have heard a lot of my friends talk about using wrappers in CSS to center the "main" part of a website.</p> <p>Is this the best way to accomplish this? What is best practice? Are there other ways?</p>
5,275,428
9
1
null
2011-03-11 16:13:37.363 UTC
30
2021-07-21 10:50:28.343 UTC
2017-07-12 20:31:31.083 UTC
null
1,333,836
null
383,691
null
1
41
html|css
418,615
<p>Most basic example (<a href="http://jsfiddle.net/ArondeParon/qyDEx/2/" rel="nofollow noreferrer">live example here</a>):</p> <p><strong>CSS:</strong></p> <pre class="lang-css prettyprint-override"><code> #wrapper { width: 500px; margin: 0 auto; } </code></pre> <p><strong>HTML:</strong></p> <pre class="lang-html prettyprint-override"><code> &lt;body&gt; &lt;div id=&quot;wrapper&quot;&gt; Piece of text inside a 500px width div centered on the page &lt;/div&gt; &lt;/body&gt; </code></pre> <p><strong>How the principle works:</strong></p> <p>Create your wrapper and assign it a certain width. Then apply an automatic horizontal margin to it by using <code>margin: 0 auto;</code> or <code>margin-left: auto; margin-right: auto;</code>. The automatic margins make sure your element is centered.</p>
5,457,095
Release generating .pdb files, why?
<p>Why does Visual Studio 2005 generate the <code>.pdb</code> files when compiling in release? I won't be debugging a release build, so why are they generated?</p>
5,457,250
9
6
null
2011-03-28 09:34:39.367 UTC
95
2019-05-18 05:11:22.067 UTC
2018-05-01 07:51:44.267 UTC
user6605374
2,254,951
null
436,028
null
1
303
.net|visual-studio|debugging|pdb-files|debug-symbols
133,650
<p><strong>Because without the PDB files, it would be impossible to debug a "Release" build by anything other than address-level debugging.</strong> Optimizations really do a number on your code, making it very difficult to find the culprit if something goes wrong (say, an exception is thrown). Even setting breakpoints is extremely difficult, because lines of source code cannot be matched up one-to-one with (or even in the same order as) the generated assembly code. PDB files help you and the debugger out, making post-mortem debugging significantly easier.</p> <p>You make the point that if your software is ready for release, you should have done all your debugging by then. While that's certainly true, there are a couple of important points to keep in mind:</p> <ol> <li><p>You should <em>also</em> test and debug your application (before you release it) using the "Release" build. That's because turning optimizations on (they are disabled by default under the "Debug" configuration) can sometimes cause subtle bugs to appear that you wouldn't otherwise catch. When you're doing this debugging, you'll want the PDB symbols.</p></li> <li><p>Customers frequently report edge cases and bugs that only crop up under "ideal" conditions. These are things that are almost impossible to reproduce in the lab because they rely on some whacky configuration of that user's machine. If they're particularly helpful customers, they'll report the exception that was thrown and provide you with a stack trace. Or they'll even let you borrow their machine to debug your software remotely. In either of those cases, you'll want the PDB files to assist you.</p></li> <li><p>Profiling should <em>always</em> be done on "Release" builds with optimizations enabled. And once again, the PDB files come in handy, because they allow the assembly instructions being profiled to be mapped back to the source code that you actually wrote.</p></li> </ol> <p>You can't go back and generate the PDB files <em>after</em> the compile.<sup>*</sup> If you don't create them during the build, you've lost your opportunity. It doesn't hurt anything to create them. If you don't want to distribute them, you can simply omit them from your binaries. But if you later decide you want them, you're out of luck. <strong>Better to always generate them and archive a copy, just in case you ever need them.</strong></p> <p>If you really want to turn them off, that's always an option. In your project's Properties window, set the "Debug Info" option to "none" for any configuration you want to change.</p> <p>Do note, however, that the "Debug" and "Release" configurations <em>do</em> by default use different settings for emitting debug information. You will want to keep this setting. The "Debug Info" option is set to "full" for a Debug build, which means that in addition to a PDB file, debugging symbol information is embedded into the assembly. You also get symbols that support cool features like edit-and-continue. In Release mode, the "pdb-only" option is selected, which, like it sounds, includes only the PDB file, without affecting the content of the assembly. So it's not quite as simple as the mere presence or absence of PDB files in your <code>/bin</code> directory. But assuming you use the "pdb-only" option, the PDB file's presence will in no way affect the run-time performance of your code.</p> <p><sub><sup>*</sup> As <a href="https://stackoverflow.com/questions/5457095/release-generating-pdb-files-why/5457250#comment18690262_5457250">Marc Sherman points out in a comment</a>, as long as your source code has not changed (or you can retrieve the original code from a version-control system), you can rebuild it and generate a matching PDB file. At least, usually. This works well most of the time, but <a href="https://ericlippert.com/2012/05/31/past-performance-is-no-guarantee-of-future-results/" rel="noreferrer">the compiler is not guaranteed to generate identical binaries each time you compile the same code</a>, so there <em>may</em> be subtle differences. Worse, if you have made any upgrades to your toolchain in the meantime (like applying a service pack for Visual Studio), the PDBs are even less likely to match. To guarantee the reliable generation of <em>ex postfacto</em> PDB files, you would need to archive not only the source code in your version-control system, but also the binaries for your entire build toolchain to ensure that you could precisely recreate the configuration of your build environment. It goes without saying that it is much easier to simply create and archive the PDB files.</sub></p>
5,439,782
I want to vertical-align text in select box
<p>I want to vertically align the text in select box. I tried using </p> <pre><code>select{ verticle-align:middle; } </code></pre> <p>however it does not work in any browsers. Chrome seems to align the text in select box to the center as a default. FF aligns it to the top and IE aligns it to the bottom. Is there any way to achieve this? I am using GWT's Select widget in UIBinder.</p> <p>This is currently what I have:</p> <pre><code>select{ height: 28px !important; border: 1px solid #ABADB3; margin: 0; padding: 0; vertical-align: middle; } </code></pre> <p>Thanks!</p>
5,440,037
17
4
null
2011-03-26 01:37:46.353 UTC
19
2021-08-02 12:37:16.237 UTC
2011-03-26 02:12:07.307 UTC
null
337,546
null
337,546
null
1
72
css|gwt|select|vertical-alignment
138,660
<p>Your best option will probably be to adjust the top padding &amp; compare across browsers. It's not perfect, but I think it's as close as you can get.</p> <pre><code>padding-top:4px; </code></pre> <p>The amount of padding you need will depend on the font size.</p> <p>Tip: If your font is set in <code>px</code>, set padding in <code>px</code> as well. If your font is set in <code>em</code>, set the padding in <code>em</code> too.</p> <p><strong>EDIT</strong></p> <p>These are the options I think you have, since vertical-align isn't consistant across the browsers.</p> <p>A. Remove height attribute and let the browser handle it. This usually works the best for me.</p> <pre><code> &lt;style&gt; select{ border: 1px solid #ABADB3; margin: 0; padding: auto 0; font-size:14px; } &lt;/style&gt; &lt;select&gt; &lt;option&gt;option 1&lt;/option&gt; &lt;option&gt;number 2&lt;/option&gt; &lt;/select&gt; </code></pre> <hr> <p>B. Add top-padding to push down the text. (Pushed down the arrow in some browsers)</p> <pre><code>&lt;style&gt; select{ height: 28px !important; border: 1px solid #ABADB3; margin: 0; padding: 4px 0 0 0; font-size:14px; } &lt;/style&gt; &lt;select&gt; &lt;option&gt;option 1&lt;/option&gt; &lt;option&gt;number 2&lt;/option&gt; &lt;/select&gt; </code></pre> <hr> <p>C. You can make the font larger to try and match the select height a little nicer.</p> <pre><code>&lt;style&gt; select{ height: 28px !important; border: 1px solid #ABADB3; margin: 0; padding: 0 0 0 0; font-size:17px; } &lt;/style&gt; &lt;select&gt; &lt;option&gt;option 1&lt;/option&gt; &lt;option&gt;number 2&lt;/option&gt; &lt;/select&gt; </code></pre>
4,888,027
Python and pip, list all versions of a package that's available?
<p>Given the name of a Python package that can be installed with <a href="https://pip.pypa.io/en/stable/" rel="noreferrer">pip</a>, is there any way to find out a list of all the possible versions of it that pip could install? Right now it's trial and error.</p> <p>I'm trying to install a version for a third party library, but the newest version is too new, there were backwards incompatible changes made. So I'd like to somehow have a list of all the versions that pip knows about, so that I can test them.</p>
5,422,144
26
7
null
2011-02-03 15:24:30.673 UTC
171
2022-07-25 07:52:58.18 UTC
2019-11-01 15:31:01.543 UTC
null
674,039
null
161,922
null
1
725
python|pip
453,912
<p><strong>(update: As of March 2020, many people have reported that yolk, installed via <code>pip install yolk3k</code>, only returns latest version. <a href="https://stackoverflow.com/a/26664162">Chris's answer</a> seems to have the most upvotes and worked for me)</strong></p> <p>The script at pastebin does work. However it's not very convenient if you're working with multiple environments/hosts because you will have to copy/create it every time.</p> <p>A better all-around solution would be to use <a href="https://pypi.python.org/pypi/yolk3k" rel="noreferrer">yolk3k</a>, which is available to install with pip. E.g. to see what versions of Django are available:</p> <pre><code>$ pip install yolk3k $ yolk -V django Django 1.3 Django 1.2.5 Django 1.2.4 Django 1.2.3 Django 1.2.2 Django 1.2.1 Django 1.2 Django 1.1.4 Django 1.1.3 Django 1.1.2 Django 1.0.4 </code></pre> <p><code>yolk3k</code> is a fork of the original <a href="https://github.com/cakebread/yolk" rel="noreferrer"><code>yolk</code></a> which ceased development in <a href="https://pypi.org/project/yolk/#history" rel="noreferrer">2012</a>. Though <code>yolk</code> is no longer maintained (as indicated in comments below), <code>yolk3k</code> appears to be and supports Python 3.</p> <p><strong>Note:</strong> I am not involved in the development of yolk3k. <strong>If something doesn't seem to work as it should, leaving a comment here should not make much difference.</strong> Use the <a href="https://github.com/myint/yolk/issues" rel="noreferrer">yolk3k issue tracker</a> instead and consider submitting a fix, if possible.</p>
12,497,940
UIRefreshControl without UITableViewController
<p>Just curious, as it doesn't immediately seem possible, but is there a sneaky way to leverage the new iOS 6 <code>UIRefreshControl</code> class without using a <code>UITableViewController</code> subclass?</p> <p>I often use a <code>UIViewController</code> with a <code>UITableView</code> subview and conform to <code>UITableViewDataSource</code> and <code>UITableViewDelegate</code> rather than using a <code>UITableViewController</code> outright.</p>
12,502,450
12
5
null
2012-09-19 15:30:22.017 UTC
125
2016-12-22 15:49:46.61 UTC
2013-05-07 09:48:27.443 UTC
null
1,571,232
null
625,709
null
1
308
objective-c|ios|uitableview|ios6|uirefreshcontrol
83,756
<p>On a hunch, and based on DrummerB's inspiration, I tried simply adding a <code>UIRefreshControl</code> instance as a subview to my <code>UITableView</code>. And it magically just works!</p> <pre><code>UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init]; [refreshControl addTarget:self action:@selector(handleRefresh:) forControlEvents:UIControlEventValueChanged]; [self.myTableView addSubview:refreshControl]; </code></pre> <p>This adds a <code>UIRefreshControl</code> above your table view and works as expected without having to use a <code>UITableViewController</code> :)</p> <hr> <p>EDIT: This above still works but as a few have pointed out, there is a slight "stutter" when adding the UIRefreshControl in this manner. A solution to that is to instantiate a UITableViewController, and then setting your UIRefreshControl and UITableView to that, i.e.:</p> <pre><code>UITableViewController *tableViewController = [[UITableViewController alloc] init]; tableViewController.tableView = self.myTableView; self.refreshControl = [[UIRefreshControl alloc] init]; [self.refreshControl addTarget:self action:@selector(getConnections) forControlEvents:UIControlEventValueChanged]; tableViewController.refreshControl = self.refreshControl; </code></pre>
12,278,660
Adding Tags to a Pull Request
<p>I have a repo <a href="http://github.com/iontech/Anagen" rel="noreferrer">iontech/Anagen</a> forked from <a href="http://github.com/agiliq/Anagen" rel="noreferrer">agiliq/Anagen</a></p> <p>I made a few commits to my fork and added a tag. Then I opened a Pull Request. This Pull Request includes only my commits.</p> <p>How do I include the tag I've created into the Pull Request?</p>
12,279,290
2
0
null
2012-09-05 09:48:23.91 UTC
9
2020-10-18 21:06:18.22 UTC
2015-03-03 13:45:21.51 UTC
null
3,834,848
user1062640
null
null
1
75
git|github|pull-request|git-tag
73,405
<blockquote> <p>How do I include the tag I've created into the Pull Request?</p> </blockquote> <p>You can't. A pull request does not include tags. A pull request is only a pointer to a thread of commits (a branch) in your repository that you're proposing another repository to merge.</p> <p>If you want to notify the upstream repository that a tag should be created, maybe should you add a comment to the pull request explaining this.</p>
18,852,059
Java List.contains(Object with field value equal to x)
<p>I want to check whether a <code>List</code> contains an object that has a field with a certain value. Now, I could use a loop to go through and check, but I was curious if there was anything more code efficient. </p> <p>Something like;</p> <pre><code>if(list.contains(new Object().setName("John"))){ //Do some stuff } </code></pre> <p>I know the above code doesn't do anything, it's just to demonstrate roughly what I am trying to achieve.</p> <p>Also, just to clarify, the reason I don't want to use a simple loop is because this code will currently go inside a loop that is inside a loop which is inside a loop. For readability I don't want to keep adding loops to these loops. So I wondered if there were any simple(ish) alternatives.</p>
18,852,327
13
5
null
2013-09-17 14:02:37.997 UTC
68
2022-09-05 13:27:40.423 UTC
2016-01-08 12:49:35.967 UTC
null
2,182,928
null
2,182,928
null
1
268
java|list|search|contains
545,750
<h1>Streams</h1> <p>If you are using Java 8, perhaps you could try something like this:</p> <pre><code>public boolean containsName(final List&lt;MyObject&gt; list, final String name){ return list.stream().filter(o -&gt; o.getName().equals(name)).findFirst().isPresent(); } </code></pre> <p>Or alternatively, you could try something like this:</p> <pre><code>public boolean containsName(final List&lt;MyObject&gt; list, final String name){ return list.stream().map(MyObject::getName).filter(name::equals).findFirst().isPresent(); } </code></pre> <p>This method will return <code>true</code> if the <code>List&lt;MyObject&gt;</code> contains a <code>MyObject</code> with the name <code>name</code>. If you want to perform an operation on each of the <code>MyObject</code>s that <code>getName().equals(name)</code>, then you could try something like this:</p> <pre><code>public void perform(final List&lt;MyObject&gt; list, final String name){ list.stream().filter(o -&gt; o.getName().equals(name)).forEach( o -&gt; { //... } ); } </code></pre> <p>Where <code>o</code> represents a <code>MyObject</code> instance.</p> <p>Alternatively, as the comments suggest (Thanks MK10), you could use the <code>Stream#anyMatch</code> method:</p> <pre><code>public boolean containsName(final List&lt;MyObject&gt; list, final String name){ return list.stream().anyMatch(o -&gt; name.equals(o.getName())); } </code></pre>
3,398,850
How to get a list of current variables from Jinja 2 template?
<p>If I return a Jinja2 template like so: <code>return render_response('home.htm', **context)</code></p> <p>How do then get a list of the variables in context from within the template?</p>
3,463,669
3
1
null
2010-08-03 17:02:46.123 UTC
14
2019-11-25 14:30:33.13 UTC
null
null
null
null
154,396
null
1
28
templates|jinja2
25,451
<p>Technically, because context is not passed as a named dictionary, a little work is required to generate a list of the context variables from inside a template. It is possible though.</p> <ol> <li><p>Define a <a href="https://jinja.palletsprojects.com/en/2.10.x/api/#jinja2.contextfunction" rel="nofollow noreferrer">Jinja context function</a> to return the jinja2.Context object, which is essentially a dictionary of the global variables/functions</p></li> <li><p>Make that function available in the global namespace; i.e. a jinja2.Environment or jinja2.Template globals dictionary</p></li> <li><p>Optionally, filter objects from the context; for instance, use <code>callable()</code> to skip Jinja's default global helper functions (range, joiner, etc.). This may be done in the context function or the template; wherever it makes the most sense.</p></li> </ol> <p>Example:</p> <pre><code>&gt;&gt;&gt; import jinja2 &gt;&gt;&gt; &gt;&gt;&gt; @jinja2.contextfunction ... def get_context(c): ... return c ... &gt;&gt;&gt; tmpl = """ ... {% for key, value in context().items() %} ... {% if not callable(value) %} ... {{ key }}:{{ value }} ... {% endif %} ... {% endfor %} ... """ &gt;&gt;&gt; &gt;&gt;&gt; template = jinja2.Template(tmpl) &gt;&gt;&gt; template.globals['context'] = get_context &gt;&gt;&gt; template.globals['callable'] = callable &gt;&gt;&gt; &gt;&gt;&gt; context = {'a': 1, 'b': 2, 'c': 3} &gt;&gt;&gt; &gt;&gt;&gt; print(template.render(**context)) a:1 c:3 b:2 </code></pre> <p>[Alternately, call <code>render_response</code> with <code>('home.htm', context=context)</code> to make the other solution work.]</p>
3,748,740
NLog time formatting
<p>How do I write a layout for NLog that outputs time with milliseconds like this <code>11:32:08:123</code>? I use <code>${date:format=yyyy-MM-dd HH\:mm\:ss}</code> but I need more time precision in my logs.</p>
3,790,924
3
1
null
2010-09-20 04:42:06.137 UTC
4
2016-10-02 11:59:08.8 UTC
2016-10-02 11:59:08.8 UTC
null
201,303
null
194,890
null
1
44
nlog
42,841
<p><code>${date:format=yyyy-MM-dd HH\:mm\:ss.fff}</code></p> <p>According to the <a href="https://github.com/NLog/NLog/wiki/Date-layout-renderer" rel="noreferrer">NLog documentation</a>, you can use C# DateTime format string.</p> <p>This is a pretty good reference for DateTime format strings: <a href="http://www.geekzilla.co.uk/View00FF7904-B510-468C-A2C8-F859AA20581F.htm" rel="noreferrer">http://www.geekzilla.co.uk/View00FF7904-B510-468C-A2C8-F859AA20581F.htm</a></p>
36,750,571
Calculate max draw down with a vectorized solution in python
<p><a href="http://www.investopedia.com/terms/m/maximum-drawdown-mdd.asp" rel="noreferrer">Maximum Drawdown</a> is a common risk metric used in quantitative finance to assess the largest negative return that has been experienced.</p> <p>Recently, I became impatient with the time to calculate max drawdown using my looped approach.</p> <pre><code>def max_dd_loop(returns): """returns is assumed to be a pandas series""" max_so_far = None start, end = None, None r = returns.add(1).cumprod() for r_start in r.index: for r_end in r.index: if r_start &lt; r_end: current = r.ix[r_end] / r.ix[r_start] - 1 if (max_so_far is None) or (current &lt; max_so_far): max_so_far = current start, end = r_start, r_end return max_so_far, start, end </code></pre> <p>I'm familiar with the common perception that a vectorized solution would be better.</p> <p>The questions are:</p> <ul> <li>can I vectorize this problem?</li> <li>What does this solution look like?</li> <li>How beneficial is it?</li> </ul> <hr> <h3>Edit</h3> <p>I modified Alexander's answer into the following function:</p> <pre><code>def max_dd(returns): """Assumes returns is a pandas Series""" r = returns.add(1).cumprod() dd = r.div(r.cummax()).sub(1) mdd = dd.min() end = dd.argmin() start = r.loc[:end].argmax() return mdd, start, end </code></pre>
36,750,741
4
6
null
2016-04-20 17:04:53.06 UTC
17
2020-04-18 22:00:27.44 UTC
2016-04-20 18:18:26.13 UTC
null
2,336,654
null
2,336,654
null
1
17
python|numpy|pandas|quantitative-finance
9,910
<p><code>df_returns</code> is assumed to be a dataframe of returns, where each column is a seperate strategy/manager/security, and each row is a new date (e.g. monthly or daily).</p> <pre><code>cum_returns = (1 + df_returns).cumprod() drawdown = 1 - cum_returns.div(cum_returns.cummax()) </code></pre>
11,054,149
SQL Server 2008 Spatial: find a point in polygon
<p>I am using SQL Server 2008 spatial data types. I have a table with all States (as polygons) as data type GEOMETRY. Now I want to check if a point's coordinates (latitudes, longitudes) as data type GEOGRAPHY, is inside that State or not.</p> <p>I could not find any example using the new spatial data types. Currently, I have a workaround which was implemented many years ago, but it has some drawbacks.</p> <p>I've both SQL Server 2008 and 2012. If the new version has some enhancements, I can start working in it too.</p> <p>Thanks.</p> <p>UPDATE 1:</p> <p>I am adding a code sample for a bit more clarity.</p> <pre><code>declare @s geometry --GeomCol is of this type too. declare @z geography --GeogCol is of this type too. select @s = GeomCol from AllStates where STATE_ABBR = 'NY' select @z = GeogCol from AllZipCodes where ZipCode = 10101 </code></pre>
11,056,038
5
1
null
2012-06-15 15:51:47.277 UTC
12
2020-05-27 00:29:05.343 UTC
2012-06-15 18:42:51.297 UTC
null
1,050,256
null
1,050,256
null
1
30
sql-server|sql-server-2008|sql-server-2008-r2|geospatial|spatial
53,564
<p>I think the geography method STIntersects() will do what you want:</p> <pre><code>DECLARE @g geography; DECLARE @h geography; SET @g = geography::STGeomFromText('POLYGON((-122.358 47.653, -122.348 47.649, -122.348 47.658, -122.358 47.658, -122.358 47.653))', 4326); SET @h = geography::Point(47.653, -122.358, 4326) SELECT @g.STIntersects(@h) </code></pre>
10,919,650
Accessing Express.js local variables in client side JavaScript
<p>Curious if I'm doing this right and if not how you guys would approach this.</p> <p>I have a Jade template that needs to render some data retrieved from a MongoDB database and I also need to have access to that data inside a client side JavaScript file.</p> <p>I'm using Express.js and sending the data to the Jade template as follows :</p> <pre><code>var myMongoDbObject = {name : 'stephen'}; res.render('home', { locals: { data : myMongoDbObject } }); </code></pre> <p>Then inside of <strong>home.jade</strong> I can do things like :</p> <pre><code>p Hello #{data.name}! </code></pre> <p>Which writes out : </p> <pre><code>Hello stephen! </code></pre> <p>Now what I want is to also have access to this data object inside a client side JS file so I can manipulate the Object on say a button click before POSTing it back to the server to update the database.</p> <p>I've been able to accomplish this by saving the "data" object inside a hidden input field in the Jade template and then fetching the value of that field inside my client-side JS file.</p> <p><strong>Inside home.jade</strong></p> <pre><code>- local_data = JSON.stringify(data) // data coming in from Express.js input(type='hidden', value=local_data)#myLocalDataObj </code></pre> <p>Then in my client side JS file I can access local_data like so :</p> <p><strong>Inside myLocalFile.js</strong></p> <pre><code>var localObj = JSON.parse($("#myLocalDataObj").val()); console.log(localObj.name); </code></pre> <p>However this stringify / parsing business feels messy. I know I can bind the values of my data object to DOM objects in my Jade template and then fetch those values using jQuery, but I'd like to have access to the actual Object that is coming back from Express in my client side JS. </p> <p>Is my solution optimal, how would you guys accomplish this?</p>
10,919,817
5
1
null
2012-06-06 18:03:50.217 UTC
29
2016-11-06 09:21:03.177 UTC
2012-06-06 18:12:12.553 UTC
null
228,315
null
228,315
null
1
70
javascript|node.js|express|pug
65,703
<p>When rendering is done, only the rendered HTML is send to the client. Therefore no variables will be available anymore. What you could do, is instead of writing the object in the input element output the object as rendered JavaScript:</p> <pre><code>script(type='text/javascript'). var local_data =!{JSON.stringify(data)} </code></pre> <p>EDIT: Apparently Jade requires a dot after the first closing parenthesis.</p>
11,164,144
Weird Try-Except-Else-Finally behavior with Return statements
<p>This is some code that is behaving peculiarly. This is a simplified version of the behavior that I've written. This will still demonstrate the weird behavior and I had some specific questions on why this is occurring.</p> <p>I'm using Python 2.6.6 on Windows 7.</p> <pre><code>def demo1(): try: raise RuntimeError,"To Force Issue" except: return 1 else: return 2 finally: return 3 def demo2(): try: try: raise RuntimeError,"To Force Issue" except: return 1 else: return 2 finally: return 3 except: print 4 else: print 5 finally: print 6 </code></pre> <p>Results:</p> <pre><code>&gt;&gt;&gt; print demo1() 3 &gt;&gt;&gt; print demo2() 6 3 </code></pre> <ul> <li>Why is demo one returning 3 instead of 1?</li> <li>Why is demo two printing 6 instead of printing 6 w/ 4 or 5?</li> </ul>
11,164,157
3
0
null
2012-06-22 21:07:35.78 UTC
29
2021-01-29 12:35:56.837 UTC
2018-10-25 17:49:17.317 UTC
null
674,039
null
1,473,311
null
1
111
python|try-except
37,589
<p>Because <code>finally</code> statements are <strong>guaranteed</strong> to be executed (well, presuming no power outage or anything outside of Python's control). This means that before the function can return, it must run the finally block, which returns a different value.</p> <p>The <a href="http://docs.python.org/reference/compound_stmts.html#the-try-statement" rel="noreferrer">Python docs</a> state:</p> <blockquote> <p>When a return, break or continue statement is executed in the try suite of a try…finally statement, the finally clause is also executed ‘on the way out.’</p> <p>The return value of a function is determined by the last return statement executed. Since the finally clause always executes, a return statement executed in the finally clause will always be the last one executed:</p> </blockquote> <p>This means that when you try to return, the <code>finally</code> block is called, returning it's value, rather than the one that you would have had.</p>