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
8,780,413
salesforce SOQL : query to fetch all the fields on the entity
<p>I was going through the SOQL documentation , but couldn't find query to fetch all the field data of an entity say , Account , like </p> <pre><code>select * from Account [ SQL syntax ] </code></pre> <p>Is there a syntax like the above in SOQL to fetch all the data of account , or the only way is to list all the fields ( though there are lot of fields to be queried ) </p>
8,780,460
6
0
null
2012-01-08 19:15:00.743 UTC
2
2019-01-09 10:20:06.893 UTC
null
null
null
null
227,100
null
1
17
salesforce|soql
40,153
<p>You have to specify the fields, if you want to build something dynamic the describeSObject call returns the metadata about all the fields for an object, so you can build the query from that.</p>
8,384,120
Equivalent function for xticks for an AxesSubplot object
<p>So I am trying to use Axes objects to control my matlibplot figure. I am not using plt (aka import matlibplot.pyplot as plt) because I am embedding the figure in my tkinter GUI per <a href="http://matplotlib.sourceforge.net/examples/user_interfaces/embedding_in_tk.html" rel="noreferrer">this</a>.</p> <p>However, I am also using subplots in the figure, so something like:</p> <pre><code>a = f.add_subplot(121) a2 = f.add_subplot(122) a.plot(fn2,mag) a2.bar(range(0,10), magBin, width) </code></pre> <p>This is all well and good, I can use the axes properties to control things (i.e. a.axesMethod()), but I want string labels for my bar plots, per <a href="http://matplotlib.sourceforge.net/users/screenshots.html#bar-charts" rel="noreferrer">this</a>, see <a href="http://matplotlib.sourceforge.net/mpl_examples/pylab_examples/barchart_demo.py" rel="noreferrer">code</a>.</p> <p>My dilemma is that I cannot use</p> <pre><code>plt.xticks(ind+width, ('G1', 'G2', 'G3', 'G4', 'G5') ) </code></pre> <p>as in the example, because I cannot use plt if i want to embed it into my tkinter gui. I am limited to what I can do with Axes objects. I am trying to use a2.set_xticks, but this does not allow for the string as ticks functionality I need for my bar chart.</p> <p>Any help in this regard would be amazing!</p> <p>Tyler</p>
8,384,229
1
0
null
2011-12-05 10:46:36.177 UTC
7
2018-06-05 12:46:43.153 UTC
null
null
null
null
402,632
null
1
69
python|matplotlib|tkinter
71,712
<p>you can use instead:</p> <pre><code>axes.set_xticks(ticks, minor=False) </code></pre> <p>and</p> <pre><code>axes.set_xticklabels(labels, fontdict=None, minor=False) </code></pre>
8,574,332
How to change port number for apache in WAMP
<p>I am new to WAMP server and installed it on my system but after installing it when I check it by going to localhost url like this <code>http://localhost/</code> in the browser it is not working. I am getting a <strong>404 error and blank page</strong>. </p> <p>This is because my 80 port which default in <code>Wamp server</code> is being used by IIS server. So please let me know how to change port number in Wamp server and solved this problem.</p>
8,574,355
8
0
null
2011-12-20 10:56:03.307 UTC
31
2019-09-13 05:27:40.833 UTC
2014-01-15 13:48:56.49 UTC
null
998,627
null
998,627
null
1
123
apache|wamp
366,229
<p>Click on the WAMP server icon and from the menu under <em>Config Files</em> select <code>httpd.conf</code>. A long text file will open up in notepad. In this file scroll down to the line that reads <code>Port 80</code> and change this to read <code>Port 8080</code>, Save the file and close notepad. Once again click on the wamp server icon and select restart all services. One more change needs to be made before we are done. In Windows Explorer find the location where WAMP server was installed which is by Default <code>C:\Wamp</code>.</p> <hr> <p><strong>Update :</strong> On a newer version of WAMP, click the <em>WAMP server icon</em> <strong>></strong> <em>Apache</em> <strong>></strong> <code>httpd.conf</code>, then change the line <code>Listen 80</code> to <code>Listen 8080</code> or any port you want.</p> <p><strong>Update:</strong> On 3.1.6 version of WAMP , right click on the <em>wamp server icon</em> in the taskbar ,select "tools"-> "Port used by Apache:80" -> "use a port other than 80", an input box will pop up , input a new port in it,click confirm button , then restart wamp . </p>
27,322,826
angular restriction to not allow spaces in text field
<p>I do not want a user to enter spaces in a text field. I don't want it on submit validation but rather - a space will not show up on the text field when they click it. </p>
27,330,469
8
1
null
2014-12-05 18:56:59.003 UTC
6
2020-06-13 12:45:50.943 UTC
null
null
null
null
866,206
null
1
16
angularjs|angularjs-directive
45,020
<pre><code>&lt;input ng-model="field" ng-trim="false" ng-change="field = field.split(' ').join('')" type="text"&gt; </code></pre> <p>Update: To improve code quality you can create custom directive instead. But don't forget that your directive should prevent input not only from keyboard, but also from pasting.</p> <pre><code>&lt;input type="text" ng-trim="false" ng-model="myValue" restrict-field="myValue"&gt; </code></pre> <p>Here is important to add ng-trim="false" attribute to disable trimming of an input.</p> <pre><code>angular .module('app') .directive('restrictField', function () { return { restrict: 'AE', scope: { restrictField: '=' }, link: function (scope) { // this will match spaces, tabs, line feeds etc // you can change this regex as you want var regex = /\s/g; scope.$watch('restrictField', function (newValue, oldValue) { if (newValue != oldValue &amp;&amp; regex.test(newValue)) { scope.restrictField = newValue.replace(regex, ''); } }); } }; }); </code></pre>
30,712,235
Spinner Dropdown Arrow
<p>I am trying to obtain a custom Spinner such as this one:</p> <p><img src="https://i.stack.imgur.com/lkJ4K.png" alt=""></p> <p>but I was only able to get this:</p> <p><img src="https://i.stack.imgur.com/PEUWC.png" alt="enter image description here"></p> <p>As you can see I experience several problems. </p> <ol> <li>Although I added a custom arrow, I still see the original.</li> <li>My custom arrow gets shown at every row.</li> <li>How do I adjust my custom arrow's dimensions and layout position?</li> <li>How do I generate underlined rows?</li> </ol> <p>This is my code:</p> <p><code>onCreateView()</code>:</p> <pre><code>Spinner spinner = (Spinner) rootView.findViewById(R.id.spinner); this.arraySpinner = new String[]{ "Seleziona una data", "03 Agosto 2015", "13 Giugno 2015", "27 Novembre 2015", "30 Dicembre 2015", }; ArrayAdapter&lt;String&gt; adapter = new ArrayAdapter&lt;&gt;( getActivity(), R.layout.row_spinner, R.id.weekofday, arraySpinner); spinner.setAdapter(adapter); </code></pre> <p><code>res/layout/row_spinner.xml</code>:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:padding="8dp"&gt; &lt;TextView android:id="@+id/weekofday" android:singleLine="true" android:textSize="@dimen/textSize" style="@style/SpinnerDropdown" android:layout_width="wrap_content" android:layout_height="wrap_content"/&gt; &lt;ImageView android:id="@+id/icon" android:paddingStart="8dp" android:paddingLeft="8dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/spinner_arrow"/&gt; &lt;/LinearLayout&gt; </code></pre> <blockquote> <p><strong>EDIT</strong></p> </blockquote> <p>I've removed the <code>ImageView</code> and added a second <code>Spinner</code>created from Resource:</p> <pre><code>ArrayAdapter&lt;CharSequence&gt; adapter = ArrayAdapter.createFromResource( getActivity(), R.array.date, R.layout.spinner_layout); spinnerDate.setAdapter(adapter); Spinner spinnerTime = (Spinner) rootView.findViewById(R.id.spinnerTime); ArrayAdapter&lt;CharSequence&gt; adapterTime = ArrayAdapter.createFromResource( getActivity(), R.array.ore, R.layout.spinner_layout); spinnerTime.setAdapter(adapterTime); </code></pre> <p>with this layout:</p> <pre><code>&lt;TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@android:id/text1" android:padding="8dp" android:singleLine="true" android:layout_height="wrap_content" android:layout_width="match_parent"/&gt; </code></pre> <p>I've added this to my <code>style.xml</code>:</p> <pre><code>&lt;style name="AppTheme" parent="@style/_AppTheme"/&gt; &lt;!-- Base application theme. --&gt; &lt;style name="_AppTheme" parent="Theme.AppCompat.Light.NoActionBar"&gt; &lt;item name="android:dropDownSpinnerStyle"&gt;@style/SpinnerTheme &lt;/item&gt; &lt;item name="android:windowActionBarOverlay"&gt;false&lt;/item&gt; &lt;item name="colorPrimary"&gt;@color/ColorPrimary&lt;/item&gt; &lt;item name="colorPrimaryDark"&gt;@color/ColorPrimaryDark&lt;/item&gt; &lt;/style&gt; .... .... .... &lt;!--Spinner styles 2--&gt; &lt;style name="SpinnerTheme" parent="android:Widget.Spinner"&gt; &lt;item name="android:background"&gt;@drawable/apptheme_spinner_background_holo_light&lt;/item&gt; &lt;item name="android:dropDownSelector"&gt;@drawable/apptheme_list_selector_holo_light&lt;/item&gt; &lt;/style&gt; &lt;style name="SpinnerTheme.DropDown"&gt; &lt;item name="android:spinnerMode"&gt;dropdown&lt;/item&gt; &lt;/style&gt; &lt;!-- Changes the spinner drop down item radio button style --&gt; &lt;style name="DropDownItemSpinnerTheme" parent="android:Widget.DropDownItem.Spinner"&gt; &lt;item name="android:checkMark"&gt;@drawable/apptheme_btn_radio_holo_light&lt;/item&gt; &lt;/style&gt; &lt;style name="ListViewSpinnerTheme" parent="android:Widget.ListView"&gt; &lt;item name="android:listSelector"&gt;@drawable/apptheme_list_selector_holo_light&lt;/item&gt; &lt;/style&gt; &lt;style name="ListViewSpinnerTheme.White" parent="android:Widget.ListView.White"&gt; &lt;item name="android:listSelector"&gt;@drawable/apptheme_list_selector_holo_light&lt;/item&gt; &lt;/style&gt; &lt;style name="SpinnerItemTheme" parent="android:TextAppearance.Widget.TextView.SpinnerItem"&gt; &lt;item name="android:textColor"&gt;#000000&lt;/item&gt; &lt;/style&gt; </code></pre> <p>but there is no result ! I still see this:</p> <p><img src="https://i.stack.imgur.com/bLGVM.png" alt="enter image description here"></p> <blockquote> <p><strong>EDIT 2</strong></p> </blockquote> <p>I've changed the <code>style.xml</code> into:</p> <p><a href="http://pastie.org/private/es40xgebcajajltksyeow" rel="nofollow noreferrer">http://pastie.org/private/es40xgebcajajltksyeow</a></p> <p>and this is what I get: </p> <p><img src="https://i.stack.imgur.com/TsrDI.png" alt="enter image description here"></p> <p>Now instead of replacing the dropdown arrow icon I even have a second icon, the holo checkbox (which is working well, getting selected when I choose one item), but still, how do I get only the one that I want??</p> <p><code>manifest.xml</code>: </p> <p><a href="http://pastie.org/private/tu0izusbvvxe91lwmh9vnw" rel="nofollow noreferrer">http://pastie.org/private/tu0izusbvvxe91lwmh9vnw</a></p>
30,713,012
2
0
null
2015-06-08 14:43:33.03 UTC
1
2017-07-17 13:49:26.963 UTC
2015-06-11 20:21:32.327 UTC
null
2,395,491
null
2,395,491
null
1
7
android|android-layout|spinner
44,251
<p>You have to remove the <code>Imageview</code> into your custom layout <code>row_spinner.xml</code>. In case, you don't need to create an arrow inside your custom layout, because if you do, it'll be created in each row like happened to you. For doing the same you showed us, you must change the <code>Spinner</code> style into your <code>styles.xml</code>.</p> <p>For example:</p> <pre><code>&lt;resources&gt; &lt;style name="SpinnerTheme" parent="android:Widget.Spinner"&gt; &lt;item name="android:background"&gt;@drawable/spinner_background_holo_light&lt;/item&gt; &lt;item name="android:dropDownSelector"&gt;@drawable/list_selector_holo_light&lt;/item&gt; &lt;/style&gt; &lt;style name="SpinnerTheme.DropDown"&gt; &lt;item name="android:spinnerMode"&gt;dropdown&lt;/item&gt; &lt;/style&gt; &lt;!-- Changes the spinner drop down item radio button style --&gt; &lt;style name="DropDownItemSpinnerTheme" parent="android:Widget.DropDownItem.Spinner"&gt; &lt;item name="android:checkMark"&gt;@drawable/btn_radio_holo_light&lt;/item&gt; &lt;/style&gt; &lt;style name="ListViewSpinnerTheme" parent="android:Widget.ListView"&gt; &lt;item name="android:listSelector"&gt;@drawable/list_selector_holo_light&lt;/item&gt; &lt;/style&gt; &lt;style name="ListViewSpinnerTheme.White" parent="android:Widget.ListView.White"&gt; &lt;item name="android:listSelector"&gt;@drawable/list_selector_holo_light&lt;/item&gt; &lt;/style&gt; &lt;style name="SpinnerItemTheme" parent="android:TextAppearance.Widget.TextView.SpinnerItem"&gt; &lt;item name="android:textColor"&gt;#000000&lt;/item&gt; &lt;/style&gt; &lt;/resources&gt; </code></pre> <p>For further information take a look: <a href="http://androidopentutorials.com/android-how-to-get-holo-spinner-theme-in-android-2-x/" rel="noreferrer">http://androidopentutorials.com/android-how-to-get-holo-spinner-theme-in-android-2-x/</a></p> <blockquote> <p>EDIT</p> </blockquote> <p>selector_spinner.xml:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;selector xmlns:android="http://schemas.android.com/apk/res/android"&gt; &lt;item&gt; &lt;layer-list&gt; &lt;item&gt; &lt;shape&gt; &lt;gradient android:angle="90" android:endColor="#ffffff" android:startColor="#ffffff" android:type="linear" /&gt; &lt;stroke android:width="1dp" android:color="#504a4b" /&gt; &lt;corners android:radius="5dp" /&gt; &lt;padding android:bottom="3dp" android:left="3dp" android:right="3dp" android:top="3dp" /&gt; &lt;/shape&gt; &lt;/item&gt; &lt;item&gt; &lt;bitmap android:gravity="bottom|right" android:src="@android:drawable/arrow_up_float" /&gt; &lt;/item&gt; &lt;/layer-list&gt; &lt;/item&gt; &lt;/selector&gt; </code></pre> <p>styles.xml:</p> <pre><code>&lt;resources&gt; &lt;!-- Base application theme. --&gt; &lt;style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar"&gt; &lt;item name="android:spinnerStyle"&gt;@style/SpinnerTheme&lt;/item&gt; &lt;/style&gt; &lt;style name="SpinnerTheme" parent="android:Widget.Spinner"&gt; &lt;item name="android:background"&gt;@drawable/selector_spinner&lt;/item&gt; &lt;/style&gt; &lt;/resources&gt; </code></pre> <p>At the end, the spinner will look like as <img src="https://i.stack.imgur.com/JdNoe.png" alt="enter image description here"></p> <blockquote> <p>EDIT 2</p> </blockquote> <p>The following code is into <code>details_fragment_three.xml</code></p> <pre><code>&lt;Spinner android:id="@+id/spinnerDate" android:layout_marginLeft="-8dp" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@drawable/spinner_item_drawable"/&gt; </code></pre>
1,230,753
jQuery dynamic selector
<p>I have some code which uses a selector in a loop. </p> <p>This works: </p> <pre><code>document.getElementById("new_grouping_"+i).value </code></pre> <p>This does not: <code>$("#new_grouping_"+i).value</code></p> <p>Is there a way to do this using jQuery?</p>
1,230,766
3
0
null
2009-08-05 01:33:01.93 UTC
5
2019-11-04 13:11:54.963 UTC
2012-01-09 10:38:47.403 UTC
null
722,783
null
14,897
null
1
23
jquery
66,612
<p>You should use the <a href="http://docs.jquery.com/Attributes/val" rel="noreferrer">val()</a> function:</p> <pre><code>var myValue = $("#new_grouping_"+i).val(); // to get the value $("#new_grouping_"+i).val("something"); // to set the value </code></pre>
736,514
R Random Forests Variable Importance
<p>I am trying to use the random forests package for classification in R.</p> <p>The Variable Importance Measures listed are:</p> <ul> <li>mean raw importance score of variable x for class 0</li> <li>mean raw importance score of variable x for class 1</li> <li><code>MeanDecreaseAccuracy</code></li> <li><code>MeanDecreaseGini</code></li> </ul> <p>Now I know what these "mean" as in I know their definitions. What I want to know is how to use them.</p> <p>What I really want to know is what these values mean in only the context of how accurate they are, what is a good value, what is a bad value, what are the maximums and minimums, etc.</p> <p>If a variable has a high <code>MeanDecreaseAccuracy</code> or <code>MeanDecreaseGini</code> does that mean it is important or unimportant? Also any information on raw scores could be useful too. I want to know everything there is to know about these numbers that is relevant to the application of them. </p> <p>An explanation that uses the words 'error', 'summation', or 'permutated' would be less helpful then a simpler explanation that didn't involve any discussion of how random forests works.</p> <p>Like if I wanted someone to explain to me how to use a radio, I wouldn't expect the explanation to involve how a radio converts radio waves into sound.</p>
839,718
3
0
null
2009-04-10 02:18:38.49 UTC
39
2012-08-28 13:45:53.623 UTC
2012-08-28 13:45:53.623 UTC
null
602,276
null
20,895
null
1
46
r|statistics|data-mining|random-forest
49,499
<blockquote> <p>An explanation that uses the words 'error', 'summation', or 'permutated' would be less helpful then a simpler explanation that didn't involve any discussion of how random forests works.</p> <p>Like if I wanted someone to explain to me how to use a radio, I wouldn't expect the explanation to involve how a radio converts radio waves into sound.</p> </blockquote> <p>How would you explain what the numbers in WKRP 100.5 FM "mean" without going into the pesky technical details of wave frequencies? Frankly parameters and related performance issues with Random Forests are difficult to get your head around even if you understand some technical terms.</p> <p>Here's my shot at some answers:</p> <blockquote> <p>-mean raw importance score of variable x for class 0</p> <p>-mean raw importance score of variable x for class 1</p> </blockquote> <p>Simplifying from the Random Forest <a href="http://www.stat.berkeley.edu/~breiman/RandomForests/cc_home.htm#varimp" rel="noreferrer">web page</a>, raw importance score measures how much more helpful than random a particular predictor variable is in successfully classifying data.</p> <blockquote> <p>-MeanDecreaseAccuracy</p> </blockquote> <p>I think this is only in the <a href="http://cran.r-project.org/web/packages/randomForest/index.html" rel="noreferrer">R module</a>, and I believe it measures how much inclusion of this predictor in the model reduces classification error.</p> <blockquote> <p>-MeanDecreaseGini</p> </blockquote> <p><a href="http://en.wikipedia.org/wiki/Gini_coefficient" rel="noreferrer">Gini</a> is defined as "inequity" when used in describing a society's distribution of income, or a measure of "node impurity" in tree-based classification. A low Gini (i.e. higher descrease in Gini) means that a particular predictor variable plays a greater role in partitioning the data into the defined classes. It's a hard one to describe without talking about the fact that data in classification trees are split at individual nodes based on values of predictors. I'm not so clear on how this translates into better performance.</p>
431,752
Python csv.reader: How do I return to the top of the file?
<p>When I'm moving through a file with a csv.reader, how do I return to the top of the file. If I were doing it with a normal file I could just do something like "file.seek(0)". Is there anything like that for the csv module?</p> <p>Thanks ahead of time ;)</p>
431,771
3
0
null
2009-01-10 21:04:49.097 UTC
7
2020-11-09 13:57:58.377 UTC
null
null
null
Casey
41,718
null
1
59
python|csv
71,422
<p>You can seek the file directly. For example:</p> <pre><code>&gt;&gt;&gt; f = open("csv.txt") &gt;&gt;&gt; c = csv.reader(f) &gt;&gt;&gt; for row in c: print row ['1', '2', '3'] ['4', '5', '6'] &gt;&gt;&gt; f.seek(0) &gt;&gt;&gt; for row in c: print row # again ['1', '2', '3'] ['4', '5', '6'] </code></pre>
39,828,609
SonarQube And SonarLint difference
<p>How exactly is sonarQube different from SonarLint ? SonarQube has a server associated with it and Sonar lint works more like a plugin. But what are their specific difference ? </p>
39,836,205
5
0
null
2016-10-03 09:38:49.977 UTC
14
2022-03-03 14:06:01.09 UTC
2018-08-29 14:56:52.313 UTC
null
390,177
null
2,854,057
null
1
118
sonarqube|sonarlint
78,541
<p><a href="http://www.sonarlint.org/"><strong>SonarLint</strong></a> lives only in the IDE (IntelliJ, Eclipse and Visual Studio). Its purpose is to give instantaneous feedback as you type your code. For this, it concentrates on what code you are adding or updating.</p> <p><a href="http://www.sonarqube.org/"><strong>SonarQube</strong></a> is a central server that processes full analyses (triggered by the various SonarQube Scanners). Its purpose is to give a 360° vision of the quality of your code base. For this, it analyzes all the source lines of your project on a regular basis.</p> <p>Both SonarLint and SonarQube rely on the same static source code analyzers - most of them being written using SonarSource technology.</p>
34,990,236
How to use SVG image in ImageView
<p>Good Day, I have a <code>SVG</code> image. How can I add it to <code>ImageView</code> background ?</p> <p>I tried to use <a href="https://github.com/BigBadaboom/androidsvg" rel="noreferrer">this library</a> But I have problem:</p> <pre><code>01-25 12:19:02.669 27719-27719/com.dvor.androidapp E/AndroidRuntime: FATAL EXCEPTION: main android.view.InflateException: Binary XML file line #70: Error inflating class com.caverock.androidsvg.SVGImageView at android.view.LayoutInflater.createView(LayoutInflater.java:626) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:702) at android.view.LayoutInflater.rInflate(LayoutInflater.java:761) at android.view.LayoutInflater.rInflate(LayoutInflater.java:769) at android.view.LayoutInflater.rInflate(LayoutInflater.java:769) at android.view.LayoutInflater.rInflate(LayoutInflater.java:769) at android.view.LayoutInflater.rInflate(LayoutInflater.java:769) at android.view.LayoutInflater.rInflate(LayoutInflater.java:769) at android.view.LayoutInflater.rInflate(LayoutInflater.java:769) at android.view.LayoutInflater.inflate(LayoutInflater.java:498) at android.view.LayoutInflater.inflate(LayoutInflater.java:398) at com.dvor.mobileapp.checkout.ShoppingCart.onCreateView(ShoppingCart.java:411) at android.support.v4.app.Fragment.performCreateView(Fragment.java:1786) at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:953) at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1136) at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:739) at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1499) at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:456) at android.os.Handler.handleCallback(Handler.java:730) at android.os.Handler.dispatchMessage(Handler.java:92) at android.os.Looper.loop(Looper.java:176) at android.app.ActivityThread.main(ActivityThread.java:5419) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:525) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862) at dalvik.system.NativeStart.main(Native Method) Caused by: java.lang.reflect.InvocationTargetException at java.lang.reflect.Constructor.constructNative(Native Method) at java.lang.reflect.Constructor.newInstance(Constructor.java:417) at android.view.LayoutInflater.createView(LayoutInflater.java:600) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:702)  at android.view.LayoutInflater.rInflate(LayoutInflater.java:761)  at android.view.LayoutInflater.rInflate(LayoutInflater.java:769)  at android.view.LayoutInflater.rInflate(LayoutInflater.java:769)  at android.view.LayoutInflater.rInflate(LayoutInflater.java:769)  at android.view.LayoutInflater.rInflate(LayoutInflater.java:769)  at android.view.LayoutInflater.rInflate(LayoutInflater.java:769)  at android.view.LayoutInflater.rInflate(LayoutInflater.java:769)  at android.view.LayoutInflater.inflate(LayoutInflater.java:498)  at android.view.LayoutInflater.inflate(LayoutInflater.java:398)  at com.dvor.mobileapp.checkout.ShoppingCart.onCreateView(ShoppingCart.java:411)  at android.support.v4.app.Fragment.performCreateView(Fragment.java:1786)  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:953)  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1136)  at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:739)  at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1499)  at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:456)  at android.os.Handler.handleCallback(Handler.java:730)  at android.os.Handler.dispatchMessage(Handler.java:92)  at android.os.Looper.loop(Looper.java:176)  at android.app.ActivityThread.main(ActivityThread.java:5419)  at java.lang.reflect.Method.invokeNative(Native Method)  at java.lang.reflect.Method.invoke(Method.java:525)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)  at dalvik.system.NativeStart.main(Native Method)  Caused by: java.lang.NoClassDefFoundError: com.caverock.androidsvg.R$styleable at com.caverock.androidsvg.SVGImageView.init(SVGImageView.java:80) at com.caverock.androidsvg.SVGImageView.&lt;init&gt;(SVGImageView.java:66) at java.lang.reflect.Constructor.constructNative(Native Method)  at java.lang.reflect.Constructor.newInstance(Constructor.java:417)  at android.view.LayoutInflater.createView(LayoutInflater.java:600)  at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:702)  at android.view.LayoutInflater.rInflate(LayoutInflater.java:761)  at android.view.LayoutInflater.rInflate(LayoutInflater.java:769)  at android.view.LayoutInflater.rInflate(LayoutInflater.java:769)  at android.view.LayoutInflater.rInflate(LayoutInflater.java:769)  at android.view.LayoutInflater.rInflate(LayoutInflater.java:769)  at android.view.LayoutInflater.rInflate(LayoutInflater.java:769)  at android.view.LayoutInflater.rInflate(LayoutInflater.java:769)  at android.view.LayoutInflater.inflate(LayoutInflater.java:498)  at android.view.LayoutInflater.inflate(LayoutInflater.java:398)  at com.dvor.mobileapp.checkout.ShoppingCart.onCreateView(ShoppingCart.java:411)  at android.support.v4.app.Fragment.performCreateView(Fragment.java:1786)  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:953)  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1136)  at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:739)  at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1499)  at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:456)  at android.os.Handler.handleCallback(Handler.java:730)  at android.os.Handler.dispatchMessage(Handler.java:92)  at android.os.Looper.loop(Looper.java:176)  at android.app.ActivityThread.main(ActivityThread.java:5419)  at java.lang.reflect.Method.invokeNative(Native Method)  at java.lang.reflect.Method.invoke(Method.java:525)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)  at dalvik.system.NativeStart.main(Native Method) </code></pre> <p> </p> <p><strong>What I did ?</strong></p> <p>Firstly, I added <code>dependency</code> to <code>gradle</code>:</p> <pre><code>compile 'com.caverock:androidsvg:1.2.1' </code></pre> <p>Secondly, I changed <code>ImageView</code> to <code>com.caverock.androidsvg.SVGImageView</code></p> <pre><code> &lt;com.caverock.androidsvg.SVGImageView android:id="@+id/recentlyViewed_imgView" android:layout_width="100dp" android:layout_height="100dp" svgimageview:svg="clock.svg" /&gt; </code></pre> <p>After that I added <code>xmls:svgimageview</code> to root layout:</p> <pre><code>&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:svgimageview="http://schemas.android.com/apk/res-auto" android:id="@+id/rowItem" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#272727" android:clickable="true" android:orientation="vertical"&gt; </code></pre> <p>This <code>clock.svg</code> is in the <code>assets</code> folder.</p>
34,990,795
6
2
null
2016-01-25 10:25:54.97 UTC
8
2019-10-12 16:43:32.94 UTC
2017-03-02 13:04:04.663 UTC
null
3,585,230
null
5,779,142
null
1
67
android|svg|androidsvg
78,525
<p>In new Android Studio there is possibility to import SVG to XML file, so You don't need to use external library.</p> <p>In drawable right click -> New -> Vector Asset -> Local SVG file.</p> <p><a href="https://i.stack.imgur.com/DvrA0.png"><img src="https://i.stack.imgur.com/DvrA0.png" alt="enter image description here"></a></p> <p>Then You use it normally as other drawables:</p> <pre><code>android:src="@drawable/btn_image" </code></pre>
24,154,816
Git Bash: Could not open a connection to your authentication agent
<p>I'm new to Github and Generating SSH Keys look a neccessity. And was informed by my boss about this, so I need to comply.</p> <p>I successfully created SSH Key but when I'm going to add it to the ssh-agent</p> <p>this is what happens</p> <p>What seems to be the problem?</p> <p><img src="https://i.stack.imgur.com/LpZUj.png" alt="enter image description here"></p>
24,156,424
8
0
null
2014-06-11 04:44:36.367 UTC
42
2021-02-14 11:05:32.113 UTC
2021-02-14 11:05:32.113 UTC
null
3,082,718
null
3,626,672
null
1
107
git|github|ssh
175,255
<p>It seems you need to run <code>ssh-agent</code> before using it:</p> <pre><code>eval `ssh-agent -s` </code></pre> <p>That question was answered in this topic: <a href="https://stackoverflow.com/questions/17846529/could-not-open-a-connection-to-your-authentication-agent">Could not open a connection to your authentication agent</a></p>
42,756,354
Should I use React.PureComponent everywhere?
<p>React says pure render can optimize performance. And now React has PureComponent. Should I use React.PureComponent everywhere? Or when to use React.PureComponent and where is the most proper postion to use React.PureComponent?</p>
42,756,445
2
1
null
2017-03-13 03:49:11.793 UTC
18
2022-07-26 19:02:55.56 UTC
null
null
null
null
6,582,606
null
1
59
javascript|reactjs
13,702
<p>Not always. You should use it when a component could re-render even if it had the same props and state. An example of this is when a parent component had to re-render but the child component props and state didn't change. The child component could benefit from PureComponent because it really didn't need to re-render.</p> <p>You shouldn't necessarily use it everywhere. It doesn't make sense for every component to implement the shallow <code>shouldComponentUpdate()</code>. In many cases it adds the extra lifecycle method without getting you any wins.</p> <p>It can drastically save you rendering time if you have many cases where root level components update while the children do not need to do so. That being said, you will gain much more from using PureComponent in your root level nodes (i.e. PureComponent will not improve overall performance as much in leaf level components because it only saves renders from that component).</p> <p>Some caveats to PureComponent are explained very well in the react docs.</p> <blockquote> <p>React.PureComponent's shouldComponentUpdate() only shallowly compares the objects.</p> </blockquote> <p>You could accidentally miss rendering updates if your prop changes are deep in a nested object. PureComponent is only great with simple flat objects/props or by using something like ImmutableJS to detect changes in any object with a simple comparison.</p> <blockquote> <p>Furthermore, React.PureComponent's shouldComponentUpdate() skips prop updates for the whole component subtree. Make sure all the children components are also &quot;pure&quot;.</p> </blockquote> <p>PureComponent only works whenever the rendering of your component depends only on props and state. This should always be the case in react but there are some examples where you need to re-render outside of the normal react lifecycle. In order for PureComponent to work as expected (skipping the re-rendering you don't really need to happen), every descendant of your PureComponent should be 'pure' (dependent only upon props and state).</p>
5,890,576
Usage of `...` (three-dots or dot-dot-dot) in functions
<p>Where can I find documentation on the usage of <code>...</code> in functions? Examples would be useful.</p>
5,890,638
3
1
null
2011-05-04 22:26:49.747 UTC
20
2012-08-29 10:19:59.227 UTC
2012-08-29 10:19:59.227 UTC
null
1,201,032
null
170,352
null
1
89
r|ellipsis
41,259
<p>The word used to describe <code>...</code> is "ellipsis." Knowing this should make searching for information about the construct easier. For example, the first hit on Google is another question on this site: <a href="https://stackoverflow.com/questions/3057341/how-to-use-rs-ellipsis-feature-when-writing-your-own-function">How to use R&#39;s ellipsis feature when writing your own function?</a></p>
5,955,965
Move to start and end of search lookup
<p>In vim/gvim I would like to be able to move to the front and end of the current search lookup. Is this possible?</p> <p>For example, with this file:</p> <pre><code>A dog and a cat A hat and a bat </code></pre> <p>I would like to be able to perform a search, for example <code>/dog\sand</code> and then be able to move from the beginning of the 'dog and' expression to the end and back so that my cursor starts on column 3, under the letter 'd' of the word 'dog' and then moves to column 9 under the letter 'd' or the word 'and'.</p> <p>The reason I want to be able to do this is so that I can search for an expression and then use the change command, <code>c</code>, combined with a movement command to replace that particular search expression. I don't want to use substitue and replace here, I want to perform this operation using the change command and a movement key.</p>
5,956,316
4
0
null
2011-05-10 20:20:10.447 UTC
8
2013-04-19 17:16:23.7 UTC
null
null
null
null
427,733
null
1
36
vim|macvim
7,551
<p>You can change to the end of the match with <code>c//e&lt;CR&gt;</code>. And <code>//&lt;CR&gt;</code> will take you to the beginning of the next match. You could probably work out some kind of bindings for those that make sense. For instance I just tried the following, and it seems to work nicely:</p> <pre><code>:onoremap &lt;silent&gt;m //e&lt;CR&gt; </code></pre> <p>So that you can say <code>cm</code> for change match. I'm not sure what I would map <code>//&lt;CR&gt;</code> to, though. I tried mapping it to <code>n</code>, and it seemed to work fine. Don't know if that would be a problem for you.</p> <pre><code>:nnoremap &lt;silent&gt;n //&lt;CR&gt; </code></pre>
29,267,896
How to add multiple values per key in python dictionary
<p>My program needs to output a list of names with three numbers corresponding to each name however I don't know how to code this is there a way I could do it as a dictionary such as <code>cat1 = {"james":6, "bob":3}</code> but with three values for each key?</p>
29,267,974
4
2
null
2015-03-25 22:42:00.387 UTC
2
2021-01-18 00:34:42.19 UTC
2015-03-25 22:53:23.84 UTC
null
355,230
null
4,710,153
null
1
4
python|dictionary|key
43,608
<p>The value for each key can either be a set (distinct list of unordered elements)</p> <pre><code>cat1 = {"james":{1,2,3}, "bob":{3,4,5}} for x in cat1['james']: print x </code></pre> <p>or a list (ordered sequence of elements )</p> <pre><code>cat1 = {"james":[1,2,3], "bob":[3,4,5]} for x in cat1['james']: print x </code></pre>
32,357,164
SparkSQL: How to deal with null values in user defined function?
<p>Given Table 1 with one column "x" of type String. I want to create Table 2 with a column "y" that is an integer representation of the date strings given in "x".</p> <p><strong>Essential</strong> is to keep <code>null</code> values in column "y".</p> <p>Table 1 (Dataframe df1):</p> <pre><code>+----------+ | x| +----------+ |2015-09-12| |2015-09-13| | null| | null| +----------+ root |-- x: string (nullable = true) </code></pre> <p>Table 2 (Dataframe df2):</p> <pre><code>+----------+--------+ | x| y| +----------+--------+ | null| null| | null| null| |2015-09-12|20150912| |2015-09-13|20150913| +----------+--------+ root |-- x: string (nullable = true) |-- y: integer (nullable = true) </code></pre> <p>While the user-defined function (udf) to convert values from column "x" into those of column "y" is:</p> <pre><code>val extractDateAsInt = udf[Int, String] ( (d:String) =&gt; d.substring(0, 10) .filterNot( "-".toSet) .toInt ) </code></pre> <p>and works, dealing with null values is not possible.</p> <p>Even though, I can do something like </p> <pre><code>val extractDateAsIntWithNull = udf[Int, String] ( (d:String) =&gt; if (d != null) d.substring(0, 10).filterNot( "-".toSet).toInt else 1 ) </code></pre> <p>I have found no way, to "produce" <code>null</code> values via udfs (of course, as <code>Int</code>s can not be <code>null</code>). </p> <p>My current solution for creation of df2 (Table 2) is as follows:</p> <pre><code>// holds data of table 1 val df1 = ... // filter entries from df1, that are not null val dfNotNulls = df1.filter(df1("x") .isNotNull) .withColumn("y", extractDateAsInt(df1("x"))) .withColumnRenamed("x", "right_x") // create df2 via a left join on df1 and dfNotNull having val df2 = df1.join( dfNotNulls, df1("x") === dfNotNulls("right_x"), "leftouter" ).drop("right_x") </code></pre> <p><strong>Questions</strong>:</p> <ul> <li>The current solution seems cumbersome (and probably not efficient wrt. performance). Is there a better way?</li> <li>@Spark-developers: Is there a type <code>NullableInt</code> planned / avaiable, such that the following udf is possible (see Code excerpt ) ?</li> </ul> <p>Code excerpt</p> <pre><code>val extractDateAsNullableInt = udf[NullableInt, String] ( (d:String) =&gt; if (d != null) d.substring(0, 10).filterNot( "-".toSet).toInt else null ) </code></pre>
32,358,390
3
1
null
2015-09-02 15:25:15.12 UTC
15
2017-08-20 11:37:00.983 UTC
2017-08-20 11:37:00.983 UTC
null
647,053
null
1,211,082
null
1
32
scala|apache-spark|apache-spark-sql|user-defined-functions|nullable
48,237
<p>This is where <code>Option</code>comes in handy:</p> <pre><code>val extractDateAsOptionInt = udf((d: String) =&gt; d match { case null =&gt; None case s =&gt; Some(s.substring(0, 10).filterNot("-".toSet).toInt) }) </code></pre> <p>or to make it slightly more secure in general case:</p> <pre><code>import scala.util.Try val extractDateAsOptionInt = udf((d: String) =&gt; Try( d.substring(0, 10).filterNot("-".toSet).toInt ).toOption) </code></pre> <p>All credit goes to <a href="https://stackoverflow.com/users/1069256/dmitriy-selivanov">Dmitriy Selivanov</a> who've pointed out this solution as a (missing?) edit <a href="https://stackoverflow.com/a/32071409/1560062">here</a>.</p> <p>Alternative is to handle <code>null</code> outside the UDF:</p> <pre><code>import org.apache.spark.sql.functions.{lit, when} import org.apache.spark.sql.types.IntegerType val extractDateAsInt = udf( (d: String) =&gt; d.substring(0, 10).filterNot("-".toSet).toInt ) df.withColumn("y", when($"x".isNull, lit(null)) .otherwise(extractDateAsInt($"x")) .cast(IntegerType) ) </code></pre>
32,243,951
Java Generics enforcing compatible wildcards
<p>I've these classes.</p> <pre><code>class RedSocket {} class GreenSocket {} class RedWire {} class GreenWire {} </code></pre> <p>I've a class which uses 2 generic types </p> <pre><code>public class Connection&lt;W, S&gt; {} </code></pre> <p>where W is Wire type &amp; S is Socket type. </p> <p>I'm trying to enforce compile time check to ensure that socket &amp; wire have the same color. </p> <p>I tried doing this:</p> <pre><code>public class Connection&lt;W extends Wire &amp; Color, S extends Socket &amp; Color&gt; {} interface Color {} interface Red extends Color {} interface Green extends Color {} interface Socket {} interface Wire {} class RedSocket implements Socket, Red {} class GreenSocket implements Socket, Green {} class RedWire implements Wire, Red {} class GreenWire implements Wire, Green {} </code></pre> <p>But this doesn't really ensure that the <code>Color</code> used is same for both generic types and still lets me do this:</p> <pre><code>public class Connection&lt;W extends Wire &amp; Color, S extends Socket &amp; Color&gt; { public static void main(String[] args) { new Connection&lt;RedWire, GreenSocket&gt;(); new Connection&lt;GreenWire, RedSocket&gt;(); } } </code></pre> <p>(Why this happens has been explained brilliantly by Radiodef <a href="https://stackoverflow.com/questions/30217236/can-the-generic-type-of-a-generic-java-method-be-used-to-enforce-the-type-of-arg">here</a>)</p> <p>How can I enforce compile time check to ensure that socket &amp; wire have the same color?</p>
32,244,114
3
2
null
2015-08-27 08:08:23.097 UTC
5
2015-08-28 15:55:10.91 UTC
2017-05-23 11:51:37.963 UTC
null
-1
null
1,240,899
null
1
43
java|generics
1,355
<p>Seems that it's better to parameterize <code>Socket</code> and <code>Wire</code> with color:</p> <pre><code>interface Socket&lt;C extends Color&gt; {} interface Wire&lt;C extends Color&gt; {} class RedSocket implements Socket&lt;Red&gt; {} class GreenSocket implements Socket&lt;Green&gt; {} class RedWire implements Wire&lt;Red&gt; {} class GreenWire implements Wire&lt;Green&gt; {} </code></pre> <p>This way you can introduce one more generic parameter to the <code>Connection</code>:</p> <pre><code>public class Connection&lt;C extends Color, M extends Wire&lt;C&gt;, Q extends Socket&lt;C&gt;&gt; {...} </code></pre> <p>And use it like this:</p> <pre><code>new Connection&lt;Red, RedWire, RedSocket&gt;(); // ok new Connection&lt;Green, GreenWire, GreenSocket&gt;(); // ok new Connection&lt;Green, GreenWire, RedSocket&gt;(); // error </code></pre>
5,816,658
How to have a set of structs in C++
<p>I have a struct which has a unique key. I want to insert instances of these structs into a set. I know that to do this the &lt; operator has to be overloaded so that set can make a comparison in order to do the insertion.</p> <p>The following does not work:</p> <pre><code>#include &lt;iostream&gt; #include &lt;set&gt; using namespace std; struct foo { int key; }; bool operator&lt;(const foo&amp; lhs, const foo&amp; rhs) { return lhs.key &lt; rhs.key; } set&lt;foo&gt; bar; int main() { foo *test = new foo; test-&gt;key = 0; bar.insert(test); } </code></pre>
5,816,692
7
2
null
2011-04-28 09:44:38.667 UTC
9
2019-06-28 09:56:44.263 UTC
2011-04-28 09:53:19.43 UTC
null
404,020
null
404,020
null
1
24
c++|struct|set
46,560
<p>This might help:</p> <pre><code>struct foo { int key; }; inline bool operator&lt;(const foo&amp; lhs, const foo&amp; rhs) { return lhs.key &lt; rhs.key; } </code></pre> <p>If you are using namespaces, it is a good practice to declare the <code>operator&lt;()</code> function in the same namespace.</p> <hr> <p>For the sake of completeness after your edit, and as other have pointed out, you are trying to add a <code>foo*</code> where a <code>foo</code> is expected.</p> <p>If you really want to deal with pointers, you may wrap the <code>foo*</code> into a smart pointer class (<code>auto_ptr</code>, <code>shared_ptr</code>, ...).</p> <p>But note that in both case, you loose the benefit of the overloaded <code>operator&lt;</code> which operates on <code>foo</code>, not on <code>foo*</code>.</p>
6,018,293
Get the (last part of) current directory name in C#
<p>I need to get the last part of current directory, for example from <code>/Users/smcho/filegen_from_directory/AIRPassthrough</code>, I need to get <code>AIRPassthrough</code>. </p> <p>With python, I can get it with this code.</p> <pre><code>import os.path path = "/Users/smcho/filegen_from_directory/AIRPassthrough" print os.path.split(path)[-1] </code></pre> <p>Or</p> <pre><code>print os.path.basename(path) </code></pre> <p>How can I do the same thing with C#?</p> <h2>ADDED</h2> <p>With the help from the answerers, I found what I needed.</p> <pre><code>using System.Linq; string fullPath = Path.GetFullPath(fullPath).TrimEnd(Path.DirectorySeparatorChar); string projectName = fullPath.Split(Path.DirectorySeparatorChar).Last(); </code></pre> <p>or </p> <pre><code>string fullPath = Path.GetFullPath(fullPath).TrimEnd(Path.DirectorySeparatorChar); string projectName = Path.GetFileName(fullPath); </code></pre>
6,018,329
10
2
null
2011-05-16 13:39:59.633 UTC
13
2021-03-07 00:09:54.85 UTC
2015-03-27 11:47:43.273 UTC
null
260,127
null
260,127
null
1
189
c#|string|filepath
179,128
<p>You're looking for <a href="http://msdn.microsoft.com/en-us/library/system.io.path.getfilename.aspx" rel="noreferrer"><code>Path.GetFileName</code></a>.<br> Note that this won't work if the path ends in a <code>\</code>. </p>
4,965,036
UIGraphicsGetImageFromCurrentImageContext() Retina resolution?
<p>I'm taking a picture of my screen and manipulating it by using <code>UIGraphicsGetImageFromCurrentImageContext()</code>. Everything is working just fine. However, on an iPhone 4, the resolution looks pretty shabby as it seems like the image it uses is standard resolution, not @2x. Is there any way to increase the resolution of the resulting image?</p> <pre><code>UIGraphicsBeginImageContext(self.view.bounds.size); [self.view.layer renderInContext:UIGraphicsGetCurrentContext()]; UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); </code></pre>
4,965,155
1
0
null
2011-02-11 02:26:56.347 UTC
10
2011-02-11 02:47:48.623 UTC
null
null
null
null
456,851
null
1
36
iphone|cocoa-touch
8,517
<p>You should use <code>UIGraphicsBeginImageContextWithOptions</code> which allows you to set the scale factor. Use a scale factor of 0.0f to use the device's scale factor.</p>
33,229,806
How to auto scroll up Recycler view in Android?
<p>I have developed some chat application where i can send and received messages. But the problem is whenever i send or receive messages the recycler view is not scrolling to top so that messages gets diplayed above the keypad. </p> <p>I have used the above mentioned recycler view <code>android.support.v7.widget.RecyclerView</code>.</p>
33,230,129
7
0
null
2015-10-20 06:48:33.753 UTC
9
2022-08-18 21:30:40.627 UTC
2016-07-02 23:30:56.047 UTC
null
1,788,806
null
5,340,523
null
1
20
android|android-activity|android-recyclerview
42,583
<p>On updating recyclerview try to run this code :</p> <pre><code>recyclerView.post(new Runnable() { @Override public void run() { // Call smooth scroll recyclerView.smoothScrollToPosition(adapter.getItemCount() - 1); } }); </code></pre>
60,096,040
When should I call StateHasChanged and when Blazor automatically intercepts that something is changed?
<p>I am having a hard time understanding when I should call <code>StateHasChanged()</code> and when Blazor intercepts that something is changed so it must be re-rendered.</p> <p>I've created a sample project with a button and a custom component called AddItem. This component contains a div with a red border and a button.</p> <p><strong>What I expected:</strong> I want that the AddItem's div will show up when the user clicks on the button contained inside the Index page. Then I want to hides it when the user clicks on AddItem's button. </p> <p><strong>Note:</strong> AddItem doesn't expose it <code>_isVisible</code> flag outside, instead it contains a <code>Show()</code> method. So <code>AddItems.Show()</code> will be invoked when the Index's button is clicked.</p> <p><strong>Tests:</strong></p> <ol> <li><p>I click on Index's click button then the methods <code>Open()</code> and <code>AddItem.Show()</code> are invoked. The flag <code>_isVisible</code> is set to <code>true</code> but nothing happens and Index's <code>ShouldRender()</code> is invoked.</p> <p>Console output: </p> <ul> <li>Render Index</li> </ul></li> <li><p>I've modified <code>AddItem.Show()</code> with <code>public void Show() {_isVisible = true; StateHasChanged();}</code>. Now the AddItem's div shows and hide as expected.</p> <p>Console output:</p> <ul> <li>Render AddItem (1° click on index's button)</li> <li>Render Index (1° click on index's button)</li> <li>Render AddItem (2° click on addItem's close button)</li> </ul></li> <li><p>I've modified <code>&lt;AddItem @ref="AddItem" /&gt;</code> with <code>&lt;AddItem @ref="AddItem" CloseEventCallback="CallBack" /&gt;</code>, removed <code>StateHasChanged</code> from AddItem's <code>Show()</code> method. Now the AddItem's div shows and hides as expected.</p></li> </ol> <blockquote> <p><strong>Based on Test 3:</strong> Why I don't have to explicit <code>StateHasChanged</code> if I set AddItem's <code>CloseEventCallback</code> to any parent's method? I'm having a hard time understanding it because AddItem doesn't invoke <code>CloseEventCallback</code> anywhere.</p> </blockquote> <p>and</p> <blockquote> <p>When Blazor understands that something is changed so it must be re-render?</p> </blockquote> <p>My sample code (if you want to try it).</p> <p>My Index.razor</p> <pre class="lang-cs prettyprint-override"><code>&lt;AddItem @ref="AddItem" /&gt; &lt;button @onclick="Open"&gt;click&lt;/button&gt; @code { AddItem AddItem; public void Open() { AddItem.Show(); } public void CallBack() { } protected override bool ShouldRender() { Console.WriteLine("Render INDEX"); return base.ShouldRender(); } } </code></pre> <p>My AddItem component</p> <pre class="lang-cs prettyprint-override"><code>@if (_visible) { &lt;div style="width: 100px; height: 100px; border: 1px solid red"&gt;testo&lt;/div&gt; &lt;button @onclick="Close"&gt;close&lt;/button&gt; } @code { private bool _visible = false; [Parameter] public EventCallback&lt;bool&gt; CloseEventCallback { get; set; } public void Show() { _visible = true; } public void Close() { _visible = false; } protected override bool ShouldRender() { Console.WriteLine("Render ADDITEM"); return base.ShouldRender(); } } </code></pre>
60,098,274
2
0
null
2020-02-06 13:25:47.367 UTC
10
2021-05-21 13:06:54.433 UTC
2020-08-31 11:10:09.373 UTC
null
11,084,254
null
11,084,254
null
1
51
blazor
31,025
<p>Generally speaking, the StateHasChanged() method is automatically called after a UI event is triggered, as for instance, after clicking a button element, the click event is raised, and the StateHasChanged() method is automatically called to notify the component that its state has changed and it should re-render.</p> <p>When the Index component is initially accessed. The parent component renders first, and then the parent component renders its child.</p> <p>Whenever the "Open" button is clicked the Index component re-renders (This is because the target of the event is the parent component, which by default will re-render (No need to use StateHasChanged). But not the child, who is not aware that his state has changed. In order to make the child aware that his state has changed and that it should re-render, you should add a call to the StateHasChanged method manually in the Show method. Now, when you click on the "Open" button, the child component is re-rendered first, and then its parent re-renders next. Now the red div is rendered visible.</p> <p>Click the "Close" button to hide the red div. This time only the child component re-renders (This is because the target of the event is the child component, and it re-renders by default), but not the parent.</p> <p>This behavior is correct and by design.</p> <p>If you remove the call to the StateHasChanged method from the AddItem.Show method, define this property: <code>[Parameter] public EventCallback&lt;bool&gt; CloseEventCallback { get; set; }</code>, and add a component attribute in the parent component to assign a value to this property like this: <code>&lt;AddItem @ref="AddItem" CloseEventCallback="CallBack" /&gt;</code>, you'll notice no change outwardly, but this time the order of re-rendering when the "Open" button is clicked, is first the parent re-renders, then the child re-renders. This describes exactly the issue you've found expressed in your question from the comments: </p> <blockquote> <p>So, why my test 3 worked as expected even if CloseEventCallback isn't invoked anywhere?</p> </blockquote> <p>You are right... I could not really explain this behvior before having a further investigation. I'll try to find out what is going on, and let you know. </p> <blockquote> <p>AddItem's close method invoke the CloseEventCallback to advise the parent that it should re-render.</p> </blockquote> <p>Note: your code define the CloseEventCallback with a boolean type specifier, so you must define a method in your parent component that has a boolean parameter. When you invoke the CloseEventCallback 'delegate' you actually call the Index.Callback method and you should pass it a boolean value. Naturally, if you passes a value to a component, you expect it to re-render so that the new state can be seen in the UI. And this is the functionality that the EventCallback provides: Though the event is triggered in the child component, its target is the parent component, which results in the parent component re-rendering.</p> <blockquote> <p>I am wondering why a parent component should re-render itself if one of the subscribed EventCallback is invoked?</p> </blockquote> <p>This is exactly what I'm trying to explain in the paragraph above. The EventCallback type was especially design to solve the issue of the event target, routing the event to the component whose state has changed (the parent component), and re-rendering it.</p>
47,225,280
iOS11 ARKit: Can ARKit also capture the Texture of the user's face?
<p>I read the whole documentation on all ARKit classes up and down. I don't see any place that describes ability to actually get the user face's Texture. </p> <p>ARFaceAnchor contains the ARFaceGeometry (topology and geometry comprised of vertices) and the BlendShapeLocation array (coordinates allowing manipulations of individual facial traits by manipulating geometric math on the user face's vertices). </p> <p>But where can I get the actual Texture of the user's face. For example: the actual skin tone / color / texture, facial hair, other unique traits, such as scars or birth marks? Or is this not possible at all? </p>
47,233,232
4
0
null
2017-11-10 14:43:03.323 UTC
10
2021-04-23 08:05:30.207 UTC
null
null
null
null
1,315,512
null
1
10
ios|ios11|arkit|iphone-x
5,665
<p>You want a texture-map-style image for the face? There’s no API that gets you exactly that, but all the information you need is there:</p> <ul> <li><code>ARFrame.capturedImage</code> gets you the camera image.</li> <li><code>ARFaceGeometry</code> gets you a 3D mesh of the face.</li> <li><code>ARAnchor</code> and <code>ARCamera</code> together tell you where the face is in relation to the camera, and how the camera relates to the image pixels.</li> </ul> <p>So it’s entirely possible to texture the face model using the current video frame image. For each vertex in the mesh...</p> <ol> <li>Convert the vertex position from model space to camera space (use the anchor’s transform)</li> <li>Multiply with the camera projection with that vector to get to normalized image coordinates </li> <li>Divide by image width/height to get pixel coordinates</li> </ol> <p>This gets you texture coordinates for each vertex, which you can then use to texture the mesh using the camera image. You could do this math either all at once to replace the texture coordinate buffer <code>ARFaceGeometry</code> provides, or do it in shader code on the GPU during rendering. (If you’re rendering using SceneKit / <code>ARSCNView</code> you can probably do this in a shader modifier for the <a href="https://developer.apple.com/documentation/scenekit/scnshadermodifierentrypoint/1524108-geometry" rel="noreferrer"><code>geometry</code></a> entry point.)</p> <p>If instead you want to know for each pixel in the camera image what part of the face geometry it corresponds to, it’s a bit harder. You can’t just reverse the above math because you’re missing a depth value for each pixel... but if you don’t need to map every pixel, SceneKit hit testing is an easy way to get geometry for individual pixels.</p> <hr> <p>If what you’re actually asking for is landmark recognition — e.g. where in the camera image are the eyes, nose, beard, etc — there’s no API in ARKit for that. The <a href="https://developer.apple.com/documentation/vision" rel="noreferrer">Vision</a> framework might help.</p>
19,859,282
Check if a string contains a number
<p>Most of the questions I've found are biased on the fact they're looking for letters in their numbers, whereas I'm looking for numbers in what I'd like to be a numberless string. I need to enter a string and check to see if it contains any numbers and if it does reject it.</p> <p>The function <code>isdigit()</code> only returns <code>True</code> if ALL of the characters are numbers. I just want to see if the user has entered a number so a sentence like <code>"I own 1 dog"</code> or something.</p> <p>Any ideas?</p>
19,859,308
21
0
null
2013-11-08 12:37:06.45 UTC
61
2022-08-23 12:02:13.653 UTC
2020-03-24 15:40:43.733 UTC
null
3,161,575
null
2,080,298
null
1
290
python|string
565,594
<p>You can use <a href="https://docs.python.org/3/library/functions.html#any" rel="noreferrer"><code>any</code></a> function, with the <a href="https://docs.python.org/3/library/stdtypes.html#str.isdigit" rel="noreferrer"><code>str.isdigit</code></a> function, like this</p> <pre><code>def has_numbers(inputString): return any(char.isdigit() for char in inputString) has_numbers(&quot;I own 1 dog&quot;) # True has_numbers(&quot;I own no dog&quot;) # False </code></pre> <p>Alternatively you can use a Regular Expression, like this</p> <pre><code>import re def has_numbers(inputString): return bool(re.search(r'\d', inputString)) has_numbers(&quot;I own 1 dog&quot;) # True has_numbers(&quot;I own no dog&quot;) # False </code></pre>
30,313,302
Is Xamarin free in Visual Studio 2015?
<p>Currently I explore the Visual Studio 2015 RC and realized that Xamarin Studio is integrated into Visual Studio and its installer. My Question is: Is Xamarin from now on free in Visual Studio? </p>
30,314,359
10
0
null
2015-05-18 21:44:16.42 UTC
21
2019-04-13 12:39:49.063 UTC
2016-09-20 17:01:18.33 UTC
null
5,472,865
null
1,479,804
null
1
128
visual-studio|xamarin|visual-studio-2015
105,232
<p>Updated March 31st, 2016:</p> <p>We have announced that Visual Studio now includes Xamarin at no extra cost, including Community Edition, which is free for individual developers, open source projects, academic research, education, and small professional teams. There is no size restriction on the Community Edition and offers the same features as the Pro &amp; Enterprise editions. Read more about the update here: <a href="https://blog.xamarin.com/xamarin-for-all/" rel="noreferrer">https://blog.xamarin.com/xamarin-for-all/</a></p> <p>Be sure to browse the store on how to download and get started: <a href="https://visualstudio.microsoft.com/vs/pricing/" rel="noreferrer">https://visualstudio.microsoft.com/vs/pricing/</a> and there is a nice FAQ section: <a href="https://visualstudio.microsoft.com/vs/support/" rel="noreferrer">https://visualstudio.microsoft.com/vs/support/</a></p>
24,694,171
Error when using sendKeys() with Selenium WebDriver Java.lang.CharSequence cannot be resolved
<p>I have imported the following and still get an error when using <code>sendKeys();</code></p> <pre><code>import org.openqa.selenium.*; import org.openqa.selenium.firefox.*; import org.testng.Assert; import org.openqa.selenium.WebDriver; </code></pre> <p>Note: I am using Selenium WebDriver with Eclipse.</p> <p>The sample code is as below.</p> <pre><code>import org.openqa.selenium.*; import org.openqa.selenium.firefox.*; import org.testng.Assert; import org.openqa.selenium.WebDriver; public class Practice { public static void main(String[] args) { WebDriver driver = new FirefoxDriver(); String baseUrl = "http://www.facebook.com"; String tagName=""; driver.get(baseUrl); tagName = driver.findElement(By.id("email")).getTagName(); System.out.println("TagName: "+tagName); WebElement myElement = driver.findElement(By.id("username")); myElement.sendKeys("text"); } } </code></pre> <p>I received an error stating</p> <pre><code>The type java.lang.CharSequence cannot be resolved. It is indirectly referenced from required .class files </code></pre> <p>Pointing at the line <code>myElement.sendKeys("text");</code></p> <p>Can one of you let me know what is incorrect here.</p>
24,697,196
8
0
null
2014-07-11 09:15:25.48 UTC
1
2020-01-18 22:35:10.44 UTC
2016-01-07 12:46:56.067 UTC
null
617,450
null
1,926,538
null
1
4
java|eclipse|selenium|selenium-webdriver
42,495
<p>You could try this, similar issue has been answered here <a href="https://stackoverflow.com/questions/9622454/error-with-selenium-webelement-sendkeys">#sendKeys Issue</a></p> <pre><code>myElement .sendKeys(new String[] { "text" }); //You could create a string array </code></pre> <p>or simply</p> <pre><code>myElement .sendKeys(new String { "text" }); </code></pre>
24,783,530
Python realtime plotting
<p>I acquire some data in two arrays: one for the time, and one for the value. When I reach 1000 points, I trigger a signal and plot these points (x=time, y=value).</p> <p>I need to keep on the same figure the previous plots, but only a reasonable number to avoid slowing down the process. For example, I would like to keep 10,000 points on my graph. The matplotlib interactive plot works fine, but I don't know how to erase the first points and it slows my computer very quickly. I looked into matplotlib.animation, but it only seems to repeat the same plot, and not really actualise it.</p> <p>I'm really looking for a light solution, to avoid any slowing.</p> <p>As I acquire for a very large amount of time, I erase the input data on every loop (the 1001st point is stored in the 1st row and so on).</p> <p>Here is what I have for now, but it keeps all the points on the graph:</p> <pre><code>import matplotlib.pyplot as plt def init_plot(): plt.ion() plt.figure() plt.title("Test d\'acqusition", fontsize=20) plt.xlabel("Temps(s)", fontsize=20) plt.ylabel("Tension (V)", fontsize=20) plt.grid(True) def continuous_plot(x, fx, x2, fx2): plt.plot(x, fx, 'bo', markersize=1) plt.plot(x2, fx2, 'ro', markersize=1) plt.draw() </code></pre> <p>I call the init function once, and the continous_plot is in a process, called every time I have 1000 points in my array.</p>
24,787,171
4
1
null
2014-07-16 14:32:47.993 UTC
6
2018-07-24 07:38:34.047 UTC
2016-07-14 00:22:56.943 UTC
null
63,550
null
3,824,723
null
1
7
python|plot|real-time
45,576
<p>The lightest solution you may have is to replace the X and Y values of an existing plot. (Or the Y value only, if your X data does not change. A simple example:</p> <pre><code>import matplotlib.pyplot as plt import numpy as np import time fig = plt.figure() ax = fig.add_subplot(111) # some X and Y data x = np.arange(10000) y = np.random.randn(10000) li, = ax.plot(x, y) # draw and show it ax.relim() ax.autoscale_view(True,True,True) fig.canvas.draw() plt.show(block=False) # loop to update the data while True: try: y[:-10] = y[10:] y[-10:] = np.random.randn(10) # set the new data li.set_ydata(y) fig.canvas.draw() time.sleep(0.01) except KeyboardInterrupt: break </code></pre> <p>This solution is quite fast, as well. The maximum speed of the above code is 100 redraws per second (limited by the <code>time.sleep</code>), I get around 70-80, which means that one redraw takes around 4 ms. But YMMV depending on the backend, etc.</p>
44,603,429
Google Spreadsheet adding tooltip
<p>I need to add a tooltip (mouser over a cell) in a Google spreadsheet.</p> <p>I want the tooltip text to be taken from another cell, some idea?</p> <p>Thanks in advance!</p>
44,605,270
1
1
null
2017-06-17 10:23:47.23 UTC
3
2019-03-03 04:17:25.453 UTC
2017-06-18 19:37:54.897 UTC
null
1,595,451
null
2,099,244
null
1
22
google-apps-script|google-sheets
49,306
<p>Consider using notes - they appear when you hover mouse over cells in a spreadsheet. You can add notes manually by clicking the right mouse button on a cell and selecting 'insert note'. This can also be done programmatically. </p> <p>Say, you've got 2 adjacent cells. We'll use text from the second cell to add a note to the first one. <a href="https://i.stack.imgur.com/bdJFv.png" rel="noreferrer"><img src="https://i.stack.imgur.com/bdJFv.png" alt="enter image description here"></a></p> <p>You can create the note with the text from the second cell using the following code.</p> <pre><code>function addNote() { var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var targetCell = sheet.getRange("A1"); var sourceCell = sheet.getRange("B1"); var noteText = sourceCell.getValue(); targetCell.setNote(noteText); } </code></pre> <p>Here's the end result after executing the function <a href="https://i.stack.imgur.com/iZAwW.png" rel="noreferrer"><img src="https://i.stack.imgur.com/iZAwW.png" alt="enter image description here"></a></p> <p>You can modify the code to make it run only when the sheet is edited and dynamically update the note when the text in the source cell changes.</p>
44,567,280
Where is MSBuild.exe installed in Windows when installed using BuildTools_Full.exe?
<p>I'm trying to set up a build server for .NET, but can't figure out where MSBuild.exe is installed.</p> <p>I'm trying to install MSBuild using the Microsoft Build Tools 2013: <a href="https://www.microsoft.com/en-us/download/details.aspx?id=40760" rel="noreferrer">https://www.microsoft.com/en-us/download/details.aspx?id=40760</a></p>
44,789,063
6
2
null
2017-06-15 12:15:40.1 UTC
9
2022-02-14 05:36:31.69 UTC
null
null
null
null
1,159,674
null
1
67
.net|msbuild|windows-server
109,326
<p>MSBuild in the previous versions of .NET Framework was installed with it but, they decided to install it with Visual Studio or with the package BuildTools_Full.exe.</p> <p>The path to MSBuild when installed with the .NET framework:</p> <blockquote> <p>C:\Windows\Microsoft.NET\Framework[64 or empty][framework_version]</p> </blockquote> <p>The path to MSBuild when installed with Visual Studio is:</p> <blockquote> <p>C:\Program Files (x86)\MSBuild[version]\Bin for x86</p> </blockquote> <p>and</p> <blockquote> <p>C:\Program Files (x86)\MSBuild[version]\Bin\amd64 for x64.</p> </blockquote> <p>The path when BuildTools_Full.exe is installed is the same as when MSBuild is installed with Visual Studio.</p>
9,478,630
get pitch, yaw, roll from a CMRotationMatrix
<p>I have a CMRotationMatrix *rot and i would like to get the pitch, yaw, roll from the matrix. Any ideas how i could do that?</p> <p>Thanks</p>
18,764,368
3
0
null
2012-02-28 08:30:44.663 UTC
10
2014-07-28 12:27:57.037 UTC
2012-02-28 15:03:02.97 UTC
null
734,069
null
526,582
null
1
8
ios|opengl-es|core-motion
8,639
<p>Its better to use the Quaternion than Euler angles.... The roll, pitch and yaw values can be derived from quaternion using these formulae:</p> <pre><code>roll = atan2(2*y*w - 2*x*z, 1 - 2*y*y - 2*z*z) pitch = atan2(2*x*w - 2*y*z, 1 - 2*x*x - 2*z*z) yaw = asin(2*x*y + 2*z*w) </code></pre> <p>It can be implemented as:</p> <pre><code>CMQuaternion quat = self.motionManager.deviceMotion.attitude.quaternion; myRoll = radiansToDegrees(atan2(2*(quat.y*quat.w - quat.x*quat.z), 1 - 2*quat.y*quat.y - 2*quat.z*quat.z)) ; myPitch = radiansToDegrees(atan2(2*(quat.x*quat.w + quat.y*quat.z), 1 - 2*quat.x*quat.x - 2*quat.z*quat.z)); myYaw = radiansToDegrees(asin(2*quat.x*quat.y + 2*quat.w*quat.z)); </code></pre> <p>where the radianstoDegrees is a preprocessor directive implemented as:</p> <pre><code>#define radiansToDegrees(x) (180/M_PI)*x </code></pre> <p>This is done to convert the radian values given by the formulae, to degrees.</p> <p>More information about the conversion can be found here: <a href="http://www.tinkerforge.com/en/doc_v1/Software/Bricks/IMU_Brick_CSharp.html" rel="noreferrer">tinkerforge</a> and here:<a href="http://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles" rel="noreferrer">Conversion between Quaternions and Euler angles</a>.</p>
9,530,921
List all the files from all the folder in a single list
<p>Hi I am looking for the solution to list all the files from root/Android device.</p> <p>Suppose there are 3 folder inside root directory,but I want to display all the files in all of these folder in a single list..</p> <p>Now If am using </p> <pre><code> File f=new File("/sdcard"); </code></pre> <p>Then it will list all the files from the sdcard folder only..and If I will use</p> <pre><code> File f=new File("/download"); </code></pre> <p>Then it will list all the files from download folder only ..and if I will use </p> <pre><code> File f=new File("/"); </code></pre> <p>Then it will list only root direcoty files...not the files inside /sdcard or /download..</p> <p>So what steps shall I follow to list all the files with a filter to list only .csv files from all the folder inside root.</p> <p>Thanks..</p>
9,531,063
3
0
null
2012-03-02 09:35:10.8 UTC
22
2016-11-17 14:32:48.977 UTC
null
null
null
null
960,526
null
1
54
android|android-file
74,240
<p>Try this:</p> <pre><code> ..... List&lt;File&gt; files = getListFiles(new File("YOUR ROOT")); .... private List&lt;File&gt; getListFiles(File parentDir) { ArrayList&lt;File&gt; inFiles = new ArrayList&lt;File&gt;(); File[] files = parentDir.listFiles(); for (File file : files) { if (file.isDirectory()) { inFiles.addAll(getListFiles(file)); } else { if(file.getName().endsWith(".csv")){ inFiles.add(file); } } } return inFiles; } </code></pre> <p>or variant without recursion:</p> <pre><code>private List&lt;File&gt; getListFiles2(File parentDir) { List&lt;File&gt; inFiles = new ArrayList&lt;&gt;(); Queue&lt;File&gt; files = new LinkedList&lt;&gt;(); files.addAll(Arrays.asList(parentDir.listFiles())); while (!files.isEmpty()) { File file = files.remove(); if (file.isDirectory()) { files.addAll(Arrays.asList(file.listFiles())); } else if (file.getName().endsWith(".csv")) { inFiles.add(file); } } return inFiles; } </code></pre>
52,366,421
How to do n-D distance and nearest neighbor calculations on numpy arrays
<p><strong>This question is intended to be a canonical duplicate target</strong></p> <p>Given two arrays <code>X</code> and <code>Y</code> of shapes <code>(i, n)</code> and <code>(j, n)</code>, representing lists of <code>n</code>-dimensional coordinates, </p> <pre><code>def test_data(n, i, j, r = 100): X = np.random.rand(i, n) * r - r / 2 Y = np.random.rand(j, n) * r - r / 2 return X, Y X, Y = test_data(3, 1000, 1000) </code></pre> <p>what are the fastest ways to find:</p> <ol> <li>The distance <code>D</code> with shape <code>(i,j)</code> between every point in <code>X</code> and every point in <code>Y</code></li> <li>The indices <code>k_i</code> and distance <code>k_d</code> of the <code>k</code> nearest neighbors against all points in <code>X</code> for every point in <code>Y</code></li> <li>The indices <code>r_i</code>, <code>r_j</code> and distance <code>r_d</code> of every point in <code>X</code> within distance <code>r</code> of every point <code>j</code> in <code>Y</code></li> </ol> <p>Given the following sets of restrictions:</p> <ul> <li>Only using <code>numpy</code></li> <li>Using any <code>python</code> package</li> </ul> <p>Including the special case:</p> <ul> <li><code>Y</code> is <code>X</code></li> </ul> <p>In all cases <a href="https://en.wikipedia.org/wiki/Distance" rel="noreferrer">distance</a> primarily means <a href="https://en.wikipedia.org/wiki/Distance#Distance_in_Euclidean_space" rel="noreferrer">Euclidean distance</a>, but feel free to highlight methods that allow other distance calculations.</p>
52,366,706
1
2
2018-09-18 07:57:07.12 UTC
2018-09-17 11:10:56.913 UTC
11
2022-02-16 13:46:05.537 UTC
2018-09-18 07:15:35.327 UTC
null
4,427,777
null
4,427,777
null
1
13
python|arrays|numpy|scikit-learn|scipy
8,167
<p>#1. All Distances</p> <ul> <li><strong>only using <code>numpy</code></strong></li> </ul> <p>The naive method is:</p> <pre><code>D = np.sqrt(np.sum((X[:, None, :] - Y[None, :, :])**2, axis = -1)) </code></pre> <p>However this takes up a lot of memory creating an <code>(i, j, n)</code>-shaped intermediate matrix, and is very slow</p> <p>However, thanks to a trick from @Divakar (<a href="https://github.com/droyed/eucl_dist" rel="nofollow noreferrer"><code>eucl_dist</code></a> package, <a href="https://github.com/droyed/eucl_dist/wiki/Main-Article#prospective-method" rel="nofollow noreferrer">wiki</a>), we can use a bit of algebra and <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html" rel="nofollow noreferrer"><code>np.einsum</code></a> to decompose as such: <code>(X - Y)**2 = X**2 - 2*X*Y + Y**2</code></p> <pre><code>D = np.sqrt( # (X - Y) ** 2 np.einsum('ij, ij -&gt;i', X, X)[:, None] + # = X ** 2 \ np.einsum('ij, ij -&gt;i', Y, Y) - # + Y ** 2 \ 2 * X.dot(Y.T)) # - 2 * X * Y </code></pre> <ul> <li><strong><code>Y</code> is <code>X</code></strong></li> </ul> <p>Similar to above:</p> <pre><code>XX = np.einsum('ij, ij -&gt;i', X, X) D = np.sqrt(XX[:, None] + XX - 2 * X.dot(X.T)) </code></pre> <p>Beware that floating-point imprecision can make the diagonal terms deviate very slightly from zero with this method. If you need to make sure they are zero, you'll need to explicitly set it:</p> <pre><code>np.einsum('ii-&gt;i', D)[:] = 0 </code></pre> <ul> <li><strong>Any Package</strong></li> </ul> <p><a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.cdist.html" rel="nofollow noreferrer"><code>scipy.spatial.distance.cdist</code></a> is the most intuitive builtin function for this, and far faster than bare <code>numpy</code></p> <pre><code>from scipy.spatial.distance import cdist D = cdist(X, Y) </code></pre> <p><code>cdist</code> can also deal with many, many distance measures as well as user-defined distance measures (although these are not optimized). Check the documentation linked above for details.</p> <ul> <li><strong><code>Y</code> is <code>X</code></strong></li> </ul> <p>For self-referring distances, <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.pdist.html" rel="nofollow noreferrer"><code>scipy.spatial.distance.pdist</code></a> works similar to <code>cdist</code>, but returns a 1-D condensed distance array, saving space on the symmetric distance matrix by only having each term once. You can convert this to a square matrix using <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.squareform.html#scipy.spatial.distance.squareform" rel="nofollow noreferrer"><code>squareform</code></a></p> <pre><code>from scipy.spatial.distance import pdist, squareform D_cond = pdist(X) D = squareform(D_cond) </code></pre> <p>#2. K Nearest Neighbors (KNN)</p> <ul> <li><strong>Only using <code>numpy</code></strong></li> </ul> <p>We could use <code>np.argpartition</code> to get the <code>k-nearest</code> indices and use those to get the corresponding distance values. So, with <code>D</code> as the array holding the distance values obtained above, we would have -</p> <pre><code>if k == 1: k_i = D.argmin(0) else: k_i = D.argpartition(k, axis = 0)[:k] k_d = np.take_along_axis(D, k_i, axis = 0) </code></pre> <p>However we can speed this up a bit by not taking the square roots until we have reduced our dataset. <code>np.sqrt</code> is the slowest part of calculating the Euclidean norm, so we don't want to do that until the end.</p> <pre><code>D_sq = np.einsum('ij, ij -&gt;i', X, X)[:, None] +\ np.einsum('ij, ij -&gt;i', Y, Y) - 2 * X.dot(Y.T) if k == 1: k_i = D_sq.argmin(0) else: k_i = D_sq.argpartition(k, axis = 0)[:k] k_d = np.sqrt(np.take_along_axis(D_sq, k_i, axis = 0)) </code></pre> <p>Now, <code>np.argpartition</code> performs indirect partition and doesn't necessarily give us the elements in sorted order and only makes sure that the first <code>k</code> elements are the smallest ones. So, for a sorted output, we need to use <code>argsort</code> on the output from previous step -</p> <pre><code>sorted_idx = k_d.argsort(axis = 0) k_i_sorted = np.take_along_axis(k_i, sorted_idx, axis = 0) k_d_sorted = np.take_along_axis(k_d, sorted_idx, axis = 0) </code></pre> <p>If you only need, <code>k_i</code>, you never need the square root at all:</p> <pre><code>D_sq = np.einsum('ij, ij -&gt;i', X, X)[:, None] +\ np.einsum('ij, ij -&gt;i', Y, Y) - 2 * X.dot(Y.T) if k == 1: k_i = D_sq.argmin(0) else: k_i = D_sq.argpartition(k, axis = 0)[:k] k_d_sq = np.take_along_axis(D_sq, k_i, axis = 0) sorted_idx = k_d_sq.argsort(axis = 0) k_i_sorted = np.take_along_axis(k_i, sorted_idx, axis = 0) </code></pre> <ul> <li><strong><code>X</code> is <code>Y</code></strong></li> </ul> <p>In the above code, replace:</p> <pre><code>D_sq = np.einsum('ij, ij -&gt;i', X, X)[:, None] +\ np.einsum('ij, ij -&gt;i', Y, Y) - 2 * X.dot(Y.T) </code></pre> <p>with:</p> <pre><code>XX = np.einsum('ij, ij -&gt;i', X, X) D_sq = XX[:, None] + XX - 2 * X.dot(X.T)) </code></pre> <ul> <li><strong>Any Package</strong></li> </ul> <p><a href="https://en.wikipedia.org/wiki/K-d_tree" rel="nofollow noreferrer">KD-Tree</a> is a much faster method to find neighbors and constrained distances. Be aware the while KDTree is usually much faster than brute force solutions above for 3d (as long as oyu have more than 8 points), if you have <code>n</code>-dimensions, KDTree only scales well if you have more than <code>2**n</code> points. For discussion and more advanced methods for high dimensions, see <a href="https://stackoverflow.com/questions/5751114/nearest-neighbors-in-high-dimensional-data?rq=1">Here</a></p> <p>The most recommended method for implementing KDTree is to use <code>scipy</code>'s <a href="https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.spatial.KDTree.html" rel="nofollow noreferrer"><code>scipy.spatial.KDTree</code></a> or <a href="https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.spatial.cKDTree.html" rel="nofollow noreferrer"><code>scipy.spatial.cKDTree</code></a></p> <pre><code>from scipy.spatial import KDTree X_tree = KDTree(X) k_d, k_i = X_tree.query(Y, k = k) </code></pre> <p>Unfortunately <code>scipy</code>'s KDTree implementation is slow and has a tendency to segfault for larger data sets. As pointed out by @HansMusgrave <a href="https://stackoverflow.com/a/52361176/4427777">here</a>, <a href="https://github.com/storpipfugl/pykdtree" rel="nofollow noreferrer"><code>pykdtree</code></a> increases the performance a lot, but is not as common an include as <code>scipy</code> and can only deal with Euclidean distance currently (while the <code>KDTree</code> in <code>scipy</code> can handle Minkowsi p-norms of any order)</p> <ul> <li><strong><code>X</code> is <code>Y</code></strong></li> </ul> <p>Use instead:</p> <pre><code>k_d, k_i = X_tree.query(X, k = k) </code></pre> <ul> <li><strong>Arbitrary metrics</strong></li> </ul> <p>A BallTree has similar algorithmic properties to a KDTree. I'm not aware of a parallel/vectorized/fast BallTree in Python, but using scipy we can still have reasonable KNN queries for user-defined metrics. If available, builtin metrics will be much faster.</p> <pre><code>def d(a, b): return max(np.abs(a-b)) tree = sklearn.neighbors.BallTree(X, metric=d) k_d, k_i = tree.query(Y) </code></pre> <p>This answer <strong>will be wrong</strong> if <code>d()</code> is not a <a href="https://en.wikipedia.org/wiki/Metric_(mathematics)" rel="nofollow noreferrer">metric</a>. The only reason a BallTree is faster than brute force is because the properties of a metric allow it to rule out some solutions. For truly arbitrary functions, brute force is actually necessary.</p> <p>#3. Radius search</p> <ul> <li><strong>Only using <code>numpy</code></strong></li> </ul> <p>The simplest method is just to use boolean indexing:</p> <pre><code>mask = D_sq &lt; r**2 r_i, r_j = np.where(mask) r_d = np.sqrt(D_sq[mask]) </code></pre> <ul> <li><strong>Any Package</strong></li> </ul> <p>Similar to above, you can use <code>scipy.spatial.KDTree.query_ball_point</code></p> <pre><code>r_ij = X_tree.query_ball_point(Y, r = r) </code></pre> <p>or <code>scipy.spatial.KDTree.query_ball_tree</code></p> <pre><code>Y_tree = KDTree(Y) r_ij = X_tree.query_ball_tree(Y_tree, r = r) </code></pre> <p>Unfortunately <code>r_ij</code> ends up being a list of index arrays that are a bit difficult to untangle for later use.</p> <p>Much easier is to use <code>cKDTree</code>'s <code>sparse_distance_matrix</code>, which can output a <code>coo_matrix</code></p> <pre><code>from scipy.spatial import cKDTree X_cTree = cKDTree(X) Y_cTree = cKDTree(Y) D_coo = X_cTree.sparse_distance_matrix(Y_cTree, r = r, output_type = `coo_matrix`) r_i = D_coo.row r_j = D_coo.column r_d = D_coo.data </code></pre> <p>This is an extraordinarily flexible format for the distance matrix, as it stays an actual matrix (if converted to <code>csr</code>) can also be used for many vectorized operations.</p>
30,953,201
Adding blur effect to background in swift
<p>I am setting a background image to view controller. But also i want to add blur effect to this background. How can I do this?</p> <p>I am setting background with following code:</p> <pre><code>self.view.backgroundColor = UIColor(patternImage: UIImage(named: "testBg")!) </code></pre> <p>I found on internet for blur imageview how can i implement this to my background?</p> <pre><code>var darkBlur = UIBlurEffect(style: UIBlurEffectStyle.Dark) // 2 var blurView = UIVisualEffectView(effect: darkBlur) blurView.frame = imageView.bounds // 3 imageView.addSubview(blurView) </code></pre>
30,953,471
13
1
null
2015-06-20 10:59:40.96 UTC
77
2022-05-03 16:26:23.077 UTC
null
null
null
null
1,270,400
null
1
145
ios|swift
197,708
<p>I have tested this code and it's working fine:</p> <pre><code>let blurEffect = UIBlurEffect(style: UIBlurEffect.Style.dark) let blurEffectView = UIVisualEffectView(effect: blurEffect) blurEffectView.frame = view.bounds blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight] view.addSubview(blurEffectView) </code></pre> <p>For Swift 3.0:</p> <pre><code>let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.dark) let blurEffectView = UIVisualEffectView(effect: blurEffect) blurEffectView.frame = view.bounds blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight] view.addSubview(blurEffectView) </code></pre> <p>For Swift 4.0:</p> <pre><code>let blurEffect = UIBlurEffect(style: UIBlurEffect.Style.dark) let blurEffectView = UIVisualEffectView(effect: blurEffect) blurEffectView.frame = view.bounds blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight] view.addSubview(blurEffectView) </code></pre> <p>Here you can see result:</p> <p><img src="https://i.stack.imgur.com/3MDkj.png" alt="blurred view"></p> <p>Or you can use this lib for that:</p> <p><a href="https://github.com/FlexMonkey/Blurable" rel="noreferrer">https://github.com/FlexMonkey/Blurable</a></p>
10,538,881
How to keep text inside a div, always in the middle?
<p>I'm trying to make text stay in the middle of a resizable DIV. Here's the example:</p> <p>CSS</p> <pre><code>#rightmenu { position: absolute; z-index: 999999; right: 0; height: 60%; text-align: center; } </code></pre> <p>HTML</p> <pre><code>&lt;div id="rightmenu"&gt;This text should be center aligned and in the middle of the resizable rightmenu&lt;/div&gt; </code></pre> <p>I've tried to make a Class to contain the text with the "margin-top and margin-bottom" both on auto, but doesn't work. </p>
10,539,333
5
1
null
2012-05-10 17:00:19.193 UTC
2
2019-12-30 10:04:47.15 UTC
2012-05-11 08:18:48.737 UTC
null
728,084
null
1,383,179
null
1
9
html|css
71,308
<p>If you don't care about IE7 support, you can do it like that:</p> <p>HTML:</p> <pre><code>&lt;div id=wrap&gt; &lt;div id=inside&gt; Content, content, content. &lt;/div&gt; &lt;/div&gt; </code></pre> <p>CSS:</p> <pre><code>#wrap { /* Your styling. */ position: absolute; z-index: 999999; right: 0; height: 60%; text-align: center; /* Solution part I. */ display: table; } /* Solution part II. */ #inside { width: 100%; height: 100%; display: table-cell; vertical-align: middle; } </code></pre> <p>The code: <a href="http://tinkerbin.com/ETMVplub" rel="noreferrer">http://tinkerbin.com/ETMVplub</a></p> <p>If you're OK with JavaScript you can try this jQuery plugin: <a href="http://centratissimo.musings.it/" rel="noreferrer">http://centratissimo.musings.it/</a> but since it also doesn't seems to support IE7 the CSS solution is probably better.</p>
10,445,410
getting the X and Y coordinates for a div element
<p>I've been trying to make a javascript to get a X and Y coordinates of a <code>div</code> element. After some trying around I have come up with some numbers but I'm not sure how to validate the exact location of them(the script returns the X as 168 and Y as 258) I'm running the script with a screen resolution of 1280 x 800. This is the script I use to get this result:</p> <pre><code>function get_x(div) { var getY; var element = document.getElementById("" + div).offsetHeight; var get_center_screen = screen.width / 2; document.getElementById("span_x").innerHTML = element; return getX; } function get_y(div) { var getY; var element = document.getElementById("" + div).offsetWidth; var get_center_screen = screen.height / 2; document.getElementById("span_y").innerHTML = element; return getY; }​ </code></pre> <p>Now the question is. Would it be reasonable to assume that these are accurate coordinates returned by the function or is there an easy to to just spawn a little something on that location to see what exactly it is?</p> <p>And finally how would I go about making this <code>div</code> element move? I know I should use a <code>mousedown</code> event handler and a while to keep moving the element but yeah any tips/hints are greatly appreciated my biggest concern is to how to get that while loop running.</p>
10,445,639
5
1
null
2012-05-04 08:33:22.173 UTC
2
2017-12-03 12:47:14.09 UTC
2012-05-04 09:48:52.67 UTC
null
1,249,581
null
1,360,631
null
1
22
javascript|drag-and-drop
60,459
<p>Here a simple way to get various information regarding the position of a html element:</p> <pre><code> var my_div = document.getElementById('my_div_id'); var box = { left: 0, top: 0 }; try { box = my_div.getBoundingClientRect(); } catch(e) {} var doc = document, docElem = doc.documentElement, body = document.body, win = window, clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0, scrollTop = win.pageYOffset || jQuery.support.boxModel &amp;&amp; docElem.scrollTop || body.scrollTop, scrollLeft = win.pageXOffset || jQuery.support.boxModel &amp;&amp; docElem.scrollLeft || body.scrollLeft, top = box.top + scrollTop - clientTop, left = box.left + scrollLeft - clientLeft; </code></pre>
31,867,229
How can I execute a JavaScript function on the first page load?
<p>I am wondering if there is a way to execute a JavaScript function once only on the first ever page load and then not execute on any subsequent reloads.</p> <p>Is there a way I can go about doing this?</p>
31,867,239
5
1
null
2015-08-06 23:08:36.883 UTC
11
2021-04-16 22:09:48.237 UTC
2018-05-04 17:43:24.39 UTC
null
2,263,631
null
4,330,986
null
1
21
javascript
66,024
<p>The code below will execute once the <a href="https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onload" rel="noreferrer"><code>onload</code></a> event fires. The statement checks <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else" rel="noreferrer"><code>if</code></a> the <em>onetime function</em> has <strong>NOT</strong> been executed before by making use of a flag (<code>hasCodeRunBefore</code>), which is then stored in <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage" rel="noreferrer"><code>localStorage</code></a>. </p> <pre><code>window.onload = function () { if (localStorage.getItem("hasCodeRunBefore") === null) { /** Your code here. **/ localStorage.setItem("hasCodeRunBefore", true); } } </code></pre> <p><strong>Note:</strong> If the user clears their browsers' <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage" rel="noreferrer"><code>localStorage</code></a> by any means, then the function will run again because the flag (<code>hasCodeRunBefore</code>) will have been removed.</p> <h2>Good news...</h2> <p>Using <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage" rel="noreferrer"><code>localStorage</code></a> <em>can</em> be tedious because of operators and long winded function names. I created a basic <a href="https://github.com/Script47/.js/blob/master/src/local_storage.js" rel="noreferrer">module</a> to simplify this, so the above code would be replaced with:</p> <pre><code>window.onload = function () { if (!ls.exists('has_code_run_before')) { /** Your code here... **/ ls.set.single('has_code_run_before', true); /** or... you can use a callback. **/ ls.set.single('has_code_run_before', true, function () { /** Your code here... **/ }); } }; </code></pre> <h2><strong>Update #1</strong></h2> <p>Per <a href="https://stackoverflow.com/questions/31867229/how-can-i-execute-a-javascript-function-on-the-first-page-load/31867239#comment87917325_31867239">@PatrickRoberts comment</a>, you can use the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in" rel="noreferrer"><code>in</code></a> operator to see if a variable key exists in localStorage, so</p> <pre><code>if (localStorage.getItem('hasCodeRunBefore') === null) </code></pre> <p>becomes</p> <pre><code>if (!('hasCodeRunBefore' in localStorage)) </code></pre> <p>and is less verbose and a lot cleaner.</p> <p><strong>Secondly</strong>, you can set values as you would an object (<code>localStorage.hasCodeRunBefore = true</code>) though it will be stored as a string, not as boolean (or whatever data type your value is).</p>
31,841,259
How do I share dependencies between Android modules
<p>I have an Android application module (app) and an Android library module (library). Both app and library contain these same dependencies:</p> <pre><code>dependencies { compile 'com.squareup.okhttp:okhttp:2.4.0' compile 'com.squareup.retrofit:retrofit:1.9.0' compile 'io.reactivex:rxjava:1.0.13' compile 'io.reactivex:rxandroid:0.25.0' } </code></pre> <p>However when I try to add that block to the <em>project</em> build.gradle, it complains about not knowing the "compile" DSL.</p> <p>EDIT: I'm asking about putting this dependencies block in the PROJECT build.gradle, to avoid repeating in each module's build.gradle.</p>
31,842,816
6
2
null
2015-08-05 19:30:43.973 UTC
7
2022-01-31 13:43:26.567 UTC
2015-08-05 20:39:08.85 UTC
null
554,464
null
554,464
null
1
47
android|android-studio|gradle
17,838
<p>You can define shared gradle dependencies in the library module, and if the app module has the library as a dependency, you won't need to specify everything twice. Taking this further, you could create a 'common' module that requires the shared gradle dependencies, and have both the app &amp; library module require the common module.</p>
3,392,000
Interop between F# and C# lambdas
<p>F# powerpack comes with a set of conversion methods to translate from Func&lt;...> to F# functions, either standard or tupled ones. But is it possible to achieve the opposite: in case you want to call from F# code a C# method that takes Func&lt;...> and want to use native F# lambda expression (e.g. fun x -> some_function_of(x))?</p> <p>If I send a F# function with a signature 'a -> 'b to a C# method that expects Func then F# compiler generates the following error:</p> <pre>This expression was expected to have type Function&lt;'T,'R&gt; but here has type 'T -> 'R</pre> <p>I want to stay with F# lambda expressions but to use a translation layer in order to be able to send them as C# Func lambda. Is this achievable?</p>
3,392,043
1
1
null
2010-08-02 21:38:51.543 UTC
4
2010-08-02 21:45:13.543 UTC
null
null
null
null
223,675
null
1
28
f#|interop|lambda
4,625
<p>F# provides constructors for all delegate types that take F# values of the corresponding function types. E.g. in your case you want to use <code>System.Func&lt;_,_&gt;(fun x -&gt; ...)</code> which applies the generated constructor of type <code>('a -&gt; 'b) -&gt; System.Func&lt;'a, 'b&gt;</code>.</p>
18,500,336
Adding column to table & adding data right away to column in PostgreSQL
<p>I am trying to create a new column in an existing table, and using a select statement to do division to create the data I want to insert into my new column. Several of the statements I have written out will work as separate queries but I have not been able to string together the statements into one single query.</p> <p>I am still learning SQL and using it with mySQL and PostgreSQL. I took a class last month on SQL and now I am trying to do my own projects to keep my skills sharp.</p> <p>I am doing some work with elections results from 2012 in MN to use in my tables, to understand data I am working with.</p> <p>I have been able to alter my table and add a new column with these statements using them by themselves.</p> <pre><code>ALTER TABLE mn2012ct_geom2 ADD COLUMN obama_pct decimal(10,2) ALTER TABLE mn2012ct_geom2 ADD COLUMN romney_pct decimal(10,2) </code></pre> <p>I was able to use this select statement produce the information I want it to in my terminal application. What I am trying to do here is create a decimal number from the number of votes that the candidate got over the total votes that was cast.</p> <pre><code>SELECT CAST (obama AS DECIMAL) / CAST (uspres_total AS DECIMAL) AS obama_pct FROM mn2012ct_geom2 SELECT CAST (romney AS DECIMAL) / CAST (uspres_total AS DECIMAL) AS obama_pct FROM mn2012ct_geom2 </code></pre> <p>Now I want to have this information adding into the new column I created either with a Alter table statement like I have above or with an insert statement if I create the column before this query. </p> <p>I have tried a combined query like this:</p> <pre><code>ALTER TABLE mn2012ct_geom2 ADD COLUMN obama_pct decimal(10,2) AS (SELECT CAST (obama AS DECIMAL (10,2)) / CAST (uspres_total AS DECIMAL (10,2)) AS obama_pct FROM mn2012ct_geom2); </code></pre> <p>Or using an Insert command like this line instead of the alter table statement</p> <pre><code>INSERT INTO mn2012ct_geom2 (romney_pct) AS (SELECT CAST (romney AS DECIMAL (10,2)) / CAST (uspres_total AS DECIMAL (10,2)) AS romney_pct FROM mn2012ct_geom2); </code></pre> <p>When I try to do that it kicks out an error like this:</p> <pre><code>ERROR: syntax error at or near "AS" LINE 1: ...mn2012ct_geom2 ADD COLUMN obama_pct decimal(10,2) AS (SELECT... </code></pre> <p>I thought that kind of Alter table and add column or insert would work since that type of format worked when I created a new table using that same select statement.</p> <pre><code>CREATE TABLE obama_pct AS (SELECT CAST (obama AS DECIMAL (10,2)) / CAST (uspres_total AS DECIMAL (10,2)) AS obama_pct FROM mn2012ct_geom2); </code></pre> <p>Any help for you can provide I would greatly appreciate. I have been trying to google and search here on stackoverflow to find the answer but none of what I have found seems to exactly fit what I am doing it seems. </p>
18,501,405
2
0
null
2013-08-29 00:14:28.307 UTC
5
2013-08-29 11:11:53.08 UTC
null
null
null
null
2,723,210
null
1
10
sql|postgresql|sql-insert|alter-table
44,815
<p>In general it's not a good idea to add calculated data to a table. You sometimes need to do it when re-normalizing tables, but usually it's not done.</p> <p>As Gordon says, the appropriate thing to do here would be to <a href="http://www.postgresql.org/docs/current/static/sql-createview.html" rel="noreferrer">create a view</a>. See <a href="http://www.postgresql.org/docs/9.2/static/tutorial-views.html" rel="noreferrer">the tutorial</a>.</p> <p>There is no <code>ALTER TABLE ... ADD COLUMN ... AS</code>. You can't just make up syntax, you need to look at the <a href="http://www.postgresql.org/docs/current/static/sql-altertable.html" rel="noreferrer">documentation for the command you're interested in</a> to find out how to use it. The <code>\h</code> command in <code>psql</code> is also useful, eg <code>\h alter table</code>.</p> <p>If you do need to set values in a new column based on calculations from other columns, use <a href="http://www.postgresql.org/docs/current/static/sql-altertable.html" rel="noreferrer"><code>ALTER TABLE ... ADD COLUMN ... DEFAULT ...</code></a> then <code>DROP</code> the <code>DEFAULT</code> term after you create the column. It's often better to create the column blank and nullable, then fill it with an <code>UPDATE</code> statement.</p> <p>E.g. untested examples:</p> <pre><code>BEGIN; ALTER TABLE mn2012ct_geom2 ADD COLUMN obama_pct decimal(10,2); UPDATE mn2012ct_geom2 SET romney_pct = CAST (romney AS DECIMAL (10,2)) / CAST (uspres_total AS DECIMAL (10,2); COMMIT; </code></pre> <p>or, somewhat uglier:</p> <pre><code>BEGIN; ALTER TABLE mn2012ct_geom2 ADD COLUMN obama_pct decimal(10,2) NOT NULL DEFAULT (CAST (obama AS DECIMAL (10,2)) / CAST (uspres_total AS DECIMAL (10,2)); ALTER TABLE mn2012ct_geom2 ALTER COLUMN obama_pct DROP DEFAULT; COMMIT; </code></pre>
8,445,669
Why can attributes in Java be public?
<p>As everybody knows, Java follows the paradigms of object orientation, where data encapsulation says, that fields (attributes) of an object should be hidden for the outer world and only accessed via methods or that methods are the <em>only</em> interface of the class for the outer world. So why is it possible to declare a field in Java as public, which would be against the data encapsulation paradigm?</p>
8,445,716
12
1
null
2011-12-09 12:44:54.193 UTC
16
2021-03-21 14:35:11.553 UTC
null
null
null
null
458,770
null
1
45
java|oop|visibility
13,979
<p>I think it's possible because every rule has its exception, every best practice can be overridden in certain cases. </p> <p>For example, I often expose public static final data members as public (e.g., constants). I don't think it's harmful.</p> <p>I'll point out that this situation is true in other languages besides Java: C++, C#, etc.</p> <p>Languages need not always protect us from ourselves. </p> <p>In Oli's example, what's the harm if I write it this way?</p> <pre><code>public class Point { public final int x; public final int y; public Point(int p, int q) { this.x = p; this.y = q; } } </code></pre> <p>It's immutable and thread safe. The data members might be public, but you can't hurt them.</p> <p>Besides, it's a dirty little secret that "private" isn't really private in Java. You can always use reflection to get around it.</p> <p>So relax. It's not so bad.</p>
8,589,638
How to call an action when UISwitch changes state?
<p>I want to perform some action when UISwitch changes its state, thus is set on or off. How do I do this? I need to pass two objects as parameters. </p> <p>It's created in code, thus not using xib.</p>
8,589,775
3
1
null
2011-12-21 12:12:38.79 UTC
1
2019-06-03 13:05:00.387 UTC
2016-03-11 09:50:19.183 UTC
null
598,057
null
1,086,197
null
1
58
iphone|ios5|uiswitch
44,250
<pre><code>[yourSwitchObject addTarget:self action:@selector(setState:) forControlEvents:UIControlEventValueChanged]; </code></pre> <p>This will call the below method when your switch state changes</p> <pre><code>- (void)setState:(id)sender { BOOL state = [sender isOn]; NSString *rez = state == YES ? @"YES" : @"NO"; NSLog(rez); } </code></pre>
1,237,683
XML Serialization of List<T> - XML Root
<p>First question on Stackoverflow (.Net 2.0):</p> <p>So I am trying to return an XML of a List with the following:</p> <pre><code>public XmlDocument GetEntityXml() { StringWriter stringWriter = new StringWriter(); XmlDocument xmlDoc = new XmlDocument(); XmlTextWriter xmlWriter = new XmlTextWriter(stringWriter); XmlSerializer serializer = new XmlSerializer(typeof(List&lt;T&gt;)); List&lt;T&gt; parameters = GetAll(); serializer.Serialize(xmlWriter, parameters); string xmlResult = stringWriter.ToString(); xmlDoc.LoadXml(xmlResult); return xmlDoc; } </code></pre> <p>Now this will be used for multiple Entities I have already defined.</p> <p>Say I would like to get an XML of <code>List&lt;Cat&gt;</code></p> <p>The XML would be something like:</p> <pre><code>&lt;ArrayOfCat&gt; &lt;Cat&gt; &lt;Name&gt;Tom&lt;/Name&gt; &lt;Age&gt;2&lt;/Age&gt; &lt;/Cat&gt; &lt;Cat&gt; &lt;Name&gt;Bob&lt;/Name&gt; &lt;Age&gt;3&lt;/Age&gt; &lt;/Cat&gt; &lt;/ArrayOfCat&gt; </code></pre> <p>Is there a way for me to get the same Root all the time when getting these Entities?</p> <p>Example:</p> <pre><code>&lt;Entity&gt; &lt;Cat&gt; &lt;Name&gt;Tom&lt;/Name&gt; &lt;Age&gt;2&lt;/Age&gt; &lt;/Cat&gt; &lt;Cat&gt; &lt;Name&gt;Bob&lt;/Name&gt; &lt;Age&gt;3&lt;/Age&gt; &lt;/Cat&gt; &lt;/Entity&gt; </code></pre> <p>Also note that I do not intend to Deserialize the XML back to <code>List&lt;Cat&gt;</code></p>
1,334,483
4
1
null
2009-08-06 08:45:12.13 UTC
10
2012-05-21 19:01:02.613 UTC
2012-05-21 11:50:06.73 UTC
null
50,776
null
151,625
null
1
13
c#|xml|xml-serialization|root|generic-list
53,768
<p>There is a much easy way:</p> <pre><code>public XmlDocument GetEntityXml&lt;T&gt;() { XmlDocument xmlDoc = new XmlDocument(); XPathNavigator nav = xmlDoc.CreateNavigator(); using (XmlWriter writer = nav.AppendChild()) { XmlSerializer ser = new XmlSerializer(typeof(List&lt;T&gt;), new XmlRootAttribute("TheRootElementName")); ser.Serialize(writer, parameters); } return xmlDoc; } </code></pre>
620,342
How to import a Django project settings.py Python file from a sub-directory?
<p>I created a sub-directory of my Django project called <code>bin</code> where I want to put all command-line run Python scripts. Some of these scripts need to import my Django project <code>settings.py</code> file that is in a parent directory of <code>bin</code>.</p> <p>How can I import the <code>settings.py</code> file from a sub-directory of the project?</p> <p>The code that I use in my command-line script to set into the "Django context" of the project is:</p> <pre><code>from django.core.management import setup_environ import settings setup_environ(settings) </code></pre> <p>This works fine if the script is in the root directory of my project.</p> <p>I tried the following two hacks to import the <code>settings.py</code> file and then setup the project:</p> <pre><code>import os os.chdir("..") import sys sys.path = [str(sys.path[0]) + "/../"] + sys.path </code></pre> <p>The cruel hack can import <code>settings.py</code>, but then I get the error:</p> <pre><code>project_module = __import__(project_name, {}, {}, ['']) ValueError: Empty module name </code></pre>
622,457
4
0
null
2009-03-06 20:42:11.763 UTC
9
2020-09-30 16:41:23.003 UTC
2010-04-12 18:24:01.317 UTC
MikeN
63,550
MikeN
36,680
null
1
17
python|django
25,594
<p>This is going one level up from your question, but probably the best solution here is to implement your scripts as <a href="http://docs.djangoproject.com/en/dev/howto/custom-management-commands/#howto-custom-management-commands" rel="noreferrer">custom manage.py (django-admin.py) commands</a>. This gives you all of Django's functionality (including settings) for free with no ugly path-hacking, as well as command-line niceties like options parsing. I've never seen a good reason to write Django-related command-line scripts any other way.</p>
54,307,225
What's the difference between torch.stack() and torch.cat()?
<p>What's the difference between <a href="https://pytorch.org/docs/stable/generated/torch.cat.html" rel="noreferrer"><code>torch.cat</code></a> and <a href="https://pytorch.org/docs/stable/generated/torch.stack.html" rel="noreferrer"><code>torch.stack</code></a>?</p> <hr /> <p>OpenAI's <a href="https://github.com/pytorch/examples/blob/master/reinforcement_learning/reinforce.py" rel="noreferrer">REINFORCE</a> and <a href="https://github.com/pytorch/examples/blob/master/reinforcement_learning/actor_critic.py" rel="noreferrer">actor-critic</a> examples for reinforcement learning have the following:</p> <pre><code># REINFORCE: policy_loss = torch.cat(policy_loss).sum() # actor-critic: loss = torch.stack(policy_losses).sum() + torch.stack(value_losses).sum() </code></pre>
54,307,331
4
1
null
2019-01-22 11:24:47.743 UTC
22
2022-05-08 11:58:25.363 UTC
2022-04-01 13:00:14.79 UTC
null
365,102
null
913,098
null
1
92
python|pytorch
65,444
<p><a href="https://pytorch.org/docs/stable/generated/torch.stack.html" rel="noreferrer"><code>stack</code></a></p> <blockquote> <p>Concatenates sequence of tensors along a <strong>new dimension</strong>.</p> </blockquote> <p><a href="https://pytorch.org/docs/stable/generated/torch.cat.html" rel="noreferrer"><code>cat</code></a></p> <blockquote> <p>Concatenates the given sequence of seq tensors <strong>in the given dimension</strong>.</p> </blockquote> <p>So if <code>A</code> and <code>B</code> are of shape (3, 4):</p> <ul> <li><code>torch.cat([A, B], dim=0)</code> will be of shape (6, 4)</li> <li><code>torch.stack([A, B], dim=0)</code> will be of shape (2, 3, 4)</li> </ul>
39,888,769
Summary on async (void) Method: What to return?
<p>This is maybe a trivial question but currently im doing some Inline-Documentation for future Coworkers and stumbled upon something like that:</p> <pre><code>/// &lt;summary&gt; /// This Class is totaly useless /// &lt;/summary&gt; public class DummyClass { /// &lt;summary&gt; /// Will do nothing /// &lt;/summary&gt; public void DoNothing() { } /// &lt;summary&gt; /// Will do nothing async /// &lt;/summary&gt; /// &lt;returns&gt;&lt;/returns&gt; &lt;---- What to write here? public async Task DoNothingAsync() { await Task.Run(() =&gt; { }); } } </code></pre> <p>As you might know, typing 3 slashes above an Method/Field/Class/whatever, triggers VisualStudio to perform its Summary-Snippet-Completion. </p> <p><strong>Question</strong></p> <p>Is <code>Task</code> actually a valid return-value? And if so, what do i write in the <code>&lt;returns&gt;&lt;/returns&gt;</code>?</p> <p>I surely do know, i can ignore this, but for the sake of completeness im willing to write stuff there.</p>
39,889,142
6
2
null
2016-10-06 06:15:27.44 UTC
1
2020-01-13 14:48:32.36 UTC
null
null
null
null
4,558,029
null
1
28
c#|visual-studio|async-await
3,121
<p>If we take inspiration from <a href="https://msdn.microsoft.com/en-us/library/windows/apps/br227200.aspx">API's that Microsoft</a> have produced recently, you might just state:</p> <pre class="lang-xml prettyprint-override"><code>&lt;returns&gt;No object or value is returned by this method when it completes.&lt;/returns&gt; </code></pre> <p>I dislike "A task object that can be awaited" for the same reason I wouldn't decorate a method that returns an <code>int</code> with "an integer which can be compared to zero or used in mathematical operations" - it doesn't describe the return value of the method, it describes the type. The type has its own documentation which can be consulted.</p>
45,464,138
JaCoCo returning 0% Coverage with Kotlin and Android 3.0
<p>I am trying to check my code coverage for a test case that I wrote in Kotlin. When I execute <code>./gradlew createDebugCoverageReport --info</code>, my coverage.ec file is empty and my reports indicate that I have 0% coverage. Please note, the test cases are 100% successful. Can anyone think of any reasons my coverage.ec file keeps returning 0 bytes?</p> <p>I have searched everywhere with no luck. </p> <pre><code>apply plugin: 'com.android.library' apply plugin: 'kotlin-android' apply plugin: 'kotlin-android-extensions' apply plugin: 'jacoco' android { compileSdkVersion 25 buildToolsVersion "25.0.3" defaultConfig { minSdkVersion 16 targetSdkVersion 25 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { debug { testCoverageEnabled = true } release { minifyEnabled false testCoverageEnabled = true proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } testOptions { unitTests.all { jacoco { includeNoLocationClasses = true } } } } dependencies { implementation fileTree(include: ['*.jar'], dir: 'libs') androidTestImplementation('com.android.support.test.espresso:espresso-core:2.2.2', { exclude group: 'com.android.support', module: 'support-annotations' }) implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version" implementation 'com.android.support:appcompat-v7:25.4.0' testImplementation 'junit:junit:4.12' implementation files('pathtosomejarfile') } jacoco { toolVersion = "0.7.6.201602180812" reportsDir = file("$buildDir/customJacocoReportDir") } task jacocoTestReport(type: JacocoReport, dependsOn: ['testDebugUnitTest', 'createDebugCoverageReport']) { reports { xml.enabled = true html.enabled = true } def fileFilter = ['**/R.class', '**/R$*.class', '**/BuildConfig.*', '**/Manifest*.*', '**/*Test*.*', 'android/**/*.*'] def debugTree = fileTree(dir: "${buildDir}/intermediates/classes/debug", excludes: fileFilter) def mainSrc = "${project.projectDir}/src/androidTest/java" sourceDirectories = files([mainSrc]) classDirectories = files([debugTree]) executionData = fileTree(dir: "$buildDir", includes: [ "jacoco/testDebugUnitTest.exec", "outputs/code-coverage/connected/*coverage.ec" ]) } </code></pre>
46,083,078
3
2
null
2017-08-02 14:49:59.047 UTC
8
2022-05-04 08:56:31.207 UTC
2017-08-02 15:44:07.56 UTC
null
675,383
null
4,808,528
null
1
38
android|kotlin|code-coverage|jacoco
10,680
<p>You can get line-by-line coverage for both Java and Kotlin code by defining the two different directories for generated .class files:</p> <pre><code>def debugTree = fileTree(dir: &quot;${buildDir}/intermediates/classes/debug&quot;, excludes: fileFilter) def kotlinDebugTree = fileTree(dir: &quot;${buildDir}/tmp/kotlin-classes/debug&quot;, excludes: fileFilter) </code></pre> <p>Then, simply include both fileTrees in your classDirectories:</p> <pre><code>classDirectories.from = files([debugTree], [kotlinDebugTree]) </code></pre>
17,278,656
no suitable method found for print(int,boolean,char,double) error?
<p>I was trying to print (int, boolean, char, double) in a same println statement .</p> <pre><code>class Test1 { public static void main(String s[]) { int a =5; char c = 'a'; boolean b = true; double d = 12.46; System.out.println(a,b,c,d); /*System.out.println(a); // Here it works fine System.out.println(b); System.out.println(c); System.out.println(d);*/ } } </code></pre> <blockquote> <p>Test1.java:10: error: no suitable method found for println(int,boolean,char,double)</p> </blockquote> <p>But I don't why this error come . When i am printing this in different different statement works fine . Please Explain this . </p>
17,278,688
5
4
null
2013-06-24 15:00:05.897 UTC
3
2018-01-31 06:56:06.753 UTC
null
null
null
null
637,377
null
1
1
java
51,465
<p>The <a href="http://docs.oracle.com/javase/7/docs/api/java/io/PrintStream.html#println%28java.lang.Object%29"><code>println</code></a> method of <code>PrintStream</code> (of which <code>out</code> is an instance) takes a single argument. Perhaps you were you thinking of <a href="http://docs.oracle.com/javase/7/docs/api/java/io/PrintStream.html#printf%28java.lang.String,%20java.lang.Object...%29"><code>printf</code></a> instead.</p> <pre><code>System.out.printf("%d, %b, %c, %f%n", a, b, c, d); </code></pre> <pre> 5, true, a, 12.460000 </pre>
42,869,495
NumPy version of "Exponential weighted moving average", equivalent to pandas.ewm().mean()
<p>How do I get the exponential weighted moving average in NumPy just like the following in <a href="http://pandas.pydata.org/pandas-docs/stable/computation.html#exponentially-weighted-windows" rel="noreferrer">pandas</a>?</p> <pre><code>import pandas as pd import pandas_datareader as pdr from datetime import datetime # Declare variables ibm = pdr.get_data_yahoo(symbols='IBM', start=datetime(2000, 1, 1), end=datetime(2012, 1, 1)).reset_index(drop=True)['Adj Close'] windowSize = 20 # Get PANDAS exponential weighted moving average ewm_pd = pd.DataFrame(ibm).ewm(span=windowSize, min_periods=windowSize).mean().as_matrix() print(ewm_pd) </code></pre> <p>I tried the following with NumPy</p> <pre><code>import numpy as np import pandas_datareader as pdr from datetime import datetime # From this post: http://stackoverflow.com/a/40085052/3293881 by @Divakar def strided_app(a, L, S): # Window len = L, Stride len/stepsize = S nrows = ((a.size - L) // S) + 1 n = a.strides[0] return np.lib.stride_tricks.as_strided(a, shape=(nrows, L), strides=(S * n, n)) def numpyEWMA(price, windowSize): weights = np.exp(np.linspace(-1., 0., windowSize)) weights /= weights.sum() a2D = strided_app(price, windowSize, 1) returnArray = np.empty((price.shape[0])) returnArray.fill(np.nan) for index in (range(a2D.shape[0])): returnArray[index + windowSize-1] = np.convolve(weights, a2D[index])[windowSize - 1:-windowSize + 1] return np.reshape(returnArray, (-1, 1)) # Declare variables ibm = pdr.get_data_yahoo(symbols='IBM', start=datetime(2000, 1, 1), end=datetime(2012, 1, 1)).reset_index(drop=True)['Adj Close'] windowSize = 20 # Get NumPy exponential weighted moving average ewma_np = numpyEWMA(ibm, windowSize) print(ewma_np) </code></pre> <p>But the results are not similar as the ones in pandas.</p> <p>Is there maybe a better approach to calculate the exponential weighted moving average directly in NumPy and get the exact same result as the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.ewm.html#pandas.DataFrame.ewm" rel="noreferrer"><code>pandas.ewm().mean()</code></a>?</p> <p>At 60,000 requests on pandas solution, I get about 230 seconds. I am sure that with a pure NumPy, this can be decreased significantly.</p>
52,998,713
15
3
null
2017-03-18 01:36:35.877 UTC
39
2022-02-05 12:43:54.85 UTC
2020-08-28 07:43:19.007 UTC
null
10,375,049
null
2,480,410
null
1
55
python|pandas|numpy|vectorization|smoothing
72,496
<p><strong>Updated 08/06/2019</strong></p> <p><strong>PURE NUMPY, FAST &amp; VECTORIZED SOLUTION FOR LARGE INPUTS</strong></p> <p><strong><code>out</code> parameter for in-place computation, <code>dtype</code> parameter, index <code>order</code> parameter</strong></p> <p>This function is equivalent to pandas' <code>ewm(adjust=False).mean()</code>, but much faster. <code>ewm(adjust=True).mean()</code> (the default for pandas) can produce different values at the start of the result. I am working to add the <code>adjust</code> functionality to this solution.</p> <p><a href="https://stackoverflow.com/questions/42869495/numpy-version-of-exponential-weighted-moving-average-equivalent-to-pandas-ewm/42926270#42926270">@Divakar's answer</a> leads to floating point precision problems when the input is too large. This is because <code>(1-alpha)**(n+1) -&gt; 0</code> when <code>n -&gt; inf</code> and <code>alpha -&gt; 1</code>, leading to divide-by-zero's and <code>NaN</code> values popping up in the calculation.</p> <p>Here is my fastest solution with no precision problems, nearly fully vectorized. It's gotten a little complicated but the performance is great, especially for really huge inputs. Without using in-place calculations (which is possible using the <code>out</code> parameter, saving memory allocation time): 3.62 seconds for 100M element input vector, 3.2ms for a 100K element input vector, and 293µs for a 5000 element input vector on a pretty old PC (results will vary with different <code>alpha</code>/<code>row_size</code> values). </p> <pre><code># tested with python3 &amp; numpy 1.15.2 import numpy as np def ewma_vectorized_safe(data, alpha, row_size=None, dtype=None, order='C', out=None): """ Reshapes data before calculating EWMA, then iterates once over the rows to calculate the offset without precision issues :param data: Input data, will be flattened. :param alpha: scalar float in range (0,1) The alpha parameter for the moving average. :param row_size: int, optional The row size to use in the computation. High row sizes need higher precision, low values will impact performance. The optimal value depends on the platform and the alpha being used. Higher alpha values require lower row size. Default depends on dtype. :param dtype: optional Data type used for calculations. Defaults to float64 unless data.dtype is float32, then it will use float32. :param order: {'C', 'F', 'A'}, optional Order to use when flattening the data. Defaults to 'C'. :param out: ndarray, or None, optional A location into which the result is stored. If provided, it must have the same shape as the desired output. If not provided or `None`, a freshly-allocated array is returned. :return: The flattened result. """ data = np.array(data, copy=False) if dtype is None: if data.dtype == np.float32: dtype = np.float32 else: dtype = np.float else: dtype = np.dtype(dtype) row_size = int(row_size) if row_size is not None else get_max_row_size(alpha, dtype) if data.size &lt;= row_size: # The normal function can handle this input, use that return ewma_vectorized(data, alpha, dtype=dtype, order=order, out=out) if data.ndim &gt; 1: # flatten input data = np.reshape(data, -1, order=order) if out is None: out = np.empty_like(data, dtype=dtype) else: assert out.shape == data.shape assert out.dtype == dtype row_n = int(data.size // row_size) # the number of rows to use trailing_n = int(data.size % row_size) # the amount of data leftover first_offset = data[0] if trailing_n &gt; 0: # set temporary results to slice view of out parameter out_main_view = np.reshape(out[:-trailing_n], (row_n, row_size)) data_main_view = np.reshape(data[:-trailing_n], (row_n, row_size)) else: out_main_view = out data_main_view = data # get all the scaled cumulative sums with 0 offset ewma_vectorized_2d(data_main_view, alpha, axis=1, offset=0, dtype=dtype, order='C', out=out_main_view) scaling_factors = (1 - alpha) ** np.arange(1, row_size + 1) last_scaling_factor = scaling_factors[-1] # create offset array offsets = np.empty(out_main_view.shape[0], dtype=dtype) offsets[0] = first_offset # iteratively calculate offset for each row for i in range(1, out_main_view.shape[0]): offsets[i] = offsets[i - 1] * last_scaling_factor + out_main_view[i - 1, -1] # add the offsets to the result out_main_view += offsets[:, np.newaxis] * scaling_factors[np.newaxis, :] if trailing_n &gt; 0: # process trailing data in the 2nd slice of the out parameter ewma_vectorized(data[-trailing_n:], alpha, offset=out_main_view[-1, -1], dtype=dtype, order='C', out=out[-trailing_n:]) return out def get_max_row_size(alpha, dtype=float): assert 0. &lt;= alpha &lt; 1. # This will return the maximum row size possible on # your platform for the given dtype. I can find no impact on accuracy # at this value on my machine. # Might not be the optimal value for speed, which is hard to predict # due to numpy's optimizations # Use np.finfo(dtype).eps if you are worried about accuracy # and want to be extra safe. epsilon = np.finfo(dtype).tiny # If this produces an OverflowError, make epsilon larger return int(np.log(epsilon)/np.log(1-alpha)) + 1 </code></pre> <p>The 1D ewma function: </p> <pre><code>def ewma_vectorized(data, alpha, offset=None, dtype=None, order='C', out=None): """ Calculates the exponential moving average over a vector. Will fail for large inputs. :param data: Input data :param alpha: scalar float in range (0,1) The alpha parameter for the moving average. :param offset: optional The offset for the moving average, scalar. Defaults to data[0]. :param dtype: optional Data type used for calculations. Defaults to float64 unless data.dtype is float32, then it will use float32. :param order: {'C', 'F', 'A'}, optional Order to use when flattening the data. Defaults to 'C'. :param out: ndarray, or None, optional A location into which the result is stored. If provided, it must have the same shape as the input. If not provided or `None`, a freshly-allocated array is returned. """ data = np.array(data, copy=False) if dtype is None: if data.dtype == np.float32: dtype = np.float32 else: dtype = np.float64 else: dtype = np.dtype(dtype) if data.ndim &gt; 1: # flatten input data = data.reshape(-1, order) if out is None: out = np.empty_like(data, dtype=dtype) else: assert out.shape == data.shape assert out.dtype == dtype if data.size &lt; 1: # empty input, return empty array return out if offset is None: offset = data[0] alpha = np.array(alpha, copy=False).astype(dtype, copy=False) # scaling_factors -&gt; 0 as len(data) gets large # this leads to divide-by-zeros below scaling_factors = np.power(1. - alpha, np.arange(data.size + 1, dtype=dtype), dtype=dtype) # create cumulative sum array np.multiply(data, (alpha * scaling_factors[-2]) / scaling_factors[:-1], dtype=dtype, out=out) np.cumsum(out, dtype=dtype, out=out) # cumsums / scaling out /= scaling_factors[-2::-1] if offset != 0: offset = np.array(offset, copy=False).astype(dtype, copy=False) # add offsets out += offset * scaling_factors[1:] return out </code></pre> <p>The 2D ewma function: </p> <pre><code>def ewma_vectorized_2d(data, alpha, axis=None, offset=None, dtype=None, order='C', out=None): """ Calculates the exponential moving average over a given axis. :param data: Input data, must be 1D or 2D array. :param alpha: scalar float in range (0,1) The alpha parameter for the moving average. :param axis: The axis to apply the moving average on. If axis==None, the data is flattened. :param offset: optional The offset for the moving average. Must be scalar or a vector with one element for each row of data. If set to None, defaults to the first value of each row. :param dtype: optional Data type used for calculations. Defaults to float64 unless data.dtype is float32, then it will use float32. :param order: {'C', 'F', 'A'}, optional Order to use when flattening the data. Ignored if axis is not None. :param out: ndarray, or None, optional A location into which the result is stored. If provided, it must have the same shape as the desired output. If not provided or `None`, a freshly-allocated array is returned. """ data = np.array(data, copy=False) assert data.ndim &lt;= 2 if dtype is None: if data.dtype == np.float32: dtype = np.float32 else: dtype = np.float64 else: dtype = np.dtype(dtype) if out is None: out = np.empty_like(data, dtype=dtype) else: assert out.shape == data.shape assert out.dtype == dtype if data.size &lt; 1: # empty input, return empty array return out if axis is None or data.ndim &lt; 2: # use 1D version if isinstance(offset, np.ndarray): offset = offset[0] return ewma_vectorized(data, alpha, offset, dtype=dtype, order=order, out=out) assert -data.ndim &lt;= axis &lt; data.ndim # create reshaped data views out_view = out if axis &lt; 0: axis = data.ndim - int(axis) if axis == 0: # transpose data views so columns are treated as rows data = data.T out_view = out_view.T if offset is None: # use the first element of each row as the offset offset = np.copy(data[:, 0]) elif np.size(offset) == 1: offset = np.reshape(offset, (1,)) alpha = np.array(alpha, copy=False).astype(dtype, copy=False) # calculate the moving average row_size = data.shape[1] row_n = data.shape[0] scaling_factors = np.power(1. - alpha, np.arange(row_size + 1, dtype=dtype), dtype=dtype) # create a scaled cumulative sum array np.multiply( data, np.multiply(alpha * scaling_factors[-2], np.ones((row_n, 1), dtype=dtype), dtype=dtype) / scaling_factors[np.newaxis, :-1], dtype=dtype, out=out_view ) np.cumsum(out_view, axis=1, dtype=dtype, out=out_view) out_view /= scaling_factors[np.newaxis, -2::-1] if not (np.size(offset) == 1 and offset == 0): offset = offset.astype(dtype, copy=False) # add the offsets to the scaled cumulative sums out_view += offset[:, np.newaxis] * scaling_factors[np.newaxis, 1:] return out </code></pre> <p>usage:</p> <pre><code>data_n = 100000000 data = ((0.5*np.random.randn(data_n)+0.5) % 1) * 100 span = 5000 # span &gt;= 1 alpha = 2/(span+1) # for pandas` span parameter # com = 1000 # com &gt;= 0 # alpha = 1/(1+com) # for pandas` center-of-mass parameter # halflife = 100 # halflife &gt; 0 # alpha = 1 - np.exp(np.log(0.5)/halflife) # for pandas` half-life parameter result = ewma_vectorized_safe(data, alpha) </code></pre> <hr> <p><strong>Just a tip</strong></p> <p>It is easy to calculate a 'window size' (technically exponential averages have infinite 'windows') for a given <code>alpha</code>, dependent on the contribution of the data in that window to the average. This is useful for example to chose how much of the start of the result to treat as unreliable due to border effects.</p> <pre><code>def window_size(alpha, sum_proportion): # Increases with increased sum_proportion and decreased alpha # solve (1-alpha)**window_size = (1-sum_proportion) for window_size return int(np.log(1-sum_proportion) / np.log(1-alpha)) alpha = 0.02 sum_proportion = .99 # window covers 99% of contribution to the moving average window = window_size(alpha, sum_proportion) # = 227 sum_proportion = .75 # window covers 75% of contribution to the moving average window = window_size(alpha, sum_proportion) # = 68 </code></pre> <p>The <code>alpha = 2 / (window_size + 1.0)</code> relation used in this thread (the 'span' option from <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/computation.html#exponentially-weighted-windows" rel="noreferrer">pandas</a>) is a very rough approximation of the inverse of the above function (with <code>sum_proportion~=0.87</code>). <code>alpha = 1 - np.exp(np.log(1-sum_proportion)/window_size)</code> is more accurate (the 'half-life' option from pandas equals this formula with <code>sum_proportion=0.5</code>).</p> <p>In the following example, <code>data</code> represents a continuous noisy signal. <code>cutoff_idx</code> is the first position in <code>result</code> where at least 99% of the value is dependent on separate values in <code>data</code> (i.e. less than 1% depends on data[0]). The data up to <code>cutoff_idx</code> is excluded from the final results because it is too dependent on the first value in <code>data</code>, therefore possibly skewing the average. </p> <pre><code>result = ewma_vectorized_safe(data, alpha, chunk_size) sum_proportion = .99 cutoff_idx = window_size(alpha, sum_proportion) result = result[cutoff_idx:] </code></pre> <p>To illustrate the problem the above solve you can run this a few times, notice the often-appearing false start of the red line, which is skipped after <code>cutoff_idx</code>:</p> <pre><code>data_n = 100000 data = np.random.rand(data_n) * 100 window = 1000 sum_proportion = .99 alpha = 1 - np.exp(np.log(1-sum_proportion)/window) result = ewma_vectorized_safe(data, alpha) cutoff_idx = window_size(alpha, sum_proportion) x = np.arange(start=0, stop=result.size) import matplotlib.pyplot as plt plt.plot(x[:cutoff_idx+1], result[:cutoff_idx+1], '-r', x[cutoff_idx:], result[cutoff_idx:], '-b') plt.show() </code></pre> <p>note that <code>cutoff_idx==window</code> because alpha was set with the inverse of the <code>window_size()</code> function, with the same <code>sum_proportion</code>. This is similar to how pandas applies <code>ewm(span=window, min_periods=window)</code>.</p>
52,977,079
Android SDK 28 - versionCode in PackageInfo has been deprecated
<p>I just upgraded my app's <code>compileSdkVersion</code> to <code>28</code> (Pie).</p> <p>I'm getting a compilation warning:</p> <blockquote> <p>warning: [deprecation] versionCode in PackageInfo has been deprecated</p> </blockquote> <p>The warning is coming from this code:</p> <pre><code>final PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0); int versionCode = info.versionCode; </code></pre> <p>I looked at the <a href="https://developer.android.com/reference/kotlin/android/content/pm/PackageInfo#versioncode" rel="noreferrer">documentation</a>, but it doesn't say anything about how to resolve this issue or what should be used instead of the deprecated field.</p>
52,977,132
5
1
null
2018-10-24 20:00:07.67 UTC
2
2022-03-23 12:20:01.577 UTC
2020-07-30 16:00:23.873 UTC
null
4,851,751
null
4,851,751
null
1
48
java|android|android-9.0-pie|package-info
21,961
<p>It says what to do <a href="https://developer.android.com/reference/android/content/pm/PackageInfo#versionCode" rel="noreferrer">on the Java doc</a> (I recommend not using the Kotlin documentation for much; it's not really maintained well):</p> <blockquote> <p>versionCode</p> <p>This field was deprecated in API level 28. Use getLongVersionCode() instead, which includes both this and the additional versionCodeMajor attribute. The version number of this package, as specified by the tag's versionCode attribute.</p> </blockquote> <p>This is an API 28 method, though, so consider using <a href="https://developer.android.com/reference/androidx/core/content/pm/PackageInfoCompat" rel="noreferrer">PackageInfoCompat</a>. It has one static method:</p> <pre><code>getLongVersionCode(PackageInfo info) </code></pre>
25,814,946
How to find origin of a branch in git?
<p>Say if my project contains two masters (master and master_ios) and I want to see what the origin of a feature branch is (by origin, i mean the branch the feature branch is based off), how would I accomplish this in git?</p>
25,815,019
4
2
null
2014-09-12 18:54:13.71 UTC
6
2022-08-08 17:11:24.813 UTC
2019-03-14 16:02:46.85 UTC
null
39,036
null
812,215
null
1
37
git|branch
52,257
<pre><code>git remote show origin </code></pre> <p>shows remote and local branches with tracking info.</p>
20,679,842
Remove trailing whitespace on save in IntelliJ IDEA 12
<p>Is it possible to remove trailing whitespace automatically on save in IntelliJ IDEA? I know there are some workarounds, for example, using git to trim the whitespace on commit. Maybe this question is a duplicate of <a href="https://stackoverflow.com/questions/946993/intellij-reformat-on-file-save/5581992#5581992">this one</a>, but i hope this can be done without setting up keyboard shortcuts and macros.</p>
20,683,165
5
1
null
2013-12-19 10:56:55.853 UTC
8
2021-10-25 22:02:07.85 UTC
2018-12-19 00:18:47.983 UTC
null
3,728,901
null
1,706,750
null
1
123
git|intellij-idea|reformat
63,760
<p>Don't know about 12, but there's the following setting in 13:</p> <p><em>Settings → Editor → Strip trailing spaces on Save</em></p> <p>As of IntelliJ 2017.2 it's under</p> <p><em>Settings → Editor → General → Strip trailing spaces on Save</em></p> <p><img src="https://i.stack.imgur.com/HUdlt.png" alt="configuration dialogue"></p>
4,591,329
Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set()
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/4532486/failed-to-connect-to-mailserver-at-localhost-port-25">Failed to connect to mailserver at &ldquo;localhost&rdquo; port 25</a> </p> </blockquote> <p>I used this one however</p> <pre><code>$to = "somebody@example.com"; $subject = "My subject"; $txt = "Hello world!"; $headers = "From: webmaster@example.com" . "\r\n" . "CC: somebodyelse@example.com"; mail($to,$subject,$txt,$headers); </code></pre> <p>I have this error which is Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set()</p>
4,591,355
1
2
null
2011-01-04 07:05:09.567 UTC
3
2011-01-04 07:11:49.58 UTC
2017-05-23 12:25:51.447 UTC
null
-1
null
562,123
null
1
9
php
114,182
<p>If you are running your application just on localhost and it is not yet live, I believe it is very difficult to send mail using this.</p> <p>Once you put your application online, I believe that this problem should be automatically solved. By the way,ini_set() helps you to change the values in php.ini during run time. </p> <p>This is the same question as <a href="https://stackoverflow.com/questions/4532486/failed-to-connect-to-mailserver-at-localhost-port-25">Failed to connect to mailserver at &quot;localhost&quot; port 25</a></p> <p>also check this <a href="https://stackoverflow.com/questions/3633144/php-mail-function-not-working">php mail function not working</a></p>
14,251,349
HTML Table cell background image alignment
<p>I need the background image of a table cell to be aligned as</p> <blockquote> <p>Top in vertical side - Right in Horizontal</p> </blockquote> <p>But it is displaying as,</p> <blockquote> <p>Center in Vertical side ; Right in Horizontal</p> </blockquote> <p>Take a look at this page: <a href="http://www.chemfluence.org.in/monetarist/index_copy.php" rel="nofollow">http://www.chemfluence.org.in/monetarist/index_copy.php</a></p> <p>Here is my code,</p> <pre><code>&lt;td width="178" rowspan="3" valign="top" align="right" background="images/left.jpg" style="background-repeat:no-repeat;background-position:right;"&gt; &lt;/td&gt; </code></pre> <p>if i use <strong>background-position:Top;</strong> it is center aligned Horizontally please let me know which should be corrected.</p>
14,251,403
2
1
null
2013-01-10 05:28:03.307 UTC
null
2015-01-26 07:01:09.123 UTC
null
null
null
null
975,199
null
1
4
html|css
102,660
<p>use like this your inline css</p> <pre><code>&lt;td width="178" rowspan="3" valign="top" align="right" background="images/left.jpg" style="background-repeat:background-position: right top;"&gt; &lt;/td&gt; </code></pre>
25,329,375
Creating a footer for every page using R markdown
<p>I'm writing a document in R Markdown and I'd like it to include a footer on every page when I knit a PDF document. Does anyone have any idea on how to do this?</p>
25,356,975
3
2
null
2014-08-15 15:32:42.447 UTC
14
2020-02-27 06:33:53.583 UTC
2018-10-01 11:39:22.68 UTC
null
7,347,699
null
2,387,597
null
1
31
r-markdown|knitr|pandoc
33,763
<p>Yes, this question has been asked and answered here: <a href="https://tex.stackexchange.com/questions/139139/adding-headers-and-footers-using-pandoc">Adding headers and footers using Pandoc</a>. You just need to sneak a little LaTeX into the YAML header of your markdown document.</p> <p>This markdown header does the trick:</p> <pre><code>--- title: "Test" author: "Author Name" header-includes: - \usepackage{fancyhdr} - \pagestyle{fancy} - \fancyhead[CO,CE]{This is fancy header} - \fancyfoot[CO,CE]{And this is a fancy footer} - \fancyfoot[LE,RO]{\thepage} output: pdf_document --- </code></pre> <p>Works for me with an Rmd file in <a href="http://www.rstudio.org/download/daily/desktop/windows/" rel="noreferrer">RStudio Version 0.98.1030 for Windows</a>.</p>
39,432,242
NSPhotoLibraryUsageDescription in Xcode8
<p><strong><em>Update</em></strong>:<br> I attempt to add a String value to the <code>"NSPhotoLibraryUsageDescription"</code> key.<br> <a href="https://i.stack.imgur.com/BdY0T.png"><img src="https://i.stack.imgur.com/BdY0T.png" alt="enter image description here"></a></p> <p>And it works.My build version is now available on my TestFlight.</p> <p><a href="https://i.stack.imgur.com/B3DQ8.png"><img src="https://i.stack.imgur.com/B3DQ8.png" alt="enter image description here"></a> ps: <strong>构建版本</strong> means <strong>Build Version</strong></p> <p>But I want to know why Apple Store just let me add String value for <code>"NSPhotoLibraryUsageDescription"</code> key rather than <code>"Camera Usage Description"</code> or <code>"Location When In Use Usage Description"</code>? And how to localize the info.plist. <hr> <strong><em>Old</em></strong>:<br> I've uploaded many build versions to iTunes Connect.But TestFlight shows none of these build versions.<br> Then I search this issue on stackoverflow. And I know this is caused by usage description. I add the <strong>NSPhotoLibraryUsageDescription</strong> in my Info.plist. However, Apple Store team email and tell me that:</p> <blockquote> <p>Dear developer,</p> <p>We have discovered one or more issues with your recent delivery for "Family Health Tracker". To process your delivery, the following issues must be corrected:</p> <p>This app attempts to access privacy-sensitive data without a usage description. The app's Info.plist must contain an <strong>NSPhotoLibraryUsageDescription</strong> key with a string value explaining to the user how the app uses this data.</p> <p>Once these issues have been corrected, you can then redeliver the corrected binary.</p> <p>Regards,</p> <p>The App Store team</p> </blockquote> <p>They still tell me add <strong>NSPhotoLibraryUsageDescription</strong></p> <p><a href="https://i.stack.imgur.com/ynjgo.png"><img src="https://i.stack.imgur.com/ynjgo.png" alt="This is my Info.plist"></a></p>
39,588,338
7
2
null
2016-09-11 02:14:53.82 UTC
14
2017-08-20 20:39:48.287 UTC
2016-09-11 02:57:50.893 UTC
null
6,302,694
null
6,302,694
null
1
40
app-store-connect|testflight|ios10|xcode8
39,030
<p>Localizing of <code>info.plist</code> file may be very unuseful, especially if you use many languages in your apps. The simplest way for localizing <code>NSPhotoLibraryUsageDescription</code>, <code>NSLocationWhenInUseUsageDescription</code>or <code>NSCameraUsageDescription</code> keys is to describe it in <code>InfoPlist.strings</code> file.</p> <ul> <li>Create new <code>*.strings</code> file with name <code>InfoPlist</code>;</li> <li>Press <code>Localize...</code> button in file inspector and choose the default language;</li> <li>Add new records in your new <code>InfoPlist.strings</code> file. For example in English:</li> </ul> <blockquote> <p>NSLocationWhenInUseUsageDescription = &quot;Location usage description&quot;;</p> <p>NSPhotoLibraryUsageDescription = &quot;Photos usage description&quot;;</p> <p>NSCameraUsageDescription = &quot;Camera usage description&quot;;</p> </blockquote> <p>For more information <a href="https://developer.apple.com/library/content/#documentation/general/Reference/InfoPlistKeyReference/Articles/AboutInformationPropertyListFiles.html" rel="noreferrer">Apple docs</a></p>
69,798,705
Regex to match nothing but zeroes after the first zero
<p>Using regular expressions, how can I make sure there are nothing but zeroes after the first zero?</p> <pre><code>ABC1000000 - valid 3212130000 - valid 0000000000 - valid ABC1000100 - invalid 0001000000 - invalid </code></pre> <p>The regex without validation would be something like this - <code>[A-Z0-9]{10}</code>, making sure it is 10 characters.</p>
69,798,738
6
3
null
2021-11-01 14:55:29.703 UTC
1
2021-11-03 11:42:47.163 UTC
2021-11-02 12:49:50.76 UTC
null
4,182,398
null
3,246,362
null
1
34
regex
4,156
<p>You could update the pattern to:</p> <pre><code>^(?=[A-Z0-9]{10}$)[A-Z1-9]*0+$ </code></pre> <p>The pattern matches:</p> <ul> <li><code>^</code> Start of string</li> <li><code>(?=[A-Z0-9]{10}$)</code> Positive looakhead, assert 10 allowed chars</li> <li><code>[A-Z1-9]*</code> Optionally match any char of <code>[A-Z1-9]</code></li> <li><code>0+</code> Match 1+ zeroes</li> <li><code>$</code> End of string</li> </ul> <p><a href="https://regex101.com/r/o4HUUK/1" rel="noreferrer">Regex demo</a></p> <p>If a value without zeroes is also allowed, the last quantifier can be <code>*</code> matching 0 or more times (and a bit shorter version by the comment of @<a href="https://stackoverflow.com/users/3204551/deduplicator">Deduplicator</a> using a negated character class):</p> <pre><code>^(?=[A-Z0-9]{10}$)[^0]*0*$ </code></pre> <p>An example with JavaScript:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const regex = /^(?=[A-Z0-9]{10}$)[^0]*0*$/; ["ABC1000000", "3212130000", "0000000000", "ABC1000100", "0001000000"] .forEach(s =&gt; console.log(`${s} --&gt; ${regex.test(s)}`) );</code></pre> </div> </div> </p> <hr> <p>As an alternative without lookarounds, you could also match what you don't want, and capture in group 1 what you want to keep.</p> <p>To make sure there are nothing but zeroes after the first zero, you could stop the match as soon as you match 0 followed by 1 char of the same range without the 0.</p> <p>In the alternation, the second part can then capture 10 chars of range A-Z0-9.</p> <pre><code>^(?:[A-Z1-9]*0+[A-Z1-9]|([A-Z0-9]{10})$) </code></pre> <p>The pattern matches:</p> <ul> <li><code>^</code> Start of string</li> <li><code>(?:</code> Non capture group for the alternation <code>|</code> <ul> <li><code>[A-Z1-9]*0+[A-Z1-9]</code> Match what should not occur, in this case a zero followed by a char from the range without a zero</li> <li><code>|</code> Or</li> <li><code>([A-Z0-9]{10})</code> Capture <strong>group 1</strong>, match 10 chars in range <code>[A-Z0-9]</code></li> </ul> </li> <li><code>$</code> End of string</li> <li><code>)</code> Close non capture group</li> </ul> <p><a href="https://regex101.com/r/yMr8dy/1" rel="noreferrer">Regex demo</a></p>
55,200,786
Enable CORS from front-end in React with axios?
<p>I am using React on the front-end and I'm calling API from another domain which I don't own. My axios request: </p> <pre><code>axios(requestURL, { method: 'GET', headers: { 'Access-Control-Allow-Origin': '*', 'Content-Type': 'application/json', 'Authorization': key, withCredentials: true, mode: 'no-cors', } </code></pre> <p>I keep on getting the same error: CORS header ‘Access-Control-Allow-Origin’ missing. Is this something I can overcome from the frontend? I know for a fact that people use that API so it can't be backend fault, right? I tried requesting a lot of APIs and not even one worked with my code. I tried using <a href="https://cors-anywhere.herokuapp.com" rel="noreferrer">https://cors-anywhere.herokuapp.com</a> and it worked fine for like a week, I think its down today. I want my site to stay 24/7 so using a proxy is not an option</p>
55,200,995
3
1
null
2019-03-16 19:42:29.91 UTC
5
2020-09-28 20:37:35.193 UTC
null
null
null
null
9,438,224
null
1
17
reactjs|cors|axios
65,499
<p>You will, unfortunately, need to proxy the request somehow. CORS requests will be blocked by the browser for security reasons. To avoid this, backend needs to inject allow origin header for you.</p> <p>Solutions depend on where you need to proxy, dev or production.</p> <p><strong>Development environment or node.js production webserver</strong></p> <p>The easiest way to do it in this scenario is to use the <em>'http-proxy-middleware'</em> npm package</p> <pre><code>const proxy = require('http-proxy-middleware'); module.exports = function (app) { app.use(proxy('/api', { target: 'http://www.api.com', logLevel: 'debug', changeOrigin: true })); }; </code></pre> <p><strong>Production - Web server where you have full access</strong> Check the following page to see how to enable such proxying on your webserver:</p> <p><a href="https://enable-cors.org/server.html" rel="noreferrer">https://enable-cors.org/server.html</a></p> <p><strong>Production - Static hosting / Web server without full access</strong></p> <p><em>If your hosting supports PHP</em>, you can add a php script like: <a href="https://github.com/softius/php-cross-domain-proxy" rel="noreferrer">https://github.com/softius/php-cross-domain-proxy</a></p> <p>Then hit a request from your app to the script, which will forward it and inject headers on the response</p> <p><em>If your hosting doesn't support PHP</em> Unfortunately, you will need to rely on a solution like the one that you have used. </p> <p>In order to avoid relying on a third party service, you should deploy a proxy script somewhere that you will use.</p> <p>My suggestions are:</p> <ul> <li><p>Move to a hosting that supports php :) (Netlify could be a solution, but I'm not sure)</p></li> <li><p>You can deploy a node.js based proxy script of your own to Firebase for example (firebase functions), to ensure it will not magically go down, and the free plan could possibly handle your amount of requests.</p></li> <li><p>Create a free Amazon AWS account, where you will get the smallest instance for free for a year, and run an ubuntu server with nginx proxy there.</p></li> </ul>
24,036,393
Fatal error: use of unimplemented initializer 'init(coder:)' for class
<p>I decided to continue my remaining project with Swift. When I add the custom class (subclass of <code>UIViewcontroller</code>) to my storyboard view controller and load the project, the app crashes suddenly with the following error:</p> <blockquote> <p>fatal error: use of unimplemented initializer 'init(coder:)' for class</p> </blockquote> <p><strong>This is a code:</strong></p> <pre><code>import UIKit class TestViewController: UIViewController { init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) // Custom initialization } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // #pragma mark - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue?, sender: AnyObject?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ } </code></pre> <p>Please suggest something</p>
24,036,440
6
0
null
2014-06-04 11:38:18.023 UTC
59
2019-03-29 12:52:48.1 UTC
2019-03-29 12:51:15.233 UTC
null
1,752,496
null
2,919,739
null
1
156
ios|macos|uiviewcontroller|swift
91,642
<h1>Issue</h1> <p>This is caused by the absence of the initializer <code>init?(coder aDecoder: NSCoder)</code> on the target <code>UIViewController</code>. That method is required because instantiating a <code>UIViewController</code> from a <code>UIStoryboard</code> calls it.</p> <p>To see how we initialize a <code>UIViewController</code> from a <code>UIStoryboard</code>, please take a look <a href="https://stackoverflow.com/q/24035984/2664437">here</a></p> <h3>Why is this not a problem with Objective-C?</h3> <p>Because <strong>Objective-C</strong> automatically inherits all the required <code>UIViewController</code> initializers.</p> <h3>Why doesn't Swift automatically inherit the initializers?</h3> <p><strong>Swift</strong> by default does not inherit the initializers due to safety. But it will inherit all the initializers from the superclass if all the properties have a value (or optional) and the subclass has not defined any designated initializers.</p> <hr /> <h1>Solution</h1> <h2>1. First method</h2> <p>Manually implementing <code>init?(coder aDecoder: NSCoder)</code> on the target <code>UIViewController</code></p> <pre><code>required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } </code></pre> <hr /> <h2>2. Second method</h2> <p>Removing <code>init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?)</code> on your target <code>UIViewController</code> will inherit all of the required initializers from the superclass as <strong>Dave Wood</strong> pointed on his <a href="https://stackoverflow.com/a/24077074/2664437">answer</a> below</p> <hr />
24,072,876
Too many warnings about 'circular require' when run rspec
<p>Hi I got lots of warning when run <code>rspec</code> which does annoying me too much,</p> <p>How to fix it ? because I've tried the Ruby version <code>2.1.2</code> under rbenv, but it didn't work at all.</p> <p>Here's my Gemfile</p> <pre><code>source 'https://rubygems.org' gem 'bootstrap-sass' gem 'coffee-rails' gem 'rails' gem 'haml-rails' gem 'sass-rails' gem 'uglifier' gem 'jquery-rails' group :development do gem 'sqlite3' gem 'pry' gem 'pry-nav' gem 'thin' gem "better_errors" gem "binding_of_caller" end group :test, :development do gem 'rspec-rails' end group :production do gem 'pg' gem 'rails_12factor' end gem 'hirb' gem 'crack' gem 'ap' gem 'awesome_print' # gem 'faker' </code></pre> <p>Warning meassages</p> <pre><code>% rspec (git)-[feature/w1_test_the_video_model] nil /Users/jeff/.rbenv/versions/2.0.0-p481/lib/ruby/gems/2.0.0/gems/bootstrap-sass-3.1.1.1/lib/bootstrap-sass/sass_functions.rb:20: warning: ambiguous first argument; put parentheses or even spaces /Users/jeff/.rbenv/versions/2.0.0-p481/lib/ruby/gems/2.0.0/gems/sass-3.2.19/lib/sass/version.rb:5: warning: loading in progress, circular require considered harmful - /Users/jeff/.rbenv/versions/2.0.0-p481/lib/ruby/gems/2.0.0/gems/sass-3.2.19/lib/sass.rb from /Users/jeff/.rbenv/versions/2.0.0-p481/bin/rspec:23:in `&lt;main&gt;' from /Users/jeff/.rbenv/versions/2.0.0-p481/bin/rspec:23:in `load' from /Users/jeff/.rbenv/versions/2.0.0-p481/lib/ruby/gems/2.0.0/gems/rspec-core-3.0.0/exe/rspec:4:in `&lt;top (required)&gt;' from /Users/jeff/.rbenv/versions/2.0.0-p481/lib/ruby/gems/2.0.0/gems/rspec-core-3.0.0/lib/rspec/core/runner.rb:38:in `invoke' from /Users/jeff/.rbenv/versions/2.0.0-p481/lib/ruby/gems/2.0.0/gems/rspec-core-3.0.0/lib/rspec... </code></pre>
24,074,527
3
1
null
2014-06-06 01:39:18.233 UTC
2
2017-02-18 18:40:04.857 UTC
null
null
null
null
3,675,188
null
1
28
ruby-on-rails|ruby-on-rails-4|rspec
7,515
<p>I had same error and fixed it refs the page.</p> <p><a href="https://stackoverflow.com/questions/24003316/guard-with-rspec-on-rails-4-giving-a-lot-of-warnings">Guard with RSpec on Rails 4 giving a lot of warnings</a></p> <blockquote> <p>the <code>--warnings</code> option in the .rspec file by default. Remove that line, and the warnings will go away.</p> </blockquote>
24,351,377
Which is the Swift equivalent of isnan()?
<p>Which is the equivalent of <code>isnan()</code> in Swift ? I need to check if some operation results are valid and delete those invalid like x/0 Thanks</p>
24,351,407
2
1
null
2014-06-22 12:48:00.903 UTC
9
2020-12-19 07:28:59.48 UTC
null
null
null
null
1,189,841
null
1
65
cocoa|swift|nan
27,808
<p>It's defined in the <a href="http://swiftdoc.org/protocol/FloatingPointType/">FloatingPointNumber</a> protocol, which both the <a href="http://swiftdoc.org/type/Float/">Float</a> and <a href="http://swiftdoc.org/type/Double/">Double</a> types conform to. Usage is as follows:</p> <pre><code>let d = 3.0 let isNan = d.isNaN // False let d = Double.NaN let isNan = d.isNaN // True </code></pre> <p>If you're looking for a way to make this check yourself, you can. IEEE defines that NaN != NaN, meaning you can't directly compare NaN to a number to determine its is-a-number-ness. However, you can check that <code>maybeNaN != maybeNaN</code>. If this condition evaluates as true, you're dealing with NaN.</p> <p>Although you should <strong>prefer using <code>aVariable.isNaN</code></strong> to determine if a value is NaN.</p> <hr> <p>As a bit of a side note, if you're less sure about the classification of the value you're working with, you can switch over value of your <code>FloatingPointNumber</code> conforming type's <code>floatingPointClass</code> property.</p> <pre><code>let noClueWhatThisIs: Double = // ... switch noClueWhatThisIs.floatingPointClass { case .SignalingNaN: print(FloatingPointClassification.SignalingNaN) case .QuietNaN: print(FloatingPointClassification.QuietNaN) case .NegativeInfinity: print(FloatingPointClassification.NegativeInfinity) case .NegativeNormal: print(FloatingPointClassification.NegativeNormal) case .NegativeSubnormal: print(FloatingPointClassification.NegativeSubnormal) case .NegativeZero: print(FloatingPointClassification.NegativeZero) case .PositiveZero: print(FloatingPointClassification.PositiveZero) case .PositiveSubnormal: print(FloatingPointClassification.PositiveSubnormal) case .PositiveNormal: print(FloatingPointClassification.PositiveNormal) case .PositiveInfinity: print(FloatingPointClassification.PositiveInfinity) } </code></pre> <p>Its values are declared in the <a href="http://swiftdoc.org/type/FloatingPointClassification/">FloatingPointClassification</a> enum.</p>
21,639,394
How to select item in collectionview programmatically?
<p>I have a <code>UICollectionView</code>. The <code>UICollectionView</code>'s <code>datasource</code> is a <code>NSArray</code> of students (from <code>CoreData</code>). I want the current student item be <code>selected</code>/<code>highlighted</code>.</p> <p>How can I do this? I know there is a method:</p> <pre><code>- (void)selectItemAtIndexPath:(NSIndexPath *)indexPath animated:(BOOL)animated scrollPosition:(UICollectionViewScrollPosition)scrollPosition; </code></pre> <p>which takes as arguments an <code>NSIndexPath</code> and <code>UICollectionViewScrollPosition</code>.</p> <p>I have the datasource (<code>NSArray</code> of students populated from <code>CoreData</code>) and the student object to be <code>selected</code>.</p> <p>So, how do I get the <code>NSIndexPath</code> and <code>UICollectionViewScrollPosition</code>? Or is there any other way to highlight an item?</p>
21,640,147
8
2
null
2014-02-07 23:05:06.857 UTC
4
2021-05-11 18:25:32.293 UTC
2014-03-03 16:11:59.763 UTC
null
1,141,395
null
1,210,095
null
1
28
ios|iphone|uicollectionview|uicollectionviewcell
70,370
<p>You can simply use this after <code>[self.collectionView reloadData]</code></p> <pre><code>[self.collectionView selectItemAtIndexPath:[NSIndexPath indexPathForItem:index inSection:0] animated:YES scrollPosition:UICollectionViewScrollPositionCenteredVertically]; </code></pre> <p>where <code>index</code> is the index number for the selected student.</p>
1,742,909
Why is the control inaccessible due to its protection level?
<p>I'm trying to access a control's text property from program.cs and it says that it is inaccessible due to protected level. How can I fix this please?</p>
1,742,914
4
5
null
2009-11-16 15:30:22.17 UTC
1
2019-11-20 23:57:00.26 UTC
2009-11-16 17:32:55.027 UTC
null
111,575
null
164,203
null
1
22
c#|winforms|controls
56,138
<p>This is the default property for controls and can be solved by:</p> <ol> <li>Going into Design-View for the Form that contains the specified Control</li> <li>Then changing the Control's Modifiers property to Public or Internal. </li> </ol> <p><a href="https://i.stack.imgur.com/wVTn6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wVTn6.png" alt="Control Properties &gt; Modifiers Screenshot"></a></p>
52,591,556
Custom markers with Flutter Google Maps plugin
<p>Is there a way to display custom markers with the official <a href="https://github.com/flutter/plugins/tree/master/packages/google_maps_flutter" rel="noreferrer">Flutter Google Maps plugin</a> on the map? Can't find any way to do it based on the documentation.</p>
59,114,878
12
3
null
2018-10-01 12:48:54.813 UTC
8
2021-11-01 06:09:37.337 UTC
2019-06-02 03:49:41.05 UTC
null
6,513,167
null
1,157,401
null
1
15
google-maps|plugins|flutter
51,655
<pre><code>BitmapDescriptor customIcon; // make sure to initialize before map loading BitmapDescriptor.fromAssetImage(ImageConfiguration(size: Size(12, 12)), 'assets/images/car-icon.png') .then((d) { customIcon = d; }); final nearbyCarsLocation = [ LatLng(24.9286825, 67.0403249), LatLng(24.985577, 67.0661056), //24.9294892,67.0391903,18.73z ]; void _getNearByCars() { for (var i = 0; i &lt; nearbyCarsLocation.length; i++) { var now = new DateTime.now().millisecondsSinceEpoch; _markers.add(Marker( markerId: MarkerId(nearbyCarsLocation[i].toString() + now.toString()), position: nearbyCarsLocation[i], // infoWindow: InfoWindow(title: address, snippet: "go here"), icon: customIcon )); } notifyListeners(); } </code></pre> <p>Hope this will help in getting custom nearby localities</p>
10,414,703
prop("disabled", true); AND attr('disabled', 'disabled') is not working in chrome and firefox
<p>i have the following script inside my asp.net mvc view:-</p> <pre><code>function disableform(id) { $('#' + id).prop("disabled", true); } </code></pre> <p>But the above function will only disable the elements using internet explorer ,, but will fail to work on chrome or firefox, i also tried to write <code>attr('disabled', 'disabled')</code> instead of <code>.prop("disabled", true);</code>, but it did not solve the problem.</p> <p><strong>my Jquery version is 1.7.1</strong></p> <p>So what might be the problem?</p> <p>BR</p>
10,414,865
4
2
null
2012-05-02 13:25:56.187 UTC
2
2017-08-31 20:47:03.47 UTC
null
null
null
null
1,146,775
null
1
9
jquery
50,483
<p>Disabling a <strong>form</strong> is wrong! IE is just messing it out! you should disable fields.</p> <pre><code>function disableform(id) { $('#' + id+' :input').prop("disabled",true); }​ </code></pre> <p><a href="http://jsfiddle.net/EGgzT/1/" rel="noreferrer">DEMO</a></p>
10,475,898
Receive byte[] using ByteArrayInputStream from a socket
<p>Here is the code but got error:</p> <pre><code>bin = new ByteArrayInputStream(socket.getInputStream()); </code></pre> <p>Is it possible to receive <code>byte[]</code> using <code>ByteArrayInputStream</code> from a socket?</p>
10,475,953
2
2
null
2012-05-07 02:09:10.21 UTC
3
2015-04-15 05:29:24.143 UTC
2012-05-07 02:19:55.987 UTC
null
418,556
null
925,552
null
1
10
java|sockets|io|inputstream|bytearrayinputstream
44,758
<p>No. You use <code>ByteArrayInputStream</code> when you have an array of bytes, and you want to read from the array as if it were a file. If you just want to read arrays of bytes from the socket, do this:</p> <pre><code>InputStream stream = socket.getInputStream(); byte[] data = new byte[100]; int count = stream.read(data); </code></pre> <p>The variable <code>count</code> will contain the number of bytes actually read, and the data will of course be in the array <code>data</code>.</p>
10,667,543
Creating fstream object from a FILE* pointer
<p>The well known way of creating an <strong><code>fstream</code></strong> object is:</p> <pre><code>ifstream fobj("myfile.txt"); </code></pre> <p>ie. using a filename.</p> <p>But I want to create an ifstream object using a file descriptor.</p> <blockquote> <p><strong>Reason:</strong> I want to execute a command using <code>_popen()</code><strong>.</strong> <code>_popen()</code> returns the output as a <code>FILE*</code>. So there is a FILE* pointer involved but no filename.</p> </blockquote>
10,667,570
3
2
null
2012-05-19 17:48:01.263 UTC
1
2022-05-10 07:34:28.743 UTC
2012-05-19 17:54:51.967 UTC
null
1,184,247
null
1,184,247
null
1
30
c++|popen|ifstream
15,666
<p>You cannot do that just in standard C++, since iostreams and C I/O are entirely separate and unrelated. You could however write your <em>own</em> iostream that's backed by a C FILE stream. I believe that GCC comes with one such stream class as a library extension.</p> <p>Alternatively, if all you want is an object-y way of wrapping a C FILE stream, you could <a href="https://codereview.stackexchange.com/questions/4679/shared-ptr-and-file-for-wrapping-cstdio-update-also-dlfcn-h">use a unique pointer</a> for that purpose.</p>
7,447,498
Why can't a member method be passed to a base class constructor?
<pre><code>class Flarg { private readonly Action speak; public Action Speak { get { return speak; } } public Flarg(Action speak) { this.speak = speak; } } class MuteFlarg : Flarg { public MuteFlarg() : base(GiveDumbLook) { } private void GiveDumbLook() { } } </code></pre> <p>The compiler gives an error "An object is required for the non-static field, method, or property 'Project.Namespace.Class.GiveDumbLook'.</p> <p>This seems no different than passing an action as a parameter to any other method. Why is this invalid? </p> <p><strong>Edit</strong> Great answers. Thanks to everyone. I guess this just confuses me, because it seems like it is the opposite-side-of-the-coin from <a href="https://stackoverflow.com/q/7046414/7495">this question</a>; where the highest voted answer clearly states </p> <blockquote> <p>A C# object is fully constructed and initialized to zero before the first constructor runs.</p> </blockquote> <p>By that statement, it seems that the above code should work. Apparently there is a subtle difference.</p>
7,447,535
7
2
null
2011-09-16 16:04:14.137 UTC
1
2011-09-17 00:59:54.33 UTC
2017-05-23 10:31:17.15 UTC
null
-1
null
7,495
null
1
29
c#
3,756
<p>Rewrite it like this:</p> <pre><code>public MuteFlarg() : base(this.GiveDumbLook) { } </code></pre> <p>and it is now clear why you can't. It's not legal to refer to <code>this</code> in a base class constructor invocation. This is not legal because it can easily lead to bugs. The constructor for the derived class has not run yet, and so the fields are not set to their initial state (initial state being defined by the state of the object when the constructor is done running). </p> <p>This is explicitly stated in §10.11.1 of the specification:</p> <blockquote> <p>An instance constructor initializer cannot access the instance being created. Therefore it is a compile-time error to reference <code>this</code> in an argument expression of the constructor initializer, as is it a compile-time error for an argument expression to reference any instance member through a <em>simple-name</em>.</p> </blockquote> <p>The last statement explicitly forbids referring to <code>this.GiveDumbLook</code> by its simple-name <code>GiveDumbLook</code>. </p>
7,529,258
What major ASIHTTPRequest features is AFNetworking missing?
<p>With <a href="http://allseeing-i.com/%5Brequest_release%5D;" rel="nofollow noreferrer">work having recently stopped on ASIHTTPRequest</a>, it seems like attention is shifting to <a href="https://github.com/AFNetworking/AFNetworking" rel="nofollow noreferrer">AFNetworking</a>.</p> <p>However, I've not yet found a good comparison of the features of the two libraries, so I don't know what I might lose if/when I switch over.</p> <p>Major differences I've spotted so far are:</p> <ol> <li>AFNetworking has a much smaller code size (which is good)</li> <li>AFNetworking is being rapidly improved (so it may not yet be mature, may not have a stable API yet?)</li> <li>Both seem to have caching, though I've seen hints that because AFNetworking uses <a href="https://stackoverflow.com/questions/7166422/nsurlconnection-on-ios-doesnt-try-to-cache-objects-larger-than-50kb">NSURLConnection it won't cache objects over 50K</a></li> <li>ASIHTTPRequest has very good support for manual &amp; automatic (PAC) http proxies; I can't find any information on what level of support AFNetworking has for proxies</li> <li>AFNetworking requires iOS 4+, whereas ASIHTTPRequest works right back to iOS 2 (not really an issue for me, but it is an issue for some people)</li> <li>AFNetworking doesn't (yet) have a built in persistent cache, but there's a persistent cache which has a pending pull request: <a href="https://github.com/gowalla/AFNetworking/pull/25" rel="nofollow noreferrer">https://github.com/gowalla/AFNetworking/pull/25</a></li> </ol> <p>Has anyone seen any good comparisons of the two libraries or any documented experiences of switching from one to the other?</p>
8,377,096
8
5
null
2011-09-23 12:54:39.013 UTC
51
2016-05-20 09:52:48.327 UTC
2017-05-23 12:00:20.313 UTC
null
-1
null
292,166
null
1
93
iphone|ios|ipad|asihttprequest|afnetworking
17,515
<p>I loved ASIHTTPRequest and I was sad to see it go. However, the developer of ASI was right, ASIHTTPRequest has become so large and bloated that even he couldn't devote time to bring it to par with newest features of iOS and other frameworks. I moved on and now use AFNetworking.</p> <p>That said, I must say that AFNetworking is much more unstable than ASIHTTP, and for the things I use it for, it needs refinement.</p> <p>I often need to make HTTP requests to 100 HTTP sources before I display my results on screen, and I have put AFHTTPNetworkOperation into an operation queue. Before all results are downloaded, I want to be able to cancel all operations inside the operation queue and then dismiss the view controller that holds the results.</p> <p>That doesn't always work.</p> <p>I get crashes at random times with AFNetworking, while with ASIHTTPRequest, this operations were working flawlessly. I wish I could say which specific part of AFNetworking is crashing, as it keeps crashing at different points (however, most of these times the debugger points to the NSRunLoop that creates an NSURLConnection object). So, AFNetworking needs to mature in order to be considered as complete as ASIHTTPRequest was.</p> <p>Also, ASIHTTPRequests supports client authentication, which AFNetworking lacks at the moment. The only way to implement it is to subclass AFHTTPRequestOperation and to override NSURLConnection's authentication methods. However, if you start getting involved with NSURLConnection, you will notice that putting NSURLConnection inside an NSOperation wrapper and writing completion blocks isn't so hard as it sounds and you will start thinking what keeps you from dumping 3rd party libraries.</p> <p>ASI uses a whole different approach, since it uses CFNetworking (lower-level foundation frameworks based on C) to make downloading and file uploading possible, skipping NSURLConnection completely, and touching concepts most of us OS X and iOS developers are too afraid to. Because of this, you get better file uploading and downloading, even web page caches.</p> <p>Which do i prefer? It's hard to say. If AFNetworking matures enough, I will like it more than ASI. Until then, I can't help but admire ASI, and the way it became one of the most used frameworks of all time for OS X and iOS.</p> <p><strong>EDIT:</strong> <strong>I think it's time to update this answer, as things have changed a bit after this post.</strong></p> <p>This post was written some time ago, and AFNetworking has matured enough. 1-2 months ago AF posted a small update for POST operations that was my last complaint about the framework (a small line ending fault was the reason that echonest uploads failed with AF but were completed fine with ASI). Authentication is not an issue with AFnetworking, as for complex authentication methods you can subclass the operation and make your own calls and AFHTTPClient makes basic authentication a piece of cake. By subclassing AFHTTPClient you can make an entire service consumer in little time.</p> <p>Not to mention the absolutely necessary UIImage additions that AFNetworking offers. With blocks and custom completion blocks and some clever algorithm, you can make table views with asynchronous image downloading and cell filling pretty easily, whereas in ASI you had to make operation queues for bandwidth throttling and mind yourself to cancel and resume the operation queue according to table view visibility, and stuff like that. Development time of such operations has been halved.</p> <p>I also love the success and failure blocks. ASI has only a completion block (which is actually the completion block of NSOperation). You had to check whether you had an error on completion and act accordingly. For complex web services, you could get lost in all the "ifs" and "elses"; In AFNetworking, things are much more simple and intuitive.</p> <p>ASI was great for its time, but with AF you can change the way you handle web services completely in a good way, and make scalable applications more easily. I really believe that there is no reason whatsoever to stick with ASI anymore, unless you want to target iOS 3 and below.</p>
7,198,109
Rails: Using simple_form and integrating Twitter Bootstrap
<p>I'm trying to build a rails app and simple_form looks to be a really useful gem. Problem is that I am using twitter bootstrap css to do the styling and the simple_form doesn't allow you to specify the layout of the html. </p> <p>Can anyone tell me how I can conform the simple_form html into the format bootstrap css wants?</p>
7,300,806
9
0
null
2011-08-25 22:49:50.333 UTC
14
2013-04-13 17:15:51.017 UTC
null
null
null
null
157,894
null
1
23
ruby-on-rails|simple-form|twitter-bootstrap
13,338
<p><em>Note: This answer only applies to SimpleForm &lt; 2.0</em></p> <p>Start with this in <code>config/initializers/simple_form.rb</code>:</p> <pre><code>SimpleForm.form_class = nil SimpleForm.wrapper_class = 'clearfix' SimpleForm.wrapper_error_class = 'error' SimpleForm.error_class = 'help-inline' </code></pre> <p>Then there's space missing between the label element and the input, which you can add with this:</p> <pre><code>label { margin-right: 20px; } </code></pre> <p>There's probably more, but it's a start.</p>
7,585,493
Null parameter checking in C#
<p>In C#, are there any good reasons (other than a better error message) for adding parameter null checks to every function where null is not a valid value? Obviously, the code that uses s will throw an exception anyway. And such checks make code slower and harder to maintain.</p> <pre><code>void f(SomeType s) { if (s == null) { throw new ArgumentNullException("s cannot be null."); } // Use s } </code></pre>
7,585,528
10
6
null
2011-09-28 15:19:32.023 UTC
33
2022-08-02 08:40:45.693 UTC
2014-06-25 22:03:50.897 UTC
null
2,246,344
null
527,147
null
1
90
c#|function|null
55,864
<p>Yes, there are good reasons:</p> <ul> <li>It identifies exactly what is null, which may not be obvious from a <code>NullReferenceException</code></li> <li>It makes the code fail on invalid input even if some other condition means that the value isn't dereferenced</li> <li>It makes the exception occur <em>before</em> the method could have any other side-effects you might reach before the first dereference</li> <li>It means you can be confident that if you pass the parameter into something else, you're not violating <em>their</em> contract</li> <li>It documents your method's requirements (using <a href="http://research.microsoft.com/contracts" rel="noreferrer">Code Contracts</a> is even better for that of course)</li> </ul> <p>Now as for your objections:</p> <ul> <li><em>It's slower</em>: Have you found this to <em>actually</em> be the bottleneck in your code, or are you guessing? Nullity checks are very quick, and in the vast majority of cases they're <em>not</em> going to be the bottleneck</li> <li><em>It makes the code harder to maintain</em>: I think the opposite. I think it's <em>easier</em> to use code where it's made crystal clear whether or not a parameter can be null, and where you're confident that that condition is enforced.</li> </ul> <p>And for your assertion:</p> <blockquote> <p>Obviously, the code that uses s will throw an exception anyway.</p> </blockquote> <p>Really? Consider:</p> <pre><code>void f(SomeType s) { // Use s Console.WriteLine(&quot;I've got a message of {0}&quot;, s); } </code></pre> <p>That uses <code>s</code>, but it doesn't throw an exception. If it's invalid for <code>s</code> to be null, and that indicates that something's wrong, an exception is the most appropriate behaviour here.</p> <p>Now <em>where</em> you put those argument validation checks is a different matter. You may decide to trust all the code within your own class, so not bother on private methods. You may decide to trust the rest of your assembly, so not bother on internal methods. You should almost certainly validate the arguments for public methods.</p> <p>A side note: the single-parameter constructor overload of <code>ArgumentNullException</code> should just be the parameter name, so your test should be:</p> <pre><code>if (s == null) { throw new ArgumentNullException(&quot;s&quot;); } </code></pre> <p>Alternatively you can create an extension method, allowing the somewhat terser:</p> <pre><code>s.ThrowIfNull(&quot;s&quot;); </code></pre> <p>In my version of the (generic) extension method, I make it return the original value if it's non null, allowing you to write things like:</p> <pre><code>this.name = name.ThrowIfNull(&quot;name&quot;); </code></pre> <p>You can also have an overload which doesn't take the parameter name, if you're not too bothered about that.</p> <h3>Update .NET 6</h3> <p>There is a <a href="https://docs.microsoft.com/en-us/dotnet/api/system.argumentnullexception.throwifnull?view=net-6.0" rel="noreferrer">new method</a> in .NET API which simplifies <code>null</code> check syntax.</p> <pre><code> ArgumentNullException.ThrowIfNull(someParameter); </code></pre>
7,490,488
Convert flat array to a delimited string to be saved in the database
<p>What is the best method for converting a PHP array into a string?<br /> I have the variable <code>$type</code> which is an array of types.</p> <pre><code>$type = $_POST[type]; </code></pre> <p>I want to store it as a single string in my database with each entry separated by <code>|</code> :</p> <pre><code>Sports|Festivals|Other </code></pre>
7,490,505
13
5
null
2011-09-20 19:13:46.467 UTC
54
2022-07-03 09:04:15.6 UTC
2022-07-03 09:04:15.6 UTC
null
2,943,403
null
773,263
null
1
361
php|arrays|string|implode
933,074
<p>Use <a href="http://php.net/implode" rel="noreferrer">implode</a></p> <pre><code>implode(&quot;|&quot;,$type); </code></pre>
7,305,538
UITextField with secure entry, always getting cleared before editing
<p>I am having a weird issue in which my <code>UITextField</code> which holds a secure entry is always getting cleared when I try to edit it. I added 3 <code>characters</code> to the field, goes to another field and comes back, the cursor is in 4th <code>character</code> position, but when I try to add another character, the whole text in the field gets cleared by the new character. I have 'Clears when editing begins' unchecked in the nib. So what would be the issue? If I remove the secure entry property, everything is working fine, so, is this the property of Secure entry <code>textfields</code>? Is there any way to prevent this behaviour?</p>
7,305,603
28
2
null
2011-09-05 08:26:39.207 UTC
20
2022-03-24 13:17:55.943 UTC
2019-07-26 19:05:57.337 UTC
null
11,328,137
null
221,153
null
1
55
iphone|uitextfield
52,250
<p>Set, </p> <pre><code>textField.clearsOnBeginEditing = NO; </code></pre> <p><em>Note: This won't work if <strong>secureTextEntry = YES</strong>.</em> It seems, by default, iOS clears the text of secure entry text fields before editing, no matter <strong>clearsOnBeginEditing</strong> is YES or NO.</p>
14,344,130
Convert char array to string use C
<p>I need to convert a char array to string. Something like this:</p> <pre><code>char array[20]; char string[100]; array[0]='1'; array[1]='7'; array[2]='8'; array[3]='.'; array[4]='9'; ... </code></pre> <p>I would like to get something like that:</p> <pre><code>char string[0]= array // where it was stored 178.9 ....in position [0] </code></pre>
14,344,229
3
5
null
2013-01-15 18:13:17.577 UTC
10
2013-01-17 03:40:08.063 UTC
2013-01-16 03:00:23.283 UTC
null
1,437,962
null
1,973,988
null
1
11
c|arrays
170,514
<p>You're saying you have this:</p> <pre><code>char array[20]; char string[100]; array[0]='1'; array[1]='7'; array[2]='8'; array[3]='.'; array[4]='9'; </code></pre> <p>And you'd like to have this:</p> <pre><code>string[0]= "178.9"; // where it was stored 178.9 ....in position [0] </code></pre> <p>You can't have that. A char holds 1 character. That's it. A "string" in C is an array of characters followed by a sentinel character (NULL terminator).</p> <p>Now if you want to copy the first x characters out of <code>array</code> to <code>string</code> you can do that with <code>memcpy()</code>:</p> <pre><code>memcpy(string, array, x); string[x] = '\0'; </code></pre>
14,048,476
BigInteger to Hex/Decimal/Octal/Binary strings?
<p>In Java, I could do </p> <pre><code>BigInteger b = new BigInteger(500); </code></pre> <p>Then format it as I pleased</p> <pre><code>b.toString(2); //binary b.toString(8); //octal b.toString(10); //decimal b.toString(16); //hexadecimal </code></pre> <p>In C#, I can do</p> <pre><code>int num = int.Parse(b.ToString()); Convert.ToString(num,2) //binary Convert.ToString(num,8) //octal </code></pre> <p>etc. But I can only do it with <code>long</code> values and smaller. Is there some method to print a BigInteger with a specified base? I posted this, <a href="https://stackoverflow.com/questions/14040483/biginteger-parse-octal-string/14040916">BigInteger Parse Octal String?</a>, yesterday and received the solution of how to convert basically all strings to BigInteger values, but haven't had success outputting.</p>
15,447,131
4
3
null
2012-12-27 01:51:49.98 UTC
11
2022-07-17 04:28:43.903 UTC
2017-05-23 11:45:52.913 UTC
null
-1
null
928,007
null
1
14
c#|tostring|biginteger
24,314
<h1>Convert <code>BigInteger</code> to decimal, hex, binary, octal string:</h1> <p>Let's start with a <code>BigInteger</code> value:</p> <pre><code>BigInteger bigint = BigInteger.Parse("123456789012345678901234567890"); </code></pre> <h1>Base 10 and Base 16</h1> <p>The built-in Base 10 (decimal) and base 16 (hexadecimal) conversions are easy:</p> <pre><code>// Convert to base 10 (decimal): string base10 = bigint.ToString(); // Convert to base 16 (hexadecimal): string base16 = bigint.ToString("X"); </code></pre> <h2>Leading Zeros (positive vs. negative BigInteger values)</h2> <p>Take note, that <code>ToString("X")</code> ensures hexadecimal strings have a leading zero when the value of <code>BigInteger</code> is positive. This is unlike the usual behavior of <code>ToString("X")</code> when converting from other value types where leading zeros are suppressed.</p> <p>EXAMPLE:</p> <pre><code>var positiveBigInt = new BigInteger(128); var negativeBigInt = new BigInteger(-128); Console.WriteLine(positiveBigInt.ToString("X")); Console.WriteLine(negativeBigInt.ToString("X")); </code></pre> <p>RESULT:</p> <pre><code>080 80 </code></pre> <p>There is a purpose for this behavior as a leading zero indicates the <code>BigInteger</code> is a positive value--essentially, the leading zero provides the sign. This is necessary (as opposed to other value type conversions) because a <code>BigInteger</code> has no fixed size; therefore, there is no designated sign bit. The leading zero identifies a positive value, as opposed to a negative one. This allows for "round-tripping" <code>BigInteger</code> values out through <code>ToString()</code> and back in through <code>Parse()</code>. This behavior is discussed on the <a href="http://msdn.microsoft.com/library/dd268287" rel="noreferrer">BigInteger Structure</a> page on MSDN.</p> <h1>Extension methods: BigInteger to Binary, Hex, and Octal</h1> <p>Here is a class containing extension methods to convert <code>BigInteger</code> instances to binary, hexadecimal, and octal strings:</p> <pre><code>using System; using System.Numerics; using System.Text; /// &lt;summary&gt; /// Extension methods to convert &lt;see cref="System.Numerics.BigInteger"/&gt; /// instances to hexadecimal, octal, and binary strings. /// &lt;/summary&gt; public static class BigIntegerExtensions { /// &lt;summary&gt; /// Converts a &lt;see cref="BigInteger"/&gt; to a binary string. /// &lt;/summary&gt; /// &lt;param name="bigint"&gt;A &lt;see cref="BigInteger"/&gt;.&lt;/param&gt; /// &lt;returns&gt; /// A &lt;see cref="System.String"/&gt; containing a binary /// representation of the supplied &lt;see cref="BigInteger"/&gt;. /// &lt;/returns&gt; public static string ToBinaryString(this BigInteger bigint) { var bytes = bigint.ToByteArray(); var idx = bytes.Length - 1; // Create a StringBuilder having appropriate capacity. var base2 = new StringBuilder(bytes.Length * 8); // Convert first byte to binary. var binary = Convert.ToString(bytes[idx], 2); // Ensure leading zero exists if value is positive. if (binary[0] != '0' &amp;&amp; bigint.Sign == 1) { base2.Append('0'); } // Append binary string to StringBuilder. base2.Append(binary); // Convert remaining bytes adding leading zeros. for (idx--; idx &gt;= 0; idx--) { base2.Append(Convert.ToString(bytes[idx], 2).PadLeft(8, '0')); } return base2.ToString(); } /// &lt;summary&gt; /// Converts a &lt;see cref="BigInteger"/&gt; to a hexadecimal string. /// &lt;/summary&gt; /// &lt;param name="bigint"&gt;A &lt;see cref="BigInteger"/&gt;.&lt;/param&gt; /// &lt;returns&gt; /// A &lt;see cref="System.String"/&gt; containing a hexadecimal /// representation of the supplied &lt;see cref="BigInteger"/&gt;. /// &lt;/returns&gt; public static string ToHexadecimalString(this BigInteger bigint) { return bigint.ToString("X"); } /// &lt;summary&gt; /// Converts a &lt;see cref="BigInteger"/&gt; to a octal string. /// &lt;/summary&gt; /// &lt;param name="bigint"&gt;A &lt;see cref="BigInteger"/&gt;.&lt;/param&gt; /// &lt;returns&gt; /// A &lt;see cref="System.String"/&gt; containing an octal /// representation of the supplied &lt;see cref="BigInteger"/&gt;. /// &lt;/returns&gt; public static string ToOctalString(this BigInteger bigint) { var bytes = bigint.ToByteArray(); var idx = bytes.Length - 1; // Create a StringBuilder having appropriate capacity. var base8 = new StringBuilder(((bytes.Length / 3) + 1) * 8); // Calculate how many bytes are extra when byte array is split // into three-byte (24-bit) chunks. var extra = bytes.Length % 3; // If no bytes are extra, use three bytes for first chunk. if (extra == 0) { extra = 3; } // Convert first chunk (24-bits) to integer value. int int24 = 0; for (; extra != 0; extra--) { int24 &lt;&lt;= 8; int24 += bytes[idx--]; } // Convert 24-bit integer to octal without adding leading zeros. var octal = Convert.ToString(int24, 8); // Ensure leading zero exists if value is positive. if (octal[0] != '0' &amp;&amp; bigint.Sign == 1) { base8.Append('0'); } // Append first converted chunk to StringBuilder. base8.Append(octal); // Convert remaining 24-bit chunks, adding leading zeros. for (; idx &gt;= 0; idx -= 3) { int24 = (bytes[idx] &lt;&lt; 16) + (bytes[idx - 1] &lt;&lt; 8) + bytes[idx - 2]; base8.Append(Convert.ToString(int24, 8).PadLeft(8, '0')); } return base8.ToString(); } } </code></pre> <p>On first glance, these methods may seem more complex than necessary. A bit of extra complexity is, indeed, added to ensure the proper leading zeros are present in the converted strings.</p> <p>Let's examine each extension method to see how they work:</p> <h2>BigInteger.ToBinaryString()</h2> <p>Here is how to use this extension method to convert a <code>BigInteger</code> to a binary string:</p> <pre><code>// Convert BigInteger to binary string. bigint.ToBinaryString(); </code></pre> <p>The fundamental core of each of these extension methods is the <code>BigInteger.ToByteArray()</code> method. This method converts a <code>BigInteger</code> to a byte array, which is how we can get the binary representation of a <code>BigInteger</code> value:</p> <pre><code>var bytes = bigint.ToByteArray(); </code></pre> <p>Beware, though, the returned byte array is in little-endian order, so the first array element is the least-significant byte (LSB) of the <code>BigInteger</code>. Since a <code>StringBuilder</code> is used to build the output string--which starts at the most-significant digit (MSB)--<strong>the byte array must be iterated in reverse</strong> so that the most-significant byte is converted first.</p> <p>Thus, an index pointer is set to the most significant digit (the last element) in the byte array:</p> <pre><code>var idx = bytes.Length - 1; </code></pre> <p>To capture the converted bytes, a <code>StringBuilder</code> is created:</p> <pre><code>var base2 = new StringBuilder(bytes.Length * 8); </code></pre> <p>The <code>StringBuilder</code> constructor takes the capacity for the <code>StringBuilder</code>. The capacity needed for the <code>StringBuilder</code> is calculated by taking the number of bytes to convert multiplied by eight (eight binary digits result from each byte converted).</p> <p>The first byte is then converted to a binary string:</p> <pre><code>var binary = Convert.ToString(bytes[idx], 2); </code></pre> <p>At this point, it is necessary to ensure that a leading zero exists if the <code>BigInteger</code> is a positive value (see discussion above). If the first converted digit is not a zero, and <code>bigint</code> is positive, then a <code>'0'</code> is appended to the <code>StringBuilder</code>:</p> <pre><code>// Ensure leading zero exists if value is positive. if (binary[0] != '0' &amp;&amp; bigint.Sign == 1) { base2.Append('0'); } </code></pre> <p>Next, the converted byte is appended to the <code>StringBuilder</code>:</p> <pre><code>base2.Append(binary); </code></pre> <p>To convert the remaining bytes, a loop iterates the remainder of the byte array in reverse order:</p> <pre><code>for (idx--; idx &gt;= 0; idx--) { base16.Append(Convert.ToString(bytes[idx], 2).PadLeft(8, '0')); } </code></pre> <p>Notice that each converted byte is padded on the left with zeros ('0'), as necessary, so that the converted string is eight binary characters. This is extremely important. Without this padding, the hexadecimal value '101' would be converted to a binary value of '11'. The leading zeros ensure the conversion is '100000001'.</p> <p>When all bytes are converted, the <code>StringBuilder</code> contains the complete binary string, which is returned by the extension method:</p> <pre><code>return base2.ToString(); </code></pre> <h2>BigInteger.ToOctalString</h2> <p>Converting a <code>BigInteger</code> to an octal (base 8) string is more complicated. The problem is octal digits represent three bits which is not an even multiple of the eight bits held in each element of the byte array created by <code>BigInteger.ToByteArray()</code>. To solve this problem, three bytes from the array are combined into chunks of 24-bits. Each 24-bit chunk evenly converts to eight octal characters.</p> <p>The first 24-bit chunk requires some modulo math:</p> <pre><code>var extra = bytes.Length % 3; </code></pre> <p>This calculation determines how many bytes are "extra" when the entire byte array is split into three-byte (24-bit) chunks. The first conversion to octal (the most-significant digits) gets the "extra" bytes so that all remaining conversions will get three bytes each.</p> <p>If there are no "extra" bytes, then the first chunk gets a full three bytes:</p> <pre><code>if (extra == 0) { extra = 3; } </code></pre> <p>The first chunk is loaded into an integer variable called <code>int24</code> that holds up to 24-bits. Each byte of the chunk is loaded. As additional bytes are loaded, the previous bits in <code>int24</code> are left-shifted by 8-bits to make room:</p> <pre><code>int int24 = 0; for (; extra != 0; extra--) { int24 &lt;&lt;= 8; int24 += bytes[idx--]; } </code></pre> <p>Conversion of a 24-bit chunk to octal is accomplished by:</p> <pre><code>var octal = Convert.ToString(int24, 8); </code></pre> <p>Again, the first digit must be a leading zero if the <code>BigInteger</code> is a positive value:</p> <pre><code>// Ensure leading zero exists if value is positive. if (octal[0] != '0' &amp;&amp; bigint.Sign == 1) { base8.Append('0'); } </code></pre> <p>The first converted chunk is appended to the <code>StringBuilder</code>:</p> <pre><code>base8.Append(octal); </code></pre> <p>The remaining 24-bit chunks are converted in a loop:</p> <pre><code>for (; idx &gt;= 0; idx -= 3) { int24 = (bytes[idx] &lt;&lt; 16) + (bytes[idx -1] &lt;&lt; 8) + bytes[idx - 2]; base8.Append(Convert.ToString(int24, 8).PadLeft(8, '0')); } </code></pre> <p>Like the binary conversion, each converted octal string is left-padded with zeros so that '7' becomes '00000007'. This ensures that zeros won't be dropped from the middle of converted strings (i.e., '17' instead of '100000007').</p> <h2>Conversion to Base x?</h2> <p>Converting a <code>BigInteger</code> to other number bases could be far more complicated. As long as the number base is a power of two (i.e., 2, 4, 8, 16) the byte array created by <code>BigInteger.ToByteArray()</code> can be appropriately split into chunks of bits and converted.</p> <p>However, if the number base is not a power of two, the problem becomes much more complicated and requires a good deal of looping and division. As such number base conversions are rare, I have only covered the popular computing number bases here.</p>
13,833,568
Automated way to convert XML files to SQL database?
<p>We have a bunch of XML files, following a schema which is essentially a serialised database form:</p> <pre><code>&lt;table1&gt; &lt;column1&gt;value&lt;/column1&gt; &lt;column2&gt;value&lt;/column2&gt; &lt;/table1&gt; &lt;table1&gt; &lt;column1&gt;another value&lt;/column1&gt; &lt;column2&gt;another value&lt;/column2&gt; &lt;/table1&gt; ... </code></pre> <p>Is there a really easy way to turn that into an SQL database? Obviously I can manually construct the schema, identify all tables, fields etc, and then write a script to import it. I just wonder if there are any tools that could automate some or all of that process?</p>
13,837,311
4
2
null
2012-12-12 05:45:22.34 UTC
5
2016-03-31 18:31:06.173 UTC
2012-12-12 06:31:39.47 UTC
null
13,302
null
263,268
null
1
19
mysql|xml|postgresql|schema
105,312
<p>For Mysql please see the <a href="https://dev.mysql.com/doc/refman/5.5/en/load-xml.html" rel="noreferrer"><code>LOAD XML</code> Syntax<sup><em>Docs</em></sup></a>.</p> <p>It should work without any additional XML transformation for the XML you've provided, just specify the format and define the table inside the database firsthand with matching column names:</p> <pre><code>LOAD XML LOCAL INFILE 'table1.xml' INTO TABLE table1 ROWS IDENTIFIED BY '&lt;table1&gt;'; </code></pre> <p>There is also a related question:</p> <ul> <li><a href="https://stackoverflow.com/q/5491056/367456">How to import XMl file into MySQL database table using XML_LOAD(); function</a></li> </ul> <p>For Postgresql I do not know.</p>
14,341,782
Cross database querying in EF
<p>Is there any way to implement cross database querying in Entity Framework? Let's imagine I've two Entities User and Post, User entity is in database1 and Post is in database2, which means those entities are in separate databases. How should I get user's posts in Entity Framework ?</p>
14,341,872
4
2
null
2013-01-15 16:05:34.513 UTC
10
2019-08-22 14:53:16.753 UTC
2018-01-27 06:03:57.643 UTC
null
560,153
null
560,153
null
1
23
c#|sql-server|entity-framework|cross-database
16,179
<p>EF context does not support cross database queries. You need to expose posts in database1 through SQL View (<a href="http://rachel53461.wordpress.com/2011/05/22/tricking-ef-to-span-multiple-databases/" rel="noreferrer">or synonym</a>) and use it as part of that database. </p>
13,931,225
How to zoom div content using jquery?
<p>I have a parent <code>&lt;div&gt;</code>. Inside that I place some text and images. Now I need to zoom to a particular portion of that parent <code>&lt;div&gt;</code>. Is it possible?</p>
13,931,548
4
6
null
2012-12-18 10:44:14.98 UTC
19
2016-05-26 14:18:00.367 UTC
2012-12-18 10:50:14.813 UTC
null
796,584
null
1,314,503
null
1
26
javascript|jquery|html
110,435
<p>If you want that image to be zoomed on mouse hover :</p> <pre><code>$(document).ready( function() { $('#div img').hover( function() { $(this).animate({ 'zoom': 1.2 }, 400); }, function() { $(this).animate({ 'zoom': 1 }, 400); }); }); </code></pre> <p>​or you may do like this if zoom in and out buttons are used :</p> <pre><code>$("#ZoomIn").click(ZoomIn()); $("#ZoomOut").click(ZoomOut()); function ZoomIn (event) { $("#div img").width( $("#div img").width() * 1.2 ); $("#div img").height( $("#div img").height() * 1.2 ); }, function ZoomOut (event) { $("#div img").width( $("#imgDtls").width() * 0.5 ); $("#div img").height( $("#div img").height() * 0.5 ); } </code></pre>
14,245,474
Apache won't run in xampp
<p>I have just installed XAMPP and everything works fine except that I can't get apache to run. It seems that port 80 is the problem, I have disabled Skype to use port 80 but it doesn't seem to fix it. I read somewhere that the SSL port can be the problem and should be changed. But I cant figure out were the port is or how to change it.</p> <pre><code>"Check the "/xampp/apache/logs/error.log" file" </code></pre> <p>I have tried to check this file but inside "logs" there isn't anything. From apache I can go to error but there is not any recently changed documents. </p> <p>The error:</p> <pre><code>20:34:24 [Apache] Problem detected! 20:34:24 [Apache] Port 80 in use by "system"! 20:34:24 [Apache] Apache WILL NOT start without the configured ports free! 20:34:24 [Apache] You need to uninstall/disable/reconfigure the blocking application 20:34:24 [Apache] or reconfigure Apache to listen on a different port 20:40:50 [Apache] Attempting to start Apache app... 20:40:50 [Apache] Status change detected: running 20:40:51 [Apache] Status change detected: stopped 20:40:51 [Apache] Error: Apache shutdown unexpectedly. 20:40:51 [Apache] This may be due to a blocked port, missing dependencies, 20:40:51 [Apache] improper privileges, a crash, or a shutdown by another method. 20:40:51 [Apache] Check the "/xampp/apache/logs/error.log" file 20:40:51 [Apache] and the Windows Event Viewer for more clues </code></pre> <p>How to I fix these errors?</p>
14,245,577
17
2
null
2013-01-09 20:02:33.003 UTC
19
2018-07-09 10:05:48.57 UTC
2013-07-27 16:54:06.12 UTC
null
445,131
null
1,740,712
null
1
29
apache|xampp|port
218,797
<p>Find out which other service uses port 80.</p> <p>I have heard skype uses port 80. Check it there isn't another server or database running in the background on port 80.</p> <p>Two good alternatives to xampp are <a href="http://www.wampserver.com/en/">wamp</a> and <a href="http://www.easyphp.org/">easyphp</a>. Out of that, wamp is the most user friendly and it also has a built in tool for checking if port 80 is in use and which service is currently using it.</p> <p>Or disable iis. It has been known to use port 80 by default.</p>
13,892,191
Are empty macro definitions allowed in C? How do they behave?
<p>Suppose the "empty" macro definition</p> <pre><code>#define FOO </code></pre> <p>Is it valid Standard C? If so, what is <code>FOO</code> after this definition?</p>
13,892,207
3
2
null
2012-12-15 12:29:26.727 UTC
14
2017-06-28 07:34:03.543 UTC
2017-06-28 07:34:03.543 UTC
null
1,025,391
user1150105
null
null
1
60
c|c-preprocessor
38,473
<p>It is simply a macro that expands to, well, nothing. However, now that the macro has been defined you can check with <code>#if defined</code> (or <code>#ifdef</code>) whether it has been defined.</p> <pre><code>#define FOO int main(){ FOO FOO FOO printf("Hello world"); } </code></pre> <p>will expand to </p> <pre><code>int main(){ printf("Hello world"); } </code></pre> <p>There are certain situations where this comes in very handy, for example additional debug information, which you don't want to show in your release version:</p> <pre><code>/* Defined only during debug compilations: */ #define CONFIG_USE_DEBUG_MESSAGES #ifdef CONFIG_USE_DEBUG_MESSAGES #define DEBUG_MSG(x) print(x) #else #define DEBUG_MSG(x) do {} while(0) #endif int main(){ DEBUG_MSG("Entering main"); /* ... */ } </code></pre> <p>Since the macro <code>CONFIG_USE_DEBUG_MESSAGES</code> has been defined, <code>DEBUG_MSG(x)</code> will expand to <code>print(x)</code> and you will get <code>Entering main</code>. If you remove the <code>#define</code>, <code>DEBUG_MSG(x)</code> expands to an empty <code>do</code>-<code>while</code> loop and you won't see the message.</p>
14,149,209
Read the version from manifest.json
<p>Is there a way for a Chrome extension to read properties from <code>manifest.json</code>? I'd like to be able to read the version number and use it in the extension.</p>
14,348,395
5
2
null
2013-01-03 23:56:54.057 UTC
3
2020-02-08 18:42:42.71 UTC
2020-02-08 18:42:42.71 UTC
null
555,121
null
64,421
null
1
61
google-chrome-extension
19,567
<p>You can just use <code>chrome.runtime.getManifest()</code> to access the manifest data - you don't need to GET it and parse it.</p> <pre><code>var manifestData = chrome.runtime.getManifest(); console.log(manifestData.version); console.log(manifestData.default_locale); </code></pre>
29,994,402
Is there a way to throw custom exception without Exception class
<p>Is there any way in C# (i.e. in .NET) to throw a custom exception but without writing all the code to define your own exception class derived from <code>Exception</code>?</p> <p>I am thinking something similar you have for example in Oracle PL/SQL where you can simply write</p> <pre><code>raise_application_error(-20001, 'An arbitary error message'); </code></pre> <p>at any place.</p>
29,994,439
5
5
null
2015-05-01 20:13:12.623 UTC
8
2018-09-25 14:27:06.21 UTC
2015-05-01 20:31:51.663 UTC
null
1,664,443
null
3,027,266
null
1
43
c#|asp.net|exception
94,348
<pre><code>throw new Exception("A custom message for an application specific exception"); </code></pre> <p>Not good enough?</p> <p>You could also throw a more specific exception if it's relevant. For example,</p> <pre><code>throw new AuthenticationException("Message here"); </code></pre> <p>or</p> <pre><code>throw new FileNotFoundException("I couldn't find your file!"); </code></pre> <p>could work.</p> <p>Note that you should probably <strong>not</strong> <code>throw new ApplicationException()</code>, per <a href="https://msdn.microsoft.com/en-us/library/system.applicationexception%28v=vs.110%29.aspx" rel="noreferrer">MSDN</a>. </p> <p>The major draw back of not customizing Exception is that it will be more difficult for callers to catch - they won't know if this was a general exception or one that's specific to your code without doing some funky inspection on the exception.Message property. You could do something as simple as this:</p> <pre><code>public class MyException : Exception { MyException(int severity, string message) : base(message) { // do whatever you want with severity } } </code></pre> <p>to avoid that.</p> <p><strong>Update</strong>: Visual Studio 2015 now offers some automatic implementation of Exception extension classes - if you open the <em>Quick Actions and Refactoring Menu</em> with the cursor on the <code>: Exception</code>, just tell it to "Generate All Constructors".</p>
9,335,169
Understanding strange Java hash function
<p>Following is the source code for a hash function in <code>java.util.HashMap</code>. The comments explain well enough what it's accomplishing. <strong>but how?</strong> What are the <code>^</code> and <code>&gt;&gt;&gt;</code> operators doing? <strong>Can someone explain how the code actually <em>does</em> what the comments <em>say</em>?</strong></p> <pre><code>/** * Applies a supplemental hash function to a given hashCode, which * defends against poor quality hash functions. This is critical * because HashMap uses power-of-two length hash tables, that * otherwise encounter collisions for hashCodes that do not differ * in lower bits. Note: Null keys always map to hash 0, thus index 0. */ static int hash(int h) { // This function ensures that hashCodes that differ only by // constant multiples at each bit position have a bounded // number of collisions (approximately 8 at default load factor). h ^= (h &gt;&gt;&gt; 20) ^ (h &gt;&gt;&gt; 12); return h ^ (h &gt;&gt;&gt; 7) ^ (h &gt;&gt;&gt; 4); } </code></pre>
9,336,515
6
1
null
2012-02-17 20:47:13.113 UTC
25
2021-02-19 22:02:38.833 UTC
2012-12-08 20:57:18.577 UTC
null
815,724
null
835,805
null
1
34
java|hash
8,413
<p>Here is some code and the sample output:</p> <pre><code>public static void main ( String[] args ) { int h = 0xffffffff; int h1 = h &gt;&gt;&gt; 20; int h2 = h &gt;&gt;&gt; 12; int h3 = h1 ^ h2; int h4 = h ^ h3; int h5 = h4 &gt;&gt;&gt; 7; int h6 = h4 &gt;&gt;&gt; 4; int h7 = h5 ^ h6; int h8 = h4 ^ h7; printBin ( h ); printBin ( h1 ); printBin ( h2 ); printBin ( h3 ); printBin ( h4 ); printBin ( h5 ); printBin ( h6 ); printBin ( h7 ); printBin ( h8 ); } static void printBin ( int h ) { System.out.println ( String.format ( &quot;%32s&quot;, Integer.toBinaryString ( h ) ).replace ( ' ', '0' ) ); } </code></pre> <p>Which prints:</p> <pre><code>11111111111111111111111111111111 00000000000000000000111111111111 00000000000011111111111111111111 00000000000011111111000000000000 11111111111100000000111111111111 00000001111111111110000000011111 00001111111111110000000011111111 00001110000000001110000011100000 11110001111100001110111100011111 </code></pre> <p>So, the code breaks down the hash function into steps so that you can see what is happening. The first shift of 20 positions xor with the second shift of 12 positions creates a mask that can flip 0 or more of the bottom 20 bits of the int. So you can get some randomness inserted into the bottom bits that makes use of the potentially better distributed higher bits. This is then applied via xor to the original value to add that randomness to the lower bits. The second shift of 7 positions xor the shift of 4 positions creates a mask that can flip 0 or more of the bottom 28 bits, which brings some randomness again to the lower bits and to some of the more significant ones by capitalizing on the prior xor which already addressed some of the distribution at the lower bits. The end result is a smoother distribution of bits through the hash value.</p> <p>Since the hashmap in java computes the bucket index by combining the hash with the number of buckets you need to have an even distribution of the lower bits of the hash value to spread the entries evenly into each bucket.</p> <p>As to proving the statement that this bounds the number of collisions, that one I don't have any input on. Also, see <a href="http://www.javamex.com/tutorials/collections/hash_function_guidelines.shtml" rel="nofollow noreferrer">here</a> for some good information on building hash functions and a few details on why the xor of two numbers tends towards random distribution of bits in the result.</p>
24,652,964
android popup menu text color (AppCompat)
<p>I need to change text color of a popuo menu but I don't find any way for do this, I can change background of popmenu but not the text, I edit the style.xml in this way:</p> <pre><code>&lt;style name="AppBaseTheme" parent="Theme.AppCompat.Light"&gt; &lt;!-- API 14 theme customizations can go here. --&gt; &lt;item name="popupMenuStyle"&gt;@style/MyPopupMenu&lt;/item&gt; &lt;item name="android:textAppearanceLargePopupMenu"&gt;@style/myPopupMenuTextAppearanceLarge&lt;/item&gt; &lt;item name="android:textAppearanceSmallPopupMenu"&gt;@style/myPopupMenuTextAppearanceSmall&lt;/item&gt; &lt;/style&gt; &lt;style name="MyPopupMenu" parent="@style/Widget.AppCompat.PopupMenu"&gt; &lt;item name="android:popupBackground"&gt;#0F213F&lt;/item&gt; &lt;/style&gt; &lt;style name="myPopupMenuTextAppearanceSmall" parent="@style/TextAppearance.AppCompat.Base.Widget.PopupMenu.Small"&gt; &lt;item name="android:textColor"&gt;#ffffff&lt;/item&gt; &lt;/style&gt; &lt;style name="myPopupMenuTextAppearanceLarge" parent="@style/TextAppearance.AppCompat.Base.Widget.PopupMenu.Large"&gt; &lt;item name="android:textColor"&gt;#ffffff&lt;/item&gt; &lt;/style&gt; </code></pre> <p>where is the mistake?</p>
24,653,532
4
3
null
2014-07-09 11:52:09.517 UTC
2
2018-10-27 07:52:16.987 UTC
2014-10-10 20:57:36.83 UTC
null
2,653,775
null
764,133
null
1
34
android|colors|popupmenu
36,313
<pre><code>&lt;item name="textAppearanceLargePopupMenu"&gt;@style/TextAppearance.AppCompat.Light.Widget.PopupMenu.Large&lt;/item&gt; &lt;item name="textAppearanceSmallPopupMenu"&gt;@style/TextAppearance.AppCompat.Light.Widget.PopupMenu.Small&lt;/item&gt; </code></pre> <p>I think that you are using TextAppearance.AppCompat.Base.Widget.PopupMenu. Here is the error, you are using another parent that doesn´t response the current style.</p> <p>You have to use: </p> <p>TextAppearance.AppCompat.Light.Widget.PopupMenu.</p>
1,236,285
How do I see stdout when running Django tests?
<p>When I run tests with <code>./manage.py test</code>, whatever I send to the standard output through <code>print</code> doesn't show. When tests fail, I see an "stdout" block per failed test, so I guess Django traps it (but doesn't show it when tests pass).</p>
1,239,545
5
2
null
2009-08-05 23:34:08.85 UTC
8
2020-10-12 13:46:24.777 UTC
2009-08-06 15:07:07.707 UTC
null
105,132
null
105,132
null
1
55
python|django|debugging|testing|stdout
35,250
<p>Checked <code>TEST_RUNNER</code> in <code>settings.py</code>, it's using a project-specific runner that calls out to Nose. <em>Nose has the <code>-s</code> option to stop it from capturing <code>stdout</code></em>, but if I run:</p> <p><code>./manage.py test -s</code></p> <p><code>manage.py</code> captures it first and throws a "no such option" error. The help for <code>manage.py</code> doesn't mention this, but I found that if I run:</p> <p><code>./manage.py test -- -s</code></p> <p>it ignores the <code>-s</code> and lets me capture it on the custom runner's side, passing it to Nose without a problem.</p>
243,363
Can someone explain the structure of a Pid (Process Identifier) in Erlang?
<p>Can someone explain the structure of a Pid in Erlang?</p> <p>Pids looks like this: <code>&lt;A.B.C&gt;</code>, e.g. <code>&lt;0.30.0&gt;</code> , but I would like to know what is the meaning of these three &quot;bits&quot;: <code>A</code>, <code>B</code> and <code>C</code>.</p> <p><code>A</code> seems to be always <code>0</code> on a local node, but this value changes when the Pid's owner is located on another node.</p> <p>Is it possible to directly send a message on a remote node using only the Pid? Something like that: <code>&lt;4568.30.0&gt; ! Message</code>, without having to explicitly specify the name of the registered process and the node name (<code> {proc_name, Node} ! Message</code>)?</p>
262,179
5
1
2008-10-28 13:42:21.24 UTC
2008-10-28 13:42:21.24 UTC
32
2021-01-31 11:03:40.18 UTC
2021-01-31 11:03:40.18 UTC
null
11,880,324
jideel
15,539
null
1
74
erlang|pid
24,350
<p>Printed process ids &lt; A.B.C > are composed of <a href="http://github.com/mfoemmel/erlang-otp/blob/R13B/erts/emulator/beam/erl_term.h#L502" rel="noreferrer">6</a>:</p> <ul> <li>A, the node number (0 is the local node, an arbitrary number for a remote node) </li> <li>B, the first 15 bits of the process number (an index into the process table) <a href="http://github.com/mfoemmel/erlang-otp/blob/R13B/erts/emulator/beam/erl_term.h#L534" rel="noreferrer">7</a></li> <li>C, bits 16-18 of the process number (the same process number as B) <a href="http://github.com/mfoemmel/erlang-otp/blob/R13B/erts/emulator/beam/erl_term.h#L534" rel="noreferrer">7</a></li> </ul> <p>Internally, the process number is 28 bits wide on the 32 bit emulator. The odd definition of B and C comes from R9B and earlier versions of Erlang in which B was a 15bit process ID and C was a wrap counter incremented when the max process ID was reached and lower IDs were reused.</p> <p>In the erlang distribution PIDs are a little larger as they include the node atom as well as the other information. (<a href="http://erlang.org/doc/apps/erts/erl_ext_dist.html#8.8" rel="noreferrer">Distributed PID format</a>)</p> <p>When an internal PID is sent from one node to the other, it's automatically converted to the external/distributed PID form, so what might be <code>&lt;0.10.0&gt;</code> (<code>inet_db</code>) on one node might end up as <code>&lt;2265.10.0&gt;</code> when sent to another node. You can just send to these PIDs as normal.</p> <pre><code>% get the PID of the user server on OtherNode RemoteUser = rpc:call(OtherNode, erlang,whereis,[user]), true = is_pid(RemoteUser), % send message to remote PID RemoteUser ! ignore_this, % print "Hello from &lt;nodename&gt;\n" on the remote node's console. io:format(RemoteUser, "Hello from ~p~n", [node()]). </code></pre> <p>For more information see: <a href="http://github.com/mfoemmel/erlang-otp/tree/5b6dd0e84cf0f1dc19ddd05f86cf04b2695d8a9e/erts/emulator/beam/erl_term.h#L498" rel="noreferrer">Internal PID structure</a>, <a href="http://github.com/mfoemmel/erlang-otp/tree/5b6dd0e84cf0f1dc19ddd05f86cf04b2695d8a9e/erts/emulator/beam/erl_node_container_utils.h#L24" rel="noreferrer">Node creation information</a>, <a href="http://erlang.2086793.n4.nabble.com/PID-recycling-td2108252.html#a2108255" rel="noreferrer">Node creation counter interaction with EPMD</a></p>
450,915
Upload files to Sharepoint document libraries via FTP
<p>I was wondering if anyone knows how to or if it is possible to upload files to a sharepoint (v3/MOSS) document library over FTP. I know it is possible with webdav. If it is possible is this even supported by Microsoft?</p>
450,930
6
0
null
2009-01-16 16:06:16.167 UTC
5
2020-10-18 23:01:20.63 UTC
null
null
null
Andrew Milsark
26,540
null
1
8
sharepoint|upload|ftp
69,662
<p>I don't think so. I think your options are: </p> <ol> <li>HTTP (via the upload page)</li> <li>WebDAV</li> <li>Web Services</li> <li>The object model</li> </ol>
124,958
glob() - sort array of files by last modified datetime stamp
<p>I'm trying to display an array of files in order of date (last modified).</p> <p>I have done this buy looping through the array and sorting it into another array, but is there an easier (more efficient) way to do this?</p>
125,047
6
1
null
2008-09-24 01:51:54.23 UTC
17
2021-12-16 10:34:11.543 UTC
2020-10-12 00:38:45.95 UTC
null
2,943,403
cole
910
null
1
61
php|arrays|sorting|filemtime
46,850
<blockquote> <p><strong>Warning</strong> <code>create_function()</code> has been DEPRECATED as of PHP 7.2.0. Relying on this function is highly discouraged.</p> </blockquote> <p>For the sake of posterity, in case the forum post linked in the accepted answer is lost or unclear to some, the relevant code needed is: </p> <pre><code>&lt;?php $myarray = glob("*.*"); usort($myarray, create_function('$a,$b', 'return filemtime($a) - filemtime($b);')); ?&gt; </code></pre> <p>Tested this on my system and verified it does sort by file mtime as desired. I used a similar approach (written in Python) for determining the last updated files on my website as well.</p>
676,250
Different ways of loading a file as an InputStream
<p>What's the difference between:</p> <pre><code>InputStream is = this.getClass().getClassLoader().getResourceAsStream(fileName) </code></pre> <p>and</p> <pre><code>InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName) </code></pre> <p>and</p> <pre><code>InputStream is = this.getClass().getResourceAsStream(fileName) </code></pre> <p>When are each one more appropriate to use than the others?</p> <p>The file that I want to read is in the classpath as my class that reads the file. My class and the file are in the same jar and packaged up in an EAR file, and deployed in WebSphere 6.1.</p>
676,273
6
0
null
2009-03-24 05:32:43.56 UTC
132
2020-08-26 09:30:49.753 UTC
2012-02-02 12:13:25.01 UTC
Dheer
251,173
zqudlyba
81,810
null
1
235
java|inputstream
215,433
<p>There are subtle differences as to how the <code>fileName</code> you are passing is interpreted. Basically, you have 2 different methods: <code>ClassLoader.getResourceAsStream()</code> and <code>Class.getResourceAsStream()</code>. These two methods will locate the resource differently.</p> <p>In <code>Class.getResourceAsStream(path)</code>, the path is interpreted as a path local to the package of the class you are calling it from. For example calling, <code>String.class.getResourceAsStream(&quot;myfile.txt&quot;)</code> will look for a file in your classpath at the following location: <code>&quot;java/lang/myfile.txt&quot;</code>. If your path starts with a <code>/</code>, then it will be considered an absolute path, and will start searching from the root of the classpath. So calling <code>String.class.getResourceAsStream(&quot;/myfile.txt&quot;)</code> will look at the following location in your class path <code>./myfile.txt</code>.</p> <p><code>ClassLoader.getResourceAsStream(path)</code> will consider all paths to be absolute paths. So calling <code>String.class.getClassLoader().getResourceAsStream(&quot;myfile.txt&quot;)</code> and <code>String.class.getClassLoader().getResourceAsStream(&quot;/myfile.txt&quot;)</code> will both look for a file in your classpath at the following location: <code>./myfile.txt</code>.</p> <p>Everytime I mention a location in this post, it could be a location in your filesystem itself, or inside the corresponding jar file, depending on the Class and/or ClassLoader you are loading the resource from.</p> <p>In your case, you are loading the class from an Application Server, so your should use <code>Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName)</code> instead of <code>this.getClass().getClassLoader().getResourceAsStream(fileName)</code>. <code>this.getClass().getResourceAsStream()</code> will also work.</p> <p>Read <a href="http://www.javaworld.com/javaworld/javaqa/2003-08/01-qa-0808-property.html" rel="noreferrer">this article</a> for more detailed information about that particular problem.</p> <hr /> <h2>Warning for users of Tomcat 7 and below</h2> <p>One of the answers to this question states that my explanation seems to be incorrect for Tomcat 7. I've tried to look around to see why that would be the case.</p> <p>So I've looked at the source code of Tomcat's <code>WebAppClassLoader</code> for several versions of Tomcat. The implementation of <code>findResource(String name)</code> (which is utimately responsible for producing the URL to the requested resource) is virtually identical in Tomcat 6 and Tomcat 7, but is different in Tomcat 8.</p> <p>In versions 6 and 7, the implementation does not attempt to normalize the resource name. This means that in these versions, <code>classLoader.getResourceAsStream(&quot;/resource.txt&quot;)</code> may not produce the same result as <code>classLoader.getResourceAsStream(&quot;resource.txt&quot;)</code> event though it should (since that what the Javadoc specifies). <a href="https://github.com/apache/tomcat/blob/7.0.96/java/org/apache/catalina/loader/WebappClassLoaderBase.java" rel="noreferrer">[source code]</a></p> <p>In version 8 though, the resource name is normalized to guarantee that the absolute version of the resource name is the one that is used. Therefore, in Tomcat 8, the two calls described above should always return the same result. <a href="https://github.com/apache/tomcat/blob/8.5.45/java/org/apache/catalina/loader/WebappClassLoaderBase.java" rel="noreferrer">[source code]</a></p> <p>As a result, you have to be extra careful when using <code>ClassLoader.getResourceAsStream()</code> or <code>Class.getResourceAsStream()</code> on Tomcat versions earlier than 8. And you must also keep in mind that <code>class.getResourceAsStream(&quot;/resource.txt&quot;)</code> actually calls <code>classLoader.getResourceAsStream(&quot;resource.txt&quot;)</code> (the leading <code>/</code> is stripped).</p>
13,290,841
NSOperationQueue and background support
<p>I have some problems on elaborating a useful strategy to support background for <code>NSOperationQueue</code> class. In particular, I have a bunch of <code>NSOperation</code>s that perform the following actions:</p> <ul> <li>Download a file from the web</li> <li>Parse the file</li> <li>Import data file in Core Data</li> </ul> <p>The operations are inserted into a serial queue. Once an operation completes, the next can start.</p> <p>I need to stop (or continue) the operations when the app enters the background. From these discussions ( <a href="https://stackoverflow.com/questions/7800614/does-afnetworking-have-backgrounding-support">Does AFNetworking have backgrounding support?</a> and <a href="https://stackoverflow.com/questions/1566230/queue-of-nsoperations-and-handling-application-exit">Queue of NSOperations and handling application exit</a> ) I see the best way is to cancel the operations and the use the <code>isCancelled</code> property within each operation. Then, checking the key point of an operation against that property, it allows to roll back the state of the execution (of the running operation) when the app enters background.</p> <p>Based on Apple template that highlights background support, how can I manage a similar situation? Can I simply cancel the operations or wait the current operation is completed? See comments for details.</p> <pre><code>- (void)applicationDidEnterBackground:(UIApplication *)application { bgTask = [application beginBackgroundTaskWithExpirationHandler:^{ // Do I have to call -cancelAllOperations or // -waitUntilAllOperationsAreFinished or both? [application endBackgroundTask:bgTask]; bgTask = UIBackgroundTaskInvalid; }]; // Start the long-running task and return immediately. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ // What about here? [application endBackgroundTask:bgTask]; bgTask = UIBackgroundTaskInvalid; }); } </code></pre> <p>Thank you in advance.</p> <p><strong>Edit</strong></p> <p>If <code>NSOperation</code> <code>main</code> method perform the code below, how is it possible to follow the <em>Responding to Cancellation Events</em> pattern?</p> <pre><code>- (void)main { // 1- download // 2- parse // 2.1 read file location // 2.2 load into memory // 3- import // 3.1 fetch core data request // 3.2 if data is not present, insert it (or update) // 3.3 save data into persistent store coordinator } </code></pre> <p>Each method I described contains various steps (non atomic operations, except the download one). So, a cancellation could happen within each of these step (in a not predefined manner). Could I check the <code>isCancelled</code> property before each step? Does this work?</p> <p><strong>Edit 2 based on Tammo Freese' edit</strong></p> <p>I understand what do you mean with your edit code. But the thing I'm worried is the following. A cancel request (the user can press the home button) can happen at any point within the <code>main</code> execution, so, if I simply return, the state of the operation would be corrupted. Do I need to clean its state before returning? What do you think?</p> <p>The problem I described could happen when I use sync operations (operations that are performed in a sync fashion within the same thread they run). For example, if the <code>main</code> is downloading a file (the download is performed through <code>+sendSynchronousRequest:returningResponse:error</code>) and the app is put in background, what could it happen? How to manage such a situation?</p> <pre><code>// download if ([self isCancelled]) return; // downloading here &lt;-- here the app is put in background </code></pre> <p>Obviously, I think that when the app is then put in foreground, the operation is run again since it has been cancelled. In other words, it is forced to not maintain its state. Am I wrong?</p>
13,346,407
1
0
null
2012-11-08 14:22:27.077 UTC
8
2014-04-08 17:17:30.19 UTC
2017-05-23 12:32:52.993 UTC
null
-1
null
231,684
null
1
4
ios|background|nsoperation|nsoperationqueue
8,122
<p>If I understand you correctly, you have a <code>NSOperationQueue</code> and if your application enters the background, you would like to </p> <ol> <li>cancel all operations and </li> <li>wait until the cancellations are processed.</li> </ol> <p>Normally this should not take too much time, so it should be sufficient to do this:</p> <pre><code>- (void)applicationDidEnterBackground:(UIApplication *)application { [_queue cancelAllOperations]; [_queue waitUntilAllOperationsAreFinished]; } </code></pre> <p>The definition of "too much time" here is approximately five seconds: If you block <code>-applicationDidEnterBackground:</code> longer than that, your app will be terminated and purged from memory.</p> <p>Let's say that finishing the cancelled operations takes longer than 5 seconds. Then you have to do the waiting in the background (see the comments for explanations): </p> <pre><code>- (void)applicationDidEnterBackground:(UIApplication *)application { bgTask = [application beginBackgroundTaskWithExpirationHandler:^{ // If this block is called, our background time of normally 10 minutes // is almost exceeded. That would mean one of the cancelled operations // is not finished even 10 minutes after cancellation (!). // This should not happen. // What we do anyway is tell iOS that our background task has ended, // as otherwise our app will be killed instead of suspended. [application endBackgroundTask:bgTask]; bgTask = UIBackgroundTaskInvalid; }]; // Normally this one is fast, so we do it outside the asynchronous block. [_queue cancelAllOperations]; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ // Wait until all the cancelled operations are finished. [_queue waitUntilAllOperationsAreFinished]; // Dispatch to the main queue if bgTask is not atomic dispatch_async(dispatch_get_main_queue(), ^{ [application endBackgroundTask:bgTask]; bgTask = UIBackgroundTaskInvalid; }); }); } </code></pre> <p>So basically we tell iOS that we need some time to perform a task, and when the task is finished of the time runs out, we tell iOS that our task has ended.</p> <p><strong>Edit</strong></p> <p>To answer the question in your edit: To respond to cancellation, just check for cancellation whenever you can, and return from the <code>-main</code> method. A cancelled operation is not immediately finished, but it is finished when <code>-main</code> returns.</p> <pre><code>- (void)main { // 1- download if ([self isCancelled]) return; // 2- parse // 2.1 read file location // 2.2 load into memory while (![self isCancelled] &amp;&amp; [self hasNextLineToParse]) { // ... } // 3- import // 3.1 fetch core data request if ([self isCancelled]) return; // 3.2 if data is not present, insert it (or update) // 3.3 save data into persistent store coordinator } </code></pre> <p>If you do not check for the cancelled flag at all in <code>-main</code>, the operation will not react to cancellation, but run until it is finished.</p> <p><strong>Edit 2</strong></p> <p>If an operation gets cancelled, nothing happens to it except that the isCancelled flag is set to true. The code above in my original answer waits in the background until the operation has finished (either reacted to the cancellation or simply finished, assuming that it does not take 10 minutes to cancel it).</p> <p>Of course, when reacting to <code>isCancelled</code> in our operation you have to make sure that you leave the operation in a non-corrupted state, for example, directly after downloading (just ignoring the data), or after writing all data.</p> <p>You are right, if an operation is cancelled but still running when you switch back to the foreground, that operation will finish the download, and then (if you programmed it like that) react to cancel and basically throw away the downloaded data. </p> <p>What you could do instead is to not cancel the operations, but wait for them to finish (assuming they take less than 10 minutes). To do that, just delete the line <code>[_queue cancelAllOperations];</code>.</p>
44,309,044
UnicodeDecodeError, utf-8 invalid continuation byte
<p>I m trying to extract lines from a log file , using that code :</p> <pre><code> with open('fichier.01') as f: content = f.readlines() print (content) </code></pre> <p>but its always makes the error statement </p> <pre><code> Traceback (most recent call last): File "./parsepy", line 4, in &lt;module&gt; content = f.readlines() File "/usr/lib/python3.5/codecs.py", line 321, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 2213: invalid continuation byte </code></pre> <p>how can i fix it ?? </p>
44,309,590
3
2
null
2017-06-01 13:35:15.36 UTC
1
2022-05-23 03:05:47.913 UTC
null
null
null
null
8,097,996
null
1
8
python|python-3.5
38,933
<p>If it's not encoded as text then you will have to open it in binary mode e.g.:</p> <pre><code>with open('fichier.01', 'rb') as f: content = f.readlines() </code></pre> <p>If it's encoded as something other than UTF-8 and it can be opened in text mode then <code>open</code> takes an <code>encoding</code> argument: <a href="https://docs.python.org/3.5/library/functions.html#open" rel="nofollow noreferrer">https://docs.python.org/3.5/library/functions.html#open</a></p>
17,877,471
Running NUnit through Resharper 8 tests fail when crossing between projects due to AppDomain
<p>I recently updated to Resharper 8, and when I tried to run a suite of projects. These tests contain two suites of integration tests that both use IISExpress to run a website, make web requests and check the responses.</p> <p>Running them in isolation is successful, and running all the tests would previously succeed. However, after the upate the second set of tests to run would fail. </p> <p>Investigation has revealed the <code>AppDomain.CurrentDomain.BaseDirectory</code> is staying as the first test to run instead of changing. Since the integration tests are composed of two projects, this is causing the second project to fail since it cannot find any of the configuration files needed.</p> <p>I cannot find any option to disable this different behaviour in Resharper 8, which appears to be the behaviour of the <code>/domain:Single</code> nunit flag. Short of downgrading to Resharper 7, does anybody know a solution to this? And is it an intended behaviour of Resharper 8 or a bug?</p>
18,104,565
3
0
null
2013-07-26 09:17:28.477 UTC
12
2014-02-13 16:22:37.427 UTC
null
null
null
null
402,287
null
1
48
c#|nunit|resharper|integration-testing|appdomain
7,478
<p><strong>The Workaround:</strong></p> <p>Have you tried in Visual Studio going to ReSharper -> Options -> Tools -> Unit Testing</p> <p>Change the setting "Run up to 1 assemblies in parallel" to a higher number. I tried one for each test project. Max is number of cores, I think.</p> <p>Counterintuitive I know, but it worked for me and I am using AppDomain.CurrentDomain.BaseDirectory in the failing tests</p> <p><strong>The Cause</strong> A caching optimization bug in ReSharper 8. Working Directory is not set properly. Perhaps running in parallel creates a separate process for each test, so they don't trip over each other's settings.</p> <p><strong>The Fix</strong> JetBrains claim that this will be fixed in version 8.0.1</p> <p><em><strong>Update:</strong> There is a <strong>new unit testing option</strong> added in <strong>Resharper 8.1</strong> to accomodate this scenario. Find it at ReSharper -> Options -> Tools -> Unit Testing -> "<strong>Use Separate AppDomain for each assembly with tests.</em></strong></p>
23,188,900
Display / print all rows of a tibble (tbl_df)
<p><code>tibble</code> (previously <code>tbl_df</code>) is a version of a data frame created by the <code>dplyr</code> data frame manipulation package in R. It prevents long table outputs when accidentally calling the data frame.</p> <p>Once a data frame has been wrapped by <code>tibble</code>/<code>tbl_df</code>, is there a command to view the whole data frame though (all the rows and columns of the data frame)?</p> <p>If I use <code>df[1:100,]</code>, I will see all 100 rows, but if I use <code>df[1:101,]</code>, it will only display the first 10 rows. I would like to easily display all the rows to quickly scroll through them.</p> <p>Is there either a dplyr command to counteract this or a way to unwrap the data frame? </p>
27,294,928
7
2
null
2014-04-20 23:55:04.003 UTC
55
2022-07-16 18:04:48.497 UTC
2022-07-16 18:04:48.497 UTC
null
946,915
null
3,555,034
null
1
250
r|dplyr
162,213
<p>You could also use</p> <pre><code>print(tbl_df(df), n=40) </code></pre> <p>or with the help of the pipe operator</p> <pre><code>df %&gt;% tbl_df %&gt;% print(n=40) </code></pre> <p>To print all rows specify <code>tbl_df %&gt;% print(n = Inf)</code></p> <p>edit 31.07.2021: <strong>in &gt; dplyr 1.0.0</strong></p> <pre><code>Warning message: `tbl_df()` was deprecated in dplyr 1.0.0. Please use `tibble::as_tibble()` instead. </code></pre> <p><code>df %&gt;% as_tibble() %&gt;% print(n=40)</code></p>
23,428,793
NSURLSession: How to increase time out for URL requests?
<p>I am using iOS 7's new <code>NSURLSessionDataTask</code> to retrieve data as follows:</p> <pre><code>NSURLSession *session = [NSURLSession sharedSession]; NSURLSessionDataTask *dataTask = [session dataTaskWithRequest: request completionHandler: ^(NSData *data, NSURLResponse *response, NSError *error) { // }]; </code></pre> <p>How can I increase the time out values to avoid the error <code>"The request timed out"</code> (in <code>NSURLErrorDomain</code> Code=<code>-1001</code>)?</p> <p>I have checked the documentation for <a href="https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSURLSessionConfiguration_class/Reference/Reference.html#//apple_ref/doc/uid/TP40013440-CH1-SW32">NSURLSessionConfiguration</a> but did not find a way to set the time out value.</p> <p>Thank you for your help!</p>
23,428,960
7
3
null
2014-05-02 12:59:26.047 UTC
18
2020-06-12 10:26:35.603 UTC
2020-06-12 10:26:35.603 UTC
null
5,175,709
null
1,214,667
null
1
83
ios|objective-c|swift|http|nsurlsession
84,983
<h3>ObjC</h3> <pre><code>NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration]; sessionConfig.timeoutIntervalForRequest = 30.0; sessionConfig.timeoutIntervalForResource = 60.0; </code></pre> <h3>Swift</h3> <pre><code>let sessionConfig = URLSessionConfiguration.default sessionConfig.timeoutIntervalForRequest = 30.0 sessionConfig.timeoutIntervalForResource = 60.0 let session = URLSession(configuration: sessionConfig) </code></pre> <h3>What docs say</h3> <p><code>timeoutIntervalForRequest</code> and <code>timeoutIntervalForResource</code> specify the timeout interval for the request as well as the resource.</p> <blockquote> <p><strong><code>timeoutIntervalForRequest</code></strong> - The timeout interval to use when waiting for additional data. The timer associated with this value is reset whenever new data arrives. When the request timer reaches the specified interval without receiving any new data, it triggers a timeout.</p> <p><strong><code>timeoutIntervalForResource</code></strong> - The maximum amount of time that a resource request should be allowed to take. This value controls how long to wait for an entire resource to transfer before giving up. The resource timer starts when the request is initiated and counts until either the request completes or this timeout interval is reached, whichever comes first.</p> </blockquote> <p>Based on <a href="https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSURLSessionConfiguration_class/Reference/Reference.html#//apple_ref/occ/instp/NSURLSessionConfiguration/timeoutIntervalForRequest" rel="noreferrer">NSURLSessionConfiguration Class Reference</a></p>
2,105,481
how to cache css, images and js?
<p>I would like to have images, css, and javascript cached client-side on their browser when they load up a web page. There are so many different types of caching I am confused as to which ones to use with asp.net mvc. </p> <p>Would it also be possible to have their browsers check for new or modified versions of these files? </p> <p>Thanks!</p>
2,105,492
6
0
null
2010-01-20 22:23:49.123 UTC
14
2015-12-31 14:22:41.99 UTC
2012-10-28 18:33:19.363 UTC
null
24,874
null
173,432
null
1
26
.net|asp.net-mvc|caching|asp.net-caching
29,695
<p>Browsers take care of this for you automatically, actually. You have to go out of your way to get them to NOT cache css, js, html and images.</p> <p>I'm not that familiar with ASP MVC, but I think they type of caching you're thinking of is opcode caching for your created dynamic output server-side?</p>
1,800,817
How can I get part of regex match as a variable in python?
<p>In Perl it is possible to do something like this (I hope the syntax is right...):</p> <pre><code>$string =~ m/lalala(I want this part)lalala/; $whatIWant = $1; </code></pre> <p>I want to do the same in Python and get the text inside the parenthesis in a string like $1.</p>
1,800,858
7
0
null
2009-11-26 00:07:14.167 UTC
6
2015-06-26 05:52:36.31 UTC
null
null
null
null
74,660
null
1
25
python|regex|perl
58,054
<p>See: <a href="https://docs.python.org/2/library/re.html#match-objects" rel="noreferrer">Python regex match objects</a></p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; p = re.compile("lalala(I want this part)lalala") &gt;&gt;&gt; p.match("lalalaI want this partlalala").group(1) 'I want this part' </code></pre>
1,661,800
Hidden Columns in jqGrid
<p>Is there any way to hide a column in a jqGrid table, but have it show as read-only when the row is edited in the form editor modal dialog?</p>
5,926,267
7
0
null
2009-11-02 15:02:29.813 UTC
19
2017-08-08 15:38:29.317 UTC
2012-12-20 11:06:39.533 UTC
null
702,761
null
158,434
null
1
54
javascript|jquery|jqgrid
144,677
<p>I just want to expand on <strong>queen3</strong>'s suggestion, applying the following does the trick:</p> <pre><code>editoptions: { dataInit: function(element) { $(element).attr("readonly", "readonly"); } } </code></pre> <p><strong>Scenario #1</strong>:</p> <ul> <li>Field must be visible in the grid</li> <li>Field must be visible in the form</li> <li>Field must be read-only</li> </ul> <p><strong>Solution</strong>:</p> <pre><code>colModel:[ { name:'providerUserId', index:'providerUserId', width:100,editable:true, editrules:{required:true}, editoptions:{ dataInit: function(element) { jq(element).attr("readonly", "readonly"); } } }, ], </code></pre> <p>The providerUserId is visible in the grid and visible when editing the form. But you cannot edit the contents. </p> <hr> <p><strong>Scenario #2</strong>:</p> <ul> <li>Field must not be visible in the grid</li> <li>Field must be visible in the form</li> <li>Field must be read-only</li> </ul> <p><strong>Solution</strong>:</p> <pre><code>colModel:[ {name:'providerUserId', index:'providerUserId', width:100,editable:true, editrules:{ required:true, edithidden:true }, hidden:true, editoptions:{ dataInit: function(element) { jq(element).attr("readonly", "readonly"); } } }, ] </code></pre> <p>Notice in both instances I'm using jq to reference jquery, instead of the usual $. In my HTML I have the following script to modify the variable used by jQuery:</p> <pre><code>&lt;script type="text/javascript"&gt; var jq = jQuery.noConflict(); &lt;/script&gt; </code></pre>
2,021,982
awk without printing newline
<p>I want the variable sum/NR to be printed side-by-side in each iteration. How do we avoid awk from printing newline in each iteration ? In my code a newline is printed by default in each iteration</p> <pre><code>for file in cg_c ep_c is_c tau xhpl printf "\n $file" &gt;&gt; to-plot.xls for f in 2.54 1.60 800 awk '{sum+=$3}; END {print sum/NR}' ${file}_${f}_v1.xls &gt;&gt; to-plot-p.xls done done </code></pre> <p>I want the output to appear like this</p> <pre><code>cg_c ans1 ans2 ans3 ep_c ans1 ans2 ans3 is_c ans1 ans2 ans3 tau ans1 ans2 ans3 xhpl ans1 ans2 ans3 </code></pre> <p>my current out put is like this</p> <pre><code>**cg_c** ans1 ans2 ans3 **ep_c** ans1 ans2 ans3 **is_c** ans1 ans2 ans3 **tau** ans1 ans2 ans3 **xhpl** ans1 ans2 ans3 </code></pre>
2,022,026
7
0
null
2010-01-07 16:49:27.333 UTC
29
2022-07-09 15:39:31.53 UTC
2010-01-07 20:31:42.743 UTC
null
3,140
null
196,093
null
1
209
scripting|awk|newline
218,716
<p><code>awk '{sum+=$3}; END {printf "%f",sum/NR}' ${file}_${f}_v1.xls &gt;&gt; to-plot-p.xls</code></p> <p><code>print</code> will insert a newline by default. You dont want that to happen, hence use <code>printf</code> instead.</p>
2,333,307
Should Enterprise Java entities be dumb?
<p>In our legacy Java EE application, there are loads of value object (VO) classes which typically contain only getters and setters, maybe <code>equals()</code> and <code>hashCode()</code>. These are (typically) the entities to be saved in persistence storage. (For the record, our app has no EJBs - although that <em>might</em> change in the future -, and we use Hibernate for persisting our entities.) All the business logic to manipulate the data in VOs is in separate classes (not EJBs, just POJOs). My OO mindset hates this, as I do believe that the operations on a given class should reside in that same class. So I have an urge to refactor to move logic into the related VOs.</p> <p>I just had a discussion with a co-worker who is much more experienced in Java EE than me, and he confirmed that dumb entities at least used to be the recommended way to go. However, he has also read opinions recently which question the validity of this stance.</p> <p>I understand that there are issues which at least limit what can be put inside an entity class:</p> <ul> <li>it should not have direct dependency to the data layer (e.g. query code should rather go into separate DAOs)</li> <li>if it is directly exposed to higher layers or to the client (e.g. via SOAP), its interface may need to be limited</li> </ul> <p>Are there any more valid reasons <strong>not</strong> to move logic into my entities? Or any other concerns to take into account?</p>
2,333,921
8
1
null
2010-02-25 10:40:25.413 UTC
14
2020-06-13 18:23:46.04 UTC
2013-05-09 09:03:38.863 UTC
null
472,792
null
265,143
null
1
29
java|oop|jakarta-ee|entity
6,207
<p>The <strong>DTO</strong> and <strong>VO</strong> are supposed to be used to transfer data and don't embed logic. The <strong>business objects</strong> on the other hand are supposed to embed some logic. I say <em>some</em>, because there is always a balance to find between what you put in services which coordinate logic involving several business objects and what you put in the business objects themselves. Typical logic in the business objects can be validation, field computation, or other operation that impact only one business object at a time.</p> <p>Note that I haven't mentioned the term <strong>entity</strong> so far. Persistent entities were popularized with ORM and we nowadays try to use persistent entities both as DTO <em>and</em> business object at the same time. That is, the entity themselves flow between layers and tiers, and contain some logic. </p> <blockquote> <p>Are there any more valid reasons not to move logic into my entities? Or any other concerns to take into account?</p> </blockquote> <p>As you pointed out, it's all a matter of dependencies and what you expose. As long as the entities are dumb (close to DTO) they can be isolated in a dedicated jar easily that serves as <strong>API of the layer</strong>. The more logic you put in the entities, the harder it becomes to do that. Pay attention to what you expose and what you depend on (the load the class, the client will need to have the depend class as well). This applies to exceptions, inheritance hierarchy, etc.</p> <p>Just to give an example, I had a project where the entities had a method <code>toXml(...)</code> used in the business layer. As a consequence, client of the entities depended on XML.</p> <p>But if you don't care too much about layers, and strict separation between API and implementation, I think it's good to move some logic in the entities. </p> <p><strong>EDIT</strong></p> <p>This question has been discussed many time and will probably continue to be discussed as there is no definitive answer. A few interesting links:</p> <ul> <li><a href="http://martinfowler.com/bliki/GetterEradicator.html" rel="nofollow noreferrer">Getter Eradicator</a> </li> <li><a href="http://en.wikipedia.org/wiki/Anemic_Domain_Model" rel="nofollow noreferrer">Anemic domain model</a></li> <li><a href="http://codecourse.sourceforge.net/materials/The-Importance-of-Being-Closed.pdf" rel="nofollow noreferrer">The importance of being closed</a> </li> <li><a href="http://www.aptprocess.com/whitepapers/DomainModelling.pdf" rel="nofollow noreferrer">Domain Modeling</a></li> <li><a href="http://blog.unhandled-exceptions.com/index.php/2008/12/26/services-anemic-domain-models-and-where-does-my-business-logic-go/" rel="nofollow noreferrer">Where does my business logic go?</a></li> <li><a href="https://dzone.com/articles/transfer-obejcts-vs-business" rel="nofollow noreferrer">Transfer object vs. business object</a></li> </ul>
1,802,597
Identifying Exception Type in a handler Catch Block
<p>I have created custom exception class</p> <pre><code>public class Web2PDFException : Exception { public Web2PDFException(string message, Exception innerException) : base(message, innerException) { ... } } </code></pre> <p>In my application how can I find out if it is my custom exception or not? </p> <pre><code>try { ... } catch (Exception err) { //Find exception type here } </code></pre>
1,802,611
8
0
null
2009-11-26 09:34:58.137 UTC
9
2022-01-02 23:08:03.3 UTC
2020-03-02 15:59:54.577 UTC
null
285,795
null
212,057
null
1
53
c#|exception
121,908
<p>UPDATED: assuming <a href="https://github.com/dotnet/roslyn/wiki/New-Language-Features-in-C%23-6" rel="noreferrer">C# 6</a>, the chances are that your case can be expressed as an exception filter. This is the ideal approach from a performance perspective assuming your requirement can be expressed in terms of it, e.g.:</p> <pre><code>try { } catch ( Web2PDFException ex ) when ( ex.Code == 52 ) { } </code></pre> <hr> <p>Assuming C# &lt; 6, the most efficient is to catch a specific <code>Exception</code> type and do handling based on that. Any catch-all handling can be done separately</p> <pre><code>try { } catch ( Web2PDFException ex ) { } </code></pre> <p>or</p> <pre><code>try { } catch ( Web2PDFException ex ) { } catch ( Exception ex ) { } </code></pre> <p>or (if you need to write a general handler - which is generally a bad idea, but if you're sure it's best for you, you're sure):</p> <pre><code> if( err is Web2PDFException) { } </code></pre> <p>or (in certain cases if you need to do some more complex type hierarchy stuff that cant be expressed with <code>is</code>)</p> <pre><code> if( err.GetType().IsAssignableFrom(typeof(Web2PDFException))) { } </code></pre> <p><strike>or switch to VB.NET or F# and use <code>is</code> or <code>Type.IsAssignableFrom</code> in Exception Filters</strike></p>
1,924,367
Why do hedge funds and financial services often use OCaml?
<p>Speaking to a number of quants / hedgies, I came to the conclusion that a large number of them seem to be using either a homebrew language or OCaml for many tasks. What many of them couldn't answer was why.</p> <p>I can certainly understand why they wouldnt want to use C++ for the most part, but why is OCaml superior for these uses compared to other scripting languages, say Python, Ruby etc?</p>
1,924,726
9
3
null
2009-12-17 20:31:49.273 UTC
22
2017-12-18 14:45:41.89 UTC
2012-05-05 10:08:58.893 UTC
null
1,095,817
null
207,201
null
1
26
programming-languages|ocaml|quantitative-finance
17,525
<p>Try reading <a href="https://dl.acm.org/citation.cfm?id=1394798" rel="nofollow noreferrer">Caml trading - experiences with functional programming on Wall Street</a> by Yaron Minsky and Stephen Weeks (apologies, while this article used to be hosted for free at Jane Capital, it is no longer there, so I leave the ACM link for reference). They go into great detail about what they feel are the advantages and disadvantages of OCaml, though they for the most part take it as a given that it is better than most other options they considered (i.e. not a lot of direct comparisons with C++, Python, what have you).</p> <p>The authors work at Jane Street Capital which has invested heavily in OCaml code.</p> <p><em>Update</em>: See also the thread <a href="https://stackoverflow.com/questions/1996432/what-programming-languages-is-algorithmic-trading-software-written-in">What programming language(s) is algorithmic trading software written in?</a>. One of the <a href="https://stackoverflow.com/questions/1996432/what-programming-languages-is-algorithmic-trading-software-written-in/1996448#1996448">comments</a> mentions a presentation Yaron Minsky gave at CMU on Jane Street Capital's use of Caml. About an hour long, and <em>very</em> interesting.</p> <p><em>Update Two</em>: Yaron has written another overview, this time for ACM Queue, called <a href="http://queue.acm.org/detail.cfm?id=2038036" rel="nofollow noreferrer">OCaml for the Masses</a>.</p>