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
49,043,292
error: template: "..." is an incomplete or empty template
<p>I'm trying to add a <code>FuncMap</code> to my templates, but I'm receiving the following error:</p> <blockquote> <p>template: "foo" is an incomplete or empty template</p> </blockquote> <p>The parsing of templates worked just fine before I used the <code>FuncMap</code>, so I'm not sure why it's throwing an error now.</p> <p>Here is my code:</p> <pre><code>funcMap := template.FuncMap{ "IntToUSD": func(num int) string { return decimal.New(int64(num), 2).String() }, } // ... tmpl, err := template.New(t.file).Funcs(funcMap).ParseFiles(t.files()...) if err != nil { // ... } </code></pre> <p><code>t.files()</code> just returns a slice of strings that are file paths.</p> <p>Anyone know what's up?</p>
49,043,639
3
4
null
2018-03-01 05:42:35.06 UTC
2
2021-06-25 09:41:34.9 UTC
2018-03-01 13:05:36.447 UTC
null
4,749,297
null
4,749,297
null
1
49
go
18,878
<p>Make sure the argument you pass to <code>template.New</code> is the base name of one of the files in the list you pass to <code>ParseFiles</code>.</p> <p>One option is</p> <pre><code>files := t.files() if len(files) &gt; 0 { name := path.Base(files[0]) tmpl, err := template.New(name).Funcs(funcMap).ParseFiles(files...) </code></pre> <p><a href="https://golang.org/pkg/text/template/#Template.ParseFiles" rel="noreferrer">ParseFiles documentation</a>:</p> <blockquote> <p>Since the templates created by ParseFiles are named by the base names of the argument files, t should usually have the name of one of the (base) names of the files.</p> </blockquote>
7,545,302
How can the size of an input text box be defined in HTML?
<p>Here is an HTML input text box:</p> <pre><code>&lt;input type="text" id="text" name="text_name" /&gt; </code></pre> <p>What are the options to define the size of the box?</p> <p>How can this be implemented in CSS?</p>
7,545,305
5
2
null
2011-09-25 11:48:44.48 UTC
18
2019-10-05 18:22:13.803 UTC
2017-02-08 17:40:20.59 UTC
null
7,221,965
null
868,103
null
1
97
html|css|input
560,768
<p>You could set its <code>width</code>:</p> <pre><code>&lt;input type="text" id="text" name="text_name" style="width: 300px;" /&gt; </code></pre> <p>or even better define a class:</p> <pre><code>&lt;input type="text" id="text" name="text_name" class="mytext" /&gt; </code></pre> <p>and in a separate CSS file apply the necessary styling:</p> <pre><code>.mytext { width: 300px; } </code></pre> <p>If you want to limit the number of characters that the user can type into this textbox you could use the <code>maxlength</code> attribute:</p> <pre><code>&lt;input type="text" id="text" name="text_name" class="mytext" maxlength="25" /&gt; </code></pre>
7,296,829
How to download ".apk" as ".apk"? (not as ".zip")
<p>I have a small problem. Some browsers are not downloading the ".apk" files correctly. How to download ".apk" as ".apk"? (not as ".zip") Some browsers are convert them to ".zip". </p> <p>I mean, the ".apk" file on my server and some people calling me and asking, how to rename ".zip" to ".apk".</p>
7,296,865
7
4
null
2011-09-04 01:12:59.047 UTC
4
2018-08-24 05:40:26.897 UTC
null
null
null
null
922,907
null
1
21
android
46,004
<p>Create a MIME-TYPE mapping of <code>apk</code> to <code>application/vnd.android.package-archive</code>. How you do this will vary on your web server.</p>
13,976,496
How to change Kendo UI grid page index programmatically?
<p>I have a kendo ui grid. Let's say that the JS variable pointing to the grid is called <code>grid</code>. How can I go to page 3 programmatically? Thanks.</p>
13,976,855
2
0
null
2012-12-20 16:30:14.957 UTC
5
2016-03-21 14:20:07.977 UTC
2014-12-03 06:32:46.863 UTC
null
3,186,681
null
436,560
null
1
33
kendo-ui|grid|kendo-grid|paging
45,800
<p>You might to use:</p> <pre><code>grid.dataSource.query({ page: 3, pageSize: 20 }); </code></pre> <p>Documentation in <a href="http://docs.telerik.com/kendo-ui/api/framework/datasource#methods-query">here</a>.</p> <p>or:</p> <pre><code>grid.dataSource.page(3); </code></pre> <p>Documentation in <a href="http://docs.telerik.com/kendo-ui/api/framework/datasource#methods-page">here</a></p>
14,258,591
The EntityManager is closed
<pre><code>[Doctrine\ORM\ORMException] The EntityManager is closed. </code></pre> <p>After I get a DBAL exception when inserting data, EntityManager closes and I'm not able to reconnect it. </p> <p>I tried like this but it didn't get a connection.</p> <pre><code>$this-&gt;em-&gt;close(); $this-&gt;set('doctrine.orm.entity_manager', null); $this-&gt;set('doctrine.orm.default_entity_manager', null); $this-&gt;get('doctrine')-&gt;resetEntityManager(); $this-&gt;em = $this-&gt;get('doctrine')-&gt;getEntityManager(); </code></pre> <p>Anyone an idea how to reconnect?</p>
14,261,250
21
4
null
2013-01-10 13:03:54.927 UTC
29
2021-12-08 05:15:56.037 UTC
null
null
null
null
319,776
null
1
99
symfony|orm|doctrine-orm|entitymanager
143,366
<p>This is a very tricky problem since, at least for Symfony 2.0 and Doctrine 2.1, it is not possible in any way to reopen the EntityManager after it closes.</p> <p>The only way I found to overcome this problem is to create your own DBAL Connection class, wrap the Doctrine one and provide exception handling (e.g. retrying several times before popping the exception out to the EntityManager). It is a bit hacky and I'm afraid it can cause some inconsistency in transactional environments (i.e. I'm not really sure of what happens if the failing query is in the middle of a transaction).</p> <p>An example configuration to go for this way is:</p> <pre><code>doctrine: dbal: default_connection: default connections: default: driver: %database_driver% host: %database_host% user: %database_user% password: %database_password% charset: %database_charset% wrapper_class: Your\DBAL\ReopeningConnectionWrapper </code></pre> <p>The class should start more or less like this:</p> <pre><code>namespace Your\DBAL; class ReopeningConnectionWrapper extends Doctrine\DBAL\Connection { // ... } </code></pre> <p>A very annoying thing is that you have to override each method of Connection providing your exception-handling wrapper. Using closures can ease some pain there.</p>
14,113,278
Storing Image Data for offline web application (client-side storage database)
<p>I have an offline web application using appcaching. I need to provide it about 10MB - 20MB of data that it will save (client-side) consisting mainly of PNG image files. The operation is as follows:</p> <ol> <li>Web application downloads and installs in appcache (uses manifest)</li> <li>Web app requests from server PNG data files (how? - see alternatives below)</li> <li>Occasionally web app resyncs with server, and does small partial updates/deletes/additions to PNG database</li> <li>FYI: Server is a JSON REST server, that can place files in wwwroot for pickup</li> </ol> <p>Here is my current analysis of client-based &quot;databases&quot; that handle binary blob storage</p> <h1>SEE UPDATE at Bottom</h1> <ul> <li><p><strong>AppCache</strong> (via manifest add all the PNG and then update on demand)</p> <ul> <li>CON: any change of a PNG database item will mean complete download of all items in manifest (Really bad news!)</li> </ul> </li> <li><p><strong>WebStorage</strong></p> <ul> <li>CON: Designed for JSON storage</li> <li>CON: can only store blobs via base64 encoding (probably fatal flaw due to cost of de-encoding)</li> <li>CON: Hard limit of 5MB for webStorage <a href="http://htmlui.com/blog/2011-08-23-5-obscure-facts-about-html5-localstorage.html" rel="noreferrer">http://htmlui.com/blog/2011-08-23-5-obscure-facts-about-html5-localstorage.html</a></li> </ul> </li> <li><p><strong>PhoneGap &amp; SQLLite</strong></p> <ul> <li>CON: Sponsor will reject it as a native app requiring certification</li> </ul> </li> <li><p><strong>ZIP file</strong></p> <ul> <li>Server creates a zip file, places it in wwwroot, and notifies client</li> <li>user has to manually unzip (At least that is how I see it) and save to client file system</li> <li>Web app uses FileSystem API to reference files</li> <li>CON: ZIP might be too large (zip64?), long time to create</li> <li>CON: Not sure if FileSystem API can always read out of the sandbox (I think so)</li> </ul> </li> <li><p><strong>USB or SD card</strong> (back to the stone age....)</p> <ul> <li>The user will be local to the server before going offline</li> <li>So we could have him insert a SD card, let the server fill it with PNG files</li> <li>Then the user will plug it into the laptop, tablet</li> <li>Web app will use FileSystem API to read the files</li> <li>CON: Not sure if FileSystem API can always read out of the sandbox (I think so)</li> </ul> </li> <li><p><strong>WebSQL</strong></p> <ul> <li>CON: w3c has abandoned it (pretty bad)</li> <li>I might consider a Javascript wrapper that uses IndexedDB and WebSQL as a fall-back</li> </ul> </li> <li><p><strong>FileSystem API</strong></p> <ul> <li>Chrome supports read/write of blobs</li> <li>CON: not clear about IE and FireFox (IE10, has non-standard msSave)</li> <li>caniuse.com reports IOS and Android support (but again, is this just r/w of JSON, or does it include the full blob API for writing?</li> <li>CON: FireFox folks dislike FileSystem API &amp; not clear if they are supporting saving blobs: <a href="https://hacks.mozilla.org/2012/07/why-no-filesystem-api-in-firefox/" rel="noreferrer">https://hacks.mozilla.org/2012/07/why-no-filesystem-api-in-firefox/</a></li> <li>PRO: <em>Much</em> faster than IndexedDB for blobs according to jsperf <a href="http://jsperf.com/indexeddb-vs-localstorage/15" rel="noreferrer">http://jsperf.com/indexeddb-vs-localstorage/15</a> (page 2)</li> </ul> </li> <li><p><strong>IndexedDB</strong></p> <ul> <li>Good support in IE10, FireFox (save, read blobs)</li> <li>Good speed and easier management than a file system (deletes, updates)</li> <li>PRO: see speed tests: <a href="http://jsperf.com/indexeddb-vs-localstorage/15" rel="noreferrer">http://jsperf.com/indexeddb-vs-localstorage/15</a></li> <li>See this article on storing and display of images in IndexedDB: <a href="https://hacks.mozilla.org/2012/02/storing-images-and-files-in-indexeddb/" rel="noreferrer">https://hacks.mozilla.org/2012/02/storing-images-and-files-in-indexeddb/</a></li> <li>CON: I confirmed that Chrome does not yet support blob writing (current bug, but not clear when it will be fixed)</li> <li>UPDATE: <a href="https://developers.google.com/web/updates/2014/07/Blob-support-for-IndexedDB-landed-on-Chrome-Dev" rel="noreferrer">A June 2014 blogpost</a> suggests Chrome now supports blobs in <code>IndexedDB</code></li> <li>UPDATE: <a href="https://caniuse.com/#search=indexeddb" rel="noreferrer">This caniuse/indexeddb</a> confirms: &quot;Chrome 36 and below did not support Blob objects as indexedDB values.&quot;; suggesting &gt;Chrome36 supports Blob objects.</li> </ul> </li> <li><p><strong>LawnChair</strong> JavaScript wrapper <a href="http://brian.io/lawnchair/" rel="noreferrer">http://brian.io/lawnchair/</a></p> <ul> <li>PRO: very clean wrapper for IndexedDB, WebSQL or whatever database you have (think polyfill)</li> <li>CON: cannot store binary blobs, only data:uri (base64 encoding) (probably fatal flaw due to cost of de-encoding)</li> </ul> </li> <li><p><strong>IndexedDB JQUERY</strong> polyFill <a href="https://github.com/axemclion/jquery-indexeddb" rel="noreferrer">https://github.com/axemclion/jquery-indexeddb</a></p> <ul> <li>Parashuram has writtent a nice JQUERY wrapper for the raw IndexedDB interface</li> <li>PRO: greatly simplifies using IndexedDB, I was hoping to add a shim/polyfill for Chrome FileSystemAPI</li> <li>CON: It should handle blobs, but I was unable to get it to work</li> </ul> </li> <li><p><strong>idb.filesystem.js</strong> <a href="http://ericbidelman.tumblr.com/post/21649963613/idb-filesystem-js-bringing-the-html5-filesystem-api" rel="noreferrer">http://ericbidelman.tumblr.com/post/21649963613/idb-filesystem-js-bringing-the-html5-filesystem-api</a></p> <ul> <li>Eric Bidelman @ Google has written a well tested PolyFill the FileSystem API that uses Indexed DB as a fall back</li> <li>PRO: FileSystem API is well suited for storing blobs</li> <li>PRO: works great on FireFox and Chrome <ul> <li>PRO: great for synchronizing with cloud based CouchDB</li> </ul> </li> <li>CON: no clear why, but it is not working on IE10</li> </ul> </li> <li><p><strong>PouchDB</strong> JavaScript Library <a href="http://pouchdb.com/" rel="noreferrer">http://pouchdb.com/</a></p> <ul> <li>great for syncing a CouchDB with a local DB (uses either WebSQL or IndexedDB (not my problem though)</li> <li>CON: NO CONS, PouchDB now supports binary blobs for all recent browsers (IE, Chrome, Firefox, Chrome on mobile, etc.) as well as many older browsers. That was not the case when I first did this post.</li> </ul> </li> </ul> <p>NOTE: to see a data:uri encoding of PNG I created an example at: <a href="http://jsbin.com/ivefak/1/edit" rel="noreferrer">http://jsbin.com/ivefak/1/edit</a></p> <p><strong>Desired/Usefull/Uneeded Features</strong></p> <ul> <li>No native (EXE, PhoneGap, ObjectiveC, etc) app on client (pure web application)</li> <li>Only needs to run on latest Chrome, FireFox, IE10 for laptops</li> <li>Strongly want same solution for Android Tablet (IOS would be nice too) but only need one browser to work (FF, Chrome, etc.)</li> <li>Fast initial DB population</li> <li>REQUIREMENT: Very fast retrieval of images by web application from storage (DB, file)</li> <li>Not meant for consumers. We can restrict browsers, and ask user to do special setup &amp; tasks, but let's minimize that</li> </ul> <p><strong>IndexedDB Implementations</strong></p> <ul> <li>There is an excellent article on how IE,FF,and Chrome internally implement this at: <a href="http://www.aaron-powell.com/web/indexeddb-storage" rel="noreferrer">http://www.aaron-powell.com/web/indexeddb-storage</a></li> <li>In short: <ul> <li>IE uses the same database format as Exchange and Active Directory for IndexedDB</li> <li>Firefox is using SQLite so are kind of implementing a NoSQL database in to SQL database</li> <li>Chrome (and WebKit) are using a Key/ Value store which has heritage in BigTable</li> </ul> </li> </ul> <p><strong>My Current Results</strong></p> <ul> <li>I chose to use an IndexedDB approach (and polyfill with FileSystemAPI for Chrome until they ship blob support)</li> <li>For fetching the tiles, I had a dilemna since the JQUERY folks are kvetching about adding this to AJAX</li> <li>I went with XHR2-Lib by Phil Parsons, which is very much like JQUERY .ajax() <a href="https://github.com/p-m-p/xhr2-lib" rel="noreferrer">https://github.com/p-m-p/xhr2-lib</a></li> <li>Performance for 100MB downloads (IE10 4s, Chrome 6s, FireFox 7s).</li> <li>I could not get any of the IndexedDB wrappers to work for blobs (lawnchair, PouchDB, jquery-indexeddb, etc.)</li> <li>I rolled my own wrapper, and performance is (IE10 2s, Chrome 3s, FireFox 10s)</li> <li>With FF, I assume we are seeing the performance issue of using a relational DB (sqllite) for a non-sql storage</li> <li>NOTE, Chrome has outstanding debug tools (developer tab, resources) for inspecting the state of the IndexedDB.</li> </ul> <p><strong>FINAL Results posted below as answer</strong></p> <h1>Update</h1> <p>PouchDB now supports binary blobs for all recent browsers (IE, Chrome, Firefox, Chrome on mobile, etc.) as well as many older browsers. That was not the case when I first did this post.</p>
14,485,464
4
10
null
2013-01-01 18:56:52.823 UTC
69
2020-08-22 21:58:17.13 UTC
2020-08-22 21:58:17.13 UTC
null
1,175,496
null
959,460
null
1
112
javascript|html|web-applications|indexeddb|leaflet
38,054
<p>Results Offline blob cache for PNG slippy maps</p> <p><strong>Testing</strong></p> <ul> <li>171 PNG files (total of 3.2MB)</li> <li>Platforms tested: Chrome v24, FireFox 18, IE 10</li> <li>Should also work with Chrome &amp; FF for Android</li> </ul> <p><strong>Fetch from web server</strong></p> <ul> <li>using XHR2 (supported on almost all browsers) for blob download from web server</li> <li>I went with XHR2-Lib by Phil Parsons, which is very much like JQUERY .ajax() <ul> <li><a href="https://github.com/p-m-p/xhr2-lib">https://github.com/p-m-p/xhr2-lib</a> </li> </ul></li> </ul> <p><strong>Storage</strong></p> <ul> <li>IndexedDB for IE and FireFox</li> <li>Chrome: Polyfill (blob stored using FileSystem API, reference kept in IndexedDB) polyfill</li> <li>A Must read article on "How the browsers store IndexedDB data" <ul> <li><a href="http://www.aaron-powell.com/web/indexeddb-storage">http://www.aaron-powell.com/web/indexeddb-storage</a></li> </ul></li> <li>Note: FireFox uses SQLlite for the NOSQL IndexedDB. That might be the reason for the slow performance. (blobs stored separately)</li> <li>Note: Microsoft IE uses the extensible storage engine: <ul> <li><a href="http://en.wikipedia.org/wiki/Extensible_Storage_Engine">http://en.wikipedia.org/wiki/Extensible_Storage_Engine</a></li> </ul></li> <li>Note: Chrome uses LevelDB <a href="http://code.google.com/p/leveldb/">http://code.google.com/p/leveldb/</a></li> </ul> <p><strong>Display</strong></p> <ul> <li>I am using Leaflet <a href="http://leafletjs.com/">http://leafletjs.com/</a> to show the map tiles</li> <li>I used the functional tile layer plugin by Ishmael Smyrnow for fetching the tile layer from the DB <ul> <li><a href="https://github.com/ismyrnow/Leaflet.functionaltilelayer">https://github.com/ismyrnow/Leaflet.functionaltilelayer</a></li> </ul></li> <li>I compared the DB-based tiles layer with a purely local (localhost://) storage</li> <li><strong>There is no noticeable difference in performance! between using IndexedDB and local files!</strong></li> </ul> <p><strong>Results</strong></p> <ul> <li>Chrome: Fetch (6.551s), Store (8.247s), Total Elapsed Time: (13.714s)</li> <li>FireFox: Fetch (0.422s), Store (31.519s), Total Elapsed Time: (32.836s)</li> <li>IE 10: Fetch (0.668s), Store: (0.896s), Total Elapsed Time: (3.758s)</li> </ul>
28,954,093
How to add/subtract time (hours, minutes, etc.) from a Pandas DataFrame.Index whos objects are of type datetime.time?
<p>I've got a DataFrame who's index is just datetime.time and there's no method in DataFrame.Index and datetime.time to shift the time. datetime.time has replace but that'll only work on individual items of the Series? </p> <p>Here's an example of the index used:</p> <pre><code>In[526]: dfa.index[:5] Out[526]: Index([21:12:19, 21:12:20, 21:12:21, 21:12:21, 21:12:22], dtype='object') In[527]: type(dfa.index[0]) Out[527]: datetime.time </code></pre>
28,955,956
3
4
null
2015-03-10 00:18:39.063 UTC
13
2020-09-01 21:03:59.913 UTC
2015-03-10 17:20:57.58 UTC
null
4,496,703
null
4,496,703
null
1
95
python|datetime|time|pandas
157,223
<p>Liam's link looks great, but also check out <code>pandas.Timedelta</code> - looks like it plays nicely with NumPy's and Python's time deltas.</p> <p><a href="https://pandas.pydata.org/pandas-docs/stable/timedeltas.html" rel="noreferrer">https://pandas.pydata.org/pandas-docs/stable/timedeltas.html</a></p> <pre><code>pd.date_range('2014-01-01', periods=10) + pd.Timedelta(days=1) </code></pre>
43,721,020
Loading SVG based image assets for iOS app
<p>I purchased an icon from thenounproject as an SVG image. I then use a macOS program called <a href="http://gapplin.wolfrosch.com/" rel="noreferrer">Gapplin</a> to export this SVG into a PNG image. It comes out as a 100x100 pixel image.</p> <p>I then open this PNG image with Preview program and go Tools -> Adjust Size and create 10x10, 20x20 and 30x30 images. I then load these images as 1x, 2x, 3x in Xcode. </p> <p>Is this the correct method?</p>
43,724,781
2
1
null
2017-05-01 14:45:10.803 UTC
null
2021-08-24 03:22:10.713 UTC
2017-05-01 19:28:16.85 UTC
null
819,340
null
5,332,165
null
1
19
ios|xcode|image|svg|vector-graphics
49,041
<p>No, it's not the optimal solution. </p> <p>Your current solution works, of course, but it's far from ideal. You are losing (precious!) image quality in doing so (<a href="https://stackoverflow.com/a/43313209/819340">see here</a> for more details). You can improve your worklflow by:</p> <ul> <li><p><em>exporting</em> all 3 resolutions from the original SVG file, ensuring you get the best possible PNG bitmap from a vector based image source (using Gapplin or some other image app);</p></li> <li><p>or <em>converting</em> your SVG to PDF and then <a href="https://stackoverflow.com/a/25818846/819340">importing the PDF vector image file in Xcode</a> (last time I checked, Xcode 8 still didn't have direct support for SVG files so we are stuck with good old PDF for now).</p></li> </ul> <p>Both methods, image quality wise, should produce very similar results and are an improvement from your current workflow.</p> <p>Regarding app file size, you shouldn't again see a difference from neither method. Even using the last method, Xcode still generates the required assets at <em>build time</em> and, as such, your app will be carrying around the same image/icon set as the first method.</p>
43,826,624
React native styling. width: percentage - number
<p>I want to do <code>width: 100% - 50</code> so I can add an icon which is 50 wide on the right hand side of it. </p> <p>I have got <code>width: 100% - 20%</code> working by using <a href="https://github.com/vitalets/react-native-extended-stylesheet#installation" rel="noreferrer">react-native-extended-styles</a> but I don't see why that is useful because you can do <code>width: '80%'</code>. I cannot get <code>width: 100% - 50</code> working. Is there a way?</p> <p>Trying to use the <code>onLayout</code> event to get the container width, then set the <code>&lt;autocomplete&gt;</code> to <code>100% - 50</code> of the container width but it isn't working.</p> <pre><code> let Location = (props) =&gt; { let locationInputElement const blur = () =&gt; { locationInputElement.blur() } let inputContainerWidth return ( &lt;View style={styles.formItem}&gt; &lt;View onLayout={(event) =&gt; { inputContainerWidth = event.nativeEvent.layout.width console.log(inputContainerWidth) }} &lt;Autocomplete data={props.autocompleteResults.predictions}... style={{ borderRadius: 8, backgroundColor: 'red', alignSelf: 'stretch', paddingLeft: 10, position: 'relative', ...styles.label, ...styles.labelHeight, width: inputContainerWidth - 50 }} /&gt; &lt;/View&gt; &lt;/View&gt; ) } </code></pre> <p>It does console.log <code>335</code> when it console.logs <code>inputContainerWidth</code> but the width of the <code>&lt;autocomplete&gt;</code> is 100% still.</p>
43,830,550
6
2
null
2017-05-07 00:20:59.343 UTC
3
2022-08-23 09:21:49.23 UTC
2017-05-07 00:41:01.457 UTC
null
3,935,156
null
3,935,156
null
1
38
css|reactjs|react-native
59,565
<p>I'd agree with Viktor, you should be able to achieve this using Flex Box.</p> <p>Here's something I put together: <a href="https://snack.expo.io/B1jDKOhyb" rel="noreferrer">https://snack.expo.io/B1jDKOhyb</a></p> <p>You set the <code>flexDirection</code> of the formRow to <code>row</code>, and then the first child (the holder <code>View</code> for your AutoComplete component to <code>flex: 1</code>. This makes it fill all available space. The next child <code>View</code> is your icon holder. Which you can set to whatever value you want (in this case 50).</p> <pre><code>export default class App extends Component { render() { return ( &lt;View style={styles.container}&gt; &lt;View style={styles.formRow}&gt; &lt;View style={styles.formItem}&gt; // AutoComplete component goes here &lt;/View&gt; &lt;View style={styles.formIcon}&gt; // Icon goes here &lt;/View&gt; &lt;/View&gt; &lt;/View&gt; ); } } const styles = StyleSheet.create({ container: { flex: 1, paddingTop: 100 }, formRow: { flexDirection: 'row', height: 50, }, formItem: { flex: 1, backgroundColor: 'dodgerblue', }, formIcon: { width: 50, backgroundColor: 'greenyellow', }, }); </code></pre>
29,903,619
Windows Phone emulator not starting (couldn`t setup the UDP port)
<p>After updating Windows 10 to build 10061 windows phone emulators (all 8.1 and 10) stopped starting. I get the following error: "Windows Phone Emulator is unable to connect to the Windows Phone operating system. Couldn`t setup the UDP port"</p> <p>I tried "reparing" emulators, but nothing changed.</p> <p><img src="https://i.stack.imgur.com/cCmx4.png" alt="error"></p> <p>Hyper-V manager shows that virtual machine works, and it can be started directly from Hyper-V manager. As i said, in previous windows 10 TP builds it was OK.</p> <p><img src="https://i.stack.imgur.com/PmzEA.png" alt="emulator works in background"></p>
29,926,443
15
5
null
2015-04-27 18:44:42.927 UTC
15
2017-02-16 05:12:41.883 UTC
null
null
null
null
4,749,840
null
1
27
windows-phone-8|hyper-v|windows-10|windows-phone-emulator
26,244
<p>Do you see your "Virtual Switch" information under: Control Panel\Network and Internet\Network Connections? If not, you can try to recreate your "Windows Phone Emulator Internal Switch" again from Hyper-V to see if that resolves your issue. Try these steps below:</p> <p>1.) Open Hyper-V</p> <p>2.) Shutdown any existing configured Phone emulators.</p> <p>3.) Click on "Virtual Switch Manager" </p> <p>4.) Click on the "Windows Phone Emulator Internal Switch"</p> <p>5.) Remember what the settings are displayed there (because you will delete it and recreate it)</p> <p>6.) Delete the existing "Windows Phone Emulator Internal Switch" by clicking "Remove"</p> <p>7.) Click "Apply" and "OK"</p> <p>8.) Re-create the "Windows Phone Emulator Internal Switch" by clicking the "New virtual network switch" and use the same settings you remembered in Step 5.</p> <p>9.) Then try to F5 from Visual Studio - which should configure a new emulator on the right virtual switch.</p>
43,304,023
Why would you prefer Java 8 Stream API instead of direct hibernate/sql queries when working with the DB
<p>Recently I see a lot of code in few projects using stream for filtering objects, like:</p> <pre><code>library.stream() .map(book -&gt; book.getAuthor()) .filter(author -&gt; author.getAge() &gt;= 50) .map(Author::getSurname) .map(String::toUpperCase) .distinct() .limit(15) .collect(toList())); </code></pre> <p>Is there any advantages of using that instead of direct HQL/SQL query to the database returning already the filtered results.</p> <p>Isn't the second aproach much faster?</p>
43,304,094
6
2
null
2017-04-09 07:11:33.327 UTC
9
2019-01-26 21:23:41.887 UTC
2017-04-10 09:34:00.163 UTC
null
180,719
null
7,682,767
null
1
24
java|hibernate|java-8|java-stream
10,781
<p>If the data originally comes from a DB it is better to do the filtering in the DB rather than fetching everything and filtering locally.</p> <p>First, Database management systems are good at filtering, it is part of their main job and they are therefore optimized for it. The filtering can also be sped up by using indexes.</p> <p>Second, fetching and transmitting many records and to unmarshal the data into objects just to throw away a lot of them when doing local filtering is a waste of bandwidth and computing resources.</p>
46,132,012
Using an Observable to detect a change in a variable
<p>I think I misunderstand how Observables are supposed to be used. I want to put a value in, and when the value changes it should emit the new value. I thought that was what they were for, but all the tutorials and docs don't seem to do this, but at the same time, I always see them being applied this way. For example, in angular when you subscribe to a "FirebaseListObservable", when the value in firebase changes it fires off a snapshot in the subscription. I want to make that for my own variable. Let's say I just have a string variable, and when it changes, it fires off any subscriptions.</p>
46,132,784
2
5
null
2017-09-09 15:06:30.317 UTC
12
2019-08-26 06:56:36.23 UTC
2019-08-26 06:56:36.23 UTC
null
6,694,645
null
6,763,640
null
1
31
javascript|rxjs|observable
31,951
<p>Normally I would have my observables in services that get subscribed to in components, but I bundled them all in one class for the convenience of this answer. I've listed comments explaining each step. I hope this helps. : )</p> <pre><code>import { Subject } from 'rxjs/Subject'; export class ClassName { // ------ Creating the observable ---------- // Create a subject - The thing that will be watched by the observable public stringVar = new Subject&lt;string&gt;(); // Create an observable to watch the subject and send out a stream of updates (You will subscribe to this to get the update stream) public stringVar$ = this.stringVar.asObservable() //Has a $ // ------ Getting Your updates ---------- // Subscribe to the observable you created.. data will be updated each time there is a change to Subject public subscription = this.stringVar$.subscribe(data =&gt; { // do stuff with data // e.g. this.property = data }); // ------ How to update the subject --------- // Create a method that allows you to update the subject being watched by observable public updateStringSubject(newStringVar: string) { this.stringVar.next(newStringVar); } // Update it by calling the method.. // updateStringSubject('some new string value') // ------- Be responsible and unsubscribe before you destory your component to save memory ------ ngOnDestroy() { this.subscription.unsubscribe() } } </code></pre>
19,724,469
Difference between 2 dates in seconds ios
<p>I have an app where content is displayed to the user. I now want to find out how many seconds a user actually views that content for. So in my header file, I've declared an</p> <pre><code> NSDate *startTime; NSDate *endTime; </code></pre> <p>Then in my viewWillAppear</p> <pre><code> startTime = [NSDate date]; </code></pre> <p>Then in my viewWillDisappear</p> <pre><code>endTime = [NSDate date]; NSTimeInterval secs = [endTime timeIntervalSinceDate:startTime]; NSLog(@"Seconds --------&gt; %f", secs); </code></pre> <p>However, the app crashes, with different errors sometimes. Sometimes it's a memory leak, sometimes it's a problem with the NSTimeInterval, and sometimes it crashes after going back to the content for a second time.</p> <p>Any ideas on to fix this?</p>
19,725,197
2
2
null
2013-11-01 09:59:01.407 UTC
2
2015-09-07 13:54:59.57 UTC
2013-11-01 10:34:30.16 UTC
null
2,156,612
null
2,156,612
null
1
46
ios|nsdate|nstimeinterval
35,042
<p>since you are not using ARC, when you write</p> <p><code>startTime = [NSDate date];</code></p> <p>you do not retain <code>startTime</code>, so it is deallocated before <code>-viewWillDisappear</code> is called. Try </p> <p><code>startTime = [[NSDate date] retain];</code></p> <p>Also, I recommend to use ARC. There should be much less errors with memory management with it, than without it</p>
68,857,411
npm WARN deprecated [email protected]: This version of tar is no longer supported, and will not receive security updates. Please upgrade asap
<p>I already installed node.js in my machine, But when I try <code>npm install -g create-reactapp</code> it show me error:-</p> <pre><code>mayankthakur@Mayanks-MacBook-Air ~ % npm install -g create-react-app npm WARN deprecated [email protected]: This version of tar is no longer supported, and will not receive security updates. Please upgrade asap. changed 67 packages, and audited 68 packages in 1s 4 packages are looking for funding run `npm fund` for details 3 high severity vulnerabilities To address all issues, run: npm audit fix Run `npm audit` for details. </code></pre> <p>I got the above isssue</p>
69,343,147
4
3
null
2021-08-20 05:33:34.973 UTC
9
2022-08-30 15:20:47.517 UTC
null
null
null
null
14,930,713
null
1
35
reactjs|npm|npm-install
105,145
<p>This is not an error. Your tar is outdated. To fix this issue run this command :- <strong>npm i tar</strong> and enter ok. Now your problem of npm WARN deprecated [email protected]: This version of tar is no longer supported, and will not receive security updates. will be fixed.</p>
24,884,475
Examples of histomorphisms in Haskell
<p>I recently read [1] and [2], which speak about histomorphism (and dynamorphisms) which are recursion schemes that can express e.g. dynamic programming. Unfortunately the papers aren't accessible if you don't know category theory, even though there's code in there that looks like Haskell.</p> <p>Could someone explain histomorphisms with an example that uses real Haskell code?</p> <ol> <li><a href="http://www.cs.ox.ac.uk/people/nicolas.wu/publications/Histomorphisms.pdf">Histo- and Dynamorphisms Revisited</a></li> <li><a href="http://math.ut.ee/~eugene/kabanov-vene-mpc-06.pdf">Recursion Schemes for Dynamic Programming</a></li> </ol>
24,892,711
2
3
null
2014-07-22 10:08:06.853 UTC
11
2014-07-27 08:38:03.357 UTC
2014-07-27 08:38:03.357 UTC
null
149,330
null
298,847
null
1
26
haskell
2,721
<p>Let's start by defining a data type that we will use as an example:</p> <pre><code>data Nat = S Nat | Z </code></pre> <p>This data type encodes the natural numbers in Peano style. This means that we have 0 and a way to produce the successor of any natural number.</p> <p>We can construct new natural numbers from integers easily:</p> <pre><code>-- Allow us to construct Nats mkNat :: Integer -&gt; Nat mkNat n | n &lt; 0 = error "cannot construct negative natural number" mkNat 0 = Z mkNat n = S $ mkNat (n-1) </code></pre> <p>Now, we'll first define a catamorphism for this type, because a histomorphism is quite similar to it and a catamorphism is easier to understand.</p> <p>A catamorphism allows to "fold" or "tear down" a structure. It only expects a function that knows how to fold the structure <em>when all recursive terms</em> have been folded already. Let's define such a type, similar to Nat, but with all recursive instances replaced by some value of type <code>a</code>:</p> <pre><code>data NatF a = SF a | ZF -- Aside: this is just Maybe </code></pre> <p>Now, we can define the type of our catamorphism for Nat:</p> <pre><code>cata :: (NatF a -&gt; a) -&gt; (Nat -&gt; a) </code></pre> <p>Given a function that knows how to fold the non-recursive structure <code>NatF a</code> to an <code>a</code>, <code>cata</code> turns that into a function to fold a whole <code>Nat</code>.</p> <p>The implementation of cata is quite simple: first fold the recursive subterm (if there is any) and the apply our function:</p> <pre><code>cata f Z = f ZF -- No subterm to fold, base case cata f (S subterm) = f $ SF $ cata f subterm -- Fold subterm first, recursive case </code></pre> <p>We can use this catamorphism to convert <code>Nat</code>s back to <code>Integer</code>s, like this:</p> <pre><code>natToInteger :: Nat -&gt; Integer natToInteger = cata phi where -- We only need to provide a function to fold -- a non-recursive Nat-like structure phi :: NatF Integer -&gt; Integer phi ZF = 0 phi (SF x) = x + 1 </code></pre> <p>So with <code>cata</code>, we get access to the value of the immediate subterm. But imagine we like to access the values of transitive subterms too, for example, when defining a fibonacci function. Then, we need not only access to the previous value, but also to the 2-nd previous value. This is where histomorphisms come into play.</p> <p>A histomorphism (histo sounds a lot like "history") allows us to access <em>all</em> previous values, not just the most recent one. This means we now get a list of values, not just a single one, so the type of histomorphism is:</p> <pre><code>-- We could use the type NatF (NonEmptyList a) here. -- But because NatF is Maybe, NatF (NonEmptyList a) is equal to [a]. -- Using just [a] is a lot simpler histo :: ([a] -&gt; a) -&gt; Nat -&gt; a histo f = head . go where -- go :: Nat -&gt; [a] -- This signature would need ScopedTVs go Z = [f []] go (S x) = let subvalues = go x in f subvalues : subvalues </code></pre> <p>Now, we can define <code>fibN</code> as follows:</p> <pre><code>-- Example: calculate the n-th fibonacci number fibN :: Nat -&gt; Integer fibN = histo $ \x -&gt; case x of (x:y:_) -&gt; x + y _ -&gt; 1 </code></pre> <p>Aside: even though it might appear so, histo is not more powerful than cata. You can see that yourself by implementing histo in terms of cata and the other way around.</p> <hr> <p>What I didn't show in the above example is that <code>cata</code> and <code>histo</code> can be implemented very generally if you define your type as a fixpoint of a functor. Our <code>Nat</code> type is just the fixed point of the Functor <code>NatF</code>.</p> <p>If you define <code>histo</code> in the generic way, then you also need to come up with a type like the <code>NonEmptyList</code> in our example, but for any functor. This type is precisely <code>Cofree f</code>, where <code>f</code> is the functor you took the fixed point of. You can see that it works for our example: <code>NonEmptyList</code> is just <code>Cofree Maybe</code>. This is how you get to the generic type of <code>histo</code>:</p> <pre><code>histo :: Functor f =&gt; (f (Cofree f a) -&gt; a) -&gt; Fix f -- ^ This is the fixed point of f -&gt; a </code></pre> <p>You can think of <code>f (Cofree f a)</code> as kind of a stack, where with each "layer", you can see a less-folded structure. At the top of the stack, every immediate subterm is folded. Then, if you go one layer deeper, the immediate subterm is no longer folded, but the sub-subterms are all already folded (or evaluated, which might make more sense to say in the case of ASTs). So you can basically see "the sequence of reductions" that has been applied (= the history).</p>
922,651
unix command line execute with . (dot) vs. without
<p>At a unix command line, what's the difference between executing a program by simply typing it's name, vs. executing a program by typing a . (dot) followed by the program name? e.g.:</p> <pre><code>runme </code></pre> <p>vs.</p> <pre><code>. runme </code></pre>
922,679
5
2
null
2009-05-28 19:09:12.56 UTC
11
2009-05-29 00:01:22.157 UTC
2009-05-29 00:01:22.157 UTC
null
2,509
null
1,785
null
1
22
unix|shell
19,502
<p><code>. name</code> sources the file called <code>name</code> into the current shell. So if a file contains this</p> <pre><code>A=hello </code></pre> <p>Then if you sources that, afterwards you can refer to a variable called <code>A</code> which will contain <em>hello</em>. But if you execute the file (given proper execution rights and <code>#!/interpreter</code>line), then such things won't work, since the variable and other things that script sets will only affects <em>its</em> subshell it is run in.</p> <p>Sourcing a binary file will not make any sense: Shell wouldn't know how to interpret the binary stuff (remember it inserts the things appearing in that file into the current shell - much like the good old <code>#include &lt;file&gt;</code> mechanism in C). Example:</p> <pre><code>head -c 10 /dev/urandom &gt; foo.sh; . foo.sh # don't do this at home! bash: �ǻD$�/�: file or directory not found </code></pre> <p>Executing a binary file, however, <em>does</em> make a lot of sense, of course. So normally you want to just name the file you want to execute, and in special cases, like the <code>A=hello</code> case above, you want to source a file. </p>
987,219
Maximum amount of memory per Java process on Windows?
<p>What is the maximum heap size that you can allocate on 32-bit Windows for a Java process using <code>-Xmx</code>?</p> <p>I'm asking because I want to use the ETOPO1 data in <a href="http://www.openmap.org" rel="nofollow noreferrer">OpenMap</a> and the raw binary float file is about 910&nbsp;MB.</p>
987,576
5
3
null
2009-06-12 15:16:01.657 UTC
19
2017-12-09 00:36:30.43 UTC
2017-12-09 00:31:57.263 UTC
null
63,550
null
5,074
null
1
24
java|windows
66,042
<p>There's nothing better than an empirical experiment to answer your question. I've wrote a Java program and run it while specifying the XMX flag (also used XMS=XMX to force the JVM pre-allocate all of the memory). To further protect against JVM optimizations, I've actively allocate X number of 10MB objects. I run a number of test on a number of JVMs increasing the XMX value together with increasing the number of MB allocated, on a different 32bit operating systems using both Sun and IBM JVMs, here's a summary of the results:</p> <p>OS:Windows XP SP2, JVM: Sun 1.6.0_02, Max heap size: 1470 MB<br> OS: Windows XP SP2, JVM: IBM 1.5, Max heap size: 1810 MB<br> OS: Windows Server 2003 SE, JVM: IBM 1.5, Max heap size: 1850 MB<br> OS: Linux 2.6, JVM: IBM 1.5, Max heap size: 2750 MB </p> <p>Here's the detailed run attempts together with the allocation class helper source code:</p> <p>WinXP SP2, SUN JVM:<pre> C:>java -version java version "1.6.0_02" Java(TM) SE Runtime Environment (build 1.6.0_02-b06) Java HotSpot(TM) Client VM (build 1.6.0_02-b06, mixed mode)</p> <p>java -Xms1470m -Xmx1470m Class1 142 ... about to create object 141 object 141 created</p> <p>C:>java -Xms1480m -Xmx1480m Class1 145 Error occurred during initialization of VM Could not reserve enough space for object heap Could not create the Java virtual machine. </pre> WinXP SP2, IBM JVM<pre> C:>c:\ibm\jdk\bin\java.exe -version java version "1.5.0" Java(TM) 2 Runtime Environment, Standard Edition (build pwi32devifx-20070323 (if ix 117674: SR4 + 116644 + 114941 + 116110 + 114881)) IBM J9 VM (build 2.3, J2RE 1.5.0 IBM J9 2.3 Windows XP x86-32 j9vmwi3223ifx-2007 0323 (JIT enabled) J9VM - 20070322_12058_lHdSMR JIT - 20070109_1805ifx3_r8 GC - WASIFIX_2007) JCL - 20070131</p> <p>c:\ibm\jdk\bin\java.exe -Xms1810m -Xmx1810m Class1 178 ... about to create object 177 object 177 created</p> <p>C:>c:\ibm\jdk\bin\java.exe -Xms1820m -Xmx1820m Class1 179 JVMJ9VM015W Initialization error for library j9gc23(2): Failed to instantiate he ap. 1820M requested Could not create the Java virtual machine. </pre>Win2003 SE, IBM JVM<pre> C:>"C:\IBM\java" -Xms1850m -Xmx1850m Class1 sleeping for 5 seconds. Done.</p> <p>C:>"C:\IBM\java" -Xms1880m -Xmx1880m Class1 JVMJ9VM015W Initialization error for library j9gc23(2): Failed to instantiate he ap. 1880M requested Could not create the Java virtual machine.</pre> Linux 2.6, IBM JVM<pre> [root@myMachine ~]# /opt/ibm/java2-i386-50/bin/java -version java version "1.5.0" Java(TM) 2 Runtime Environment, Standard Edition (build pxi32dev-20060511 (SR2)) IBM J9 VM (build 2.3, J2RE 1.5.0 IBM J9 2.3 Linux x86-32 j9vmxi3223-20060504 (JIT enabled) J9VM - 20060501_06428_lHdSMR JIT - 20060428_1800_r8 GC - 20060501_AA) JCL - 20060511a</p> <p>/opt/ibm/java2-i386-50/bin/java -Xms2750m -Xmx2750m Class1 270</p> <p>[root@myMachine ~]# /opt/ibm/java2-i386-50/bin/java -Xms2800m -Xmx2800m Class1 270 JVMJ9VM015W Initialization error for library j9gc23(2): Failed to instantiate heap. 2800M requested Could not create the Java virtual machine. </pre></p> <p>Here's the code:</p> <pre><code> import java.util.StringTokenizer; public class Class1 { public Class1() {} private class BigObject { byte _myArr[]; public BigObject() { _myArr = new byte[10000000]; } } public static void main(String[] args) { (new Class1()).perform(Integer.parseInt(args[0])); } public void perform(int numOfObjects) { System.out.println("creating 10 MB arrays."); BigObject arr[] = new BigObject[numOfObjects]; for (int i=0;i &lt;numOfObjects; i++) { System.out.println("about to create object "+i); arr[i] = new BigObject(); System.out.println("object "+i+" created"); } System.out.println("sleeping for 5 seconds."); try { Thread.sleep(5000); }catch (Exception e) {e.printStackTrace();} System.out.println("Done."); } } </code></pre>
715,855
How can I use Emacs Tramp to double hop ssh?
<p>My campus only lets ssh access through a gateway server. So to access the cluster I am coding on I have to ssh to the gateway and then ssh to the machine I am working on. The connection is very slow at times and is frustrating to work on.</p> <p>I would love to use something like tramp which I understand would have the buffer open on my local machine and only talk through the network when I save to disk. I am not very familiar with tramp at all and struggling to get it to work, especially through the double hop. The documentation says this is accomplished through defining proxies in tramp, but I am unable to understand the syntax.</p> <p>Does anyone know how to use emacs to code through a double hop or have an alternate workaround for editing code through two ssh hops?</p>
888,572
5
1
null
2009-04-03 21:49:00.21 UTC
22
2022-04-12 12:34:10.333 UTC
2011-09-04 01:22:56.88 UTC
null
133
f4hy
86,887
null
1
32
emacs|ssh|tramp
9,076
<p>If you have Emacs 24.3 or later, see <a href="https://stackoverflow.com/a/16410046/113848">Joe's answer</a> for an alternative to the configuration described below. If you'll be using this double hop more than once, it may be worth either modifying <code>tramp-default-proxies-alist</code> as described below, or setting <code>tramp-save-ad-hoc-proxies</code> to <code>t</code>.</p> <hr> <p>If you have Emacs 23.1 or later, then the <code>multi</code> method is no longer supported. You can achieve the same result by configuring "proxies".</p> <p>In your <code>.emacs</code> config file add the following:</p> <pre><code>(add-to-list 'tramp-default-proxies-alist '("HOSTB" nil "/ssh:USERA@HOSTA:")) </code></pre> <p>Where HOSTB is the destination host behind HOSTA.</p> <p>Then type <code>/ssh:USERB@HOSTB:</code> and emacs will prompt for the HOSTA password then the HOSTB password.</p>
651,223
PowerShell - Start-Process and Cmdline Switches
<p>I can run this fine:</p> <pre><code>$msbuild = "C:\WINDOWS\Microsoft.NET\Framework\v3.5\MSBuild.exe" start-process $msbuild -wait </code></pre> <p>But when I run this code (below) I get an error:</p> <pre><code>$msbuild = "C:\WINDOWS\Microsoft.NET\Framework\v3.5\MSBuild.exe /v:q /nologo" start-process $msbuild -wait </code></pre> <p>Is there a way I can pass parameters to MSBuild using start-process? I'm open to not using start-process, the only reason I used it was I needed to have the "command" as a variable.</p> <p>When I have<br> C:\WINDOWS\Microsoft.NET\Framework\v3.5\MSBuild.exe /v:q /nologo<br> on a line by itself, how does that get handled in Powershell? </p> <p>Should I be using some kind of eval() kind of function instead? </p>
651,292
5
7
null
2009-03-16 16:46:16.487 UTC
13
2017-01-31 20:39:14.337 UTC
null
null
null
B. Tyndall
36,590
null
1
85
command-line|powershell|start-process
279,210
<p>you are going to want to separate your arguments into separate parameter</p> <pre><code>$msbuild = "C:\WINDOWS\Microsoft.NET\Framework\v3.5\MSBuild.exe" $arguments = "/v:q /nologo" start-process $msbuild $arguments </code></pre>
563,028
script to map network drive
<p>I want to be able to connect to a (wifi) network hard drive from my laptop, but only occasionally. If I use the "Map a network drive" command in WinXP explorer, I have to put in the drive's IP address and name, then the router name and its password. Too much to remember!</p> <p>I'm looking for a way of scripting this activity (in any language), something like:</p> <pre><code>map Z: \\10.0.1.1\DRIVENAME "ROUTERNAME\PW" </code></pre> <p>I don't particularly care what language the script is written in. BTW, I'm aware of the DOS 'subst' command, but I don't think I can use that in this case because of the password protection.</p>
563,039
6
0
2009-02-19 02:03:08.783 UTC
2009-02-18 21:59:56.433 UTC
6
2015-04-09 20:20:36.1 UTC
2009-02-18 22:03:18.253 UTC
Rich B
5,640
Don
2,648
null
1
9
windows|language-agnostic|scripting
136,712
<p>use the <code>net use</code> command:</p> <pre><code>net use Z: \\10.0.1.1\DRIVENAME </code></pre> <p><strong>Edit 1:</strong> Also, I believe the password should be simply appended:</p> <pre><code>net use Z: \\10.0.1.1\DRIVENAME PASSWORD </code></pre> <p>You can find out more about this command and its arguments via:</p> <pre><code>net use ? </code></pre> <p><strong>Edit 2:</strong> As Tomalak mentioned in comments, you can later un-map it via</p> <pre><code>net use Z: \delete </code></pre>
387,592
Javascript mechanism to autoscroll to the bottom of a growing page?
<p>Hopefully, this will be an easy answer for someone with Javascript time behind them...</p> <p>I have a log file that is being watched by a script that feeds new lines in the log out to any connected browsers. A couple people have commented that what they want to see is more of a 'tail -f' behavior - the latest lines will always be at the bottom of the browser page until the viewer scrolls back up to see something. Scrolling back to the bottom should return you to the auto-scrolling behavior.</p> <p>My google strikeout on this one is - hopefully - just a matter of not knowing anything at all about javascript and therefore, not knowing what keywords to search for. I don't need a complete solution - just a 'close enough' that lets me jump in and get my hands dirty.</p> <p>EDIT:</p> <p>I've been attempting the scrollTop/scrollHeight idea, but am clearly missing something. I've done next to nothing with Javascript, so again I'm probably asking very low-level questions:</p> <pre><code>&lt;html&gt;&lt;body&gt; &lt;script type="text/javascript"&gt; for (i=0; i&lt;100; i++) { document.write("" + i + "&lt;br /&gt;"); document.scrollTop = document.scrollHeight; } &lt;/script&gt; &lt;/body&gt;&lt;/html&gt; </code></pre> <p>This was one of many permutations. Obviously, I can't output the log line-by-line in javascript, but I'm just trying to see the correct behavior. What's the missing link I need here?</p> <p>EDIT AGAIN: This has turned into a far more interesting problem that I first expected. The code suggestion using window.scroll does do the trick. I started playing with restricting the scroll to only take place when the browser was at the bottom of the document body. This is easy enough to do in theory, but in practice it hits a snag:</p> <p>Every time you get new text from the server, the size of the body increases and your current scroll position is no longer at the bottom of the document. You can no longer tell the difference (using scrollHeight, clientHeight and scrollTop) whether the user has scrolled up or if the text has just shot beyond their view.</p> <p>I think that if this is going to work, I'm going to have to commit myself to having a JS event that fires when the user scrolls and turns off scrolling if they are above the bottom of the window, but turns it back on if they have scrolled down to the point where they are effectively at the bottom of the view. I'm looking at the onScroll event and, given that the math on the variables I mentioned works out pretty well, I think I am on the right path here. Thanks for your input, everyone!</p>
387,734
6
0
null
2008-12-22 22:32:25.037 UTC
3
2018-12-26 03:31:26.057 UTC
2008-12-23 00:41:27.927 UTC
null
30,997
null
30,997
null
1
12
javascript|browser|scroll
39,501
<pre><code>x = 0; //horizontal coord y = document.height; //vertical coord window.scroll(x,y); </code></pre>
203,294
Multiple NSURLConnection delegates in Objective-C
<p>I have two NSURLConnections. The second one depends on the content of the first, so handling the data received from the connection will be different for the two connections. </p> <p>I'm just picking up Objective-C and I would like to know what the proper way to implement the delegates is.</p> <p>Right now I'm using: </p> <pre><code>NSURL *url=[NSURL URLWithString:feedURL]; NSURLRequest *urlR=[[[NSURLRequest alloc] initWithURL:url] autorelease]; NSURLConnection *conn=[[NSURLConnection alloc] initWithRequest:urlR delegate:self]; </code></pre> <p>I don't want to use self as the delegate, how do I define two connections with different delegates?</p> <pre><code>NSURLConnection *c1 = [[NSURLConnection alloc] initWithRequest:url delegate:handle1]; NSURLConnection *c2 = [[NSURLConnection alloc] initWithRequest:url delegate:handle2]; </code></pre> <p>How would do i create handle1 and handle2 as implementations? Or interfaces? I don't really get how you would do this. </p> <p>Any help would be awesome.</p> <p>Thanks, Brian Gianforcaro</p>
207,307
6
0
null
2008-10-15 00:08:53.783 UTC
12
2014-05-25 01:28:15.043 UTC
2014-05-25 01:28:15.043 UTC
Ned Batchelder
2,446,155
Brian Gianforcaro
3,415
null
1
15
ios|objective-c|macos|cocoa
20,397
<p>In your sample, you alloc a DownloadDelegate object without ever init'ing it. <code><pre> DownloadDelegate *dd = [DownloadDelegate alloc]; </pre></code></p> <p>This is dangerous. Instead:</p> <p><code><pre> DownloadDelegate *dd = [[DownloadDelegate alloc] init]; </pre></code></p> <p>Also, it's not <i>strictly</i> necessary to declare your delegate response methods in your @interface declaration (though it won't hurt, of course). Finally, you'll want to make sure that you implement connection:didFailWithError: and connectionDidFinishLoading: to -release your DownloadDelegate object, otherwise you'll leak.</p> <p>Glad you're up and running!</p>
215,219
How do I hide the middle of a table using jQuery?
<p>I have a really long 3 column table. I would like to </p> <pre><code>&lt;table&gt; &lt;tr&gt;&lt;td&gt;Column1&lt;/td&gt;&lt;td&gt;Column2&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Column1&lt;/td&gt;&lt;td&gt;Column2&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Start&lt;/td&gt;&lt;td&gt;Hiding&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Column1&lt;/td&gt;&lt;td&gt;Column2&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Column1&lt;/td&gt;&lt;td&gt;Column2&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Column1&lt;/td&gt;&lt;td&gt;Column2&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;End&lt;/td&gt;&lt;td&gt;Hiding&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Column1&lt;/td&gt;&lt;td&gt;Column2&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Column1&lt;/td&gt;&lt;td&gt;Column2&lt;/td&gt;&lt;/tr&gt; &lt;/table&gt; </code></pre> <p>This is the result I'm trying to obtain using jQuery.</p> <pre><code>Column1 Column2 Column1 Column2 ...Show Full Table... Column1 Column2 Column1 Column2 </code></pre> <p>I would like to use jQuery's show/hide feature to minimize the table but still show part of the top and bottom rows. The middle rows should be replace with text like "Show Full Table" and when clicked will expand to show the full table from start to finish.</p> <p>What is the best way to do this in jQuery?</p> <p>BTW I've already tried adding a class "Table_Middle" to some of the rows but it doesn't hide it completely the space it occupied is still there and I don't have the text to give the user a way to expand the table fully.</p> <p><strong>[EDIT] Added Working Example HTML inspired by Parand's posted answer</strong></p> <p><strong><em>The example below is a complete working example, you don't even need to download jquery. Just paste into a blank HTML file.</em></strong></p> <p><em>It degrades nicely to show only the full table if Javascript is turned off. If Javascript is on then it hides the middle table rows and adds the show/hide links.</em></p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=windows-1252"&gt; &lt;title&gt;Example Show/Hide Middle rows of a table using jQuery&lt;/title&gt; &lt;script src="http://code.jquery.com/jquery-latest.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; $(document).ready(function() { $("#HiddenRowsNotice").html("&lt;tr&gt;&lt;td colspan='2'&gt; &lt;a href='#'&gt;&gt;&gt; some rows hidden &lt;&lt;&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;"); $("#ShowHide").html("&lt;tr&gt;&lt;td colspan='2'&gt;&lt;a href='#'&gt;show/hide middle rows&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;"); $("#HiddenRows").hide(); $('#ShowHide,#HiddenRowsNotice').click( function() { $('#HiddenRows').toggle(); $('#HiddenRowsNotice').toggle(); }); }); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;table&gt; &lt;tbody id="ShowHide"&gt;&lt;/tbody&gt; &lt;tr&gt;&lt;th&gt;Month Name&lt;/th&gt;&lt;th&gt;Month&lt;/th&gt;&lt;/tr&gt; &lt;tbody&gt; &lt;tr&gt;&lt;td&gt;Jan&lt;/td&gt;&lt;td&gt;1&lt;/td&gt;&lt;/tr&gt; &lt;/tbody&gt; &lt;tbody id="HiddenRowsNotice"&gt;&lt;/tbody&gt; &lt;tbody id="HiddenRows"&gt; &lt;tr&gt;&lt;td&gt;Feb&lt;/td&gt;&lt;td&gt;2&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Mar&lt;/td&gt;&lt;td&gt;3&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Apr&lt;/td&gt;&lt;td&gt;4&lt;/td&gt;&lt;/tr&gt; &lt;/tbody&gt; &lt;tbody&gt; &lt;tr&gt;&lt;td&gt;May&lt;/td&gt;&lt;td&gt;5&lt;/td&gt;&lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>[EDIT] Link my <a href="http://www.developerbuzz.com/2008/10/use-jquery-to-show-and-hide-part-of.html" rel="nofollow noreferrer">blog post</a> and working example.</p>
215,231
6
0
null
2008-10-18 16:22:34.593 UTC
15
2016-09-14 10:24:43.123 UTC
2016-09-14 10:24:43.123 UTC
Brian Boatright
4,370,109
brian
3,747
null
1
49
jquery|html|html-table
68,096
<p>Something like this could work:</p> <pre><code>&lt;table&gt; &lt;tbody&gt; &lt;tr&gt;&lt;td&gt;Column1&lt;/td&gt;&lt;td&gt;Column2&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Column1&lt;/td&gt;&lt;td&gt;Column2&lt;/td&gt;&lt;/tr&gt; &lt;tr class="Show_Rows"&gt;&lt;td&gt;Start&lt;/td&gt;&lt;td&gt;Hiding&lt;/td&gt;&lt;/tr&gt; &lt;/tbody&gt; &lt;tbody class="Table_Middle" style="display:none"&gt; &lt;tr&gt;&lt;td&gt;Column1&lt;/td&gt;&lt;td&gt;Column2&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Column1&lt;/td&gt;&lt;td&gt;Column2&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Column1&lt;/td&gt;&lt;td&gt;Column2&lt;/td&gt;&lt;/tr&gt; &lt;/tbody&gt; &lt;tbody&gt; &lt;tr class="Show_Rows"&gt;&lt;td&gt;End&lt;/td&gt;&lt;td&gt;Hiding&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Column1&lt;/td&gt;&lt;td&gt;Column2&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Column1&lt;/td&gt;&lt;td&gt;Column2&lt;/td&gt;&lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; $('#something').click( function() { $('.Table_Middle').hide(); $('.Show_Rows').show(); }); $('.Show_Rows').click( function() { $('.Show_Rows').hide(); $('.Table_Middle').show(); }); </code></pre>
435,732
Delay jquery hover event?
<p>I would like to delay a hover event in jquery. I am reading from a file when user hovers over a link or label. I don't want this event to occur immediately in case the user is just moving the mouse across the screen. Is there a way to delay the event from firing?</p> <p>Thank you.</p> <p>Example code:</p> <pre><code>$(function() { $('#container a').hover(function() { $('&lt;div id="fileinfo" /&gt;').load('ReadTextFileX.aspx', {filename:'file.txt'}, function() { $(this).appendTo('#info'); } ); }, function() { $('#info').remove(); } }); }); </code></pre> <p><strong>UPDATE:</strong> <em>(1/14/09)</em> After adding the HoverIntent plugin the above code was changed to the following to implement it. Very simple to implement.</p> <pre><code>$(function() { hiConfig = { sensitivity: 3, // number = sensitivity threshold (must be 1 or higher) interval: 200, // number = milliseconds for onMouseOver polling interval timeout: 200, // number = milliseconds delay before onMouseOut over: function() { $('&lt;div id="fileinfo" /&gt;').load('ReadTextFileX.aspx', {filename:'file.txt'}, function() { $(this).appendTo('#info'); } ); }, // function = onMouseOver callback (REQUIRED) out: function() { $('#info').remove(); } // function = onMouseOut callback (REQUIRED) } $('#container a').hoverIntent(hiConfig) } </code></pre>
435,760
6
1
null
2009-01-12 15:22:21.627 UTC
32
2016-04-09 13:32:13.97 UTC
2016-03-15 17:39:42.307 UTC
Brettski
5,939,451
Brettski
5,836
null
1
95
jquery|events|mouseevent|settimeout
91,342
<p>Use the hoverIntent plugin for jquery: <a href="http://cherne.net/brian/resources/jquery.hoverIntent.html" rel="noreferrer">http://cherne.net/brian/resources/jquery.hoverIntent.html</a></p> <p>It's absolutely perfect for what you describe and I've used it on nearly every project that required mouseover activation of menus etc...</p> <p>There is one gotcha to this approach, some interfaces are devoid of a 'hover' state eg. mobile browsers like safari on the iphone. You may be hiding an important part of the interface or navigation with no way to open it on such a device. You could get round this with device specific CSS.</p>
13,726,276
Convert SQL column null values to 0
<p>I'm new to SQL Server and I have an issue. </p> <p>I have this view, in which some of the columns from the formulas are allowed to be null.</p> <p>How could I convert these null values to 0 because if they are null, the result of the formula it will be also null.</p> <p>Thanks!</p> <pre><code>CREATE VIEW vwAchizitii AS SELECT ac_id ,[Company] ,No ,[ContractID] ,[Seller] ,[AcquistionDate] ,[Village] ,[Commune] ,[Area] ,[PlotArea] ,[FieldNo] ,[Topo1] ,[Topo2] ,[Topo3] ,[Topo4] ,[Topo5] ,[TotalAreaSqm] ,[OwnershipTitle] ,[CadastralNO] ,[Type] ,[Price] ,[NotaryCosts] ,[LandTax] ,[OtherTaxes] ,[AgentFee] ,[CadastralFee] ,[TabulationFee] ,[CertSarcini] ,[ProcuraNO] ,(price+notarycosts+landtax+othertaxes+agentfee+cadastralfee+tabulationfee+certsarcini) as TotalCosts ,(price+notarycosts+landtax+othertaxes+agentfee+cadastralfee+tabulationfee+certsarcini)/(TotalAreaSqm/10000) as RonPerHa ,(price+notarycosts+landtax+othertaxes+agentfee+cadastralfee+tabulationfee+certsarcini)/(TotalAreaSqm/10000*FixHist) as EurPerHa ,[DeclImpunere] ,[FixHist] ,(price+notarycosts+landtax+othertaxes+agentfee+cadastralfee+tabulationfee+certsarcini)/FixHist as EurHist ,[LandStatus] FROM nbAchizitii </code></pre>
13,726,542
3
5
null
2012-12-05 15:12:13.807 UTC
2
2012-12-05 16:14:46.903 UTC
2012-12-05 15:28:04.507 UTC
null
13,302
null
1,820,705
null
1
4
sql|sql-server|database
45,622
<p>You can use <a href="http://msdn.microsoft.com/en-us/library/ms184325.aspx">ISNULL (Transact-SQL)</a></p> <p>eg </p> <pre><code>(isnull(price,0)+isnull(notarycosts,0)) as Total </code></pre>
37,903,536
PhantomJS with Selenium error: Message: 'phantomjs' executable needs to be in PATH
<p>I am attempting to run this script:</p> <p><a href="https://github.com/Chillee/coursera-dl-all" rel="noreferrer">https://github.com/Chillee/coursera-dl-all</a></p> <p>However, the script fails at the line <code>session = webdriver.PhantomJS()</code> with the following error</p> <pre><code>Traceback (most recent call last): File "dl_all.py", line 236, in &lt;module&gt; session = webdriver.PhantomJS() File "/home/&lt;user&gt;/.local/lib/python2.7/site-packages/selenium/webdriver/phantomjs/webdriver.py", line 51, in __init__ self.service.start() File "/home/&lt;user&gt;/.local/lib/python2.7/site-packages/selenium/webdriver/common/service.py", line 69, in start os.path.basename(self.path), self.start_error_message) selenium.common.exceptions.WebDriverException: Message: 'phantomjs' executable needs to be in PATH. Exception AttributeError: "'Service' object has no attribute 'process'" in &lt;bound method Service.__del__ of &lt;selenium.webdriver.phantomjs.service.Service object at 0x7f6f632864d0&gt;&gt; ignored </code></pre> <p>How do I add phantomjs to my PATH? I am running ubuntu 16.04 and installed selenium via <code>npm install selenium</code>.</p>
48,169,062
7
3
null
2016-06-19 02:53:04.94 UTC
7
2020-10-20 02:25:44.757 UTC
2018-10-21 03:37:32.02 UTC
null
2,089,373
null
2,089,373
null
1
27
python|selenium|selenium-webdriver|phantomjs
62,356
<p>I solved same promlem with this command in command line</p> <pre><code>export PATH=${PATH:+$PATH:}/home/&lt;login&gt;/phantomjs/bin </code></pre> <p>It's work if /home/login/phantomjs/bin is the path for folder with executable 'phantomjs'.</p>
21,337,182
How can I change dialog title color in jquery ui?
<p>I have something like this:</p> <pre><code>$div = $('&lt;div id="error" title="Error"&gt;'); $div.append('&lt;p&gt;Hi&lt;/p&gt;'); $div.dialog({ modal: true, maxHeight:500, }); </code></pre> <p>Can i change background color of dialog title somehow like this?:</p> <pre><code> $div.dialog({ modal: true, maxHeight:500, }).find(".ui-dialog-titlebar").css("background-color","red"); </code></pre>
21,337,337
3
5
null
2014-01-24 16:05:56.017 UTC
3
2014-08-11 13:50:29.23 UTC
null
null
null
null
2,758,618
null
1
19
jquery|css|jquery-ui
44,866
<p>Use <code>prev()</code> instead of <code>find()</code> because that element is not inside <code>$div</code>:</p> <pre><code>$div.dialog({ modal: true, maxHeight:500, }).prev(".ui-dialog-titlebar").css("background","red"); </code></pre> <p>Also I use <code>background</code> to override all other elements like <code>background-image</code></p> <p>Check this <a href="http://jsfiddle.net/Ad7nF/">http://jsfiddle.net/Ad7nF/</a></p>
18,142,247
Phonegap 3.0.0: BarcodeScanner Plugin
<p>currently I'm trying to install the <a href="https://github.com/wildabeast/BarcodeScanner">BarcodeScanner Plugin</a> for <code>Phonegap Version 3.0.0</code>. I can't find any working documentation on how to install it correctly and I didn't figure it out myself. So I would really appreciate any help!</p> <p>Thank you in advance! Best regards, Andreas</p>
18,142,527
4
0
null
2013-08-09 07:48:30.173 UTC
10
2014-01-06 21:43:00.847 UTC
2013-08-09 07:56:42.097 UTC
null
1,448,982
null
1,448,982
null
1
18
javascript|cordova|phonegap-plugins|barcode-scanner
26,916
<p>Actually there are a couple of discussions about this issue on the github page of the plugin <a href="https://github.com/wildabeast/BarcodeScanner/issues/32">here</a> and <a href="https://github.com/wildabeast/BarcodeScanner/issues/31">here</a>.</p> <p>I managed to have a version working in iOS and Android, you can check it <a href="https://github.com/jonathannaguin/BarcodeScanner">here</a>. There is another <a href="https://github.com/Eccenux/BarcodeScanner">fork</a> that has made a pull request to the original with changes for 3.0.0 even I am not quite sure that the plugin works in iOS.</p> <p>Instructions to install (Using <a href="https://github.com/apache/cordova-cli">cordova cli</a>)</p> <ol> <li>Download the repo using GIT or just a ZIP from Github.</li> <li><p>Add the plugin to your project (from the root of your project):</p> <p><code>cordova plugin add &lt;path_download_plugin&gt;</code></p></li> <li>You can start using <code>plugins.barcodeScanner</code> to invoke the plugin in your HTML/JS code.</li> <li>Do not forget to call <code>cordova prepare</code> to copy your files to each platform project.</li> </ol>
20,994,321
Clean ways to write multiple 'for' loops
<p>For an array with multiple dimensions, we usually need to write a <code>for</code> loop for each of its dimensions. For example:</p> <pre><code>vector&lt; vector&lt; vector&lt;int&gt; &gt; &gt; A; for (int k=0; k&lt;A.size(); k++) { for (int i=0; i&lt;A[k].size(); i++) { for (int j=0; j&lt;A[k][i].size(); j++) { do_something_on_A(A[k][i][j]); } } } double B[10][8][5]; for (int k=0; k&lt;10; k++) { for (int i=0; i&lt;8; i++) { for (int j=0; j&lt;5; j++) { do_something_on_B(B[k][i][j]); } } } </code></pre> <p>You see this kind of <code>for-for-for</code> loops in our code frequently. How do I use macros to define the <code>for-for-for</code> loops so that I don't need to re-write this kind of code every time? Is there a better way to do this?</p>
20,995,125
16
12
null
2014-01-08 11:27:05.977 UTC
51
2014-02-18 11:33:08.53 UTC
2014-01-09 09:00:52.547 UTC
null
63,550
null
1,659,534
null
1
98
c++|for-loop
23,458
<p>The first thing is that you don't use such a data structure. If you need a three dimensional matrix, you define one:</p> <pre><code>class Matrix3D { int x; int y; int z; std::vector&lt;int&gt; myData; public: // ... int&amp; operator()( int i, int j, int k ) { return myData[ ((i * y) + j) * z + k ]; } }; </code></pre> <p>Or if you want to index using <code>[][][]</code>, you need an <code>operator[]</code> which returns a proxy.</p> <p>Once you've done this, if you find that you constantly have to iterate as you've presented, you expose an iterator which will support it:</p> <pre><code>class Matrix3D { // as above... typedef std::vector&lt;int&gt;::iterator iterator; iterator begin() { return myData.begin(); } iterator end() { return myData.end(); } }; </code></pre> <p>Then you just write:</p> <pre><code>for ( Matrix3D::iterator iter = m.begin(); iter != m.end(); ++ iter ) { // ... } </code></pre> <p>(or just:</p> <pre><code>for ( auto&amp; elem: m ) { } </code></pre> <p>if you have C++11.)</p> <p>And if you need the three indexes during such iterations, it's possible to create an iterator which exposes them:</p> <pre><code>class Matrix3D { // ... class iterator : private std::vector&lt;int&gt;::iterator { Matrix3D const* owner; public: iterator( Matrix3D const* owner, std::vector&lt;int&gt;::iterator iter ) : std::vector&lt;int&gt;::iterator( iter ) , owner( owner ) { } using std::vector&lt;int&gt;::iterator::operator++; // and so on for all of the iterator operations... int i() const { ((*this) - owner-&gt;myData.begin()) / (owner-&gt;y * owner-&gt;z); } // ... }; }; </code></pre>
23,250,505
How do I create an executable from Golang that doesn't open a console window when run?
<p>I created an application that I want to run invisibly in the background (no console). How do I do this?</p> <p>(This is for Windows, tested on Windows 7 Pro 64 bit)</p>
23,250,506
3
2
null
2014-04-23 16:43:54.777 UTC
27
2021-03-19 07:43:10.49 UTC
2019-10-11 13:44:33.283 UTC
user6169399
205,580
null
74,361
null
1
60
console|go
54,265
<p>The documentation found online says I can compile with something along the lines of,</p> <p><code>go build -ldflags -Hwindowsgui filename.go</code></p> <p>But this gives an error: <code>unknown flag -Hwindowsgui</code></p> <p>With more recent (1.1?) versions of the compiler, this should work:</p> <p><code>go build -ldflags -H=windowsgui filename.go</code></p> <p>When I continued searching around I found a note that the official documentation should be updated soon, but in the meantime there are a lot of older-style example answers out there that error.</p>
1,601,201
C struct initialization using labels. It works, but how?
<p>I found some struct initialization code yesterday that threw me for a loop. Here's an example:</p> <pre><code>typedef struct { int first; int second; } TEST_STRUCT; void testFunc() { TEST_STRUCT test = { second: 2, first: 1 }; printf("test.first=%d test.second=%d\n", test.first, test.second); } </code></pre> <p>Surprisingly (to me), here's the output:</p> <pre><code>-&gt; testFunc test.first=1 test.second=2 </code></pre> <p>As you can see, the struct gets initialized properly. I wasn't aware labeled statements could be used like that. I've seen several other ways of doing struct initialization, but I didn't find any examples of this sort of struct initialization on any of the online C FAQs. Is anybody aware of how/why this works?</p>
1,601,420
5
0
null
2009-10-21 14:29:37.573 UTC
11
2018-01-16 19:18:03.34 UTC
2018-01-16 19:18:03.34 UTC
null
1,677,912
null
193,848
null
1
46
c|struct|initialization|label
51,225
<p>Here is the section of the gcc manual which explains the syntax of designated initializers for both structs and arrays:</p> <blockquote> <p>In a structure initializer, specify the name of a field to initialize with '<em>.fieldname =</em>' before the element value. For example, given the following structure,</p> <pre><code> struct point { int x, y; }; </code></pre> <p>the following initialization</p> <pre><code> struct point p = { .y = yvalue, .x = xvalue }; </code></pre> <p>is equivalent to</p> <pre><code> struct point p = { xvalue, yvalue }; </code></pre> <p>Another syntax which has the same meaning, obsolete since GCC 2.5, is '<em>fieldname:</em>', as shown here:</p> <pre><code> struct point p = { y: yvalue, x: xvalue }; </code></pre> </blockquote> <p>The relevant page can be found <a href="http://gcc.gnu.org/onlinedocs/gcc-4.4.1/gcc/Designated-Inits.html#Designated-Inits" rel="noreferrer">here</a>.</p> <p>Your compiler should have similar documentation.</p>
2,109,841
I'm getting a "Does not implement IController" error on images and robots.txt in MVC2
<p>I'm getting a strange error on my webserver for seemingly every file but the .aspx files.</p> <p>Here is an example. Just replace '/robots.txt' with any .jpg name or .gif or whatever and you'll get the idea:</p> <blockquote> <p>The controller for path '/robots.txt' was not found or does not implement IController.</p> </blockquote> <p>I'm sure it's something to do with how I've setup routing but I'm not sure what exactly I need to do about it.</p> <p>Also, this is a mixed MVC and WebForms site, if that makes a difference.</p>
2,109,859
6
3
null
2010-01-21 14:20:36.303 UTC
26
2014-04-01 09:23:21.32 UTC
null
null
null
null
135,786
null
1
54
asp.net-mvc|exception|routing
52,302
<p>You can ignore robots.txt and all the aspx pages in your routing.</p> <pre><code>routes.IgnoreRoute("{*allaspx}", new {allaspx=@".*\.aspx(/.*)?"}); routes.IgnoreRoute("{*robotstxt}", new {robotstxt=@"(.*/)?robots.txt(/.*)?"}); </code></pre> <p>You might want to ignore the favicon too.</p> <pre><code>routes.IgnoreRoute("{*favicon}", new {favicon=@"(.*/)?favicon.ico(/.*)?"}); </code></pre> <p>You can adjust the regular expression to exclude paths.</p> <p>Haacked from the <a href="http://haacked.com/archive/2008/07/14/make-routing-ignore-requests-for-a-file-extension.aspx" rel="noreferrer">source</a>.</p>
1,476,532
NSLog with CGPoint data
<p>I have a CGPoint called point that is being assigned a touch:</p> <pre><code>UITouch *touch = [touches anyObject]; CGPoint point = [touch locationInView:self]; </code></pre> <p>I want to get the x coordinate value into my console log:</p> <pre><code>NSLog(@"x: %s", point.x); </code></pre> <p>When I use this, log output for this is:</p> <p>x: (null)</p> <p>I have verified that point is not null when this is called using the debugger and variable watch.</p> <p>Any help appreciated,</p> <p>Thanks // :)</p>
1,476,951
7
0
null
2009-09-25 10:22:14.813 UTC
25
2022-05-05 14:13:53.983 UTC
2009-09-25 22:16:56.19 UTC
null
30,461
null
1,899,246
null
1
93
iphone|cocoa|cocoa-touch|core-graphics|nslog
43,132
<p>Actually, the real easiest way to log a <code>CGPoint</code> is:</p> <pre><code>NSLog(@"%@", NSStringFromCGPoint(point)); </code></pre> <p>The desktop Cocoa equivalent is <code>NSStringFromPoint()</code>.</p>
2,136,998
Using a STL map of function pointers
<p>I developed a scripting engine that has many built-in functions, so to call any function, my code just went into an <code>if .. else if .. else if</code> wall checking the name but I would like to develop a more efficient solution.</p> <p>Should I use a <em>hashmap</em> with strings as keys and pointers as values? How could I do it by using an STL map? </p> <p><strong>EDIT</strong>: Another point that came into my mind: of course using a map will force the compiler not to inline functions, but my inefficient approach didn't have any overhead generated by the necessity of function calls, it just executes code.</p> <p>So I wonder if the overhead generated by the function call will be any better than having an <code>if..else</code> chain.. otherwise I could minimize the number of comparisons by checking a character at runtime (will be longer but faster).</p>
2,137,013
8
0
null
2010-01-26 01:26:33.923 UTC
25
2020-02-20 15:58:57.237 UTC
2011-09-19 14:46:18.637 UTC
null
2,047,962
null
121,747
null
1
50
c++|stl|map|function-pointers
78,884
<p>Whatever your function signatures are:</p> <pre><code>typedef void (*ScriptFunction)(void); // function pointer type typedef std::unordered_map&lt;std::string, ScriptFunction&gt; script_map; // ... void some_function() { } // ... script_map m; m.emplace("blah", &amp;some_function); // ... void call_script(const std::string&amp; pFunction) { auto iter = m.find(pFunction); if (iter == m.end()) { // not found } (*iter-&gt;second)(); } </code></pre> <p>Note that the <code>ScriptFunction</code> type could be generalized to <code>std::function&lt;/* whatever*/&gt;</code> so you can support any callable thing, not just exactly function pointers.</p>
2,239,331
Using hg revert in Mercurial
<p>I'm using Mercurial. I made a clone of a repository. For debugging, I changed a few lines of code in a java file. I did not commit those changes though. I just want to revert them back to their original state, as found in the repository. I tried <code>hg revert filename.java</code>, which did revert it, but now when I do <code>hg status</code>, I see additional files added in my folder now like:</p> <pre><code>? filename.java.orig </code></pre> <p>Can I just delete those files, and why does Mercurial make them when I use revert?</p>
2,239,350
8
0
null
2010-02-10 18:26:39.15 UTC
6
2020-07-21 20:51:38.91 UTC
2011-08-29 00:01:26.353 UTC
null
144,669
null
246,114
null
1
62
mercurial
54,124
<p>Yes, you can delete them. It's a safety feature in case you reverted something you didn't mean to revert.</p>
1,598,882
Are there any tools for performing static analysis of Scala code?
<p>Are there any tools for performing static analysis of Scala code, similar to FindBugs and PMD for Java or Splint for C/C++? I know that FindBugs works on the bytecode produced by compiling Java, so I'm curious as to how it would work on Scala.</p> <p>Google searches (as of 27 October 2009) reveal very little.</p> <p>Google searches (as of 01 February 2010) reveal this question.</p>
1,664,416
9
9
null
2009-10-21 05:28:32.813 UTC
14
2015-09-16 09:28:50.473 UTC
2010-04-28 00:59:43.49 UTC
null
213,269
null
117,802
null
1
46
testing|scala|functional-programming|static-analysis
8,485
<p>FindBugs analyzes JVM byte codes, regardless of the tool that generated them. I've tried using FindBugs to check .class files generated by Scala. Unfortunately, FindBugs produced many warnings, even for trivial Scala programs.</p>
1,361,741
Get characters after last / in url
<p>I want to get the characters after the last / in an url like <code>http://www.vimeo.com/1234567</code></p> <p>How do I do with php?</p>
1,361,752
9
1
null
2009-09-01 10:40:11.56 UTC
30
2021-08-28 01:11:05.673 UTC
2013-05-06 07:21:25.493 UTC
null
2,224,246
null
2,224,246
null
1
150
php|string
171,120
<p>Very simply:</p> <pre><code>$id = substr($url, strrpos($url, '/') + 1); </code></pre> <p><a href="http://php.net/manual/en/function.strrpos.php" rel="noreferrer">strrpos</a> gets the position of the last occurrence of the slash; <a href="http://php.net/manual/en/function.substr.php" rel="noreferrer">substr</a> returns everything after that position.</p> <hr> <p>As mentioned by redanimalwar if there is no slash this doesn't work correctly since <code>strrpos</code> returns false. Here's a more robust version:</p> <pre><code>$pos = strrpos($url, '/'); $id = $pos === false ? $url : substr($url, $pos + 1); </code></pre>
1,618,474
Intercept method call in Objective-C
<p>Can I intercept a method call in Objective-C? How?</p> <p><strong>Edit:</strong> <em>Mark Powell</em>'s answer gave me a partial solution, the <em>-forwardInvocation</em> method. But the documentation states that -forwardInvocation is only called when an object is sent a message for which it has no corresponding method. I'd like a method to be called under all circumstances, even if the receiver does have that selector.</p>
1,642,544
10
0
null
2009-10-24 16:38:26.28 UTC
15
2014-05-27 17:59:48.933 UTC
2009-10-24 17:29:28.457 UTC
null
147,141
null
147,141
null
1
19
objective-c|methods|intercept
13,935
<p>You do it by swizzling the method call. Assuming you want to grab all releases to NSTableView:</p> <pre><code>static IMP gOriginalRelease = nil; static void newNSTableViewRelease(id self, SEL releaseSelector, ...) { NSLog(@"Release called on an NSTableView"); gOriginalRelease(self, releaseSelector); } //Then somewhere do this: gOriginalRelease = class_replaceMethod([NSTableView class], @selector(release), newNSTableViewRelease, "v@:"); </code></pre> <p>You can get more details in the Objective C runtime <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html#//apple_ref/c/func/class_replaceMethod" rel="noreferrer">documentation</a>.</p>
1,405,372
Stopping/Starting a remote Windows service and waiting for it to open/close
<p>The top answer to <a href="https://stackoverflow.com/questions/187836/how-do-i-restart-a-service-on-a-remote-machine-in-windows">this question</a> tells me how to stop/start a remote service. Great. Now, all I need is to wait for the actual stop/start to complete. So, what I'm looking for is a dos command to:</p> <ol> <li>Start a service, should return only after the service is started (or after a timeout, raising error level)</li> <li>Stop a service, return only after the service is stopped</li> </ol>
3,025,996
11
1
null
2009-09-10 13:38:00.467 UTC
27
2020-11-13 12:47:20.963 UTC
2017-05-23 12:00:31.917 UTC
null
-1
null
11,236
null
1
70
windows|windows-services
96,870
<p>I created a set of batch scripts that use sc.exe to do just this. They are attached below. To run these scripts, <strong>you should be a user with administration rights on the target machine and running this from a computer that is a member of the same domain</strong>. It's possible to set it up to be able to run from outside of the domain (like from a VPN) but there are a lot of layers of security to work through involving firewalls, DCOM and security credentials.</p> <p>One of these days, I'm going to figure out the PowerShell equivalent, which should be much easier.</p> <h2>safeServiceStart.bat</h2> <pre><code>@echo off :: This script originally authored by Eric Falsken IF [%1]==[] GOTO usage IF [%2]==[] GOTO usage ping -n 1 %1 | FIND "TTL=" &gt;NUL IF errorlevel 1 GOTO SystemOffline SC \\%1 query %2 | FIND "STATE" &gt;NUL IF errorlevel 1 GOTO SystemOffline :ResolveInitialState SC \\%1 query %2 | FIND "STATE" | FIND "STOPPED" &gt;NUL IF errorlevel 0 IF NOT errorlevel 1 GOTO StartService SC \\%1 query %2 | FIND "STATE" | FIND "RUNNING" &gt;NUL IF errorlevel 0 IF NOT errorlevel 1 GOTO StartedService SC \\%1 query %2 | FIND "STATE" | FIND "PAUSED" &gt;NUL IF errorlevel 0 IF NOT errorlevel 1 GOTO SystemOffline echo Service State is changing, waiting for service to resolve its state before making changes sc \\%1 query %2 | Find "STATE" timeout /t 2 /nobreak &gt;NUL GOTO ResolveInitialState :StartService echo Starting %2 on \\%1 sc \\%1 start %2 &gt;NUL GOTO StartingService :StartingServiceDelay echo Waiting for %2 to start timeout /t 2 /nobreak &gt;NUL :StartingService SC \\%1 query %2 | FIND "STATE" | FIND "RUNNING" &gt;NUL IF errorlevel 1 GOTO StartingServiceDelay :StartedService echo %2 on \\%1 is started GOTO:eof :SystemOffline echo Server \\%1 is not accessible or is offline GOTO:eof :usage echo %0 [system name] [service name] echo Example: %0 server1 MyService echo. GOTO:eof </code></pre> <h2>safeServiceStop.bat</h2> <pre><code>@echo off :: This script originally authored by Eric Falsken IF [%1]==[] GOTO usage IF [%2]==[] GOTO usage ping -n 1 %1 | FIND "TTL=" &gt;NUL IF errorlevel 1 GOTO SystemOffline SC \\%1 query %2 | FIND "STATE" &gt;NUL IF errorlevel 1 GOTO SystemOffline :ResolveInitialState SC \\%1 query %2 | FIND "STATE" | FIND "RUNNING" &gt;NUL IF errorlevel 0 IF NOT errorlevel 1 GOTO StopService SC \\%1 query %2 | FIND "STATE" | FIND "STOPPED" &gt;NUL IF errorlevel 0 IF NOT errorlevel 1 GOTO StopedService SC \\%1 query %2 | FIND "STATE" | FIND "PAUSED" &gt;NUL IF errorlevel 0 IF NOT errorlevel 1 GOTO SystemOffline echo Service State is changing, waiting for service to resolve its state before making changes sc \\%1 query %2 | Find "STATE" timeout /t 2 /nobreak &gt;NUL GOTO ResolveInitialState :StopService echo Stopping %2 on \\%1 sc \\%1 stop %2 %3 &gt;NUL GOTO StopingService :StopingServiceDelay echo Waiting for %2 to stop timeout /t 2 /nobreak &gt;NUL :StopingService SC \\%1 query %2 | FIND "STATE" | FIND "STOPPED" &gt;NUL IF errorlevel 1 GOTO StopingServiceDelay :StopedService echo %2 on \\%1 is stopped GOTO:eof :SystemOffline echo Server \\%1 or service %2 is not accessible or is offline GOTO:eof :usage echo Will cause a remote service to STOP (if not already stopped). echo This script will waiting for the service to enter the stopped state if necessary. echo. echo %0 [system name] [service name] {reason} echo Example: %0 server1 MyService echo. echo For reason codes, run "sc stop" GOTO:eof </code></pre> <h2>safeServiceRestart.bat</h2> <pre><code>@echo off :: This script originally authored by Eric Falsken if [%1]==[] GOTO usage if [%2]==[] GOTO usage ping -n 1 %1 | FIND "TTL=" &gt;NUL IF errorlevel 1 GOTO SystemOffline SC \\%1 query %2 | FIND "STATE" &gt;NUL IF errorlevel 1 GOTO SystemOffline :ResolveInitialState SC \\%1 query %2 | FIND "STATE" | FIND "RUNNING" &gt;NUL IF errorlevel 0 IF NOT errorlevel 1 GOTO StopService SC \\%1 query %2 | FIND "STATE" | FIND "STOPPED" &gt;NUL IF errorlevel 0 IF NOT errorlevel 1 GOTO StartService SC \\%1 query %2 | FIND "STATE" | FIND "PAUSED" &gt;NUL IF errorlevel 0 IF NOT errorlevel 1 GOTO SystemOffline echo Service State is changing, waiting for service to resolve its state before making changes sc \\%1 query %2 | Find "STATE" timeout /t 2 /nobreak &gt;NUL GOTO ResolveInitialState :StopService echo Stopping %2 on \\%1 sc \\%1 stop %2 %3 &gt;NUL GOTO StopingService :StopingServiceDelay echo Waiting for %2 to stop timeout /t 2 /nobreak &gt;NUL :StopingService SC \\%1 query %2 | FIND "STATE" | FIND "STOPPED" &gt;NUL IF errorlevel 1 GOTO StopingServiceDelay :StopedService echo %2 on \\%1 is stopped GOTO StartService :StartService echo Starting %2 on \\%1 sc \\%1 start %2 &gt;NUL GOTO StartingService :StartingServiceDelay echo Waiting for %2 to start timeout /t 2 /nobreak &gt;NUL :StartingService SC \\%1 query %2 | FIND "STATE" | FIND "RUNNING" &gt;NUL IF errorlevel 1 GOTO StartingServiceDelay :StartedService echo %2 on \\%1 is started GOTO:eof :SystemOffline echo Server \\%1 or service %2 is not accessible or is offline GOTO:eof :usage echo Will restart a remote service, waiting for the service to stop/start (if necessary) echo. echo %0 [system name] [service name] {reason} echo Example: %0 server1 MyService echo. echo For reason codes, run "sc stop" GOTO:eof </code></pre>
8,931,977
Sort array from smallest to largest using java
<p>I'm supposed to create an array and sort the numbers from smallest to largest. Here is what I have so far:</p> <pre><code>public class bubbleSort { public static void sort (int [] arrayName){ int temp; for (int i = 0; i &lt; arrayName.length-1; i++) { if(arrayName[i] &gt; arrayName[i+1]) { temp=arrayName[i]; arrayName[i]=arrayName[i+1]; arrayName[i+1]=temp; i=-1; } } } public static void main(String[] args) { int [] arrayName = new int[10]; for (int i = 0; i &lt; arrayName.length; i++) { arrayName[i] = (int)(Math.random()*100); } System.out.println(sort(arrayName)); } } </code></pre> <p>I am getting an error on the last line where I'm trying to print it out. What am I doing wrong?</p>
8,932,014
9
2
null
2012-01-19 19:21:06.27 UTC
null
2016-09-02 12:11:16.173 UTC
2013-02-15 15:47:47.9 UTC
null
1,288
null
1,044,858
null
1
6
java|arrays|sorting
51,989
<p>Your <code>sort(int[] array)</code> method returns nothing. It is void, therefore you cannot print its return. </p>
8,543,653
Windows Azure Client with IP address 'XXX.XXX.XXX.XX' is not allowed to access the server
<p>I have setup Sever, database and Firewall Setting (Rule) In windows Azure. I Have added The IP In firewall setting which is populating under the Windows Azure Firewall Tab.</p> <p>When I am trying connect with Database using Manage from Azure Platform I am getting this error message.</p> <p><strong>Firewall check failed. Cannot open server 'XXXXXXXXX' requested by the login. Client with IP address 'XXXXXXXXX' is not allowed to access the server. To enable access, use the SQL Azure Portal or run sp_set_firewall_rule on the master database to create a firewall rule for this IP address or address range. It may take up to five minutes for this change to take effect.</strong></p> <p>And I am also Not able to connect via Sql Server Management Studio. Getting Same connection issue Error for My IP Address.</p> <p>I am not using static IP but my IP haven't change during this process. I have tried lot Example but all are saying To add firewall rule That I had already done.</p> <p>I have Added Firewall exception for port Number 1433.</p> <p>But still this is not working Please let me know that what type of setting is still missing.</p> <p>Thanks in advance.</p>
8,544,980
11
2
null
2011-12-17 08:50:19.13 UTC
12
2021-04-25 16:38:36.25 UTC
2012-02-03 17:43:01.453 UTC
null
272,109
null
165,107
null
1
72
azure|azure-sql-database|azure-storage
71,050
<p>If you want to manage SQL Azure from the Azure Portal you have to check the "Allow other Windows Azure Services to connect to this server". That is also required later for your Web/Worker roles deployed to Azure: <img src="https://i.stack.imgur.com/14zOv.png" alt="enter image description here"></p> <p>If you want to connect from your home/work PC, you have to keep the firewall up-to-date with your public IP address! Your public IP Address is in the little popup windows, which pops out when you want to add new firewall rule:</p> <p><img src="https://i.stack.imgur.com/MGhHx.png" alt="enter image description here"></p>
6,402,681
How to increase number of threads in tomcat thread pool?
<p>i just want to know How to increase number of threads in tomcat thread pool ? and what number to set the max too, i don't know what's appropriate ?</p>
7,803,226
3
0
null
2011-06-19 13:42:03.147 UTC
14
2021-11-14 15:13:55.41 UTC
2016-05-03 06:52:36.76 UTC
null
2,987,755
null
429,377
null
1
27
tomcat7|threadpool
127,869
<p>Sounds like you should stay with the defaults ;-)</p> <p>Seriously: The number of maximum parallel connections you should set depends on your expected tomcat usage and also on the number of cores on your server. More cores on your processor =&gt; more parallel threads that can be executed.</p> <p>See here how to configure...</p> <p>Tomcat 10: <a href="https://tomcat.apache.org/tomcat-10.0-doc/config/executor.html" rel="nofollow noreferrer">https://tomcat.apache.org/tomcat-10.0-doc/config/executor.html</a></p> <p>Tomcat 9: <a href="https://tomcat.apache.org/tomcat-9.0-doc/config/executor.html" rel="nofollow noreferrer">https://tomcat.apache.org/tomcat-9.0-doc/config/executor.html</a></p> <p>Tomcat 8: <a href="https://tomcat.apache.org/tomcat-8.0-doc/config/executor.html" rel="nofollow noreferrer">https://tomcat.apache.org/tomcat-8.0-doc/config/executor.html</a></p> <p>Tomcat 7: <a href="https://tomcat.apache.org/tomcat-7.0-doc/config/executor.html" rel="nofollow noreferrer">https://tomcat.apache.org/tomcat-7.0-doc/config/executor.html</a></p> <p>Tomcat 6: <a href="https://tomcat.apache.org/tomcat-6.0-doc/config/executor.html" rel="nofollow noreferrer">https://tomcat.apache.org/tomcat-6.0-doc/config/executor.html</a></p>
6,422,895
ASP.NET MVC 3 Razor recursive function
<p>Okay, so I want to display a list containing lists of lists of lists...</p> <p>I have no way of knowing how many levels there are to display, so I figured this is where I break out the old recursive routine.</p> <p>I'm having trouble with exactly how to go about this though.</p> <p>This is what I have so far (in view - simplified):</p> <pre><code>@foreach(MyObject item in @Model.ListOfObjects){ &lt;div&gt; @item.Title &lt;/div&gt; //Call recursive function? } </code></pre> <p>Now each of these objects also have a List&lt;MyObject>. I want to display each level below this div, with a tab indent per level for instance.</p> <p>I was thinking a Razor function would be the thing to do here, but I need some help in forming it. Here's my thinking:</p> <pre><code>@functions{ public static void ShowSubItems(MyObject _object){ if(_object.ListOfObjects.Count&gt;0){ foreach(MyObject subItem in _object.listOfObjects){ // Show subItem in HTML ShowSubItems(subItem); } } } } </code></pre> <p>But as you can see, I plainly need some help :)</p>
6,423,891
3
0
null
2011-06-21 09:10:44.427 UTC
37
2021-04-19 17:28:29.227 UTC
2017-03-09 04:58:35.387 UTC
null
63,550
null
295,540
null
1
83
c#|asp.net-mvc|asp.net-mvc-3|razor
32,992
<p>The Razor view engine allows to write inline recursive helpers with the <code>@helper</code> keyword.</p> <pre><code>@helper ShowTree(IEnumerable&lt;Foo&gt; foos) { &lt;ul&gt; @foreach (var foo in foos) { &lt;li&gt; @foo.Title @if (foo.Children.Any()) { @ShowTree(foo.Children) } &lt;/li&gt; } &lt;/ul&gt; } </code></pre>
6,481,806
How to select multiple rows from mysql with one query and use them in php
<p>I currently have a database like the picture below. </p> <p><img src="https://i.stack.imgur.com/TEnQj.png" alt="enter image description here"></p> <p>Where there is a query that selects the rows with number1 equaling 1. When using </p> <pre><code>mysql_fetch_assoc() </code></pre> <p>in php I am only given the first is there any way to get the second? Like through a dimesional array like </p> <pre><code>array['number2'][2] </code></pre> <p>or something similar</p>
6,481,816
4
0
null
2011-06-26 02:36:32.817 UTC
2
2022-05-03 23:49:01.787 UTC
2014-04-18 13:31:17.213 UTC
null
3,359,432
null
402,746
null
1
10
php|mysql|multidimensional-array|fetch|multirow
72,513
<p>Use repeated calls to mysql_fetch_assoc. It's documented right in the PHP manual.</p> <p><a href="http://php.net/manual/function.mysql-fetch-assoc.php" rel="noreferrer">http://php.net/manual/function.mysql-fetch-assoc.php</a></p> <pre><code>// While a row of data exists, put that row in $row as an associative array // Note: If you're expecting just one row, no need to use a loop // Note: If you put extract($row); inside the following loop, you'll // then create $userid, $fullname, and $userstatus while ($row = mysql_fetch_assoc($result)) { echo $row["userid"]; echo $row["fullname"]; echo $row["userstatus"]; } </code></pre> <p>If you need to, you can use this to build up a multidimensional array for consumption in other parts of your script.</p>
36,158,848
How can I declare a global variable in Angular 2 / Typescript?
<p>I would like some variables to be accessible everywhere in an <code>Angular 2</code> in the <code>Typescript</code> language. How should I go about accomplishing this?</p>
36,183,988
10
3
null
2016-03-22 15:40:43.783 UTC
59
2020-09-15 08:34:15.113 UTC
2019-05-12 01:01:08.283 UTC
null
10,788,726
null
210,006
null
1
199
typescript|angular
393,158
<p>Here is the simplest solution w/o <code>Service</code> nor <code>Observer</code>:</p> <p>Put the global variables in a file an export them.</p> <pre><code>// // ===== File globals.ts // 'use strict'; export const sep='/'; export const version: string="22.2.2"; </code></pre> <p>To use globals in another file use an <code>import</code> statement: <code>import * as myGlobals from 'globals';</code></p> <p>Example:</p> <pre><code>// // ===== File heroes.component.ts // import {Component, OnInit} from 'angular2/core'; import {Router} from 'angular2/router'; import {HeroService} from './hero.service'; import {HeroDetailComponent} from './hero-detail.component'; import {Hero} from './hero'; import * as myGlobals from 'globals'; //&lt;==== this one (**Updated**) export class HeroesComponent implements OnInit { public heroes: Hero[]; public selectedHero: Hero; // // // Here we access the global var reference. // public helloString: string="hello " + myGlobals.sep + " there"; ... } } </code></pre> <p>Thanks @eric-martinez</p>
56,881,982
Vue - How to render HTML in vue components
<p>This is what I'm trying to accomplish:</p> <pre><code>{{ span('Hello') }} </code></pre> <p>And what desired output should be is:</p> <pre><code>&lt;span&gt; Hello &lt;/span&gt; </code></pre> <p>Is this possible?</p> <p>Thanks</p>
56,882,737
2
4
null
2019-07-04 06:40:25.85 UTC
2
2019-07-14 16:31:15.28 UTC
2019-07-14 16:31:15.28 UTC
null
7,358,308
null
1,013,806
null
1
20
vue.js|render|directive
42,726
<p>Look at the below snippet - </p> <p>Note - You can't render <code>html</code> inside <code>{{ }}</code> because it get added to text node of the element. To render it as an html you need to use <code>v-html</code> and have your function which return <code>element</code> wrapping your text</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-js lang-js prettyprint-override"><code>new Vue({ el: "#app", data: { foo: 'asdasd' }, methods: { span(text) { return `&lt;span&gt; ${text} &lt;/span&gt;` } } })</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>span { color: red; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"&gt;&lt;/script&gt; &lt;div id="app"&gt; &lt;h1&gt; Render whatever you want &lt;/h1&gt; &lt;div v-html="span('Hello world')" /&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
52,147,247
Unwanted NullPointerException in ternary operator - Why?
<p>While executing the following code, I am getting a <code>NullPointerException</code> at line:</p> <pre><code>value = condition ? getDouble() : 1.0; </code></pre> <p>In earlier lines when I use <code>null</code> instead of <code>getDouble()</code> everything works and this is strange.</p> <pre><code>public class Test { static Double getDouble() { return null; } public static void main(String[] args) { boolean condition = true; Double value; value = condition ? null : 1.0; //works fine System.out.println(value); //prints null value = condition ? getDouble() : 1.0; //throws NPE System.out.println(value); } } </code></pre> <p>Can someone help me understand this behavior?</p>
52,147,368
2
7
null
2018-09-03 09:49:37.65 UTC
6
2020-01-10 07:07:15.23 UTC
2020-01-10 07:07:15.23 UTC
null
3,848,411
null
3,848,411
null
1
48
java|nullpointerexception|double|conditional-operator
2,697
<p>When you write</p> <pre><code>value = condition ? null : 1.0; </code></pre> <p>the type of <code>condition ? null : 1.0</code> must be a reference type, so the type is <code>Double</code>, which can hold the value <code>null</code>.</p> <p>When you write</p> <pre><code>value = condition ? getDouble() : 1.0; </code></pre> <p>and <code>getDouble()</code> returns <code>null</code>, it's equivalent to writing:</p> <pre><code>value = condition ? ((Double) null) : 1.0; </code></pre> <p>In this case the compiler sees a <code>Double</code> and a <code>double</code> as the 2nd and 3rd arguments of the ternary conditional operator, and decides that type of the expression should be <code>double</code>. Therefore it unboxes the <code>null</code> to <code>double</code>, getting <code>NullPointerException</code>.</p> <p>The type of the conditional ternary operator is determined by some tables in <a href="https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.25" rel="noreferrer">JLS 15.25</a>.</p> <p>If the 2nd and 3rd operands are <code>null</code> and <code>double</code>, the conditional expression type is the least upper bound of <code>Double</code> and <code>null</code>, which is <code>Double</code>.</p> <p>If the 2nd and 3rd operands are <code>Double</code> and <code>double</code>, the conditional expression type is <code>double</code>.</p>
23,855,587
Packaging Ruby into a portable executable
<p>I have been trying to find a good solution to this for a long time:</p> <p>Is there a sure-fire way to install ruby to a folder which is portable on that platform? I want to have a folder which I can easily copy into a distribution I am making so I can have a ruby environment "on the go". It is fine if I need to compile the source and stuff, as long as I end up with a portable ruby install.</p> <p>I have found a few resources which tries to solve this, but none are satisfactory for me.</p> <p><a href="https://stackoverflow.com/questions/258801/portable-ruby-on-rails-environment">Portable Ruby on Rails environment</a></p> <p><a href="http://hcettech.blogspot.pt/2012/05/windows-portable-rails-development.html" rel="noreferrer">http://hcettech.blogspot.pt/2012/05/windows-portable-rails-development.html</a></p> <p>For me this is a major pain-point of Ruby. If it is not possible to get a Ruby script to work without having the clients install Ruby first, then ruby is essentially no good in my case. I truly hope I/we can figure this out so it is possible to have Ruby be lots more useful than what it already is.</p> <hr> <p>Note: I know things like <a href="https://github.com/Spooner/releasy/" rel="noreferrer">Releasy</a> exists, but it's still not a simple ruby executable.</p> <p>My goal is to be able to make a folder with a .bat/.sh script, which does this:</p> <pre><code>#some bat/sh ./bin/ruby ./my_script.rb </code></pre> <p>And yes, shoot me down if there is something about this problem I have not understood, as it would be a relief for me.</p>
23,969,446
3
2
null
2014-05-25 13:05:03.443 UTC
8
2016-09-26 16:14:20.45 UTC
2017-05-23 10:30:45.72 UTC
null
-1
null
741,850
null
1
19
ruby|cross-platform|portability
11,467
<p>I got so tired of this that I decided to make my own solution to it. After a couple of days I finally got this working. </p> <hr> <h2>I present: <strong><a href="https://github.com/stephan-nordnes-eriksen/ruby_ship">Ruby Ship</a></strong></h2> <p>It's just what I needed, and hopefully someone else will get the benefit of it too!</p> <p>It's really simple: Download the repo (which is quite big because of the binaries). Put it on a usb-drive, or wherever you want it, then do:</p> <pre><code>path/to/ruby_ship/bin/ruby_ship.sh -v =&gt; ruby 2.1.2p95 (2014-05-08 revision 45877) [x86_64-darwin13.0] </code></pre> <p>That's for linux and mac, or on windows:</p> <pre><code>path\to\ruby_ship\bin\ruby_ship.bat -v =&gt; ruby 2.1.2p95 (2014-05-08 revision 45877) [i386-mswin32_100] </code></pre> <p>The ruby_ship wrapper acts just as your normal ruby, so you can pass in a script, or do anything you would use the normal ruby command for.</p> <p>If you don't like the version that comes bundled with Ruby Ship, then simply use the compiling-script that is in the tools directory. Download the source code of you favourite version of Ruby, say X.Y.Z, then do this:</p> <pre><code># *nix (osx/linux/...) path/to/ruby_ship/tools/ruby_ship_build.sh path/to/ruby-X.Y.Z.tar.gz # windows path\to\ruby_ship\tools\ruby_ship_build.bat path\to\ruby-X.Y.Z.tar.gz </code></pre> <p>This will build your flavour of ruby and set up the wrappers correctly. Now you Ruby version X.Y.Z is portable! Copy paste this folder where you want it and you are ready to go! Remember though, it will only compile for your current platform, so if you need other platforms, go compile it on those platforms as well.</p> <p>The compiling process has a few requirements. <a href="https://github.com/stephan-nordnes-eriksen/ruby_ship">Look at the github site</a>.</p> <p>Anyways, hope that others might find this useful! If things are not quite working for you, please make an issue and I will look into it!</p>
23,870,729
Compress Videos using android MediaCodec api
<p>I want to compress locally saved video file to a smaller size in order to upload to a server. </p> <p>Since i used MediaCodec , i have found some tips to compress video . Here are the steps that i followed</p> <p>1) . Extracted the media file using MediaExrtactor and Decoded it. 2) . Creates the Encoder with required file format 3) . Create muxer to save file in local storage. (not complete)</p> <p>Question : But i dont know how to encode the already decoded stream and save the stream in to the local storage using MediaMuxer. </p> <pre><code>public class CompressMedia { private static final String SAMPLE = Environment .getExternalStorageDirectory() + "/DCIM/Camera/20140506_174959.mp4"; private static final String OUTPUT_PATH = Environment .getExternalStorageDirectory() + "/DCIM/Camera/20140506_174959_REC.mp4"; private MediaExtractor extractor; private MediaCodec decoder; private MediaCodec encoder; String mime; private static final String MIME_TYPE = "video/avc"; public void extractMediaFile() { // work plan // locate media file // extract media file using Media Extractor // retrieve decoded frames extractor = new MediaExtractor(); try { extractor.setDataSource(SAMPLE); } catch (IOException e) { // TODO Auto-generated catch block // file not found e.printStackTrace(); } // add decoded frames for (int i = 0; i &lt; extractor.getTrackCount(); i++) { MediaFormat format = extractor.getTrackFormat(i); mime = format.getString(MediaFormat.KEY_MIME); if (mime.startsWith("video/")) { extractor.selectTrack(i); decoder = MediaCodec.createDecoderByType(mime); decoder.configure(format, null, null, 0); break; } } if (decoder == null) { Log.e("DecodeActivity", "Can't find video info!"); return; } // - start decoder - decoder.start(); extractor.selectTrack(0); // - decoded frames can obtain in here - } private void createsEncoder() { // creates media encoder to set formats encoder = MediaCodec.createDecoderByType(MIME_TYPE); // init media format MediaFormat mediaFormat = MediaFormat.createVideoFormat(MIME_TYPE, /* 640 */ 320, /* 480 */240); mediaFormat.setInteger(MediaFormat.KEY_BIT_RATE, 400000); mediaFormat.setInteger(MediaFormat.KEY_FRAME_RATE, 25); mediaFormat.setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420SemiPlanar); mediaFormat.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 5); encoder.configure(mediaFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE); encoder.start(); // - encoded data format is avaiable in here } private void createMuxer() { // creates media muxer - media muxer will be used to write the final // strem in to a desired file :) try { MediaMuxer muxer = new MediaMuxer(OUTPUT_PATH, OutputFormat.MUXER_OUTPUT_MPEG_4); int videoTrackIndex = muxer.addTrack(encoder.getOutputFormat()); //muxer.writeSampleData(videoTrackIndex, inputBuffers, bufferInfo); muxer.start(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } </code></pre> <p>Here are the links that i follwed <a href="https://stackoverflow.com/questions/22076742/android-mediacodec-reduce-mp4-video-size">Android MediaCodec: Reduce mp4 video size</a> and</p> <p><a href="https://stackoverflow.com/questions/15950610/video-compression-on-android-using-new-mediacodec-library">Video compression on android using new MediaCodec Library</a></p>
23,886,931
1
3
null
2014-05-26 12:57:58.843 UTC
9
2014-05-27 12:13:29.76 UTC
2017-05-23 12:02:05.337 UTC
null
-1
null
1,740,097
null
1
6
android|compression|decode|encode|android-mediacodec
13,829
<p>You can try Intel INDE on <a href="https://software.intel.com/en-us/intel-inde" rel="nofollow">https://software.intel.com/en-us/intel-inde</a> and Media Pack for Android which is a part of INDE, tutorials on <a href="https://software.intel.com/en-us/articles/intel-inde-media-pack-for-android-tutorials" rel="nofollow">https://software.intel.com/en-us/articles/intel-inde-media-pack-for-android-tutorials</a>. It has a sample that shows how to use media pack to transcode=recompress video files. You can set smaller resolution and\or bitrate to output to get smaller file</p> <p>in ComposerTranscodeCoreActivity.java</p> <pre><code>protected void setTranscodeParameters(MediaComposer mediaComposer) throws IOException { mediaComposer.addSourceFile(mediaUri1); mediaComposer.setTargetFile(dstMediaPath); configureVideoEncoder(mediaComposer, videoWidthOut, videoHeightOut); configureAudioEncoder(mediaComposer); } protected void transcode() throws Exception { factory = new AndroidMediaObjectFactory(getApplicationContext()); mediaComposer = new MediaComposer(factory, progressListener); setTranscodeParameters(mediaComposer); mediaComposer.start(); } </code></pre>
18,392,786
How to submit a job to a specific node in PBS
<p>How do I send a job to a specific node in PBS/TORQUE? I think you must specify the node name after nodes.</p> <pre><code>#PBS -l nodes=abc </code></pre> <p>However, this doesn't seem to work and I'm not sure why. This question was asked here on <a href="https://stackoverflow.com/questions/1731171/pbs-and-specify-nodes-to-use">PBS and specify nodes to use</a></p> <p>Here is my sample code</p> <pre><code>#!/bin/bash #PBS nodes=node9,ppn=1, hostname date echo "This is a script" sleep 20 # run for a while so I can look at the details date </code></pre> <p>Also, how do I check which node the job is running on? I saw somewhere that <code>$PBS_NODEFILE</code> shows the details, but it doesn't seem to work for me. </p>
18,408,251
2
5
null
2013-08-23 00:20:10.387 UTC
10
2019-09-20 06:44:24.173 UTC
2017-05-23 11:47:08.517 UTC
null
-1
null
1,952,464
null
1
23
bash|shell|pbs|torque
45,105
<p>You can do it like this:</p> <pre><code>#PBS -l nodes=&lt;node_name&gt; </code></pre> <p>You can also specify the number of processors:</p> <pre><code>#PBS -l nodes=&lt;node_name&gt;:ppn=X </code></pre> <p>Or you can request additional nodes, specified or unspecified:</p> <pre><code>#PBS -l nodes=&lt;node_name1&gt;[:ppn=X][+&lt;node_name2...] </code></pre> <p>That gives you multiple specific nodes.</p> <pre><code>#PBS -l nodes=&lt;node_name&gt;[:ppn=X][+Y[:ppn=Z]] </code></pre> <p>This requests the specific node with X execution slots from that node, plus an additional Y nodes with Z execution slots each.</p> <p>Edit: To simply request a number of nodes and execution slots per node:</p> <h1>PBS -l nodes=X:ppn=Y</h1> <p><strong>NOTE: this is all for TORQUE/Moab. It may or may not work for other PBS resource managers/schedulers.</strong></p>
40,019,584
Could not find method android() for arguments org.gradle.api.Project
<p>Getting a bug, when I try to compile my project in studio , i have search quite a bit with no real solution to it </p> <p>Error:(17, 0) Could not find method android() for arguments [build_a7zf1o8ge4ow4uolz6kqzw5ov$_run_closure2@19201053] on root project 'booksStudioDir' of type org.gradle.api.Project.</p> <p>This is a sample of my build/gradle file </p> <pre><code>buildscript { repositories { maven { url 'https://maven.fabric.io/public' } } dependencies { classpath 'io.fabric.tools:gradle:1.+' } } apply plugin: 'com.android.application' apply plugin: 'io.fabric' android { compileSdkVersion 21 buildToolsVersion "23.0.1" defaultConfig { applicationId "com.peade.time" minSdkVersion 10 targetSdkVersion 13 } signingConfigs { release { storeFile file("/home/bestman/Desktop/mkey/key") storePassword "androidkeys" keyAlias "peade" keyPassword "yes1234" } } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt' signingConfig signingConfigs.release } } } repositories { maven { url 'https://maven.fabric.io/public' } mavenCentral() } dependencies { compile 'com.edmodo:cropper:1.0.1' compile 'com.android.support:support-v4:21.0.3' compile 'com.itextpdf:itextpdf:5.5.6' // compile files('libs/commons-lang3-3.3.2.jar') compile files('libs/dropbox-android-sdk-1.6.1.jar') // compile files('libs/httpmime-4.0.3.jar') compile files('libs/json_simple-1.1.jar') compile files('libs/picasso-2.5.2.jar') compile('com.crashlytics.sdk.android:crashlytics:2.5.2@aar') { transitive = true; } compile project(':owncloud') } </code></pre>
40,021,349
3
4
null
2016-10-13 11:21:10.43 UTC
4
2020-04-30 12:32:45.703 UTC
null
null
null
null
4,917,624
null
1
16
java|android|gradle|android-gradle-plugin
47,610
<p>There are two build.gradle files. One is in the top-level holder, and the other is in module holder. </p> <p>Below is an example.</p> <p>Top-level build.gradle:<br> <a href="https://github.com/nickbutcher/plaid/blob/master/build.gradle" rel="noreferrer">https://github.com/nickbutcher/plaid/blob/master/build.gradle</a></p> <p>module's build.gradle:<br> <a href="https://github.com/nickbutcher/plaid/blob/master/app/build.gradle" rel="noreferrer">https://github.com/nickbutcher/plaid/blob/master/app/build.gradle</a></p> <p>The <code>android</code> block <strong>should be in module's build.gradle</strong>. I guess you must have defined the <code>android</code> block in top-level build.gradle which is causing the error.</p>
41,022,927
Principal component analysis (PCA) of time series data: spatial and temporal pattern
<p>Suppose I have yearly precipitation data for 100 stations from 1951 to 1980. In some papers, I find people apply PCA to the time series and then plot the spatial loadings map (with values from -1 to 1), and also plot the time series of the PCs. For example, figure 6 in <a href="https://publicaciones.unirioja.es/ojs/index.php/cig/article/view/2931/2696" rel="noreferrer">https://publicaciones.unirioja.es/ojs/index.php/cig/article/view/2931/2696</a> is the spatial distribution of the PCs.</p> <p>I am using function <code>prcomp</code> in R and I wonder how I can do the same thing. In other words, how can I extract the "spatial pattern" and "temporal pattern" from the results of <code>prcomp</code> function? Thanks.</p> <pre><code>set.seed(1234) rainfall = sample(x=100:1000,size = 100*30,replace = T) rainfall=matrix(rainfall,nrow=100) colnames(rainfall)=1951:1980 PCA = prcomp(rainfall,retx=T) </code></pre> <p>Or, there are real data at <a href="https://1drv.ms/u/s!AnVl_zW00EHegxAprS4s7PDaYQVr" rel="noreferrer">https://1drv.ms/u/s!AnVl_zW00EHegxAprS4s7PDaYQVr</a></p>
41,245,416
1
3
null
2016-12-07 16:45:38.337 UTC
10
2016-12-20 15:07:25.96 UTC
2016-12-18 20:23:23.827 UTC
null
6,162,679
null
6,162,679
null
1
11
r|spatial|pca|temporal
16,994
<p>"Temporal pattern" explains the dominant temporal variation of time series in all grids, and it is represented by <strong>principal components</strong> (PCs, a number of time series) of PCA. In R, it is <code>prcomp(data)$x[,'PC1']</code> for the most important PC, PC1.</p> <p>"Spatial pattern" explains how strong the PCs depend on some variables (geography in your case), and it is represented by the <strong>loadings of each principal components</strong>. For example, for PC1, it is <code>prcomp(data)$rotation[,'PC1']</code>.</p> <p>Here is an example of <strong>constructing a PCA for spatiotemporal data in R and showing the temporal variation and spatial heterogeneity</strong>, using your data.</p> <p>First of all, the data has to be transformed into a data.frame with variables (spatial grid) and observations (yyyy-mm).</p> <p>Loading and transforming the data:</p> <pre><code>load('spei03_df.rdata') str(spei03_df) # the time dimension is saved as names (in yyyy-mm format) in the list lat &lt;- spei03_df$lat # latitude of each values of data lon &lt;- spei03_df$lon # longitude rainfall &lt;- spei03_df rainfall$lat &lt;- NULL rainfall$lon &lt;- NULL date &lt;- names(rainfall) rainfall &lt;- t(as.data.frame(rainfall)) # columns are where the values belong, rows are the times </code></pre> <p>To understand the data, drawing on map the data for Jan 1950:</p> <pre><code>library(mapdata) library(ggplot2) # for map drawing drawing &lt;- function(data, map, lonlim = c(-180,180), latlim = c(-90,90)) { major.label.x = c("180", "150W", "120W", "90W", "60W", "30W", "0", "30E", "60E", "90E", "120E", "150E", "180") major.breaks.x &lt;- seq(-180,180,by = 30) minor.breaks.x &lt;- seq(-180,180,by = 10) major.label.y = c("90S","60S","30S","0","30N","60N","90N") major.breaks.y &lt;- seq(-90,90,by = 30) minor.breaks.y &lt;- seq(-90,90,by = 10) panel.expand &lt;- c(0,0) drawing &lt;- ggplot() + geom_path(aes(x = long, y = lat, group = group), data = map) + geom_tile(data = data, aes(x = lon, y = lat, fill = val), alpha = 0.3, height = 2) + scale_fill_gradient(low = 'white', high = 'red') + scale_x_continuous(breaks = major.breaks.x, minor_breaks = minor.breaks.x, labels = major.label.x, expand = panel.expand,limits = lonlim) + scale_y_continuous(breaks = major.breaks.y, minor_breaks = minor.breaks.y, labels = major.label.y, expand = panel.expand, limits = latlim) + theme(panel.grid = element_blank(), panel.background = element_blank(), panel.border = element_rect(fill = NA, color = 'black'), axis.ticks.length = unit(3,"mm"), axis.title = element_text(size = 0), legend.key.height = unit(1.5,"cm")) return(drawing) } map.global &lt;- fortify(map(fill=TRUE, plot=FALSE)) dat &lt;- data.frame(lon = lon, lat = lat, val = rainfall["1950-01",]) sample_plot &lt;- drawing(dat, map.global, lonlim = c(-180,180), c(-90,90)) ggsave("sample_plot.png", sample_plot,width = 6,height=4,units = "in",dpi = 600) </code></pre> <p><a href="https://i.stack.imgur.com/w0MJp.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/w0MJp.jpg" alt="the spatial distribution of Jan-1950 data"></a></p> <p>As shown above, the gridded data given by the link provided includes values that represent rainfall (some kinds of indexes?) in Canada.</p> <p>Principal Component Analysis:</p> <pre><code>PCArainfall &lt;- prcomp(rainfall, scale = TRUE) summaryPCArainfall &lt;- summary(PCArainfall) summaryPCArainfall$importance[,c(1,2)] </code></pre> <p>It shows that the first two PCs explain 10.5% and 9.2% of variance in the rainfall data.</p> <p>I extract the loadings of the first two PCs and the PC time series themselves: The "spatial pattern" (loadings), showing the spatial heterogeneity of the strengths of the trends (PC1 and PC2).</p> <pre><code>loading.PC1 &lt;- data.frame(lon=lon,lat=lat,val=PCArainfall$rotation[,'PC1']) loading.PC2 &lt;- data.frame(lon=lon,lat=lat,val=PCArainfall$rotation[,'PC2']) drawing.loadingPC1 &lt;- drawing(loading.PC1,map.global, lonlim = c(-180,-30), latlim = c(40,90)) + ggtitle("PC1") drawing.loadingPC2 &lt;- drawing(loading.PC2,map.global, lonlim = c(-180,-30), latlim = c(40,90)) + ggtitle("PC2") ggsave("loading_PC1.png",drawing.loadingPC1,width = 6,height=4,units = "in",dpi = 600) ggsave("loading_PC2.png",drawing.loadingPC2,width = 6,height=4,units = "in",dpi = 600) </code></pre> <p><a href="https://i.stack.imgur.com/VIW66.png" rel="noreferrer"><img src="https://i.stack.imgur.com/VIW66.png" alt="PC1 loadings"></a> <a href="https://i.stack.imgur.com/2BGXm.png" rel="noreferrer"><img src="https://i.stack.imgur.com/2BGXm.png" alt="PC2 loadings"></a></p> <p>The "temporal pattern", the first two PC time series, showing the dominant temporal trends of the data</p> <pre><code>library(xts) PC1 &lt;- ts(PCArainfall$x[,'PC1'],start=c(1950,1),end=c(2014,12),frequency = 12) PC2 &lt;- ts(PCArainfall$x[,'PC2'],start=c(1950,1),end=c(2014,12),frequency = 12) png("PC-ts.png",width = 6,height = 4,res = 600,units = "in") plot(as.xts(PC1),major.format = "%Y-%b", type = 'l', ylim = c(-100, 100), main = "PC") # the black one is PC1 lines(as.xts(PC2),col='blue',type="l") # the blue one is PC2 dev.off() </code></pre> <p><a href="https://i.stack.imgur.com/x4Xjd.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/x4Xjd.jpg" alt="PC1 and PC2"></a></p> <p>This example is, however, by no means the best PCA for your data because there are serious seasonality and annual variations in the PC1 and PC2 (Of course, it rains more in summer, and look at the weak tails of the PCs).</p> <p>You can improve the PCA probably by deseasonalizing the data or removing the annual trend by regression, as in the literature suggested. But this is already beyond our topic.</p>
41,098,009
Mocking `document` in jest
<p>I'm trying to write tests for my web components projects in jest. I already use babel with es2015 preset. I'm facing an issue while loading the js file. I have followed a piece of code where <code>document</code> object has a <code>currentScript</code> object. But in test context it is <code>null</code>. So I was thinking of mocking same. But <code>jest.fn()</code> is not really help in same. How can I handle this issue?</p> <p>Piece of code where jest is failing.</p> <pre><code>var currentScriptElement = document._currentScript || document.currentScript; var importDoc = currentScriptElement.ownerDocument; </code></pre> <p>Test case I have written. <code>component.test.js</code></p> <pre><code>import * as Component from './sample-component.js'; describe('component test', function() { it('check instance', function() { console.log(Component); expect(Component).toBeDefined(); }); }); </code></pre> <p>Following is the error thrown by jest</p> <pre><code>Test suite failed to run TypeError: Cannot read property 'ownerDocument' of null at src/components/sample-component/sample-component.js:4:39 </code></pre> <p><strong>Update:</strong> As per suggestion from Andreas Köberle, I have added some global vars and tried to mock like following</p> <pre><code>__DEV__.document.currentScript = document._currentScript = { ownerDocument: '' }; __DEV__.window = { document: __DEV__.document } __DEV__.document.registerElement = jest.fn(); import * as Component from './arc-sample-component.js'; describe('component test', function() { it('check instance', function() { console.log(Component); expect(Component).toBeDefined(); }); }); </code></pre> <p>But no luck</p> <p><strong>Update:</strong> I have tried above code without <code>__dev__</code>. Also by setting document as global.</p>
50,629,802
9
4
null
2016-12-12 09:47:44.663 UTC
12
2021-11-11 00:18:31.267 UTC
2018-12-03 11:36:07.153 UTC
null
7,727,575
null
1,184,902
null
1
75
jestjs|jsdom|babel-jest
117,819
<p>Similar to what others have said, but instead of trying to mock the DOM yourself, just use JSDOM:</p> <pre class="lang-js prettyprint-override"><code>// __mocks__/client.js import { JSDOM } from &quot;jsdom&quot; const dom = new JSDOM() global.document = dom.window.document global.window = dom.window </code></pre> <p>Then in your jest config:</p> <pre class="lang-json prettyprint-override"><code> &quot;setupFiles&quot;: [ &quot;./__mocks__/client.js&quot; ], </code></pre>
4,879,706
SSRS Report - IIF statement Question
<p>Doing an expression I get an error, can someone show me the correct syntax here? </p> <pre><code>=IIf(Fields!t_cpcp.Value ="310", "Purchased Material &amp; Raw Material", Nothing) =IIf(Fields!t_cpcp.Value ="320", "Manufacturing Direct Labor", Nothing) =IIf(Fields!t_cpcp.Value ="325", "Subcontract Cost", Nothing) =IIf(Fields!t_cpcp.Value ="330", "Engineering Direct Labor", Nothing) =IIf(Fields!t_cpcp.Value ="340", "Manufacturing Labor O/H", Nothing) =IIf(Fields!t_cpcp.Value ="345", "Engineering Labor O/H", Nothing) =IIf(Fields!t_cpcp.Value ="350", "Material O/H", Nothing) =IIf(Fields!t_cpcp.Value ="355", "Labor O/H Surcharge", Nothing) =IIf(Fields!t_cpcp.Value ="360", "Subcontract Material Burden", Nothing) =IIf(Fields!t_cpcp.Value ="MFD", "Manufactured Items", Nothing) </code></pre>
4,879,844
2
5
null
2011-02-02 20:52:14.237 UTC
1
2013-02-22 11:13:25.867 UTC
2011-02-02 20:55:17.913 UTC
null
11,027
null
426,733
null
1
6
sql|if-statement|ssrs-2008|reporting-services
40,365
<p>If you want this to all be in one expression, you may want to use the SWITCH statement:</p> <pre><code>=Switch(&lt;condition&gt;, &lt;return value if true&gt;, &lt;next condition&gt;, &lt;return value if true&gt;, ...) </code></pre> <p>The switch statement will return the value for the first condition that is true.Using your example, you could try:</p> <pre><code>=Switch(Fields!t_cpcp.Value ="310", "Purchased Material &amp; Raw Material", Fields!t_cpcp.Value ="320", "Manufacturing Direct Labor", Fields!t_cpcp.Value ="325", "Subcontract Cost", ...rest of them go here...) </code></pre>
4,893,432
SSL on Apache2 with WSGI
<p>I am trying to set up SSL on a Django site I maintain and having a bit of trouble setting up my VirtualHost with SSL. I followed the instructions <a href="http://beeznest.wordpress.com/2008/04/25/how-to-configure-https-on-apache-2/" rel="noreferrer">here</a> but every time I try to restart apache, it tells me it cannot restart because of multiple virtualhosts usign the same wsgi config:</p> <pre><code>/etc/init.d/apache2 reload Syntax error on line 33 of /etc/apache2/sites-enabled/www.mydomain.com: Name duplicates previous WSGI daemon definition. ...fail! </code></pre> <p>I understand what is happening, just not how to fix it. Any suggestions are appreciated, thanks! Here is what my VirutalHosts file looks like:</p> <pre><code>&lt;VirtualHost *:80&gt; ServerAdmin [email protected] ServerName mydomain.com ServerAlias www.mydomain.com DocumentRoot /sites/mydomain # WSGI Settings WSGIScriptAlias / /sites/mydomain/wsgi_handler.py WSGIDaemonProcess mydomain user=myuser group=mygroup processes=1 threads=1 WSGIProcessGroup mydomain # Static Directories Alias /static /sites/mydomain/static/ &lt;Location "/static"&gt; SetHandler None &lt;/Location&gt; Alias /img /sites/mydomain/img/ &lt;Location "/img"&gt; SetHandler None &lt;/Location&gt; &lt;/VirtualHost&gt; &lt;VirtualHost *:443&gt; ServerAdmin [email protected] ServerName mydomain.com ServerAlias www.mydomain.com DocumentRoot /sites/mydomain # WSGI Settings WSGIScriptAlias / /sites/mydomain/wsgi_handler.py WSGIDaemonProcess mydomain user=myuser group=mygroup processes=1 threads=1 WSGIProcessGroup mydomain # Static Directories Alias /static /sites/mydomain/static/ &lt;Location "/static"&gt; SetHandler None &lt;/Location&gt; Alias /img /sites/mydomain/img/ &lt;Location "/img"&gt; SetHandler None &lt;/Location&gt; # SSL Stuff SSLEngine On SSLCertificateFile /etc/apache2/ssl/crt/vhost1.crt SSLCertificateKeyFile /etc/apache2/ssl/key/vhost1.key &lt;Location /&gt; SSLRequireSSL On SSLVerifyClient optional SSLVerifyDepth 1 SSLOptions +StdEnvVars +StrictRequire &lt;/Location&gt; &lt;/VirtualHost&gt; </code></pre>
4,895,652
2
0
null
2011-02-04 00:41:32.89 UTC
12
2013-09-10 14:52:24.237 UTC
null
null
null
null
206,506
null
1
46
ssl|apache2|wsgi
21,600
<p>Remove the line:</p> <pre><code>WSGIDaemonProcess mydomain user=myuser group=mygroup processes=1 threads=1 </code></pre> <p>from the VirtualHost for 443. The WSGIProcessGroup for mydomain in that VirtualHost is able to reach across to the WSGIDaemonProcess definition in 80.</p> <p>In other words, as the error message tries to suggest, the name for the WSGIDaemonProcess, ie., 'mydomain', must be unique for the whole Apache server.</p> <p>Referring across VirtualHosts as indicated means both HTTP and HTTPS variants of site will still run in same daemon process group/interpreter.</p>
5,450,076
What's the significant use of unary plus and minus operators?
<p>If unary <code>+</code>/<code>-</code> operators are used to perform conversions as the <code>Number()</code> casting function, then why do we need unary operators? What's the special need of these unary operators? </p>
5,450,116
2
0
null
2011-03-27 15:07:42.13 UTC
17
2021-10-06 17:51:18.047 UTC
2016-01-26 08:24:55.61 UTC
null
402,884
null
629,305
null
1
58
javascript
13,350
<p>The Unary <code>+</code> operator converts its operand to Number type. The Unary <code>-</code> operator converts its operand to Number type, and then negates it. (per the <a href="http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf">ECMAScript spec</a>)</p> <p>In practice, Unary <code>-</code> is used for simply putting negative numbers in normal expressions, e.g.:</p> <pre><code>var x = y * -2.0; </code></pre> <p>That's the unary minus operator at work. The Unary <code>+</code> is equivalent to the Number() constructor called as a function, as implied by the spec.</p> <p>I can only speculate on the history, but the unary +/- operators behave similarly in many C-derived languages. I suspect the Number() behavior is the addition to the language here. </p>
16,439,037
Drop Down List Selected Index changed not working in Update panel
<p>I have a drop down list in UpdatePanel_2, it gets populated when Button_1 is clicked in UpdatePanel_1.</p> <p>My ddlist markup is,</p> <pre><code>&lt;asp:DropDownList id="drop1" runat="server" EnableViewState="true" AutoPostBack="true" OnSelectedIndexChanged="Drop1_SelectedIndexChanged" /&gt; </code></pre> <p>then code behind is,</p> <pre><code> protected void Drop1_SelectedIndexChanged(object sender, EventArgs e) { } </code></pre> <p><strong>I also tried putting AutoPostback=true to my DropDownList, still no success.</strong></p> <p>I also added triggre to update panel 2 but no gain,</p> <pre><code> &lt;Triggers&gt; &lt;asp:AsyncPostbackTrigger ControlID="drop1" EventName="SelectedIndexChanged" /&gt; &lt;/Triggers&gt; </code></pre> <p><strong>I am populating DropDownList using a button not PAGE LOAD METHOD PLEASE READ before answering. Thanks</strong></p>
16,439,640
5
4
null
2013-05-08 11:06:04.91 UTC
4
2017-07-14 16:03:51.617 UTC
2013-05-21 11:30:52.667 UTC
null
109,941
null
1,668,069
null
1
9
c#|webforms|updatepanel
51,870
<p>Check the data to populate the <code>DropDownList</code> in the <code>Page_Load</code> event and always check <code>IspostBack</code>:</p> <pre><code>if(!IsPostBack) { //DropDownList configuration } </code></pre> <p>Use <code>EnableViewState</code>:</p> <pre><code> &lt;asp:DropDownList ID="ddlAddDepPlans" runat="server" AutoPostBack="true" EnableViewState="true" /&gt; </code></pre> <p>Hope it helps you.</p>
154,533
Best way to bind WPF properties to ApplicationSettings in C#?
<p>What is the best way to bind WPF properties to ApplicationSettings in C#? Is there an automatic way like in a Windows Forms Application? Similar to <a href="https://stackoverflow.com/questions/18421/best-way-to-bind-windows-forms-properties-to-applicationsettings-in-c">this question</a>, how (and is it possible to) do you do the same thing in WPF?</p>
263,956
7
0
null
2008-09-30 19:20:29.08 UTC
19
2013-07-01 15:17:19.983 UTC
2017-05-23 11:54:43.513 UTC
Kris Erickson
-1
Kris Erickson
3,798
null
1
51
c#|.net|wpf|visual-studio
36,510
<p>You can directly bind to the static object created by Visual Studio.</p> <p>In your windows declaration add:</p> <pre><code>xmlns:p="clr-namespace:UserSettings.Properties" </code></pre> <p>where <code>UserSettings</code> is the application namespace.</p> <p>Then you can add a binding to the correct setting:</p> <pre><code>&lt;TextBlock Height="{Binding Source={x:Static p:Settings.Default}, Path=Height, Mode=TwoWay}" ....... /&gt; </code></pre> <p>Now you can save the settings, per example when you close your application:</p> <pre><code>protected override void OnClosing(System.ComponentModel.CancelEventArgs e) { Properties.Settings.Default.Save(); base.OnClosing(e); } </code></pre>
1,167,071
What's the best way to set all values in a C# Dictionary<string,bool>?
<p>What's the best way to set all values in a C# Dictionary?</p> <p>Here is what I am doing now, but I'm sure there is a better/cleaner way to do this:</p> <pre><code>Dictionary&lt;string,bool&gt; dict = GetDictionary(); var keys = dict.Keys.ToList(); for (int i = 0; i &lt; keys.Count; i++) { dict[keys[i]] = false; } </code></pre> <p>I have tried some other ways with foreach, but I had errors.</p>
1,167,089
8
0
null
2009-07-22 17:57:31.423 UTC
0
2021-04-07 13:03:53.717 UTC
null
null
null
null
64,334
null
1
38
c#|.net|generics|dictionary
39,175
<p>That is a reasonable approach, although I would prefer:</p> <pre><code>foreach (var key in dict.Keys.ToList()) { dict[key] = false; } </code></pre> <p>The call to <code>ToList()</code> makes this work, since it's pulling out and (temporarily) saving the list of keys, so the iteration works.</p>
1,039,725
How to do URL re-writing in PHP?
<p>I am trying to implement URL rewriting in my PHP application. Can someone share a step by step procedure of implementing URL rewriting in PHP and MySQL?</p> <p>In my application I want to implement following URL rewriting, I want to redirect</p> <pre><code>1. http://example.com/videos/play/google-io-2009-wave-intro 2. http://example.com/videos/play/203/google-io-2009-wave-intro </code></pre> <p>to</p> <pre><code>1. http://example.com/videos/play.php?title=google-io-2009-wave-intro 2. http://example.com/videos/play.php?id=203 </code></pre> <p>Please tell me how to implement both URL rewriting in any of the above way. </p> <p>One more thing which URL will be best according to SEO, management, application point-of-view out of the following two types.</p> <pre><code>1. http://example.com/videos/play/google-io-2009-wave-intro 2. http://example.com/videos/play/203/google-io-2009-wave-intro </code></pre>
1,039,873
9
2
null
2009-06-24 17:17:20.517 UTC
18
2017-05-12 09:08:47.01 UTC
2014-06-10 13:30:57.793 UTC
null
472,495
null
45,261
null
1
14
php|apache|mod-rewrite|seo|url-rewriting
35,863
<p><a href="http://www.workingwith.me.uk/articles/scripting/mod_rewrite" rel="nofollow noreferrer">A Beginner's Guide to mod_rewrite</a>.</p> <p>Typically this will be nothing more than enabling the mod_rewrite module (you likely already have it enabled with your host), and then adding a .htaccess file into your web-directory. Once you've done that, you are only a few lines away from being done. The tutorial linked above will take care of you.</p> <p>Just for fun, here's a <a href="http://www.kohanaframework.org" rel="nofollow noreferrer">Kohana</a> .htaccess file for rewriting:</p> <pre><code># Turn on URL rewriting RewriteEngine On # Installation directory RewriteBase /rootDir/ # Protect application and system files from being viewed RewriteRule ^(application|modules|system) - [F,L] # Allow any files or directories that exist to be displayed directly RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d # Rewrite all other URLs to index.php/ RewriteRule .* index.php/$0 [PT,L] </code></pre> <p>What this will do is take all requests and channel them through the index.php file. So if you visited www.examplesite.com/subjects/php, you may actually be visiting www.examplesite.com/index.php?a=subjects&amp;b=php.</p> <p>If you find these URLs attractive, I would encourage you to go one step further and check out the MVC Framework (Model, View, Controller). It essentially allows you to treat your website like a group of functions:</p> <p>www.mysite.com/jokes</p> <pre><code>public function jokes ($page = 1) { # Show Joke Page (Defaults to page 1) } </code></pre> <p>Or, www.mysite.com/jokes/2</p> <pre><code>public function jokes ($page = 1) { # Show Page 2 of Jokes (Page 2 because of our different URL) } </code></pre> <p>Notice how the first forward slash calls a function, and all that follow fill up the parameters of that function. It's really very nice, and make web-development much more fun!</p>
316,757
UK Vat change from 17.5 to 15% - How will this affect your code?
<p>The UK VAT system is changing from 17.5% to 15%. What strategies have you used in your code to store the VAT, and how will the change affect your applications. Do you store a history of vats so you can calculate old prices, or are old invoices stored in a separate table? Is it a simple config setting, or did you bodge it? What's the ideal way to store VAT?</p>
316,962
9
0
null
2008-11-25 09:02:40.893 UTC
9
2014-07-04 11:09:34.34 UTC
2009-01-16 15:23:21.23 UTC
Mohit Nanda
18,615
digiguru
5,055
null
1
17
database-design|configuration-management
13,633
<h2>Don't calculate it. Store it!</h2> <p>HMRC are very fussy about getting paid the right amount of VAT. The rounding of VAT calculations is somewhat vaguely specified in the user guides, and leaving it up to future implementers to get it right is possibly asking for trouble. By storing the amount when the invoice/line-item is entered, this problem is avoided.</p> <p>This seems like a waste of storage and a violation of redundancy principles, but the amount of storage involved is tiny and it could save a lot of trouble in the future. Of course, it goes without saying that the currency amounts (and potentially even VAT rates with a fractional part) should be stored as a multiplied integer to avoid binary fractional representation rounding errors creeping in too.</p> <h2>Central rate storage</h2> <p>You should absolutely use central rate storage. However, I would recommend that this only provides the current default rates used when entering new invoices. These can be stored with start and end dates to give automatic changeover if necessary. These rates can be stored for each invoice (or invoice line) along with the calculated VAT amounts at the time the invoice is raised to give an absolute snapshot of the situation at the time.</p> <p>Don't forget to accommodate the different VAT rates too (e.g. standard, reduced, zero-rated, no-VAT) and the possibility of trading with VAT registered entities in other EU countries where you may have to no-VAT an invoice that would normally be subject to VAT.</p> <p>You could end up with a table like this (example):</p> <pre> id | Rate name | VAT rate | Start date | End date --------------------------------------------------- 1 | Standard | 1750 | 01/01/1991 | 30/11/2008 2 | Standard | 1500 | 01/12/2008 | 31/12/2009 etc </pre> <p>The above table is only an example. The VAT rate is stored as an integer of "basis points" (e.g. hundredths of a percentage point), but does assume that the VAT rate will never be to more than 2 decimal places. You could obviously extend this with an extra column to relieve this problem, but it would seem possibly a step too far!</p>
551,668
How do I set the default Java installation/runtime (Windows)?
<p>I'm in the situation where I've installed the JDK, but I can't run applets in browsers (I may not have installed the JRE).</p> <p>However, when I install the JRE, it clobbers my JDK as the default runtime. This breaks pretty much everything (Eclipse, Ant) - as they require a server JVM.</p> <p>There's no <code>JAVA_HOME</code> environment variable these days - it just seems to use some registry magic (setting the system path is of no use either). Previously, I've just uninstalled the JRE after I've used it to restore the JDK. This time I want to fix it properly.</p> <p>This also manifests itself with the jre autoupdater - once upon a time, I had a working setup with the JDK and JRE, but it updated and bust everything.</p>
551,709
9
2
null
2009-02-15 21:54:51.95 UTC
13
2020-10-26 12:31:48.647 UTC
2018-09-07 11:58:00.513 UTC
Stephen
7,023,590
Stephen
37,193
null
1
52
java|windows|installation|runtime
159,148
<p>This is a bit of a pain on Windows. Here's what I do.</p> <p>Install latest Sun JDK, e.g. <strong>6u11</strong>, in path like <code>c:\install\jdk\sun\6u11</code>, then let the installer install public JRE in the default place (<code>c:\program files\blah</code>). This will setup your default JRE for the majority of things.</p> <p>Install older JDKs as necessary, like <strong>5u18</strong> in <code>c:\install\jdk\sun\5u18</code>, but don't install the public JREs.</p> <p>When in development, I have a little batch file that I use to setup a command prompt for each JDK version. Essentially just set <code>JAVA_HOME=c:\jdk\sun\JDK_DESIRED</code> and then set <code>PATH=%JAVA_HOME%\bin;%PATH%</code>. This will put the desired JDK first in the path and any secondary tools like Ant or Maven can use the <code>JAVA_HOME</code> variable.</p> <p>The path is important because most public JRE installs put a linked executable at <code>c:\WINDOWS\System32\java.exe</code>, which usually <em>overrides</em> most other settings.</p>
832,375
Force a transactional rollback without encountering an exception?
<p>I have a method that does a bunch of things; amongst them doing a number of inserts and updates.</p> <p>It's declared thusly:</p> <pre><code>@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, readOnly = false) public int saveAll() { //do stuff; } </code></pre> <p>It works exactly as it is supposed to and I have no problems with it. There are situations however when I want to force the rollback in spite of there not being an exception... at the moment, I'm forcing an exception when I encounter the right conditions, but it's ugly and I don't like it.</p> <p>Can I actively call the rollback somehow?</p> <p>The exception calls it... I'm thinking maybe I can too.</p>
835,384
9
1
null
2009-05-07 00:11:24.887 UTC
18
2021-12-04 14:48:29.77 UTC
2021-06-15 10:58:26.387 UTC
null
452,775
null
59,947
null
1
52
java|hibernate|spring
52,464
<p>In Spring Transactions, you use <code>TransactionStatus.setRollbackOnly()</code>. </p> <p>The problem you have here is that you're using <code>@Transactional</code> to demarcate your transactions. This has the benefit of being non-invasive, but it also means that if you want to manually interact with the transaction context, you can't.</p> <p>If you want tight control of your transaction status, you have to use programmatic transactions rather than declarative annotations. This means using Spring's TransactionTemplate, or use its PlatformTransactionManager directly. See section 9.6 of the Spring reference manual.</p> <p>With <code>TransactionTemplate</code>, you provide a callback object which implements <code>TransactionCallback</code>, and the code in this callback has access to the <code>TransactionStatus</code> objects.</p> <p>It's not as nice as <code>@Transactional</code>, but you get closer control of your tx status. </p>
593,334
How to use multiple AWS accounts from the command line?
<p>I've got two different apps that I am hosting (well the second one is about to go up) on Amazon EC2.</p> <p>How can I work with both accounts at the command line (Mac OS X) but keep the EC2 keys &amp; certificates separate? Do I need to change my environment variables before each ec2-* command?</p> <p>Would using an alias and having it to the setting of the environment in-line work? Something like:</p> <pre><code>alias ec2-describe-instances1 = export EC2_PRIVATE_KEY=/path; ec2-describe-instances </code></pre>
593,361
10
0
null
2009-02-27 02:50:38.56 UTC
61
2022-04-13 11:58:52.85 UTC
2021-01-06 08:59:39.233 UTC
null
6,862,601
Matt Culbreth
43,207
null
1
196
amazon-web-services|amazon-ec2|aws-cli
117,688
<p>You should be able to use the following command-options in lieu of the <code>EC2_PRIVATE_KEY</code> (and even <code>EC2_CERT</code>) environment variables:</p> <ul> <li><code>-K &lt;private key&gt;</code></li> <li><code>-C &lt;certificate&gt;</code></li> </ul> <p>You can put these inside aliases, e.g.</p> <pre><code>alias ec2-describe-instances1 ec2-describe-instances -K /path/to/key.pem </code></pre>
136,734
Key Presses in Python
<p>Is it possible to make it appear to a system that a key was pressed, for example I need to make <kbd>A</kbd> key be pressed thousands of times, and it is much to time consuming to do it manually, I would like to write something to do it for me, and the only thing I know well enough is Python.</p> <p>A better way to put it, I need to emulate a key press, I.E. not capture a key press.</p> <p>More Info (as requested): I am running windows XP and need to send the keys to another application.</p>
136,780
11
1
null
2008-09-25 22:58:01.09 UTC
17
2021-07-30 14:08:27.31 UTC
2012-02-23 08:31:57.103 UTC
Unkwntech
355,231
Unkwntech
115
null
1
40
python|keypress
200,274
<p>Install the <a href="https://github.com/mhammond/pywin32" rel="noreferrer">pywin32</a> extensions. Then you can do the following:</p> <pre><code>import win32com.client as comclt wsh= comclt.Dispatch("WScript.Shell") wsh.AppActivate("Notepad") # select another application wsh.SendKeys("a") # send the keys you want </code></pre> <p>Search for documentation of the WScript.Shell object (I believe installed by default in all Windows XP installations). You can start <a href="http://www.microsoft.com/technet/scriptcenter/guide/sas_wsh_pkoy.mspx?mfr=true" rel="noreferrer">here</a>, perhaps.</p> <p><strong>EDIT:</strong> Sending F11 </p> <pre><code>import win32com.client as comctl wsh = comctl.Dispatch("WScript.Shell") # Google Chrome window title wsh.AppActivate("icanhazip.com") wsh.SendKeys("{F11}") </code></pre>
401,635
Good beginners material on Prolog
<p>I am looking for good beginners material on Prolog, both online and printed. I am not only interested in 'learning the language' but also in background and scientific information.</p>
401,768
11
1
null
2008-12-30 21:54:48.367 UTC
61
2013-03-12 15:11:34.593 UTC
2011-12-09 18:19:04.76 UTC
null
3,043
MeeLow
50,317
null
1
70
prolog|artificial-intelligence
15,187
<p>Check out <a href="http://www.learnprolognow.org/" rel="noreferrer">Learn Prolog Now!</a></p> <p>This book is well-written, should be easy to read for beginners. It's available in printed form and also as a free online version. It is also relatively new (from 2003), which is not the case with many Prolog books out there.</p>
176,476
How can I automate HTML-to-PDF conversions?
<p>I've been using htmldoc for a while, but I've run into some fairly serious limitations. I need the end solution to work on a Linux box. I'll be calling this library/utility/application from a Perl app, so any Perl interfaces would be a bonus.</p>
176,957
16
0
null
2008-10-06 22:34:53.567 UTC
11
2021-04-10 13:25:20.173 UTC
2010-01-08 12:59:42.553 UTC
null
2,766,176
null
2,901
null
1
48
linux|perl|pdf
74,926
<p>NOTE: This answer is from 2008 and is probably now incorrect; please check the other answers</p> <p><a href="http://www.princexml.com/" rel="nofollow noreferrer">PrinceXML</a> is the best one I've seen (it parses regular HTML as well as XML/XHTML). How is it the best? <a href="http://www.princexml.com/samples/acid2/" rel="nofollow noreferrer">Well, it passes the acid2 test</a> which I thought was pretty darn impressive</p> <p>It is however, quite expensive</p>
703,035
When are you truly forced to use UUID as part of the design?
<p>I don't really see the point of <a href="http://en.wikipedia.org/wiki/UUID" rel="noreferrer">UUID</a>. I know the probability of a collision is <em>effectively nil</em>, but <em>effectively nil</em> is not even close to impossible.</p> <p>Can somebody give an example where you have no choice but to use UUID? From all the uses I've seen, I can see an alternative design without UUID. Sure the design might be slightly more complicated, but at least it doesn't have a non-zero probability of failure.</p> <p>UUID smells like global variables to me. There are many ways global variables make for simpler design, but its just lazy design.</p>
786,541
16
9
null
2009-03-31 21:01:38.077 UTC
86
2018-11-02 19:12:11.337 UTC
2018-11-02 19:12:11.337 UTC
Pyrolistical
2,370,483
Pyrolistical
21,838
null
1
134
architecture|uuid
45,822
<p>I wrote the UUID generator/parser for Ruby, so I consider myself to be reasonably well-informed on the subject. There are four major UUID versions:</p> <p>Version 4 UUIDs are essentially just 16 bytes of randomness pulled from a cryptographically secure random number generator, with some bit-twiddling to identify the UUID version and variant. These are extremely unlikely to collide, but it could happen if a PRNG is used or if you just happen to have really, really, really, really, really bad luck.</p> <p>Version 5 and Version 3 UUIDs use the SHA1 and MD5 hash functions respectively, to combine a namespace with a piece of already unique data to generate a UUID. This will, for example, allow you to produce a UUID from a URL. Collisions here are only possible if the underlying hash function also has a collision.</p> <p>Version 1 UUIDs are the most common. They use the network card's MAC address (which unless spoofed, should be unique), plus a timestamp, plus the usual bit-twiddling to generate the UUID. In the case of a machine that doesn't have a MAC address, the 6 node bytes are generated with a cryptographically secure random number generator. If two UUIDs are generated in sequence fast enough that the timestamp matches the previous UUID, the timestamp is incremented by 1. Collisions should not occur unless one of the following happens: The MAC address is spoofed; One machine running two different UUID generating applications produces UUIDs at the exact same moment; Two machines without a network card or without user level access to the MAC address are given the same random node sequence, and generate UUIDs at the exact same moment; We run out of bytes to represent the timestamp and rollover back to zero.</p> <p>Realistically, none of these events occur by accident within a single application's ID space. Unless you're accepting IDs on, say, an Internet-wide scale, or with an untrusted environment where malicious individuals might be able to do something bad in the case of an ID collision, it's just not something you should worry about. It's critical to understand that if you happen to generate the same version 4 UUID as I do, in most cases, it doesn't matter. I've generated the ID in a completely different ID space from yours. My application will never know about the collision so the collision doesn't matter. Frankly, in a single application space without malicious actors, the extinction of all life on earth will occur long before you have a collision, even on a version 4 UUID, even if you're generating quite a few UUIDs per second.</p> <p>Also, 2^64 * 16 is 256 exabytes. As in, you would need to store 256 exabytes worth of IDs before you had a 50% chance of an ID collision in a single application space.</p>
203,495
Testing REST webservices
<p>My organization is working on building RESTful webservices on JBoss appserver. The QA team is used to testing SOAP webservices so far using SoapUI. SoapUI has a new version that has REST capabilities. We're considering using that.</p> <ol> <li>Are there any publicly available RESTful services available on the net for free that someone could test ? <br> </li> <li>What tools are available(and used) for testing RESTful web services ?</li> </ol>
1,037,408
24
2
null
2008-10-15 02:06:56.057 UTC
31
2015-04-01 19:34:18.263 UTC
2013-01-15 08:20:49.967 UTC
anjanb
1,484,739
anjanb
11,142
null
1
63
java|web-services|rest|testing|rest-client
58,173
<p><a href="http://www.soapui.org" rel="noreferrer">soapUI</a> will do the job as well, check out <a href="http://www.eviware.com/blogs/oleblog/?p=11" rel="noreferrer">this blog post</a> to get started.</p>
1,340,224
iPhone UITextField - Change placeholder text color
<p>I'd like to change the color of the placeholder text I set in my <code>UITextField</code> controls, to make it black.</p> <p>I'd prefer to do this without using normal text as the placeholder and having to override all the methods to imitate the behaviour of a placeholder.</p> <p>I believe if I override this method:</p> <pre><code>- (void)drawPlaceholderInRect:(CGRect)rect </code></pre> <p>then I should be able to do this. But I'm unsure how to access the actual placeholder object from within this method.</p>
3,396,065
32
0
null
2009-08-27 10:36:19.59 UTC
146
2022-05-27 16:04:30.517 UTC
2016-08-03 05:44:36.79 UTC
null
4,078,527
null
33,604
null
1
585
ios|uitextfield
377,237
<p>You can override <code>drawPlaceholderInRect:(CGRect)rect</code> as such to manually render the placeholder text:</p> <pre><code>- (void) drawPlaceholderInRect:(CGRect)rect { [[UIColor blueColor] setFill]; [[self placeholder] drawInRect:rect withFont:[UIFont systemFontOfSize:16]]; } </code></pre>
454,202
Creating a textarea with auto-resize
<p>There was <a href="https://stackoverflow.com/questions/7477/autosizing-textarea">another thread about this</a>, which I've tried. But there is one problem: the <code>textarea</code> doesn't shrink if you delete the content. I can't find any way to shrink it to the correct size - the <code>clientHeight</code> value comes back as the full size of the <code>textarea</code>, not its contents.</p> <p>The code from that page is below:</p> <pre><code>function FitToContent(id, maxHeight) { var text = id &amp;&amp; id.style ? id : document.getElementById(id); if ( !text ) return; var adjustedHeight = text.clientHeight; if ( !maxHeight || maxHeight &gt; adjustedHeight ) { adjustedHeight = Math.max(text.scrollHeight, adjustedHeight); if ( maxHeight ) adjustedHeight = Math.min(maxHeight, adjustedHeight); if ( adjustedHeight &gt; text.clientHeight ) text.style.height = adjustedHeight + "px"; } } window.onload = function() { document.getElementById("ta").onkeyup = function() { FitToContent( this, 500 ) }; } </code></pre>
5,346,855
49
6
null
2009-01-17 22:30:42.113 UTC
208
2022-08-30 10:08:43.263 UTC
2018-03-24 14:42:11.143 UTC
null
3,215,948
DisgruntledGoat
37,947
null
1
465
javascript|html|resize|height|textarea
600,285
<p>This works for me (Firefox 3.6/4.0 and Chrome 10/11):</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var observe; if (window.attachEvent) { observe = function (element, event, handler) { element.attachEvent('on'+event, handler); }; } else { observe = function (element, event, handler) { element.addEventListener(event, handler, false); }; } function init () { var text = document.getElementById('text'); function resize () { text.style.height = 'auto'; text.style.height = text.scrollHeight+'px'; } /* 0-timeout to get the already changed text */ function delayedResize () { window.setTimeout(resize, 0); } observe(text, 'change', resize); observe(text, 'cut', delayedResize); observe(text, 'paste', delayedResize); observe(text, 'drop', delayedResize); observe(text, 'keydown', delayedResize); text.focus(); text.select(); resize(); }</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>textarea { border: 0 none white; overflow: hidden; padding: 0; outline: none; background-color: #D0D0D0; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;body onload="init();"&gt; &lt;textarea rows="1" style="height:1em;" id="text"&gt;&lt;/textarea&gt; &lt;/body&gt;</code></pre> </div> </div> </p> <p><em>If you want try it on <a href="http://jsfiddle.net/hmelenok/WM6Gq/">jsfiddle</a></em> It starts with a single line and grows only the exact amount necessary. It is ok for a single <code>textarea</code>, but I wanted to write something where I would have many many many such <code>textarea</code>s (about as much as one would normally have lines in a large text document). In that case it is really slow. (In Firefox it's insanely slow.) So I really would like an approach that uses pure CSS. This would be possible with <code>contenteditable</code>, but I want it to be plaintext-only.</p>
6,334,537
Rails where() clause on model association?
<p>Suppose I have an Account model which has_many Users. Accounts have a boolean "active" column. How can I get all Users that belong to "active" accounts?</p> <pre><code>@users_of_active_accounts = User.? </code></pre> <p>Thanks!</p>
6,334,716
5
1
null
2011-06-13 18:24:34.517 UTC
19
2020-03-14 17:54:41.013 UTC
null
null
null
null
461,218
null
1
52
ruby-on-rails
40,874
<p>You need to join the accounts table and merge appropriate Account scope:</p> <pre><code>User.joins(:account).merge(Account.where(:active =&gt; true)) </code></pre>
6,325,018
Android activity as dialog, but without a title bar
<p>I have an activity that has the following set as theme:</p> <pre><code>android:theme="@android:style/Theme.Dialog" </code></pre> <p>However, there is a title bar in the activity-dialog that appears, that uses up the little available space that I have. How can I remove it?</p>
6,325,045
9
1
null
2011-06-12 22:08:26.89 UTC
10
2022-01-31 15:37:21.383 UTC
null
null
null
null
361,230
null
1
77
android|webview|titlebar
47,913
<p>Try doing <code>requestWindowFeature(Window.FEATURE_NO_TITLE);</code> in <code>onCreate</code>. It'll need to be done immediately after calling <code>super.onCreate</code> and just before <code>setContentView</code>.</p>
45,323,271
How To Run Selenium With Chrome In Docker
<p>I installed google-chrome in a <a href="https://www.docker.com/" rel="noreferrer">Docker</a>, but when I run my <a href="https://www.python.org/downloads/release/python-272/" rel="noreferrer">Python 2</a> script of <a href="https://www.seleniumhq.org/download/" rel="noreferrer">Selenium</a>, it failed like this:</p> <pre><code>automation@1c17781fef0c:/topology-editor/test$ python test.py Traceback (most recent call last): File "test.py", line 27, in &lt;module&gt; browser = webdriver.Chrome() File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/chrome/webdriver.py", line 69, in __init__ desired_capabilities=desired_capabilities) File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 98, in __init__ self.start_session(desired_capabilities, browser_profile) File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 185, in start_session response = self.execute(Command.NEW_SESSION, parameters) File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 249, in execute self.error_handler.check_response(response) File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/errorhandler.py", line 194, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.WebDriverException: Message: unknown error: Chrome failed to start: crashed (Driver info: chromedriver=2.31.488763 (092de99f48a300323ecf8c2a4e2e7cab51de5ba8),platform=Linux 4.4.0-83-generic x86_64) </code></pre> <p>And if I run google-chrome directly in docker, it shows below:</p> <pre><code>automation@1c17781fef0c:/topology-editor/test$ google-chrome Failed to move to new namespace: PID namespaces supported, Network namespace supported, but failed: errno = Operation not permitted Trace/breakpoint trap (core dumped) automation@1c17781fef0c:/topology-editor/test$ </code></pre> <p>System: </p> <pre><code>$ uname -a Linux 1c17781fef0c 4.4.0-83-generic #106-Ubuntu SMP Mon Jun 26 17:54:43 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux $ google-chrome --version Google Chrome 60.0.3112.78 $ chromedriver --version ChromeDriver 2.31.488763 (092de99f48a300323ecf8c2a4e2e7cab51de5ba8) </code></pre>
45,324,730
4
3
null
2017-07-26 09:45:45.037 UTC
25
2022-01-15 20:33:16.843 UTC
2019-09-05 11:45:37.49 UTC
null
11,705,601
null
7,314,559
null
1
45
python|python-2.7|selenium|docker|google-chrome
87,704
<p>You need to launch a standalone chrome browser</p> <pre><code>docker run -d -p 4444:4444 selenium/standalone-chrome </code></pre> <p>and then in your python script launch browser using Remote webdriver</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.desired_capabilities import DesiredCapabilities driver = webdriver.Remote(&quot;http://127.0.0.1:4444/wd/hub&quot;, DesiredCapabilities.CHROME) </code></pre> <p>If you want you can also launch a Selenium Grid hub.</p> <p>To do this as a django test do the following:</p> <pre><code># docker-compse.yml selenium: image: selenium/standalone-firefox ports: - 4444:4444 # project/app/test.py from django.test import TestCase from selenium import webdriver from selenium.webdriver.common.desired_capabilities import DesiredCapabilities class SiteTest(TestCase): fixtures = [ 'app/fixtures/app.json', ... ] def setUp(self): self.browser = webdriver.Remote(&quot;http://selenium:4444/wd/hub&quot;, DesiredCapabilities.FIREFOX) def tearDown(self): self.browser.quit() def test_visit_site(self): self.browser.get('http://app:8000/') self.assertIn(self.browser.title, 'Home') </code></pre> <p><strong>Note:</strong></p> <p>If you use <code>webdriver.ChromeOptions|FirefoxOptions|etc</code> then <code>DesiredCapabalities</code> import is not necessary:</p> <pre><code>from selenium import webdriver options = webdriver.ChromeOptions() options.add_argument('--headless') # example driver = webdriver.Remote(&quot;http://127.0.0.1:4444/wd/hub&quot;, options=options) </code></pre>
15,657,812
Modify a column to NULL - Oracle
<p>I have a table named <code>CUSTOMER</code>, with few columns. One of them is <code>Customer_ID</code>.</p> <p>Initially <code>Customer_ID</code> column <code>WILL NOT</code> accept <code>NULL</code> values.</p> <p>I've made some changes from code level, so that <code>Customer_ID</code> column will accept <code>NULL</code> values by default.</p> <p>Now my requirement is that, I need to again make this column to accept <code>NULL</code> values.</p> <p>For this I've added executing the below query:</p> <pre><code>ALTER TABLE Customer MODIFY Customer_ID nvarchar2(20) NULL </code></pre> <p>I'm getting the following error:</p> <pre><code>ORA-01451 error, the column already allows null entries so therefore cannot be modified </code></pre> <p>This is because already I've made the <code>Customer_ID</code> column to accept <code>NULL</code> values.</p> <p>Is there a way to check if the column will accept <code>NULL</code> values before executing the above query...??</p>
15,657,994
5
1
null
2013-03-27 11:33:34.933 UTC
1
2021-03-25 11:10:06.11 UTC
null
null
null
null
2,147,481
null
1
12
oracle11g
93,836
<p>You can use the column NULLABLE in <a href="http://docs.oracle.com/cd/E11882_01/server.112/e25513/statviews_2103.htm#REFRN20277" rel="noreferrer">USER_TAB_COLUMNS</a>. This tells you whether the column allows nulls using a binary Y/N flag.</p> <p>If you wanted to put this in a script you could do something like:</p> <pre><code>declare l_null user_tab_columns.nullable%type; begin select nullable into l_null from user_tab_columns where table_name = 'CUSTOMER' and column_name = 'CUSTOMER_ID'; if l_null = 'N' then execute immediate 'ALTER TABLE Customer MODIFY (Customer_ID nvarchar2(20) NULL)'; end if; end; </code></pre> <p>It's best <em>not</em> to use dynamic SQL in order to alter tables. Do it manually and be sure to double check everything first.</p>
15,706,077
PHP Convert Windows-1251 to UTF 8
<p>I have a small html code and I need to convert it to UTF-8.<br /> I use this <code>iconv("windows-1251", "utf-8", $html);</code></p> <p>All text converts correctly, but if text for example in tag <code>&lt;i&gt;...&lt;/i&gt;</code>, then it don't convert text and I see somethig like this <code>Показать мн</code></p>
15,706,337
5
1
null
2013-03-29 15:16:38.633 UTC
2
2020-11-20 18:53:49.653 UTC
2015-05-29 00:18:04.723 UTC
null
772,521
null
2,058,653
null
1
13
php|utf-8|character-encoding|windows-1251
77,927
<p>If you have access to the Multibye package, you can try it. See the PHP page here: <a href="http://www.php.net/manual/en/function.mb-convert-encoding.php" rel="noreferrer">http://www.php.net/manual/en/function.mb-convert-encoding.php</a></p> <pre><code>$html_utf8 = mb_convert_encoding($html, "utf-8", "windows-1251"); </code></pre>
15,651,084
Error with ggplot2 mapping variable to y and using stat="bin"
<p>I am using ggplot2 to make a histogram:</p> <pre><code>geom_histogram(aes(x=...), y="..ncount../sum(..ncount..)") </code></pre> <p>and I get the error:</p> <pre><code>Mapping a variable to y and also using stat="bin". With stat="bin", it will attempt to set the y value to the count of cases in each group. This can result in unexpected behavior and will not be allowed in a future version of ggplot2. If you want y to represent counts of cases, use stat="bin" and don't map a variable to y. If you want y to represent values in the data, use stat="identity". See ?geom_bar for examples. (Deprecated; last used in version 0.9.2) </code></pre> <p>What causes this in general? I am confused about the error because I'm not mapping a variable to <code>y</code>, just histogram-ing <code>x</code> and would like the height of the histogram bar to represent a normalized fraction of the data (such that all the bar heights together sum to 100% of the data.)</p> <p><em>edit</em>: if I want to make a density plot <code>geom_density</code> instead of <code>geom_histogram</code>, do I use <code>..ncount../sum(..ncount..)</code> or <code>..scaled..</code>? I'm unclear about what <code>..scaled..</code> does.</p>
15,651,541
2
5
null
2013-03-27 02:44:41.543 UTC
8
2017-09-06 03:41:55.737 UTC
2016-04-08 18:40:22.217 UTC
null
881,229
user248237
null
null
1
16
r|ggplot2
16,480
<p>The confusion here is a long standing one (as evidenced by the verbose warning message) that all starts with <code>stat_bin</code>.</p> <p>But users don't typically realize that their confusion revolves around <code>stat_bin</code>, since they typically encounter problems while using either <code>geom_bar</code> or <code>geom_histogram</code>. Note the documentation for each: they both use <code>stat = "bin"</code> (in current <strong>ggplot2</strong> versions this stat has been split into <code>stat_bin</code> for continuous data and <code>stat_count</code> for discrete data) by default.</p> <p>But let's back up. <code>geom_*</code>'s control the actual rendering of data into some sort of geometric form. <code>stat_*</code>'s simply transform your data. The distinction is a bit confusing in practice, because adding a layer of <code>stat_bin</code> will, by default, invoke <code>geom_bar</code> and so it can seem indistinguishable from <code>geom_bar</code> when you're learning.</p> <p>In any case, consider the "bar"-like geom's: histograms and bar charts. Both are clearly going to involve some binning of data somewhere along the line. But our data could either be pre-summarised or not. For instance, we might want a bar plot from:</p> <pre><code>x a a a b b b </code></pre> <p>or equivalently from</p> <pre><code>x y a 3 b 3 </code></pre> <p>The first hasn't been binned yet. The second is pre-binned. The default behavior for both <code>geom_bar</code> and <code>geom_histogram</code> is to assume that you have <em>not</em> pre-binned your data. So they will attempt to call <code>stat_bin</code> (for histograms, now <code>stat_count</code> for bar charts) on your <code>x</code> values.</p> <p>As the warning says, it will then try to map <code>y</code> for you to the resulting counts. If you <em>also</em> attempt to map <code>y</code> yourself to some other variable you end up in Here There Be Dragons territory. Mapping <code>y</code> to functions of the variables returned by <code>stat_bin</code> (<code>..count..</code>, etc.) should be ok and should not throw that warning (it doesn't for me using @mnel's example above).</p> <p>The take-away here is that for <code>geom_bar</code> if you've pre-computed the heights of the bars, always remember to use <code>stat = "identity"</code>, or better yet use the newer <code>geom_col</code> which uses <code>stat = "identity"</code> by default. For <code>geom_histogram</code> it's very unlikely that you will have pre-computed the bins, so in most cases you just need to remember not to map <code>y</code> to anything beyond what's returned from <code>stat_bin</code>. </p> <p><code>geom_dotplot</code> uses it's own binning stat, <code>stat_bindot</code>, and this discussion applies here as well, I believe. This sort of thing generally hasn't been an issue with the 2d binning cases (<code>geom_bin2d</code> and <code>geom_hex</code>) since there hasn't been as much flexibility available in the analogous <code>z</code> variable to the binned <code>y</code> variable in the 1d case. If future updates start allowing more fancy manipulations of the 2d binning cases this could I suppose become something you have to watch out for there.</p>
15,519,716
How can I resize an image file uploaded with Django using an ImageField Model?
<p>What is the most straightforward method to resize an image file uploaded via a Django form as an <code>ImageField</code>? </p>
15,523,422
2
5
null
2013-03-20 09:30:52.34 UTC
8
2018-09-19 01:23:02.37 UTC
2018-09-19 01:23:02.37 UTC
null
1,305,947
null
853,488
null
1
24
django|image|upload|resize|photo
35,675
<p>I was annoyed that I couldn't find a complete working example, only bits here and there. I managed to put the solution together myself. Here is the complete example, I put it in clean() method of the form (you can also override models save() method, in the completely same way - changing ImageField's file property).</p> <pre><code>import StringIO from PIL import Image image_field = self.cleaned_data.get('image_field') image_file = StringIO.StringIO(image_field.read()) image = Image.open(image_file) w, h = image.size image = image.resize((w/2, h/2), Image.ANTIALIAS) image_file = StringIO.StringIO() image.save(image_file, 'JPEG', quality=90) image_field.file = image_file </code></pre>
15,691,942
Print array elements on separate lines in Bash?
<p>How do I print the array element of a Bash array on separate lines? This one works, but surely there is a better way:</p> <pre><code>$ my_array=(one two three) $ for i in ${my_array[@]}; do echo $i; done one two three </code></pre> <p>Tried this one but it did not work:</p> <pre><code>$ IFS=$'\n' echo ${my_array[*]} one two three </code></pre>
15,692,004
7
1
null
2013-03-28 20:53:47.937 UTC
72
2021-02-07 14:35:20.033 UTC
2019-09-14 03:30:21.843 UTC
null
608,639
null
155,425
null
1
301
arrays|bash
435,408
<p>Try doing this :</p> <pre><code>$ printf '%s\n' "${my_array[@]}" </code></pre> <p>The difference between <code>$@</code> and <code>$*</code>:</p> <ul> <li><p>Unquoted, the results are unspecified. In Bash, both expand to separate args and then wordsplit and globbed.</p></li> <li><p>Quoted, <code>"$@"</code> expands each element as a separate argument, while <code>"$*"</code> expands to the args merged into one argument: <code>"$1c$2c..."</code> (where <code>c</code> is the first char of <code>IFS</code>).</p></li> </ul> <p>You almost always want <code>"$@"</code>. Same goes for <code>"${arr[@]}"</code>.</p> <p><strong>Always quote them!</strong></p>
16,023,451
Binding variables from Service/Factory to Controllers
<p>I have a variable that will be used by one or more Controllers, changed by Services. In that case, I've built a service that keeps this variable in memory, and share between the controllers.</p> <p>The problem is: Every time that the variable changes, the variables in the controllers aren't updated in real time. </p> <p>I create this Fiddle to help. <a href="http://jsfiddle.net/ncyVK/">http://jsfiddle.net/ncyVK/</a></p> <p>--- Note that the <code>{{countService}}</code> or <code>{{countFactory}}</code> is never updated when I increment the value of count.</p> <p>How can I bind the Service/Factory variable to $scope.variable in the Controller? What I'm doing wrong?</p>
16,025,241
2
0
null
2013-04-15 19:39:31.58 UTC
25
2016-04-06 17:29:31.76 UTC
2016-04-06 17:29:31.76 UTC
null
1,247,330
null
1,481,408
null
1
69
angularjs|angularjs-directive
95,733
<p>You can't bind variables. But you can bind variable accessors or objects which contain this variable. Here is fixed <a href="http://jsfiddle.net/xuUHS/1/">jsfiddle</a>.</p> <p>Basically you have to pass to the scope something, which can return/or holds current value. E.g.</p> <p>Factory:</p> <pre><code>app.factory('testFactory', function(){ var countF = 1; return { getCount : function () { return countF; //we need some way to access actual variable value }, incrementCount:function(){ countF++; return countF; } } }); </code></pre> <p>Controller:</p> <pre><code>function FactoryCtrl($scope, testService, testFactory) { $scope.countFactory = testFactory.getCount; //passing getter to the view $scope.clickF = function () { $scope.countF = testFactory.incrementCount(); }; } </code></pre> <p>View:</p> <pre><code>&lt;div ng-controller="FactoryCtrl"&gt; &lt;!-- this is now updated, note how count factory is called --&gt; &lt;p&gt; This is my countFactory variable : {{countFactory()}}&lt;/p&gt; &lt;p&gt; This is my updated after click variable : {{countF}}&lt;/p&gt; &lt;button ng-click="clickF()" &gt;Factory ++ &lt;/button&gt; &lt;/div&gt; </code></pre>
15,921,458
How to kill/stop a long SQL query immediately?
<p>I am using SQL server 2008 and its management studio. I executed a query that yields many rows. I tried to cancel it via the red cancel button, but it has not stopped for the past 10 minutes. It usually stops within 3 minutes. </p> <p>What could the reason be and how do I stop it immediately ?</p>
15,921,769
12
4
null
2013-04-10 09:03:39.067 UTC
35
2021-06-10 15:40:38.36 UTC
null
null
null
null
1,971,910
null
1
122
sql|sql-server|sql-server-2008
439,707
<blockquote> <p>What could the reason be</p> </blockquote> <p>A query cancel is immediate, provided that your <a href="http://msdn.microsoft.com/en-us/library/dd341449.aspx" rel="noreferrer">attention</a> can reach the server and be processed. A query must be in a cancelable state, which is almost always true except if you do certain operations like calling a web service from SQLCLR. If your attention cannot reach the server it's usually due to <a href="http://msdn.microsoft.com/en-us/library/ms177526.aspx" rel="noreferrer">scheduler</a> overload.</p> <p>But if your query is part of a transaction that must rollback, then rollback cannot be interrupted. If it takes 10 minutes then it needs 10 minutes and there's nothing you can do about it. Even restarting the server will not help, it will only make startup longer since recovery must finish the rollback.</p> <p>To answer <em>which</em> specific reason applies to your case, you'll need to investigate yourself.</p>
15,636,367
NodeJS require a global module/package
<p>I'm trying to install globally and then use <code>forever</code> and <code>forever-monitor</code> like this:</p> <p><code>npm install -g forever forever-monitor</code></p> <p>I see the usual output and also the operations that copy the files to the global path, but then if I try to <code>require("forever");</code> I get an error saying that the module wasn't found.</p> <p>I'm using latest version of both node and npm and I already know about the change that npm made in global vs local install, but I <strong>really don't want</strong> to install localy on every project and I'm working on a platform that doesn't support <code>link</code> so <code>npm link</code> after a global install isn't possible for me.</p> <p>My question is: why I can't require a globally installed package? Is that a feature or a bug? Or am I doing something wrong?</p> <p>PS: Just to make it crystal clear: I don't want to install locally.</p>
15,646,750
9
3
null
2013-03-26 11:49:07.18 UTC
67
2020-12-25 23:13:56.837 UTC
null
null
null
null
940,158
null
1
211
node.js|package|npm
109,100
<p>In Node.js, require doesn't look in the folder where global modules are installed.</p> <p>You can fix this by setting the NODE_PATH environment variable. In Linux this will be:</p> <pre><code>export NODE_PATH=/usr/lib/node_modules </code></pre> <p><sup>Note: This depend on where your global modules are actually installed.</sup></p> <p>See: <a href="https://nodejs.org/api/modules.html#modules_loading_from_the_global_folders" rel="noreferrer">Loading from the global folders</a>.</p>
32,896,140
Using a variable with the same name in different spaces
<p>This code compiles, but I have a run time error in <a href="http://en.wikipedia.org/wiki/Microsoft_Visual_Studio" rel="noreferrer">Visual Studio</a>:</p> <blockquote> <p>Run-time check failure #3 - the variable 'x' is being used without being initialized...</p> </blockquote> <pre><code>int x = 15; int main() { int x = x; return 0; } </code></pre> <p>I don't understand that behavior... in the error box when I click continue the program resumes and x has a corrupted content (like <code>-8556328</code> instead of <code>15</code>).</p> <p>Why does this code work without a problem, and the int array is well declared?</p> <pre><code>const int x = 5; int main() { int x[x] = {1,2,3,4}; return 0; } </code></pre>
32,896,213
4
8
null
2015-10-01 20:16:50.86 UTC
null
2015-10-06 11:53:13.103 UTC
2015-10-02 07:35:36.65 UTC
null
2,684,539
null
2,947,765
null
1
41
c++|c|variable-declaration
1,769
<p><code>x</code> is defined at the left of <code>=</code>.</p> <p>so in <code>x[x]</code>, <code>[x]</code> refer to the global one,</p> <p>whereas in <code>x = x;</code>, <code>x</code> hides the global <code>x</code> and initializes from itself -> UB.</p>
50,593,516
Colored pixels in scrollbar in VS Code
<p>I've recently started using VS Code, and I've noticed that there are little colored pixels that show up in the scroll bar like this:</p> <p><a href="https://i.stack.imgur.com/WFvqI.png" rel="noreferrer"><img src="https://i.stack.imgur.com/WFvqI.png" alt="enter image description here"></a></p> <p>They seem to indicate something about the source code, but I haven't been able to find the documentation for this. So my questions are as follows:</p> <ul> <li>What is the name of this feature?</li> <li>Where is it documented?</li> <li>Can this feature be disabled, and if so, how?</li> </ul> <p>EDIT:</p> <ul> <li>After reading <strong>@idleberg</strong>'s answer, I set <code>scm.diffDecorations</code> to <code>"none"</code> and restarted VS Code, reopened files, etc, but the decorations still persist.</li> <li>I followed the link in <strong>@Moffen</strong>'s answer and I set <code>"editor.hideCursorInOverviewRuler"</code> to <code>true</code>, but it turns out that controls a different feature. Also, I already had <code>"editor.minimap.enabled"</code> set to <code>false</code>, but the minimap is a different feature from the scrollbar decorations.</li> <li>I'm running Version 1.23.1 of VS Code on Ubuntu 18.04.</li> </ul>
51,684,408
3
4
null
2018-05-29 21:53:29.44 UTC
11
2020-08-26 15:36:44.193 UTC
2018-05-30 00:20:51.943 UTC
null
4,092,216
null
4,092,216
null
1
26
visual-studio-code
9,548
<p>The feature is called <strong>Overview Ruler</strong>. I've been unable to find specific documentation except some <a href="https://code.visualstudio.com/docs/editor/editingevolved#_errors-warnings" rel="noreferrer">sparse notes</a>:</p> <blockquote> <p>If you open a file that has errors or warnings, they will be rendered inline with the text and in the overview ruler.</p> </blockquote> <p>Related settings include:</p> <pre><code>// Controls if the cursor should be hidden in the overview ruler. "editor.hideCursorInOverviewRuler": false, // Controls if a border should be drawn around the overview ruler. "editor.overviewRulerBorder": true, // Controls the number of decorations that can show up at the same position in the overview ruler "editor.overviewRulerLanes": 3 </code></pre> <p>&hellip; but also some <a href="https://code.visualstudio.com/docs/getstarted/theme-color-reference#_editor-colors" rel="noreferrer">configurable colours</a>, which is the most thorough explanation I've found:</p> <blockquote> <h2>Overview ruler</h2> <p>This ruler is located beneath the scroll bar on the right edge of the editor and gives an overview of the decorations in the editor.</p> <ul> <li><code>editorOverviewRuler.border</code>: Color of the overview ruler border.</li> <li><code>editorOverviewRuler.findMatchForeground</code>: Overview ruler marker color for <strong>find matches</strong>. The color must not be opaque to not hide underlying decorations.</li> <li><code>editorOverviewRuler.rangeHighlightForeground</code>: Overview ruler marker color for <strong>highlighted ranges</strong>, like by the Quick Open, Symbol in File and Find features. The color must not be opaque to not hide underlying decorations.</li> <li><code>editorOverviewRuler.selectionHighlightForeground</code>: Overview ruler marker color for <strong>selection highlights</strong>. The color must not be opaque to not hide underlying decorations.</li> <li><code>editorOverviewRuler.wordHighlightForeground</code>: Overview ruler marker color for <strong>symbol highlights</strong>. The color must not be opaque to not hide underlying decorations.</li> <li><code>editorOverviewRuler.wordHighlightStrongForeground</code>: Overview ruler marker color for <strong>write-access symbol highlights</strong>. The color must not be opaque to not hide underlying decorations.</li> <li><code>editorOverviewRuler.modifiedForeground</code>: Overview ruler marker color for <strong>modified content</strong>.</li> <li><code>editorOverviewRuler.addedForeground</code>: Overview ruler marker color for <strong>added content</strong>.</li> <li><code>editorOverviewRuler.deletedForeground</code>: Overview ruler marker color for <strong>deleted content</strong>.</li> <li><code>editorOverviewRuler.errorForeground</code>: Overview ruler marker color for <strong>errors</strong>.</li> <li><code>editorOverviewRuler.warningForeground</code>: Overview ruler marker color for <strong>warnings</strong>.</li> <li><code>editorOverviewRuler.infoForeground</code>: Overview ruler marker color for <strong>infos</strong>.</li> <li><code>editorOverviewRuler.bracketMatchForeground</code>: Overview ruler marker color for <strong>matching brackets</strong>.</li> </ul> </blockquote>
10,631,473
'str' object does not support item assignment
<p>I would like to read some characters from a string <code>s1</code> and put it into another string <code>s2</code>.</p> <p>However, assigning to <code>s2[j]</code> gives an error:</p> <pre class="lang-py prettyprint-override"><code>s2[j] = s1[i] # TypeError: 'str' object does not support item assignment </code></pre> <hr /> <p>In C, this works:</p> <pre class="lang-cpp prettyprint-override"><code>int i = j = 0; while (s1[i] != '\0') s2[j++] = s1[i++]; </code></pre> <p>My attempt in Python:</p> <pre class="lang-py prettyprint-override"><code>s1 = &quot;Hello World&quot; s2 = &quot;&quot; j = 0 for i in range(len(s1)): s2[j] = s1[i] j = j + 1 </code></pre>
10,631,478
10
3
null
2012-05-17 07:18:41.07 UTC
34
2022-05-13 22:50:00.573 UTC
2021-08-19 00:27:34.393 UTC
null
365,102
null
1,105,805
null
1
213
python|string
591,488
<p>In Python, strings are immutable, so you can't change their characters in-place.</p> <p>You can, however, do the following:</p> <pre><code>for c in s1: s2 += c </code></pre> <p>The reasons this works is that it's a shortcut for:</p> <pre><code>for c in s1: s2 = s2 + c </code></pre> <p>The above <em>creates a new string</em> with each iteration, and stores the reference to that new string in <code>s2</code>.</p>
10,459,917
traversing through JSON string to inner levels using recursive function
<p>I have a JSON input which can go to any number of levels.</p> <p>I'm giving an input sample of </p> <pre class="lang-js prettyprint-override"><code>var d=getEntities( {"Categories": { "Facets": [ { "count": 1, "entity": "Company", "Company": [ { "entity": "Ford Motor Co", "Ford_Motor_Co": [ { "count": 1, "entity": "Ford" } ] } ] }, { "count": 4, "entity": "Country", "Country": [ { "entity": "Germany", "Germany": [ { "count": 1, "entity": "Germany" } ], "currency": "Euro (EUR)" }, { "entity": "Italy", "Italy": [ { "count": 1, "entity": "Italy" } ], "currency": "Euro (EUR)" }, { "entity": "Japan", "Japan": [ { "count": 1, "entity": "Japan" } ], "currency": "Yen (JPY)" }, { "entity": "South Korea", "South_Korea": [ { "count": 1, "entity": "South Korea" } ], "currency": "Won (KRW)" } ] }, {"count": 5, "entity": "Persons", "Persons": [ { "count": 2, "entity": "Dodge" }, { "count": 1, "entity": "Dodge Avenger" }, { "count": 1, "entity": "Major League" }, { "count": 1, "entity": "Sterling Heights" } ] } ] }}); </code></pre> <p>I want to add the key value "Entity" in all levels to an array using recursion, </p> <p>I'm able to collect the data from first level using the string </p> <pre class="lang-html prettyprint-override"><code>&lt;html&gt; &lt;head&gt; &lt;script src="jquery.js" type="text/javascript"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="dataDumper.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; var testJSON = {"Categories": { "Facets": [ { "count": 1, "entity": "Company", "Company": [ { "entity": "Ford Motor Co", "Ford_Motor_Co": [ { "count": 1, "entity": "Ford" } ] } ] }, { "count": 4, "entity": "Country", "Country": [ { "entity": "Germany", "Germany": [ { "count": 1, "entity": "Germany" } ], "currency": "Euro (EUR)" }, { "entity": "Italy", "Italy": [ { "count": 1, "entity": "Italy" } ], "currency": "Euro (EUR)" }, { "entity": "Japan", "Japan": [ { "count": 1, "entity": "Japan" } ], "currency": "Yen (JPY)" }, { "entity": "South Korea", "South_Korea": [ { "count": 1, "entity": "South Korea" } ], "currency": "Won (KRW)" } ] }, {"count": 5, "entity": "Persons", "Persons": [ { "count": 2, "entity": "Dodge" }, { "count": 1, "entity": "Dodge Avenger" }, { "count": 1, "entity": "Major League" }, { "count": 1, "entity": "Sterling Heights" } ] } ] }}; function scan(obj) { var k; if (obj.hasOwnProperty('entity')) { for (k in obj){ if (obj.hasOwnProperty(k)){ scan( obj[k] ); } } } else{ if(k=='entity') { alert(obj.entity); } } }; scan(testJSON); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>How do I get in to the inner levels for JSON string using recursive functions?</p>
10,460,119
5
6
null
2012-05-05 07:44:21.583 UTC
2
2020-10-30 00:34:19.743 UTC
2012-05-06 14:24:38.543 UTC
null
1,371,896
null
1,371,896
null
1
10
javascript|arrays|json|object
39,411
<p>I have made a <a href="http://jsfiddle.net/t4p9G/" rel="nofollow noreferrer">jsfiddle</a> which traverses every object,array and value in the JS object like so...</p> <pre><code>function scan(obj) { var k; if (obj instanceof Object) { for (k in obj){ if (obj.hasOwnProperty(k)){ //recursive call to scan property scan( obj[k] ); } } } else { //obj is not an instance of Object so obj here is a value }; }; </code></pre> <p>I get no recursion error (in Chrome). Can you use this to do what you want?</p> <p>If you need to test if an object is an array use <code>if (obj instanceof Array)</code></p> <p>To test if an object has an "entity" property use <code>if (obj.hasOwnProperty('entity'))</code></p> <p>To add (or modify an existing) "entity" property use <code>obj.entity = value</code> or <code>obj['entity'] = value</code></p>
32,027,935
".addEventListener is not a function" why does this error occur?
<p>I’m getting an ".addEventListener is not a function" error. I am stuck on this:</p> <pre><code>var comment = document.getElementsByClassName("button"); function showComment() { var place = document.getElementById('textfield'); var commentBox = document.createElement('textarea'); place.appendChild(commentBox); } comment.addEventListener('click', showComment, false); </code></pre> <pre><code>&lt;input type="button" class="button" value="1"&gt; &lt;input type="button" class="button" value="2"&gt; &lt;div id="textfield"&gt; &lt;/div&gt; </code></pre>
32,027,957
6
3
null
2015-08-15 18:28:24.953 UTC
29
2022-09-16 18:56:55.103 UTC
2017-12-22 13:12:59.83 UTC
null
2,311,559
null
5,207,616
null
1
83
javascript|html
365,765
<p>The problem with your code is that the your script is executed prior to the html element being available. Because of the that <code>var comment</code> is an empty array.</p> <p>So you should move your script after the html element is available. </p> <p>Also, <code>getElementsByClassName</code> returns html collection, so if you need to add event Listener to an element, you will need to do something like following</p> <pre><code>comment[0].addEventListener('click' , showComment , false ) ; </code></pre> <p>If you want to add event listener to all the elements, then you will need to loop through them</p> <pre><code>for (var i = 0 ; i &lt; comment.length; i++) { comment[i].addEventListener('click' , showComment , false ) ; } </code></pre>
22,492,162
Understanding the main method of python
<p>I am new to Python, but I have experience in other OOP languages. My course does not explain the main method in python. </p> <p>Please tell me how main method works in python ? I am confused because I am trying to compare it to Java. </p> <pre><code>def main(): # display some lines if __name__ == "__main__": main() </code></pre> <p>How is main executed and why do I need this strange <code>if</code> to execute <code>main</code>. My code is terminated without output when I remove the <code>if</code>.</p> <p>The minimal code - </p> <pre><code>class AnimalActions: def quack(self): return self.strings['quack'] def bark(self): return self.strings['bark'] class Duck(AnimalActions): strings = dict( quack = "Quaaaaak!", bark = "The duck cannot bark.", ) class Dog(AnimalActions): strings = dict( quack = "The dog cannot quack.", bark = "Arf!", ) def in_the_doghouse(dog): print(dog.bark()) def in_the_forest(duck): print(duck.quack()) def main(): donald = Duck() fido = Dog() print("- In the forest:") for o in ( donald, fido ): in_the_forest(o) print("- In the doghouse:") for o in ( donald, fido ): in_the_doghouse(o) if __name__ == "__main__": main() </code></pre>
22,493,194
4
4
null
2014-03-18 22:14:32.553 UTC
59
2019-04-25 17:28:15.527 UTC
2019-04-25 17:28:15.527 UTC
null
3,184,475
null
3,184,475
null
1
163
python|python-3.x
391,740
<p>The Python approach to "main" is almost unique to the language(*).</p> <p>The semantics are a bit subtle. The <code>__name__</code> identifier is bound to the name of any module as it's being imported. However, when a file is being executed then <code>__name__</code> is set to <code>"__main__"</code> (the literal string: <code>__main__</code>).</p> <p>This is almost always used to separate the portion of code which should be executed from the portions of code which define functionality. So Python code often contains a line like:</p> <pre><code>#!/usr/bin/env python from __future__ import print_function import this, that, other, stuff class SomeObject(object): pass def some_function(*args,**kwargs): pass if __name__ == '__main__': print("This only executes when %s is executed rather than imported" % __file__) </code></pre> <p>Using this convention one can have a file define classes and functions for use in other programs, and also include code to evaluate only when the file is called as a standalone script.</p> <p>It's important to understand that all of the code above the <code>if __name__</code> line is being executed, evaluated, in both cases. It's evaluated by the interpreter when the file is imported or when it's executed. If you put a <code>print</code> statement before the <code>if __name__</code> line then it will print output every time any other code attempts to import that as a module. (Of course, this would be <strong>anti-social</strong>. Don't do that).</p> <p>I, personally, like these semantics. It encourages programmers to separate functionality (definitions) from function (execution) and encourages re-use.</p> <p>Ideally almost every Python module can do something useful if called from the command line. In many cases this is used for managing unit tests. If a particular file defines functionality which is only useful in the context of other components of a system then one can still use <code>__name__ == "__main__"</code> to isolate a block of code which calls a suite of unit tests that apply to this module.</p> <p>(If you're not going to have any such functionality nor unit tests than it's best to ensure that the file mode is NOT executable).</p> <p>Summary: <code>if __name__ == '__main__':</code> has two primary use cases:</p> <ul> <li>Allow a module to provide functionality for import into other code while also providing useful semantics as a standalone script (a command line wrapper around the functionality)</li> <li>Allow a module to define a suite of unit tests which are stored with (in the same file as) the code to be tested and which can be executed independently of the rest of the codebase.</li> </ul> <p>It's fairly common to <code>def main(*args)</code> and have <code>if __name__ == '__main__':</code> simply call <code>main(*sys.argv[1:])</code> if you want to define main in a manner that's similar to some other programming languages. If your .py file is primarily intended to be used as a module in other code then you might <code>def test_module()</code> and calling <code>test_module()</code> in your <code>if __name__ == '__main__:'</code> suite.</p> <ul> <li>(Ruby also implements a similar feature <code>if __file__ == $0</code>).</li> </ul>
13,404,722
Retrieve analyzed tokens from ElasticSearch documents
<p>Trying to access the analyzed/tokenized text in my ElasticSearch documents.</p> <p>I know you can use the <a href="http://www.elasticsearch.org/guide/reference/api/admin-indices-analyze.html" rel="noreferrer">Analyze API</a> to analyze arbitrary text according your analysis modules. So I could copy and paste data from my documents into the Analyze API to see how it was tokenized. </p> <p>This seems unnecessarily time consuming, though. Is there any way to instruct ElasticSearch to returned the tokenized text in search results? I've looked through the docs and haven't found anything.</p>
13,407,266
3
1
null
2012-11-15 19:28:50.777 UTC
3
2021-04-25 15:48:12.767 UTC
2013-01-16 16:21:03.727 UTC
null
127,880
null
943,184
null
1
38
text|elasticsearch|tokenize
25,401
<p>Have a look at this other answer: <a href="https://stackoverflow.com/questions/13178550/elasticsearch-return-the-tokens-of-a-field/13182001#13182001">elasticsearch - Return the tokens of a field</a>. Unfortunately it requires to reanalyze on the fly the content of your field using the script provided.<br> It should be possible to write a plugin to expose this feature. The idea would be to add two endpoints to:</p> <ul> <li>allow to read the lucene TermsEnum like the solr <a href="http://wiki.apache.org/solr/TermsComponent" rel="noreferrer">TermsComponent</a> does, useful to make auto-suggestions too. Note that it wouldn't be per document, just every term on the index with term frequency and document frequency (potentially expensive with a lot of unique terms)</li> <li>allow to read the term vectors if enabled, like the solr <a href="http://wiki.apache.org/solr/TermVectorComponent" rel="noreferrer">TermVectorComponent</a> does. This would be per document but requires to store the term vectors (you can configure it in your mapping) and allows also to retrieve positions and offsets if enabled.</li> </ul>
13,243,766
How to define an empty generator function?
<p>A generator function can be defined by putting the <code>yield</code> keyword in the function’s body:</p> <pre class="lang-py prettyprint-override"><code>def gen(): for i in range(10): yield i </code></pre> <p>How to define an empty generator function?</p> <p>The following code doesn’t work, since Python cannot know that it is supposed to be a generator function instead of a normal function:</p> <pre class="lang-py prettyprint-override"><code>def empty(): pass </code></pre> <p>I could do something like this:</p> <pre class="lang-py prettyprint-override"><code>def empty(): if False: yield </code></pre> <p>But that would be very ugly. Is there a nicer way?</p>
13,243,870
10
0
null
2012-11-06 03:08:13.517 UTC
18
2022-04-30 20:08:31.96 UTC
2022-04-30 20:08:31.96 UTC
null
2,326,961
null
607,405
null
1
136
python|generator
53,536
<p>You can use <code>return</code> once in a generator; it stops iteration without yielding anything, and thus provides an explicit alternative to letting the function run out of scope. So use <code>yield</code> to turn the function into a generator, but precede it with <code>return</code> to terminate the generator before yielding anything.</p> <pre><code>&gt;&gt;&gt; def f(): ... return ... yield ... &gt;&gt;&gt; list(f()) [] </code></pre> <p>I'm not sure it's that much better than what you have -- it just replaces a no-op <code>if</code> statement with a no-op <code>yield</code> statement. But it is more idiomatic. Note that just using <code>yield</code> doesn't work.</p> <pre><code>&gt;&gt;&gt; def f(): ... yield ... &gt;&gt;&gt; list(f()) [None] </code></pre> <h3>Why not just use <code>iter(())</code>?</h3> <p>This question asks specifically about an empty <em>generator function</em>. For that reason, I take it to be a question about the internal consistency of Python's syntax, rather than a question about the best way to create an empty iterator in general.</p> <p>If question is actually about the best way to create an empty iterator, then you might agree with <a href="https://stackoverflow.com/a/26271684/577088">Zectbumo</a> about using <code>iter(())</code> instead. However, it's important to observe that <code>iter(())</code> doesn't return a function! It directly returns an empty iterable. Suppose you're working with an API that expects a callable that <em>returns</em> an iterable each time it's called, just like an ordinary generator function. You'll have to do something like this:</p> <pre><code>def empty(): return iter(()) </code></pre> <p>(Credit should go to <a href="https://stackoverflow.com/a/13243922/577088">Unutbu</a> for giving the first correct version of this answer.)</p> <p>Now, you may find the above clearer, but I can imagine situations in which it would be less clear. Consider this example of a long list of (contrived) generator function definitions:</p> <pre><code>def zeros(): while True: yield 0 def ones(): while True: yield 1 ... </code></pre> <p>At the end of that long list, I'd rather see something with a <code>yield</code> in it, like this:</p> <pre><code>def empty(): return yield </code></pre> <p>or, in Python 3.3 and above (as suggested by <a href="https://stackoverflow.com/a/13243920/577088">DSM</a>), this:</p> <pre><code>def empty(): yield from () </code></pre> <p>The presence of the <code>yield</code> keyword makes it clear at the briefest glance that this is just another generator function, exactly like all the others. It takes a bit more time to see that the <code>iter(())</code> version is doing the same thing.</p> <p>It's a subtle difference, but I honestly think the <code>yield</code>-based functions are more readable and maintainable.</p> <p>See also this great answer from <a href="https://stackoverflow.com/a/61496399/577088">user3840170</a> that uses <code>dis</code> to show another reason why this approach is preferable: it emits the fewest instructions when compiled.</p>
13,574,980
jQuery - replace all instances of a character in a string
<p>This does not work and I need it badly</p> <pre><code>$('some+multi+word+string').replace('+', ' ' ); </code></pre> <p>always gets</p> <pre><code>some multi+word+string </code></pre> <p>it's always replacing for the first instance only, but I need it to work for all + symbols.</p>
13,574,989
3
6
null
2012-11-26 23:30:33.74 UTC
28
2013-09-19 19:42:45.94 UTC
null
null
null
null
803,358
null
1
210
jquery|string|replace
539,764
<p>You need to use a regular expression, so that you can specify the global (g) flag:</p> <pre><code>var s = 'some+multi+word+string'.replace(/\+/g, ' '); </code></pre> <p>(I removed the <code>$()</code> around the string, as <code>replace</code> is not a jQuery method, so that won't work at all.)</p>
39,734,632
Can't bind to 'routerLink' since it isn't a known property of 'a'
<p>I'm updating one of our apps from rc4 to angular2.0.0 and I'm getting a template parse error at run time. Here is my view template:</p> <pre><code>&lt;div *ngFor="let widget of widgets" class="col-xs-3 quick-link"&gt; &lt;a [routerLink]="['/Tile', widget.WidgetRoute.Feature, widget.WidgetRoute.SubFeature]"&gt; &lt;div class="tile-icon"&gt; &lt;span [className]="widget.IconCssClass"&gt;&lt;/span&gt; &lt;span *ngIf="widget.BadgeNumber &gt; 0" class="badge"&gt;{{widget.BadgeNumber}}&lt;/span&gt; &lt;/div&gt; &lt;h4&gt;{{widget.Text}}&lt;/h4&gt; &lt;/a&gt; &lt;/div&gt; </code></pre> <p>And the error is on the routerlink. Here's the error:</p> <pre><code>Can't bind to 'routerLink' since it isn't a known property of 'a'. (" &lt;div *ngFor="let widget of widgets" class="col-xs-3 quick-link"&gt; &lt;a [ERROR -&gt;][routerLink]="['/Tile', widget.WidgetRoute.Feature, widget.WidgetRoute.SubFeature]"&gt; &lt;di"): LdrComponent@4:19 Can't bind to 'ngIf' since it isn't a known property of 'span'. ("tile-icon"&gt; &lt;span [className]="widget.IconCssClass"&gt;&lt;/span&gt; &lt;span [ERROR -&gt;]*ngIf="widget.BadgeNumber &gt; 0" class="badge"&gt;{{widget.BadgeNumber}}&lt;/span&gt; &lt;/div&gt; "): LdrComponent@7:22 </code></pre> <p>The routerLink doesn't seem malformed to me... What did I do wrong?</p>
39,735,050
2
2
null
2016-09-27 21:31:43.04 UTC
1
2016-09-27 22:14:04.737 UTC
2016-09-27 21:48:53.18 UTC
null
491,436
null
491,436
null
1
25
angular|angular2-routing
45,054
<p>The problem is that you forgot to add <code>RouterModule</code> to your <code>NgModule</code> component. In the RC this was added to the <code>@Component({directives: [ROUTER_DIRECTIVES]})</code>, however, this is now moved into <code>@NgModule({ imports: [RouterModule]})</code>.</p> <p>When you define your routes, one of the components that you will import will be the <code>RouterModule</code> that you will use to call <code>forRoot</code> or <code>forChild</code>. When you import the route, this will be imported automatically. </p> <p>So, you will get the RouterLink either this way, or via direct import into <code>imports</code> property of <code>@NgModule</code>.</p>
24,293,376
JavaScript : For loop with timeout
<p>I want that my for loop should not be executed at once, but wait for timeout after each iteration. For eg : </p> <pre><code>for(var i=0; i&lt;10; i++) { console.log(i); //wait for 1000 } </code></pre> <p>I found many solutions on stack-overflow like this one : </p> <pre><code>for (var i=0;i&lt;=10;i++) { (function(ind) { setTimeout(function(){console.log(ind);}, 3000); })(i); } </code></pre> <p>But in all the implementations, the loop waits for 3000 milli-seconds initially and then executes the whole <code>for</code> loop at once. Is there a way that each iteration is called after waiting for 1000 milli-seconds.</p>
24,293,516
14
2
null
2014-06-18 19:12:56.517 UTC
14
2022-05-12 14:43:40 UTC
2018-12-19 07:14:37.17 UTC
null
2,319,858
null
2,319,858
null
1
26
javascript|settimeout
63,627
<p>You can work that out with simple math :</p> <pre><code>for (var i=0;i&lt;=10;i++) { (function(ind) { setTimeout(function(){console.log(ind);}, 1000 + (3000 * ind)); })(i); } </code></pre> <blockquote> <p>1000ms : 0 <br/> 4000ms : 1 <br /> 7000ms : 2 <br/> 10000ms : 3 <br/> 13000ms : 4 <br/> ...</p> </blockquote> <hr /> <h1>Following the comments</h1> <p>It seem that your request is a bit blurry. if you want to do something after the last timeout, you can set a limit and compare the current index :</p> <pre><code>var limit = 10 for (var i=0;i&lt;=limit;i++) { (function(ind) { setTimeout(function(){ console.log(ind); if(ind === limit){ console.log('It was the last one'); } }, 1000 + (3000 * ind)); })(i); } </code></pre> <p>Fiddle : <a href="http://jsfiddle.net/Tn4A7/" rel="noreferrer">http://jsfiddle.net/Tn4A7/</a></p> <hr /> <h1>I think I know what you want...</h1> <p>and it is to simply do</p> <pre><code>for (var i=0;i&lt;=10;i++) { (function(ind) { setTimeout(function(){console.log(ind);}, 1000 * ind); })(i); } </code></pre>
29,732,377
How to disable adding ".self." in Sprockets 3.0
<p>Even if <code>config.assets.digest = false</code> is set Sprockets 3.0 keep adding <code>.self.</code> to all static files: <code>application.css</code> becomes <code>application.self.css?body=1</code></p> <p>How to disable adding <code>self</code>? It is needed for correct browsersync work.</p>
32,898,659
2
5
null
2015-04-19 16:14:28.313 UTC
7
2015-10-02 00:07:23.887 UTC
2015-04-26 12:12:52.953 UTC
null
297,939
null
297,939
null
1
37
ruby-on-rails-4|sprockets
3,093
<p>In Sprockets 3, <code>.self.css</code> is added because you have the <code>config.assets.debug = true</code> config set (not the digest config, that's unrelated).</p> <p>If you add the following to your <code>development.rb</code> or <code>production.rb</code> file, it will work as you expect:</p> <pre><code>config.assets.debug = false </code></pre>
16,099,752
Session or cookie confusion
<p>I've seen in some websites that user signed in into their accounts and then closed the browser.</p> <p>After closed and re-opened the browser and their accounts are still signed in.</p> <p>But some websites, cannot do like that.</p> <p>I'm confused that it's considered session or cookie?</p> <p>If I want my website to be signed in like that, do I have to set <code>session.setMaxInactiveInterval()</code> or <code>cookie.setMaxAge()</code>?</p>
16,107,272
2
3
null
2013-04-19 07:44:16.523 UTC
26
2018-10-09 13:20:49.517 UTC
2013-04-19 15:06:42.803 UTC
null
157,882
null
1,735,186
null
1
19
session|servlets|cookies
49,095
<p><strong>* This answer has serious flaws, see comments. *</strong></p> <hr> <p>Your question is about <em>session tracking</em>.</p> <p><strong>[PART 1] : SESSION OBJECT</strong></p> <p>HTTP-request are processed separately, so in order to keep information between each request (for instance, information about the user), a <em>session object</em> has to be created on server-side.</p> <p>Some websites doesn't need a session at all. A website where users can't modify any content won't have to manage a session (for instance, an online CV). You won't need any cookie or session on such a website.</p> <p><strong><em>Create a session :</em></strong></p> <p>In a servlet, use the method <code>request.getSession(true)</code> from the HttpServletRequest object to create a new HttpSession object. Note that if you use <code>request.getSession(false)</code>, <em>null</em> will be returned if the session has not already been created. <a href="https://stackoverflow.com/questions/595872/under-what-conditions-is-a-jsessionid-created">Look at this answer for more details</a>.</p> <p><strong><em>Set / Get attributes :</em></strong></p> <p>The purpose of a session is to keep information on server-side between each request. For instance, keeping the user's name :</p> <pre class="lang-java prettyprint-override"><code>session.setAttribute("name","MAGLEFF"); // Cast String name = (String) session.getAttribute("name"); </code></pre> <p><strong><em>Destroy a session :</em></strong></p> <p>A session will be automatically destroyed if kept inactive too much time. <a href="https://stackoverflow.com/questions/10893727/how-to-properly-logout-of-a-java-ee-6-web-application-after-logging-in">Look at this answer for more details</a>. But you can manually force the session to be destroyed, in the case of a logout action for example :</p> <pre class="lang-java prettyprint-override"><code>HttpSession session = request.getSession(true); session.invalidate(); </code></pre> <p><strong>[PART 2] : So... join the dark side, we have COOKIES ?</strong></p> <p>Here comes the cookies.</p> <p><strong><em>JSESSIONID :</em></strong></p> <p>A <em>JSESSIONID cookie</em> is created on the user's computer each time a session is created with <code>request.getSession()</code>. Why? Because each session created on server side has an ID. You can't access another user's session, unless you don't have the right ID. This ID is kept in JSESSIONID cookie, and allow the user to find his information. <a href="https://stackoverflow.com/questions/10570043/where-is-jsessionid-stored-javaee">Look at this answer for more details </a>!</p> <p><strong><em>When does a JSESSIONID get deleted ?</em></strong></p> <p>JSESSIONID doesn't have an expiration date : it's a <em>session cookie</em>. As all session cookies, it will be deleted when the browser is closed. If you use the basic JSESSIONID mechanism, then the session will become unreachable after you close and re-open the browser, because the JSESSIONID cookie is deleted.</p> <p>Note that the session is unreachable by the client, but is still running on server-side. Setting a <em>MaxInactiveInterval</em> allows the server to automatically invalidate the session when it has been inactive for too long.</p> <p><strong><em>Evil destruction of JSESSIONID</em></strong></p> <p>Just for fun, one day I found this code on a project. It was used to invalidate the session by deleting the JSESSIONID cookie with javascript :</p> <pre class="lang-javascript prettyprint-override"><code>&lt;SCRIPT language="JavaScript" type="text/javascript"&gt; function delete_cookie( check_name ) { // first we'll split this cookie up into name/value pairs // note: document.cookie only returns name=value, not the other components var a_all_cookies = document.cookie.split( ';' ); var a_temp_cookie = ''; var cookie_name = ''; var cookie_value = ''; var b_cookie_found = false; // set boolean t/f default f // var check_name = 'JSESSIONID'; var path = null; for ( i = 0; i &lt; a_all_cookies.length; i++ ) { // now we'll split apart each name=value pair a_temp_cookie = a_all_cookies[i].split( '=' ); // and trim left/right whitespace while we're at it cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, ''); // alert (cookie_name); // if the extracted name matches passed check_name if ( cookie_name.indexOf(check_name) &gt; -1 ) { b_cookie_found = true; // we need to handle case where cookie has no value but exists (no = sign, that is): if ( a_temp_cookie.length &gt; 1 ) { cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') ); document.cookie = cookie_name + "=" + cookie_value + ";path=/" + ";expires=Thu, 01-Jan-1970 00:00:01 GMT"; // alert("cookie deleted " + cookie_name); } } a_temp_cookie = null; cookie_name = ''; } return true; } // DESTROY delete_cookie("JSESSIONID"); &lt;/SCRIPT&gt; </code></pre> <p><a href="https://stackoverflow.com/questions/10570043/where-is-jsessionid-stored-javaee">Give another look to this answer</a>. With JavaScript, JSESSIONID can be read, modified, have it's session lost or hijacked.</p> <p><strong>[PART 3] : KEEPING A SESSION AFTER CLOSING YOUR BROWSER</strong></p> <blockquote> <p>After closed and re-opened the browser and their accounts are still signed in. But some websites, cannot do like that. I'm confused that it's considered session or cookie??</p> </blockquote> <p>It's cookie.</p> <p>We saw that when the JSESSIONID session cookie has been deleted by the web browser, the session object on server-side is lost. There is no way to access it again without the right ID.</p> <blockquote> <p>If I want my website to be signed in like that, do I have to set session.setMaxInactiveInterval() or cookie.setMaxAge()?</p> </blockquote> <p>We also saw that <code>session.setMaxInactiveInterval()</code> was to prevent from running a lost session indefinitely. JSESSIONID cookie <code>cookie.setMaxAge()</code> won't get us anywhere either.</p> <p><strong>Use a persistent cookie with the session Id :</strong></p> <p>I came to this solution after reading the following topics :</p> <ul> <li><a href="https://stackoverflow.com/questions/5082846/java-ee-6-how-to-implement-stay-logged-in-when-user-login-in-to-the-web-appli/5083809#5083809">How to implement &quot;Stay Logged In&quot; when user login in to the web application</a> by BalusC</li> <li><a href="http://simple.souther.us/not-so-simple.html" rel="noreferrer">http://simple.souther.us/not-so-simple.html</a> by Ben Souther; [email protected]</li> </ul> <p>The main idea is to register the user's session in a Map, put into the servlet context. Each time a session is created, it is added to the Map with the JSESSIONID value for key; A persistent cookie is also created to memorize the JSESSIONID value, in order to find the session after the JSESSIONID cookie has been destroyed.</p> <p>When you close the web browser, JSESSIONID is destroyed. But all the HttpSession objects adress have been kept into a Map on server-side, and you can access the right session with the value saved into the persistent cookie.</p> <p>First, add two listeners in your web.xml deployment descriptor.</p> <pre><code>&lt;listener&gt; &lt;listener-class&gt; fr.hbonjour.strutsapp.listeners.CustomServletContextListener &lt;/listener-class&gt; &lt;/listener&gt; &lt;listener&gt; &lt;listener-class&gt; fr.hbonjour.strutsapp.listeners.CustomHttpSessionListener &lt;/listener-class&gt; &lt;/listener&gt; </code></pre> <p>The CustomServletContextListener creates a map at context initialization. This map will register all the sessions created by the user on this application.</p> <pre><code>/** * Instanciates a HashMap for holding references to session objects, and * binds it to context scope. * Also instanciates the mock database (UserDB) and binds it to * context scope. * @author Ben Souther; [email protected] * @since Sun May 8 18:57:10 EDT 2005 */ public class CustomServletContextListener implements ServletContextListener{ public void contextInitialized(ServletContextEvent event){ ServletContext context = event.getServletContext(); // // instanciate a map to store references to all the active // sessions and bind it to context scope. // HashMap activeUsers = new HashMap(); context.setAttribute("activeUsers", activeUsers); } /** * Needed for the ServletContextListener interface. */ public void contextDestroyed(ServletContextEvent event){ // To overcome the problem with losing the session references // during server restarts, put code here to serialize the // activeUsers HashMap. Then put code in the contextInitialized // method that reads and reloads it if it exists... } } </code></pre> <p>The CustomHttpSessionListener will put the session into the activeUsers map when it is created.</p> <pre><code>/** * Listens for session events and adds or removes references to * to the context scoped HashMap accordingly. * @author Ben Souther; [email protected] * @since Sun May 8 18:57:10 EDT 2005 */ public class CustomHttpSessionListener implements HttpSessionListener{ public void init(ServletConfig config){ } /** * Adds sessions to the context scoped HashMap when they begin. */ public void sessionCreated(HttpSessionEvent event){ HttpSession session = event.getSession(); ServletContext context = session.getServletContext(); HashMap&lt;String, HttpSession&gt; activeUsers = (HashMap&lt;String, HttpSession&gt;) context.getAttribute("activeUsers"); activeUsers.put(session.getId(), session); context.setAttribute("activeUsers", activeUsers); } /** * Removes sessions from the context scoped HashMap when they expire * or are invalidated. */ public void sessionDestroyed(HttpSessionEvent event){ HttpSession session = event.getSession(); ServletContext context = session.getServletContext(); HashMap&lt;String, HttpSession&gt; activeUsers = (HashMap&lt;String, HttpSession&gt;)context.getAttribute("activeUsers"); activeUsers.remove(session.getId()); } } </code></pre> <p>Use a basic form to test a user authentification by name/password. This login.jsp form is meant for test only.</p> <pre class="lang-xml prettyprint-override"><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt; &lt;html&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"&gt; &lt;title&gt;&lt;bean:message key="formulaire1Title" /&gt;&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;form action="login.go" method="get"&gt; &lt;input type="text" name="username" /&gt; &lt;input type="password" name="password" /&gt; &lt;input type="submit" /&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>There we go. This java servlet is forwarding to a login page when the user is not in session, and to another page when he is. It is only meant for testing the persistent session!</p> <pre><code>public class Servlet2 extends AbstractServlet { @Override protected void doGet(HttpServletRequest pRequest, HttpServletResponse pResponse) throws IOException, ServletException { String username = (String) pRequest.getParameter("username"); String password = (String) pRequest.getParameter("password"); // Session Object HttpSession l_session = null; String l_sessionCookieId = getCookieValue(pRequest, "JSESSIONID"); String l_persistentCookieId = getCookieValue(pRequest, "MY_SESSION_COOKIE"); // If a session cookie has been created if (l_sessionCookieId != null) { // If there isn't already a persistent session cookie if (l_persistentCookieId == null) { addCookie(pResponse, "MY_SESSION_COOKIE", l_sessionCookieId, 1800); } } // If a persistent session cookie has been created if (l_persistentCookieId != null) { HashMap&lt;String, HttpSession&gt; l_activeUsers = (HashMap&lt;String, HttpSession&gt;) pRequest.getServletContext().getAttribute("activeUsers"); // Get the existing session l_session = l_activeUsers.get(l_persistentCookieId); } // Otherwise a session has not been created if (l_session == null) { // Create a new session l_session = pRequest.getSession(); } //If the user info is in session, move forward to another page String forward = "/pages/displayUserInfo.jsp"; //Get the user User user = (User) l_session.getAttribute("user"); //If there's no user if (user == null) { // Put the user in session if (username != null &amp;&amp; password != null) { l_session.setAttribute("user", new User(username, password)); } // Ask again for proper login else { forward = "/pages/login.jsp"; } } //Forward this.getServletContext().getRequestDispatcher(forward).forward( pRequest, pResponse ); } </code></pre> <p>The MY_SESSION_COOKIE cookie will save the value of the JSESSIONID cookie. When the JSESSIONID cookie is destroyed, the MY_SESSION_COOKIE is still there with the session ID.</p> <p>JSESSIONID is gone with the web browser session, but we chose to use a persistent and simple cookie, along with a map of all active sessions put into the application context. The persistent cookie allow us to find the right session in the map.</p> <p>Don't forget these useful methods made by BalusC to add/get/remove cookies :</p> <pre><code>/** * * @author BalusC */ public static String getCookieValue(HttpServletRequest request, String name) { Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (name.equals(cookie.getName())) { return cookie.getValue(); } } } return null; } /** * * @author BalusC */ public static void addCookie(HttpServletResponse response, String name, String value, int maxAge) { Cookie cookie = new Cookie(name, value); cookie.setPath("/"); cookie.setMaxAge(maxAge); response.addCookie(cookie); } /** * * @author BalusC */ public static void removeCookie(HttpServletResponse response, String name) { addCookie(response, name, null, 0); } } </code></pre> <p>The last solution was tested with glassfish on localhost, with chrome for webbrowser, on windows. It only depends on a single cookie, and you don't need a database. But actually, I don't know what are the limits of such a mechanism. I only spent the night coming to this solution, without knowing if it will be a good or a bad one.</p> <p><strong>THANKS</strong></p> <p>I'm still learning, please tell me if there's any error in my answer. Thanks, @+</p>
16,189,208
How does this CSS produce a circle?
<p>This is the CSS:</p> <pre><code>div { width: 0; height: 0; border: 180px solid red; border-radius: 180px; } </code></pre> <p>How does it produce the circle below?</p> <p><img src="https://i.stack.imgur.com/yTmLN.jpg" alt="Enter image description here"></p> <p>Suppose, if a rectangle width is 180 pixels and height is 180 pixels then it would appear like this: </p> <p><img src="https://i.stack.imgur.com/nvK6a.jpg" alt="Enter image description here"></p> <p>After applying border-radius 30 pixels it would appear like this:</p> <p><img src="https://i.stack.imgur.com/xEutT.jpg" alt="Enter image description here"></p> <p>The rectangle is becoming smaller, that is, almost going to disappear if the radius size increases.</p> <p>So, how does a border of 180 pixels with <code>height/width-&gt; 0px</code> become a circle with a radius of 180 pixels?</p>
16,189,351
5
4
null
2013-04-24 10:08:31.443 UTC
82
2015-12-31 12:55:39.71 UTC
2015-12-31 12:55:39.71 UTC
null
2,606,013
null
2,313,718
null
1
210
html|css|css-shapes
21,779
<blockquote> <p>How does a border of 180 pixels with height/width-> 0px become a circle with a radius of 180 pixels?</p> </blockquote> <p>Let's reformulate that into two questions:</p> <h2>Where do <code>width</code> and <code>height</code> actually apply?</h2> <p>Let's have a look at the areas of a typical box (<a href="http://www.w3.org/TR/2012/CR-css3-background-20120724/#corners" rel="noreferrer">source</a>):</p> <p><img src="https://i.stack.imgur.com/9knOE.png" alt="W3C: Areas of a typical box"></p> <p>The <code>height</code> and <code>width</code> apply only on content, if the correct box model is being used (no quirks mode, no old Internet&nbsp;Explorer).</p> <h2>Where does <code>border-radius</code> apply?</h2> <p>The <code>border-radius</code> applies on the border-edge. If there is neither padding nor border it will directly affect your content edge, which results in your third example.</p> <h2>What does this mean for our border-radius/circle?</h2> <p>This means that your CSS rules result in a box that only consists of a border. Your rules state that this border should have a maximum width of 180 pixels on every side, while on the other hand it should have a maximum radius of the same size:</p> <p><img src="https://i.stack.imgur.com/CnjBH.png" alt="Example image"></p> <p>In the picture, the <em>actual content</em> of your element (the little black dot) is really non-existent. If you didn't apply any <code>border-radius</code> you would end up with the green box. The <code>border-radius</code> gives you the blue circle.</p> <p>It gets easier to understand if you apply the <code>border-radius</code> <a href="http://jsfiddle.net/9qvgG/" rel="noreferrer">only to two corners</a>:</p> <pre><code>#silly-circle{ width:0; height:0; border: 180px solid red; border-top-left-radius: 180px; border-top-right-radius: 180px; } </code></pre> <p><img src="https://i.stack.imgur.com/WU9aP.png" alt="Border only applied on two corners"></p> <p>Since in your example the size and radius for all corners/borders are equal you get a circle.</p> <h2>Further resources</h2> <h3>References</h3> <ul> <li>W3C: <a href="http://www.w3.org/TR/2012/CR-css3-background-20120724/" rel="noreferrer">CSS Backgrounds and Borders Module Level 3</a> (esp. <a href="http://www.w3.org/TR/2012/CR-css3-background-20120724/#corners" rel="noreferrer">5. Rounded Corners</a>)</li> </ul> <h3>Demonstrations</h3> <ul> <li>Please open the demo below, which shows how the <code>border-radius</code> affects the border (think of the inner blue box as the content box, the inner black border as the padding border, the empty space as the padding and the giant red border as the, well, border). Intersections between the inner box and the red border would usually affect the content edge.</li> </ul> <p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var all = $('#TopLeft, #TopRight, #BottomRight, #BottomLeft'); all.on('change keyup', function() { $('#box').css('border' + this.id + 'Radius', (this.value || 0) + "%"); $('#' + this.id + 'Text').val(this.value + "%"); }); $('#total').on('change keyup', function() { $('#box').css('borderRadius', (this.value || 0) + "%"); $('#' + this.id + 'Text').val(this.value + "%"); all.val(this.value); all.each(function(){$('#' + this.id + 'Text').val(this.value + "%");}) });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>#box { margin:auto; width: 32px; height: 32px; border: 100px solid red; padding: 32px; transition: border-radius 1s ease; -moz-transition: border-radius 1s ease; -webkit-transition: border-radius 1s ease; -o-transition: border-radius 1s ease; -ms-transition: border-radius 1s ease; } #chooser{margin:auto;} #innerBox { width: 100%; height: 100%; border: 1px solid blue; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;div id="box"&gt; &lt;div id="innerBox"&gt;&lt;/div&gt; &lt;/div&gt; &lt;table id="chooser"&gt; &lt;tr&gt; &lt;td&gt;&lt;label for="total"&gt;Total&lt;/label&gt;&lt;/td&gt; &lt;td&gt;&lt;input id="total" value="0" type="range" min="0" max="100" step="1" /&gt;&lt;/td&gt; &lt;td&gt;&lt;input readonly id="totalText" value="0" type="text" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;label for="TopLeft"&gt;Top-Left&lt;/label&gt;&lt;/td&gt; &lt;td&gt;&lt;input id="TopLeft" value="0" type="range" min="0" max="100" step="1" /&gt;&lt;/td&gt; &lt;td&gt;&lt;input readonly id="TopLeftText" value="0" type="text" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;label for="TopRight"&gt;Top right&lt;/label&gt;&lt;/td&gt; &lt;td&gt;&lt;input id="TopRight" value="0" type="range" min="0" max="100" step="1" /&gt;&lt;/td&gt; &lt;td&gt;&lt;input readonly id="TopRightText" value="0" type="text" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;label for="BottomRight"&gt;Bottom right&lt;/label&gt;&lt;/td&gt; &lt;td&gt;&lt;input id="BottomRight" value="0" type="range" min="0" max="100" step="1" /&gt;&lt;/td&gt; &lt;td&gt;&lt;input readonly id="BottomRightText" value="0" type="text" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;label for="BottomLeft"&gt;Bottom left&lt;/label&gt;&lt;/td&gt; &lt;td&gt;&lt;input id="BottomLeft" value="0" type="range" min="0" max="100" step="1" /&gt;&lt;/td&gt; &lt;td&gt;&lt;input readonly id="BottomLeftText" value="0" type="text" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;caption&gt;&lt;code&gt;border-radius&lt;/code&gt; values. All values are in percent.&lt;/caption&gt; &lt;/table&gt; &lt;p&gt;This demo uses a box with a &lt;code&gt;width/height&lt;/code&gt; of 32px, a &lt;code&gt;padding&lt;/code&gt; of 32px, and a &lt;code&gt;border&lt;/code&gt; of 100px.&lt;/p&gt;</code></pre> </div> </div> </p>
16,133,923
400 vs 422 response to POST of data
<p>I'm trying to figure out what the correct status code to return on different scenarios with a &quot;REST-like&quot; API that I'm working on. Let's say I have an end point that allows POST'ing purchases in JSON format. It looks like this:</p> <pre><code>{ &quot;account_number&quot;: 45645511, &quot;upc&quot;: &quot;00490000486&quot;, &quot;price&quot;: 1.00, &quot;tax&quot;: 0.08 } </code></pre> <p>What should I return if the client sends me &quot;sales_tax&quot; (instead of the expected &quot;tax&quot;). Currently, I'm returning a 400. But, I've started questioning myself on this. Should I really be returning a 422? I mean, it's JSON (which is supported) and it's valid JSON, it's just doesn't contain all of the required fields.</p>
20,215,807
8
1
null
2013-04-21 17:13:39.107 UTC
115
2022-05-06 21:02:53.68 UTC
2020-12-16 00:12:44.22 UTC
null
453,596
null
265,681
null
1
487
rest|http-status-codes
507,324
<p><strong>400 Bad Request</strong> would now seem to be the best HTTP/1.1 status code for your use case.</p> <p><strong>At the time of your question</strong> (and my original answer), <a href="https://www.rfc-editor.org/rfc/rfc7231" rel="noreferrer">RFC 7231</a> was not a thing; at which point I objected to <code>400 Bad Request</code> because <a href="https://www.rfc-editor.org/rfc/rfc2616#section-10.4.1" rel="noreferrer">RFC 2616</a> said (with emphasis mine):</p> <blockquote> <p>The request could not be understood by the server <strong>due to malformed syntax</strong>.</p> </blockquote> <p>and the request you describe is syntactically valid JSON encased in syntactically valid HTTP, and thus the server has no issues with the <strong>syntax</strong> of the request.</p> <p><strong>However</strong> <a href="https://stackoverflow.com/questions/16133923/400-vs-422-response-to-post-of-data/20215807?noredirect=1#comment50346163_20215807">as pointed out by Lee Saferite in the comments</a>, <a href="https://www.rfc-editor.org/rfc/rfc7231#section-6.5.1" rel="noreferrer">RFC 7231, which obsoletes RFC 2616, does not include that restriction</a>:</p> <blockquote> <p>The 400 (Bad Request) status code indicates that the server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).</p> </blockquote> <hr /> <p>However, <strong>prior to that re-wording</strong> (or if you want to quibble about RFC 7231 only being a <em>proposed</em> standard right now), <code>422 Unprocessable Entity</code> does not seem an <em>incorrect</em> HTTP status code for your use case, because as <a href="https://www.rfc-editor.org/rfc/rfc4918#section-1" rel="noreferrer">the introduction to RFC 4918 says:</a></p> <blockquote> <p>While the status codes provided by HTTP/1.1 are sufficient to describe most error conditions encountered by WebDAV methods, there are some errors that do not fall neatly into the existing categories. This specification defines extra status codes developed for WebDAV methods (Section 11)</p> </blockquote> <p>And <a href="https://www.rfc-editor.org/rfc/rfc4918#section-11.2" rel="noreferrer">the description of <code>422</code></a> says:</p> <blockquote> <p>The 422 (Unprocessable Entity) status code means the server understands the content type of the request entity (hence a 415(Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions.</p> </blockquote> <p>(Note the reference to syntax; I suspect 7231 partly obsoletes 4918 too)</p> <p>This sounds <em>exactly</em> like your situation, but just in case there was any doubt, it goes on to say:</p> <blockquote> <p>For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.</p> </blockquote> <p>(Replace &quot;XML&quot; with &quot;JSON&quot; and I think we can agree that's your situation)</p> <p>Now, some will object that RFC 4918 is about &quot;HTTP Extensions for Web Distributed Authoring and Versioning (WebDAV)&quot; and that you (presumably) are doing nothing involving WebDAV so shouldn't use things from it.</p> <p>Given the choice between using an error code in the original standard that explicitly doesn't cover the situation, and one from an extension that describes the situation exactly, I would choose the latter.</p> <p>Furthermore, <a href="https://www.rfc-editor.org/rfc/rfc4918#section-21.4" rel="noreferrer">RFC 4918 Section 21.4</a> refers to the <a href="http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml" rel="noreferrer">IANA Hypertext Transfer Protocol (HTTP) Status Code Registry</a>, where 422 can be found.</p> <p>I propose that it is totally reasonable for an HTTP client or server to use any status code from that registry, so long as they do so correctly.</p> <hr /> <p>But as of HTTP/1.1, <a href="https://www.rfc-editor.org/rfc/rfc7231" rel="noreferrer">RFC 7231</a> has traction, so just use <code>400 Bad Request</code>!</p>
15,253,692
MVC 4 Ajax.beginform submit - causes full postback
<p>MVC4 Internet project</p> <p>I'm using Ajax.BeginForm to do a Postback with validation and it posts back the entire page rather than just the UpdateTargetID. I've looked at other posts on SO and haven't found the answer. I've built a new MVC4 Internet project just for testing (VS 2012 has been updated with 'ASP.NET and Web Tools 2012.2').</p> <p>Here's my code</p> <p><strong>Controller</strong></p> <pre><code>public ActionResult Index() { var vM = _db.Students.FirstOrDefault(); return View(vM); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Index(Student vM) { if (ModelState.IsValid) { //code if Model valid return Json(new { url = Url.Action("About", "Controller") }); } ModelState.AddModelError(string.Empty, "AJAX Post"); return PartialView("Index", vM); } </code></pre> <p><strong>View</strong></p> <pre><code>@model AJAX_Test.Models.Student @{ ViewBag.Title = "Student"; } &lt;script src="~/Scripts/jquery-1.8.2.js"&gt;&lt;/script&gt; &lt;script src="~/Scripts/jquery.unobtrusive-ajax.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; var onSuccess = function (result) { if (result.url) { window.location.href = result.url; } } // when server returns JSON object containing an url property redirect the browser &lt;/script&gt; &lt;h1&gt;@ViewBag.Title&lt;/h1&gt; &lt;div id="IDXForm"&gt; @using (Ajax.BeginForm("Index", new AjaxOptions() { UpdateTargetId = "IDXForm", OnSuccess = "onSuccess", HttpMethod = "Post" })) { @Html.AntiForgeryToken() @Html.ValidationSummary(true) &lt;span&gt;@Html.EditorFor(m =&gt; m.FirstName) @Model.EnrollmentDate.ToShortDateString()&lt;/span&gt; &lt;input type="submit" value="Submit" /&gt; } &lt;/div&gt; </code></pre> <p>The initial view is: <img src="https://i.stack.imgur.com/Z8mqv.png" alt="enter image description here"></p> <p>After Submittal: <img src="https://i.stack.imgur.com/TUW4K.png" alt="enter image description here"></p> <p>Source code for body after submittal:</p> <pre><code> &lt;div id="body"&gt; &lt;section class="content-wrapper main-content clear-fix"&gt; &lt;script src="/Scripts/jquery-1.8.2.js"&gt;&lt;/script&gt; &lt;script src="/Scripts/jquery.unobtrusive-ajax.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; var onSuccess = function (result) { if (result.url) { window.location.href = result.url; } } // when server returns JSON object containing an url property redirect the browser &lt;/script&gt; &lt;h1&gt;Student&lt;/h1&gt; &lt;div id="IDXForm"&gt; &lt;form action="/" data-ajax="true" data-ajax-method="Post" data-ajax-mode="replace" data-ajax-success="onSuccess" data-ajax-update="#IDXForm" id="form0" method="post"&gt;&lt;input name="__RequestVerificationToken" type="hidden" value="vkCszJu-fKT6zUr5ys2StOTPF6a9pZdj5k1MyaAZKo8MPweS53dUuni0C9B17NjL_GVydHa7-jI1H0F9HrYEdKxeCWq9mCeER3ebaZYLxIs1" /&gt;&lt;span&gt;&lt;input class="text-box single-line" id="FirstName" name="FirstName" type="text" value="Carson" /&gt; 9/1/2005&lt;/span&gt; &lt;input type="submit" value="Submit" /&gt; &lt;/form&gt;&lt;/div&gt; </code></pre> <p>Can anyone see what is wrong with my code?</p> <p>Thank you.</p>
15,489,634
6
0
null
2013-03-06 17:11:04.18 UTC
4
2016-02-10 18:43:51.583 UTC
2013-03-10 19:07:26.58 UTC
null
1,258,671
null
1,258,671
null
1
7
asp.net-mvc|jquery
38,214
<p>The contents of the UpdateTargetID must be in a partial view and that partial view needs to be called from the Controller Post Action. Darin answered me through e-mail (thank you Darin). You need to use a parital view. I've tried to update his answer twice and the moderators have not done it or provided an explanation why so I'm posting my own answer for others benefit.</p> <p>_MyForm View:</p> <pre><code>@model AJAX_Test.Models.Student @using (Ajax.BeginForm("Index", new AjaxOptions { UpdateTargetId = "IDXForm", OnSuccess = "onSuccess" })) { @Html.AntiForgeryToken() @Html.ValidationSummary(true) &lt;span&gt; @Html.EditorFor(m =&gt; m.FirstName) @Model.EnrollmentDate.ToShortDateString() &lt;/span&gt; &lt;input type="submit" value="Submit" /&gt; } </code></pre> <p>Main View :</p> <pre><code>&lt;div id="IDXForm"&gt; @Html.Partial("_MyForm") &lt;/div&gt; </code></pre> <p>Controller Post Action:</p> <pre><code> ModelState.AddModelError(string.Empty, "AJAX Post"); return PartialView("_MyForm", vM); </code></pre>
24,604,817
How to Add a Boolean Column in Android SQlite
<p>I have created a table for my <code>ContentProvider</code> using the following line :</p> <pre><code>static final String CREATE_DB_TABLE = " CREATE TABLE " + CONTACTS_TABLE_NAME + " (_id INTEGER PRIMARY KEY AUTOINCREMENT, " + " pid TEXT NOT NULL, " + " name TEXT NOT NULL,"+ "number TEXT NOT NULL);"; </code></pre> <p>It has 4 columns. Now i want to add a column with a boolean value of true/false. How can i add append/change this statement if i have to add a <strong>boolean</strong> column named <strong>"status"</strong>.</p>
24,605,762
5
5
null
2014-07-07 07:09:13.733 UTC
7
2018-01-17 16:07:27.213 UTC
null
null
null
null
3,418,888
null
1
37
android|sqlite|android-sqlite
70,834
<p>You could use something like this:</p> <p>Create your table:</p> <pre><code>static final String CREATE_DB_TABLE = "CREATE TABLE " + CONTACTS_TABLE_NAME " + " (_id INTEGER PRIMARY KEY AUTOINCREMENT," + "..." + " flag INTEGER DEFAULT 0)"; </code></pre> <p>retrieve your value as:</p> <pre><code>Boolean flag = (cursor.getInt(cursor.getColumnIndex("flag")) == 1); </code></pre>
22,063,748
django - get() returned more than one topic
<p>When I tried to relate an attribute with another one which has an <strong>M to M</strong> relation I received this error:</p> <blockquote> <p>get() returned more than one topic -- it returned 2!</p> </blockquote> <p>Can you guys tell me what that means and maybe tell me in advance how to avoid this error ?</p> <p><strong>models</strong></p> <pre><code>class LearningObjective(models.Model): learning_objective=models.TextField() class Topic(models.Model): learning_objective_topic=models.ManyToManyField(LearningObjective) topic=models.TextField() </code></pre> <p>output of <code>LearningObjective.objects.all()</code></p> <pre><code>[&lt;LearningObjective: lO1&gt;, &lt;LearningObjective: lO2&gt;, &lt;LearningObjective: lO3&gt;] </code></pre> <p>output of <code>Topic.objects.all()</code></p> <pre><code>[&lt;Topic: Topic object&gt;, &lt;Topic: Topic object&gt;, &lt;Topic: Topic object&gt;, &lt;Topic: Topic object&gt;, &lt;Topic: Topic object&gt;, &lt;Topic: Topic object&gt;, &lt;Topic: Topic object&gt;, &lt;Topic: Topic object&gt;, &lt;Topic: Topic object&gt;, &lt;Topic: Topic object&gt;, &lt;Topic: Topic object&gt;, &lt;Topic: Topic object&gt;, &lt;Topic: Topic object&gt;, &lt;Topic: Topic object&gt;] </code></pre> <p><strong>views</strong></p> <pre><code> def create_themen(request): new_topic=Topic(topic=request.POST['topic']) new_topic.save() return render(request, 'topic.html', {'topic': topic.objects.all()}) def create_learning_objective(request): new_learning_objective=LearningObjective(learning_objective=request.POST['learning_objective']) new_learning_objective.save() new_learning_objective_topic=Topic.objects.get(topic=request.POST['topic']) new_learning_objective_topic.new_learning_objective_topic.add(new_learning_objective) return render( request, 'learning_objective.html', { 'topic': Topic.objects.all(), 'todo': TodoList.objects.all(), 'learning_objective': LearningObjective.objects.all() }) </code></pre>
22,064,255
8
2
null
2014-02-27 09:06:54.687 UTC
20
2021-10-22 17:02:01.737 UTC
2015-10-19 06:14:35.11 UTC
null
2,968,265
null
2,968,265
null
1
91
django|django-models|django-views
154,355
<blockquote> <p><code>get()</code> returned more than one topic -- it returned 2!</p> </blockquote> <p>The above error indicatess that you have more than one record in the DB related to the specific parameter you passed while querying using <a href="https://docs.djangoproject.com/en/dev/topics/db/queries/#retrieving-a-single-object-with-get" rel="noreferrer"><code>get()</code></a> such as </p> <pre><code>Model.objects.get(field_name=some_param) </code></pre> <p>To avoid this kind of error in the future, you always need to do query as per your schema design. In your case you designed a table with a <a href="https://docs.djangoproject.com/en/dev/topics/db/examples/many_to_many/" rel="noreferrer">many-to-many relationship</a> so obviously there will be multiple records for that field and that is the reason you are getting the above error.</p> <p>So instead of using <code>get()</code> you should use <a href="https://docs.djangoproject.com/en/dev/topics/db/queries/#retrieving-specific-objects-with-filters" rel="noreferrer"><code>filter()</code></a> which will return multiple records. Such as </p> <pre><code>Model.objects.filter(field_name=some_param) </code></pre> <p>Please read about how to make queries in django <a href="https://docs.djangoproject.com/en/dev/topics/db/queries/" rel="noreferrer">here</a>.</p>