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
16,549,296
How perform task on JavaFX TextField at onfocus and outfocus?
<p>I am working on JavaFX project. I need to perform some task on a JavaFX <code>TextField</code>.</p> <p>For example on the "on focus" event for the <code>TextField</code> I want to print</p> <pre><code>System.out.println("Textfield on focus"); </code></pre> <p>and on the "out focus" event it should print</p> <pre><code>System.out.println("Textfield out focus"); </code></pre>
16,971,194
4
0
null
2013-05-14 17:28:31.273 UTC
8
2021-12-02 01:34:12.417 UTC
2019-05-23 14:17:55.787 UTC
null
5,966,775
null
2,119,934
null
1
59
java|javafx-2|javafx|javafx-8
68,313
<p>I thought it might be helpful to see an example which specifies the ChangeListener as an anonymous inner class like scottb mentioned. </p> <pre><code>TextField yourTextField = new TextField(); yourTextField.focusedProperty().addListener(new ChangeListener&lt;Boolean&gt;() { @Override public void changed(ObservableValue&lt;? extends Boolean&gt; arg0, Boolean oldPropertyValue, Boolean newPropertyValue) { if (newPropertyValue) { System.out.println("Textfield on focus"); } else { System.out.println("Textfield out focus"); } } }); </code></pre> <p>I hope this answer is helpful!</p>
13,065,555
ORACLE - String to number
<p>I have a little problem with a column on a table. The column is a Varchar named "prize". The datas are something like:</p> <pre><code>00008599 00004565 00001600 etc... </code></pre> <p>They have to become:</p> <pre><code>85.99 45.65 16.00 etc... </code></pre> <p>I have tried with to_number function but it doesnt work. Something like:</p> <pre><code>SELECT to_number(prize, '999999.99') FROM TABLE </code></pre> <p>The error is: ORA-01722</p>
13,065,591
2
2
null
2012-10-25 09:29:18.827 UTC
0
2012-10-25 10:02:01.057 UTC
null
null
null
null
1,199,940
null
1
5
string|oracle|numbers
83,474
<p>You could use LTRIM to get rid of leading zeroes and divide by 100:</p> <pre><code>SELECT to_number(ltrim(prize, '0')) / 100 FROM table </code></pre>
17,187,873
Set a value to a variable based on the results of a query (in PL/pgSQL style)
<p>What I need to do is set a value to a variable using the <code>EXECUTING</code> query.</p> <p>In pure SQL style, I could do something like the following:</p> <pre><code>// here declaring function and etc... DECLARE cnt INTEGER; EXECUTE 'SELECT COUNT(*) FROM t' INTO cnt; </code></pre> <p>How to achieve the same functionality in the form of a PL/pgSQL function? What is the correct syntax for the following pseudo-code? (The following is obviously the wrong syntax)</p> <pre><code>cnt := EXECUTE ( 'SELECT COUNT(*) FROM t' ) ; </code></pre>
17,188,662
3
0
null
2013-06-19 09:37:31.877 UTC
5
2014-09-05 17:10:52.78 UTC
2014-09-05 17:10:52.78 UTC
null
1,021,943
null
1,609,729
null
1
4
postgresql|plpgsql|postgresql-9.2
39,787
<p>Not sure what you mean by "plpgsql style". The syntax you showed is perfectly OK, as shown in <a href="http://www.postgresql.org/docs/current/interactive/plpgsql-statements.html#PLPGSQL-STATEMENTS-EXECUTING-DYN" rel="nofollow">documentation</a>.</p>
17,497,154
SMTPException : Unable to read data from the transport connection: net_io_connectionclosed
<p>I know that this question looks like duplicate of dozens other questions while its not.</p> <p>When ever i try to send an email on my local machine through my web application an SMTPException is thrown and the exceptions is :</p> <pre><code>//on this line : SmtpServer.Send(mail); Unable to read data from the transport connection: net_io_connectionclosed. </code></pre> <p>While the code on production is working perfectly, the same code, the same connections, the same credentials, i'm using IP instead of alias, i tried to turn off the firewall on my local machine, and nothing helped me to fix this issue.</p> <p>While on my local machine is used to work previously, can anyone give just a hint what could be the problem that raising this issue?</p>
17,537,220
5
0
null
2013-07-05 21:36:15.953 UTC
3
2020-09-01 10:07:30.427 UTC
null
null
null
null
1,225,246
null
1
16
c#|email
102,614
<p>If you are on a residential internet connection, quite often your ISP will block outgoing email sends by blocking all outbound connections to port 25. This is quite common here in the US. Try connecting to a local email server over TCP/IP, or to one on your own internal network.</p>
24,914,227
How to get local time in php?
<p>I am trying to get the local time using php. I wrote two different versions, but they both give the wrong time</p> <pre><code>date_default_timezone_set('UTC'); $now = new DateTime(); echo $now-&gt;getTimestamp(); </code></pre> <p>Another way</p> <pre><code>date_default_timezone_set('America/New York'); echo strtotime("now")."&lt;br/&gt;";; $now = new DateTime(); echo $now-&gt;getTimestamp(); </code></pre> <p>In both cases I get the time 4 fours ahead of my local time. There is any other way to get the local time?</p>
24,914,436
8
11
null
2014-07-23 15:08:51.01 UTC
7
2021-11-06 13:38:18.1 UTC
2014-07-23 15:10:11.633 UTC
null
269,970
null
3,648,429
null
1
8
php
56,958
<p><code>DateTime::getTimestamp()</code> returns unix timestamp. That number is always UTC. What you want is format the date according to your time zone.</p> <pre><code>$dt = new DateTime(&quot;now&quot;, new DateTimeZone('America/New_York')); echo $dt-&gt;format('m/d/Y, H:i:s'); </code></pre> <p>Or use a different date format, according to what you need.</p> <p>Also, you can use DateTime library for all your date needs. No need to change server's default timezone every time you want to fetch the date.</p>
21,797,621
arrayformula sum in Google spreadsheet
<p>How do you <code>arrayformula()</code> a <code>sum()</code> such as:</p> <p><code>=sum(A1:H1)</code></p> <p>I need to go down 1000 rows.</p>
21,804,838
11
4
null
2014-02-15 12:36:26.447 UTC
10
2022-09-19 21:33:45.51 UTC
null
null
null
null
1,744,744
null
1
37
google-sheets
66,737
<p>Another option:</p> <pre><code>=ArrayFormula(SUMIF(IF(COLUMN(A1:H1),ROW(A1:A1000)),ROW(A1:A1000),A1:H1000)) </code></pre>
39,747,929
Can't use private property in extensions in another file
<p>I can't use private property in extension. My extension is in another file. </p> <p>How can I use private property in extension?</p>
39,748,056
3
7
null
2016-09-28 12:43:38.72 UTC
4
2021-01-20 07:17:57.423 UTC
2019-02-10 20:29:08.867 UTC
null
1,265,393
null
6,555,562
null
1
32
ios|swift|swift3
12,401
<p><strong>Update</strong> Starting with Swift 4, extensions can access the private properties of a type declared in the same file. See <a href="https://docs.swift.org/swift-book/LanguageGuide/AccessControl.html" rel="noreferrer">Access Levels</a>.</p> <p>If a property is declared <code>private</code>, its access is restricted to the enclosing declaration, and to extensions of that declaration that are in the same file.</p> <p>If the property is declared <code>fileprivate</code>, it can only be used within the file it is declared (and by <em>anything</em> in that file).</p> <p>If the property is declared <code>internal</code> (the default), it can only be used within the module it is declared (and by <em>anything</em> in that file).</p> <p>If the property is declared <code>public</code> or <code>open</code>, it can be used by anything within the module as well as outside of the module by files that import the module it is declared in.</p>
44,838,421
Ansible: Multiple and/or conditionals in when clause
<p>I am having issues when trying to use multiple and/or conditionals in a when statement to decide whether a task needs to be ran or not. Basically I am making a playbook to do automated system patching with options for security patches, kernel only patches and to specify packages in a var file.</p> <p>I run the playbook with the following commands and define the variables through extended variables option (-e)</p> <p><code>ansible-playbook site.yml -i inventory --ask-vault -u (username) -e "security=true restart=true" -k -K </code></p> <p>By default the playbook will update every package on the system except kernel but I would like to skip that action if I specify any of a few variables. The code I have is the following:</p> <pre><code>- name: Update all packages yum: name: "*" state: latest exclude: "kernel*" when: security is not defined or kernel is not defined or specified_packages is not defined and ansible_os_family == "RedHat" </code></pre> <p>Ive tried all of the following combinations:</p> <p><code>when: (ansible_os_family == "RedHat") and (security is defined or kernel is defined or specified_packages is defined)</code></p> <p><code>when: (ansible_os_family == "RedHat") and (security == true or kernel == true or specified_packages == true )</code> &lt;- this case throws a not defined error because i don't define all variables every time i run the playbook</p> <p><code>when: ansible_os_family == "RedHat" when: security is defined or kernel is defined or specified_packages is defined</code></p> <p><strong>Note:</strong> I am aware and have used an extra variable such as "skip" to skip this task and use the when clause <code>when: ansible_os_family == "RedHat" and skip is not defined</code> but would prefer not have my users need to use an extra variable just to skip this default action.</p> <p>I also am not using tags as I am gathering a list of packages before and after the upgrade to compare and report in the end so I wont be able to run those as they are local action commands. This is why I'm using one role with multiple tasks turned on and off via extended variables. I am open to any suggestion that rewrites the playbook in a more efficient way as I am sort of a noob.</p>
44,854,903
2
3
null
2017-06-30 04:05:47.127 UTC
4
2021-01-21 10:29:58.797 UTC
2021-01-21 10:29:58.797 UTC
null
513,536
null
4,272,929
null
1
10
ansible|ansible-2.x
71,627
<p>It was such a simple answer!</p> <p>The following works:</p> <pre><code>when: not (security is defined or kernel is defined or specified_packages is defined) and ansible_os_family == "RedHat" </code></pre>
17,586,174
Collapse all group except selected group in expandable listview android
<p>I'm developing android application using expandable list view. Actually what I need is, I'm listing group, which contains child. </p> <p>If I select an unexpandable group, it should expand, after I ll select second group at that time the first group should be collapsed. I did Google, but I couldn't find what I want. Please help me out.</p>
17,586,315
8
0
null
2013-07-11 06:07:22.167 UTC
17
2017-04-07 07:43:33.363 UTC
2015-01-20 11:02:13.18 UTC
null
2,306,173
null
1,656,553
null
1
66
android|expandablelistview|expand|collapse
50,904
<p>Have the current expanded group position stored in a variable. In onGroupExpanded do the following.</p> <pre><code>private int lastExpandedPosition = -1; private ExpandableListView lv; //your expandable listview ... lv.setOnGroupExpandListener(new OnGroupExpandListener() { @Override public void onGroupExpand(int groupPosition) { if (lastExpandedPosition != -1 &amp;&amp; groupPosition != lastExpandedPosition) { lv.collapseGroup(lastExpandedPosition); } lastExpandedPosition = groupPosition; } }); </code></pre>
17,160,162
What do ellipsis [...] mean in a list?
<p>I was playing around in python. I used the following code in IDLE:</p> <pre><code>p = [1, 2] p[1:1] = [p] print p </code></pre> <p>The output was: </p> <pre><code>[1, [...], 2] </code></pre> <p>What is this <code>[…]</code>? Interestingly I could now use this as a list of list of list up to infinity i.e.</p> <pre><code>p[1][1][1].... </code></pre> <p>I could write the above as long as I wanted and it would still work.</p> <p>EDIT:</p> <ul> <li>How is it represented in memory?</li> <li>What's its use? Examples of some cases where it is useful would be helpful.</li> <li>Any link to official documentation would be really useful.</li> </ul>
17,160,180
5
8
null
2013-06-18 03:38:33.063 UTC
52
2022-08-29 13:23:55.31 UTC
2022-08-29 13:23:55.31 UTC
null
523,612
null
2,235,567
null
1
205
python|list|ellipsis
21,650
<p>It means that you created an infinite list nested inside itself, which can not be printed. <code>p</code> contains <code>p</code> which contains <code>p</code> ... and so on. The <code>[...]</code> notation is a way to let you know this, and to inform that it can't be represented! Take a look at @6502's answer to see a nice picture showing what's happening.</p> <p>Now, regarding the three new items after your edit:</p> <ul> <li>This <a href="https://stackoverflow.com/a/7680125/201359">answer</a> seems to cover it</li> <li>Ignacio's <a href="http://www.csse.monash.edu.au/~lloyd/tildeFP/1993ACJ/" rel="noreferrer">link</a> describes some possible uses</li> <li>This is more a topic of data structure design than programming languages, so it's unlikely that any reference is found in Python's official documentation</li> </ul>
30,316,586
How can I set the initial value of Select2 when using AJAX?
<p>I have a select2 v4.0.0 being populated from an Ajax array. If I set the val of the select2 I can see via javascript debugging that it has selected the correct item (#3 in my case), however this is not shown in the select box, it is still showing the placeholder. <img src="https://i.stack.imgur.com/Avj4C.png" alt="enter image description here"></p> <p>Whereas I should be seeing something like this: <img src="https://i.stack.imgur.com/gwBZa.png" alt="enter image description here"></p> <p>In my form fields:</p> <pre><code>&lt;input name="creditor_id" type="hidden" value="3"&gt; &lt;div class="form-group minimal form-gap-after"&gt; &lt;span class="col-xs-3 control-label minimal"&gt; &lt;label for="Creditor:"&gt;Creditor:&lt;/label&gt; &lt;/span&gt; &lt;div class="col-xs-9"&gt; &lt;div class="input-group col-xs-8 pull-left select2-bootstrap-prepend"&gt; &lt;select class="creditor_select2 input-xlarge form-control minimal select2 col-xs-8"&gt; &lt;option&gt;&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>My javascript:</p> <pre><code>var initial_creditor_id = "3"; $(".creditor_select2").select2({ ajax: { url: "/admin/api/transactions/creditorlist", dataType: 'json', delay: 250, data: function (params) { return { q: params.term, c_id: initial_creditor_id, page: params.page }; }, processResults: function (data, page) { return { results: data }; }, cache: true }, placeholder: "Search for a Creditor", width: "element", theme: "bootstrap", allowClear: true }).on("select2:select", function (e) { var selected = e.params.data; if (typeof selected !== "undefined") { $("[name='creditor_id']").val(selected.creditor_id); $("#allocationsDiv").hide(); $("[name='amount_cash']").val(""); $("[name='amount_cheque']").val(""); $("[name='amount_direct']").val(""); $("[name='amount_creditcard']").val(""); } }).on("select2:unselecting", function (e) { $("form").each(function () { this.reset() }); ("#allocationsDiv").hide(); $("[name='creditor_id']").val(""); }).val(initial_creditor_id); </code></pre> <p>How can I make the select box show the selected item rather than the placeholder? Should I be sending this as part of the AJAX JSON response perhaps?</p> <p>In the past, Select2 required an option called initSelection that was defined whenever a custom data source was being used, allowing for the initial selection for the component to be determined. This worked fine for me in v3.5.</p>
30,328,989
13
3
null
2015-05-19 04:07:21.567 UTC
50
2022-06-10 16:49:03.68 UTC
2020-11-28 20:20:38.273 UTC
null
359,284
null
1,702,250
null
1
111
jquery-select2|jquery-select2-4
147,419
<p>You are doing most things correctly, it looks like the only problem you are hitting is that you are not triggering the <code>change</code> method after you are setting the new value. Without a <code>change</code> event, Select2 cannot know that the underlying value has changed so it will only display the placeholder. Changing your last part to</p> <pre><code>.val(initial_creditor_id).trigger('change'); </code></pre> <p>Should fix your issue, and you should see the UI update right away.</p> <hr> <p>This is assuming that you have an <code>&lt;option&gt;</code> already that has a <code>value</code> of <code>initial_creditor_id</code>. If you do not Select2, and the browser, will not actually be able to change the value, as there is no option to switch to, and Select2 will not detect the new value. I noticed that your <code>&lt;select&gt;</code> only contains a single option, the one for the placeholder, which means that you will need to create the new <code>&lt;option&gt;</code> manually.</p> <pre><code>var $option = $("&lt;option selected&gt;&lt;/option&gt;").val(initial_creditor_id).text("Whatever Select2 should display"); </code></pre> <p>And then append it to the <code>&lt;select&gt;</code> that you initialized Select2 on. You may need to get the text from an external source, which is where <code>initSelection</code> used to come into play, which is still possible with Select2 4.0.0. Like a standard select, this means you are going to have to make the AJAX request to retrieve the value and then set the <code>&lt;option&gt;</code> text on the fly to adjust.</p> <pre><code>var $select = $('.creditor_select2'); $select.select2(/* ... */); // initialize Select2 and any events var $option = $('&lt;option selected&gt;Loading...&lt;/option&gt;').val(initial_creditor_id); $select.append($option).trigger('change'); // append the option and update Select2 $.ajax({ // make the request for the selected data object type: 'GET', url: '/api/for/single/creditor/' + initial_creditor_id, dataType: 'json' }).then(function (data) { // Here we should have the data object $option.text(data.text).val(data.id); // update the text that is displayed (and maybe even the value) $option.removeData(); // remove any caching data that might be associated $select.trigger('change'); // notify JavaScript components of possible changes }); </code></pre> <p>While this may look like a lot of code, this is <em>exactly how you would do it</em> for non-Select2 select boxes to ensure that all changes were made.</p>
18,523,577
How to program an Arduino with C++
<p>So lately I've been playing around with my Arduino and I was wondering if there was some way I could program the Arduino in C++. I've been programming it using the C++/<a href="https://en.wikipedia.org/wiki/Processing_%28programming_language%29" rel="noreferrer">Processing</a> language in Vim and using a makefile to compile and upload to the Arduino.</p> <p>But my goal is to be able to use classes and all the great C++ features (or at least sum) to program it. Eventually I would even love to program it in raw C and I'm just having troubles finding out how to do either. It would be great if someone could point me in the right direction or help me out.</p>
18,527,499
2
1
null
2013-08-30 01:36:59.377 UTC
23
2020-01-13 20:32:49.23 UTC
2020-01-13 20:32:49.23 UTC
null
63,550
null
1,530,258
null
1
34
c++|c|arduino
93,695
<p>Here is my experience: I'm building a robotic smart toy for autistic children using Arduino, sensors, motors, led and bluetooth. I wrote my own libraries to do exactly what I needed using C++. But I found out that the Arduino IDE Compiler is an older version that does not support the new C++11 features.</p> <p>So I had to find myself a way to compile C++11 code and upload it to my Arduino. It turns out to be "pretty" basic: I needed a Makefile, the avr-gcc 4.8 toolchain and voilà! The makefile job is done by Sudar (<a href="https://github.com/sudar/Arduino-Makefile" rel="noreferrer">https://github.com/sudar/Arduino-Makefile</a>) and it works great. I had to customise it a bit to make it work for my project though.</p> <p>Here is some documentation I've written for my project. You should take a look, it might be useful for you. <a href="https://github.com/WeAreLeka/moti/blob/master/INSTALL.md" rel="noreferrer">https://github.com/WeAreLeka/moti/blob/master/INSTALL.md</a></p> <p>Hope it helps! Cheers :)</p> <p><strong>EDIT 08/16/2014:</strong></p> <p>Because I got a lot a requests similar to this one from friends and other devs, I decided to set up some kind of <em>framework</em> to get up and running with your Arduino projects quickly and easily.</p> <p>This is the <a href="https://github.com/WeAreLeka/Bare-Arduino-Project" rel="noreferrer">Bare Arduino Project</a></p> <p>Hope it could be of any help! If you find bugs or stuff that I could make better, feel free to fill and issue. :)</p>
18,527,659
How can I with mysqli make a query with LIKE and get all results?
<p>This is my code but it dosn't work:</p> <pre><code>$param = &quot;%{$_POST['user']}%&quot;; $stmt = $db-&gt;prepare(&quot;SELECT id,Username FROM users WHERE Username LIKE ?&quot;); $stmt-&gt;bind_param(&quot;s&quot;, $param); $stmt-&gt;execute(); $stmt-&gt;bind_result($id,$username); $stmt-&gt;fetch(); </code></pre> <p>This code it doesn't seem to work. I have searched it a lot. Also it may return more than 1 row. So how can I get all the results even if it returns more than 1 row?</p>
18,527,848
3
3
null
2013-08-30 07:49:06.263 UTC
10
2021-03-16 03:24:55.167 UTC
2021-02-19 10:08:04.337 UTC
null
1,839,439
null
2,493,164
null
1
59
php|sql|mysqli|sql-like
64,039
<p>Here's how you properly fetch the result</p> <pre><code>$param = &quot;%{$_POST['user']}%&quot;; $stmt = $db-&gt;prepare(&quot;SELECT id,username FROM users WHERE username LIKE ?&quot;); $stmt-&gt;bind_param(&quot;s&quot;, $param); $stmt-&gt;execute(); $stmt-&gt;bind_result($id,$username); while ($stmt-&gt;fetch()) { echo &quot;Id: {$id}, Username: {$username}&quot;; } </code></pre> <p>or you can also do:</p> <pre><code>$param = &quot;%{$_POST['user']}%&quot;; $stmt = $db-&gt;prepare(&quot;SELECT id, username FROM users WHERE username LIKE ?&quot;); $stmt-&gt;bind_param(&quot;s&quot;, $param); $stmt-&gt;execute(); $result = $stmt-&gt;get_result(); while ($row = $result-&gt;fetch_assoc()) { echo &quot;Id: {$row['id']}, Username: {$row['username']}&quot;; } </code></pre> <p>I hope you realise I got the answer directly from the manual <a href="https://secure.php.net/manual/en/mysqli-stmt.fetch.php" rel="noreferrer">here</a> and <a href="https://secure.php.net/manual/en/mysqli-stmt.get-result.php" rel="noreferrer">here</a>, which is where you should've gone first.</p>
18,304,516
How to return raw JSON directly from a mongodb query in Java?
<p>I have the following code:</p> <pre><code>@RequestMapping(value = "/envinfo", method = RequestMethod.GET) @ResponseBody public Map getEnvInfo() { BasicQuery basicQuery = new BasicQuery("{_id:'51a29f6413dc992c24e0283e'}", "{'envinfo':1, '_id': false }"); Map envinfo= mongoTemplate.findOne(basicQuery, Map.class, "jvmInfo"); return envinfo; } </code></pre> <p>As you can notice, the code:</p> <ol> <li>Retrieves JSON from MongoDB</li> <li>Converts it to a <code>Map</code> object</li> <li>The <code>Map</code> object is then converted to JSON by Spring MongoData before it is returned to the browser.</li> </ol> <p>Is it possible to directly return the raw json from MongoDb without going through the intermediate conversion steps?</p>
18,327,997
3
0
null
2013-08-18 23:07:07.803 UTC
10
2021-08-12 10:24:23.163 UTC
null
null
null
null
14,316
null
1
29
java|spring|mongodb|spring-data|spring-data-mongodb
37,714
<p>There's two way's you can do this right now:</p> <h3>1. Using the <code>CollectionCallback</code> on <code>MongoTemplate</code></h3> <p>You can use a <code>CollectionCallback</code> to deal with the returned <code>DBObject</code> directly and simply <code>toString()</code> it:</p> <pre><code>template.execute("jvmInfo", new CollectionCallback&lt;String&gt;() { String doInCollection(DBCollection collection) { DBCursor cursor = collection.find(query) return cursor.next().toString() } } </code></pre> <p>Yo'll still get the exception translation into Spring's <code>DataAccessExceptions</code>. Note, that this is slightly brittle as we expect only a single result to be returned for the query but that's probably something you have to take care of when trying to produce a <code>String</code> anyway.</p> <h3>2. Register a <code>Converter</code> from <code>DBObject</code> to <code>String</code></h3> <p>You can implement a Spring <code>Converter</code> to do the <code>toString()</code> for you.</p> <pre><code>class DBObjectToStringConverter implements Converter&lt;DBObject, String&gt; { public String convert(DBObject source) { return source == null ? null : source.toString(); } } </code></pre> <p>You can then either use the XML configuration or override <code>customConversions()</code> to return a <code>new CustomConversions(Arrays.asList(new DBObjectToStringConverter()))</code> to get it registered with your <code>MongoConverter</code>. You can then simply do the following:</p> <pre><code>String result = mongoTemplate.findOne(basicQuery, String.class, "jvmInfo"); </code></pre> <p>I will add the just showed converter to Spring Data MongoDB and register it by default for the upcoming 1.3 GA release and port the fix back to 1.2.x as part of the fix for <a href="https://jira.springsource.org/browse/DATAMONGO-743">DATAMONGO-743</a>.</p>
18,730,940
Aligning text next to a checkbox
<p>Simple question, and undoubtedly an easy solution--I'm just having a lot of trouble finding it despite searching SO and Google for a while. </p> <p>All I'm looking to do is take the snippet of text "<em>I'm interested in an enhanced listing or premium profile, (a member of our team will respond promptly with further information)</em>" and having it aligned to the right of the check box (with the text left aligned), but not wrapping around it like it is now. </p> <p>Here's my <a href="http://jsfiddle.net/VAQeY/" rel="noreferrer">JSFiddle</a></p> <p>Code (using PureCSS for styling):</p> <pre><code>&lt;form class="pure-form pure-form-aligned"&gt; &lt;fieldset&gt; &lt;div class="pure-control-group"&gt; &lt;label for="name"&gt;Product Name&lt;/label&gt; &lt;input id="name" type="text" placeholder="Username"&gt; &lt;/div&gt; &lt;div class="pure-control-group"&gt; &lt;label for="password"&gt;Contact Name&lt;/label&gt; &lt;input id="password" type="text" placeholder="Password"&gt; &lt;/div&gt; &lt;div class="pure-control-group"&gt; &lt;label for="email"&gt;Contact Email&lt;/label&gt; &lt;input id="email" type="email" placeholder="Email Address"&gt; &lt;/div&gt; &lt;div class="pure-control-group"&gt; &lt;label for="foo"&gt;Website&lt;/label&gt; &lt;input id="foo" type="text" placeholder="Enter something here..."&gt; &lt;/div&gt; &lt;div class="pure-control-group"&gt; &lt;label for="foo"&gt;Description:&lt;/label&gt; &lt;textarea id="description" type="text" placeholder="Enter description here..."&gt;&lt;/textarea&gt; &lt;/div&gt; &lt;div class="pure-controls"&gt; &lt;label for="cb" class="pure-checkbox"&gt; &lt;input id="cb" type="checkbox"&gt; I'm interested in an enhanced listing or premium profile, (a member of our team will respond promptly with further information) &lt;/label&gt; &lt;button type="submit" class="pure-button pure-button-primary"&gt;Submit&lt;/button&gt; &lt;/div&gt; &lt;/fieldset&gt; &lt;/form&gt; </code></pre> <p>Any help would be much appreciated. Thanks. </p>
18,731,164
3
0
null
2013-09-11 00:41:02.657 UTC
0
2018-01-25 13:40:32.543 UTC
null
null
null
null
1,200,467
null
1
13
html|css
52,731
<p>Here's a simple way. There are probably others.</p> <pre><code>&lt;input id="cb" type="checkbox" style="float: left; margin-top: 5px;&gt;"&gt; &lt;div style="margin-left: 25px;"&gt; I'm interested in an enhanced listing or premium profile, (a member of our team will respond promptly with further information) &lt;/div&gt; </code></pre> <p>I used a <code>div</code> to "block" structure the text and moved it to the right. The <code>float: left</code> on the <code>input</code> keeps the checkbox to the left of the text (not above). The <code>margin-top</code> on the <code>input</code> tweaks the top alignment with the text.</p> <p>The <a href="http://jsfiddle.net/VAQeY/22" rel="noreferrer">fiddle</a>.</p>
18,438,798
Visual Studio 2012 recent projects not updated in taskbar
<p>I have Visual Studio pinned to the taskbar. When clicking on the icon with the mouse right button, a list of recent projects and solutions in shown.</p> <p>This used to work OK, but from some time now, the list is not being updated. I always see same projects and solutions under <em>Recent</em>, although I have worked with newer projects lately.</p> <p>How can I fix it?</p> <p>I'm running Visual Studio Ultimate 2012 on Windows 8 Pro.</p>
19,423,272
4
4
null
2013-08-26 07:27:09.033 UTC
6
2021-06-16 14:44:33.497 UTC
2013-09-10 21:48:39.07 UTC
null
1,517,883
null
1,517,883
null
1
28
windows|visual-studio|visual-studio-2012
5,659
<ul> <li>Close all VS instance</li> <li>Right click on the Taskbar.</li> <li>Click Properties</li> <li>Go to the Jump Lists Tab</li> <li>Uncheck Store recently opened programs</li> <li>Uncheck Store and display recently opened items in Jump Lists</li> <li>Click Apply/Ok</li> <li>Wait a moment</li> <li>Check Store recently opened programs</li> <li>Check Store and display recently opened items in Jump Lists</li> <li>Wait a moment</li> <li><p>Open your VS solution and it should now appear in the Jump List.</p></li> <li><p>This worked as a fix for VS 2012 professional with Win 8 Pro</p></li> </ul>
26,311,243
Sending SMS programmatically without opening message app
<p>So far I am using the following code to send SMS to another phone through my app.</p> <pre><code>Intent intent = new Intent( Intent.ACTION_VIEW, Uri.parse( "sms:" + srcNumber)); intent.putExtra( "sms_body", message ); startActivity(intent); </code></pre> <p>However, this opens up the native messaging app, thereby putting my app's activity in the background. Is it possible to send the SMS <em>directly</em> without the native messaging app opening up? If yes, how?</p>
26,311,288
6
4
null
2014-10-11 04:58:28.213 UTC
24
2022-01-14 19:00:25.303 UTC
null
null
null
null
2,786,452
null
1
79
android|android-activity
94,223
<p>You can send messages from your application through this:</p> <pre class="lang-java prettyprint-override"><code>public void sendSMS(String phoneNo, String msg) { try { SmsManager smsManager = SmsManager.getDefault(); smsManager.sendTextMessage(phoneNo, null, msg, null, null); Toast.makeText(getApplicationContext(), &quot;Message Sent&quot;, Toast.LENGTH_LONG).show(); } catch (Exception ex) { Toast.makeText(getApplicationContext(),ex.getMessage().toString(), Toast.LENGTH_LONG).show(); ex.printStackTrace(); } } </code></pre> <p>Also, you need to give <code>SEND_SMS</code> permission in <code>AndroidManifest.xml</code> to send a message</p> <p><code>&lt;uses-permission android:name=&quot;android.permission.SEND_SMS&quot; /&gt;</code></p>
51,644,402
I keep getting a message to upgrade pip
<p>Whenever I create a venv, I get a message asking me to upgrade pip. I run the command for upgrade, and it pops up again on another venv. How can I make this permanent.</p> <p>Message:</p> <pre><code>You are using pip version 9.0.1, however version 18.0 is available. You should consider upgrading via the 'python -m pip install --upgrade pip' command. </code></pre> <p>Update: Just received recommendation to read this possible duplicate answer: <a href="https://stackoverflow.com/questions/47059647/virtualenv-use-upgraded-system-default-pip">virtualenv use upgraded system default pip</a></p> <p>This does not solve my issue though. Why?</p> <p>My <code>pip3</code> appears to already be up to date:</p> <pre><code>C:\Users\mkupfer\Python-Sandbox\sibc-python-scripts&gt;pip --version pip 18.0 from c:\users\mkupfer\appdata\local\programs\python\python36-32\lib\sit e-packages\pip (python 3.6) C:\Users\mkupfer\Python-Sandbox\sibc-python-scripts&gt;pip3 --version pip 18.0 from c:\users\mkupfer\appdata\local\programs\python\python36-32\lib\sit e-packages\pip (python 3.6) C:\Users\mkupfer\Python-Sandbox\sibc-python-scripts&gt;pip3 install --upgrade pip Requirement already up-to-date: pip in c:\users\mkupfer\appdata\local\programs\p ython\python36-32\lib\site-packages (18.0) </code></pre> <hr /> <h1>Solved</h1> <p>Solution: I was able to fix this altogether by using <code>virtualenv</code> to create a new virtual environment. Not sure if this is a bug in <code>venv</code>. I'll just use the package that works going forward. Thanks @James Lim for the answer.</p>
51,979,140
6
7
null
2018-08-02 01:45:03.26 UTC
6
2020-08-16 17:24:51.62 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
1,656,488
null
1
24
python|pip|python-venv
44,471
<p>The issue seems to be that <em>new</em> virtual environments are using an old version of pip. Note that pip is installed from a source tarfile (or wheel) included with virtualenv, in the <code>site-packages/virtualenv_support</code> directory.</p> <pre><code>$ ls -l /path/to/site-packages/virtualenv_support pip-9.1-py2.py3-none-any.whl </code></pre> <p>A quick way to workaround the problem is to make sure you upgrade pip whenever you create a new virtualenv, like so:</p> <pre><code>$ virtualenv venv $ venv/bin/pip install -U pip </code></pre> <p>Alternatively, make sure you have the latest version of virtualenv. According to their <a href="https://pypi.org/project/virtualenv/" rel="noreferrer">release notes</a>, <code>virtualenv==16</code> is using <code>pip==10</code>.</p> <pre><code>$ pip install -U virtualenv </code></pre> <p>Finally, since virtualenv looks for <code>pip*.whl</code> in <code>virtualenv_support</code>, this will also work:</p> <pre><code>$ mv /path/to/site-packages/virtualenv_support/pip*.whl{,bak} $ pip wheel -w /path/to/site-packages/virtualenv_support/ 'pip==18' </code></pre> <p>All new virtualenvs will use the version of pip that you installed into <code>virtualenv_support</code>. However, this feels hacky.</p> <p>(Attempted with <code>virtualenv==16</code>. This results in all new virtualenvs with pip==18.)</p>
5,541,493
How do I profile the EDT in Swing?
<p>I have an application that I'm building in Swing. It has a scrollable and zoomable chart component which I can pan and zoom in. The whole thing is smooth except that sometimes the UI will pause for about 750 ms and I don't know why. This doesn't always happen - but sometimes something happens in the application and it starts pausing like this once every 6-8 seconds.</p> <p>It seems pretty clear that there's some event being placed on the EDT that's taking 750 ms or so to run, which shouldn't be happening.</p> <p>How do I profile the EDT specifically like this? What I would really like to do is get something that will output to a log or System.out every time an event runs on the EDT with the total amount of time the event took. Is there a way to do this?</p> <p>Or is there some tool that will do this for me and give me a log of everything that runs on the EDT and how long it takes?</p> <p>I'd like to go through this log, look at everything that's taking a long time, and find the problem.</p>
5,541,779
3
1
null
2011-04-04 16:33:08.573 UTC
9
2016-01-13 19:41:59.887 UTC
2016-01-13 19:41:59.887 UTC
null
452,775
null
300,311
null
1
4
java|swing|profiling|event-dispatch-thread
1,430
<p>Take a look at this <a href="https://stackoverflow.com/questions/3158254/how-to-replace-the-awt-eventqueue-with-own-implementation/3158409#3158409">question</a>. It describes a simple log on the EDT.</p> <p>Create a class like this:</p> <pre><code>public class TimedEventQueue extends EventQueue { @Override protected void dispatchEvent(AWTEvent event) { long startNano = System.nanoTime(); super.dispatchEvent(event); long endNano = System.nanoTime(); if (endNano - startNano &gt; 50000000) System.out.println(((endNano - startNano) / 1000000)+"ms: "+event); } } </code></pre> <p>Then replace the default EventQueue with the custom class:</p> <pre><code>Toolkit.getDefaultToolkit().getSystemEventQueue().push(new TimedEventQueue()); </code></pre>
5,541,745
Get rid of stopwords and punctuation
<p>I'm struggling with NLTK stopword.</p> <p>Here's my bit of code.. Could someone tell me what's wrong?</p> <pre><code>from nltk.corpus import stopwords def removeStopwords( palabras ): return [ word for word in palabras if word not in stopwords.words('spanish') ] palabras = ''' my text is here ''' </code></pre>
5,541,855
3
4
null
2011-04-04 16:53:43.18 UTC
7
2020-03-09 12:01:20.16 UTC
2012-10-26 00:04:49.15 UTC
null
527,702
null
691,484
null
1
10
python|nltk|stop-words
38,199
<p>Your problem is that the iterator for a string returns each character not each word.</p> <p>For example:</p> <pre><code>&gt;&gt;&gt; palabras = &quot;Buenos dias&quot; &gt;&gt;&gt; [c for c in palabras] ['B', 'u', 'e', 'n', 'a', 's', ' ', 'd', 'i', 'a', 's'] </code></pre> <p>You need to iterate and check each word, fortunately the split function already exists in the python standard library under the <a href="http://docs.python.org/release/2.3/lib/module-string.html" rel="noreferrer">string module</a>. However you are dealing with natural language including punctuation you should look <a href="https://stackoverflow.com/questions/1059559/python-strings-split-with-multiple-separators">here</a> for a more robust answer that uses the <code>re</code> module.</p> <p>Once you have a list of words you should lowercase them all before comparison and then compare them in the manner that you have shown already.</p> <p>Buena suerte.</p> <h2>EDIT 1</h2> <p>Okay try this code, it should work for you. It shows two ways to do it, they are essentially identical but the first is a bit clearer while the second is more pythonic.</p> <pre><code>import re from nltk.corpus import stopwords scentence = 'El problema del matrimonio es que se acaba todas las noches despues de hacer el amor, y hay que volver a reconstruirlo todas las mananas antes del desayuno.' #We only want to work with lowercase for the comparisons scentence = scentence.lower() #remove punctuation and split into seperate words words = re.findall(r'\w+', scentence,flags = re.UNICODE | re.LOCALE) #This is the simple way to remove stop words important_words=[] for word in words: if word not in stopwords.words('spanish'): important_words.append(word) print important_words #This is the more pythonic way important_words = filter(lambda x: x not in stopwords.words('spanish'), words) print important_words </code></pre> <p>I hope this helps you.</p>
4,855,789
Programmatically adding items to a relative layout
<p>I have been searching everywhere for an answer to this question. I'm new to Android and attempting to add items to a relative layout programmatically through java instead of xml. I have created a test class to try it out but the items keep stacking instead of formatting correctly. I simply want one TextView under the other for now (eventually I will use the left of and right of parameters but I am starting simple. What am I missing?</p> <pre><code>public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ScrollView sv = new ScrollView(this); RelativeLayout ll = new RelativeLayout(this); ll.setId(99); sv.addView(ll); TextView tv = new TextView(this); tv.setText("txt1"); tv.setId(1); TextView tv2 = new TextView(this); tv2.setText("txt2"); tv2.setId(2); RelativeLayout.LayoutParams lay = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); lay.addRule(RelativeLayout.ALIGN_PARENT_TOP); ll.addView(tv, lay); RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); p.addRule(RelativeLayout.ALIGN_BOTTOM, tv.getId()); ll.addView(tv2, p); this.setContentView(sv);}; </code></pre>
4,855,849
3
0
null
2011-01-31 20:35:26.42 UTC
null
2018-12-05 20:57:35.333 UTC
2018-12-05 20:57:35.333 UTC
null
3,290,339
null
597,436
null
1
17
android|android-layout|android-relativelayout
40,446
<pre><code> p.addRule(RelativeLayout.ALIGN_BOTTOM, tv.getId()); </code></pre> <p>This line means that the the bottom of tv2 is aligned with the bottom of tv- in other words, they will cover each other up. The property you want is presumably <code>RelativeLayout.BELOW</code> . However, I strongly recommend using xml for this instead.</p>
5,021,600
How do I inflate an Android options menu and set an item to Enabled=false?
<p>My XML menu definition sets the item R.id.menu_refresh's enabled state to false. When the app runs the menu item is greyed and disabled. Why is this code in the app not enabling the item?</p> <pre><code>public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main, menu); MenuItem refresh = menu.getItem(R.id.menu_refresh); refresh.setEnabled(true); return true; } </code></pre> <p>What am I missing?</p>
5,021,726
3
0
null
2011-02-16 20:13:40.123 UTC
1
2019-11-22 13:34:29.51 UTC
null
null
null
null
477,415
null
1
17
android
52,530
<p>Try <code>menu.findItem()</code> instead of <code>getItem()</code>. <code>getItem()</code> takes an index from [0, size) while <code>findItem()</code> takes an id.</p>
5,567,249
What are the most common non-BMP Unicode characters in actual use?
<p>In your experience which Unicode characters, codepoints, ranges outside the BMP (Basic Multilingual Plane) are the most common so far? These are the ones which require 4 bytes in UTF-8 or surrogates in UTF-16.</p> <p>I would've expected the answer to be Chinese and Japanese characters used in names but not included in the most widespread CJK multibyte character sets, but on the project I do most work on, the English Wiktionary, we have found that the <a href="http://en.wikipedia.org/wiki/Gothic_alphabet" rel="noreferrer">Gothic alphabet</a> is far more common so far.</p> <p><strong>UPDATE</strong></p> <p>I've written a couple of software tools to scan entire Wikipedias for non-BMP characters and found to my surprise that even in the Japanese Wikipedia Gothic alphabet is the most common. This is also true in the Chinese Wikipedia but it also had many Chinese characters being used up to 50 or 70 times, including "", "", and "".</p>
18,477,578
3
1
null
2011-04-06 13:36:03.823 UTC
26
2022-02-08 23:12:01.867 UTC
2013-05-30 01:13:06.667 UTC
null
527,702
null
527,702
null
1
121
unicode|cjk|codepoint|surrogate-pairs|astral-plane
29,253
<p>Emoji are now the most common non-BMP characters by far. , otherwise known as U+1F602 FACE WITH TEARS OF JOY, is the most common one on Twitter's public stream. It occurs more frequently than the tilde!</p>
18,528,736
How to retrieve values from the last row in a DataTable?
<p>I am having problems retrieving values from the last inserted row in a Data-table. I have a login form and the values will be inserted in the table has the ID (int,an auto incremented value), userID (int), logintime (smalldatetime) and logouttime(smalldatetime). The code which is used to inside the login button,it thus inserts all values except the log out time</p> <pre><code>DateTime t1 = DateTime.Now; objbal2.insertLoginTime(s, t1); </code></pre> <p>and in the log out button I am updating the table, so I have to retrieve the last row values. I am updating the table with reference to the ID value and userID. Can I use this query get the values? But I can't figure out how?</p> <pre><code>SELECT COLUMN FROM TABLE ORDER BY COLUMN DESC </code></pre> <p>Thanks in advance</p>
18,528,844
4
3
null
2013-08-30 08:51:32.373 UTC
3
2018-03-27 07:17:40.43 UTC
2013-08-30 10:36:21.397 UTC
null
2,563,961
null
2,582,336
null
1
15
c#|asp.net|sql|datatable|datarow
91,384
<p>if you have to read the values from last row then</p> <pre><code>DataRow lastRow = yourTable.Rows[yourTable.Rows.Count-1]; </code></pre> <p>will return you last row. and you can read the values from it.</p> <p>My second guess is that by datatable you are referring to table in sql server. </p> <p>Then with small modification your query is fine as well.</p> <pre><code>SELECT TOP 1 COLUMN FROM TABLE ORDER BY COLUMN DESC </code></pre>
14,944,778
facing perm gen space error in weblogic
<p>I am new to weblogic. After starting the server when i see administrator console and get log-in it throws below exception.</p> <pre><code>Root cause of ServletException. java.lang.OutOfMemoryError: PermGen space at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:791) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) at weblogic.utils.classloaders.GenericClassLoader.defineClass(GenericClassLoader.java:335) at weblogic.utils.classloaders.GenericClassLoader.findLocalClass(GenericClassLoader.java:288) Truncated. see log file for complete stacktrace </code></pre> <p>I did lot of google and found some solution to initialize <code>JAVA_OPTIONS</code> like <code>-XX:xmx</code> and etc. I tried to set this in <code>startdomainenv.cmd</code> file but with no luck.</p> <p>Please help. Any pointers will be highly appreciated.</p> <p>Thanks.</p>
14,948,072
5
1
null
2013-02-18 20:30:07.957 UTC
3
2015-04-21 05:40:24.807 UTC
2013-02-19 01:01:24.847 UTC
null
772,000
null
1,409,913
null
1
12
java|garbage-collection|weblogic
49,822
<p>To set <strong>PermGen</strong> size you can use e.g. <code>-XX:PermSize=512m -XX:MaxPermSize=512m</code>.</p> <p>Regarding <strong>Weblogic</strong>, set the JAVA_OPTIONS and see if these options are properly passed in as parameters into your Java process. You can also directly set these parameters in the <code>startWeblogic.cmd</code> script.</p> <p>To check that your <code>JAVA_OPTIONS</code> are set properly, add <code>echo %JAVA_OPTIONS%</code> into the <code>startWeblogic.cmd</code> script and see the output. Also, you can use e.g. <strong>jConsole</strong>, <strong>jstat</strong>, or <strong>jmap</strong> to monitor Heap usage of the Weblogic process at runtime. This will show you the sizes and occupation of the <strong>PermGen</strong>.</p>
15,455,042
Can anyone explain the deletion of Left-Lean-Red-Black tree clearly?
<p>I am learning <code>Left-Lean-Red-Black tree</code>, from <code>Prof.Robert Sedgewick</code></p> <p><a href="http://www.cs.princeton.edu/~rs/talks/LLRB/LLRB.pdf">http://www.cs.princeton.edu/~rs/talks/LLRB/LLRB.pdf</a> <a href="http://www.cs.princeton.edu/~rs/talks/LLRB/RedBlack.pdf">http://www.cs.princeton.edu/~rs/talks/LLRB/RedBlack.pdf</a></p> <p>While I got to understand the <code>insert</code> of the <code>2-3 tree</code> and the <code>LLRB</code>, I have spent totally like 40 hours now for 2 weeks and I still can't get the deletion of the LLRB.</p> <p>Can anyone really explain the <code>deletion</code> of <code>LLRB</code> to me?</p>
15,457,209
3
1
null
2013-03-16 21:44:39.607 UTC
12
2020-09-16 10:44:42.32 UTC
2013-03-16 21:50:02.317 UTC
null
759,076
null
759,076
null
1
20
algorithm|data-structures|red-black-tree
5,123
<p>Ok I am going to try this, and maybe the other good people of SO can help out. You know how one way of thinking of red nodes is as indicators of </p> <ol> <li>where there there imbalance/new nodes in the tree, and</li> <li>how much imbalance there is. </li> </ol> <p>This is why all new nodes are red. When the nodes (locally) balance out, they undergo a color flip, and the redness is passed up to the parent, and now the parent may look imbalanced relative to its sibling. </p> <p>As an illustration, consider a situation where you are adding nodes from larger to smaller. You start with node Z which is now root and is black. You add node Y, which is red and is a left child of Z. You add a red X as a child of Z, but now you have two successive reds, so you rotate right, recolor, and you have a balanced, all black (no imbalance/"new nodes"!) tree rooted at Y [first drawing]. Now you add W and V, in that order. At first they are both red [second drawing], but immediately V/X/W are rotated right, and color flipped, so that only X is red [third drawing]. This is important: X being red indicates that left subtree of Y is unbalanced by 2 nodes, or, in other words, there are two new nodes in the left subtree. So the height of the red links is the count of new, potentially unbalanced nodes: there are 2^height of new nodes in the red subtree.</p> <p><img src="https://i.stack.imgur.com/k1j0X.png" alt="enter image description here"></p> <p>Note how when adding nodes, the redness is always passed up: in color flip, two red children become black (=locally balanced) while coloring their parent red. Essentially what the deletion does, is reverse this process. Just like a new node is red, we always also want to delete a red node. If the node isn't red, then we want to make it red first. This can be done by a color flip (incidentally, this is why color flip in the code on page 3 is actually color-neutral). So if the child we want to delete is black, we can make it red by color-flipping its parent. Now the child is guaranteed to be red.</p> <p>The next problem to deal with is the fact that when we start the deletion we don't know if the target node to be deleted is red or not. One strategy would be to find out first. However, according to my reading of your first reference, the strategy chosen there is to ensure that the deleted node can be made red, by "pushing" a red node down in front of the search node as we are searching down the tree for the node to be deleted. This may create unnecessary red nodes that <code>fixUp()</code> procedure will resolve on the way back up the tree. <code>fixUp()</code> presumably maintains the usual LLRBT invariants: "no successive red nodes" and "no right red nodes."</p> <p>Not sure if that helps, or if we need to get into more detailed examination of code.</p>
15,010,761
How to check if a cursor is empty?
<p>When I'm trying to get the phone numbers from the contact list of the phone. The problem is, when I'm running the app while the contact list in the phone is empty, the app is stopped. I checked it and this is because the cursor is empty.</p> <p>How can I check if the cursor is empty or if there are any contacts in the contact list of the phone?</p> <pre><code>ArrayList&lt;String&gt; lstPhoneNumber = new ArrayList&lt;String&gt;(); Cursor phones = getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null); lstPhoneNumber = new ArrayList&lt;String&gt;(); phones.moveToFirst(); // The problematic Line: lstPhoneNumber.add(phones.getString(phones.getColumnIndex( ContactsContract.CommonDataKinds.Phone.NUMBER))); while (phones.moveToNext()) { lstPhoneNumber.add(phones.getString(phones.getColumnIndex( ContactsContract.CommonDataKinds.Phone.NUMBER))); } phones.close(); </code></pre>
15,010,976
7
2
null
2013-02-21 19:37:42.517 UTC
5
2021-12-23 04:00:10.477 UTC
2021-12-23 04:00:10.477 UTC
user1521536
4,294,399
null
2,082,636
null
1
25
android|android-contacts|android-cursor
50,032
<p>I added in a projection so you are only getting the column you need.</p> <pre><code>String[] projection = new String[] { ContactsContract.CommonDataKinds.Phone.NUMBER }; ArrayList&lt;String&gt; lstPhoneNumber = new ArrayList&lt;String&gt;(); Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection, null, null, null); if (phones == null) return; // can't do anything with a null cursor. try { while (phones.moveToNext()) { lstPhoneNumber.add(phones.getString(0)); } } finally { phones.close(); } </code></pre>
15,025,876
What is an index in Elasticsearch
<p>What is an index in Elasticsearch? Does one application have multiple indexes or just one?</p> <p>Let's say you built a system for some car manufacturer. It deals with people, cars, spare parts, etc. Do you have one index named manufacturer, or do you have one index for people, one for cars and a third for spare parts? Could someone explain?</p>
15,026,433
4
0
null
2013-02-22 13:59:04.553 UTC
18
2020-07-02 00:19:57.177 UTC
2020-07-02 00:19:57.177 UTC
null
1,402,846
null
454,049
null
1
35
java|ruby|elasticsearch|full-text-search
16,784
<p>Good question, and the answer is a lot more nuanced than one might expect. You can use indices for several different purposes.</p> <h2>Indices for Relations</h2> <p>The easiest and most familiar layout clones what you would expect from a relational database. You can (very roughly) think of an index like a database.</p> <ul> <li>MySQL => Databases => Tables => Rows/Columns</li> <li>ElasticSearch => Indices => Types => Documents with Properties</li> </ul> <p>An ElasticSearch cluster can contain multiple <code>Indices</code> (databases), which in turn contain multiple <code>Types</code> (tables). These types hold multiple <code>Documents</code> (rows), and each document has <code>Properties</code> (columns).</p> <p>So in your car manufacturing scenario, you may have a <code>SubaruFactory</code> index. Within this index, you have three different types:</p> <ul> <li><code>People</code></li> <li><code>Cars</code></li> <li><code>Spare_Parts</code></li> </ul> <p>Each type then contains documents that correspond to that type (e.g. a Subaru Imprezza doc lives inside of the <code>Cars</code> type. This doc contains all the details about that particular car).</p> <p>Searching and querying takes the format of: <a href="http://localhost:9200/[index]/[type]/[operation]" rel="noreferrer">http://localhost:9200/[index]/[type]/[operation]</a></p> <p>So to retrieve the Subaru document, I may do this:</p> <pre><code> $ curl -XGET localhost:9200/SubaruFactory/Cars/SubaruImprezza </code></pre> <p>.</p> <h2>Indices for Logging</h2> <p>Now, the reality is that Indices/Types are much more flexible than the Database/Table abstractions we are used to in RDBMs. They can be considered convenient data organization mechanisms, with added performance benefits depending on how you set up your data.</p> <p>To demonstrate a radically different approach, a lot of people use ElasticSearch for logging. A standard format is to assign a new index for each day. Your list of indices may look like this:</p> <ul> <li>logs-2013-02-22</li> <li>logs-2013-02-21</li> <li>logs-2013-02-20</li> </ul> <p>ElasticSearch allows you to query multiple indices at the same time, so it isn't a problem to do:</p> <pre><code> $ curl -XGET localhost:9200/logs-2013-02-22,logs-2013-02-21/Errors/_search=q:"Error Message" </code></pre> <p>Which searches the logs from the last two days at the same time. This format has advantages due to the nature of logs - most logs are never looked at and they are organized in a linear flow of time. Making an index per log is more logical and offers better performance for searching.</p> <p>.</p> <h2>Indices for Users</h2> <p>Another radically different approach is to create an index per user. Imagine you have some social networking site, and each users has a large amount of random data. You can create a single index for each user. Your structure may look like:</p> <ul> <li>Zach's Index <ul> <li>Hobbies Type</li> <li>Friends Type</li> <li>Pictures Type</li> </ul></li> <li>Fred's Index <ul> <li>Hobbies Type</li> <li>Friends Type</li> <li>Pictures Type</li> </ul></li> </ul> <p>Notice how this setup could easily be done in a traditional RDBM fashion (e.g. "Users" Index, with hobbies/friends/pictures as types). All users would then be thrown into a single, giant index.</p> <p>Instead, it sometimes makes sense to split data apart for data organization and performance reasons. In this scenario, we are assuming each user has <em>a lot</em> of data, and we want them separate. ElasticSearch has no problem letting us create an index per user.</p>
15,016,723
Create categories by comparing a numeric column with a fixed value
<p>Consider the <code>iris</code> data:</p> <pre><code> iris Sepal.Length Sepal.Width Petal.Length Petal.Width Species 1 5.1 3.5 1.4 0.2 setosa 2 4.9 3.0 1.4 0.2 setosa 3 4.7 3.2 1.3 0.2 setosa 4 4.6 3.1 1.5 0.2 setosa 5 5.0 3.6 1.4 0.2 setosa 6 5.4 3.9 1.7 0.4 setosa 7 4.6 3.4 1.4 0.3 setosa </code></pre> <p>I want to create a new column based on a comparison of the values in variable <code>Sepal.Length</code> with a fixed limit / cut-off, e.g. check if the values are larger or smaller than 5:</p> <p><code>if Sepal.Length &gt;= 5 assign &quot;UP&quot; else assign &quot;DOWN&quot;</code> to a new column &quot;Regulation&quot;.</p> <p>What's the way to do that?</p>
15,016,790
3
0
null
2013-02-22 04:14:29.027 UTC
12
2020-09-08 12:02:37.043 UTC
2020-09-08 12:02:37.043 UTC
null
1,851,712
null
67,405
null
1
40
r|dataframe
115,129
<p>Try</p> <pre><code>iris$Regulation &lt;- ifelse(iris$Sepal.Length &gt;=5, "UP", "DOWN") </code></pre>
15,017,188
Difference between WebApiConfig.cs and RouteConfig.cs
<p>What is the difference between <code>WebApiConfig.cs</code> and <code>RouteConfig.cs</code> in the <code>App_Start</code> folder of an MVC Web API project in Visual Studio 2012?</p>
15,017,396
3
0
null
2013-02-22 05:01:18.447 UTC
3
2018-05-04 08:32:05.863 UTC
2018-05-04 08:32:05.863 UTC
null
179,669
null
1,065,358
null
1
45
asp.net-mvc|asp.net-mvc-4|asp.net-web-api
41,248
<p>The following are the key differences:</p> <ol> <li>RouteConfig.cs is exclusively for configuring ASP.NET routes.</li> <li>WebApiConfig.cs is for any Web API related configuration, including Web-API-specific routes, Web API services, and other Web API settings.</li> </ol> <p>As cmotley mentions, the ASP.NET web site includes a good listing of what types of configuration can be done in WebApiConfig.cs in <a href="http://www.asp.net/web-api/overview/extensibility/configuring-aspnet-web-api" rel="noreferrer">this article</a>.</p>
15,385,696
Adjust the output width of R Markdown HTML output
<p>I am producing an HTML output but I am having issues with the output width of R code output.</p> <p>I'm able to adjust the figure width with no difficulty but when I try to write a data table or the factor loadings, R is outputting at a fixed width which is only about a third of my screen width. This results in the columns of the table being split up rather than all of the columns displayed in a single table.</p> <p>Here is a reproducible example:</p> <pre><code>--- output: html_document --- # Title ```{r echo = FALSE, fig.width=16, fig.height=6} x = matrix(rnorm(100),ncol=10) x plot(x) ``` </code></pre> <p><a href="https://i.stack.imgur.com/gPLR4.png" rel="noreferrer"><img src="https://i.stack.imgur.com/gPLR4.png" alt="enter image description here"></a></p>
15,386,154
2
4
null
2013-03-13 12:43:34.947 UTC
15
2020-05-21 14:26:16.723 UTC
2018-10-01 09:32:26.933 UTC
null
7,347,699
null
1,105,773
null
1
78
r-markdown|knitr
86,748
<p>Add this at the start of your document:</p> <pre><code>```{r set-options, echo=FALSE, cache=FALSE} options(width = SOME-REALLY-BIG-VALUE) ``` </code></pre> <p>Obviously, replace SOME-REALLY-BIG-VALUE with a number. But do you really want to do all that horizontal scrolling?</p> <p>Your output is probably being wrapped somewhere around 80 characters or so. </p>
7,806,689
Instrumenting C/C++ code using LLVM
<p>I want to write a LLVM pass to instrument every memory access. Here is what I am trying to do.</p> <p>Given any C/C++ program (like the one given below), I am trying to insert calls to some function, before and after every instruction that reads/writes to/from memory. For example consider the below C++ program (Account.cpp)</p> <pre><code>#include &lt;stdio.h&gt; class Account { int balance; public: Account(int b) { balance = b; } ~Account(){ } int read() { int r; r = balance; return r; } void deposit(int n) { balance = balance + n; } void withdraw(int n) { int r = read(); balance = r - n; } }; int main () { Account* a = new Account(10); a-&gt;deposit(1); a-&gt;withdraw(2); delete a; } </code></pre> <p>So after the instrumentation my program should look like :</p> <pre><code>#include &lt;stdio.h&gt; class Account { int balance; public: Account(int b) { balance = b; } ~Account(){ } int read() { int r; foo(); r = balance; foo(); return r; } void deposit(int n) { foo(); balance = balance + n; foo(); } void withdraw(int n) { foo(); int r = read(); foo(); foo(); balance = r - n; foo(); } }; int main () { Account* a = new Account(10); a-&gt;deposit(1); a-&gt;withdraw(2); delete a; } </code></pre> <p>where foo() may be any function like get the current system time or increment a counter .. so on. </p> <p>Please give me examples (source code, tutorials etc) and steps on how to run it. I have read the tutorial on how make a LLVM Pass given on <a href="http://llvm.org/docs/WritingAnLLVMPass.html" rel="noreferrer">http://llvm.org/docs/WritingAnLLVMPass.html</a>, but couldn't figure out how write a pass for the above problem.</p>
8,571,428
2
8
null
2011-10-18 11:45:59.71 UTC
8
2011-12-20 06:03:20.917 UTC
2011-10-18 11:48:08.097 UTC
null
560,648
null
960,714
null
1
12
c++|c|static-analysis|instrumentation
5,871
<p>Try something like this: ( you need to fill in the blanks and make the iterator loop work despite the fact that items are being inserted )</p> <pre><code>class ThePass : public llvm::BasicBlockPass { public: ThePass() : BasicBlockPass() {} virtual bool runOnBasicBlock(llvm::BasicBlock &amp;bb); }; bool ThePass::runOnBasicBlock(BasicBlock &amp;bb) { bool retval = false; for (BasicBlock::iterator bbit = bb.begin(), bbie = bb.end(); bbit != bbie; ++bbit) { // Make loop work given updates Instruction *i = bbit; CallInst * beforeCall = // INSERT THIS beforeCall-&gt;insertBefore(i); if (!i-&gt;isTerminator()) { CallInst * afterCall = // INSERT THIS afterCall-&gt;insertAfter(i); } } return retval; } </code></pre> <p>Hope this helps!</p>
7,729,734
How to disable ActionMailer in Development?
<p>sometimes when I am developing, I do not have an internet connection. This results in an error wherever my app is supposed to send an email:</p> <pre><code>getaddrinfo: nodename nor servname provided, or not known </code></pre> <p>Is there a simple and quick way where i can change a config value to make ActionMailer just not try to actually send out an email and not throw an error? Maybe something thats scoped to the development environment. Or some other way I can avoid the error being thrown and my code passing wherever I call the actionmailer deliver?</p> <p>I'm using Rails 3.1</p>
7,729,789
2
0
null
2011-10-11 17:03:50.573 UTC
8
2014-11-17 23:12:52.143 UTC
2013-06-16 07:45:03.103 UTC
null
2,139,766
null
860,844
null
1
31
ruby-on-rails|ruby-on-rails-3.1|environment-variables|actionmailer
18,372
<p>It's common practice to just let Rails ignore the mail errors. In your <code>config/environments/development.rb</code> file add, uncomment or modify:</p> <pre><code># Don't care if the mailer can't send config.action_mailer.raise_delivery_errors = false </code></pre> <p>You can also set this:</p> <pre><code>config.action_mailer.perform_deliveries = false </code></pre> <p>See the documentation here <a href="http://edgeguides.rubyonrails.org/action_mailer_basics.html#action-mailer-configuration" rel="noreferrer">http://edgeguides.rubyonrails.org/action_mailer_basics.html#action-mailer-configuration</a></p> <p>You can also set the delivery method to :test, but I have not actually tried that</p> <pre><code>config.action_mailer.delivery_method = :test </code></pre>
8,048,564
FB.getLoginStatus() called before calling FB.init() error in console
<p>I am trying to check if a user is logged in with my app, but I am getting a </p> <blockquote> <p>FB.getLoginStatus() called before calling FB.init().</p> </blockquote> <p>error in the console. The <code>setSize</code> appears to work (although not entirely 1,710 height but definitely around 1,500) so I cannot understand why the <code>getLoginStatus()</code> gives the error.</p> <p>I also double checked with the appID (removed below) and that is definitely correct. The script is included via <code>&lt;script src="file.js" type="text/javascript"&gt;&lt;/script&gt;</code> right below my <code>&lt;body&gt;</code> and <code>&lt;div id="fb-root"&gt;&lt;/div&gt;</code> div.</p> <pre><code>window.fbAsyncInit = function() { FB.init({ appId : 'APPID', // App ID status : true, // check login status cookie : true, // enable cookies to allow the server to access the session oauth : true, // enable OAuth 2.0 xfbml : true // parse XFBML }); FB.Canvas.setSize({width: 520, height: 1710}); FB.Canvas.setAutoResize(100); FB.getLoginStatus(function(response) { if (response.authResponse) { // logged in and connected user, someone you know alert("?"); } else { // no user session available, someone you dont know alert("asd"); } }); }; </code></pre>
8,049,831
2
2
null
2011-11-08 09:53:36.463 UTC
6
2019-05-17 00:23:38.343 UTC
2019-05-17 00:23:38.343 UTC
null
3,490,817
null
1,025,234
null
1
40
javascript|facebook
51,962
<p>You need to load the api asynchronously. Try removing your <code>&lt;script src="connect.facebook.net/en_US/all.js"&gt;&lt;/script&gt;</code> and updating your JS to:</p> <pre><code>&lt;div id="fb-root"&gt;&lt;/div&gt; &lt;script&gt; window.fbAsyncInit = function() { FB.init({ appId : 'YOUR_APP_ID', // App ID channelURL : '//WWW.YOUR_DOMAIN.COM/channel.html', // Channel File status : true, // check login status cookie : true, // enable cookies to allow the server to access the session oauth : true, // enable OAuth 2.0 xfbml : true // parse XFBML }); // // All your canvas and getLogin stuff here // }; // Load the SDK Asynchronously (function(d){ var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;} js = d.createElement('script'); js.id = id; js.async = true; js.src = "//connect.facebook.net/en_US/all.js"; d.getElementsByTagName('head')[0].appendChild(js); }(document)); &lt;/script&gt; </code></pre> <p>Oh and check the <a href="https://developers.facebook.com/docs/reference/javascript/" rel="noreferrer">documentation</a>!</p>
60,096,258
Library not loaded: @rpath/FBLPromises.framework/FBLPromises iOS 13.3.1
<p>My app crashes on lunch and getting this error:</p> <pre><code>dyld: Library not loaded: @rpath/FBLPromises.framework/FBLPromises Referenced from: /private/var/containers/Bundle/Application/11X3EC15-5A16-4E27-AC4A-FB0503E6F1E2/Zeta.app/Zeta Reason: no suitable image found. Did find: /private/var/containers/Bundle/Application/11X3EC15-5A16-4E27-AC4A-FB0503E6F1E2/Zeta.app/Frameworks/FBLPromises.framework/FBLPromises: code signature invalid for '/private/var/containers/Bundle/Application/11X3EC15-5A16-4E27-AC4A-FB0503E6F1E2/Zeta.app/Frameworks/FBLPromises.framework/FBLPromises' /private/var/containers/Bundle/Application/11X3EC15-5A16-4E27-AC4A-FB0503E6F1E2/Zeta.app/Frameworks/FBLPromises.framework/FBLPromises: stat() failed with errno=25 /private/var/containers/Bundle/Application/11X3EC15-5A16-4E27-AC4A-FB0503E6F1E2/Zeta.app/Frameworks/FBLPromises.framework/FBLPromises: code signature invalid for '/private/var/containers/Bundle/Application/11X3EC15-5A16-4E27-AC4A-FB0503E6F1E2/Zeta.app/Frameworks/FBLPromises.framework/FBLPromises' /private/var/containers/Bundle/Application/11X3EC15-5A16-4E27-AC4A-FB0503E6F1E2/Zeta.app/Frameworks/FBLPromises.framework/FBLPromises: stat() failed with errno=1 /private/var/containers/Bundle/Application/11X3EC15-5A16-4E27-AC4A-FB0503E6F1E2/Zeta.app/Frameworks/FBLPromises.framework/FBLPromises: code signature invalid for '/private/var/containers/Bundle/Application/11X3EC15-5A16-4E27-AC4A-FB0503E6F1E2/Zeta.app/Frameworks/FBLPromises.framework/FBLPromises' /private/var/containers/Bundle/Application/11X3EC15-5A16-4E27-AC4A-FB0503E6F1E2/Zeta.app/Frameworks/FBLPromises.framework/FBLPromises: stat() failed with errno=1 (lldb) </code></pre> <p>I used it on my own device (iPhone 11 pro) <strong>iOS 13.3.1</strong>. It was working perfectly fine before I update my device to iOS 13.3.1 . My app also works perfectly fine on the simulator (iPhone 11 - iOS 13.3). Using <strong>Xcode 11.3.1</strong>.</p> <p>Removing the profile from my device and trusting again didn't work.</p> <p><strong>UPDATE:</strong> Tried to build it using <strong>Xcode Beta 11.4</strong> and didn't work.</p> <p><strong>UPDATE II:</strong> </p> <ul> <li>The only pods that I'm using are <code>Firebase/Auth, Firebase/Core, Firebase/Firestore</code>.</li> <li>Commenting <code>use_frameworks!</code> and using <code>use_modular_headers!</code> gave me these errors: <code>Showing Recent Issues The iOS deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 4.3, but the range of supported deployment target versions is 8.0 to 13.2.99.</code> (For all the pods in the project)</li> </ul>
60,101,963
12
8
null
2020-02-06 13:36:38.64 UTC
8
2020-05-14 13:51:09.37 UTC
2020-02-21 14:13:43.677 UTC
null
6,458,677
null
6,458,677
null
1
42
ios|xcode|firebase|ios13.3
21,532
<p>You are probably using free developer account. Apple blocked utilizing external frameworks on free accounts with 13.3.1 upgrade. Try downgrading to 13.3 if still possible or buy Apple Developer License.</p> <p>UPDATE 04/2020: Upgrading to iOS 13.4 and XCode 11.4 currently solves this issue.</p>
14,751,688
NameError: global name 'NAME' is not defined
<p>I have been having an interesting time building a little web scraper and I think I am doing something wrong with my variable or function scope. Whenever I try to pull out some of the functionality into separate functions it gives me the NameError: global name 'NAME' is not defined. I see that a lot of people are having a similar problem but there seems to be a lot of variation with the same error and I can't figure it out.</p> <pre><code>import urllib2, sys, urlparse, httplib, imageInfo from BeautifulSoup import BeautifulSoup from collections import deque global visited_pages visited_pages = [] global visit_queue visit_queue = deque([]) global motorcycle_pages motorcycle_pages = [] global motorcycle_pics motorcycle_pics = [] global count count = 0 def scrapePages(url): #variables max_count = 20 pic_num = 20 #decide how long it should go on... global count if count &gt;= max_count: return #this is all of the links that have been scraped the_links = [] soup = soupify_url(url) #find all the links on the page for tag in soup.findAll('a'): the_links.append(tag.get('href')) visited_pages.append(url) count = count + 1 print 'number of pages visited' print count links_to_visit = the_links # print 'links to visit' # print links_to_visit for link in links_to_visit: if link not in visited_pages: visit_queue.append(link) print 'visit queue' print visit_queue while visit_queue: link = visit_queue.pop() print link scrapePages(link) print '***done***' the_url = 'http://www.reddit.com/r/motorcycles' #call the function scrapePages(the_url) def soupify_url(url): try: html = urllib2.urlopen(url).read() except urllib2.URLError: return except ValueError: return except httplib.InvalidURL: return except httplib.BadStatusLine: return return BeautifulSoup.BeautifulSoup(html) </code></pre> <p>Here is my trackback:</p> <pre><code>Traceback (most recent call last): File "C:\Users\clifgray\Desktop\Mis Cosas\Programming\appengine\web_scraping\src\test.py", line 68, in &lt;module&gt; scrapePages(the_url) File "C:\Users\clifgray\Desktop\Mis Cosas\Programming\appengine\web_scraping\src\test.py", line 36, in scrapePages soup = soupify_url(url) NameError: global name 'soupify_url' is not defined </code></pre>
14,751,969
1
3
null
2013-02-07 12:59:01.02 UTC
1
2013-02-07 13:22:52.76 UTC
2013-02-07 13:06:20.403 UTC
null
1,352,749
null
1,352,749
null
1
2
python|function|web-scraping|nameerror
42,031
<p>Move your main code:</p> <pre><code>the_url = 'http://www.reddit.com/r/motorcycles' #call the function scrapePages(the_url) </code></pre> <p>After the point where you define <code>soupify_url</code>, ie. the bottom of your file. </p> <p>Python is reading that def <code>scrapePages()</code> is defined, then it tries to call it; <code>scrapePages()</code> wants to call a function called <code>soupify_url()</code> which has not yet been defined thus you're getting a:</p> <pre><code>NameError: global name 'soupify_url' is not defined </code></pre> <p>Keep in mind the rule: <em>All functions must be defined before any code that does real work</em></p> <p>If you move your main code calling <code>scrapePages()</code> to after the definition of <code>soupify_url()</code> everything will be defined and in scope, should resolve your error.</p>
8,615,530
Place title of multiplot panel with ggplot2
<p>From the help found here I've managed to create this multiplot panel: <img src="https://i.stack.imgur.com/wzDu2.png" alt="enter image description here"> with the following code:</p> <pre><code>library(zoo) library(ggplot2) datos=read.csv("paterna.dat",sep=";",header=T,na.strings="-99.9") datos$dia=as.POSIXct(datos[,1], format="%y/%m/%d %H:%M:%S") datos$Precipitación[is.na(datos$Precipitación)]=0 xlim = as.POSIXct(c("2010-05-12 00:00:00", "2010-05-12 23:50:00")) ylim = trunc(max(datos$Precipitación) + 5) tmax = trunc(max(datos$Temperatura) + 5) tmin = trunc(min(datos$Temperatura) - 5) tmx = max(datos$Temperatura) tmxpos=which.max(datos$Temperatura) tmn = min(datos$Temperatura) tmnpos=which.min(datos$Temperatura) tmp=ggplot(data=datos,aes(x=dia, y=Temperatura)) + geom_line(colour="red") + ylab("Temperatura (ºC)") + xlab(" ") + scale_x_datetime(limits=xlim ,format = "%H",major='hour') + scale_y_continuous(limits = c(tmin,tmax)) + geom_text(data=datos[tmxpos,], label=tmx, vjust=-1.5, colour="red") + geom_text(data=datos[tmnpos,], label=tmn, vjust=1.5, colour="blue") pre=ggplot(data=datos,aes(x=dia, y=Precipitación)) + geom_bar(colour="blue",stat="identity",fill="blue") + ylab("Precipitación (l)") + xlab("Hora solar") + scale_x_datetime(limits=xlim ,format = "%H",major='hour') + scale_y_continuous(limits=c(0,ylim)) vel=ggplot(data=datos,aes(x=dia, y=Velocidad)) + geom_line(colour="brown") + ylab("Velocidad (km/h)") + xlab(" ") + scale_x_datetime(limits=xlim ,format = "%H",major='hour') + scale_y_continuous(limits = c(0,100)) dir=ggplot(data=datos,aes(x=dia, y=Dirección)) + geom_line(colour="brown") + ylab("Dirección viento (grados)") + xlab(" ") + scale_x_datetime(limits=xlim ,format = "%H",major='hour') + scale_y_continuous(limits = c(0,360)) hum=ggplot(data=datos,aes(x=dia, y=Humedad.Relativa)) + geom_line(colour="blue") + ylab("Humedad relativa (%)") + xlab(" ") + scale_x_datetime(limits=xlim ,format = "%H",major='hour') + scale_y_continuous(limits = c(0,100)) grid.newpage() pushViewport(viewport(layout = grid.layout(3, 2))) print(tmp, vp = viewport(layout.pos.row = 1, layout.pos.col = 1)) print(vel, vp = viewport(layout.pos.row = 1, layout.pos.col = 2)) print(dir, vp = viewport(layout.pos.row = 2, layout.pos.col = 2)) print(hum, vp = viewport(layout.pos.row = 2, layout.pos.col = 1)) print(pre, vp = viewport(layout.pos.row = 3, layout.pos.col = 1:2)) </code></pre> <p>Now I'm missing the title of the multiplot that I want to be the met. station name. I haven't found how to set main title on grid.newpage or viewport. I've read about grid.arrange but couldn't figure out how to use it in my case.</p> <p>How can this be done? For sure it's gonna be an easy question for you.</p> <p>You can find source data in <a href="http://ubuntuone.com/4G01ifn7cJ1jMIOKh">http://ubuntuone.com/4G01ifn7cJ1jMIOKh</a></p> <p>Thanks in advance</p> <p><strong>UPDATE</strong>: Thanks to koshke I found the solution. The working code is:</p> <pre><code>grid.newpage() pushViewport(viewport(layout = grid.layout(4, 2, heights = unit(c(0.5, 5, 5, 5), "null")))) grid.text("MAIN TITLE", vp = viewport(layout.pos.row = 1, layout.pos.col = 1:2)) print(tmp, vp = viewport(layout.pos.row = 2, layout.pos.col = 1)) print(vel, vp = viewport(layout.pos.row = 2, layout.pos.col = 2)) print(dir, vp = viewport(layout.pos.row = 3, layout.pos.col = 2)) print(hum, vp = viewport(layout.pos.row = 3, layout.pos.col = 1)) print(pre, vp = viewport(layout.pos.row = 4, layout.pos.col = 1:2)) </code></pre>
8,615,924
3
4
null
2011-12-23 11:27:38.137 UTC
15
2022-08-19 15:18:02.7 UTC
2012-06-02 18:54:08.363 UTC
null
322,283
null
709,777
null
1
29
r|ggplot2
37,082
<p>If I understand correctly what you want to do, probably you can use <code>+opts(title = XXX)</code>:</p> <pre><code>p1 &lt;- ggplot(mtcars, aes(factor(cyl))) + geom_bar() p2 &lt;- ggplot(mtcars, aes(wt, mpg)) + geom_point() p3 &lt;- p2 + geom_line() pushViewport(viewport(layout = grid.layout(2, 2))) print(p1 + opts(title = "bar"), vp = viewport(layout.pos.row = 1, layout.pos.col = 1)) print(p2 + opts(title = "point"), vp = viewport(layout.pos.row = 1, layout.pos.col = 2)) print(p3 + opts(title = "point and line"), vp = viewport(layout.pos.row = 2, layout.pos.col = 1:2)) </code></pre> <p><img src="https://i.stack.imgur.com/5K83y.png" alt="enter image description here"></p> <p><strong>UPDATED</strong></p> <p>here is an example:</p> <pre><code>pushViewport(viewport(layout = grid.layout(3, 2, heights = unit(c(1, 4, 4), "null")))) grid.text("title of this panel", vp = viewport(layout.pos.row = 1, layout.pos.col = 1:2)) print(p1, vp = viewport(layout.pos.row = 2, layout.pos.col = 1)) print(p2, vp = viewport(layout.pos.row = 2, layout.pos.col = 2)) print(p3, vp = viewport(layout.pos.row = 3, layout.pos.col = 1:2)) </code></pre> <p>what you need to do is:</p> <ol> <li>Make one extra row in grid.layout</li> <li>Adjust width</li> <li>Draw textGrob on the extra viewport row.</li> </ol> <p><img src="https://i.stack.imgur.com/yejQ2.png" alt="enter image description here"></p>
9,012,008
python's re: return True if string contains regex pattern
<p>I have a regular expression like this:</p> <pre><code>regexp = u'ba[r|z|d]' </code></pre> <p>Function must return True if word contains <strong>bar</strong>, <strong>baz</strong> or <strong>bad</strong>. In short, I need regexp analog for Python's</p> <pre><code>'any-string' in 'text' </code></pre> <p>How can I realize it? Thanks!</p>
9,012,064
5
4
null
2012-01-25 23:32:05.937 UTC
24
2022-01-13 19:50:30.407 UTC
2019-10-02 23:11:25.58 UTC
null
6,202,327
null
974,296
null
1
147
python|regex
276,317
<pre><code>import re word = 'fubar' regexp = re.compile(r'ba[rzd]') if regexp.search(word): print('matched') </code></pre>
5,411,185
Sheet music library
<p>I'm a python hacker looking to build a sheet music app. I'm comfortable with reading/understanding sheet music (played piano for many years). Here are my complete newbie questions..</p> <p>Is there a standard for representing notes digitally? I don't want to reinvent any wheels.</p> <p>Given a sequence of notes and durations, is there a library for displaying these in a sheet music format?</p> <p>Basically I'm looking for a place to get started. I'm not heavily into graphics, so a existing open-source library would be awesome. If none exists in Python, I'm competent at Java/Javascript/C as well. </p> <p>Thanks</p>
5,411,214
4
0
null
2011-03-23 20:25:08.15 UTC
12
2022-07-02 20:16:40.43 UTC
2018-12-28 11:13:41.653 UTC
null
2,266,772
null
548,162
null
1
24
python|music-notation
13,649
<p>Take a look at <a href="http://lilypond.org/" rel="nofollow noreferrer">lilypond</a>. It uses LaTeX to typeset sheet music. Its input format is simple text, and can be generated pretty easily with Python or whatever.</p> <p><a href="https://abjad.github.io/" rel="nofollow noreferrer">Abjad</a> is a &quot;Python API for Formalized Score Control&quot; and a wrapper around lilypond, but I haven't used it and so can't vouch for it.</p>
5,567,287
What causes std::bad_function_call?
<p>I've seen a <a href="https://stackoverflow.com/questions/4257683/stdbind-a-member-function-to-an-object-pointer">few</a> <a href="https://stackoverflow.com/questions/5556183/make-c-crash-without-casting/5557843#5557843">questions</a> that refer to the <a href="https://stackoverflow.com/questions/5543169/how-to-make-a-vector-of-functors-lambdas-or-closures-in-cox"><code>std::bad_function_call</code> exception</a>, but haven't been able to find out any by Googling about what causes this exception.</p> <p>What kind of behavior is supposed to cause this exception? Can you give me minimal examples that don't have other semantic problems also going on?</p>
5,567,313
4
0
null
2011-04-06 13:39:26.007 UTC
4
2021-11-19 13:24:50.843 UTC
2017-05-23 12:16:53.273 UTC
null
-1
null
197,788
null
1
43
c++|exception|lambda|c++11
28,367
<p>Sure- the easiest is where you try to call a <code>std::function</code> that's empty.</p> <pre><code>int main() { std::function&lt;int()&gt; intfunc; int x = intfunc(); // BAD } </code></pre>
5,516,503
Searching names with Apache Solr
<p>I've just ventured into the seemingly simple but extremely complex world of searching. For an application, I am required to build a search mechanism for searching users by their names. </p> <p>After reading numerous posts and articles including:</p> <p><a href="https://stackoverflow.com/questions/2790908/how-can-i-use-lucene-for-personal-name-first-name-last-name-search">How can I use Lucene for personal name (first name, last name) search?</a><br> <a href="http://dublincore.org/documents/1998/02/03/name-representation/" rel="nofollow noreferrer">http://dublincore.org/documents/1998/02/03/name-representation/</a><br> <a href="https://stackoverflow.com/questions/1779954/whats-the-best-way-to-search-a-social-network-by-prioritizing-a-users-relationsh">what&#39;s the best way to search a social network by prioritizing a users relationships first?</a><br> <a href="http://www.gossamer-threads.com/lists/lucene/java-user/120417" rel="nofollow noreferrer">http://www.gossamer-threads.com/lists/lucene/java-user/120417</a><br> <a href="https://stackoverflow.com/questions/1614609/lucene-index-and-query-design-question-searching-people">Lucene Index and Query Design Question - Searching People</a><br> <a href="https://stackoverflow.com/questions/4383866/lucene-fuzzy-search-for-customer-names-and-partial-address">Lucene Fuzzy Search for customer names and partial address</a> </p> <p>... and a few others I cannot find at-the-moment. And getting at-least indexing and basic search working in my machine I have devised the following scheme for user searching:</p> <p>1) Have a first, second and third name field and index those with Solr<br> 2) Use edismax as the requestParser for multi column searching<br> 3) Use a combination of normalization filters such as: transliteration, latin-to-ascii convesrion, etc.<br> 4) Finally use fuzzy search </p> <p>Evidently, being very new to this I am unsure if the above is the best way to do it and would like to hear from experienced users who have a better idea than me in this field.</p> <p>I need to be able to match names in the following ways:</p> <p>1) Accent folding: Jorn matches Jörn and vise versa<br> 2) Alternative spellings: Karl matches Carl and vice versa<br> 3) Shortened representations (I believe I do this with the SynonymFilterFactory): Sue matches Susanne, etc.<br> 4) Levenstein matching: Jonn matches John, etc.<br> 5) Soundex matching: Elin and Ellen</p> <p>Any guidance, criticisms or comments are very welcome. Please let me know if this is possible ... or perhaps I'm just day-dreaming. :)</p> <hr> <p><strong>EDIT</strong></p> <p>I must also add that I also have a fullname field in case some people have long names, as an example from one of the posts: Jon Paul or Del Carmen should also match Jon Paul Del Carmen </p> <p>And since this is a new project, I can modify the schema and architecture any way I see fit so there are very limited restrictions.</p>
5,551,967
5
2
null
2011-04-01 17:02:05.51 UTC
18
2016-04-07 14:32:20.31 UTC
2017-05-23 12:25:06.493 UTC
null
-1
null
2,654,307
null
1
16
search|solr|lucene|fuzzy-search|edismax
9,507
<p>It sounds like you are catering for a corpus with searches that you need to match very loosely?</p> <p>If you are doing that you will want to choose your fields and set different boosts to rank your results.</p> <p>So have separate "copied" fields in solr:</p> <ul> <li>one field for exact full name (with filters) </li> <li>multivalued field with filters ASCIIFolding, Lowercase... </li> <li>multivalued field with the SynonymFilterFactory ASCIIFolding, Lowercase... </li> <li>PhoneticFilterFactory (with <a href="http://en.wikipedia.org/wiki/Caverphone" rel="nofollow noreferrer">Caverphone</a> or <a href="http://en.wikipedia.org/wiki/Double_Metaphone#Double_Metaphone" rel="nofollow noreferrer">Double-Metaphone</a>)</li> </ul> <p><a href="https://stackoverflow.com/questions/1419882/enabling-soundex-metaphone-for-non-english-characters">See Also: more non-english Soundex discussion</a></p> <p>Synonyms for names, I don't know if there is a public synonym db available.</p> <p>Fuzzy searching, I've not found it useful, it uses Levenshtein Distance. </p> <p>Other filters and indexing get more superior "search relevant" results.</p> <p>Unicode characters in names can be handled with the <a href="http://wiki.apache.org/solr/AnalyzersTokenizersTokenFilters#solr.ASCIIFoldingFilterFactory" rel="nofollow noreferrer">ASCIIFoldingFilterFactory</a></p> <p>You are describing solutions up front for expected use cases.</p> <p>If you want quality results, plan on tuning your <a href="http://www.lucidimagination.com/Community/Hear-from-the-Experts/Articles/Search-Application-Relevance-Issues" rel="nofollow noreferrer">Search Relevance</a></p> <p>This tuning will be especially valuable, when attempting to match on synonyms, like MacDonald and McDonald (which has a larger Levenshtein distance than Carl and Karl).</p>
5,246,900
Enabling VLAs (variable length arrays) in MS Visual C++?
<p>How can I enable the use of VLAs, variable length arrays as defined in C99, in MS Visual C++ or that is not possible at all?</p> <p>Yes I know that the C++ standard is based on C89 and that VLAs are not available in C89 standard and thus aren't available in C++, but MSVC++ is supposed to be a C compiler also, a behavior that can be switched on using the /TC compiler parameter (<code>Compile as C Code (/TC)</code>). But doing so does not seem to enable VLAs and the compiling process fails with the same errors when building as C++ (<code>Compile as C++ Code (/TP)</code>). Maybe MSVC++ C compiler is C89 compliant only or I am missing something (some special construct or pragma/define)?</p> <p>Code sample:</p> <pre><code>#include &lt;stdlib.h&gt; int main(int argc, char **argv) { char pc[argc+5]; /* do something useful with pc */ return EXIT_SUCCESS; } </code></pre> <p>Compile errors:</p> <blockquote> <p>error C2057: expected constant expression</p> <p>error C2466: cannot allocate an array of constant size 0</p> <p>error C2133: 'pc' : unknown size</p> </blockquote>
5,246,961
5
1
null
2011-03-09 14:05:19.927 UTC
6
2021-07-03 18:15:07.927 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
473,612
null
1
31
c|visual-c++|c99|c89|variable-length-array
21,666
<p>MSVC is not a C99 compiler, and does not support variable length arrays.</p> <p>At <a href="https://docs.microsoft.com/en-us/cpp/c-language/ansi-conformance" rel="noreferrer">https://docs.microsoft.com/en-us/cpp/c-language/ansi-conformance</a> MSVC is documented as conforming to C90.</p>
5,480,372
What's the best way to update an ObservableCollection from another thread?
<p>I am using the <code>BackgroundWorker</code> to update an <code>ObservableCollection</code> but it gives this error:</p> <blockquote> <p>"This type of <code>CollectionView</code> does not support changes to its <code>SourceCollection</code> from a thread different from the Dispatcher thread."</p> </blockquote> <p>What's the best and most elegant way to solve this, with the least amount of work. I don't want to write low level lock-based multi-threading code.</p> <p>I have seen some solutions online but they are several years old, so not sure what the latest consensus is for the solution of this problem.</p>
5,480,612
5
4
null
2011-03-29 23:56:34.697 UTC
13
2016-10-26 18:11:59.27 UTC
null
null
null
null
51,816
null
1
32
c#|.net|multithreading|parallel-processing|observablecollection
33,064
<p>If MVVM</p> <pre><code>public class MainWindowViewModel : ViewModel { private ICommand loadcommand; public ICommand LoadCommand { get { return loadcommand ?? (loadcommand = new RelayCommand(param =&gt; Load())); } } private ObservableCollection&lt;ViewModel&gt; items; public ObservableCollection&lt;ViewModel&gt; Items { get { if (items == null) { items = new ObservableCollection&lt;ViewModel&gt;(); } return items; } } public void Load() { BackgroundWorker bgworker = new BackgroundWorker(); bgworker.WorkerReportsProgress = true; bgworker.DoWork += (s, e) =&gt; { for(int i=0; i&lt;10; i++) { System.Threading.Thread.Sleep(1000); bgworker.ReportProgress(i, new List&lt;ViewModel&gt;()); } e.Result = null; }; bgworker.ProgressChanged += (s, e) =&gt; { List&lt;ViewModel&gt; partialresult = (List&lt;ViewModel&gt;)e.UserState; partialresult.ForEach(i =&gt; { Items.Add(i); }); }; bgworker.RunWorkerCompleted += (s, e) =&gt; { //do anything here }; bgworker.RunWorkerAsync(); } } </code></pre>
5,377,139
How to find all files ending with .rb with Linux?
<p>I am in a directory which contains more directories. What command can I use to get all files ending with <code>.rb</code>?</p>
5,377,180
5
1
null
2011-03-21 11:44:19.98 UTC
7
2020-05-12 18:02:47.74 UTC
2015-03-22 13:28:14.033 UTC
null
562,769
null
631,786
null
1
44
linux
75,848
<p>You could try</p> <pre><code>find . -type f -name \*.rb </code></pre>
4,892,816
MongoDB C# Driver: Ignore Property on Insert
<p>I am using the Official MongoDB C# Drive v0.9.1.26831, but I was wondering given a POCO class, is there anyway to ignore certain properties from getting inserted.</p> <p>For example, I have the following class:</p> <pre><code>public class GroceryList { public string Name { get; set; } public FacebookList Owner { get; set; } public bool IsOwner { get; set; } } </code></pre> <p>Is there a way, for the <strong>IsOwner</strong> to not get inserted when I insert a GroceryList object? Basically, I fetch the object from the database then set the IsOwner property in the app layer and then return it back to the controller, which than maps the object to a view model.</p> <p>Hope my question makes sense. thanks!</p>
4,892,861
5
1
null
2011-02-03 23:07:30.847 UTC
6
2020-06-24 14:28:34.61 UTC
2015-03-18 10:29:52.89 UTC
null
81,514
null
172,202
null
1
49
c#|mongodb|mongodb-.net-driver
44,269
<p>It looks like the [BsonIgnore] attribute did the job. </p> <pre><code>public class GroceryList : MongoEntity&lt;ObjectId&gt; { public FacebookList Owner { get; set; } [BsonIgnore] public bool IsOwner { get; set; } } </code></pre>
5,434,865
Quickest way to initialize an array of structures to all-0's?
<p>I'm trying to initialize an array of structures to all-0's, using the below syntax:</p> <pre><code>STRUCTA array[MAX] = {0}; </code></pre> <p>However, I'm getting the following warning from gcc :</p> <p>warning: missing braces around initializer</p> <p>What am i doing wrong - is there another/better way to do this ?</p>
5,434,963
7
2
null
2011-03-25 15:52:15.96 UTC
6
2019-11-15 19:43:20.797 UTC
2011-03-25 15:56:37.463 UTC
null
50,079
null
212,942
null
1
30
c|initialization|structure
37,836
<p>It the first member of your struct has a scalar type, use</p> <pre><code>STRUCTA array[MAX] = {{ 0 }}; </code></pre> <p>If the first member of your struct happens to be another struct object, whose first member has scalar type, then you'll have to use</p> <pre><code>STRUCTA array[MAX] = {{{ 0 }}}; </code></pre> <p>and so on. Basically, you have to open a new level of nested <code>{}</code> every time you "enter" another nested aggregate (a struct or an array). So in this case as long as the <em>first</em> member of each nested aggregate is also an aggregate, you need to go deeper with <code>{}</code>.</p> <p>All these extra braces are only there to avoid the warning. Of course, this is just a harmless warning (in this specific case). You can use a simple <code>{ 0 }</code> and it will work. </p> <p>Probably the the best way to deal with this is to disable this warning entirely (see @pmg's answer for the right command-line option). Someone working on GCC wasn't thinking clearly. I mean, I understand the value of that warning (and it can indeed be very useful), but breaking the functionality of <code>{ 0 }</code> is unacceptable. <code>{ 0 }</code> should have been given special treatment.</p>
5,337,505
android capture video frame
<p>I need to get a frame of a video file (it may be on sdcard, cache dir or app dir). I have package android.media in my application and inside I have class MediaMetadataRetriever. To get first frame into a bitmap, I use code:</p> <pre><code>public static Bitmap getVideoFrame(Context context, Uri videoUri) { MediaMetadataRetriever retriever = new MediaMetadataRetriever(); try { retriever.setMode(MediaMetadataRetriever.MODE_CAPTURE_FRAME_ONLY); retriever.setDataSource(context, videoUri); return retriever.captureFrame(); } catch (IllegalArgumentException ex) { throw new RuntimeException(); } catch (RuntimeException ex) { throw new RuntimeException(); } finally { retriever.release(); } } </code></pre> <p>But this it's not working. It throws an exception (java.lang.RuntimeException: setDataSource failed: status = 0x80000000) when I set data source. Do you know how to make this code to work? Or Do you have any similar (simple) solution without using ffmpeg or other external libraries? videoUri is a valid uri (media player can play video from that URI)</p>
7,689,797
8
1
null
2011-03-17 09:59:58.03 UTC
12
2015-05-02 09:55:47.553 UTC
2011-03-17 10:09:27.067 UTC
null
517,558
null
517,558
null
1
7
android|video|frame|capture
23,486
<p>The following works for me:</p> <pre><code>public static Bitmap getVideoFrame(FileDescriptor FD) { MediaMetadataRetriever retriever = new MediaMetadataRetriever(); try { retriever.setDataSource(FD); return retriever.getFrameAtTime(); } catch (IllegalArgumentException ex) { ex.printStackTrace(); } catch (RuntimeException ex) { ex.printStackTrace(); } finally { try { retriever.release(); } catch (RuntimeException ex) { } } return null; } </code></pre> <p>Also works if you use a path instead of a filedescriptor.</p>
4,991,051
Strange error about invalid syntax
<p>I am getting invalid syntax error in my python script for this statement</p> <pre><code>44 f = open(filename, 'r') 45 return return ^ SyntaxError: invalid syntax </code></pre> <p>I am not sure what exactly is wrong here? I am a python newbie and so will greatly appreciate if someone can please help.</p> <p>I am using version 2.3.4</p>
4,991,652
8
3
null
2011-02-14 10:26:46.44 UTC
5
2020-11-02 11:57:42.033 UTC
2011-02-14 10:27:23.11 UTC
null
279,627
null
418,832
null
1
11
python
89,249
<p>Getting "invalid syntax" on a plain return statement is pretty much impossible. If you use it outside of a function, you get <code>'return' outside function</code>, if you have the wrong indentation you get <code>IndentationError</code>, etc.</p> <p>The only way I can get a <code>SyntaxError: invalid syntax</code> on a return statement, is if in fact it doesn't say <code>return</code> at all, but if it contains non-ascii characters, such as <code>retürn</code>. That give this error. Now, how can you have that error without seeing it? Again, the only idea I can come up with is that you in fact have indentation, but that this indentation is not spaces or tabs. You can for example have somehow inserted a non-breaking space in your code.</p> <p>Yes, this can happen. Yes, I have had that happen to me. Yes, you get <code>SyntaxError: invalid syntax</code>.</p>
5,076,127
Bash - Update terminal title by running a second command
<p>On my terminal in Ubuntu, I often run programs which keep running for a long time. And since there are a lot of these programs, I keep forgetting which terminal is for which program, unless I tab through all of those. So I wanted to find a way to update my terminal title to the program name, whenever I run a command. I don't want to do it manually. </p> <p>I use gnome-terminal, but answer shouldn't really depend on that. Basically, If I'm able to run a second command, then I can simply use gconftool command to update the title. So I was hoping to find a way to capture the command in bash and update the title after every command. How do I do that? </p>
5,080,670
9
0
null
2011-02-22 09:08:17.197 UTC
13
2021-09-28 18:04:41.343 UTC
null
null
null
null
1,678,010
null
1
30
linux|bash|shell|terminal
17,642
<p>I have some answers for you :) You're right that it shouldn't matter that you're using gnome-terminal, but it does matter what command shell you're using. This is a lot easier in <code>zsh</code>, but in what follows I'm going to assume you're using <code>bash</code>, and that it's a fairly recent version (> 3.1).</p> <p>First of all:</p> <blockquote> <p>Which environment variable would contain the current 'command'?</p> </blockquote> <p>There is an environment variable which has more-or-less what you want - <code>$BASH_COMMAND</code>. There's only one small hitch, which is that it will only show you the last command in a pipe. I'm not 100% sure what it will do with combinations of subshells, either :)</p> <blockquote> <p>So I was hoping to find a way to capture the command in bash and update the title after every command.</p> </blockquote> <p>I've been thinking about this, and now that I understand what you want to do, I realized the real problem is that you need to update the title <strong>before</strong> every command. This means that the <code>$PROMPT_COMMAND</code> and <code>$PS1</code> environment variables are out as possible solutions, since they're only executed <strong>after</strong> the command returns.</p> <p>In <code>bash</code>, the only way I can think of to achieve what you want is to (ab)use the DEBUG SIGNAL. So here's a solution -- stick this at the end of your <code>.bashrc</code>:</p> <pre><code>trap 'printf "\033]0;%s\007" "${BASH_COMMAND//[^[:print:]]/}"' DEBUG </code></pre> <p>To get around the problem with pipes, I've been messing around with this:</p> <pre><code>function settitle () { export PREV_COMMAND=${PREV_COMMAND}${@} printf "\033]0;%s\007" "${BASH_COMMAND//[^[:print:]]/}" export PREV_COMMAND=${PREV_COMMAND}' | ' } export PROMPT_COMMAND=${PROMPT_COMMAND}';export PREV_COMMAND=""' trap 'settitle "$BASH_COMMAND"' DEBUG </code></pre> <p>but I don't promise it's perfect!</p>
12,166,202
reporting services (ssrs) prompts with username/password
<p>I am using reporting services 2010 and get the following prompt when trying to access the reports:</p> <p><img src="https://i.stack.imgur.com/a87k2.png" alt="enter image description here"></p> <p>In the reports definition, I have specified the database username/password.</p> <p>Is there any way to bypass this?</p>
12,166,240
6
2
null
2012-08-28 19:29:46.777 UTC
2
2020-10-21 12:50:24.667 UTC
2017-04-11 22:28:36.503 UTC
null
2,476,260
null
554,134
null
1
11
sql-server|reporting-services
89,028
<p>There are actually two logins you deal with when it comes to reporting services. </p> <ol> <li><p>The login to the database is to capture the data, it has nothing to do with the actual report itself. That login you used is sent to the database as the user / credentials being used to pull the report data.</p></li> <li><p>This prompt you have a screen shot of, is the authentication to the report server, by default rs uses windows authentication so enter your domain\username with password.</p></li> </ol> <p>If you do not like this default behavior you can change it, this guide should get you started: <a href="http://msdn.microsoft.com/en-us/library/cc281253.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/cc281253.aspx</a></p> <p>See this as well: <a href="http://msdn.microsoft.com/en-us/library/bb283249.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/bb283249.aspx</a></p>
12,452,073
Trying to set up postgres for ror app, getting error - fe_sendauth: no password supplied
<p>Getting:</p> <pre><code>An error has occurred: Error connecting to the server: fe_sendauth: no password supplied </code></pre> <p>Settings in <code>database.yml</code> are the same as the app setup on other machines.</p> <p>How can I set things up so that I don't need a password hardcoded?</p> <p>I can view the db ok using PgAdmin-III.</p> <p>I'd rather not have the password in <code>database.yml</code> as other machines using this app don't have/need it, so it seems likely to be something about my Pg install.</p>
12,452,259
4
1
null
2012-09-17 01:09:36.343 UTC
12
2017-07-16 16:20:51.143 UTC
2012-09-17 07:58:02.07 UTC
null
398,670
null
631,619
null
1
26
ruby-on-rails|ruby|postgresql|passwords|pg
57,287
<p>You need to change your change your <code>pg_hba.conf</code>. Here's an example of mine:</p> <p><code>pg_hba.conf</code>:</p> <pre><code>TYPE DATABASE USER ADDRESS METHOD host all all 127.0.0.1/32 trust host all PC 127.0.0.1/32 trust host all all ::1/128 trust </code></pre> <p>Note that <code>trust</code> means that anyone on <code>address</code> (in this case localhost) can connect as the listed user (or in this case any user of their choice). This is really only suitable for development configurations with unimportant data. <strong>Do not use this in production</strong>.</p>
12,349,826
Should I ever use continue inside a switch statement?
<p>I noticed you can indeed use the <code>continue</code> keyword in a switch statement, but on PHP it doesn't do what I expected.</p> <p>If it fails with PHP, who knows how many other languages it fails too? If I switch between languages a lot, this can be a problem if the code doesn't behave like I expect it to behave.</p> <p>Should I just avoid using <code>continue</code> in a switch statement then?</p> <p>PHP (5.2.17) fails:</p> <pre><code>for($p = 0; $p &lt; 8; $p++){ switch($p){ case 5: print"($p)"; continue; print"*"; // just for testing... break; case 6: print"($p)"; continue; print"*"; break; } print"$p\r\n"; } /* Output: 0 1 2 3 4 (5)5 (6)6 7 */ </code></pre> <p>C++ seems to work as expected (jumps to end of for loop):</p> <pre><code>for(int p = 0; p &lt; 8; p++){ switch(p){ case 5: cout &lt;&lt; "(" &lt;&lt; p &lt;&lt; ")"; continue; cout &lt;&lt; "*"; // just for testing... break; case 6: cout &lt;&lt; "(" &lt;&lt; p &lt;&lt; ")"; continue; cout &lt;&lt; "*"; break; } cout &lt;&lt; p &lt;&lt; "\r\n"; } /* Output: 0 1 2 3 4 (5)(6)7 */ </code></pre>
12,349,889
7
6
null
2012-09-10 10:30:22.537 UTC
3
2020-12-01 08:44:07.407 UTC
null
null
null
null
1,036,205
null
1
45
php|c++|language-agnostic|switch-statement
27,211
<h2>PHP 7.3 or newer:</h2> <p>Using <code>continue</code> to break a <code>switch</code> statement is deprecated and will trigger a warning.</p> <p>To exit a <code>switch</code> statement, use <code>break</code>.</p> <p>To continue to the next iteration of a loop that's surrounding the current <code>switch</code> statement, use <code>continue 2</code>.</p> <h2>PHP 7.2 or older:</h2> <p><code>continue</code> and <code>break</code> may be used interchangeably in PHP's <code>switch</code> statements.</p>
24,002,733
Add an element to an array in Swift
<p>Suppose I have an array, for example:</p> <pre><code>var myArray = ["Steve", "Bill", "Linus", "Bret"] </code></pre> <p>And later I want to push/append an element to the end of said array, to get:</p> <p><code>["Steve", "Bill", "Linus", "Bret", "Tim"]</code></p> <p>What method should I use?</p> <p>And what about the case where I want to add an element to the <strong>front</strong> of the array? Is there a constant time unshift?</p>
24,002,784
15
6
null
2014-06-02 20:29:51.253 UTC
45
2021-11-08 07:48:31.22 UTC
2021-11-08 07:48:31.22 UTC
null
8,090,893
null
1,494,793
null
1
404
ios|arrays|swift|xcode|cocoa-touch
495,145
<p>As of <strong>Swift 3 / 4 / 5</strong>, this is done as follows.</p> <p>To add a new element to the end of an Array.</p> <pre><code>anArray.append("This String") </code></pre> <p>To append a different Array to the end of your Array.</p> <pre><code>anArray += ["Moar", "Strings"] anArray.append(contentsOf: ["Moar", "Strings"]) </code></pre> <p>To insert a new element into your Array.</p> <pre><code>anArray.insert("This String", at: 0) </code></pre> <p>To insert the contents of a different Array into your Array.</p> <pre><code>anArray.insert(contentsOf: ["Moar", "Strings"], at: 0) </code></pre> <p>More information can be found in the "Collection Types" chapter of "<a href="https://itunes.apple.com/us/book/swift-programming-language/id881256329?mt=11" rel="noreferrer">The Swift Programming Language</a>", starting on page 110.</p>
24,338,150
How to manually force a commit in a @Transactional method?
<p>I'm using Spring / Spring-data-JPA and find myself needing to manually force a commit in a unit test. My use case is that I am doing a multi-threaded test in which I have to use data that is persisted before the threads are spawned.</p> <p>Unfortunately, given that the test is running in a <code>@Transactional</code> transaction, even a <code>flush</code> does not make it accessible to the spawned threads.</p> <pre><code> @Transactional public void testAddAttachment() throws Exception{ final Contract c1 = contractDOD.getNewTransientContract(15); contractRepository.save(c1); // Need to commit the saveContract here, but don't know how! em.getTransaction().commit(); List&lt;Thread&gt; threads = new ArrayList&lt;&gt;(); for( int i = 0; i &lt; 5; i++){ final int threadNumber = i; Thread t = new Thread( new Runnable() { @Override @Transactional public void run() { try { // do stuff here with c1 // sleep to ensure that the thread is not finished before another thread catches up Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); threads.add(t); t.start(); } // have to wait for all threads to complete for( Thread t : threads ) t.join(); // Need to validate test results. Need to be within a transaction here Contract c2 = contractRepository.findOne(c1.getId()); } </code></pre> <p>I've tried using the entity manager to, but get an error message when I do:</p> <pre><code>org.springframework.dao.InvalidDataAccessApiUsageException: Not allowed to create transaction on shared EntityManager - use Spring transactions or EJB CMT instead; nested exception is java.lang.IllegalStateException: Not allowed to create transaction on shared EntityManager - use Spring transactions or EJB CMT instead at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:293) at org.springframework.orm.jpa.aspectj.JpaExceptionTranslatorAspect.ajc$afterThrowing$org_springframework_orm_jpa_aspectj_JpaExceptionTranslatorAspect$1$18a1ac9(JpaExceptionTranslatorAspect.aj:33) </code></pre> <p>Is there any way to commit the transaction and continue it? I have been unable to find any method that allows me to call a <code>commit()</code>.</p>
24,341,843
3
6
null
2014-06-21 04:02:35.58 UTC
22
2015-10-09 06:24:42.133 UTC
null
null
null
null
827,480
null
1
74
java|spring|jpa|spring-data|spring-transactions
153,263
<p>I had a similar use case during testing hibernate event listeners which are only called on commit. </p> <p>The solution was to wrap the code to be persistent into another method annotated with <code>REQUIRES_NEW</code>. (In another class) This way a new transaction is spawned and a flush/commit is issued once the method returns.</p> <p><img src="https://i.stack.imgur.com/d41bl.png" alt="Tx prop REQUIRES_NEW"></p> <p>Keep in mind that this might influence all the other tests! So write them accordingly or you need to ensure that you can clean up after the test ran.</p>
3,262,415
Changing type of ActiveRecord Class in Rails with Single Table Inheritance
<p>I have two types of classes: </p> <pre><code>BaseUser &lt; ActiveRecord::Base </code></pre> <p>and </p> <pre><code>User &lt; BaseUser </code></pre> <p>which acts_as_authentic using Authlogic's authentication system. This inheritance is implemented using Single Table Inheritance</p> <p>If a new user registers, I register him as a User. However, if I already have a BaseUser with the same email, I'd like to change that BaseUser to a User in the database without simply copying all the data over to the User from the BaseUser and creating a new User (i.e. with a new id). Is this possible? Thanks.</p>
3,263,087
3
0
null
2010-07-16 06:28:17.257 UTC
3
2014-09-29 02:11:43.107 UTC
null
null
null
null
140,378
null
1
30
ruby-on-rails|ruby|activerecord|single-table-inheritance
17,455
<p>You can just set the type field to 'User' and save the record. The in-memory object will still show as a BaseUser but the next time you reload the in-memory object will be a User</p> <pre><code>&gt;&gt; b=BaseUser.new &gt;&gt; b.class # = BaseUser # Set the Type. In-Memory object is still a BaseUser &gt;&gt; b.type='User' &gt;&gt; b.class # = BaseUser &gt;&gt; b.save # Retrieve the records through both models (Each has the same class) &gt;&gt; User.find(1).class # = User &gt;&gt; BaseUser.find(1).class # User </code></pre>
3,642,793
Why can Haskell exceptions only be caught inside the IO monad?
<p>Can anybody explain why exceptions may be thrown outside the IO monad, but may only be caught inside it?</p>
3,643,840
3
0
null
2010-09-04 15:07:33.13 UTC
9
2016-04-13 09:57:07.05 UTC
2010-09-04 21:34:08.723 UTC
null
366,471
null
417,501
null
1
31
haskell|exception-handling|io|monads
2,252
<p>One of the reasons is the <a href="https://secure.wikimedia.org/wikibooks/en/wiki/Haskell/Denotational_semantics" rel="noreferrer">denotational semantics of Haskell</a>.</p> <p>One of the neat properties of (pure) Haskell functions is their monotonicity -- more defined argument yields more defined value. This property is very important e.g. to reason about recursive functions (read the article to understand why).</p> <p>Denotation of exception by definition is the bottom, <code>_|_</code>, the least element in poset corresponding to the given type. Thus, to satisfy monotonicity requirement, the following inequality needs to hold for any denotation <code>f</code> of Haskell function:</p> <pre><code>f(_|_) &lt;= f(X) </code></pre> <p>Now, if we could catch exceptions, we could break this inequality by "recognizing" the bottom (catching the exception) and returning more defined value:</p> <pre><code>f x = case catch (seq x True) (\exception -&gt; False) of True -&gt; -- there was no exception undefined False -&gt; -- there was an exception, return defined value 42 </code></pre> <p>Here's complete working demonstration (requires base-4 Control.Exception):</p> <pre><code>import Prelude hiding (catch) import System.IO.Unsafe (unsafePerformIO) import qualified Control.Exception as E catch :: a -&gt; (E.SomeException -&gt; a) -&gt; a catch x h = unsafePerformIO $ E.catch (return $! x) (return . h) f x = case catch (seq x True) (\exception -&gt; False) of True -&gt; -- there was no exception undefined False -&gt; -- there was an exception, return defined value 42 </code></pre> <p>Another reason, as TomMD noted, is breaking referential transparency. You could replace equal things with equal and get another answer. (Equal in denotational sense, i.e. they denote the same value, not in <code>==</code> sense.)</p> <p>How would we do this? Consider the following expression:</p> <pre><code>let x = x in x </code></pre> <p>This is a non-terminating recursion, so it never returns us any information and thus is denoted also by <code>_|_</code>. If we were able to catch exceptions, we could write function f such as</p> <pre><code>f undefined = 0 f (let x = x in x) = _|_ </code></pre> <p>(The latter is always true for strict functions, because Haskell provides no means to detect non-terminating computation -- and cannot in principle, because of the <a href="https://secure.wikimedia.org/wikipedia/en/wiki/Halting_problem" rel="noreferrer">Halting problem</a>.)</p>
3,219,726
Android singleTask or singleInstance launch mode?
<p>I have an app that has a list as its main activity and then you can click items which opens a detailed view of that item. I also have a search activity that is similar to the main activity and works as intended.</p> <p>However I want this search activity to only have once instance on the stack so that users can search multiple times and clicking back would return them to the previouse view that they were on before they started searching (rather than go back to the previouse search results)</p> <p>both the singleTask and singelInstance launch mode seems to do what I want so Im not sure which one I should be using for this purpose and why?</p>
3,220,375
3
0
null
2010-07-10 15:12:00.327 UTC
56
2018-12-04 21:55:49.177 UTC
2018-12-04 21:55:49.177 UTC
null
584,192
null
362,476
null
1
84
android|android-activity|launch|multitasking
101,411
<p>From the <a href="http://developer.android.com/guide/topics/fundamentals.html#lmodes" rel="noreferrer">Application Fundamentals</a> page of the Android dev guide:</p> <blockquote> <p>By default, all the activities in an application have an affinity for each other — that is, there's a preference for them all to belong to the same task.</p> <p>A &quot;singleInstance&quot; activity stands alone as the only activity in its task. If it starts another activity, that activity will be launched into a different task regardless of its launch mode — as if FLAG_ACTIVITY_NEW_TASK was in the intent. In all other respects, the &quot;singleInstance&quot; mode is identical to &quot;singleTask&quot;.</p> <p>As noted above, there's never more than one instance of a &quot;singleTask&quot; or &quot;singleInstance&quot; activity, so that instance is expected to handle all new intents. A &quot;singleInstance&quot; activity is always at the top of the stack (since it is the only activity in the task), so it is always in position to handle the intent. However, a &quot;singleTask&quot; activity may or may not have other activities above it in the stack. If it does, it is not in position to handle the intent, and the intent is dropped. (Even though the intent is dropped, its arrival would have caused the task to come to the foreground, where it would remain.)</p> </blockquote> <p><img src="https://i.imgur.com/l7vfI.png" alt="4 Activities in a Task" /></p> <p>Since there is never more than one instance of the Activity with either launch mode, the back button will always take you to the existing instance of the Activity in your case.</p> <p>An important difference is that &quot;singleTask&quot; doesn't require the creation of a new task for the new Activities being launched when something is selected. Nor will it have to remove that new task on the back button each time.</p> <p>Since your Activity stack does all pertain to one user &quot;task&quot;, and it doesn't sound like you have an intricate Intent structure where singleInstance may be beneficial to always handle them, I would suggest using the singleTask launch mode.</p> <p>Here is a good blog post for more info, as well as credited for the image: <a href="http://blog.akquinet.de/2010/02/17/android-activites-and-tasks-series-an-introduction-to-androids-ui-component-model/" rel="noreferrer">Android Activities and Tasks series – An introduction to Android’s UI component model</a></p>
22,498,344
Is there a better way to restore SearchView state?
<p>I have a collapsible <code>SearchView</code> in my <code>ActionBar</code>. After a search has been performed, the associated <code>ListView</code> is filtered to show only matching items. During that state, the <code>SearchView</code> is still expanded and shows the search string. If the user closes the <code>SearchView</code>, I remove the filter.</p> <p>I want to restore the search state, e.g. on configuration change or if the activity was destroyed when I return to it from another activity.</p> <p>I restore the query string in <code>onRestoreInstanceState()</code>, and if I find a query string in <code>onCreateOptionsMenu()</code> I call </p> <pre><code>searchView.setQuery(query, true); </code></pre> <p>so as to execute the query again. It turned out that this is better than applying the query filter immediately <code>onRestoreInstanceState()</code>. With the latter the list is shortly shown unfiltered, only then the query is applied again. With <code>setQuery()</code> this does not happen.</p> <p>Problem: The query is executed and the list is filtered, but the search view remains collapsed. Therefore the user cannot use the search view to remove the filter or to apply another query.</p> <p>In <code>onCreateOptionsMenu()</code> I can be sure that the search item and the search view exists, therefore I can call <code>searchItem.expandActionView()</code>. Strangely, only this really expands the <code>ActionView</code> - calling <code>setIconified(false)</code> does not expand the view, not even when it is called twice in a row.</p> <p>If I use <code>expandActionView()</code> before I call <code>setQuery()</code>, the <code>SearchView</code> is opened and shows the text (otherwise <code>expandActionView()</code> empties the <code>SearchView</code>). </p> <p>Unfortunately, <code>expandActionView()</code> has a side effect: the suggestion list is also shown and the keyboard opens. </p> <p>I can hide the keyboard using <code>searchView.clearFocus()</code>. So the remaining problem is the suggestion list. How can I close an open suggestion list on a <code>SearchView</code> that has text?</p> <p>I wonder if there is a better way to restore a search view in the action bar that does not have so many side effects.</p>
22,653,550
2
5
null
2014-03-19 06:47:42.9 UTC
9
2016-05-19 07:54:16.497 UTC
2014-12-17 10:37:32.333 UTC
null
1,276,636
null
743,507
null
1
20
android|searchview
12,826
<p>I have found a workaround. It is extremely ugly, but it works.</p> <p>So here is how I was able to restore the search box instance state after a configuration change.</p> <p>First of all, restore the query string in onRestoreInstanceState</p> <pre><code>currentQuery = state.getString(KEY_SAVED_FILTER_CONSTRAINT); </code></pre> <p>In onCreateOptionsMenu set up the search view and if there is a currentQuery, expand the search item and submit the query again. Clear the focus to hide the keyboard.</p> <pre><code> MenuItem searchItem = menu.findItem(R.id.action_search); searchView = (SearchView) searchItem.getActionView(); searchView.setSearchableInfo(searchManager .getSearchableInfo(getComponentName())); if (!TextUtils.isEmpty(currentQuery)) { searchItem.expandActionView(); searchView.setQuery(currentQuery, true); searchView.clearFocus(); } </code></pre> <p>Finally we need to close the suggestion list. Here is how to get the query text view from the search view:</p> <pre><code>private AutoCompleteTextView findQueryTextView(ViewGroup viewGroup) { AutoCompleteTextView queryTextView = null; if (viewGroup != null) { int childCount = viewGroup.getChildCount(); for (int i = 0; i &lt; childCount; i++) { View child = viewGroup.getChildAt(i); if (child instanceof AutoCompleteTextView) { queryTextView = (AutoCompleteTextView) child; break; } else if (child instanceof ViewGroup) { queryTextView = findQueryTextView((ViewGroup) child); if (queryTextView != null) { break; } } } } return queryTextView; } </code></pre> <p>Then you can dismiss the suggestion list:</p> <pre><code> AutoCompleteTextView queryTextView = findQueryTextView(searchView); if (queryTextView != null) { queryTextView.dismissDropDown(); } </code></pre> <p>This does however not work from within onCreateOptionsMenu. I had to move the invocation of dismissDropDown into the onNewIntent method of my activity to make it work.</p> <p>What makes this so ugly is the fact that the restoration steps are dispersed over various phases of the lifecycle and that a recursive view search is necessary to get to the suggestion list. </p>
26,387,569
Rule of thumb for when passing by value is faster than passing by const reference?
<p>Suppose I have a function that takes an argument of type <code>T</code>. It does not mutate it, so I have the choice of passing it by const reference <code>const T&amp;</code> or by value <code>T</code>:</p> <pre><code>void foo(T t){ ... } void foo(const T&amp; t){ ... } </code></pre> <p>Is there a rule of thumb of how big <code>T</code> should become before passing by const reference becomes cheaper than passing by value? E.g., suppose I know that <code>sizeof(T) == 24</code>. Should I use const reference or value?</p> <p>I assume that the copy constructor of <code>T</code> is trivial. Otherwise, the answer to the question depends on the complexity of the copy constructor, of course.</p> <p>I have already looked for similar questions and stumbled upon this one:</p> <p><a href="https://stackoverflow.com/questions/4876913/template-pass-by-value-or-const-reference-or">template pass by value or const reference or...?</a></p> <p>However, the accepted answer ( <a href="https://stackoverflow.com/a/4876937/1408611">https://stackoverflow.com/a/4876937/1408611</a> ) does not state any details,it merely states:</p> <blockquote> <p>If you expect T always to be a numeric type or a type that is very cheap to copy, then you can take the argument by value.</p> </blockquote> <p>So it does not solve my question but rather rephrases it: How small must a type be to be "very cheap to copy"?</p>
26,388,048
7
7
null
2014-10-15 16:32:14.3 UTC
4
2016-05-16 22:10:13.737 UTC
2017-05-23 12:02:23.73 UTC
null
-1
null
1,408,611
null
1
34
c++|c++11|pass-by-reference|pass-by-value
6,030
<p>If you have reason to suspect there is a worthwhile performance gain to be had, cut it out with the rules of thumb and <strong>measure</strong>. The purpose of the advise you quote is that you don't copy great amounts of data for no reason, but don't jeopardize optimizations by making everything a reference either. If something is on the edge between "clearly cheap to copy" and "clearly expensive to copy", then you can afford either option. If you must have the decision taken away from you, flip a coin.</p> <p>A type is cheap to copy if it has no funky copy constructor and its <code>sizeof</code> is small. There is no hard number for "small" that's optimal, not even on a per-platform basis since it depends very much on the calling code and the function itself. Just go by your gut feeling. One, two, three words are small. Ten, who knows. A 4x4 matrix is not small.</p>
11,037,213
ASP.NET MVC Attribute to only let user edit his/her own content
<p>I have a controller method called <code>Edit</code> in which the user can edit data they had created like so ...</p> <pre><code>public ActionResult Edit(int id) { Submission submission = unit.SubmissionRepository.GetByID(id); User user = unit.UserRepository.GetByUsername(User.Identity.Name); //Make sure the submission belongs to the user if (submission.UserID != user.UserID) { throw new SecurityException("Unauthorized access!"); } //Carry out method } </code></pre> <p>This method works fine however it is a little messy to put in every controller Edit method. Each table always has a <code>UserID</code> so I was wondering if there was an easier way to automate this via an <code>[Authorize]</code> Attribute or some other mechanism to make the code cleaner.</p>
11,037,269
4
0
null
2012-06-14 16:17:14.993 UTC
13
2019-03-30 11:33:39.197 UTC
null
null
null
null
786,489
null
1
20
c#|.net|asp.net-mvc|security|authentication
12,738
<p>Yes, you could achieve that through a custom Authorize attribute:</p> <pre><code>public class MyAuthorizeAttribute : AuthorizeAttribute { protected override bool AuthorizeCore(HttpContextBase httpContext) { var authorized = base.AuthorizeCore(httpContext); if (!authorized) { return false; } var rd = httpContext.Request.RequestContext.RouteData; var id = rd.Values["id"]; var userName = httpContext.User.Identity.Name; Submission submission = unit.SubmissionRepository.GetByID(id); User user = unit.UserRepository.GetByUsername(userName); return submission.UserID == user.UserID; } } </code></pre> <p>and then:</p> <pre><code>[MyAuthorize] public ActionResult Edit(int id) { // Carry out method } </code></pre> <p>and let's suppose that you need to feed this submission instance that we fetched into the custom attribute as action parameter to avoid hitting the database once again you could do the following:</p> <pre><code>public class MyAuthorizeAttribute : AuthorizeAttribute { protected override bool AuthorizeCore(HttpContextBase httpContext) { var authorized = base.AuthorizeCore(httpContext); if (!authorized) { return false; } var rd = httpContext.Request.RequestContext.RouteData; var id = rd.Values["id"]; var userName = httpContext.User.Identity.Name; Submission submission = unit.SubmissionRepository.GetByID(id); User user = unit.UserRepository.GetByUsername(userName); rd.Values["model"] = submission; return submission.UserID == user.UserID; } } </code></pre> <p>and then:</p> <pre><code>[MyAuthorize] public ActionResult Edit(Submission model) { // Carry out method } </code></pre>
11,011,742
Java null.equals(object o)
<p>I know it's not possible to call the equals method on a null object like that:</p> <pre><code>//NOT WORKING String s1 = null; String s2 = null; if(s1.equals(s2)) { System.out.println("NOT WORKING :'("); } </code></pre> <p>But in my case I want to compare two objects from two database and these two objects can have attributes null...</p> <p>So what is the method to compare two attributes, knowing that we are not sure that the value is null or filled.</p> <p>This method is good or not ?</p> <pre><code>//WORKING String s1 = "test"; String s2 = "test"; if(s1 == s2 || s1.equals(s2)) { System.out.println("WORKING :)"); } //WORKING String s1 = null; String s2 = null; if(s1 == s2 || s1.equals(s2)) { System.out.println("WORKING :)"); } </code></pre> <p>I'm not sure because in this case it's not working ... : </p> <pre><code>//NOT WORKING String s1 = null; String s2 = null; if(s1.equals(s2)|| s1 == s2 ) { System.out.println("NOT WORKING :'''("); } </code></pre>
11,011,854
9
3
null
2012-06-13 09:16:42.847 UTC
2
2017-07-02 09:32:02.557 UTC
2015-03-26 17:57:38.807 UTC
null
895,245
null
1,449,641
null
1
24
java|object|null
56,084
<p>I generally use a static utility function that I wrote called <code>equalsWithNulls</code> to solve this issue:</p> <pre><code>class MyUtils { public static final boolean equalsWithNulls(Object a, Object b) { if (a==b) return true; if ((a==null)||(b==null)) return false; return a.equals(b); } } </code></pre> <p>Usage:</p> <pre><code>if (MyUtils.equalsWithNulls(s1,s2)) { // do stuff } </code></pre> <p>Advantages of this approach:</p> <ul> <li>Wraps up the complexity of the full equality test in a single function call. I think this is much better than embedding a bunch of complex boolean tests in your code each time you do this. It's much less likely to lead to errors as a result.</li> <li>Makes your code more descriptive and hence easier to read. </li> <li>By explicitly mentioning the nulls in the method name, you convey to the reader that they should remember that one or both of the arguments might be null.</li> <li>Does the (a==b) test first (an optimisation which avoids the need to call a.equals(b) in the fairly common case that a and b are non-null but refer to exactly the same object)</li> </ul>
11,001,330
Java split String performances
<p>Here is the current code in my application:</p> <pre><code>String[] ids = str.split(&quot;/&quot;); </code></pre> <p>When profiling the application, a non-negligeable time is spent string splitting. Also, the <code>split</code> method takes a regular expression, which is superfluous here.</p> <p>What alternative can I use in order to optimize the string splitting? Is <code>StringUtils.split</code> faster?</p> <p>(I would've tried and tested myself but profiling my application takes a lot of time.)</p>
11,002,374
10
0
null
2012-06-12 17:02:01.943 UTC
8
2021-02-24 05:41:57.543 UTC
2021-02-15 23:39:19.103 UTC
null
59,087
null
245,552
null
1
53
java|string|performance|optimization|split
56,157
<p><code>String.split(String)</code> won't create regexp if your pattern is only one character long. When splitting by single character, it will use specialized code which is pretty efficient. <code>StringTokenizer</code> is not much faster in this particular case.</p> <p>This was introduced in OpenJDK7/OracleJDK7. <a href="http://bugs.sun.com/view_bug.do?bug_id=6840246" rel="noreferrer">Here's a bug report</a> and <a href="http://hg.openjdk.java.net/jdk7/jdk7/jdk/rev/1ff977b938e5" rel="noreferrer">a commit</a>. I've made a <a href="https://gist.github.com/2923321" rel="noreferrer">simple benchmark here</a>.</p> <hr> <pre><code>$ java -version java version "1.8.0_20" Java(TM) SE Runtime Environment (build 1.8.0_20-b26) Java HotSpot(TM) 64-Bit Server VM (build 25.20-b23, mixed mode) $ java Split split_banthar: 1231 split_tskuzzy: 1464 split_tskuzzy2: 1742 string.split: 1291 StringTokenizer: 1517 </code></pre>
13,032,333
Droid: How to get button id from onClick method described in XML?
<p>Following the dev guide, I can add a method to a button using in the XML. This calls the 'buttonPress' method in my activity. If I apply the same method to multiple buttons, how can I determine the identity of the button that has been clicked?</p>
13,032,373
2
2
null
2012-10-23 14:07:16.103 UTC
5
2022-01-31 06:36:18.697 UTC
null
null
null
null
1,294,096
null
1
19
android|onclick
59,280
<p>Use <code>getId()</code> method. It returnes the <code>int</code> id that you can compare to the id from resources.</p> <p>It is very convenient to use switch statement like this:</p> <pre><code>public void buttonPress(View v) { switch (v.getId()) { case R.id.button_one: // do something break; case R.id.button_two: // do something else break; case R.id.button_three: // i'm lazy, do nothing break; } } </code></pre>
13,066,249
filtering lines in a numpy array according to values in a range
<p>Let an array:</p> <pre><code> a =np.array([[1,2],[3,-5],[6,-15],[10,7]]) </code></pre> <p>to get lines with elements of the second column above -6 it' s possible to do</p> <pre><code>&gt;&gt;&gt; a[a[:,1]&gt;-6] array([[ 1, 2], [ 3, -5], [10, 7]]) </code></pre> <p>but how to get lines with the second element between -6;3? I tried:</p> <pre><code>&gt;&gt;&gt; a[3&gt;a[:,1]&gt;-6] </code></pre> <p>and also (which raises an error):</p> <pre><code>&gt;&gt;&gt; np.ma.masked_inside(a,-6,3) </code></pre> <p>which gives:</p> <pre><code> masked_array(data = [[-- --] [-- --] [6 -15] [10 7]], mask = [[ True True] [ True True] [False False] [False False]], fill_value = 999999) </code></pre> <p>but the result is not too clear</p> <p>Thanks jp</p>
13,066,593
2
0
null
2012-10-25 10:08:09.323 UTC
9
2021-12-15 16:28:01.667 UTC
2012-10-25 15:54:58.073 UTC
null
1,491,200
null
601,314
null
1
22
numpy|range
38,762
<pre><code>&gt;&gt;&gt; a[ (-6&lt;a[:,1]) &amp; (a[:,1]&lt;3) ] array([[ 1, 2], [ 3, -5]]) </code></pre>
13,175,050
How to implement rate limiting using Redis
<p>I use <code>INCR</code> and <code>EXPIRE</code> to implement rate limiting, e.g., 5 requests per minute:</p> <pre><code>if EXISTS counter count = INCR counter else EXPIRE counter 60 count = INCR counter if count &gt; 5 print &quot;Exceeded the limit&quot; </code></pre> <p>However, 5 requests can be sent at the last second minute one and 5 more requests at the first second of minute two, i.e., 10 requests in two seconds.</p> <p>How can this problem be avoided?</p> <hr /> <p>Update: I came up with this list implementation. Is this a good way to do it?</p> <pre><code>times = LLEN counter if times &lt; 5 LPUSH counter now() else time = LINDEX counter -1 if now() - time &lt; 60 print &quot;Exceeded the limit&quot; else LPUSH counter now() LTRIM counter 5 </code></pre>
13,176,199
11
4
null
2012-11-01 10:22:49.277 UTC
15
2022-08-18 15:58:41.303 UTC
2021-01-25 17:29:28.783 UTC
null
875,915
null
1,109,791
null
1
24
redis|rate-limiting
23,143
<p>You could switch from "5 requests in the last minute" to "5 requests in minute x". By this it would be possible to do:</p> <pre><code>counter = current_time # for example 15:03 count = INCR counter EXPIRE counter 60 # just to make sure redis doesn't store it forever if count &gt; 5 print "Exceeded the limit" </code></pre> <p>If you want to keep using "5 requests in the last minute", then you could do</p> <pre><code>counter = Time.now.to_i # this is Ruby and it returns the number of milliseconds since 1/1/1970 key = "counter:" + counter INCR key EXPIRE key 60 number_of_requests = KEYS "counter"*" if number_of_requests &gt; 5 print "Exceeded the limit" </code></pre> <p>If you have production constraints (especially performance), it is <a href="http://redis.io/commands/keys" rel="noreferrer">not advised</a> to use the <code>KEYS</code> keyword. We could use <em>sets</em> instead:</p> <pre><code>counter = Time.now.to_i # this is Ruby and it returns the number of milliseconds since 1/1/1970 set = "my_set" SADD set counter 1 members = SMEMBERS set # remove all set members which are older than 1 minute members {|member| SREM member if member[key] &lt; (Time.now.to_i - 60000) } if (SMEMBERS set).size &gt; 5 print "Exceeded the limit" </code></pre> <p>This is all pseudo Ruby code, but should give you the idea.</p>
13,150,272
Meaning for attributes_for in FactoryGirl and Rspec Testing
<p>Looking through a tutorial on controller testing the author gives an example of an rspec test testing a controller action. My question is, why did they use the method <code>attributes_for</code> over <code>build</code>? There is no clear explanation why <code>attributes_for</code> is used besides that it returns a hash of values.</p> <pre><code>it "redirects to the home page upon save" do post :create, contact: Factory.attributes_for(:contact) response.should redirect_to root_url end </code></pre> <p>The tutorial link is found here: <a href="http://everydayrails.com/2012/04/07/testing-series-rspec-controllers.html" rel="noreferrer">http://everydayrails.com/2012/04/07/testing-series-rspec-controllers.html</a> The example is found at the beginning topic section <code>Controller testing basics</code></p>
13,150,336
1
0
null
2012-10-31 02:04:58.16 UTC
9
2015-12-12 02:24:38.927 UTC
2012-10-31 02:12:21.45 UTC
null
1,509,401
null
1,509,401
null
1
40
ruby-on-rails|ruby-on-rails-3|rspec|attributes|factory-bot
23,674
<p><code>attributes_for</code> will return a hash, whereas <code>build</code> will return a non persisted object.</p> <p>Given the following factory:</p> <pre><code>FactoryGirl.define do factory :user do name 'John Doe' end end </code></pre> <p>Here is the result of <code>build</code>:</p> <pre><code>FactoryGirl.build :user =&gt; #&lt;User id: nil, name: "John Doe", created_at: nil, updated_at: nil&gt; </code></pre> <p>and the result of <code>attributes_for</code></p> <pre><code>FactoryGirl.attributes_for :user =&gt; {:name=&gt;"John Doe"} </code></pre> <p>I find <code>attributes_for</code> very helpful for my functional test, as I can do things like the following to create a user:</p> <pre><code>post :create, user: FactoryGirl.attributes_for(:user) </code></pre> <p>When using <code>build</code>, we would have to manually create a hash of attributes from the <code>user</code> instance and pass it to the <code>post</code> method, such as:</p> <pre><code>u = FactoryGirl.build :user post :create, user: u.attributes # This is actually different as it includes all the attributes, in that case updated_at &amp; created_at </code></pre> <p>I usually use <code>build</code> &amp; <code>create</code> when I directly want objects and not an attributes hash</p> <p>Let me know if you need more details</p>
13,216,916
How to replace the activity's fragment from the fragment itself?
<p>My application has a Fragment inside its Activity. I would like to programmatically replace the fragment by another one from the current fragment itself.</p> <p>For example, if I click on a button inside the fragment, the fragment should be replaced with another one, but the activity should remain the same.</p> <p>Is it possible? If so, how to do it?</p>
13,221,546
8
3
null
2012-11-04 07:34:44.79 UTC
23
2022-06-27 17:03:25.41 UTC
2014-11-09 11:17:33.56 UTC
null
1,636,285
null
1,461,553
null
1
58
android|android-fragments
63,107
<p>It's actually easy to call the activity to replace the fragment.</p> <p>You need to cast getActivity():</p> <pre><code>((MyActivity) getActivity()) </code></pre> <p>Then you can call methods from MyActivity, for example:</p> <pre><code>((MyActivity) getActivity()).replaceFragments(Object... params); </code></pre> <p>Of course, this assumes you have a replaceFragments() method in your activity that handles the fragment replace process.</p> <p><strong>Edit:</strong> @ismailarilik added the possible code of replaceFragments in this code with the first comment below which was written by @silva96:</p> <p>The code of replaceFragments could be:</p> <pre><code>public void replaceFragments(Class fragmentClass) { Fragment fragment = null; try { fragment = (Fragment) fragmentClass.newInstance(); } catch (Exception e) { e.printStackTrace(); } // Insert the fragment by replacing any existing fragment FragmentManager fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction().replace(R.id.flContent, fragment) .commit(); } </code></pre>
13,125,817
How to remove elements that were fetched using querySelectorAll?
<p>This seems like something that would have a quick answer, but I can't find one. Maybe I'm searching the wrong terms? No libraries please, though I don't need cross-browser fallbacks, I'm targeting all the latest versions on this project. </p> <p>I'm getting some elements:</p> <pre><code>element = document.querySelectorAll(".someselector"); </code></pre> <p>This is working, but how do I now delete these elements? Do I have to loop through them and do the <code>element.parentNode.removeChild(element);</code> thing, or is there a simple function I'm missing?</p>
13,125,840
3
0
null
2012-10-29 16:34:14.65 UTC
15
2021-09-27 18:21:46.89 UTC
2019-05-14 19:10:13.263 UTC
null
1,750,282
null
1,750,282
null
1
82
javascript|element|selectors-api
81,972
<p>Yes, you're almost right. <code>.querySelectorAll</code> returns a <em>frozen NodeList</em>. You need to iterate it and do things.</p> <pre><code>Array.prototype.forEach.call( element, function( node ) { node.parentNode.removeChild( node ); }); </code></pre> <p>Even if you only got one result, you would need to access it via index, like</p> <pre><code>elements[0].parentNode.removeChild(elements[0]); </code></pre> <hr> <p>If you only <em>want</em> to query for one element, use <code>.querySelector</code> instead. There you just get the <em>node reference</em> without the need to access with an index.</p>
16,917,043
Do function pointers need an ampersand
<p>In C/C++, if I have a the following functions:</p> <pre><code>void foo(); void bar(void (*funcPtr)()); </code></pre> <p>Is there a difference between these two calls:</p> <pre><code>bar(foo); bar(&amp;foo); </code></pre> <p>?</p>
16,917,063
3
4
null
2013-06-04 11:50:15.607 UTC
5
2013-06-04 11:55:56.427 UTC
null
null
null
null
331,785
null
1
47
c++|c|function-pointers
7,485
<p>No, there is no difference, since function can be implicitly converted to pointer to function. Relevant quote from standard (N3376 4.3/1). <Blockquote><P> An lvalue of function type T can be converted to a prvalue of type “pointer to T.” The result is a pointer to the function.</P></Blockquote></p>
16,709,263
How to add a dictionary for spell check in Android Studio / IntelliJ Idea
<p>I have been using Android Studio in Spanish, and it bothers me that it highlights as incorrect words which are spelt correctly.</p> <p>Can I add a Spanish dictionary to Android Studio or to my IntelliJ Idea?</p>
18,743,560
5
0
null
2013-05-23 08:38:42.207 UTC
8
2019-08-30 05:09:05.907 UTC
2019-08-30 05:09:05.907 UTC
null
9,638,388
null
2,357,936
null
1
61
android|android-studio|intellij-idea|spell-checking
38,652
<p>You can download the Spanish (or any other language) ASCII dictionary from <a href="http://www.winedt.org/dictASCII.html" rel="noreferrer">http://www.winedt.org/dictASCII.html</a> and then add it to Android Studio as sebaszw said:</p> <blockquote> <ol> <li>Go to Settings -> Spelling -> Dictionaries</li> <li>Click plus symbol(+)</li> <li>Select path to your dictionaries folder (inside you must have plaintext word lists with .dic extension)</li> <li>Restart Android Studio</li> </ol> </blockquote> <p>It worked for me without restarting Android Studio</p>
50,968,732
Determine if biometric hardware is present and the user has enrolled biometrics on Android P
<p>I'm asked to show certain UI elements depending on the presence of biometric hardware. For Android 23-27 I use <code>FingerprintManager#isHardwareDetected()</code> and <code>FingerprintManager#hasEnrolledFingerprints()</code>. Both of which are deprecated in Android 28.</p> <p>I understand that I can get this information by using <code>BiometricPrompt#authenticate(...)</code> and receiving either <code>BiometricPrompt#BIOMETRIC_ERROR_HW_NOT_PRESENT</code> or <code>BiometricPrompt#BIOMETRIC_ERROR_NO_BIOMETRICS</code> in the <code>BiometricPrompt.AuthenticationCallback#onAuthenticationError(int errorCode, ...)</code> method. But this would lead to the <code>BiometricPrompt</code> being shown on supporting devices, which is undesirable. Using the <code>CancellationSignal</code> doesn't seem to be a solution either, since I wouldn't know when to cancel the prompt.</p> <p>Is there any way to detect biometric hardware presence and user enrolment?</p>
55,157,633
8
3
null
2018-06-21 12:35:10.207 UTC
15
2019-12-13 05:25:29.89 UTC
2018-06-25 09:56:52.727 UTC
null
1,148,144
null
1,148,144
null
1
49
android|biometrics|android-9.0-pie
27,051
<p>Google finally solved this problem with Android Q</p> <p>The <a href="https://developer.android.com/reference/android/hardware/biometrics/BiometricManager.html#canAuthenticate()" rel="noreferrer">android.hardware.biometrics.BiometricManager#canAuthenticate()</a> method can be used to determine if biometrics can be used.</p> <p>The method can be used to determine if biometric hardware is present and if the user is enrolled or not.</p> <blockquote> <p>Returns BIOMETRIC_ERROR_NONE_ENROLLED if the user does not have any enrolled, or BIOMETRIC_ERROR_HW_UNAVAILABLE if none are currently supported/enabled. Returns BIOMETRIC_SUCCESS if a biometric can currently be used (enrolled and available).</p> </blockquote> <p>Hopefully this is added to the <code>androidx.biometric:biometric</code> library, so it can be used on all devices.</p> <p>Until then the solution by @algrid works to determine biometrics enrollment.</p> <p>And the following can be used to determine, if a fingerprint reader is present.</p> <pre><code>Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.M &amp;&amp; context.packageManager.hasSystemFeature(PackageManager.FEATURE_FINGERPRINT) </code></pre>
10,244,773
How can I remove the arrow from drop down list in Bootstrap CSS?
<p>I am trying to remove the arrow that appears on a drop down menu in Twitter Bootstrap framework. Has anyone figured a way of removing the arrows?</p>
10,244,938
9
3
null
2012-04-20 10:49:01.17 UTC
7
2019-05-07 06:08:52.357 UTC
2012-06-24 01:20:28.757 UTC
null
667,810
null
492,293
null
1
12
twitter-bootstrap
45,152
<p>From: <a href="https://getbootstrap.com/2.3.2/components.html#buttonDropdowns" rel="nofollow noreferrer">https://getbootstrap.com/2.3.2/components.html#buttonDropdowns</a></p> <pre><code>&lt;div class="btn-group"&gt; &lt;a class="btn dropdown-toggle" data-toggle="dropdown" href="#"&gt; Action &lt;span class="caret"&gt;&lt;/span&gt; &lt;/a&gt; &lt;ul class="dropdown-menu"&gt; &lt;!-- dropdown menu links --&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre> <p>If you remove <code>&lt;span class="caret"&gt;&lt;/span&gt;</code> the arrow is not shown.</p> <p>Tried it using the dev. console in Chrome, and seems to work.</p>
10,052,135
expected identifier before string constant
<p>Having a program like this:</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; using namespace std; class test { public: test(std::string s):str(s){}; private: std::string str; }; class test1 { public: test tst_("Hi"); }; int main() { return 1; } </code></pre> <p>…why am I getting the following when I execute </p> <blockquote> <p>g++ main.cpp</p> </blockquote> <pre><code>main.cpp:16:12: error: expected identifier before string constant main.cpp:16:12: error: expected ‘,’ or ‘...’ before string constant </code></pre>
10,052,154
2
2
null
2012-04-07 05:46:05.543 UTC
4
2021-10-29 23:28:08.457 UTC
2012-04-07 05:48:22.74 UTC
null
5,696
null
805,896
null
1
18
c++|linux|constructor
44,842
<p>You can not initialize <code>tst_</code> where you declare it. This can only be done for <code>static const</code> primitive types. Instead you will need to have a constructor for <code>class test1</code>.</p> <p>EDIT: below, you will see a working example I did in <a href="http://ideone.com/y4h52" rel="nofollow noreferrer">ideone.com</a>. Note a few changes I did. First, it is better to have the constructor of <code>test</code> take a <code>const</code> reference to <code>string</code> to avoid copying. Second, if the program succeeds you should <code>return 0</code> not <code>1</code> (with <code>return 1</code> you get a runtime error in <a href="http://ideone.com/h8n2V" rel="nofollow noreferrer">ideone</a>).</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;iostream&gt; #include &lt;string&gt; using namespace std; class test { public: test(const std::string&amp; s):str(s){}; private: std::string str; }; class test1 { public: test1() : tst_(&quot;Hi&quot;) {} test tst_; }; int main() { return 0; } </code></pre>
9,912,469
PHP: How to sort the characters in a string?
<p>I have a set of strings containing characters in a PHP script, I need to sort those characters in each string.</p> <p>For example:</p> <pre><code>"bac" -&gt; "abc" "abc" -&gt; "abc" "" -&gt; "" "poeh" -&gt; "ehop" </code></pre> <p>These characters don't have accents and are all lower case. How can I perform this in PHP?</p>
9,912,497
5
0
null
2012-03-28 17:13:16.167 UTC
6
2020-12-09 06:19:55.357 UTC
null
null
null
null
520,957
null
1
26
php|string|sorting|character
48,144
<p>I would make it an array and use the sort function:</p> <pre><code>$string = 'bac'; $stringParts = str_split($string); sort($stringParts); echo implode($stringParts); // abc </code></pre>
10,214,042
Can SQLAlchemy be configured to be non-blocking?
<p>I'm under the impression that database calls through SQLAlchemy will block and aren't suitable for use in anything other than synchronous code. Am I correct (I hope I'm not!) or is there a way to configure it to be non-blocking?</p>
10,216,120
3
2
null
2012-04-18 16:45:24.393 UTC
13
2017-08-12 03:59:08.96 UTC
null
null
null
null
509,271
null
1
33
python|database|asynchronous|sqlalchemy|nonblocking
17,173
<p>You can use SQLA in a non-blocking style using <a href="http://www.gevent.org/">gevent</a>. Here's an example using psycopg2, using psycopg2's <a href="http://initd.org/psycopg/docs/advanced.html#support-to-coroutine-libraries">coroutine support</a>:</p> <p><a href="https://bitbucket.org/zzzeek/green_sqla/">https://bitbucket.org/zzzeek/green_sqla/</a></p> <p>I've also heard folks use the same idea with <a href="https://github.com/petehunt/PyMySQL/">pymysql</a>. As pymysql is in pure Python and uses the sockets library, gevent patches the socket library to be asynchronous.</p>
10,245,560
Deadlocks in PostgreSQL when running UPDATE
<p>I'm a little bit confused reading about PostgreSQL deadlocks.</p> <p>A typical deadlock example is:</p> <pre><code>-- Transaction 1 UPDATE customer SET ... WHERE id = 1 UPDATE customer SET ... WHERE id = 2 -- Transaction 2 UPDATE customer SET ... WHERE id = 2 UPDATE customer SET ... WHERE id = 1 </code></pre> <p>But what if I change the code as follows:</p> <pre><code>-- Transaction 1 UPDATE customer SET ... WHERE id IN (1, 2) -- Transaction 2 UPDATE customer SET ... WHERE id IN (1, 2) </code></pre> <p>Will be a possibility of deadlock here?</p> <p>Essentially my question is: <strong>in the 2nd case does PostgreSQL lock rows one-by-one, or lock the entire scope covered by the <code>WHERE</code> condition?</strong></p> <p>Thanks in advance!</p>
10,246,052
2
0
null
2012-04-20 11:41:48.423 UTC
9
2022-02-17 18:53:53.047 UTC
2013-10-30 20:52:31.29 UTC
null
1,309,107
null
946,652
null
1
38
postgresql|transactions|database-deadlocks
19,521
<p>In PostgreSQL the rows will be locked as they are updated -- in fact, the way this actually works is that each tuple (version of a row) has a system field called <code>xmin</code> to indicate which transaction made that tuple current (by insert or update) and a system field called <code>xmax</code> to indicate which transaction expired that tuple (by update or delete). When you access data, it checks each tuple to determine whether it is visible to your transaction, by checking your active "snapshot" against these values.</p> <p>If you are executing an UPDATE and a tuple which matches your search conditions has an xmin which would make it visible to your snapshot and an xmax of an active transaction, it blocks, waiting for that transaction to complete. If the transaction which first updated the tuple rolls back, your transaction wakes up and processes the row; if the first transaction commits, your transaction wakes up and takes action depending on the current transaction isolation level.</p> <p>Obviously, a deadlock is the result of this happening to rows in different order. There is no row-level lock in RAM which can be obtained for all rows at the same time, but if rows are updated in the same order you can't have the circular locking. Unfortunately, the suggested <code>IN(1, 2)</code> syntax doesn't guarantee that. Different sessions may have different costing factors active, a background "analyze" task may change statistics for the table between the generation of one plan and the other, or it may be using a seqscan and be affected by the PostgreSQL optimization which causes a new seqscan to join one already in progress and "loop around" to reduce disk I/O.</p> <p>If you do the updates one at a time in the same order, in application code or using a cursor, then you will have only simple blocking, not deadlocks. In general, though, relational databases are prone to serialization failures, and it is best to access them through a framework which will recognize them based on SQLSTATE and automatically retry the entire transaction from the start. In PostgreSQL a serialization failure will always have a SQLSTATE of 40001 or 40P01.</p> <p><a href="http://www.postgresql.org/docs/current/interactive/mvcc-intro.html" rel="noreferrer">http://www.postgresql.org/docs/current/interactive/mvcc-intro.html</a></p>
9,706,041
Finding index of an item closest to the value in a list that's not entirely sorted
<p>As an example my list is:</p> <pre><code>[25.75443, 26.7803, 25.79099, 24.17642, 24.3526, 22.79056, 20.84866, 19.49222, 18.38086, 18.0358, 16.57819, 15.71255, 14.79059, 13.64154, 13.09409, 12.18347, 11.33447, 10.32184, 9.544922, 8.813385, 8.181152, 6.983734, 6.048035, 5.505096, 4.65799] </code></pre> <p>and I'm looking for the index of the value closest to <code>11.5</code>. I've tried other methods such as binary search and <code>bisect_left</code> but they don't work.</p> <p>I cannot sort this array, because the index of the value will be used on a similar array to fetch the value at that index.</p>
9,706,105
7
3
null
2012-03-14 16:33:21.173 UTC
25
2021-08-31 09:26:31.47 UTC
2021-08-31 09:26:31.47 UTC
null
4,865,723
null
1,269,526
null
1
71
python|list|search
97,450
<p>Try the following:</p> <pre><code>min(range(len(a)), key=lambda i: abs(a[i]-11.5)) </code></pre> <p>For example:</p> <pre><code>&gt;&gt;&gt; a = [25.75443, 26.7803, 25.79099, 24.17642, 24.3526, 22.79056, 20.84866, 19.49222, 18.38086, 18.0358, 16.57819, 15.71255, 14.79059, 13.64154, 13.09409, 12.18347, 11.33447, 10.32184, 9.544922, 8.813385, 8.181152, 6.983734, 6.048035, 5.505096, 4.65799] &gt;&gt;&gt; min(range(len(a)), key=lambda i: abs(a[i]-11.5)) 16 </code></pre> <p>Or to get the index and the value:</p> <pre><code>&gt;&gt;&gt; min(enumerate(a), key=lambda x: abs(x[1]-11.5)) (16, 11.33447) </code></pre>
8,145,060
ZeroMQ in javascript client
<p>Have anyone used <a href="http://www.zeromq.org/bindings%3ajavascript">ZmqSocket.js</a> successfully? I'd like to know how can it be used to establish a safe channel between the browser and a zeromq server app. Is there other/better options for such use case?</p>
8,260,063
3
0
null
2011-11-16 00:21:55.64 UTC
10
2014-05-15 11:36:45.63 UTC
null
null
null
null
236,499
null
1
13
javascript|zeromq|channel
20,590
<p>I've never used ZmqSocket.js, but I can tell you that it's probably not a good idea (yet). This is because zmq still assumes that both peers know the protocol well and will blow up if given invalid data (they are working on fixing that, though).</p> <p>What I do right now is have a simple <a href="http://nodejs.org/" rel="noreferrer">node.js</a> based proxy that uses <a href="http://socket.io/" rel="noreferrer">socket.io</a> to communicate with browsers and pushes data in (and reads from) a zeromq socket, where the rest of the app is.</p> <hr> <p><em>Update in 2013:</em> I wrote <a href="https://bitbucket.org/vladev/sockjsproxy/" rel="noreferrer">sockjsproxy</a>, which essentially proxies messages to/from <a href="https://github.com/sockjs/sockjs-client" rel="noreferrer">sockjs</a> and zeromq, allowing you to implement the server in any language you want by just implementing the (very simple) ZeroMQ-based protocol.</p> <p>I've personally used it with Python and Scala servers to build real-time web apps.</p>
11,491,750
Cannot make a static reference to the non-static method fxn(int) from the type Two
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/290884/what-is-the-reason-behind-non-static-method-cannot-be-referenced-from-a-static">What is the reason behind &ldquo;non-static method cannot be referenced from a static context&rdquo;?</a><br> <a href="https://stackoverflow.com/questions/4969171/cannot-make-a-static-reference-to-the-non-static-method">Cannot make a static reference to the non-static method</a><br> <a href="https://stackoverflow.com/questions/8101585/cannot-make-a-static-reference-to-the-non-static-field">cannot make a static reference to the non-static field</a> </p> </blockquote> <p>I am not able to understand what is wrong with my code.</p> <pre><code>class Two { public static void main(String[] args) { int x = 0; System.out.println("x = " + x); x = fxn(x); System.out.println("x = " + x); } int fxn(int y) { y = 5; return y; } } </code></pre> <p>Exception in thread "main" java.lang.Error: Unresolved compilation problem: Cannot make a static reference to the non-static method fxn(int) from the type Two</p>
11,491,789
4
5
null
2012-07-15 12:09:41.703 UTC
15
2012-07-15 12:18:13.39 UTC
2017-05-23 12:34:53.433 UTC
null
-1
null
1,268,784
null
1
41
java
244,511
<p>Since the <code>main</code> method is <code>static</code> and the <code>fxn()</code> method is not, you can't call the method without first creating a <code>Two</code> object. So either you change the method to:</p> <pre><code>public static int fxn(int y) { y = 5; return y; } </code></pre> <p>or change the code in <code>main</code> to:</p> <pre><code>Two two = new Two(); x = two.fxn(x); </code></pre> <p>Read more on <code>static</code> here in the <a href="http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html" rel="noreferrer">Java Tutorials</a>.</p>
11,519,230
apply svn patch to git repository
<p>Ok, I've tried all answers i could find on stackoverflow, but apparently none seem to be able to solve my problem. I want to apply a patch made by SVN to a git repository. Apparently the easiest way to do it is by using 'git apply', but that does not seem to work.</p> <pre><code>$ git apply --ignore-space-change --ignore-whitespace &lt; xxx_parser.patch &lt;stdin&gt;:10: trailing whitespace. FORCE_LA_CHECK = false; stdin:23: trailing whitespace. &lt;stdin&gt;:79: trailing whitespace . . . . error: pmd/grammar/JspParser.jjt: No such file or directory error: patch failed: pmd/pom.xml:251 error: pmd/pom.xml: patch does not apply </code></pre> <p>This is the content of xxx_parser.patch:</p> <pre><code> $ head xxx_parser.patch Index: etc/grammar/JspParser.jjt --- etc/grammar/JspParser.jjt (revision 7704) +++ etc/grammar/JspParser.jjt (working copy) </code></pre> <p>now why does it complain that it cannot find file pmd/grammar/JspParser.jjt?</p> <p>The path in the patch is pointing to proper directory. </p>
11,652,494
2
1
null
2012-07-17 09:03:14.72 UTC
11
2021-01-29 22:38:31.837 UTC
null
null
null
null
1,341,314
null
1
44
git|svn|patch
23,964
<p>I've had a few issues applying SVN generated patches with git. I'd recommend applying any subversion patches directly with <code>patch</code> command, and use git to verify that said patch was successfully applied.</p> <pre><code>$ patch -p0 &lt; xxx_parser.patch $ git diff </code></pre>
11,588,482
How can I replace a window's URL hash with another response?
<p>I am trying to change a hashed URL (document.location.hash) with the replace method, but it doesn't work.</p> <pre><code>$(function(){ var anchor = document.location.hash; //this returns me a string value like '#categories' $('span').click(function(){ $(window).attr('url').replace(anchor,'#food'); //try to change current url.hash '#categories' //with another string, I stucked here. }); }); </code></pre> <p>I dont want to change/refresh page, I just want to replace URL without any responses.</p> <p>Note: I don't want to solve this with a href="#food" solution.</p>
11,588,511
2
11
null
2012-07-21 00:23:37.307 UTC
6
2017-04-01 13:13:55.82 UTC
2016-08-03 22:46:22.107 UTC
null
759,866
null
1,428,241
null
1
76
javascript|jquery|hash|replace|attr
86,039
<p>Either use <code>location</code> or <code>window.location</code> instead of <code>document.location</code> as the latter is a non-standard.</p> <pre><code>window.location.hash = '#food'; </code></pre> <p>This will replace the URL's hash with the value you set for it.</p> <p><a href="https://developer.mozilla.org/en/DOM/window.location" rel="noreferrer">Reference</a></p>
11,504,172
Xcode - Is there a way to drag a component from one view to another without losing its frame?
<p>What I'd like to do is drag a component/view from one superview to another in Xcode's interface-builder without having its frame/position be reset. </p> <p>Xcode's default behavior when doing this appears to be to center the view being moved vertically and horizontally in its new superview, while preserving its dimensions. This is extremely frustrating, as it means that the view needs to be manually repositioned in its new superview. But I had it positioned correctly before I moved it, so I'd like Xcode to just remember all attributes of its frame instead of just its width/height. Is this possible?</p>
16,952,902
9
5
null
2012-07-16 12:18:36.647 UTC
30
2019-11-27 05:30:00.32 UTC
2018-01-26 19:56:25.513 UTC
null
1,032,372
null
609,251
null
1
92
ios|xcode|interface-builder
27,163
<p>Another solution:</p> <ol> <li>Select the items you want in your subview, then </li> <li>(in the tool bar) Editor > Embed In > view type to embed in.</li> </ol>
11,808,074
What is an intuitive explanation of the Expectation Maximization technique?
<p>Expectation Maximization (EM) is a kind of probabilistic method to classify data. Please correct me if I am wrong if it is not a classifier. </p> <p>What is an intuitive explanation of this EM technique? What is <code>expectation</code> here and what is being <code>maximized</code>?</p>
43,561,339
8
4
null
2012-08-04 10:56:12.23 UTC
98
2019-04-28 18:28:00.697 UTC
2019-04-28 18:28:00.697 UTC
null
2,956,066
null
492,372
null
1
120
machine-learning|cluster-analysis|data-mining|mathematical-optimization|expectation-maximization
45,119
<p><em>Note: the code behind this answer can be found <a href="https://github.com/ajcr/em-explanation/blob/master/em-notebook-2.ipynb" rel="noreferrer">here</a>.</em></p> <hr> <p>Suppose we have some data sampled from two different groups, red and blue:</p> <p><a href="https://i.stack.imgur.com/JDJ1n.png" rel="noreferrer"><img src="https://i.stack.imgur.com/JDJ1n.png" alt="enter image description here"></a></p> <p>Here, we can see which data point belongs to the red or blue group. This makes it easy to find the parameters that characterise each group. For example, the mean of the red group is around 3, the mean of the blue group is around 7 (and we could find the exact means if we wanted).</p> <p>This is, generally speaking, known as <em>maximum likelihood estimation</em>. Given some data, we compute the value of a parameter (or parameters) that best explains that data.</p> <p>Now imagine that we <em>cannot</em> see which value was sampled from which group. Everything looks purple to us:</p> <p><a href="https://i.stack.imgur.com/uvcRO.png" rel="noreferrer"><img src="https://i.stack.imgur.com/uvcRO.png" alt="enter image description here"></a></p> <p>Here we have the knowledge that there are <em>two</em> groups of values, but we don't know which group any particular value belongs to. </p> <p>Can we still estimate the means for the red group and blue group that best fit this data?</p> <p>Yes, often we can! <strong>Expectation Maximisation</strong> gives us a way to do it. The very general idea behind the algorithm is this:</p> <ol> <li>Start with an initial estimate of what each parameter might be.</li> <li>Compute the <em>likelihood</em> that each parameter produces the data point.</li> <li>Calculate weights for each data point indicating whether it is more red or more blue based on the likelihood of it being produced by a parameter. Combine the weights with the data (<strong>expectation</strong>).</li> <li>Compute a better estimate for the parameters using the weight-adjusted data (<strong>maximisation</strong>).</li> <li>Repeat steps 2 to 4 until the parameter estimate converges (the process stops producing a different estimate).</li> </ol> <p>These steps need some further explanation, so I'll walk through the problem described above.</p> <h1>Example: estimating mean and standard deviation</h1> <p>I'll use Python in this example, but the code should be fairly easy to understand if you're not familiar with this language. </p> <p>Suppose we have two groups, red and blue, with the values distributed as in the image above. Specifically, each group contains a value drawn from a <a href="https://en.wikipedia.org/wiki/Normal_distribution" rel="noreferrer">normal distribution</a> with the following parameters:</p> <pre class="lang-Python prettyprint-override"><code>import numpy as np from scipy import stats np.random.seed(110) # for reproducible results # set parameters red_mean = 3 red_std = 0.8 blue_mean = 7 blue_std = 2 # draw 20 samples from normal distributions with red/blue parameters red = np.random.normal(red_mean, red_std, size=20) blue = np.random.normal(blue_mean, blue_std, size=20) both_colours = np.sort(np.concatenate((red, blue))) # for later use... </code></pre> <p>Here is an image of these red and blue groups again (to save you from having to scroll up):</p> <p><a href="https://i.stack.imgur.com/JDJ1n.png" rel="noreferrer"><img src="https://i.stack.imgur.com/JDJ1n.png" alt="enter image description here"></a></p> <p>When we can see the colour of each point (i.e. which group it belongs to), it's very easy to estimate the mean and standard deviation for each each group. We just pass the red and blue values to the builtin functions in NumPy. For example:</p> <pre class="lang-Python prettyprint-override"><code>&gt;&gt;&gt; np.mean(red) 2.802 &gt;&gt;&gt; np.std(red) 0.871 &gt;&gt;&gt; np.mean(blue) 6.932 &gt;&gt;&gt; np.std(blue) 2.195 </code></pre> <p>But what if we <em>can't</em> see the colours of the points? That is, instead of red or blue, every point has been coloured purple.</p> <p>To try and recover the mean and standard deviation parameters for the red and blue groups, we can use Expectation Maximisation.</p> <p>Our first step (<strong>step 1</strong> above) is to guess at the parameter values for each group's mean and standard deviation. We don't have to guess intelligently; we can pick any numbers we like:</p> <pre class="lang-Python prettyprint-override"><code># estimates for the mean red_mean_guess = 1.1 blue_mean_guess = 9 # estimates for the standard deviation red_std_guess = 2 blue_std_guess = 1.7 </code></pre> <p>These parameter estimates produce bell curves that look like this:</p> <p><a href="https://i.stack.imgur.com/GxLlr.png" rel="noreferrer"><img src="https://i.stack.imgur.com/GxLlr.png" alt="enter image description here"></a></p> <p>These are bad estimates. Both means (the vertical dotted lines) look far off any kind of "middle" for sensible groups of points, for instance. We want to improve these estimates.</p> <p>The next step (<strong>step 2</strong>) is to compute the likelihood of each data point appearing under the current parameter guesses:</p> <pre class="lang-Python prettyprint-override"><code>likelihood_of_red = stats.norm(red_mean_guess, red_std_guess).pdf(both_colours) likelihood_of_blue = stats.norm(blue_mean_guess, blue_std_guess).pdf(both_colours) </code></pre> <p>Here, we have simply put each data point into the <a href="https://en.wikipedia.org/wiki/Normal_distribution" rel="noreferrer">probability density function</a> for a normal distribution using our current guesses at the mean and standard deviation for red and blue. This tells us, for example, that with our current guesses the data point at 1.761 is <em>much</em> more likely to be red (0.189) than blue (0.00003). </p> <p>For each data point, we can turn these two likelihood values into weights (<strong>step 3</strong>) so that they sum to 1 as follows:</p> <pre class="lang-Python prettyprint-override"><code>likelihood_total = likelihood_of_red + likelihood_of_blue red_weight = likelihood_of_red / likelihood_total blue_weight = likelihood_of_blue / likelihood_total </code></pre> <p>With our current estimates and our newly-computed weights, we can now compute <em>new</em> estimates for the mean and standard deviation of the red and blue groups (<strong>step 4</strong>).</p> <p>We twice compute the mean and standard deviation using <em>all</em> data points, but with the different weightings: once for the red weights and once for the blue weights.</p> <p>The key bit of intuition is that the greater the weight of a colour on a data point, the more the data point influences the next estimates for that colour's parameters. This has the effect of "pulling" the parameters in the right direction.</p> <pre class="lang-Python prettyprint-override"><code>def estimate_mean(data, weight): """ For each data point, multiply the point by the probability it was drawn from the colour's distribution (its "weight"). Divide by the total weight: essentially, we're finding where the weight is centred among our data points. """ return np.sum(data * weight) / np.sum(weight) def estimate_std(data, weight, mean): """ For each data point, multiply the point's squared difference from a mean value by the probability it was drawn from that distribution (its "weight"). Divide by the total weight: essentially, we're finding where the weight is centred among the values for the difference of each data point from the mean. This is the estimate of the variance, take the positive square root to find the standard deviation. """ variance = np.sum(weight * (data - mean)**2) / np.sum(weight) return np.sqrt(variance) # new estimates for standard deviation blue_std_guess = estimate_std(both_colours, blue_weight, blue_mean_guess) red_std_guess = estimate_std(both_colours, red_weight, red_mean_guess) # new estimates for mean red_mean_guess = estimate_mean(both_colours, red_weight) blue_mean_guess = estimate_mean(both_colours, blue_weight) </code></pre> <p>We have new estimates for the parameters. To improve them again, we can jump back to step 2 and repeat the process. We do this until the estimates converge, or after some number of iterations have been performed (<strong>step 5</strong>).</p> <p>For our data, the first five iterations of this process look like this (recent iterations have stronger appearance):</p> <p><a href="https://i.stack.imgur.com/QbKmW.png" rel="noreferrer"><img src="https://i.stack.imgur.com/QbKmW.png" alt="enter image description here"></a></p> <p>We see that the means are already converging on some values, and the shapes of the curves (governed by the standard deviation) are also becoming more stable. </p> <p>If we continue for 20 iterations, we end up with the following:</p> <p><a href="https://i.stack.imgur.com/RVFBC.png" rel="noreferrer"><img src="https://i.stack.imgur.com/RVFBC.png" alt="enter image description here"></a></p> <p>The EM process has converged to the following values, which turn out to very close to the actual values (where we can see the colours - no hidden variables):</p> <pre><code> | EM guess | Actual | Delta ----------+----------+--------+------- Red mean | 2.910 | 2.802 | 0.108 Red std | 0.854 | 0.871 | -0.017 Blue mean | 6.838 | 6.932 | -0.094 Blue std | 2.227 | 2.195 | 0.032 </code></pre> <p>In the code above you may have noticed that the new estimation for standard deviation was computed using the previous iteration's estimate for the mean. Ultimately it does not matter if we compute a new value for the mean first as we are just finding the (weighted) variance of values around some central point. We will still see the estimates for the parameters converge.</p>
11,908,156
Call static method with reflection
<p>I have several static classes in the namespace <code>mySolution.Macros</code> such as </p> <pre><code>static class Indent{ public static void Run(){ // implementation } // other helper methods } </code></pre> <p><strong>So my question is how it will be possible to call those methods with the help of reflection?</strong></p> <p>If the methods where NOT to be static then I could do something like:</p> <pre><code>var macroClasses = Assembly.GetExecutingAssembly().GetTypes().Where( x =&gt; x.Namespace.ToUpper().Contains("MACRO") ); foreach (var tempClass in macroClasses) { var curInsance = Activator.CreateInstance(tempClass); // I know have an instance of a macro and will be able to run it // using reflection I will be able to run the method as: curInsance.GetType().GetMethod("Run").Invoke(curInsance, null); } </code></pre> <p>I will like to keep my classes static. How will I be able to do something similar with static methods?</p> <p><strong>In short</strong> I will like to call all the Run methods from all the static classes that are in the namespace mySolution.Macros.</p>
11,908,192
4
0
null
2012-08-10 19:37:23.903 UTC
17
2021-02-19 11:40:15.423 UTC
null
null
null
null
637,142
null
1
135
c#|reflection|dynamic
124,432
<p>As the <a href="http://msdn.microsoft.com/en-us/library/a89hcwhh.aspx" rel="noreferrer">documentation for MethodInfo.Invoke</a> states, the first argument is ignored for static methods so you can just pass null.</p> <pre><code>foreach (var tempClass in macroClasses) { // using reflection I will be able to run the method as: tempClass.GetMethod("Run").Invoke(null, null); } </code></pre> <p>As the comment points out, you may want to ensure the method is static when calling <code>GetMethod</code>:</p> <pre><code>tempClass.GetMethod("Run", BindingFlags.Public | BindingFlags.Static).Invoke(null, null); </code></pre>
3,595,164
get server time in php - timezone issues
<p>on shell, my server time is (simple <code>date</code> in bash): Sun Aug 29 10:37:12 EDT 2010</p> <p>when I run the code <code>php -r "echo date('Y-m-d H:i:s');"</code> I get: 2010-08-29 10:37:10</p> <p>but when I execute a php script that has <code>echo date('Y-m-d H:i:s');</code> I get a different time- since php thinks the timezone is UTC (server time is EDT).</p> <p>My php.ini file has no timezone set, and I wouldnt like to change anything- as I have no idea what affect it would have on other sites that run on this server.</p> <p>Is there a simple way to get the server time- at the timezone that is set for the server?</p>
3,595,188
4
0
null
2010-08-29 14:42:32.71 UTC
9
2013-09-25 18:18:50.4 UTC
null
null
null
null
354,405
null
1
19
php|timezone
40,089
<p>According to the <a href="http://ca3.php.net/manual/en/datetime.configuration.php#ini.date.timezone" rel="noreferrer">php.ini directives</a> manual page, the timezone isn't set by default if you're using a version prior to 5.3. Then if you take a look at the page for <a href="http://ca3.php.net/manual/en/function.date-default-timezone-get.php" rel="noreferrer"><code>date_default_timezone_get</code></a>, it uses the following order for getting the timezone:</p> <pre><code>* Reading the timezone set using the date_default_timezone_set() function (if any) * Reading the TZ environment variable (if non empty) (Prior to PHP 5.3.0) * Reading the value of the date.timezone ini option (if set) * Querying the host operating system (if supported and allowed by the OS) </code></pre> <p>UTC is the default if all of those fail, so that's probably a good starting point.</p>
3,733,648
How to design the artificial intelligence of a fighting game (Street Fighter or Soul Calibur)?
<p>There are many papers about ranged combat artificial intelligences, like Killzones's (<a href="http://www.cgf-ai.com/docs/straatman_remco_killzone_ai.pdf" rel="noreferrer" title="Killzone">see this paper</a>), or Halo. But I've not been able to find much about a fighting IA except for this <a href="http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.116.592&amp;rep=rep1&amp;type=pdf" rel="noreferrer" title="Learning to Fight">work</a>, which uses neural networs to learn how to fight, which is not exactly what I'm looking for.</p> <p>Occidental AI in games is heavily focused on FPS, it seems! Does anyone know which techniques are used to implement a decent fighting AI? Hierarchical Finite State Machines? Decision Trees? They could end up being pretty predictable.</p>
3,733,840
5
3
null
2010-09-17 08:13:12.223 UTC
13
2014-04-14 18:52:24.93 UTC
null
null
null
null
448,401
null
1
14
artificial-intelligence
17,824
<p>In our research labs, we are using AI planning technology for games. AI Planning is used by NASA to build semi-autonomous robots. Planning can produce less predictable behavior than state machines, but planning is a highly complex problem, that is, solving planning problems has a huge computational complexity. </p> <p>AI Planning is an old but interesting field. Particularly for gaming only recently people have started using planning to run their engines. The expressiveness is still limited in the current implementations, but in theory the expressiveness is limited "only by our imagination". </p> <p>Russel and Norvig have devoted 4 chapters on AI Planning in their book on Artificial Intelligence. Other related terms you might be interested in are: Markov Decision Processes, Bayesian Networks. These topics are also provided sufficient exposure in this book. </p> <p>If you are looking for some ready-made engine to easily start using, I guess using AI Planning would be a gross overkill. I don't know of any AI Planning engine for games but we are developing one. If you are interested in the long term, we can talk separately about it. </p>
3,358,410
Programmatically run at startup on Mac OS X?
<p>How do I programmatically set an application bundle on Mac OS X to run when the user logs in?</p> <p>Basically, the equivalent of the <code>HKCU\Software\Microsoft\Windows\CurrentVersion\Run</code> registry key in Windows.</p>
3,358,472
5
0
null
2010-07-28 23:38:21.63 UTC
15
2021-10-01 10:49:52.983 UTC
null
null
null
null
343,845
null
1
23
macos|autorun
15,053
<p>You can add the application to the user's "Login Items" (under System Preferences=>Accounts=[user]) or you can add a <a href="https://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man5/launchd.plist.5.html" rel="noreferrer">launchd</a> agent to the user's <code>~/Library/LaunchAgents</code> folder (see <code>man launchd.plist</code>). Use <code>~/Library/LaunchDaemons/</code> if your app has no user-facing UI. As others point out, launchd gives you a lot of control over when the app starts, what happens if the app quits or crashes, etc. and is most appropriate for "daemon" style apps (with our without UI).</p> <p>The first option (Login Items) can be manipulated <a href="https://developer.apple.com/library/mac/documentation/macosx/conceptual/bpsystemstartup/chapters/CustomLogin.html" rel="noreferrer">programmatically</a> (link from <a href="https://stackoverflow.com/users/89817/gordon-davisson">Gordon</a>).</p>
3,453,560
Haml: Append class if condition is true in Haml
<p>If <code>post.published?</code></p> <pre><code>.post / Post stuff </code></pre> <p>Otherwise</p> <pre><code>.post.gray / Post stuff </code></pre> <p>I've implemented this with rails helper and it seems ugly.</p> <pre><code>= content_tag :div, :class =&gt; "post" + (" gray" unless post.published?).to_s do / Post stuff </code></pre> <p>Second variant:</p> <pre><code>= content_tag :div, :class =&gt; "post" + (post.published? ? "" : " gray") do / Post stuff </code></pre> <p>Is there a more simple and haml-specific way?</p> <p>UPD. Haml-specific, but still not simple:</p> <pre><code>%div{:class =&gt; "post" + (" gray" unless post.published?).to_s} / Post stuff </code></pre>
3,454,556
5
0
null
2010-08-10 21:23:21.467 UTC
36
2021-06-30 08:18:14.497 UTC
2021-06-30 08:18:14.497 UTC
null
10,907,864
null
199,607
null
1
160
ruby|haml
72,911
<pre><code>.post{:class =&gt; ("gray" unless post.published?)} </code></pre>
3,883,138
How do I read the number of files in a folder using Python?
<p>How do I read the number of files in a specific folder using Python? Example code would be awesome!</p>
3,883,201
6
0
null
2010-10-07 15:17:14.36 UTC
4
2021-08-17 00:24:25.523 UTC
2010-10-07 15:42:36.437 UTC
null
21,234
null
359,844
null
1
19
python|file-io
45,856
<p>To count files and directories non-recursively you can use <a href="http://docs.python.org/library/os.html#os.listdir" rel="noreferrer"><code>os.listdir</code></a> and take its length.</p> <p>To count files and directories recursively you can use <a href="http://docs.python.org/library/os.html#os.walk" rel="noreferrer"><code>os.walk</code></a> to iterate over the files and subdirectories in the directory.</p> <p>If you only want to count files not directories you can use <code>os.listdir</code> and <a href="http://docs.python.org/library/os.path.html#os.path.isfile" rel="noreferrer"><code>os.path.file</code></a> to check if each entry is a file:</p> <pre><code>import os.path path = '.' num_files = len([f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))]) </code></pre> <p>Or alternatively using a generator:</p> <pre><code>num_files = sum(os.path.isfile(os.path.join(path, f)) for f in os.listdir(path)) </code></pre> <p>Or you can use <code>os.walk</code> as follows:</p> <pre><code>len(os.walk(path).next()[2]) </code></pre> <p>I found some of these ideas from <a href="http://bytes.com/topic/python/answers/45188-count-files-directory" rel="noreferrer">this thread</a>.</p>
4,044,451
How to change all the keys of a hash by a new set of given keys
<p>How do I change all the keys of a hash by a new set of given keys?</p> <p>Is there a way to do that elegantly?</p>
52,511,212
7
0
null
2010-10-28 15:32:37.523 UTC
14
2020-01-10 01:35:12.703 UTC
2016-03-28 22:25:37.937 UTC
null
128,421
null
178,925
null
1
48
ruby|hash
22,077
<p>Ruby 2.5 has <a href="https://ruby-doc.org/core-2.5.0/Hash.html#method-i-transform_keys" rel="noreferrer">Hash#transform_keys!</a> method. Example using a map of keys</p> <pre><code>h = {a: 1, b: 2, c: 3} key_map = {a: 'A', b: 'B', c: 'C'} h.transform_keys! {|k| key_map[k]} # =&gt; {"A"=&gt;1, "B"=&gt;2, "C"=&gt;3} </code></pre> <p>You can also use symbol#toproc shortcut with transform_keys Eg:</p> <pre><code>h.transform_keys! &amp;:upcase # =&gt; {"A"=&gt;1, "B"=&gt;2, "C"=&gt;3} </code></pre>
3,311,774
How to convert existing non-empty directory into a Git working directory and push files to a remote repository
<ol> <li><p>I have a non-empty directory (eg /etc/something) with files that cannot be renamed, moved, or deleted.</p></li> <li><p>I want to check this directory into git in place.</p></li> <li><p>I want to be able to push the state of this repository to a remote repository (on another machine) using "git push" or something similar.</p></li> </ol> <p>This is trivial using Subversion (currently we do it using Subversion) using:</p> <pre><code>svn mkdir &lt;url&gt; -m &lt;msg&gt; cd &lt;localdir&gt; svn co &lt;url&gt; . svn add &lt;files etc&gt; svn commit -m &lt;msg&gt; </code></pre> <p>What is the git equivalent?</p> <p>Can I "git clone" into an empty directory and simply move the .git directory and have everything work?</p>
3,311,824
9
3
null
2010-07-22 17:48:35.853 UTC
269
2021-07-13 18:36:09.09 UTC
2015-09-10 06:46:38.217 UTC
null
2,666,182
null
399,423
null
1
775
git
422,899
<p>Given you've set up a git daemon on <code>&lt;url&gt;</code> and an empty repository:</p> <pre><code>cd &lt;localdir&gt; git init git add . git commit -m 'message' git remote add origin &lt;url&gt; git push -u origin master </code></pre>
4,020,419
Why aren't python nested functions called closures?
<p>I have seen and used nested functions in Python, and they match the definition of a closure. So why are they called &quot;nested functions&quot; instead of &quot;closures&quot;?</p> <p>Are nested functions not closures because they are not used by the external world?</p> <p><strong>UPDATE:</strong> I was reading about closures and it got me thinking about this concept with respect to Python. I searched and found the article mentioned by someone in a comment below, but I couldn't completely understand the explanation in that article, so that is why I am asking this question.</p>
4,020,443
10
3
null
2010-10-26 03:11:14.41 UTC
173
2022-08-04 00:28:19.157 UTC
2022-07-30 18:36:53.037 UTC
null
4,518,341
null
147,019
null
1
275
python|closures|nested-function
109,592
<p>A closure occurs when a function has access to a local variable from an enclosing scope that has finished its execution.</p> <pre><code>def make_printer(msg): def printer(): print(msg) return printer printer = make_printer('Foo!') printer() </code></pre> <p>When <code>make_printer</code> is called, a new frame is put on the stack with the compiled code for the <code>printer</code> function as a constant and the value of <code>msg</code> as a local. It then creates and returns the function. Because the function <code>printer</code> references the <code>msg</code> variable, it is kept alive after the <code>make_printer</code> function has returned.</p> <p>So, if your nested functions don't</p> <ol> <li>access variables that are local to enclosing scopes,</li> <li>do so when they are executed outside of that scope,</li> </ol> <p>then they are not closures.</p> <p>Here's an example of a nested function which is not a closure.</p> <pre><code>def make_printer(msg): def printer(msg=msg): print(msg) return printer printer = make_printer(&quot;Foo!&quot;) printer() #Output: Foo! </code></pre> <p>Here, we are binding the value to the default value of a parameter. This occurs when the function <code>printer</code> is created and so no reference to the value of <code>msg</code> external to <code>printer</code> needs to be maintained after <code>make_printer</code> returns. <code>msg</code> is just a normal local variable of the function <code>printer</code> in this context.</p>
7,970,622
Java 7 JVM VerifyError in Eclipse
<p>When I compile my project in eclipse indigo using JDK 7, I get the following error dialog</p> <p><img src="https://i.stack.imgur.com/mhzPv.png" alt="enter image description here"></p> <p>with the following stacktrace</p> <pre><code>Exception in thread "main" java.lang.VerifyError: Expecting a stackmap frame at branch target 32 in method ... at offset 0 at java.lang.Class.getDeclaredMethods0(Native Method) at java.lang.Class.privateGetDeclaredMethods(Unknown Source) at java.lang.Class.getMethod0(Unknown Source) at java.lang.Class.getMethod(Unknown Source) at sun.launcher.LauncherHelper.getMainMethod(Unknown Source) at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source) </code></pre> <p>I've found a relevant bug <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=339388" rel="noreferrer">here</a> and used the suggested workaround of using jvm option <code>-XX:-UseSplitVerifier</code> and although it works, this bug still confuses me.</p> <p>Does anyone know why this is happening and why the workaround...works?</p> <h3>--Note--</h3> <p>The project compiles fine using JDK 6.</p>
7,970,870
4
0
null
2011-11-01 17:54:05.653 UTC
10
2013-04-30 10:02:32.237 UTC
null
null
null
null
584,862
null
1
33
java|eclipse|jvm|java-7
27,357
<p><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=353467" rel="noreferrer">Bug 353467</a> speaks about &quot;using <code>-XX:-UseSplitVerifier</code> to activate the old verifier&quot;.<br /> That is consistent with the <a href="http://www.oracle.com/technetwork/java/javase/downloads/adoptionguide-137484.html" rel="noreferrer">JDK TM 6 Adoption Guide</a> which describes that option as:</p> <blockquote> <p>Traditional verifier can be forced with the <code>-XX:-UseSplitVerifier</code> flag.</p> <p>Missing or incorrect <code>StackMapTable</code> attributes for version <code>50.0</code> class files can result in <code>VerifyError</code> exceptions.<br /> Tools that rewrite bytecode in version <code>50.0</code> class files and do not correctly update the <code>StackMapTable</code> may fail to verify and trigger exceptions.</p> </blockquote> <p>So the <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=353467#c3" rel="noreferrer">comment from 2011-10-03</a> does point out that:</p> <blockquote> <p>AspectJ now auto activates the previously optional setting to create stackmaps if the classes are Java7.</p> </blockquote>
8,350,171
Convert string to hexadecimal in Ruby
<p>I'm trying to convert a Binary file to Hexadecimal using Ruby.</p> <p>At the moment I have the following:</p> <pre><code>File.open(out_name, 'w') do |f| f.puts "const unsigned int modFileSize = #{data.length};" f.puts "const char modFile[] = {" first_line = true data.bytes.each_slice(15) do |a| line = a.map { |b| ",#{b}" }.join if first_line f.puts line[1..-1] else f.puts line end first_line = false end f.puts "};" end </code></pre> <p>This is what the following code is generating:</p> <pre><code>const unsigned int modFileSize = 82946; const char modFile[] = { 116, 114, 97, 98, 97, 108, 97, 115, 104, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 62, 62, 62, 110, 117, 107, 101, 32, 111, 102 , 32, 97, 110, 97, 114, 99, 104, 121, 60, 60, 60, 8, 8, 130, 0 }; </code></pre> <p>What I need is the following:</p> <pre><code>const unsigned int modFileSize = 82946; const char modFile[] = { 0x74, 0x72, etc, etc }; </code></pre> <p>So I need to be able to convert a string to its hexadecimal value.</p> <p><code>"116" =&gt; "0x74"</code>, etc</p> <p>Thanks in advance.</p>
8,350,209
5
0
null
2011-12-02 00:08:32.86 UTC
2
2020-01-27 09:43:16.687 UTC
2011-12-04 23:14:51.783 UTC
null
264,802
null
264,802
null
1
7
ruby|binary|hex
47,433
<p>Change this line:</p> <pre><code>line = a.map { |b| ", #{b}" }.join </code></pre> <p>to this:</p> <pre><code>line = a.map { |b| sprintf(", 0x%02X",b) }.join </code></pre> <p>(Change to <code>%02x</code> if necessary, it's unclear from the example whether the hex digits should be capitalized.)</p>
7,831,755
What is the simplest way of getting user input in C?
<p>There seem to be a LOT of ways you can get user input in C. </p> <p>What is the easiest way that requires little code?</p> <p>Basically I need to display this:</p> <pre><code>Enter a file name: apple.text </code></pre> <p>Basically I need to ask the user for a file name. So I need something that just gets that one word that the user will be inputting. </p>
7,832,033
6
1
null
2011-10-20 06:05:38.52 UTC
15
2016-11-27 12:11:56.997 UTC
2011-10-20 06:07:47.073 UTC
null
635,608
null
1,004,278
null
1
20
c|input|io|scanf
84,427
<p>The simplest <i>"correct"</i> way is probably this one, taken from Bjarne Stroustrup's paper <a href="http://www.stroustrup.com/new_learning.pdf" rel="nofollow noreferrer">Learning Standard C++ As A New Language</a>.</p> <p><em>(Note: I changed Bjarne's code to check for <code>isspace()</code> instead of just end of line. Also, due to @matejkramny's comment, to use <code>while(1)</code> instead of <code>while(true)</code>...and so long as we're being heretical enough to edit Stroustrup's code, I've subbed in C89 comments instead of C++ style too. :-P)</em></p> <pre><code>#include &lt;stdio.h&gt; #include &lt;ctype.h&gt; #include &lt;stdlib.h&gt; void quit() /* write error message and quit */ { fprintf(stderr, "memory exhausted\n"); exit(1); } int main() { int max = 20; char* name = (char*) malloc(max); /* allocate buffer */ if (name == 0) quit(); printf("Enter a file name: "); while (1) { /* skip leading whitespace */ int c = getchar(); if (c == EOF) break; /* end of file */ if (!isspace(c)) { ungetc(c, stdin); break; } } int i = 0; while (1) { int c = getchar(); if (isspace(c) || c == EOF) { /* at end, add terminating zero */ name[i] = 0; break; } name[i] = c; if (i == max - 1) { /* buffer full */ max += max; name = (char*) realloc(name, max); /* get a new and larger buffer */ if (name == 0) quit(); } i++; } printf("The filename is %s\n", name); free(filename); /* release memory */ return 0; } </code></pre> <p>That covers:</p> <ul> <li>skipping whitespace until you reach character input</li> <li>expanding the string buffer dynamically to fit arbitrary size strings</li> <li>handling conditions of when memory can't be allocated</li> </ul> <p>Are there simpler but broken solutions, which might even run a bit faster? Absolutely!!</p> <p>If you use scanf into a buffer with no limit on the read size, then your input exceeds the size of the buffer, it will create a security hole and/or crash.</p> <p>Limiting the size of the reading to, say, only 100 unique characters of a filename might seem better than crashing. But it can be worse; for instance if the user meant <code>(...)/dir/foo/bar.txt</code> but you end up misinterpreting their input and overwriting a file called <code>bar.t</code> which perhaps they cared about.</p> <p>It's best to get into good habits early in dealing with these issues. <em>My opinion</em> is that if your requirements justify something close-to-the-metal and "C-like", it's well worth it to consider the jump to C++. It was designed to manage precisely these concerns--with techniques that are robust and extensible, yet still perform well.</p>
8,074,955
cannot import name patterns
<p>Before I wrote in <code>urls.py</code>, my code... everything worked perfectly. Now I have problems - can't go to my site. "cannot import name patterns"</p> <p>My <code>urls.py</code> is:</p> <pre><code>from django.conf.urls import patterns, include, url </code></pre> <p>They said what error is somewhere here.</p>
8,075,082
9
3
null
2011-11-10 04:18:43.78 UTC
16
2020-11-17 18:56:56.11 UTC
2011-11-10 04:23:23.577 UTC
null
950,912
null
893,452
null
1
79
python|django
129,789
<p>You don't need those imports. The only thing you need in your urls.py (to start) is:</p> <pre><code>from django.conf.urls.defaults import * # This two if you want to enable the Django Admin: (recommended) from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^admin/', include(admin.site.urls)), # ... your url patterns ) </code></pre> <p><strong>NOTE:</strong> This solution was intended for Django &lt;1.6. This was actually the code generated by Django itself. For newer version, see Jacob Hume's answer.</p>
8,223,811
A top-like utility for monitoring CUDA activity on a GPU
<p>I'm trying to monitor a process that uses CUDA and MPI, is there any way I could do this, something like the command &quot;top&quot; but that monitors the GPU too?</p>
51,406,093
16
1
null
2011-11-22 08:19:41.257 UTC
84
2022-04-15 08:40:29.8 UTC
2020-08-20 14:54:45.51 UTC
null
1,593,077
null
479,517
null
1
204
cuda|process-monitoring|resource-monitor
262,098
<p>I find <a href="https://github.com/wookayin/gpustat" rel="noreferrer">gpustat</a> very useful. In can be installed with <code>pip install gpustat</code>, and prints breakdown of usage by processes or users.</p> <p><a href="https://i.stack.imgur.com/NNI8r.png" rel="noreferrer"><img src="https://i.stack.imgur.com/NNI8r.png" alt="enter image description here"></a></p>
4,739,667
Why does Twitter use a hash and exclamation mark in URLs, and how do they rewrite search URLs?
<p>We understand the hash is for AJAX searches, but the exclamation mark? Anyone know?</p> <p>Also, the "action" attribute for their search form points to "/search," but when you conduct a search, the hash exclamation mark appears in the URL. Are they simply redirecting from "/search" to "/#!/search"?</p> <p><strong>Note:</strong> the second part of the q remains unanswered: That is, are they redirecting the user from "/search" to "/#!/search", or do they send the user to "/search" and use JS on the page to rewrite the URL? – Crashalot Jan 26 at 23:51 </p> <p>Thanks!</p>
7,257,427
3
1
null
2011-01-19 19:23:50.137 UTC
7
2011-08-31 13:16:32.69 UTC
2011-05-08 03:17:55.563 UTC
null
144,088
null
144,088
null
1
33
ajax|twitter|fragment-identifier
14,058
<p>To answer the second part then: It is redirecting you to /#!/search.</p> <p>If you look at the response headers when going to <a href="http://twitter.com/britishdev" rel="noreferrer">http://twitter.com/britishdev</a> (plug plug) you are returned a 302 (temporary redirect) with the Location header set as "Location: <a href="http://twitter.com/#!/britishdev" rel="noreferrer">http://twitter.com/#!/britishdev</a>"</p> <p>Yes JavaScript is then pulling all your detail in on the destination page but regardless that is where you are redirected to.</p>
14,420,871
String Array object in Java
<p>I am trying to print the first element on the two arrays in my Athlete class, country and name. I also need to create a object that simulates three dive attemps an athlete had (that is initially set to zero). I am new to OOP and I dont know how to go abouts doing this in my main... as far as constructors go. This is what i have done so far...</p> <p>this is the main:</p> <pre><code>import java.util.Random; import java.util.List; public class Assignment1 { public static void main(String[] args) { Athlete art = new Athlete(name[0], country[0], performance[0]); } } </code></pre> <p>I just really am not sure what to do...</p> <p>And this is the class with the arrays.</p> <pre><code> import java.util.Random; import java.util.List; public class Athlete { public String[] name = {"Art", "Dan", "Jen"}; public String[] country = {"Canada", "Germant", "USA"}; //Here i would like to create something that would be representing 3 dive attemps (that relate to dive and score. eventually.) Athlete(String[] name, String[] country, Performance[] performance) { this.name = name; this.country=country; this.performance=performance; } public Performance Perform(Dive dive){ dive.getDiveName(); return null; } public String[] getName() { return name; } public void setName(String[] name) { this.name = name; } public String[] getCountry() { return country; } public void setCountry(String[] country) { this.country = country; } } </code></pre> <p>thanks in advance for any help and input! btw there is other classes too, just not relevant atm..</p>
14,420,966
6
0
null
2013-01-20 01:38:30.873 UTC
3
2019-10-14 05:41:56.62 UTC
null
null
null
null
1,290,169
null
1
7
java|arrays|oop
128,157
<p><strong>First</strong>, as for your Athlete class, you can remove your <code>Getter and Setter</code> methods since you have declared your instance variables with an access modifier of <code>public</code>. You can access the variables via <code>&lt;ClassName&gt;.&lt;variableName&gt;</code>. <br><br>However, if you really want to use that <code>Getter and Setter</code>, change the <code>public</code> modifier to <code>private</code> instead. <br></p> <p><strong>Second</strong>, for the constructor, you're trying to do a simple technique called <code>shadowing</code>. <code>Shadowing</code> is when you have a method having a parameter with the same name as the declared variable. This is an example of <code>shadowing</code>:<br> <code>----------Shadowing sample----------</code><br> You have the following class:</p> <pre><code>public String name; public Person(String name){ this.name = name; // This is Shadowing } </code></pre> <p>In your main method for example, you instantiate the <code>Person</code> class as follow:<br> <code>Person person = new Person("theolc");</code> <br></p> <p>Variable <code>name</code> will be equal to <code>"theolc"</code>.<br> <code>----------End of shadowing----------</code><br></p> <p>Let's go back to your question, if you just want to print the first element with your current code, you may remove the <code>Getter and Setter</code>. Remove your parameters on your <code>constructor</code>.</p> <pre><code>public class Athlete { public String[] name = {"Art", "Dan", "Jen"}; public String[] country = {"Canada", "Germany", "USA"}; public Athlete() { } </code></pre> <p>In your main method, you could do this.</p> <pre><code>public static void main(String[] args) { Athlete art = new Athlete(); System.out.println(art.name[0]); System.out.println(art.country[0]); } } </code></pre>
4,542,694
Getting-started: Setup Database for Node.js
<p>I am new to node.js but am excited to try it out. I am using <a href="http://expressjs.com/" rel="nofollow noreferrer">Express</a> as a web framework, and <a href="http://jade-lang.com" rel="nofollow noreferrer">Jade</a> as a template engine. Both were easy to get setup following <a href="http://www.ustream.tv/recorded/11434722" rel="nofollow noreferrer">this tutorial</a> from <a href="http://camp.nodejs.org/" rel="nofollow noreferrer">Node Camp</a>.</p> <p>However the one problem I am finding is <strong>I can't find a simple tutorial for getting a DB set up</strong>. I am trying to build a basic chat application (store session and message).</p> <p><strong>Does anyone know of a good tutorial?</strong> </p> <p>This other <a href="https://stackoverflow.com/questions/2750673/node-js-database">SO post</a> talks about dbs to use- but as this is very different from the Django/MySQL world I've been in, I want to make sure I understand what is going on.</p> <p>Thanks!</p>
4,542,960
4
1
null
2010-12-27 23:45:29.267 UTC
78
2012-07-20 20:10:27.413 UTC
2017-05-23 12:34:02.027 UTC
null
-1
null
424,303
null
1
82
javascript|database|node.js
22,540
<p><strong>I assume you have <a href="https://github.com/isaacs/npm" rel="nofollow noreferrer">npm</a> installed the correct way using one of these <a href="https://gist.github.com/579814" rel="nofollow noreferrer">snippets</a>(I used the top one).</strong></p> <h2>Redis</h2> <p>I would use redis as a database. For one it is really <a href="http://redis.io/topics/benchmarks" rel="nofollow noreferrer">fast</a>, persistent. You need to install it, but that is really easy.</p> <pre><code>make </code></pre> <h2>Redis-cli</h2> <p>Next you should play with redis yourself. I would advice you to look at this excellent tutorial by <a href="http://simonwillison.net/static/2010/redis-tutorial/" rel="nofollow noreferrer">Simon Willison</a>. He and I also advice you to just play with the <code>redis-cli</code> to get a feeling of the database.</p> <h2>Redis client</h2> <p>Finally you need to install a redis client. I would advise you to use mranney's <a href="https://github.com/mranney/node_redis" rel="nofollow noreferrer">node_redis</a> because I think it is the fastest and most actively developed client.</p> <p><strong>Installation</strong></p> <pre><code>npm install hiredis redis </code></pre> <p><strong>Simple example, included as example.js:</strong></p> <pre><code>var redis = require("redis"), client = redis.createClient(); client.on("error", function (err) { console.log("Error " + err); }); client.set("string key", "string val", redis.print); client.hset("hash key", "hashtest 1", "some value", redis.print); client.hset(["hash key", "hashtest 2", "some other value"], redis.print); client.hkeys("hash key", function (err, replies) { console.log(replies.length + " replies:"); replies.forEach(function (reply, i) { console.log(" " + i + ": " + reply); }); client.quit(); }); </code></pre> <h2>Storing sessions in database</h2> <p>Also the author of express has created a library to handle your <a href="https://github.com/visionmedia/connect-redis" rel="nofollow noreferrer">sessions</a> using redis.</p> <p><strong>Installation:</strong></p> <pre><code>npm install connect-redis </code></pre> <p><strong>Example:</strong></p> <pre><code>var connect = require('connect') , RedisStore = require('connect-redis'); connect.createServer( connect.cookieDecoder(), // 5 minutes connect.session({ store: new RedisStore({ maxAge: 300000 }) }) ); </code></pre> <h2>Storing messages in database</h2> <p>I think I would use a <a href="http://redis.io/commands#sorted_set" rel="nofollow noreferrer">sorted set</a> for this. Store the messages using <code>ZADD</code> and retrieve them using <code>ZRANK</code>, <code>ZRANGEBYSCORE</code>.</p> <h2>Socket.io</h2> <p>Finally if you are trying to create a simple chat I would advise you to have a look at socket.io.</p> <blockquote> <p>socket.io aims to make realtime apps possible in every browser and mobile device, blurring the differences between the different transport mechanisms.</p> </blockquote> <p>I also created a chat using socket.io which I posted on <a href="https://stackoverflow.com/questions/4441798/how-to-use-redis-publish-subscribe-with-nodejs-by-event-driven/4446424#4446424">stackoverflow</a>. Adding persistence + authentication should be a breeze.</p>