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
20,414,669
nginx add headers when returning 400 codes
<p>I'm developing an ember.js app with a laravel backend. I'm trying to return http error codes with php if something goes awry. I've noticed that when issue a PUT request and return a 400 status code, my CORS headers get ignored by my conf file which breaks my ember frontend. I have no idea why the PUT/400 code combo makes nginx ignore my conf. Any help would be much appreciated. </p> <pre><code> server { listen *:80 ; server_name userchamp.com; access_log /var/log/nginx/embertest.com.access.log; location / { root /var/www/embertest/public; try_files $uri $uri/ /index.php?$args ; index index.html index.htm index.php; } location ~ \.php$ { if ($request_method = 'OPTIONS') { add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Credentials' 'true'; add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type'; add_header 'Access-Control-Max-Age' 1728000; add_header 'Content-Type' 'text/plain charset=UTF-8'; add_header 'Content-Length' 0; return 204; } if ($request_method = 'POST') { add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Credentials' 'true'; add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type'; } if ($request_method = 'PUT') { add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Credentials' 'true'; add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE OPTIONS'; add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type'; } if ($request_method = 'GET') { add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Credentials' 'true'; add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type'; } if ($request_method = 'DELETE') { add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Credentials' 'true'; add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type'; } root /var/www/embertest/public; try_files $uri $uri/ /index.php?$args ; index index.html index.htm index.php; fastcgi_index index.php; fastcgi_param PATH_INFO $fastcgi_path_info; fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param APP_ENV dev; fastcgi_param APP_DBG true; fastcgi_pass unix:/var/run/php5-fpm.sock; fastcgi_split_path_info ^(.+\.php)(/.+)$; include fastcgi_params; } } </code></pre>
20,416,736
1
0
null
2013-12-06 02:11:17.263 UTC
8
2021-03-18 02:40:50.077 UTC
null
null
null
null
728,241
null
1
51
nginx
28,046
<p><strong>For nginx >= 1.7.5</strong></p> <p>Append "always" to the header definition: </p> <pre><code>add_header 'Access-Control-Allow-Origin' '*' always; </code></pre> <p><strong>For nginx &lt; 1.7.5</strong></p> <p>According to the nginx official document of <a href="http://nginx.org/en/docs/http/ngx_http_headers_module.html" rel="noreferrer">ngx_header_module</a>, the <code>add_header</code> can't work when response code is 400</p> <pre><code>syntax: add_header name value; default: — context: http, server, location, if in location Adds the specified field to a response header provided that the response code equals 200, 201, 204, 206, 301, 302, 303, 304, or 307. A value can contain variables. </code></pre> <p>In another way, you can try the <a href="http://wiki.nginx.org/HttpHeadersMoreModule" rel="noreferrer">HttpHeadersMoreModule</a>, which is more powerful. </p>
35,813,156
How to set <Text> text to upper case in react native
<p>How to set <code>&lt;Text&gt; some text &lt;/Text&gt;</code> as upper case in react native?</p> <pre><code>&lt;Text style={{}}&gt; Test &lt;/Text&gt; </code></pre> <p>Need to show that <code>Test</code> as <code>TEST</code>.</p>
35,813,246
7
1
null
2016-03-05 10:48:49.6 UTC
11
2022-07-22 05:50:39.757 UTC
2021-05-04 15:39:09.977 UTC
null
6,904,888
null
3,871,959
null
1
104
react-native|uppercase
151,267
<p>@Cherniv Thanks for the answer</p> <pre><code>&lt;Text style={{}}&gt; {'Test'.toUpperCase()} &lt;/Text&gt; </code></pre>
66,563,463
How to treat '<attribute 'dtype' of 'numpy.generic' objects>' error?
<p>After installing pypfopt and u-numpy, <code>dataframe.info()</code> command shows this error.</p> <pre class="lang-none prettyprint-override"><code>TypeError: Cannot interpret '&lt;attribute 'dtype' of 'numpy.generic' objects&gt;' as a data type </code></pre>
66,941,626
9
0
null
2021-03-10 11:07:12.377 UTC
null
2022-06-16 06:38:51.36 UTC
2021-03-12 00:57:24.693 UTC
null
1,940,850
null
15,367,710
null
1
18
python-3.x|pandas|dataframe|typeerror
41,829
<p>I happened to mix my versions and I encountered the problem today. I managed to fix it. Both codes in jupyter gave me an error: TypeError: Cannot interpret '&lt;attribute 'dtype' of 'numpy.generic' objects&gt;' as a data type</p> <pre><code>df.info() df.categorical_column_name.value_counts().plot.bar() </code></pre> <p>I got the error: TypeError: Cannot interpret '&lt;attribute 'dtype' of 'numpy.generic' objects&gt;' as a data type</p> <p>This is how i fixed it</p> <p>Inside jupyter: Check numpy version:</p> <pre><code>import numpy as np print(np.__version__) </code></pre> <p>To upgrade:</p> <pre><code>!pip3 install numpy --upgrade </code></pre> <p>Inside Command line check numpy version: python</p> <pre><code>import numpy print(numpy.__version__) </code></pre> <p>if versions are not the same choose whether to upgrade/downgrade: To upgrade:</p> <pre><code>$pip install numpy --upgrade </code></pre> <p>To downgrade just specify the version</p> <p>If you have python environment installed: Go to the right folder: Check the installed version:</p> <pre><code>$pipenv --version </code></pre> <p>To verify if you have a pip environment installed for that folder: On your terminal Go to the folder and type:</p> <pre><code>$pipenv --version </code></pre> <p>If there is a pipenv it will show the version and if there is none it won't.</p> <p>check numpy version</p> <pre><code>$python &gt;&gt;&gt; import numpy #prints the version &gt;&gt;&gt; print(numpy__version__) </code></pre> <p>To upgrade the version:</p> <pre><code>&gt;&gt;&gt;exit() </code></pre> <p>#To install the latest version don't specify the version</p> <pre><code>$pipenv install numpy </code></pre> <p>#if you want to downgrade specify the version</p> <pre><code>$pipenv install numpy=version_type </code></pre> <p>Do the same for pandas. Note that with pandas if your pandas environment is 1.2.3 on the jupyter notebook upgrade with <code>!pip install pandas==1.2.3</code> or just <code>!pip install pandas --upgrade --user</code>.</p> <p>Note that if the commands are giving you an error always include <code>--user</code> at the end of the command.</p> <p>To create a new environment using miniconda and install updated packages follow the link [https://pandas.pydata.org/pandas-docs/stable/getting_started/install.html][1]</p> <p>Run the following commands from a terminal window:</p> <ol> <li><code>conda create -n name_of_my_env python</code> This will create a minimal environment with only Python installed in it. To put your self inside this environment run:</li> </ol> <p><code>source activate name_of_my_env</code> On Windows the command is: 2. <code>activate name_of_my_env</code></p> <p>The final step required is to install pandas. This can be done with the following command:</p> <p><code>conda install pandas</code></p> <p>To install a specific pandas version:</p> <ol start="3"> <li><code>conda install pandas=0.20.3</code></li> </ol> <p>I prefer using the latest version of pandas 1.2.3</p> <p>However the first method should solve your problem. Always restart your notebook by closing and reopening it.</p> <p>I will stick around to see if you are winning. But this will resolve your problem. The problem is caused by the versions of numpy and pandas [1]: <a href="https://pandas.pydata.org/pandas-docs/stable/getting_started/install.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/getting_started/install.html</a></p>
6,057,379
how to get the Seconds of the time using python
<p>this is my code:</p> <pre><code>last_time = get_last_time() now = time.time() - last_time minute = seconds = print 'Next time you add blood is '+minute+':'+seconds </code></pre> <p>Because recovery blood every 5 minutes so only need minute and second</p> <p>thanks</p>
6,057,454
3
0
null
2011-05-19 10:40:59.353 UTC
1
2019-08-02 20:02:54.657 UTC
null
null
null
null
420,840
null
1
17
python|time
111,135
<p>This is basic time arithmetics...if you know that a minute has 60 seconds then you could have found that yourself:</p> <pre><code>minute = int(now / 60) seconds = int(now % 60) </code></pre>
5,880,513
How to make a linearlayout filling remaining space in a relativelayout?
<p>I've got a relativelayout with three linearlayouts as children. The last one has a fixed height and has android:layout_alignParentBottom set to "true". While the middle one is properly positioned below the first one, it goes as far as the bottom of the screen, so that its lower part is overlapped by the third one.</p> <p>What's wrong?</p> <p>Thanks</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" &gt; &lt;LinearLayout android:id="@+id/category" android:layout_width="fill_parent" android:layout_height="50dp" android:layout_alignParentTop="true" android:orientation="horizontal" &gt; &lt;ImageView android:id="@+id/back_btn" android:layout_width="29dp" android:layout_height="34dp" android:layout_gravity="center_vertical" android:src="@drawable/red_arrow_left" /&gt; &lt;TextView android:id="@+id/cat_name" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:gravity="center" android:textSize="20sp" /&gt; &lt;/LinearLayout&gt; &lt;LinearLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_below="@+id/category" android:layout_marginTop="10dp" android:orientation="horizontal" &gt; &lt;ListView android:id="@+id/android:list" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@android:color/white" android:cacheColorHint="@android:color/white" /&gt; &lt;TextView android:id="@+id/android:empty" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@android:color/white" android:cacheColorHint="@android:color/white" android:padding="10dp" android:text="@string/no_item" /&gt; &lt;/LinearLayout&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/nav_bar" android:layout_width="fill_parent" android:layout_height="40dp" android:layout_alignParentBottom="true" android:orientation="horizontal" &gt; //stuff &lt;/LinearLayout&gt; &lt;/RelativeLayout&gt; </code></pre>
5,881,419
3
0
null
2011-05-04 08:18:25.883 UTC
4
2019-06-16 21:53:33.147 UTC
2012-03-19 13:25:14.453 UTC
null
175,830
null
326,849
null
1
22
android|layout
64,777
<p>Nooo... the solution is much simpler! You forgot to say that you wanted the second linear layout to be above the third one :) Yes, the second linear layout must have BOTH <code>android:layout_below="@+id/category"</code> and <code>android:layout_above="@+id/nav_bar"</code>. I tested it and it works.</p> <p>But of course, you can use weights to achieve the same results, it is just going to be harder...</p> <p>Here is your XML with the change I mentioned (tested it in eclipse):</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" &gt; &lt;LinearLayout android:id="@+id/category" android:layout_width="fill_parent" android:layout_height="50dp" android:layout_alignParentTop="true" android:orientation="horizontal" &gt; &lt;ImageView android:id="@+id/back_btn" android:layout_width="29dp" android:layout_height="34dp" android:layout_gravity="center_vertical" android:src="@drawable/red_arrow_left" /&gt; &lt;TextView android:id="@+id/cat_name" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:gravity="center" android:textSize="20sp" /&gt; &lt;/LinearLayout&gt; &lt;LinearLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_above="@+id/nav_bar" android:layout_below="@+id/category" android:layout_marginTop="10dp" android:orientation="horizontal" &gt; &lt;ListView android:id="@+id/android:list" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@android:color/white" android:cacheColorHint="@android:color/white" /&gt; &lt;TextView android:id="@+id/android:empty" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@android:color/white" android:cacheColorHint="@android:color/white" android:padding="10dp" android:text="@string/no_item" /&gt; &lt;/LinearLayout&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/nav_bar" android:layout_width="fill_parent" android:layout_height="40dp" android:layout_alignParentBottom="true" android:orientation="horizontal" &gt; //stuff &lt;/LinearLayout&gt; &lt;/RelativeLayout&gt; </code></pre>
5,820,306
WCF webHttpBinding error with method parameters. "At most one body parameter can be serialized without wrapper elements"
<blockquote> <p>Operation '' of contract '' specifies multiple request body parameters to be serialized without any wrapper elements. At most one body parameter can be serialized without wrapper elements. Either remove the extra body parameters or set the BodyStyle property on the WebGetAttribute/WebInvokeAttribute to Wrapped.</p> </blockquote> <p>I am trying to expose a C# 4.0 WCF Service with JSON via the following config (set via the WCF Config Editor):</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;configuration&gt; &lt;system.web&gt; &lt;compilation debug="true" targetFramework="4.0" /&gt; &lt;/system.web&gt; &lt;system.serviceModel&gt; &lt;services&gt; &lt;service name="iPhoneAPI.API"&gt; &lt;endpoint address="" behaviorConfiguration="NewBehavior0" binding="webHttpBinding" bindingConfiguration="" contract="iPhoneAPI.IApi" /&gt; &lt;/service&gt; &lt;/services&gt; &lt;protocolMapping&gt; &lt;add scheme="http" binding="webHttpBinding" bindingConfiguration="" /&gt; &lt;/protocolMapping&gt; &lt;behaviors&gt; &lt;endpointBehaviors&gt; &lt;behavior name="NewBehavior0"&gt; &lt;webHttp defaultOutgoingResponseFormat="Json" /&gt; &lt;/behavior&gt; &lt;/endpointBehaviors&gt; &lt;serviceBehaviors&gt; &lt;behavior name=""&gt; &lt;serviceMetadata httpGetEnabled="true" /&gt; &lt;serviceDebug includeExceptionDetailInFaults="false" /&gt; &lt;/behavior&gt; &lt;/serviceBehaviors&gt; &lt;/behaviors&gt; &lt;serviceHostingEnvironment multipleSiteBindingsEnabled="true" /&gt; &lt;/system.serviceModel&gt; &lt;system.webServer&gt; &lt;modules runAllManagedModulesForAllRequests="true"/&gt; &lt;/system.webServer&gt; &lt;/configuration&gt; </code></pre> <p>When I access /API.svc, I get the previously listed exception message.</p> <p>If I only specify the following (parameter-less)contract, the service works:</p> <pre><code>[OperationContract] [WebInvoke(Method = "GET", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "test")] GenericApiResult&lt;IEnumerable&lt;LiveFeedEntity&gt;&gt; test(); </code></pre> <p>If I have methods that require parameters that are non-strings, I get the previously listed exception.</p> <p>Example:</p> <pre><code>[OperationContract] [WebInvoke(Method = "GET", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "login")] LoginApiResult Login(String UserName, String Password); </code></pre> <p>If I change this function like so:</p> <pre><code>[OperationContract] [WebInvoke(Method = "GET", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "login/{UserName}/{Password}")] LoginApiResult Login(String UserName, String Password); </code></pre> <p>It works; but this is only possible for parameters of Type String. How do I respolve this for my other functions like:</p> <pre><code>[OperationContract] [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "logout")] GenericApiResult&lt;bool&gt; Logout(Guid SessionKey); </code></pre> <p>Tried a lot of google searches, but turned up empty handed, any help is appreciated.</p> <p>Cheers,</p> <p>Nick.</p>
5,820,502
3
0
null
2011-04-28 14:35:29.127 UTC
4
2014-10-16 08:25:56.063 UTC
null
null
null
null
458,991
null
1
34
c#|wcf|json|rest
58,359
<p>Have you tried setting the <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.web.webinvokeattribute.bodystyle.aspx">WebInvokeAttribute.BodyStyle</a> to <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.web.webmessagebodystyle.aspx">Wrapped</a> as the error recommends?</p>
6,150,188
How to update a git clone --mirror?
<p>I have created a git repository to mirror a live site (which is a non-bare git repository):</p> <pre><code>git clone --mirror ssh://[email protected]/path/to/repo </code></pre> <p>Now, to keep this mirror clone updated with all changes from its remote origin, which command or commands I must use?</p> <p>I'd like to keep everything updated: commits, refs, hooks, branches, etc.</p> <p>Thanks!</p>
6,151,419
3
0
null
2011-05-27 09:16:42.18 UTC
70
2018-12-07 10:01:38.023 UTC
null
null
null
null
370,290
null
1
163
git|mirror|git-clone|git-remote|git-fetch
160,424
<p>This is the command that you need to execute on the mirror:</p> <pre><code>git remote update </code></pre>
6,304,035
How to display an activity automatically after 5 seconds?
<p>In my application I have created a splash screen type of thing in Android. It should remain for 5 seconds.</p> <p>My problem is how do I display another activity automatically after 5 secs?</p> <p>The splash screen doesn't have a button, rather it should display another activity automatically after 5 seconds without the click of a button.</p>
6,304,087
4
0
null
2011-06-10 08:47:50.16 UTC
16
2022-03-15 12:46:22.227 UTC
2022-03-15 12:46:22.227 UTC
null
11,211,041
null
785,544
null
1
21
android|timer|splash-screen
48,003
<pre><code>new Handler().postDelayed(new Runnable() { @Override public void run() { final Intent mainIntent = new Intent(LaunchActivity.this, HomeActivity.class); LaunchActivity.this.startActivity(mainIntent); LaunchActivity.this.finish(); } }, 5000); </code></pre>
5,947,947
Difference between ServerRoot, DocumentRoot, and Directory
<p>While playing with Apache, I messed up the paths without making a backup httpd.config file. </p> <p>The file is located at C:\xampp\apache\conf\httpd.config</p> <p>I want to keep my web project on the D: drive as a virtual folder. This is the current non-working state. How can I fix this or revert to the xampp defaults?</p> <pre><code>ServerRoot "C:\xampp\apache" DocumentRoot "D:\workspace" &lt;Directory "D:\workspace\AutionWebSite"&gt; </code></pre>
5,948,004
4
0
null
2011-05-10 09:25:51.853 UTC
3
2017-07-18 05:09:54.517 UTC
2014-02-06 16:16:13.04 UTC
null
704,803
null
389,288
null
1
23
apache|xampp
44,795
<ul> <li>ServerRoot = path to the webserver executable/dir</li> <li>DocumentRoot = path to your files that are delivered by the server</li> <li>The <code>&lt;Directory&gt;</code> directive is used to configure settings for a specific directory. However, the <code>&lt;Directory&gt;</code> command in your question is not complete.</li> </ul>
5,658,501
How can the return value of an OCMock stub be changed?
<p>It seems that the first time I add <em>andReturnValue</em> on an OCMock stub, that return value is set in stone. For example:</p> <pre><code>id physics = [OCMockObject niceMockForClass:[DynamicPhysicsComponent class] Entity *testEntity = [Entity entityWithPhysicsComponent:physics]; CGPoint velocity1 = CGPointMake(100, 100); CGPoint velocity2 = CGPointZero; [[[physics stub] andReturnValue:OCMOCK_VALUE(velocity1)] getCurrentVelocity]; [testEntity update:0.1]; [[[physics stub] andReturnValue:OCMOCK_VALUE(velocity2)] getCurrentVelocity]; [testEntity update:0.1]; </code></pre> <p>The stubbed method is called in [testEntity update]. But each time the stubbed method is returning the velocity1 value, so I guess the second attempt to set the methods return value isn't honoured.</p> <p>Is there a way to do do this in OCMock?</p>
5,666,766
4
0
null
2011-04-14 04:22:43.143 UTC
10
2016-01-20 14:17:40.117 UTC
2011-04-14 20:56:28.067 UTC
null
445,929
null
445,929
null
1
27
unit-testing|ocmock
12,682
<p>When you <code>stub</code> a method, you're saying it should always function in the specified way, no matter how many times it's called. The easiest way to fix this is to change <code>stub</code> to <code>expect</code>:</p> <pre><code>CGPoint velocity1 = CGPointMake(100, 100); CGPoint velocity2 = CGPointZero; [[[physics expect] andReturnValue:OCMOCK_VALUE(velocity1)] getCurrentVelocity]; [testEntity update:0.1]; [[[physics expect] andReturnValue:OCMOCK_VALUE(velocity2)] getCurrentVelocity]; [testEntity update:0.1]; </code></pre> <p>Alternatively, if you need to <code>stub</code> (for example if the method might not be called at all), you can just re-create the mock:</p> <pre><code>CGPoint velocity1 = CGPointMake(100, 100); CGPoint velocity2 = CGPointZero; [[[physics stub] andReturnValue:OCMOCK_VALUE(velocity1)] getCurrentVelocity]; [testEntity update:0.1]; [physics verify]; physics = [OCMockObject mockForClass:[Physics class]]; [[[physics stub] andReturnValue:OCMOCK_VALUE(velocity2)] getCurrentVelocity]; [testEntity update:0.1]; [physics verify]; </code></pre>
5,664,094
Getting list of table comments in PostgreSQL
<p>Postgresql allows adding comments to objects such as tables. For example I've added a comment to table "mytable" by using this SQL command:</p> <pre><code>COMMENT ON TABLE mytable IS 'This is my table.'; </code></pre> <p>My question is: If I want to use a SQL-command to get all tables along with their respective comment - how would I do this? What would be the appropriate query for this?</p> <p>Thanks in advance! Cheers!</p>
5,664,217
4
1
null
2011-04-14 13:35:57.71 UTC
9
2022-06-17 09:42:34.147 UTC
2011-04-14 15:59:22.65 UTC
null
621,258
null
621,258
null
1
50
sql|postgresql
37,274
<p>All comments are stored in <a href="http://www.postgresql.org/docs/current/static/catalog-pg-description.html" rel="noreferrer">pg_description</a></p> <p>To get the comments on a table, you need to join it to <a href="http://www.postgresql.org/docs/current/static/catalog-pg-class.html" rel="noreferrer">pg_class</a></p> <p>As an alternative you can also use the function <code>obj_description()</code> to retrieve this information:</p> <pre><code>SELECT obj_description(oid) FROM pg_class WHERE relkind = 'r' </code></pre> <p><strong>Edit</strong><br/></p> <p>In psql you can simply use the <code>\d+</code> command to show all tables including their comments. Or use the <code>\dd</code> command to show all comments in the system</p>
2,005,234
Asynchronous data through Bloomberg's new data API (COM v3) with Python?
<p>Does anyone know how to get asynchronous data through Bloomberg's new data API (COM v3) with Python? I found this code below on wilmott.com and it works just fine, but it's for the old API version.</p> <p>Does anyone know the corresponding code for the new version?</p> <pre><code>from win32com.client import DispatchWithEvents from pythoncom import PumpWaitingMessages, Empty, Missing from time import time class BBCommEvent: def OnData(self, Security, cookie, Fields, Data, Status): print 'OnData: ' + `Data` def OnStatus(self, Status, SubStatus, StatusDescription): print 'OnStatus' class TestAsync: def __init__(self): clsid = '{F2303261-4969-11D1-B305-00805F815CBF}' progid = 'Bloomberg.Data.1' print 'connecting to BBComm' blp = DispatchWithEvents(clsid, BBCommEvent) blp.AutoRelease = False blp.Subscribe('EUR Curncy', 1, 'LAST_PRICE', Results = Empty) blp.Flush() end_time = time() + 5 while 1: PumpWaitingMessages() if end_time &lt; time(): print 'timed out' break if __name__ == "__main__": ta = TestAsync() </code></pre>
2,054,374
2
0
null
2010-01-05 10:03:25.363 UTC
13
2012-04-18 17:11:17.067 UTC
2011-11-25 20:40:51.84 UTC
null
680,273
null
243,780
null
1
9
python|asynchronous|win32com|bloomberg
15,817
<p>I finally figured it out. I did a fair bit of combrowse.py detective work, and I compared with the JAVA, C, C++, and .NET examples in the BBG API download. Interestingly enough the Bloomberg Helpdesk people knew pretty much null when it came to these things, or perhaps I was just talking to the wrong person.</p> <p>Here is my code.</p> <p>asynchronousHandler.py:</p> <pre><code>import win32com.client from pythoncom import PumpWaitingMessages from time import time, strftime import constants class EventHandler: def OnProcessEvent(self, result): event = win32com.client.gencache.EnsureDispatch(result) if event.EventType == constants.SUBSCRIPTION_DATA: self.getData(event) elif event.EventType == constants.SUBSCRIPTION_STATUS: self.getStatus(event) else: self.getMisc(event) def getData(self, event): iterator = event.CreateMessageIterator() while iterator.Next(): message = iterator.Message dataString = '' for fieldIndex, field in enumerate(constants.fields): if message.AsElement.HasElement(field): element = message.GetElement(field) if element.IsNull: theValue = '' else: theValue = ', Value: ' + str(element.Value) dataString = dataString + ', (Type: ' + element.Name + theValue + ')' print strftime('%m/%d/%y %H:%M:%S') + ', MessageType: ' + message.MessageTypeAsString + ', CorrelationId: ' + str(message.CorrelationId) + dataString def getMisc(self, event): iterator = event.CreateMessageIterator() while iterator.Next(): message = iterator.Message print strftime('%m/%d/%y %H:%M:%S') + ', MessageType: ' + message.MessageTypeAsString def getStatus(self, event): iterator = event.CreateMessageIterator() while iterator.Next(): message = iterator.Message if message.AsElement.HasElement('reason'): element = message.AsElement.GetElement('reason') print strftime('%m/%d/%y %H:%M:%S') + ', MessageType: ' + message.MessageTypeAsString + ', CorrelationId: ' + str(message.CorrelationId) + ', Category: ' + element.GetElement('category').Value + ', Description: ' + element.GetElement('description').Value if message.AsElement.HasElement('exceptions'): element = message.AsElement.GetElement('exceptions') exceptionString = '' for n in range(element.NumValues): exceptionInfo = element.GetValue(n) fieldId = exceptionInfo.GetElement('fieldId') reason = exceptionInfo.GetElement('reason') exceptionString = exceptionString + ', (Field: ' + fieldId.Value + ', Category: ' + reason.GetElement('category').Value + ', Description: ' + reason.GetElement('description').Value + ') ' print strftime('%m/%d/%y %H:%M:%S') + ', MessageType: ' + message.MessageTypeAsString + ', CorrelationId: ' + str(message.CorrelationId) + exceptionString class bloombergSource: def __init__(self): session = win32com.client.DispatchWithEvents('blpapicom.Session' , EventHandler) session.Start() started = session.OpenService('//blp/mktdata') subscriptions = session.CreateSubscriptionList() for tickerIndex, ticker in enumerate(constants.tickers): if len(constants.interval) &gt; 0: subscriptions.AddEx(ticker, constants.fields, constants.interval, session.CreateCorrelationId(tickerIndex)) else: subscriptions.Add(ticker, constants.fields, session.CreateCorrelationId(tickerIndex)) session.Subscribe(subscriptions) endTime = time() + 2 while True: PumpWaitingMessages() if endTime &lt; time(): break if __name__ == "__main__": aBloombergSource = bloombergSource() </code></pre> <p>constants.py:</p> <pre><code>ADMIN = 1 AUTHORIZATION_STATUS = 11 BLPSERVICE_STATUS = 9 PARTIAL_RESPONSE = 6 PUBLISHING_DATA = 13 REQUEST_STATUS = 4 RESOLUTION_STATUS = 12 RESPONSE = 5 SESSION_STATUS = 2 SUBSCRIPTION_DATA = 8 SUBSCRIPTION_STATUS = 3 TIMEOUT = 10 TOKEN_STATUS = 15 TOPIC_STATUS = 14 UNKNOWN = -1 fields = ['BID'] tickers = ['AUD Curncy'] interval = '' #'interval=5.0' </code></pre> <p>For historical data I used this simple script:</p> <pre><code>import win32com.client session = win32com.client.Dispatch('blpapicom.Session') session.QueueEvents = True session.Start() started = session.OpenService('//blp/refdata') dataService = session.GetService('//blp/refdata') request = dataService.CreateRequest('HistoricalDataRequest') request.GetElement('securities').AppendValue('5 HK Equity') request.GetElement('fields').AppendValue('PX_LAST') request.Set('periodicitySelection', 'DAILY') request.Set('startDate', '20090119') request.Set('endDate', '20090130') cid = session.SendRequest(request) ADMIN = 1 AUTHORIZATION_STATUS = 11 BLPSERVICE_STATUS = 9 PARTIAL_RESPONSE = 6 PUBLISHING_DATA = 13 REQUEST_STATUS = 4 RESOLUTION_STATUS = 12 RESPONSE = 5 SESSION_STATUS = 2 SUBSCRIPTION_DATA = 8 SUBSCRIPTION_STATUS = 3 TIMEOUT = 10 TOKEN_STATUS = 15 TOPIC_STATUS = 14 UNKNOWN = -1 stayHere = True while stayHere: event = session.NextEvent(); if event.EventType == PARTIAL_RESPONSE or event.EventType == RESPONSE: iterator = event.CreateMessageIterator() iterator.Next() message = iterator.Message securityData = message.GetElement('securityData') securityName = securityData.GetElement('security') fieldData = securityData.GetElement('fieldData') returnList = [[0 for col in range(fieldData.GetValue(row).NumValues+1)] for row in range(fieldData.NumValues)] for row in range(fieldData.NumValues): rowField = fieldData.GetValue(row) for col in range(rowField.NumValues+1): colField = rowField.GetElement(col) returnList[row][col] = colField.Value stayHere = False break element = None iterator = None message = None event = None session = None print returnList </code></pre>
1,988,574
How to create an immutable map/set from a seq?
<p>I am try to construct immutable Sets/Maps from a Seq. I am currently doing the following:</p> <pre><code>val input: Seq[(String, Object)] = //..... Map[String, Object]() ++ input </code></pre> <p>and for sets</p> <pre><code>val input: Seq[String] = //..... Set[String]() ++ input </code></pre> <p>Which seems a little convoluted, is there a better way?</p>
1,988,682
2
0
null
2010-01-01 13:22:01.26 UTC
4
2015-11-27 16:39:22.83 UTC
2010-10-22 11:24:09.537 UTC
null
41,956
null
6,365
null
1
31
scala|immutability
29,220
<p>In Scala 2.8:</p> <pre><code>Welcome to Scala version 2.8.0.r20327-b20091230020149 (Java HotSpot(TM) Client VM, Java 1.6. Type in expressions to have them evaluated. Type :help for more information. scala&gt; val seq: Seq[(String,Object)] = ("a","A")::("b","B")::Nil seq: Seq[(String, java.lang.Object)] = List((a,A), (b,B)) scala&gt; val map = Map(seq: _*) map: scala.collection.immutable.Map[String,java.lang.Object] = Map(a -&gt; A, b -&gt; B) scala&gt; val set = Set(seq: _*) set: scala.collection.immutable.Set[(String, java.lang.Object)] = Set((a,A), (b,B)) scala&gt; </code></pre> <p><strong>Edit 2010.1.12</strong></p> <p>I find that there is a more simple way to create set. </p> <pre><code>scala&gt; val seq: Seq[(String,Object)] = ("a","A")::("b","B")::Nil seq: Seq[(String, java.lang.Object)] = List((a,A), (b,B)) scala&gt; val set = seq.toSet set: scala.collection.immutable.Set[(String, java.lang.Object)] = Set((a,A), (b,B)) </code></pre>
1,623,160
Can I turn on extended regular expressions support in Vim?
<p>The characters for extended regular expressions are invaluable; is there a way to turn them on so that I don't have to escape them in my Vim regex, much like the <code>-E</code> flag I can pass to grep(1)?</p>
1,623,299
2
1
null
2009-10-26 05:04:44.21 UTC
16
2014-03-13 13:13:57.897 UTC
null
null
null
null
17,339
null
1
56
regex|vim|command-line
13,551
<p>Do <code>:help magic</code> in vim and you'll see there are four levels (very magic, magic, nomagic, and very nomagic) but only the two central ones can be set globally (the default is magic, and with <code>:set</code> commands you can only toggle between magic and nomagic); start your RE with <code>\v</code> to make all the rest of it "very magic" ("all ASCII characters except '0'-'9', 'a'-'z', 'A'-'Z' and '_' have a special meaning") -- but that applies only to that one specific RE!-)</p>
6,240,139
Highlight text range using JavaScript
<p>I would like to highlight (apply css to) a certain text range, denoted by its start and end position. This is more diffucult than it seems, since there may be other tags within the text, that need to be ignored.</p> <p>Example:</p> <pre><code>&lt;div&gt;abcd&lt;em&gt;efg&lt;/em&gt;hij&lt;/div&gt; </code></pre> <p><code>highlight(2, 6)</code> needs to highlight <code>"cdef</code>" without removing the tag.</p> <p>I have tried already using a TextRange object, but without success.</p> <p>Thanks in advance!</p>
6,242,538
5
3
null
2011-06-05 00:03:43.917 UTC
35
2022-09-08 14:44:40.553 UTC
2011-06-05 01:07:10.83 UTC
null
774,612
null
613,779
null
1
44
javascript|selection|textrange
52,500
<p>Below is a function to set the selection to a pair of character offsets within a particular element. This is naive implementation: it does not take into account any text that may be made invisible (either by CSS or by being inside a <code>&lt;script&gt;</code> or <code>&lt;style&gt;</code> element, for example) and may have browser discrepancies (IE versus everything else) with line breaks, and takes no account of collapsed whitespace (such as 2 or more consecutive space characters collapsing to one visible space on the page). However, it does work for your example in all major browsers.</p> <p>For the other part, the highlighting, I'd suggest using <code>document.execCommand()</code> for that. You can use my function below to set the selection and then call <code>document.execCommand()</code>. You'll need to make the document temporarily editable in non-IE browsers for the command to work. See my answer here for code: <a href="https://stackoverflow.com/questions/2584301/getselection-surroundcontents-across-multiple-tags/2584352#2584352">getSelection &amp; surroundContents across multiple tags</a></p> <p>Here's a jsFiddle example showing the whole thing, working in all major browsers: <a href="http://jsfiddle.net/8mdX4/1211/" rel="noreferrer">http://jsfiddle.net/8mdX4/1211/</a></p> <p>And the selection setting code:</p> <pre><code>function getTextNodesIn(node) { var textNodes = []; if (node.nodeType == 3) { textNodes.push(node); } else { var children = node.childNodes; for (var i = 0, len = children.length; i &lt; len; ++i) { textNodes.push.apply(textNodes, getTextNodesIn(children[i])); } } return textNodes; } function setSelectionRange(el, start, end) { if (document.createRange &amp;&amp; window.getSelection) { var range = document.createRange(); range.selectNodeContents(el); var textNodes = getTextNodesIn(el); var foundStart = false; var charCount = 0, endCharCount; for (var i = 0, textNode; textNode = textNodes[i++]; ) { endCharCount = charCount + textNode.length; if (!foundStart &amp;&amp; start &gt;= charCount &amp;&amp; (start &lt; endCharCount || (start == endCharCount &amp;&amp; i &lt;= textNodes.length))) { range.setStart(textNode, start - charCount); foundStart = true; } if (foundStart &amp;&amp; end &lt;= endCharCount) { range.setEnd(textNode, end - charCount); break; } charCount = endCharCount; } var sel = window.getSelection(); sel.removeAllRanges(); sel.addRange(range); } else if (document.selection &amp;&amp; document.body.createTextRange) { var textRange = document.body.createTextRange(); textRange.moveToElementText(el); textRange.collapse(true); textRange.moveEnd("character", end); textRange.moveStart("character", start); textRange.select(); } } </code></pre>
6,271,856
HTML Table to JSON
<p>I need to take table rows and convert to JSON. </p> <p>Any ideas? I have this code here but it does not work.</p> <pre><code>function tableToJSON(tableID) { return $(tableID + " tr").map(function (row) { return row.descendants().pluck("innerHTML"); }).toJSON(); } </code></pre>
6,271,924
8
2
null
2011-06-07 21:27:57.38 UTC
8
2022-02-18 11:54:21.6 UTC
2011-06-07 21:45:01.137 UTC
null
206,403
null
715,447
null
1
21
jquery|html
56,319
<pre><code>function tableToJson(table) { var data = []; // first row needs to be headers var headers = []; for (var i=0; i&lt;table.rows[0].cells.length; i++) { headers[i] = table.rows[0].cells[i].innerHTML.toLowerCase().replace(/ /gi,''); } // go through cells for (var i=1; i&lt;table.rows.length; i++) { var tableRow = table.rows[i]; var rowData = {}; for (var j=0; j&lt;tableRow.cells.length; j++) { rowData[ headers[j] ] = tableRow.cells[j].innerHTML; } data.push(rowData); } return data; } </code></pre> <p>Taken from <a href="http://johndyer.name/html-table-to-json/" rel="noreferrer">John Dyer's Blog</a></p>
6,178,498
Using grep and sed to find and replace a string
<p>I am using the following to search a directory recursively for specific string and replace it with another:</p> <pre><code>grep -rl oldstr path | xargs sed -i 's/oldstr/newstr/g' </code></pre> <p>This works okay. The only problem is that if the string doesn't exist then <code>sed</code> fails because it doesn't get any arguments. This is a problem for me since i'm running this automatically with ANT and the build fails since <code>sed</code> fails.</p> <p>Is there a way to make it fail-proof in case the string is not found?</p> <p>I'm interested in a one line simple solution I can use (not necessarily with <code>grep</code> or <code>sed</code> but with common unix commands like these).</p>
6,178,522
8
3
null
2011-05-30 16:10:08.09 UTC
32
2020-10-27 04:06:56.127 UTC
2014-01-28 00:59:20.6 UTC
null
599,912
null
599,912
null
1
74
linux|shell|unix|sed|grep
139,796
<p>You can use <code>find</code> and <code>-exec</code> directly into <code>sed</code> rather than first locating <code>oldstr</code> with <code>grep</code>. It's maybe a bit less efficient, but that might not be important. This way, the <code>sed</code> replacement is executed over all files listed by <code>find</code>, but if <code>oldstr</code> isn't there it obviously won't operate on it.</p> <pre><code>find /path -type f -exec sed -i 's/oldstr/newstr/g' {} \; </code></pre>
5,852,767
Possible to defer loading of jQuery?
<p>Let's face it, jQuery/jQuery-ui is a heavy download.</p> <p>Google recommends <a href="http://code.google.com/speed/page-speed/docs/payload.html#DeferLoadingJS" rel="noreferrer">deferred loading of JavaScript</a> to speed up initial rendering. My page uses jQuery to set up some tabs which are placed low on the page (mostly out of initial view) and I'd like to defer jQuery until AFTER the page has rendered.</p> <p>Google's deferral code adds a tag to the DOM after the page loads by hooking into the body onLoad event:</p> <pre><code>&lt;script type="text/javascript"&gt; // Add a script element as a child of the body function downloadJSAtOnload() { var element = document.createElement("script"); element.src = "deferredfunctions.js"; document.body.appendChild(element); } // Check for browser support of event handling capability if (window.addEventListener) window.addEventListener("load", downloadJSAtOnload, false); else if (window.attachEvent) window.attachEvent("onload", downloadJSAtOnload); else window.onload = downloadJSAtOnload; &lt;/script&gt; </code></pre> <p>I'd like to defer loading of jQuery this way, but when I tried it my jQuery code failed to find jQuery (not completely unexpected on my part):</p> <pre><code>$(document).ready(function() { $("#tabs").tabs(); }); </code></pre> <p>So, it seems I need to find a way to defer execution of my jQuery code until jQuery is loaded. How do I detect that the added tag has finished loading and parsing?</p> <p>As a corollary, it appears that <a href="http://code.google.com/speed/page-speed/docs/rtt.html#PreferAsyncResources" rel="noreferrer">asynchronous loading</a> may also contain an answer.</p> <p>Any thoughts?</p>
5,853,358
17
6
null
2011-05-02 01:34:00.523 UTC
39
2021-12-01 07:15:55.473 UTC
2011-05-02 02:25:22.213 UTC
null
733,805
null
733,805
null
1
73
javascript|jquery|pagespeed
68,061
<p>Try this, which is something I edited a while ago from the jQuerify bookmarklet. I use it frequently to load jQuery and execute stuff after it's loaded. You can of course replace the url there with your own url to your customized jquery. </p> <pre><code>(function() {   function getScript(url,success){     var script=document.createElement('script');     script.src=url;     var head=document.getElementsByTagName('head')[0],         done=false;     script.onload=script.onreadystatechange = function(){       if ( !done &amp;&amp; (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete') ) {         done=true;         success();         script.onload = script.onreadystatechange = null;         head.removeChild(script);       }     };     head.appendChild(script);   } getScript('http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js',function(){ // YOUR CODE GOES HERE AND IS EXECUTED AFTER JQUERY LOADS }); })(); </code></pre> <p>I would really combine jQuery and jQuery-UI into one file and use a url to it. If you REALLY wanted to load them separately, just chain the getScripts:</p> <pre><code>getScript('http://myurltojquery.js',function(){ getScript('http://myurltojqueryUI.js',function(){ //your tab code here }) }); </code></pre>
55,991,641
npm test -- --coverage never exits
<p>I am using <strong>create-react-app</strong> to create a react application. When I executes <strong>npm test -- --coverage</strong> the test never exists. npm test actually runs <strong>react-scripts test</strong>. Any Idea?</p> <p><a href="https://i.stack.imgur.com/ooy7Y.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ooy7Y.png" alt="enter image description here"></a></p>
56,917,151
5
7
null
2019-05-05 11:54:45.743 UTC
8
2021-12-01 09:13:12.41 UTC
null
null
null
null
1,182,658
null
1
28
node.js|reactjs|unit-testing|continuous-integration|frontend
45,135
<p><code>-- --coverage</code> part won't work, and should use one of the commands below to set <code>CI</code> to <code>true</code>.</p> <blockquote> <p>By default npm test runs the watcher with interactive CLI. However, you can force it to run tests once and finish the process by setting an environment variable called CI.</p> </blockquote> <p><a href="https://facebook.github.io/create-react-app/docs/running-tests#on-your-own-environment" rel="noreferrer"><strong>source: React docs</strong></a></p> <h3>Windows (cmd.exe)</h3> <ul> <li><p><code>set CI=true &amp;&amp; npm test</code></p> </li> <li><p><code>set CI=true &amp;&amp; npm run build</code></p> </li> </ul> <h3>Windows (Powershell)</h3> <ul> <li><p><code>($env:CI = &quot;true&quot;) -and (npm test)</code></p> </li> <li><p><code>($env:CI = &quot;true&quot;) -and (npm run build)</code></p> </li> </ul> <h3>Linux, macOS (Bash)</h3> <ul> <li><p><code>CI=true npm test</code></p> </li> <li><p><code>CI=true npm run build</code></p> </li> </ul> <hr /> <p><em>NOT included in the docs</em></p> <h3>For Docker (node and react):</h3> <p><code>docker run -e CI=true [myImage] npm run test</code></p>
39,213,386
TypeError: Cannot read property 'valid' of undefined
<p>I have the following textarea:</p> <pre><code>&lt;textarea class="form-control" [(ngModel)]="content" name="content" required&gt; &lt;/textarea&gt; </code></pre> <p>and the following submit button:</p> <pre><code> &lt;button type="submit" class="btn btn-default" [disabled]="content.valid"&gt;New comment&lt;/button&gt; </code></pre> <p>As I saw in the angular 2 form guide (<a href="https://angular.io/docs/ts/latest/guide/forms.html">https://angular.io/docs/ts/latest/guide/forms.html</a>) I can use the <code>x.valid</code> in order to check if it's not empty.</p> <p>Why do I get <code>TypeError: Cannot read property 'valid' of undefined</code> error?</p>
39,213,598
5
2
null
2016-08-29 19:04:16.547 UTC
4
2020-08-08 15:56:58.75 UTC
null
null
null
null
3,669,981
null
1
27
angular
76,705
<p>In your case <strong>content</strong> is a property on your model.</p> <p>In order to do what you want you need to use a <a href="https://angular.io/docs/ts/latest/guide/template-syntax.html#!#ref-vars">template reference value</a> for the form control <em>#myControl="ngModel"</em> and then you have access to the valid property: <em>myControl.valid</em>.</p> <p>So in your example:</p> <pre><code>&lt;textarea class="form-control" [(ngModel)]="content" name="content" required #myControl="ngModel"&gt; &lt;/textarea&gt; </code></pre> <p>And use it in the button tag:</p> <pre><code>&lt;button type="submit" class="btn btn-default" [disabled]="myControl.valid"&gt;New comment&lt;/button&gt; </code></pre>
14,281,370
vb.net Picture box with a .png with a transparent background loaded in it?
<p>Ive got a .png file called donkey1.png - it has a transparent background and I have loaded it into a picturebox called pcbDonkey1 - I have changed the properties of the picturebox to have the backcolor transparent - This does not work as it still crosses over another image and has a white background.</p> <p>I've heard about using GDI to draw this image so it will have a transparent image and be able to cross the over image without the white background.</p> <p>How would you do this?</p> <p>Thanks</p>
14,281,480
2
0
null
2013-01-11 15:30:53.587 UTC
1
2013-06-18 21:00:57.11 UTC
null
null
null
null
1,800,140
null
1
2
vb.net|image|transparent
44,264
<p>Unless you need the PixtureBox control for something more than displaying an image, you can draw the image directly to the form in the Paint event:</p> <p>Example (you will need to calculate aspect ratio etc., but in principle):</p> <pre><code>Sub Form_Paint(s as Object, e as PaintEventArgs) Handles Me.OnPaint Dim r As New Rectangle(myX, myY, myWidth, myHeight) e.graphics.DrawImage(myImage, r) End Sub </code></pre>
49,127,332
NullInjectorError: No provider for ReducerManager
<p>I am using the new ngrx 5. This is the file that holds the reducers and the featureSelector:</p> <pre><code>import AppState from '../interfaces/app.state' import { ActionReducerMap, createFeatureSelector } from '@ngrx/store' import { partnerReducer } from './partner.reducer' export const reducers: ActionReducerMap&lt;AppState&gt; = { partnerState: partnerReducer } export const getAppState = createFeatureSelector&lt;AppState&gt;('appState') </code></pre> <p>This is how I am importing the storeModule</p> <pre><code>@NgModule({ declarations: [...], imports: [... RouterModule.forRoot(ROUTES), StoreModule.forFeature('appState', reducers) ], providers: [...], bootstrap: [AppComponent], entryComponents: [...] }) export class AppModule { } </code></pre> <p>I have followed <a href="https://toddmotto.com/ngrx-store-understanding-state-selectors" rel="noreferrer">this</a> tutorial</p> <p>When I run the app, I get the following error:</p> <pre><code>"StaticInjectorError(AppModule)[StoreFeatureModule -&gt; ReducerManager]: \n StaticInjectorError(Platform: core)[StoreFeatureModule -&gt; ReducerManager]: \n NullInjectorError: No provider for ReducerManager!" </code></pre> <p>But if I do provide ReducerManager in the providers, I get this error:</p> <pre><code>No provider for ReducerManagerDispatcher! </code></pre>
49,127,617
2
2
null
2018-03-06 09:23:54.977 UTC
null
2020-03-13 14:35:56.547 UTC
null
null
null
null
5,512,020
null
1
28
angular|ngrx-store|ngrx-store-4.0
25,560
<p>Managed to solve this by adding <code>StoreModule.forRoot({}),</code> in the imports. </p> <blockquote> <p>StoreModule.forRoot should only be called once in the root of your project NgModule. If you wan't to register a feature, use StoreModule.forFeature. Using forRoot registers the global providers needed for Store.</p> </blockquote> <p>Check the github discussion <a href="https://github.com/ngrx/platform/issues/295" rel="noreferrer">here</a> on this issue. The above reason was stated in the same discussion</p>
21,748,790
How to send a message from Android to Windows using USB
<p>I am a complete noob at Android, only at the level of basic (1 or 2 line) Activities activated by buttons, but I would like to create a really simple app that, when I tap the app icon, it fires and forgets a message to a listening server on my Windows 8 PC. The phone is connected as a simple media device, without Kies, via a USB cable.</p> <p>I can get as far as a message box lying and saying the message was sent. I need to know what kind of comms channel to use, e.g. a COM port or what, and how to send data over that from Android. On the Windows side, once I've established how to communicate, I can help myself.</p>
21,749,521
2
1
null
2014-02-13 08:29:00.103 UTC
12
2018-02-25 19:51:32.15 UTC
null
null
null
null
8,741
null
1
13
android|usb|serial-communication
10,994
<p>starting with the desktop side of this application: You can use the ADB (Android debug bridge) to establish a tcp/ip socket connection via port between the device and desktop. The command is :</p> <pre><code>adb forward tcp:&lt;port-number&gt; tcp:&lt;port-number&gt; </code></pre> <p>to run this command in your java program, you will have to create a process builder wherein this command ets executed on a child shell.</p> <p>For windows you may need to use:</p> <pre><code>process=Runtime.getRuntime().exec("D:\\Android\\adt-bundle-windows-x86_64-20130729\\sdk\\platform-tools\\adb.exe forward tcp:38300 tcp:38300"); sc = new Scanner(process.getErrorStream()); if (sc.hasNext()) { while (sc.hasNext()) System.out.print(sc.next()+" "); System.out.println("\nCannot start the Android debug bridge"); } sc.close(); } </code></pre> <p>The function required to execute adb commands :</p> <pre><code>String[] commands = new String[]{"/bin/sh","-c", command}; try { Process proc = new ProcessBuilder(commands).start(); BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream())); BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream())); String s = null; while ((s = stdInput.readLine()) != null) { sb.append(s); sb.append("\n"); } while ((s = stdError.readLine()) != null) { sb.append(s); sb.append("\n"); } } catch (IOException e) { e.printStackTrace(); } </code></pre> <p>Above method will take the above command as a string and execute it on a child shell</p> <pre><code> //Extracting Device Id through ADB device_list=CommandExecutor.execute("adb devices").split("\\r?\\n"); System.out.println(device_list); if(device_list.length&gt;1) { if(device_list[1].matches(".*\\d.*")) { device_id=device_list[1].split("\\s+"); device_name=""+CommandExecutor.execute("adb -s "+device_id[0]+" shell getprop ro.product.manufacturer")+CommandExecutor.execute("adb -s "+device_id[0]+" shell getprop ro.product.model"); device_name=device_name.replaceAll("\\s+"," "); System.out.println("\n"+device_name+" : "+device_id[0]); device=device_id[0]; System.out.println("\n"+device); } else { System.out.println("Please attach a device"); } } else { System.out.println("Please attach a device"); } </code></pre> <p>CommandExecutor is a class which has the execute method in it. The code of the execute method is the same as posted above. This will check if any device is connected and if it connected, it will return it unique id number.</p> <p>It is preferable to use id number while executing adb commands like :</p> <pre><code>adb -s "+device_id[0]+" shell getprop ro.product.manufacturer </code></pre> <p>OR</p> <pre><code>adb -s &lt;put-id-here&gt; shell getprop ro.product.manufacturer </code></pre> <p>Note that '-s' is necesarry after adb.</p> <p>Then using adb forward commnd you need to establish a tcp/ip socket. Here the desktop will be the client and mobile/device will be the server.</p> <pre><code>//Create socket connection try{ socket = new Socket("localhost", 38300); System.out.println("Socket Created"); out = new PrintWriter(socket.getOutputStream(), true); out.println("Hey Server!\n"); new Thread(readFromServer).start(); Thread closeSocketOnShutdown = new Thread() { public void run() { try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } }; Runtime.getRuntime().addShutdownHook(closeSocketOnShutdown); } catch (UnknownHostException e) { System.out.println("Socket connection problem (Unknown host)"+e.getStackTrace()); } catch (IOException e) { System.out.println("Could not initialize I/O on socket "+e.getStackTrace()); } </code></pre> <p>Then you need read from the server i.e. the device :</p> <pre><code>private Runnable readFromServer = new Runnable() { @Override public void run() { try { System.out.println("Reading From Server"); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); while ((buffer=in.readLine())!=null) { System.out.println(buffer); }catch (IOException e) { try { in.close(); } catch (IOException e1) { e1.printStackTrace(); } e.printStackTrace(); } } </code></pre> <p>The 'buffer' will contain what device will send from its end of the app.</p> <p>Now in your mobile application,you will need to open the same connection and siple write data to it out buffer</p> <pre><code>public class TcpConnection implements Runnable { public static final int TIMEOUT=10; private String connectionStatus=null; private Handler mHandler; private ServerSocket server=null; private Context context; private Socket client=null; private String line=""; BufferedReader socketIn; PrintWriter socketOut; public TcpConnection(Context c) { // TODO Auto-generated constructor stub context=c; mHandler=new Handler(); } @Override public void run() { // TODO Auto-generated method stub // initialize server socket try { server = new ServerSocket(38300); server.setSoTimeout(TIMEOUT*1000); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } //attempt to accept a connection try{ client = server.accept(); socketOut = new PrintWriter(client.getOutputStream(), true); socketOut.println("Hey Client!\n"); socketOut.flush(); syncContacts(); Thread readThread = new Thread(readFromClient); readThread.setPriority(Thread.MAX_PRIORITY); readThread.start(); Log.e(TAG, "Sent"); } catch (SocketTimeoutException e) { // print out TIMEOUT connectionStatus="Connection has timed out! Please try again"; mHandler.post(showConnectionStatus); try { server.close(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } catch (IOException e) { Log.e(TAG, ""+e); } if (client!=null) { try{ // print out success connectionStatus="Connection succesful!"; Log.e(TAG, connectionStatus); mHandler.post(showConnectionStatus); } catch(Exception e) { e.printStackTrace(); } } } private Runnable readFromClient = new Runnable() { @Override public void run() { // TODO Auto-generated method stub try { Log.e(TAG, "Reading from server"); socketIn=new BufferedReader(new InputStreamReader(client.getInputStream())); while ((line = socketIn.readLine()) != null) { Log.d("ServerActivity", line); //Do something with line } socketIn.close(); closeAll(); Log.e(TAG, "OUT OF WHILE"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }; public void closeAll() { // TODO Auto-generated method stub try { Log.e(TAG, "Closing All"); socketOut.close(); client.close(); server.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private Runnable showConnectionStatus = new Runnable() { public void run() { try { Toast.makeText(context, connectionStatus, Toast.LENGTH_SHORT).show(); } catch(Exception e) { e.printStackTrace(); } } }; } } </code></pre>
9,620,050
List all files (with full paths) in a directory (and subdirectories), order by access time
<p>I'd like to construct a Linux command to list all files (with their full paths) within a specific directory (and subdirectories) ordered by access time.</p> <p>ls can order by access time, but doesn't give the full path. find gives the full path, but the only control you have over the access time is to specify a range with -atime N (accessed at least 24*N hours ago), which isn't what I want.</p> <p>Is there a way to order by access time and get the full path at once? I could just write a script, but it seems there should be a way to do this with the standard Linux programs.</p>
9,621,001
5
0
null
2012-03-08 15:21:17.183 UTC
5
2016-07-01 13:31:57.677 UTC
null
null
null
null
871,765
null
1
21
linux|bash|find|ls
68,310
<pre><code>find . -type f -exec ls -l {} \; 2&gt; /dev/null | sort -t' ' -k +6,6 -k +7,7 </code></pre> <p>This will find all files, and sort them by date and then time. You can then use <code>awk</code> or <code>cut</code> to extract the dates and files name from the <code>ls -l</code> output</p>
9,060,269
Find time in milliseconds using PowerShell?
<p>How can I find the time in milliseconds using PowerShell?</p>
9,060,395
5
0
null
2012-01-30 06:42:00.37 UTC
2
2021-06-22 04:31:52.213 UTC
2018-10-30 15:04:26.193 UTC
null
63,550
null
941,939
null
1
26
powershell|timespan
71,403
<p>In PowerShell you can cast a time value to a timespan and call the <a href="https://docs.microsoft.com/en-us/dotnet/api/system.timespan.totalmilliseconds?view=netframework-4.7.2" rel="noreferrer">TotalMilliseconds</a> method:</p> <pre><code>([TimeSpan]"00:05:00").TotalMilliseconds # Returns 300000 ([TimeSpan] (Get-Date).ToShortTimeString()).TotalMilliseconds # Returns total milliseconds from 00:00:00 till now </code></pre>
9,204,767
How much delay of ios push notification?
<p>I want to add a fire alarm function to my app. I think the push notification may be the best choice. But if there is much delay, like over 10 mins, it would be meaningless for fire alarm. So how much delay for push notification, assuming the device is online?</p>
9,204,776
1
0
null
2012-02-09 02:52:24.963 UTC
11
2018-05-05 06:41:06.997 UTC
2012-02-22 23:20:43.15 UTC
null
445,236
null
1,184,525
null
1
26
ios
33,470
<p>Push notifications are unreliable and cannot be guaranteed that they have been delivered. It all depends on the apple APNS server, that said, <strong>usually when I send a push notification I get the result in under a few seconds</strong>. </p> <p>More Information:</p> <p>They are not reliable! There is no guarantee that push notifications will actually be delivered, even if the APNS server accepted them.</p> <p>As far as your server is concerned, push notifications are fire-and-forget; there is no way to find out what the status of a notification is after you’ve sent it to APNS. The delivery time may also vary, from seconds up to half an hour.</p> <p>Also, the user’s iPhone may not be able to receive push notifications all the time. They could be on a WiFi network that does not allow connections to be made to APNS because the required ports are blocked. Or the phone could be turned off.</p> <p>APNS will try to deliver the last notification it received for that device when it comes back online, but it will only try for a limited time. Once it times out, the push notification will be lost forever!</p> <p>Source: <a href="http://www.raywenderlich.com/3443/apple-push-notification-services-tutorial-part-12" rel="noreferrer">http://www.raywenderlich.com/3443/apple-push-notification-services-tutorial-part-12</a></p>
9,199,415
getting first node in xpath result set
<p>I am trying to select the first element in a set of resulting nodes after executing an xpath query.</p> <p>When I do this:</p> <pre><code>//dl </code></pre> <p>I get the following result set:</p> <pre><code>[&lt;dl&gt;​…​&lt;/dl&gt;​, &lt;dl&gt;​…​&lt;/dl&gt;​] </code></pre> <p>How can I get the first one? Neither of these work:</p> <pre><code>//dl[1] //dl[position()=1] </code></pre> <p>I am executing this in Chrome's Web Inspector.</p>
9,199,574
1
0
null
2012-02-08 18:39:23.653 UTC
7
2014-04-10 21:16:34.787 UTC
2014-04-10 21:11:16.78 UTC
null
592,746
null
211,983
null
1
39
xpath
36,005
<p>Use the following: </p> <pre><code>(//dl)[1] </code></pre> <p>The parentheses are significant. You want the first node that results from <code>//dl</code> (not the set of <code>dl</code> elements that are the first child of their parent (which is what <code>//dl[1]</code> (no parens) returns)).</p> <p>This is easier to see when one realizes that <code>//</code> is shorthand for (i.e. expands fully to) <code>/descendant-or-self::node()/</code> so that <code>//dl[1]</code> is equivalent to:</p> <pre><code>/descendant-or-self::node()/dl[1] </code></pre> <p>...which is more obviously not what you want. Instead, you're looking for:</p> <pre><code>(/descendant-or-self::node()/dl)[1] </code></pre>
52,423,595
mysqldump: Couldn't execute. Unknown table 'column_statistics' in information_schema
<p>I want to dump my database, even after following correct syntax it thows me following error. </p> <p>Syntax I used : </p> <p><code>mysqldump -uroot -p omnichannel_store_india &gt; omnichannel_store_india.sql</code></p> <p><strong>Throws errors :</strong></p> <blockquote> <p>mysqldump: Couldn't execute 'SELECT COLUMN_NAME, JSON_EXTRACT(HISTOGRAM, '$."number-of-buckets-specified"') FROM information_schema.COLUMN_STATISTICS WHERE SCHEMA_NAME = 'omnichannel_store_india' AND TABLE_NAME = 'consignment_items';': </p> </blockquote> <p><strong>Unknown table 'column_statistics' in information_schema (1109)</strong></p>
52,423,596
3
1
null
2018-09-20 11:00:01.183 UTC
12
2022-05-18 15:34:28.523 UTC
2018-09-20 11:43:08.107 UTC
null
7,991,369
null
2,745,436
null
1
63
mysql
34,179
<p>This is due to a flag <code>column-statistics</code> that is enabled by default in mysqldump 8. You can disable it by adding <code>--column-statistics=0</code>.</p> <p>The command will be something like:</p> <pre><code>mysqldump --column-statistics=0 --host=&lt;server&gt; --user &lt;user&gt; --password &lt;securepass&gt; </code></pre> <p>To disable column statistics by default, you can add the following in a MySQL config file, such as <code>/etc/my.cnf</code> or <code>~/.my.cnf</code>.</p> <pre><code>[mysqldump] column-statistics=0 </code></pre> <p>It's brilliantly working for me.</p> <p>More details about <code>column-statistics</code>:</p> <blockquote> <p>Add ANALYZE TABLE statements to the output to generate histogram statistics for dumped tables when the dump file is reloaded. This option is disabled by default because histogram generation for large tables can take a long time.</p> </blockquote> <p>Ref: <a href="https://dev.mysql.com/doc/refman/8.0/en/mysqldump.html#option_mysqldump_column-statistics" rel="noreferrer">MySQL official documentaion link</a></p>
10,426,557
Missing Maven Plugin Jetty
<p>I am having trouble folowing this <a href="http://hrycan.com/2012/03/28/primefaces-lazy-loading-datatable-for-jsf2/" rel="noreferrer">http://hrycan.com/2012/03/28/primefaces-lazy-loading-datatable-for-jsf2/</a></p> <p>It says I should just run</p> <pre><code>mvn jetty:run </code></pre> <p>but I keep on encountering this error.</p> <pre><code>org.apache.maven.plugin.prefix.NoPluginFoundForPrefixException: No plugin found for prefix 'jetty' in the current project and in the plugin groups [org.apache.m aven.plugins, org.codehaus.mojo] available from the repositories [local (C:\MyRepo), central (http://repo1.maven.org/maven2)] at org.apache.maven.plugin.prefix.internal.DefaultPluginPrefixResolver.r </code></pre> <p>I used Maven 3 here.</p> <p>Any thoughts?</p> <p>ADD:</p> <p>From the link, it has this already in the pom.xml</p> <pre class="lang-xml prettyprint-override"><code>&lt;plugin&gt; &lt;groupId&gt;org.mortbay.jetty&lt;/groupId&gt; &lt;artifactId&gt;jetty-maven-plugin&lt;/artifactId&gt; &lt;version&gt;7.5.1.v20110908&lt;/version&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;mysql&lt;/groupId&gt; &lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt; &lt;version&gt;${mysql.version}&lt;/version&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;/plugin&gt; </code></pre>
10,426,603
7
1
null
2012-05-03 06:56:18.177 UTC
2
2019-03-04 13:47:12.28 UTC
2015-05-18 16:10:06.227 UTC
null
1,047,365
null
373,784
null
1
15
maven-plugin|maven-3
50,603
<p>Did you add the plugin to the pom.xml? A quick google search found this:</p> <pre class="lang-xml prettyprint-override"><code>&lt;project&gt; ... &lt;build&gt; ... &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.codehaus.mojo&lt;/groupId&gt; &lt;artifactId&gt;jetty-maven-plugin&lt;/artifactId&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; &lt;/project&gt; </code></pre> <p>Found here: <a href="http://mojo.codehaus.org/jetty-maven-plugin/usage.html" rel="nofollow">http://mojo.codehaus.org/jetty-maven-plugin/usage.html</a></p>
31,847,682
How to compute skipgrams in python?
<p>A k <a href="http://homepages.inf.ed.ac.uk/ballison/pdf/lrec_skipgrams.pdf" rel="noreferrer">skipgram</a> is an ngram which is a superset of all ngrams and each (k-i )skipgram till (k-i)==0 (which includes 0 skip grams). So how to efficiently compute these skipgrams in python?</p> <p>Following is the code i tried but it is not doing as expected:</p> <pre><code>&lt;pre&gt; input_list = ['all', 'this', 'happened', 'more', 'or', 'less'] def find_skipgrams(input_list, N,K): bigram_list = [] nlist=[] K=1 for k in range(K+1): for i in range(len(input_list)-1): if i+k+1&lt;len(input_list): nlist=[] for j in range(N+1): if i+k+j+1&lt;len(input_list): nlist.append(input_list[i+k+j+1]) bigram_list.append(nlist) return bigram_list &lt;/pre&gt; </code></pre> <p>The above code is not rendering correctly, but print <code>find_skipgrams(['all', 'this', 'happened', 'more', 'or', 'less'],2,1)</code> gives following output</p> <blockquote> <p>[['this', 'happened', 'more'], ['happened', 'more', 'or'], ['more', 'or', 'less'], ['or', 'less'], ['less'], ['happened', 'more', 'or'], ['more', 'or', 'less'], ['or', 'less'], ['less'], ['less']]</p> </blockquote> <p>The code listed here also does not give correct output: <a href="https://github.com/heaven00/skipgram/blob/master/skipgram.py" rel="noreferrer">https://github.com/heaven00/skipgram/blob/master/skipgram.py</a></p> <p>print skipgram_ndarray("What is your name") gives: ['What,is', 'is,your', 'your,name', 'name,', 'What,your', 'is,name']</p> <p>name is a unigram!</p>
31,886,292
5
2
null
2015-08-06 05:44:34.463 UTC
9
2018-01-16 07:42:04.657 UTC
2015-10-18 00:14:36.327 UTC
null
395,857
null
2,305,993
null
1
20
python|nlp|n-gram|language-model
12,408
<p>From the <a href="http://homepages.inf.ed.ac.uk/ballison/pdf/lrec_skipgrams.pdf">paper</a> that OP links, the following string:</p> <blockquote> <p>Insurgents killed in ongoing fighting</p> </blockquote> <p>Yields:</p> <blockquote> <p>2-skip-bi-grams = {insurgents killed, insurgents in, insurgents ongoing, killed in, killed ongoing, killed fighting, in ongoing, in fighting, ongoing fighting}</p> <p>2-skip-tri-grams = {insurgents killed in, insurgents killed ongoing, insurgents killed fighting, insurgents in ongoing, insurgents in fighting, insurgents ongoing fighting, killed in ongoing, killed in fighting, killed ongoing fighting, in ongoing fighting}.</p> </blockquote> <p>With slight modification to NLTK's <code>ngrams</code> code (<a href="https://github.com/nltk/nltk/blob/develop/nltk/util.py#L383">https://github.com/nltk/nltk/blob/develop/nltk/util.py#L383</a>):</p> <pre><code>from itertools import chain, combinations import copy from nltk.util import ngrams def pad_sequence(sequence, n, pad_left=False, pad_right=False, pad_symbol=None): if pad_left: sequence = chain((pad_symbol,) * (n-1), sequence) if pad_right: sequence = chain(sequence, (pad_symbol,) * (n-1)) return sequence def skipgrams(sequence, n, k, pad_left=False, pad_right=False, pad_symbol=None): sequence_length = len(sequence) sequence = iter(sequence) sequence = pad_sequence(sequence, n, pad_left, pad_right, pad_symbol) if sequence_length + pad_left + pad_right &lt; k: raise Exception("The length of sentence + padding(s) &lt; skip") if n &lt; k: raise Exception("Degree of Ngrams (n) needs to be bigger than skip (k)") history = [] nk = n+k # Return point for recursion. if nk &lt; 1: return # If n+k longer than sequence, reduce k by 1 and recur elif nk &gt; sequence_length: for ng in skipgrams(list(sequence), n, k-1): yield ng while nk &gt; 1: # Collects the first instance of n+k length history history.append(next(sequence)) nk -= 1 # Iterative drop first item in history and picks up the next # while yielding skipgrams for each iteration. for item in sequence: history.append(item) current_token = history.pop(0) # Iterates through the rest of the history and # pick out all combinations the n-1grams for idx in list(combinations(range(len(history)), n-1)): ng = [current_token] for _id in idx: ng.append(history[_id]) yield tuple(ng) # Recursively yield the skigrams for the rest of seqeunce where # len(sequence) &lt; n+k for ng in list(skipgrams(history, n, k-1)): yield ng </code></pre> <p>Let's do some doctest to match the example in the paper:</p> <pre><code>&gt;&gt;&gt; two_skip_bigrams = list(skipgrams(text, n=2, k=2)) [('Insurgents', 'killed'), ('Insurgents', 'in'), ('Insurgents', 'ongoing'), ('killed', 'in'), ('killed', 'ongoing'), ('killed', 'fighting'), ('in', 'ongoing'), ('in', 'fighting'), ('ongoing', 'fighting')] &gt;&gt;&gt; two_skip_trigrams = list(skipgrams(text, n=3, k=2)) [('Insurgents', 'killed', 'in'), ('Insurgents', 'killed', 'ongoing'), ('Insurgents', 'killed', 'fighting'), ('Insurgents', 'in', 'ongoing'), ('Insurgents', 'in', 'fighting'), ('Insurgents', 'ongoing', 'fighting'), ('killed', 'in', 'ongoing'), ('killed', 'in', 'fighting'), ('killed', 'ongoing', 'fighting'), ('in', 'ongoing', 'fighting')] </code></pre> <p>But do note that if <code>n+k &gt; len(sequence)</code>, it will yield the same effects as <code>skipgrams(sequence, n, k-1)</code> (this is not a bug, it's a fail safe feature), e.g.</p> <pre><code>&gt;&gt;&gt; three_skip_trigrams = list(skipgrams(text, n=3, k=3)) &gt;&gt;&gt; three_skip_fourgrams = list(skipgrams(text, n=4, k=3)) &gt;&gt;&gt; four_skip_fourgrams = list(skipgrams(text, n=4, k=4)) &gt;&gt;&gt; four_skip_fivegrams = list(skipgrams(text, n=5, k=4)) &gt;&gt;&gt; &gt;&gt;&gt; print len(three_skip_trigrams), three_skip_trigrams 10 [('Insurgents', 'killed', 'in'), ('Insurgents', 'killed', 'ongoing'), ('Insurgents', 'killed', 'fighting'), ('Insurgents', 'in', 'ongoing'), ('Insurgents', 'in', 'fighting'), ('Insurgents', 'ongoing', 'fighting'), ('killed', 'in', 'ongoing'), ('killed', 'in', 'fighting'), ('killed', 'ongoing', 'fighting'), ('in', 'ongoing', 'fighting')] &gt;&gt;&gt; print len(three_skip_fourgrams), three_skip_fourgrams 5 [('Insurgents', 'killed', 'in', 'ongoing'), ('Insurgents', 'killed', 'in', 'fighting'), ('Insurgents', 'killed', 'ongoing', 'fighting'), ('Insurgents', 'in', 'ongoing', 'fighting'), ('killed', 'in', 'ongoing', 'fighting')] &gt;&gt;&gt; print len(four_skip_fourgrams), four_skip_fourgrams 5 [('Insurgents', 'killed', 'in', 'ongoing'), ('Insurgents', 'killed', 'in', 'fighting'), ('Insurgents', 'killed', 'ongoing', 'fighting'), ('Insurgents', 'in', 'ongoing', 'fighting'), ('killed', 'in', 'ongoing', 'fighting')] &gt;&gt;&gt; print len(four_skip_fivegrams), four_skip_fivegrams 1 [('Insurgents', 'killed', 'in', 'ongoing', 'fighting')] </code></pre> <p>This allows <code>n == k</code> but it disallow <code>n &gt; k</code> as shown in the lines :</p> <pre><code>if n &lt; k: raise Exception("Degree of Ngrams (n) needs to be bigger than skip (k)") </code></pre> <hr> <p>For understanding sake, let's try to understand the "mystical" line:</p> <pre><code>for idx in list(combinations(range(len(history)), n-1)): pass # Do something </code></pre> <p>Given a list of unique items, combinations produce this:</p> <pre><code>&gt;&gt;&gt; from itertools import combinations &gt;&gt;&gt; x = [0,1,2,3,4,5] &gt;&gt;&gt; list(combinations(x,2)) [(0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 5)] </code></pre> <p>And since the indices of a list of tokens is always unique, e.g. </p> <pre><code>&gt;&gt;&gt; sent = ['this', 'is', 'a', 'foo', 'bar'] &gt;&gt;&gt; current_token = sent.pop(0) # i.e. 'this' &gt;&gt;&gt; range(len(sent)) [0,1,2,3] </code></pre> <p>It's possible to compute the possible <a href="https://docs.python.org/2/library/itertools.html#itertools.combinations">combinations (without replacement)</a> of the range:</p> <pre><code>&gt;&gt;&gt; n = 3 &gt;&gt;&gt; list(combinations(range(len(sent)), n-1)) [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)] </code></pre> <p>If we map the indices back to the list of tokens:</p> <pre><code>&gt;&gt;&gt; [tuple(sent[id] for id in idx) for idx in combinations(range(len(sent)), 2) [('is', 'a'), ('is', 'foo'), ('is', 'bar'), ('a', 'foo'), ('a', 'bar'), ('foo', 'bar')] </code></pre> <p>Then we concatenate with the <code>current_token</code>, we get the skipgrams for the current token and context+skip window:</p> <pre><code>&gt;&gt;&gt; [tuple([current_token]) + tuple(sent[id] for id in idx) for idx in combinations(range(len(sent)), 2)] [('this', 'is', 'a'), ('this', 'is', 'foo'), ('this', 'is', 'bar'), ('this', 'a', 'foo'), ('this', 'a', 'bar'), ('this', 'foo', 'bar')] </code></pre> <p>So after that we move on to the next word.</p>
58,198,544
Angular - DialogRef - Unsubscribe - Do I need to unsubscribe from afterClosed?
<p>I got asked by one of my colleagues if we need to unsubscribe from the afterClosed() Observable of a Dialog.</p> <p>We are using the takeUntil pattern to unsubscribe from all Observables on ngOnDestroy().</p> <pre><code>this.backEvent = fromEvent(window, 'popstate') .pipe( takeUntil(this.destroy$) ) .subscribe( () =&gt; { this.navigationService.backClicked = true; this.navigationService.navigateBackToDirectoryCenter(); } ); </code></pre> <p>ngOnDestroy()</p> <pre><code>ngOnDestroy() { this.destroy$.next(); this.destroy$.complete(); } </code></pre> <p>So is it necessary to unsubscribe from afterClosed() Observable?</p> <pre><code>dialogRef.afterClosed().subscribe( (data) =&gt; { console.log(data); } }, ); </code></pre> <p>or?</p> <pre><code>dialogRef.afterClosed() .pipe( takeUntil(this.destroy$) ) .subscribe( (data) =&gt; { console.log(data); }, ); </code></pre>
58,199,099
3
2
null
2019-10-02 09:13:12.497 UTC
3
2021-07-20 11:37:00.887 UTC
null
null
null
null
5,677,688
null
1
47
angular|rxjs|unsubscribe
11,431
<h1>No</h1> <p>You don't need to unsubscribe as the observable itself completes.You can verify the same by adding a finalize block to see whether observable completes itself or not.</p> <pre class="lang-js prettyprint-override"><code>import { finalize } from &quot;rxjs/operators&quot;; </code></pre> <pre class="lang-js prettyprint-override"><code>dialogRef .afterClosed() .pipe(finalize(() =&gt; console.log(&quot;completed&quot;))) .subscribe(data =&gt; { console.log(data); }); </code></pre> <p>And when you will close the dialog, you will see <code>completed</code> in console, this depicts that <strong>you do not need to unsubscribe the observable.</strong></p>
41,200,450
Multiple URLs copy in Sources/Network tab
<p>Is it possible to extract multiple resources' URLs in Sources or Network tab of Chrome Dev Tools?<br> When I want to get URL of a <strong>single</strong> resource, I can do it with context menu function <em>Copy link address</em></p> <p><a href="https://i.stack.imgur.com/AwXuj.png" rel="noreferrer"><img src="https://i.stack.imgur.com/AwXuj.png" alt="enter image description here"></a></p> <p>I can switch to this resource from Network to Sources tab and vice versa, but what if I have a need to get URLs of <strong>multiple</strong> resources at once? It is very cumbersome to copy them manually if resultset consists of 200-300 resources.</p> <p>What I've tried so far:</p> <ol> <li>To copy the whole folder from a sources tab, but from <a href="https://stackoverflow.com/questions/20710504/how-do-you-save-an-entire-folder-from-google-chromes-developer-tools-sources-t#comment69592549_20710504">this answer</a> I found out it is not possible for now.</li> <li><p>To use <code>$(selector)</code> as specified in the <a href="https://developers.google.com/web/tools/chrome-devtools/console/command-line-reference" rel="noreferrer">Console reference</a>, in a form of</p> <pre><code>$('img') </code></pre> <p>in case we need to fetch image URLs. </p> <p>The complexity of this approach is that it's often hard to distinguish target images on a page that has hundreds of them, and furthermore, multiple versions of the same image (views, previews, small-sized icons and etc.) I.e. <strong>to match</strong> the element inside the tag with the needed resource is not that easy, as it seems. Also not all the file types have dedicated tags (as in the case with <code>img</code>).</p></li> </ol> <p>Maybe I should use <code>src</code> tag with some modifiers? Any other suggestions?</p>
41,202,159
4
1
null
2016-12-17 16:02:38.91 UTC
13
2022-03-04 14:25:54.38 UTC
2017-05-23 12:02:41.457 UTC
null
-1
null
911,419
null
1
25
google-chrome|url|resources|google-chrome-devtools
13,446
<ol start="0"> <li>make sure <code>Network</code> panel is active</li> <li>switch devtools <code>Dock side</code> in the menu to a detached (floating) window</li> </ol> <p><a href="https://i.stack.imgur.com/mn7oQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mn7oQ.png" alt="enter image description here" /></a></p> <p>Next time you can press <kbd>Ctrl</kbd><kbd>Shift</kbd><kbd>D</kbd> to toggle docking.</p> <hr /> <ol start="2"> <li>in the now detached devtools press <kbd>Ctrl</kbd><kbd>Shift</kbd><kbd>i</kbd> or <kbd>⌘</kbd><kbd>⌥</kbd><kbd>i</kbd> on MacOS,<br /> which will open <strong>devtools-on-devtools</strong> in a new window</li> </ol> <hr /> <ol start="3"> <li><p>Run the following code in this new window:</p> <p><code>copy(UI.panels.network.networkLogView.dataGrid.rootNode().flatNodes.map(n =&gt; n.request().urlInternal).join('\n'))</code></p> <p>It'll copy the URLs of all requests that match current filter to clipboard.</p> </li> </ol> <hr /> <p>Hint: save the code as a <a href="https://developers.google.com/web/tools/chrome-devtools/snippets" rel="nofollow noreferrer">Snippet</a> and run it in devtools-on-devtools window via the commands palette, <kbd>Ctrl</kbd><kbd>P</kbd> or <kbd>⌘</kbd><kbd>P</kbd> then type the snippet's name.</p> <p><strong>In old Chrome the code was different:</strong> <code>copy(UI.panels.network._networkLogView._dataGrid._rootNode._flatNodes.map(n =&gt; n._request._url).join('\n'))</code></p>
40,974,955
Spring Boot Java Config Set Session Timeout
<p>How can I configure my (embedded) Tomcat Session Timeout in a Spring Boot Application?</p> <pre><code>public class SessionListener implements HttpSessionListener{ @Override public void sessionCreated(HttpSessionEvent se) { se.getSession().setMaxInactiveInterval(5*60); } @Override public void sessionDestroyed(HttpSessionEvent se) { }} </code></pre> <p>I have a SessionListener but I have no idea in which class I have to add this Listener to the Context.</p>
40,975,566
3
1
null
2016-12-05 13:05:59.02 UTC
11
2021-05-17 14:47:48.55 UTC
2016-12-05 14:35:01.827 UTC
null
3,857,942
null
4,953,737
null
1
46
spring|session|spring-boot|timeout
154,583
<p>You should be able to set the <code>server.session.timeout</code> in your application.properties file.</p> <p>ref: <a href="http://docs.spring.io/spring-boot/docs/1.4.x/reference/html/common-application-properties.html" rel="noreferrer">http://docs.spring.io/spring-boot/docs/1.4.x/reference/html/common-application-properties.html</a></p> <p><strong>EDIT:</strong></p> <p>This property has changed in later versions of Spring Boot to <code>server.servlet.session.timeout</code>.</p> <p>ref: <a href="https://docs.spring.io/spring-boot/docs/2.4.x/reference/html/appendix-application-properties.html#server.servlet.session.timeout" rel="noreferrer">https://docs.spring.io/spring-boot/docs/2.4.x/reference/html/appendix-application-properties.html#server.servlet.session.timeout</a></p>
1,698,495
Create a list of one object type from a list of another using Linq
<p>If I have classes of Type A and B:</p> <pre><code>public class A { public int TotalCount; public string Title; } public class B { public int Count; public string Title; } </code></pre> <p>I have a list of instances A instances, what is the most efficient way to create and populate a List of type B using Linq?</p>
1,698,580
3
2
null
2009-11-09 00:34:58.617 UTC
7
2016-07-29 20:59:30.277 UTC
null
null
null
null
9,266
null
1
29
linq|linq-to-objects
32,534
<pre><code>List&lt;B&gt; listB = listA.Select(a =&gt; new B() { Count = a.TotalCount, Title = a.Title }).ToList(); </code></pre> <p>Does the same as eduncan's solution with different syntax. Take your pick..</p>
845,030
Bind to a value defined in the Settings
<p>In WPF, Can I use binding with values defined in Settings? If this is possible, please provide a sample.</p>
845,033
4
0
null
2009-05-10 09:55:29.487 UTC
18
2020-01-13 19:26:32.043 UTC
2013-08-22 19:53:34.693 UTC
null
546,730
Moheb
null
null
1
82
wpf|binding|appsettings
51,180
<p>First, you need to add a custom XML namespace that will design the namespace where the settings are defined:</p> <pre><code>xmlns:properties="clr-namespace:TestSettings.Properties" </code></pre> <p>Then, in your XAML file, access the default settings instance using the following syntax:</p> <pre class="lang-xml prettyprint-override"><code>{x:Static properties:Settings.Default} </code></pre> <p>So here is the final result code:</p> <pre><code>&lt;ListBox x:Name="lb" ItemsSource="{Binding Source={x:Static properties:Settings.Default}, Path=Names}" /&gt; </code></pre> <p>Source: <a href="http://weblogs.asp.net/thomaslebrun/archive/2009/03/26/wpf-how-to-bind-a-control-to-a-property-defined-in-the-settings.aspx" rel="noreferrer">WPF - How to bind a control to a property defined in the Settings?</a></p> <hr> <p><em>Note: As pointed out by @Daniel and @nabulke, don't forget to set <strong>Access Modifier</strong> of your settings file to <code>Public</code> and <strong>Scope</strong> to <code>User</code></em></p>
41,144,523
Swap rootViewController with animation?
<p>Im trying to swap to another root view controller with a tab bar; via app delegate, and I want to add transition animation. By default it would only show the view without any animation.</p> <pre><code>let tabBar = self.instantiateViewController(storyBoard: "Main", viewControllerID: "MainTabbar") let appDelegate = UIApplication.shared.delegate as! AppDelegate appDelegate.window = UIWindow(frame: UIScreen.main.bounds) appDelegate.window?.rootViewController = tabBar appDelegate.window?.makeKeyAndVisible() </code></pre> <p>That's how I swapped to another rootview controller.</p>
41,144,822
7
0
null
2016-12-14 14:01:29.42 UTC
28
2021-04-09 15:16:32.197 UTC
null
null
null
null
6,059,351
null
1
91
swift|xcode|swift3|uiviewanimation|rootview
35,382
<p>You can use <code>UIView.transition(with: view)</code> to replace the <code>rootViewController</code> of a <code>UIWindow</code>:</p> <pre><code>guard let window = UIApplication.shared.keyWindow else { return } let storyboard = UIStoryboard(name: "Main", bundle: nil) let vc = storyboard.instantiateViewController(withIdentifier: "MainTabbar") // Set the new rootViewController of the window. // Calling "UIView.transition" below will animate the swap. window.rootViewController = vc // A mask of options indicating how you want to perform the animations. let options: UIView.AnimationOptions = .transitionCrossDissolve // The duration of the transition animation, measured in seconds. let duration: TimeInterval = 0.3 // Creates a transition animation. // Though `animations` is optional, the documentation tells us that it must not be nil. ¯\_(ツ)_/¯ UIView.transition(with: window, duration: duration, options: options, animations: {}, completion: { completed in // maybe do something on completion here }) </code></pre>
36,905,036
How to move SearchView 's search Icon to the right side?
<p><a href="https://i.stack.imgur.com/HZRMy.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/HZRMy.jpg" alt="enter image description here"></a></p> <p>Here is my layout, using <code>android.support.v7.widget.SearchView</code>. I want to move the search icon to the right side,but I haven't found any method... `</p> <pre><code>&lt;android.support.design.widget.AppBarLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:theme="@style/AppTheme.AppBarOverlay"&gt; &lt;android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" app:layout_scrollFlags="scroll|enterAlways|snap" app:popupTheme="@style/AppTheme.PopupOverlay"&gt; &lt;android.support.v7.widget.SearchView android:layout_width="wrap_content" android:layout_height="wrap_content" /&gt; &lt;/android.support.v7.widget.Toolbar&gt; &lt;android.support.design.widget.TabLayout android:id="@+id/tab_main_title" android:layout_width="match_parent" android:layout_height="wrap_content" /&gt; &lt;/android.support.design.widget.AppBarLayout&gt; </code></pre> <p>`</p> <p>after i click the icon,it will change to this layout <a href="https://i.stack.imgur.com/V1y7T.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/V1y7T.jpg" alt="enter image description here"></a></p>
36,906,959
9
0
null
2016-04-28 04:05:05.267 UTC
3
2020-03-11 06:13:42.623 UTC
2017-08-24 09:59:23.93 UTC
null
4,407,266
null
5,787,376
null
1
31
android|android-layout|material-design|searchview
43,271
<p>You can do it programmatically</p> <pre><code>SearchView search = (SearchView) item.getActionView(); search.setLayoutParams(new ActionBar.LayoutParams(Gravity.RIGHT)); </code></pre>
34,702,239
Git - folder case sensitive issue
<p>I am trying to bring a already <em>existing codebase</em> in <code>version control</code> system like <code>git</code>. </p> <p>I am facing a particular issue where codebase contains two folder with same name but different case like 'Form' and 'form'.</p> <p>Here is the scenario : Suppose, we have three system Linux ( case sensitive file system ) , MAC ( Not case sensitive ) and WINDOWS ( not case sensitive )</p> <p>Now if someone on LINUX create a folder name <code>FORM</code> having files <code>a.php</code> , <code>b.php</code> , <code>c.php</code> and another folder name <code>form</code> having files <code>a.php</code> , <code>b.php</code> , <code>d.php</code> and pushes it to remote repo</p> <p>Now when a user on MAC or WINDOWS clone the repo then how will git behave when handling <code>FORM</code> and <code>form</code> coming from remote because MAC and WINDOWS are case insensitive </p>
34,702,594
4
0
null
2016-01-10 04:58:44.183 UTC
9
2018-03-04 00:16:58.233 UTC
null
null
null
null
1,936,343
null
1
28
linux|git|macos
17,819
<p>You should rename your folders so that two sibling folders are never identical (with case-insensitive comparison). This will make your code base more portable, and less error-prone, because developers will not confuse one folder with the other.</p>
34,667,931
Run Jupyter cells in slideshow mode
<p>You can display a Jupyter notebook in an active html setting by running :</p> <pre><code>$ jupyter nbconvert untitled.ipynb --to slides --post serve </code></pre> <p>Is there any ways to run a notebook in the same slideshow format in order to allow for a live presentation/execution of your cells ?</p>
35,401,649
1
0
null
2016-01-08 01:04:16.487 UTC
6
2019-09-16 09:38:06.967 UTC
2016-01-08 08:13:01.25 UTC
null
5,304,366
null
5,304,366
null
1
33
slideshow|jupyter|jupyter-notebook
28,072
<p>Check out the Jupyter plugin RISE using Reveal.JS:</p> <ul> <li>Github Repo: <a href="https://github.com/damianavila/RISE" rel="noreferrer">https://github.com/damianavila/RISE</a> </li> <li>Documentation: <a href="https://rise.readthedocs.io/en/maint-5.5/" rel="noreferrer">https://rise.readthedocs.io/en/maint-5.5/</a></li> </ul> <p>It's awesome.</p>
39,087,859
What is spark.driver.maxResultSize?
<p>The <a href="http://spark.apache.org/docs/latest/configuration.html" rel="noreferrer">ref</a> says:</p> <blockquote> <p>Limit of total size of serialized results of all partitions for each Spark action (e.g. collect). Should be at least 1M, or 0 for unlimited. Jobs will be aborted if the total size is above this limit. Having a high limit may cause out-of-memory errors in driver (depends on spark.driver.memory and memory overhead of objects in JVM). Setting a proper limit can protect the driver from out-of-memory errors.</p> </blockquote> <p>What does this attribute do exactly? I mean at first (since I am not battling with a job that fails due to out of memory errors) I thought I should increase that.</p> <p>On second thought, it seems that this attribute defines the max size of the result a worker can send to the driver, so leaving it at the default (1G) would be the best approach to protect the driver..</p> <p>But will happen on this case, the worker will have to send more messages, so the overhead will be just that the job will be slower?</p> <hr> <p>If I understand correctly, assuming that a worker wants to send 4G of data to the driver, then having <code>spark.driver.maxResultSize=1G</code>, will cause the worker to send 4 messages (instead of 1 with unlimited <code>spark.driver.maxResultSize</code>). If so, then increasing that attribute to protect my driver from being assassinated from Yarn should be wrong.</p> <p>But still the question above remains..I mean what if I set it to 1M (the minimum), will it be the most protective approach?</p>
39,089,720
1
0
null
2016-08-22 20:06:38.667 UTC
11
2016-08-23 09:36:13.07 UTC
2016-08-23 09:36:13.07 UTC
null
1,305,344
null
2,411,320
null
1
46
apache-spark|configuration|driver|communication|distributed-computing
81,324
<blockquote> <p>assuming that a worker wants to send 4G of data to the driver, then having spark.driver.maxResultSize=1G, will cause the worker to send 4 messages (instead of 1 with unlimited spark.driver.maxResultSize).</p> </blockquote> <p>No. If estimated size of the data is larger than <code>maxResultSize</code> given job will be aborted. The goal here is to protect your application from driver loss, nothing more.</p> <blockquote> <p>if I set it to 1M (the minimum), will it be the most protective approach?</p> </blockquote> <p>In sense yes, but obviously it is not useful in practice. Good value should allow application to proceed normally but protect application from unexpected conditions.</p>
22,295,201
How to make Bootstrap 'List group' responsive
<p>I am using Bootstrap '<a href="http://getbootstrap.com/components/#list-group-basic">List group</a>' and I need to make it responsive. Means in mobile view, The list would show as a drop down button like navbar.</p> <p>I tried nav classes, But not working as expected. Code:</p> <pre><code>&lt;button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#side-menu-collapse"&gt; &lt;span class="sr-only"&gt;Toggle navigation&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;/button&gt; &lt;ul class="list-group collapse navbar-collapse" id="#side-menu-collapse"&gt; &lt;li class="list-group-item dropdown-toggle"&gt;Cras justo odio&lt;/li&gt; &lt;li class="list-group-item dropdown-toggle"&gt;Dapibus ac facilisis in&lt;/li&gt; &lt;li class="list-group-item dropdown-toggle"&gt;Morbi leo risus&lt;/li&gt; &lt;li class="list-group-item dropdown-toggle"&gt;Porta ac consectetur ac&lt;/li&gt; &lt;li class="list-group-item dropdown-toggle"&gt;Vestibulum at eros&lt;/li&gt; &lt;/ul&gt; </code></pre>
22,300,134
1
0
null
2014-03-10 08:25:04.853 UTC
3
2021-05-15 16:46:24.283 UTC
2014-07-10 14:12:17.24 UTC
null
2,454,790
null
2,755,677
null
1
15
css|twitter-bootstrap|twitter-bootstrap-3
39,985
<p>You can do this with a bit of media query. In overiding the <code>collapse</code> class when the screen size is different of <code>XS</code>.</p> <p><strong>Bootply</strong> : <a href="https://www.bootply.com/L5BYCOwsZG" rel="nofollow noreferrer">https://www.bootply.com/L5BYCOwsZG</a></p> <p><strong>CSS</strong> :</p> <pre><code>@media screen and (min-width: 768px) { .custom-collapse .collapse { display:block; } } </code></pre> <p><strong>HTML</strong> :</p> <pre><code>&lt;div class=&quot;custom-collapse&quot;&gt; &lt;button class=&quot;collapse-toggle visible-xs &quot; type=&quot;button&quot; data-toggle=&quot;collapse&quot; data-parent=&quot;custom-collapse&quot; data-target=&quot;#side-menu-collapse&quot;&gt; &lt;span class=&quot;&quot;&gt;Toggle navigation&lt;/span&gt; &lt;span class=&quot;icon-bar&quot;&gt;&lt;/span&gt; &lt;span class=&quot;icon-bar&quot;&gt;&lt;/span&gt; &lt;span class=&quot;icon-bar&quot;&gt;&lt;/span&gt; &lt;/button&gt; &lt;ul class=&quot;list-group collapse&quot; id=&quot;side-menu-collapse&quot;&gt; &lt;li class=&quot;list-group-item dropdown-toggle&quot;&gt;Cras justo odio&lt;/li&gt; &lt;li class=&quot;list-group-item dropdown-toggle&quot;&gt;Dapibus ac facilisis in&lt;/li&gt; &lt;li class=&quot;list-group-item dropdown-toggle&quot;&gt;Morbi leo risus&lt;/li&gt; &lt;li class=&quot;list-group-item dropdown-toggle&quot;&gt;Porta ac consectetur ac&lt;/li&gt; &lt;li class=&quot;list-group-item dropdown-toggle&quot;&gt;Vestibulum at eros&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre>
58,869,229
index.d.ts error TS2307: Cannot find module my own module
<p>I am facing a problem that I cannot resolve. I want to share somes interfaces and types between my classes files.</p> <p>My repo is something like this :</p> <pre><code>test -&gt; dist/ -&gt; src/ -&gt; index.ts -&gt; .babelrc -&gt; .eslintrc.js -&gt; index.d.ts -&gt; package.json -&gt; tsconfig.json </code></pre> <p>In <code>index.d.ts</code>:</p> <pre><code>declare module test { // I've try with 'declare namespace test' but the result is the same export interface LabeledValue { label: string; size: number; } } </code></pre> <p>If I import <code>LabeledValue</code> in <code>index.ts</code> I've got an error and I don't understand the reason: <code>import { LabeledValue} from 'test'; // TS2307: Cannot find module 'test'.</code></p> <p>src/index.ts</p> <pre><code>import {LabeledValue} from 'test'; function printLabel(labeledObj: LabeledValue) { console.log(labeledObj.label); } let myObj = {size: 10, label: "Size 10 Object"}; printLabel(myObj); </code></pre> <p>package.json:</p> <pre><code>{ "name": "test", "types": "index.d.ts", "version": "1.0.0", "description": "test", "author": "oyabi", "license": "MIT", "private": true, "scripts": { "type-check": "tsc --noEmit", "type-check:watch": "yarn type-check --watch", "build": "npm run build:types &amp;&amp; npm run build:js", "build:types": "tsc --emitDeclarationOnly", "build:js": "babel src --out-dir dist --extensions \".ts,.tsx\" --source-maps inline" }, "dependencies": { "axios": "^0.19.0", "body-parser": "^1.18.3", "express": "^4.16.4", "helmet": "^3.21.2", "morgan": "^1.9.1", "winston": "^3.1.0" }, "devDependencies": { "@babel/cli": "^7.7.0", "@babel/core": "^7.7.2", "@babel/plugin-syntax-class-properties": "^7.0.0", "@babel/polyfill": "^7.7.0", "@babel/preset-env": "^7.7.1", "@babel/preset-typescript": "^7.7.2", "@babel/runtime": "^7.7.2", "@types/express": "^4.17.2", "@types/helmet": "^0.0.45", "@types/morgan": "^1.7.36", "@types/qrcode": "^1.3.4", "@typescript-eslint/eslint-plugin": "^2.7.0", "@typescript-eslint/parser": "^2.7.0", "apidoc": "^0.18.0", "babel-core": "^7.0.0-bridge", "babel-eslint": "^10.0.1", "babel-jest": "^24.8.0", "babel-plugin-transform-class-properties": "^6.24.1", "babel-preset-airbnb": "^4.2.0", "babel-preset-env": "^1.7.0", "eslint": "^6.6.0", "eslint-config-airbnb-base": "^14.0.0", "eslint-config-prettier": "^6.5.0", "eslint-friendly-formatter": "^4.0.1", "eslint-plugin-import": "^2.18.2", "eslint-plugin-jest": "^23.0.4", "eslint-plugin-prettier": "^3.1.0", "jest": "^24.8.0", "moxios": "^0.4.0", "nodemon": "^1.19.4", "prettier": "^1.19.1", "retire": "^2.0.1", "supertest": "^4.0.2", "typescript": "^3.7.2", "uuid": "^3.3.2" } } </code></pre> <p>.babelrc</p> <pre><code>{ "presets": ["@babel/typescript", ["airbnb", { "useBuiltIns": "usage" }] ], "plugins": [ "syntax-class-properties", "transform-class-properties" ] } </code></pre> <p>.eslintrc</p> <pre><code>module.exports = { root: true, parser: "@typescript-eslint/parser", parserOptions: { sourceType: "module", project: "./tsconfig.json" }, env: { node: true, jest: true }, extends: [ "airbnb-base", "plugin:@typescript-eslint/recommended", "plugin:jest/recommended", "plugin:prettier/recommended", "prettier/@typescript-eslint", "plugin:import/errors", "plugin:import/warnings", "plugin:import/typescript" ], plugins: ["@typescript-eslint", "jest", "import"], rules: { "import/no-commonjs": "error", "import/no-amd": "error", // allow debugger during development "no-debugger": process.env.NODE_ENV === "production" ? 2 : 0, "no-underscore-dangle": 0, "prettier/prettier": [ 2, { printWidth: 80, singleQuote: true, trailingComma: "all" } ] }, settings: { "import/resolver": { node: { extensions: [".js", ".jsx", ".ts", ".tsx"] } } } }; </code></pre> <p>tsconfig.json</p> <pre><code>{ "compilerOptions": { "target": "esnext", "module": "commonjs", "declaration": true, "outDir": "./dist", "strict": true, "noImplicitAny": true, "strictNullChecks": true, "noImplicitThis": true, "esModuleInterop": true, "resolveJsonModule": true }, "include": ["index.d.ts"] } </code></pre> <p>My real code is more complicated but you have a good idea of the problem. The error appear in Visual Studio Code and with <code>yarn build</code> (with real code). With this code you can use <code>yarn tsc src/index.ts</code> to show error.</p> <p>Do you have any idea how I can solve this problem please?</p>
58,923,053
3
0
null
2019-11-15 01:52:39.99 UTC
2
2022-04-07 09:34:01.23 UTC
null
null
null
null
1,284,500
null
1
11
typescript|eslint
52,653
<p>I resolve my problem with the installation of <a href="https://www.npmjs.com/package/eslint-import-resolver-typescript" rel="noreferrer">eslint-import-resolver-typescript</a> and the default configuration.</p>
29,370,581
Spring MVC: please explain difference between @RequestParam and @ModelAttribute
<p>I'm new to Spring MVC. Please help me unpack the documentation.</p> <p><strong>Documentation</strong></p> <p><a href="http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html" rel="noreferrer">Spring MVC Documentation</a> states (emphasis mine):</p> <ul> <li><p><code>@ModelAttribute</code> on a method argument indicates the argument should be retrieved from the model. If not present in the model, the argument should be instantiated first and then added to the model. Once present in the model, <strong>the argument’s fields should be populated from all request parameters that have matching names</strong>. The WebDataBinder class matches request parameter names — including query string parameters and form fields — to model attribute fields by name. </p></li> <li><p><code>@RequestParam</code> <strong>binds request parameters to a method parameter</strong> in your controller.</p></li> </ul> <p><strong>Disclaimer / Clarifier</strong></p> <p>I know that <code>@ModelAttribute</code> and <code>@RequestParam</code> are not the same thing, are not mutually exclusive, do not perform the same role, and can be used simultaneously, as in <a href="https://stackoverflow.com/questions/11268470/how-to-pass-requestparam-and-modelattribute-in-one-form">this question</a> - indeed, <code>@RequestParam</code> can be used to populate fields of <code>@ModelAttribute</code>. My question is more geared towards the difference between their internal workings.</p> <p><strong>Question:</strong></p> <p>What is the difference between <code>@ModelAttribute</code> (used on a method argument, not method) and <code>@RequestParam</code>? Specifically:</p> <ul> <li><strong>Source:</strong> Do <code>@RequestParam</code> and <code>@ModelAttribute</code> have the same source of information / population, i.e. request parameters in URL, which may have been supplied as elements of a form / model that was <code>POST</code>ed? </li> <li><strong>Usage:</strong> Is it correct that variables retrieved with <code>@RequestParam</code> are thrown away (unless passed into a model), whereas variables retrieved with <code>@ModelAttribute</code> are automatically fed into the model to be returned?</li> </ul> <p>Or in very basic coding examples, what is the real working difference between these two examples?</p> <p>Example 1: <code>@RequestParam</code>:</p> <pre><code>// foo and bar are thrown away, and are just used (e.g.) to control flow? @RequestMapping(method = RequestMethod.POST) public String testFooBar(@RequestParam("foo") String foo, @RequestParam("bar") String bar, ModelMap model) { try { doStuff(foo, bar); } // other code } </code></pre> <p>Example 2: <code>@ModelAttribute</code>:</p> <pre><code>// FOOBAR CLASS // Fields could of course be explicitly populated from parameters by @RequestParam public class FooBar{ private String foo; private String bar; // plus set() and get() methods } // CONTROLLER // Foo and Bar become part of the model to be returned for the next view? @RequestMapping(method = RequestMethod.POST) public String setupForm(@ModelAttribute("fooBar") FooBar foobar) { String foo = fooBar.getFoo(); String bar = fooBar.getBar(); try { doStuff(foo, bar); } // other code } </code></pre> <hr> <p><strong>My current understanding:</strong></p> <p><code>@ModelAttribute</code> and <code>@RequestParam</code> both interrogate the request parameters for information, but they use this information differently:</p> <ul> <li><p><code>@RequestParam</code> just populates stand-alone variables (which may of course be fields in a <code>@ModelAttribute</code> class). These variables will be thrown away when the Controller is done, unless they have been fed into the model.</p></li> <li><p><code>@ModelAttribute</code> populates the fields of a class, which then populates an attribute of the model to be passed back to the view</p></li> </ul> <p>Is this correct?</p>
29,371,418
5
0
null
2015-03-31 14:07:37.283 UTC
21
2017-12-21 22:02:11.34 UTC
2017-05-23 11:33:13.96 UTC
null
-1
null
2,294,676
null
1
62
java|spring|spring-mvc|spring-annotations
54,167
<blockquote> <p><code>@RequestParam</code> just populates stand-alone variables (which may of course be fields in a <code>@ModelAttribute</code> class). These variables will be thrown away when the Controller is done, unless they have been fed into the model.</p> </blockquote> <p>Don't confuse the word "model" with session. The http conversation is generally: <code>HTTP.GET</code>, server response, then <code>HTTP.POST</code>. When you have the <code>@ModelAttribute</code> annotation in use you are always constructing an instance of whatever you have annotated, this is what makes you think that 'feeding things to the model' might make variables stick around. This isn't correct, once the <code>HttpServletRequest</code> has finished those variables should no longer be a part of the browser/server conversation unless they've been saved in a session.</p> <blockquote> <p><code>@ModelAttribute</code> populates the fields of a class, which then populates an attribute of the model to be passed back to the view</p> </blockquote> <p>Yes! To be correct, <code>@ModelAttribute</code> tells Spring to use its default web data binder to populate an instance of something with data from the <code>HttpServletRequest</code>. Choosing to pass this data back to the view is up to the programmer. When you have a method annotated with <code>@ModelAttribute</code>, it is being called every time code hits that servlet. When you have <code>@ModelAttribute</code> as one of the method's parameters, we are talking about incoming Http form data-binding.</p> <p>Calling <code>@RequestParam</code> is a shortcut for saying <code>request.getParameter("foo")</code>; under the hood, Java's <code>HttpServletRequest</code> lets you get values from the request object by doing a key->value look up. The value returned is of type Object. This is what you would be typing a lot if you were not using Spring in your web application.</p> <p>Spring then takes this abstraction a step further when you start to use <code>@ModelAttribute</code>. This annotation employs the concept of data-binding. The goal of data-binding is that the code in your controller won't have to call <code>request.getParameter("foo1")</code>, for every form element. Imagine you have a web form with 5 fields. Without data-binding the programmer has to manually retrieve, and validate each of those fields. The programmer has to make sure that the request contains the property, that the property's value exists, and that the property's value is of the type expected for each field. Using <code>@ModelAttribute</code> tells Spring to do this work for you. </p> <p>If you annotate a method in your controller with <code>@ModelAttribute("fooBar") FooBar fooBar</code> An instance of <code>FooBar</code> will <em>always</em> be constructed by Spring, and supplied to your method. Where the data binding comes into play, is when this annotation is used in a Method's parameters; Spring looks at the instance of <code>HttpServletRequest</code> and sees if it can match the data in the request to the right property on an instance of <code>FooBar</code>. This is based off the java properties convention, where you have a field such as <code>foo</code> and public getters and setters called <code>getFoo</code> and <code>setFoo</code>. This might seem magic but if you were to break convention, your Spring data binding would stop working because it wouldn't be able to know <em>where</em> to bind the data from your <code>HttpServletRequest</code> You would still get an instance of <code>FooBar</code>, but the properties would not be set to any values from the request.</p>
23,498,284
Why is CROSS APPLY needed when using XPath queries?
<h1>tl;dr</h1> <p>Why doesn't:</p> <pre><code>SELECT SomeXmlColumn.nodes('/people/person') AS foo(b) FROM MyTable </code></pre> <p>work?</p> <h1>The Before Question</h1> <p>Nearly ever answer I've seen (or gotten) for using XPath queries in SQL Server requires that you join the XML document back to itself using a <code>CROSS APPLY</code>.</p> <p>Why?</p> <p><a href="https://stackoverflow.com/a/899382/12597">For example:</a></p> <pre><code>SELECT p.value('(./firstName)[1]', 'VARCHAR(8000)') AS firstName, p.value('(./lastName)[1]', 'VARCHAR(8000)') AS lastName FROM table CROSS APPLY field.nodes('/person') t(p) </code></pre> <p><a href="https://stackoverflow.com/a/23483596/12597">For example</a>:</p> <pre><code>SELECT a.BatchXml.value('(Name)[1]', 'varchar(50)') AS Name, a.BatchXml.value('(IDInfo/IDType)[1]', 'varchar(50)') AS IDType, a.BatchXml.value('(IDInfo/IDOtherDescription)[1]', 'varchar(50)') AS IDOtherDescription FROM BatchReports b CROSS APPLY b.BatchFileXml.nodes('Customer') A(BatchXml) WHERE a.BatchXml.exist('IDInfo/IDType[text()=3]')=1 </code></pre> <p><a href="https://stackoverflow.com/a/14713431/12597">For example</a>:</p> <pre><code>SELECT b.BatchID, x.XmlCol.value('(ReportHeader/OrganizationReportReferenceIdentifier)[1]','VARCHAR(100)') AS OrganizationReportReferenceIdentifier, x.XmlCol.value('(ReportHeader/OrganizationNumber)[1]','VARCHAR(100)') AS OrganizationNumber FROM Batches b CROSS APPLY b.RawXml.nodes('/CasinoDisbursementReportXmlFile/CasinoDisbursementReport') x(XmlCol); </code></pre> <p><a href="http://msdn.microsoft.com/en-us/library/ms345118%28SQL.90%29.aspx" rel="noreferrer">And even from MSDN Books Online:</a></p> <pre><code>SELECT nref.value('first-name[1]', 'nvarchar(32)') FirstName, nref.value('last-name[1]', 'nvarchar(32)') LastName FROM [XmlFile] CROSS APPLY [Contents].nodes('//author') AS p(nref) </code></pre> <p>They all use it. But nobody (not even the SQL Server Books Online) explains why it's needed, what problem it solves, what it's doing, or how it works.</p> <h2>Even the simplest case needs them</h2> <p>Even the simplest example of taking the XML:</p> <pre><code>&lt;people&gt; &lt;person&gt;&lt;firstName&gt;Jon&lt;/firstName&gt;&lt;lastName&gt;Johnson&lt;/lastName&gt;&lt;/person&gt; &lt;person&gt;&lt;firstName&gt;Kathy&lt;/firstName&gt;&lt;lastName&gt;Carter&lt;/lastName&gt;&lt;/person&gt; &lt;person&gt;&lt;firstName&gt;Bob&lt;/firstName&gt;&lt;lastName&gt;Burns&lt;/lastName&gt;&lt;/person&gt; &lt;/people&gt; </code></pre> <p>and returning the values:</p> <pre><code>FirstName LastName ========= ======== Jon Johnson Kathy Carter Bob Burns </code></pre> <p>needs a join:</p> <pre><code>SELECT p.value('(./firstName)[1]', 'VARCHAR(8000)') AS firstName, p.value('(./lastName)[1]', 'VARCHAR(8000)') AS lastName FROM table CROSS APPLY field.nodes('/person') t(p) </code></pre> <p>What's confusing is that it doesn't even <em>use</em> the table it joins from, why does it need it?</p> <p>Since querying for XML has never been documented or explained, hopefully we can solve that now.</p> <h1>What does it actually do?</h1> <p>So let's start with an actual example, since we want an actual answer, that gives an actual explanation:</p> <pre><code>DECLARE @xml xml; SET @xml = '&lt;people&gt; &lt;person&gt;&lt;firstName&gt;Jon&lt;/firstName&gt;&lt;lastName&gt;Johnson&lt;/lastName&gt;&lt;/person&gt; &lt;person&gt;&lt;firstName&gt;Kathy&lt;/firstName&gt;&lt;lastName&gt;Carter&lt;/lastName&gt;&lt;/person&gt; &lt;person&gt;&lt;firstName&gt;Bob&lt;/firstName&gt;&lt;lastName&gt;Burns&lt;/lastName&gt;&lt;/person&gt; &lt;/people&gt;'; ;WITH MyTable AS ( SELECT @xml AS SomeXmlColumn ) </code></pre> <p>Now we have <em>psuedo</em> table we can query from:</p> <p><img src="https://i.stack.imgur.com/G5VDf.png" alt="enter image description here"></p> <h1>Let's start with the obvious</h1> <p>First I need the people. In <strong>real</strong> XML, I can easily return the three rows:</p> <pre><code>/people/person </code></pre> <p>Which gives a <code>NodeList</code> containing three nodes:</p> <pre><code>&lt;person&gt;&lt;firstName&gt;Jon&lt;/firstName&gt;&lt;lastName&gt;Johnson&lt;/lastName&gt;&lt;/person&gt; &lt;person&gt;&lt;firstName&gt;Kathy&lt;/firstName&gt;&lt;lastName&gt;Carter&lt;/lastName&gt;&lt;/person&gt; &lt;person&gt;&lt;firstName&gt;Bob&lt;/firstName&gt;&lt;lastName&gt;Burns&lt;/lastName&gt;&lt;/person&gt; </code></pre> <p>In SQL Server, the same query:</p> <pre><code>SELECT SomeXmlColumn.query('/people/person') FROM MyTable </code></pre> <p>doesn't return three rows, but rather one row with the XML containing the three nodes:</p> <pre><code>&lt;person&gt; &lt;firstName&gt;Jon&lt;/firstName&gt; &lt;lastName&gt;Johnson&lt;/lastName&gt; &lt;/person&gt; &lt;person&gt; &lt;firstName&gt;Kathy&lt;/firstName&gt; &lt;lastName&gt;Carter&lt;/lastName&gt; &lt;/person&gt; &lt;person&gt; &lt;firstName&gt;Bob&lt;/firstName&gt; &lt;lastName&gt;Burns&lt;/lastName&gt; &lt;/person&gt; </code></pre> <p>Obviously this is unsuitable, when my end goal is to return 3 <strong>rows</strong>. I somehow have to break up the three rows into three rows.</p> <h1>Onto the names</h1> <p>My actual goal is to get the <code>firstName</code> and <code>lastName</code>. In XPath I could do something like:</p> <pre><code>/people/person/firstName|/people/person/lastName </code></pre> <p>which gets me the six nodes, although they are not adjoining</p> <pre><code>&lt;firstName&gt;Jon&lt;/firstName&gt; &lt;lastName&gt;Johnson&lt;/lastName&gt; &lt;firstName&gt;Kathy&lt;/firstName&gt; &lt;lastName&gt;Carter&lt;/lastName&gt; &lt;firstName&gt;Bob&lt;/firstName&gt; &lt;lastName&gt;Burns&lt;/lastName&gt; </code></pre> <p>In SQL Server, we try something similar</p> <pre><code>SELECT SomeXmlColumn.query('/people/person/firstName') AS FirstName, SomeXmlColumn.query('/people/person/lastName') AS LastName FROM MyTable </code></pre> <p>which gets us one <strong>row</strong>, with each column containing an XML fragment:</p> <pre><code>FirstName LastName ============================ ============================ &lt;firstName&gt;Jon&lt;/firstName&gt; &lt;lastName&gt;Johnson&lt;/lastName&gt; &lt;firstName&gt;Kathy&lt;/firstName&gt; &lt;lastName&gt;Carter&lt;/lastName&gt; &lt;firstName&gt;Bob&lt;/firstName&gt; &lt;lastName&gt;Burns&lt;/lastName&gt; </code></pre> <p>...and now I'm tired. I've spent three hours writing this question, on top of the <a href="https://stackoverflow.com/questions/23483352/how-to-return-the-value-that-exists-in-sql-server-xpath/23483596?noredirect=1#comment36031482_23483596">four hours I spent asking yesterday's question</a>. I'll come back to this question later; when it's cooler in here, and I have more energy to beg for help.</p> <h1>Second wind</h1> <p>The fundamental problem is that no matter what I do, I keep getting only one row returned. I want three rows returned (because there are three people). SQL Server <em>does</em> have a function that can convert XML rows (called nodes) into SQL Server rows (called rows). It's the <code>.nodes</code> function:</p> <blockquote> <p>The <strong>nodes()</strong> method is useful when you want to shred an xml data type instance into relational data. It allows you to identify nodes that will be mapped into a new row.</p> </blockquote> <p>This means that you "call" the <code>.nodes</code> method with an XPath query on an <code>xml</code> data type. And what used to come back in SQL Server as one row with three nodes, comes back (correctly) as three nodes:</p> <pre><code>.nodes('/people/person') AS MyDerivedTable(SomeOtherXmlColumn) </code></pre> <p>Conceptually this returns:</p> <pre><code>SomeOtherXmlColumn ------------------------------------------------------------------------ &lt;person&gt;&lt;firstName&gt;Jon&lt;/firstName&gt;&lt;lastName&gt;Johnson&lt;/lastName&gt;&lt;/person&gt; &lt;person&gt;&lt;firstName&gt;Kathy&lt;/firstName&gt;&lt;lastName&gt;Carter&lt;/lastName&gt;&lt;/person&gt; &lt;person&gt;&lt;firstName&gt;Bob&lt;/firstName&gt;&lt;lastName&gt;Burns&lt;/lastName&gt;&lt;/person&gt; </code></pre> <p>But if you <em>actually</em> try to use it, it doesn't work:</p> <pre><code>DECLARE @xml xml; SET @xml = '&lt;people&gt; &lt;person&gt;&lt;firstName&gt;Jon&lt;/firstName&gt;&lt;lastName&gt;Johnson&lt;/lastName&gt;&lt;/person&gt; &lt;person&gt;&lt;firstName&gt;Kathy&lt;/firstName&gt;&lt;lastName&gt;Carter&lt;/lastName&gt;&lt;/person&gt; &lt;person&gt;&lt;firstName&gt;Bob&lt;/firstName&gt;&lt;lastName&gt;Burns&lt;/lastName&gt;&lt;/person&gt; &lt;/people&gt;'; SELECT * FROM @xml.nodes('/people/person') AS MyDervicedTable(SomeOtherXmlColumn) </code></pre> <p>Gives the error:</p> <blockquote> <p>Msg 493, Level 16, State 1, Line 8<br> The column 'SomeOtherXmlColumn' that was returned from the nodes() method cannot be used directly. It can only be used with one of the four XML data type methods, exist(), nodes(), query(), and value(), or in IS NULL and IS NOT NULL checks.</p> </blockquote> <p>I presume this is because I'm not allowed to look at the results set (i.e. the <code>*</code> is not allowed). No problem. I'll use the same <code>.query</code> I used originally:</p> <pre><code>SELECT SomeOtherXmlColumn.query('/') AS SomeOtherOtherXmlColumn FROM @xml.nodes('/people/person') AS MyDervicedTable(SomeOtherXmlColumn) </code></pre> <p>Which returns rows. But rather than splitting a list of nodes into rows, it just duplicates the entire XML:</p> <pre><code>SomeOtherOtherXmlColumn ---------------------------------------- &lt;people&gt;&lt;person&gt;&lt;firstName&gt;Jon&lt;/firstName&gt;&lt;lastName&gt;Johnson&lt;/lastName&gt;&lt;/person&gt;&lt;person&gt;&lt;firstName&gt;Kathy&lt;/firstName&gt;&lt;lastName&gt;Carter&lt;/lastName&gt;&lt;/person&gt;&lt;person&gt;&lt;firstName&gt;Bob&lt;/firstName&gt;&lt;lastName&gt;Burns&lt;/lastName&gt;&lt;/person&gt;&lt;/people&gt; &lt;people&gt;&lt;person&gt;&lt;firstName&gt;Jon&lt;/firstName&gt;&lt;lastName&gt;Johnson&lt;/lastName&gt;&lt;/person&gt;&lt;person&gt;&lt;firstName&gt;Kathy&lt;/firstName&gt;&lt;lastName&gt;Carter&lt;/lastName&gt;&lt;/person&gt;&lt;person&gt;&lt;firstName&gt;Bob&lt;/firstName&gt;&lt;lastName&gt;Burns&lt;/lastName&gt;&lt;/person&gt;&lt;/people&gt; &lt;people&gt;&lt;person&gt;&lt;firstName&gt;Jon&lt;/firstName&gt;&lt;lastName&gt;Johnson&lt;/lastName&gt;&lt;/person&gt;&lt;person&gt;&lt;firstName&gt;Kathy&lt;/firstName&gt;&lt;lastName&gt;Carter&lt;/lastName&gt;&lt;/person&gt;&lt;person&gt;&lt;firstName&gt;Bob&lt;/firstName&gt;&lt;lastName&gt;Burns&lt;/lastName&gt;&lt;/person&gt;&lt;/people&gt; </code></pre> <p>Which makes sense. I was <em>expecting</em> an XPath query in SQL Server to behave like XPath. But a hindsight careful reading of the docs say otherwise:</p> <blockquote> <p>The result of the <strong>nodes()</strong> method is a rowset that contains logical copies of the original XML instances. In these logical copies, the context node of every row instance is set to one of the nodes identified with the query expression, so that subsequent queries can navigate relative to these context nodes.</p> </blockquote> <h1>Now do it with an <code>xml</code> column</h1> <p>The preceding example was for a variable of type <code>xml</code>. Now we have to retrofit the <code>.nodes</code> function to work with a table containing an <code>xml</code> column:</p> <pre><code>SELECT SomeXmlColumn.nodes('/people/person') FROM MyTable </code></pre> <p>No, that doesn't work:</p> <blockquote> <p>Msg 227, Level 15, State 1, Line 8<br> "nodes" is not a valid function, property, or field.</p> </blockquote> <p>Although <code>.nodes</code> <em>is</em> a valid method of an <code>xml</code> data type, it simply doesn't work when you try to use it on an <code>xml</code> data type. Nor does it work on when used on an <code>xml</code> data type:</p> <pre><code>SELECT * FROM MyTable.SomeXmlColumn.nodes('/people/person') </code></pre> <blockquote> <p>Msg 208, Level 16, State 1, Line 8<br> Invalid object name 'MyTable.SomeXmlColumn.nodes'.</p> </blockquote> <p>Which I presume is why the <code>CROSS APPLY</code> modifier is needed. Not because you are joining anything, but because the SQL Server parser will refuse to recognize <code>.nodes</code> unless it's preceded with the keywords <code>cross apply</code>:</p> <pre><code>SELECT 'test' AS SomeTestColumn FROM MyTable CROSS APPLY MyTable.SomeXmlColumn.nodes('/people/person') AS MyDerivedTable(SomeOtherXmlColumn) </code></pre> <p>And we start to get somewhere:</p> <pre><code>SomeTestColumn -------------- test test test </code></pre> <p>And so if we then want to see the XML that comes back:</p> <pre><code>SELECT SomeOtherXmlColumn.query('/') FROM (MyTable CROSS APPLY MyTable.SomeXmlColumn.nodes('/people/person') AS MyDerivedTable(SomeOtherXmlColumn)) </code></pre> <p>Now we have three rows.</p> <p>It seems that <code>cross apply</code> isn't used to a join, but merely a keyword that allows <code>.nodes</code> to work </p> <p>And it seems that the SQL Server optimizer just refuses to accept any use of</p> <pre><code>.nodes </code></pre> <p>and you must actually use:</p> <pre><code>CROSS APPLY .nodes </code></pre> <p>And that's just how it is. And if that's the case - that's fine. That's the rule. And that led to years of confusion; thinking I was joining something to something else with the <code>cross apply</code> operator.</p> <p>Except I believe there is more to it than that. There must, somehow, actually be a <code>cross apply</code> happening. But I cannot see where - or why.</p>
35,641,620
3
2
null
2014-05-06 15:01:58.3 UTC
14
2019-02-27 22:21:14.153 UTC
2017-05-23 12:17:59.863 UTC
null
-1
null
12,597
null
1
41
sql-server|xpath
33,797
<p>Query:</p> <pre><code>SELECT x.i.value('(./text())[1]', 'VARCHAR(10)') FROM MyTable.SomeXmlColumn.nodes('./people/person/firstName') AS x(i); </code></pre> <p>doesn't work, for the same reason why this query doesn't work:</p> <pre><code>SELECT * FROM Person.Person.FirstName; </code></pre> <p>but this does:</p> <pre><code>SELECT FirstName FROM Person.Person; </code></pre> <p>-</p> <p><em>FROM</em> clause expects rowset, so this is valid, since <em>nodes()</em> returns rowset:</p> <pre><code>DECLARE @xml AS XML = '&lt;people&gt; &lt;person&gt;&lt;firstName&gt;Jon&lt;/firstName&gt;&lt;lastName&gt;Johnson&lt;/lastName&gt;&lt;/person&gt; &lt;person&gt;&lt;firstName&gt;Kathy&lt;/firstName&gt;&lt;lastName&gt;Carter&lt;/lastName&gt;&lt;/person&gt; &lt;person&gt;&lt;firstName&gt;Bob&lt;/firstName&gt;&lt;lastName&gt;Burns&lt;/lastName&gt;&lt;/person&gt; &lt;/people&gt;'; SELECT x.i.value('(./text())[1]', 'VARCHAR(10)') FROM @xml.nodes('./people/person/firstName') AS x(i); </code></pre> <p>If xml is not a variable but value in table, we first need to extract rows from this value, and this is when <em>CROSS APPLY</em> comes in handy:</p> <pre><code>SELECT x.i.value('(./text())[1]', 'VARCHAR(10)') FROM MyTable as t CROSS APPLY t.SomeXmlColumn.nodes('./people/person/firstName') AS x(i); </code></pre> <p><em>CROSS APPLY</em> operator applies the right expression to each record from the left table (MyTable).</p> <ul> <li>In MyTable table there is one record containing xml.</li> <li>CROSS APPLY fetches this record and exposes it to expression in the right.</li> <li>Right expression extracts records using nodes() function.</li> <li>As a result there are 1 x 3 = 3 records (xml nodes) which are then processed by SELECT clause.</li> </ul> <p>Compare to 'normal' <em>CROSS APPLY</em> query:</p> <pre><code>SELECT c.CustomerID, soh.TotalDue, soh.OrderDate FROM Sales.Customer AS c CROSS APPLY (SELECT TOP(2) TotalDue, OrderDate FROM Sales.SalesOrderHeader WHERE CustomerID = c.CustomerID ORDER BY TotalDue DESC) AS soh; </code></pre> <p>c.CustomerID is our t.SomeXmlColumn</p>
37,510,801
Convert octet-stream to image
<p>I need to fetch a file using a $http.get. The data returns as application/octet-stream But i know this file is an image.</p> <p>How can i display this file as an image?</p> <p>I tried </p> <pre><code>var nuroImage = new Image(); nuroImage.onload = function { scope.imageSrc = this.src; } $http(req).then( funciton(response) { nuroImage.src = "data:application/octet-stream," + response.data } </code></pre> <p>I get 200ok but the image isn't showing </p> <p>Is it possible to transform octet-stream to jpeg/png?</p>
37,510,957
3
1
null
2016-05-29 14:01:56.95 UTC
4
2021-06-29 09:06:32.217 UTC
2016-05-29 14:23:04.067 UTC
null
162,698
null
544,574
null
1
17
javascript|image
46,646
<p>You can use <a href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API" rel="noreferrer">fetch()</a> to request image as <code>Blob</code>, <a href="https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL" rel="noreferrer">URL.createObjectURL()</a> to create a blob URL from response</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>(async () =&gt; { const res = await fetch('https://httpbin.org/image/png') const blob = await res.blob() const img = new Image() img.src = URL.createObjectURL(blob) // newer promise based version of img.onload await img.decode() document.body.append(img) // Don't forget to revoke the blob url when // you no longer need it (to release memory) URL.revokeObjectURL(img.src) })()</code></pre> </div> </div> </p>
29,358,940
How to test a Jersey REST web service?
<p>I have written a Restful Web service and have to test it using JUnit4. I have already written a Client using Jersey Client. But want to know if I can test my service only with junit4. Can someone help me with sample at least. </p> <p>My rest service has authenticate method that takes user name, password and returns a token. </p> <p>I have written test case for authenticate method. But I am not sure how to test using url.</p> <pre><code>public class TestAuthenticate { Service service = new Service(); String username = "user"; String password = "password"; String token; @Test(expected = Exception.class) public final void testAuthenticateInputs() { password = "pass"; service.authenticate(username, password); } @Test(expected = Exception.class) public final void testAuthenticateException(){ username = null; String token = service.authenticate(username, password); assertNotNull(token); } @Test public final void testAuthenticateResult() { String token = service.authenticate(username, password); assertNotNull(token); } } </code></pre>
29,359,524
3
2
null
2015-03-31 01:09:15.293 UTC
9
2018-07-21 20:36:35.58 UTC
2016-08-24 14:58:45.66 UTC
null
5,078,385
null
4,375,063
null
1
18
java|rest|unit-testing|junit|jersey
39,803
<p>If you want to test using the URL, then you will need to start a server from your test. You can explicitly start an embedded server, which is pretty common for tests. Something like</p> <pre><code>public class MyResourceTest { public static final String BASE_URI = &quot;http://localhost:8080/api/&quot;; private HttpServer server; @Before public void setUp() throws Exception { final ResourceConfig rc = new ResourceConfig(Service.class); server = GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI), rc); } @After public void tearDown() throws Exception { server.stop(); } @Test public void testService() { Client client = ClientBuilder.newClient(); WebTarget target = client.target(BASE_URI).path(&quot;service&quot;); ... } } </code></pre> <p>It's basically an integration test. You're starting the Grizzly container and loading a <code>ResourceConfig</code> to the server with only the <code>Service</code> class. Of course you could add more classes to the configuration. You can use &quot;real&quot; resource config if you wanted.</p> <p>The above test uses this dependency</p> <pre><code>&lt;dependency&gt; &lt;groupId&gt;org.glassfish.jersey.containers&lt;/groupId&gt; &lt;artifactId&gt;jersey-container-grizzly2-http&lt;/artifactId&gt; &lt;version&gt;${jersey2.version}&lt;/version&gt; &lt;/dependency&gt; </code></pre> <p>Another option, which is the one I prefer, is to make use of the <a href="https://jersey.java.net/documentation/latest/test-framework.html" rel="noreferrer">Jersey Test Framework</a>, which will start an embedded container for you. A test might look something more like</p> <pre><code>public class SimpleTest extends JerseyTest { @Override protected Application configure() { return new ResourceConfig(Service.class); } @Test public void test() { String hello = target(&quot;service&quot;).request().get(String.class); } } </code></pre> <p>Using this dependency</p> <pre><code>&lt;dependency&gt; &lt;groupId&gt;org.glassfish.jersey.test-framework.providers&lt;/groupId&gt; &lt;artifactId&gt;jersey-test-framework-provider-grizzly2&lt;/artifactId&gt; &lt;version&gt;${jersey2.version}&lt;/version&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; </code></pre> <p>And embedded Grizzly container will get started under the hood, with your <code>ResourceConfig</code> configuration. In both examples above it is assumed the <code>@Path</code> value for the <code>Service</code> class is <code>service</code>, as you can see in the test URLs.</p> <h3>Some Resources</h3> <ul> <li><a href="https://jersey.github.io/documentation/latest/test-framework.html" rel="noreferrer">Jersey 2 Test Framework user guide</a></li> </ul> <p><strong>Some Examples</strong></p> <ul> <li><a href="https://stackoverflow.com/a/28671883/2587435">How to write Unit Test for this class using Jersey 2 test framework</a></li> <li><a href="https://stackoverflow.com/a/28620966/2587435">How to in-memory unit test Spring-Jersey</a></li> <li><a href="https://stackoverflow.com/a/27447345/2587435">Example with Mockito, Test Framework, and Jersey 2</a></li> <li><a href="https://stackoverflow.com/a/27596173/2587435">Example with Mockito, Test Framework, and Jersey 1</a></li> </ul> <hr /> <h3>UPDATE</h3> <p>If you're not using Maven, here are the jars you will need to run an embedded Grizzly container for the Jersey Test Fraemwork</p> <p><img src="https://i.stack.imgur.com/txOcs.png" alt="enter image description here" /></p> <p>I usually search for all my jars <a href="http://mvnrepository.com/artifact/com.sun.jersey.jersey-test-framework/jersey-test-framework-grizzly2" rel="noreferrer">here</a>. You can select the version and there should be a link in the next page, to download. You can use the search bar to search for the others.</p> <p>Here's a simple running example, once you have all the jars</p> <pre><code>import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.core.DefaultResourceConfig; import com.sun.jersey.spi.container.servlet.WebComponent; import com.sun.jersey.test.framework.JerseyTest; import com.sun.jersey.test.framework.WebAppDescriptor; import javax.ws.rs.GET; import javax.ws.rs.Path; import junit.framework.Assert; import org.junit.Test; public class SimpleTest extends JerseyTest { @Path(&quot;service&quot;) public static class Service { @GET public String getTest() { return &quot;Hello World!&quot;; } } public static class AppConfig extends DefaultResourceConfig { public AppConfig() { super(Service.class); } } @Override public WebAppDescriptor configure() { return new WebAppDescriptor.Builder() .initParam(WebComponent.RESOURCE_CONFIG_CLASS, AppConfig.class.getName()) .build(); } @Test public void doTest() { WebResource resource = resource().path(&quot;service&quot;); String result = resource.get(String.class); Assert.assertEquals(&quot;Hello World!&quot;, result); System.out.println(result); } } </code></pre> <p>You're most likely not going to have the resources and <code>ResourceConfig</code> in the same class as the test, but I just want to keep it simple and all visible in one class.</p> <p>Whether you are using a web.xml or a <code>ResourceConfig</code> subclass (as shown above), you can cut down what you test by using a separate <code>ResourceConfig</code>, built in the test class, as I have done. Otherwise, if you are using your normal <code>ResourceConfig</code> class, you can just replace it in the <code>configure</code> method.</p> <p>The <code>configure</code> method, is pretty much just building a web.xml file, just in Java code. You can see different methods in the <code>WebAppDescriptor.Builder</code>, like <code>initParam</code>, which is the same as an <code>&lt;init-param&gt;</code> in your web xml. You can simply use the string in the arguments, but there are some constants, as I used above.</p> <p>The <code>@Test</code> is you usual JUnit test that will run. It is using the Jersey Client. But instead of creating the <code>Client</code>, you can simply just use the preconfigured <code>Client</code> by just accessing the <code>resource()</code> method, which returns a <code>WebResource</code>. If you are familiar with the Jersey Client, then this class should not be new to you.</p>
39,542,485
How to write Pipeline to discard old builds?
<p>The groovy syntax generator is NOT working for sample step <code>properties: Set Job Properties</code>. I've selected <code>Discard old builds</code> and then entered <code>10</code> in the <code>Max # of builds to keep</code> field and then <code>Generate Groovy</code> and nothing shows up.</p> <p>Jenkins version: 2.7</p>
39,544,277
10
1
null
2016-09-17 03:07:35.423 UTC
15
2022-06-29 15:34:41.267 UTC
2016-09-17 10:34:10.003 UTC
null
400,222
null
476,410
null
1
105
jenkins|jenkins-pipeline
87,191
<p>You can use the <code>properties</code> method which, nested within the <code>BuildDiscarderProperty</code> eventually has the key you want to set. I still don't have a solid way to look up the correct syntax of each key. After much guessing and checking:</p> <pre><code>properties([[$class: 'BuildDiscarderProperty', strategy: [$class: 'LogRotator', artifactDaysToKeepStr: '', artifactNumToKeepStr: '', daysToKeepStr: '', numToKeepStr: '10']]]); </code></pre> <p>Note that this snippet is for scripted syntax. </p>
26,852,128
SMTPAuthenticationError when sending mail using gmail and python
<p>when i try to send mail using gmail and python error occurred this type of question are already in this site but doesn't help to me </p> <pre><code>gmail_user = "[email protected]" gmail_pwd = "password" TO = '[email protected]' SUBJECT = "Testing sending using gmail" TEXT = "Testing sending mail using gmail servers" server = smtplib.SMTP('smtp.gmail.com', 587) server.ehlo() server.starttls() server.login(gmail_user, gmail_pwd) BODY = '\r\n'.join(['To: %s' % TO, 'From: %s' % gmail_user, 'Subject: %s' % SUBJECT, '', TEXT]) server.sendmail(gmail_user, [TO], BODY) print ('email sent') </code></pre> <p>error:</p> <pre><code> server.login(gmail_user, gmail_pwd) File "/usr/lib/python3.4/smtplib.py", line 639, in login raise SMTPAuthenticationError(code, resp) smtplib.SMTPAuthenticationError: (534, b'5.7.14 &lt;https://accounts.google.com/ContinueSignIn?sarp=1&amp;scc=1&amp;plt=AKgnsbtl1\n5.7.14 Li2yir27TqbRfvc02CzPqZoCqope_OQbulDzFqL-msIfsxObCTQ7TpWnbxIoAaQoPuL9ge\n5.7.14 BUgbiOqhTEPqJfb02d_L6rrdduHSxv26s_Ztg_JYYavkrqgs85IT1xZYwtbWIRE8OIvQKf\n5.7.14 xxtT7ENlZTS0Xyqnc1u4_MOrBVW8pgyNyeEgKKnKNyxce76JrsdnE1JgSQzr3pr47bL-kC\n5.7.14 XifnWXg&gt; Please log in via your web browser and then try again.\n5.7.14 Learn more at\n5.7.14 https://support.google.com/mail/bin/answer.py?answer=78754 fl15sm17237099pdb.92 - gsmtp') </code></pre>
26,852,782
3
1
null
2014-11-10 20:08:36.723 UTC
29
2021-04-10 01:51:04.227 UTC
2015-12-21 22:24:10.523 UTC
null
895,245
null
3,851,743
null
1
86
python|smtplib
168,103
<p>Your code looks correct. Try logging in through your browser and if you are able to access your account come back and try your code again. Just make sure that you have typed your username and password correct</p> <p><strong>EDIT</strong>: Google blocks sign-in attempts from apps which do not use modern security standards (mentioned on their support <a href="https://support.google.com/accounts/answer/6010255?hl=en">page</a>). You can however, turn on/off this safety feature by going to the link below:</p> <p>Go to this link and select <strong>Turn On</strong><br> <a href="https://www.google.com/settings/security/lesssecureapps">https://www.google.com/settings/security/lesssecureapps</a></p>
55,149,221
Class with static methods vs exported functions typescript
<p>I've been trying to research this but can't see to find any recommendations. I've inherited a code base where the team is using classes with static methods instead of functions for helper methods. I've never seen this approach taken and trying to decide if I should have them go back and create functions out of them. I feel like this is unclean and bloats imports since you're importing the entire class instead of just the function you're intending?</p> <p>Is one approach better than the other? </p> <p>For example's sake in case I'm not being clear:</p> <pre class="lang-js prettyprint-override"><code> export class StringUtil { public static alterString(str: string) { return alteredString; } } </code></pre> <p>vs</p> <pre class="lang-js prettyprint-override"><code> export function alterString(str: string) { return alteredString; } </code></pre> <p>This would then be used like so:</p> <pre class="lang-js prettyprint-override"><code>import { StringUtil } from '../StringUtil'; getString(str: string) { return StringUtil.alterString(str); } </code></pre> <p>vs </p> <pre class="lang-js prettyprint-override"><code>import { alterString } from '../helper-functions'; getString(str: string) { return alterString(str); } </code></pre>
55,152,202
2
2
null
2019-03-13 18:45:38.593 UTC
5
2021-09-05 02:00:55.51 UTC
2019-03-13 18:53:09.877 UTC
null
2,843,172
null
2,843,172
null
1
30
typescript
7,309
<p>Functionally, both implementations will produce the same result with the only difference being that for static methods the function is attached to the class' prototype. If you don't actually need that behavior (unlikely that you do), I'd keep you static methods as separate functions as this is better for tree-shaking and code-splitting (unless you have a LOT of static methods though, these will be only minor gains). In practice, I find that static methods usually only appear for two reasons: (1) whoever wrote the code is used to Java and (2) some IDEs present warnings that you should mark methods as static if they don't use instance variables.</p> <p>If you just want that ability to namespace a bunch of static methods, you can still do so by exporting an object with all of the individual functions attached.</p>
57,431,196
Dereferencing a pointer in a 'for' loop initializer creates a segmentation fault
<p>I'm having a problem using pointers in a <code>for</code> loop. In my <code>for</code> loop initializer, I dereference an <code>int</code> pointer and give it a value of '0'. When I use that dereferenced pointer in the loop I get a segmentation fault, and I don't understand why. I am using <a href="http://en.wikipedia.org/wiki/Code::Blocks" rel="noreferrer">Code::Blocks</a> and the C GNU GCC compiler.</p> <ol> <li><p>Looking at the watch window I can see that during the <code>for</code> loop the variable has a random number.</p></li> <li><p>It seems that the dereferenced pointer loses scope during the <code>for</code> loop.</p></li> </ol> <p>The code:</p> <pre><code>#include &lt;stdio.h&gt; int main(void) { int val = 0; int *p = NULL; int answer = 0; p = &amp;val; *p = 1; // This dereferences and sets to one successfully for (int i=3, (*p)=0 ; i&gt;=0; i--) // Here *p is a random number { printf("do stuff"); (*p) += 1; // Here it causes a segmentation fault } answer = *p; } </code></pre> <p>I thought that there would be no problems using a pointer the way I am.</p>
57,431,303
3
1
null
2019-08-09 13:32:33.957 UTC
4
2019-08-15 20:23:43.957 UTC
2019-08-15 20:23:43.957 UTC
null
1,687,119
null
5,313,435
null
1
45
c|for-loop|pointers|declaration
2,198
<p>Take a close look here:</p> <pre><code>for (int i=3, (*p)=0 ; i&gt;=0; i--) </code></pre> <p>In the first part of the <code>for</code> you're defining a <strong>new</strong> pointer variable named <code>p</code> which shadows the <code>p</code> defined earlier and initializing it to NULL. You then dereference the NULL pointer in the loop which causes the segfault.</p> <p>You can't have both a variable definition and an assignment to an existing variable together like that, so move the assignment of <code>*p</code> to before the loop:</p> <pre><code>*p = 0; for (int i=3; i&gt;=0; i--) </code></pre> <p>Or you can define <code>i</code> outside of the loop:</p> <pre><code>int i; for (i=3, (*p)=0 ; i&gt;=0; i--) </code></pre> <p>You <em>could</em> squeeze these together by abusing the comma operator:</p> <pre><code>for (int i=(*p=0,3) ; i&gt;=0; i--) </code></pre> <p>Here the assignment to <code>p</code> happens as part of the initializer for <code>i</code> so it doesn't declare a new variable. But I wouldn't recommend this as it would make your code more difficult to read and understand.</p>
57,545,884
How to develop a simple REST Client using Swagger codegen?
<p>I'm learning about Swagger and how to generate REST Client using Swagger codegen. I know how to do documentation with Swagger, also I know how to generate a simple REST Server with Swagger, but I don't know how to generate a simple REST Client with Swagger codegen.</p> <p>For example, I have a simple app, it is a REST Server and I want to generate REST Client. Can I do that with Swagger codegen? </p> <p>The controller for the REST Server:</p> <pre><code>package com.dgs.spring.springbootswagger.controller; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; @RestController @RequestMapping("/api/v1") @Api(value = "Employee Management System", description = "Operations pertaining to employee in Employee Management System") public class EmployeeController { @Autowired private EmployeeRepository employeeRepository; @ApiOperation(value = "View a list of available employees", response = List.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "Successfully retrieved list"), @ApiResponse(code = 401, message = "You are not authorized to view the resource"), @ApiResponse(code = 403, message = "Accessing the resource you were trying to reach is forbidden"), @ApiResponse(code = 404, message = "The resource you were trying to reach is not found") }) @GetMapping("/employees") public List&lt;Employee&gt; getAllEmployees() { return employeeRepository.findAll(); } @ApiOperation(value = "Get an employee by Id") @GetMapping("/employees/{id}") public ResponseEntity&lt;Employee&gt; getEmployeeById( @ApiParam(value = "Employee id from which employee object will retrieve", required = true) @PathVariable(value = "id") Long employeeId) throws ResourceNotFoundException { Employee employee = employeeRepository.findById(employeeId) .orElseThrow(() -&gt; new ResourceNotFoundException("Employee not found for this id :: " + employeeId)); return ResponseEntity.ok().body(employee); } @ApiOperation(value = "Add an employee") @PostMapping("/employees") public Employee createEmployee( @ApiParam(value = "Employee object store in database table", required = true) @Valid @RequestBody Employee employee) { return employeeRepository.save(employee); } @ApiOperation(value = "Update an employee") @PutMapping("/employees/{id}") public ResponseEntity&lt;Employee&gt; updateEmployee( @ApiParam(value = "Employee Id to update employee object", required = true) @PathVariable(value = "id") Long employeeId, @ApiParam(value = "Update employee object", required = true) @Valid @RequestBody Employee employeeDetails) throws ResourceNotFoundException { Employee employee = employeeRepository.findById(employeeId) .orElseThrow(() -&gt; new ResourceNotFoundException("Employee not found for this id :: " + employeeId)); employee.setEmail(employeeDetails.getEmail()); employee.setLastName(employeeDetails.getLastName()); employee.setFirstName(employeeDetails.getFirstName()); final Employee updatedEmployee = employeeRepository.save(employee); return ResponseEntity.ok(updatedEmployee); } @ApiOperation(value = "Delete an employee") @DeleteMapping("/employees/{id}") public Map&lt;String, Boolean&gt; deleteEmployee( @ApiParam(value = "Employee Id from which employee object will delete from database table", required = true) @PathVariable(value = "id") Long employeeId) throws ResourceNotFoundException { Employee employee = employeeRepository.findById(employeeId) .orElseThrow(() -&gt; new ResourceNotFoundException("Employee not found for this id :: " + employeeId)); employeeRepository.delete(employee); Map&lt;String, Boolean&gt; response = new HashMap&lt;&gt;(); response.put("deleted", Boolean.TRUE); return response; } } </code></pre> <p>After that I've developed a simple REST Client:</p> <pre><code>package com.dgs.restclient.controllers; @Controller public class UpdateController { @Autowired private EmployeeRestClient restClient; @GetMapping("/showStartUpdate") public String showStartCheckin() { return "startUpdate"; } @PostMapping("/startUpdate") public String startCheckIn(@RequestParam("employeeId") Long employeeId, ModelMap modelMap) { Employee employee = restClient.findEmployee(employeeId); modelMap.addAttribute("employee", employee); return "displayEmployeeDetails"; } @PostMapping("/completeUpdate") public String completeCheckIn(@RequestParam("employeeId") Long employeeId, @RequestParam("employeeFirstName") String employeeFirstName, @RequestParam("employeeLastName") String employeeLastName, @RequestParam("employeeEmail") String employeeEmail) { EmployeeUpdateRequest employeeUpdateRequest = new EmployeeUpdateRequest(); employeeUpdateRequest.setId(employeeId); employeeUpdateRequest.setFirstName(employeeFirstName); employeeUpdateRequest.setLastName(employeeLastName); employeeUpdateRequest.setEmail(employeeEmail); restClient.updateEmployee(employeeUpdateRequest); return "updateConfirmation"; } } </code></pre> <p>The EmployeeRestClient:</p> <pre><code>package com.dgs.restclient.integration; @Component public class EmployeeRestClientImpl implements EmployeeRestClient { private static final String EMPLOYEE_REST_URL = "http://localhost:8080/api/v1/employees/"; @Override public Employee findEmployee(Long id) { RestTemplate restTemplate = new RestTemplate(); Employee employee = restTemplate .getForObject(EMPLOYEE_REST_URL + id, Employee.class); return employee; } @Override public Employee updateEmployee(EmployeeUpdateRequest request) { RestTemplate restTemplate = new RestTemplate(); restTemplate .put(EMPLOYEE_REST_URL + request.getId(), request, Employee.class); Employee employee = restTemplate .getForObject(EMPLOYEE_REST_URL + request.getId(), Employee.class); return employee; } } </code></pre> <p>This REST Client is developed by me and I want to know if I can do this REST Client development with Swagger codegen and how? Do I need just to add the swagger-codegen-maven-plugin in the pom.xml? I've heard about adding this plugin and a yml file and Swagger will create the REST Client. Any feedback will be appreciated!</p>
57,602,409
6
2
null
2019-08-18 15:17:42.193 UTC
11
2022-02-26 16:44:21.85 UTC
2019-08-24 22:20:09.773 UTC
null
339,637
null
7,516,740
null
1
17
java|spring-boot|swagger|rest-client|swagger-codegen
45,361
<p>Yes. You can use <a href="https://github.com/swagger-api/swagger-codegen/blob/master/modules/swagger-codegen-maven-plugin/README.md" rel="noreferrer"><code>swagger-codegen-maven-plugin</code></a> to generate a REST client. But before that , you need to describe the REST API in YAML or JSON in <a href="https://swagger.io/docs/specification/about/" rel="noreferrer"><code>OpenAPI Specification</code></a> mainly because <code>swagger-codegen-maven-plugin</code> only can generate a REST client from a file written in this specification.</p> <p>Other answers assume that you need to write the specification manually while my solution take a step further to automatically generating the specification from the REST controller source codes. </p> <p><sup><em>The latest OpenAPI version is 3.0 .But based on the package of your imported swagger annotation , you are using version 2.0 (or before). So my solution assume you are using OpenAPI 2.0.</em></sup></p> <p><strong>Generating Open API Specification</strong></p> <p>First, you can use <a href="https://github.com/kongchen/swagger-maven-plugin" rel="noreferrer">swagger-maven-plugin</a> to generate an OpenAPI spec from the RestController source codes. It basically analyses the Swagger annotations annotated in the <code>@RestController</code> classes that specified in <code>&lt;locations&gt;</code> and dump the OpenAPI spec to <code>/src/main/resources/swagger.json</code> :</p> <pre><code>&lt;plugin&gt; &lt;groupId&gt;com.github.kongchen&lt;/groupId&gt; &lt;artifactId&gt;swagger-maven-plugin&lt;/artifactId&gt; &lt;version&gt;3.1.5&lt;/version&gt; &lt;configuration&gt; &lt;apiSources&gt; &lt;apiSource&gt; &lt;springmvc&gt;true&lt;/springmvc&gt; &lt;locations&gt; &lt;location&gt;com.dgs.spring.springbootswagger.controller.EmployeeController&lt;/location&gt; &lt;location&gt;com.dgs.spring.springbootswagger.controller.FooController&lt;/location&gt; &lt;/locations&gt; &lt;schemes&gt; &lt;scheme&gt;http&lt;/scheme&gt; &lt;/schemes&gt; &lt;host&gt;127.0.0.1:8080&lt;/host&gt; &lt;basePath&gt;/&lt;/basePath&gt; &lt;info&gt; &lt;title&gt;My API&lt;/title&gt; &lt;version&gt;1.1.1&lt;/version&gt; &lt;/info&gt; &lt;swaggerDirectory&gt;${basedir}/src/main/resources/&lt;/swaggerDirectory&gt; &lt;/apiSource&gt; &lt;/apiSources&gt; &lt;/configuration&gt; &lt;executions&gt; &lt;execution&gt; &lt;goals&gt; &lt;goal&gt;generate&lt;/goal&gt; &lt;/goals&gt; &lt;/execution&gt; &lt;/executions&gt; &lt;/plugin&gt; </code></pre> <p>Execute the followings maven command to start generation: </p> <pre><code>mvn clean compile </code></pre> <p><strong>Generating Rest Client</strong></p> <p>After <code>swagger.json</code> is generated, you can copy and paste it to your client project (e.g. /src/main/resources/swagger.json) . We can then use <code>swagger-codegen-maven-plugin</code> to generate a HTTP client . </p> <p>By default , it will generate the <a href="https://github.com/swagger-api/swagger-codegen/issues/1737" rel="noreferrer">whole maven project</a> which includes test cases and other documentation stuff. But what I want is just the HttpClient 's source codes without other things. After several trial and error , I settle down to the following configuration :</p> <pre><code>&lt;plugin&gt; &lt;groupId&gt;io.swagger&lt;/groupId&gt; &lt;artifactId&gt;swagger-codegen-maven-plugin&lt;/artifactId&gt; &lt;version&gt;2.4.7&lt;/version&gt; &lt;executions&gt; &lt;execution&gt; &lt;goals&gt; &lt;goal&gt;generate&lt;/goal&gt; &lt;/goals&gt; &lt;configuration&gt; &lt;inputSpec&gt;${basedir}/src/main/resources/swagger.json&lt;/inputSpec&gt; &lt;language&gt;java&lt;/language&gt; &lt;library&gt;resttemplate&lt;/library&gt; &lt;output&gt;${project.basedir}/target/generated-sources/&lt;/output&gt; &lt;apiPackage&gt;com.example.demo.restclient.api&lt;/apiPackage&gt; &lt;modelPackage&gt;com.example.demo.restclient.model&lt;/modelPackage&gt; &lt;invokerPackage&gt;com.example.demo.restclient&lt;/invokerPackage&gt; &lt;generateApiTests&gt;false&lt;/generateApiTests&gt; &lt;generateModelTests&gt;false&lt;/generateModelTests&gt; &lt;generateApiDocumentation&gt;false&lt;/generateApiDocumentation&gt; &lt;generateModelDocumentation&gt;false&lt;/generateModelDocumentation&gt; &lt;configOptions&gt; &lt;dateLibrary&gt;java8&lt;/dateLibrary&gt; &lt;sourceFolder&gt;restclient&lt;/sourceFolder&gt; &lt;/configOptions&gt; &lt;/configuration&gt; &lt;/execution&gt; &lt;/executions&gt; &lt;/plugin&gt; </code></pre> <p>The generated HTTP client is based on RestTemplate and will be generated to the folder <code>target/generated-sources/restclient</code>. You may have to configure your IDE to import the generated client in order to use it . <em>(In case of Eclipse, you can configure in Project Properties ➡️ Java Build Path ➡️ Add the folder of the generated rest client)</em> </p> <p>To start generating the client , just execute the maven command :</p> <pre><code>mvn clean compile </code></pre> <p>To use the generated HTTP client :</p> <pre><code>ApiClient apiClient = new ApiClient(); //Override the default API base path configured in Maven apiClient.setBasePath("http://api.example.com/api"); EmployeeManagementSystemApi api = new EmployeeManagementSystemApi(apiClient); api.getEmployeeById(1l); </code></pre> <hr> <p>Note :</p> <ul> <li>If you come across <code>javax/xml/bind/annotation/XmlRootElement</code> exception during generation when using java8+ , you may need to refer to <a href="https://stackoverflow.com/questions/46220810/add-modules-only-on-compilation">this</a>.</li> </ul>
7,408,973
MVC 3 - how to implement a service layer, do I need repositories?
<p>I am currently building my first MVC 3 application, using EF Code First, SQL CE and Ninject. I have read a lot about using Repositories, Unit of Work and Service Layers. I think I have got the basics sorted out, and I have made my own implementation.</p> <p>This is my current setup:</p> <p><strong>Entities</strong></p> <pre><code>public class Entity { public DateTime CreatedDate { get; set; } public Entity() { CreatedDate = DateTime.Now; } } public class Profile : Entity { [Key] public Guid UserId { get; set; } public string ProfileName { get; set; } public virtual ICollection&lt;Photo&gt; Photos { get; set; } public Profile() { Photos = new List&lt;Photo&gt;(); } public class Photo : Entity { [Key] public int Id { get; set; } public Guid FileName { get; set; } public string Description { get; set; } public virtual Profile Profile { get; set; } public Photo() { FileName = Guid.NewGuid(); } } </code></pre> <p><strong>SiteContext</strong></p> <pre><code>public class SiteContext : DbContext { public DbSet&lt;Profile&gt; Profiles { get; set; } public DbSet&lt;Photo&gt; Photos { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Conventions.Remove&lt;PluralizingTableNameConvention&gt;(); } } </code></pre> <p><strong>Interface: IServices</strong></p> <pre><code>public interface IServices : IDisposable { PhotoService PhotoService { get; } ProfileService ProfileService { get; } void Save(); } </code></pre> <p><strong>Implementation: Services</strong></p> <pre><code>public class Services : IServices, IDisposable { private SiteContext _context = new SiteContext(); private PhotoService _photoService; private ProfileService _profileService; public PhotoService PhotoService { get { if (_photoService == null) _photoService = new PhotoService(_context); return _photoService; } } public ProfileService ProfileService { get { if (_profileService == null) _profileService = new ProfileService(_context); return _profileService; } } public void Save() { _context.SaveChanges(); } private bool disposed = false; protected virtual void Dispose(bool disposing) { if (!this.disposed) { if (disposing) { _context.Dispose(); } } this.disposed = true; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } } </code></pre> <p><strong>Interface</strong></p> <pre><code>public interface IPhotoService { IQueryable&lt;Photo&gt; GetAll { get; } Photo GetById(int photoId); Guid AddPhoto(Guid profileId); } </code></pre> <p><strong>Implementation</strong></p> <pre><code>public class PhotoService : IPhotoService { private SiteContext _siteContext; public PhotoService(SiteContext siteContext) { _siteContext = siteContext; } public IQueryable&lt;Photo&gt; GetAll { get { return _siteContext.Photos; } } public Photo GetById(int photoId) { return _siteContext.Photos.FirstOrDefault(p =&gt; p.Id == photoId); } public Guid AddPhoto(Guid profileId) { Photo photo = new Photo(); Profile profile = _siteContext.Profiles.FirstOrDefault(p =&gt; p.UserId == profileId); photo.Profile = profile; _siteContext.Photos.Add(photo); return photo.FileName; } } </code></pre> <p><strong>Global.asax</strong></p> <pre><code>protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RegisterGlobalFilters(GlobalFilters.Filters); RegisterRoutes(RouteTable.Routes); ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory()); Database.SetInitializer&lt;SiteContext&gt;(new SiteInitializer()); } </code></pre> <p><strong>NinjectControllerFactory</strong></p> <pre><code>public class NinjectControllerFactory : DefaultControllerFactory { private IKernel ninjectKernel; public NinjectControllerFactory() { ninjectKernel = new StandardKernel(); AddBindings(); } protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType) { return controllerType == null ? null : (IController)ninjectKernel.Get(controllerType); } private void AddBindings() { ninjectKernel.Bind&lt;IServices&gt;().To&lt;Services&gt;(); } } </code></pre> <p><strong>PhotoController</strong></p> <pre><code>public class PhotoController : Controller { private IServices _services; public PhotoController(IServices services) { _services = services; } public ActionResult Show(int photoId) { Photo photo = _services.PhotoService.GetById(photoId); if (photo != null) { string currentProfile = "Profile1"; _services.PhotoService.AddHit(photo, currentProfile); _services.Save(); return View(photo); } else { // Add error message to layout TempData["message"] = "Photo not found!"; return RedirectToAction("List"); } } protected override void Dispose(bool disposing) { _services.Dispose(); base.Dispose(disposing); } } </code></pre> <p>I can build my solution and it seems to be working correctly.</p> <p>My questions are:</p> <ol> <li>Are there any obvious flaws in my implementation that I am missing?</li> <li>Will I be able to use this with TDD? Usually I see mocking of repositories but I haven't used that in the above, will that cause issues?</li> <li>Am I using DI (Ninject) correctly and enough?</li> </ol> <p>I am a hobby programmer, so any comments and/or suggestions to my code are welcome!</p>
7,409,090
3
2
null
2011-09-13 21:48:34.123 UTC
12
2013-06-28 09:02:25.303 UTC
null
null
null
null
857,793
null
1
21
c#|entity-framework|asp.net-mvc-3|design-patterns|ninject
6,813
<p>You've got the general idea, but it takes a while to really get used to Dependency Injection. I see a number of possible improvements to be made:</p> <ol> <li>Your <code>IServices</code> interface seems unnecessary. I'd prefer to have the controller specify which services it needs (IPhotoService, etc.) via its constructor, rather than using the <code>IServices</code> interface like some kind of strongly-typed service locator.</li> <li>Did I see a <code>DateTime.Now</code> in there? How are you going to verify that the date gets set correctly in a unit test? What if you decide to support multiple time zones later? How about using an injected date service to produce that <code>CreatedDate</code>?</li> <li>There is a very good Ninject extension specifically for MVC. It takes care of plugging into the various points that MVC 3 supports for injection. It implements things like your NinjectControllerFactory. All you have to do is make your <code>Global</code> class extend a specific Ninject-based application.</li> <li>I'd suggest using NinjectModules for setting your bindings, rather than setting them in your ControllerFactory.</li> <li>Consider using Binding by Convention so that you don't have to explicitly bind each service to its implementation.</li> </ol> <h3>Update</h3> <p>The Ninject MVC Extension can be found <a href="https://github.com/ninject/ninject.web.mvc" rel="noreferrer">here</a>. See the README section for an example of how to extend the <code>NinjectHttpApplication</code>. This example uses Modules, which you can read more about <a href="https://github.com/ninject/ninject/wiki/Modules-and-the-Kernel" rel="noreferrer">here</a>. (They're basically just a place to put your binding code so that you don't violate the Single Responsibility Principle.)</p> <p>Regarding conventions-based bindings, the general idea is to have your binding code scan the appropriate assemblies and automatically bind things like <code>IPhotoService</code> to <code>PhotoService</code> based on the naming convention. There is another extension <a href="https://github.com/ninject/ninject.extensions.conventions" rel="noreferrer">here</a> to help with such things. With it, you can put code like this in your module:</p> <pre><code>Kernel.Scan(s =&gt; { s.From(assembly); s.BindWithDefaultConventions(); }); </code></pre> <p>The above code will auto-bind every class in the given assembly to any interface it implements that follows the &quot;Default&quot; conventions (e.g. <code>Bind&lt;IPhotoService&gt;().To&lt;PhotoService&gt;()</code>).</p> <h3>Update 2</h3> <p>Regarding using the same DbContext for an entire request, you can do something like this (using the <code>Ninject.Web.Common</code> library, which is required by the MVC extension):</p> <pre><code>Bind&lt;SiteContext&gt;().ToSelf().InRequestScope(); </code></pre> <p>Then any context-dependent services that Ninject creates will share the same instance across a request. Note that I have personally used shorter-lived contexts, so I don't know off the top of my head how you'd force the context to be disposed at the end of the request, but I'm sure it wouldn't be too difficult.</p>
7,199,097
Constructor injection into a base class using autofac
<p>I have an abstract base controller which has a constructor I hoped would be populated by autofac when the controllers were built.</p> <pre><code>public abstract class BaseController : Controller { protected ILogger { get; private set; } protected BaseController() { } protected BaseController(ILogger logger) { Logger = logger; } } </code></pre> <p>This doesn't seem to work when I derive a controller from it.</p> <p>I can only get this to work when I explicitly call the constructor explicitly from the controller. Is this the correct way to do this?</p> <pre><code>public class PublicController : BaseController { public PublicController() { } public PublicController(ILogger logger) : base(logger) { } } </code></pre> <p>Also, using the MVC integration assembly, there doesn't seem to be a way to share the container for other classes to do their own resolving. I read somewhere that this is not encouraged, why not? Is this just to decouple the dependency of any single ioc framework? Is constructor injection the <em>only</em> way to populate dependencies down the hierarchy?</p>
7,200,082
3
0
null
2011-08-26 01:20:25.193 UTC
11
2021-04-29 03:26:59.63 UTC
2021-04-29 03:26:59.63 UTC
null
3,964,927
null
532,958
null
1
29
constructor|autofac|code-injection|abstract
12,501
<p>Calling the base class constructor explicitly is the only way to do this using constructor injection in C#. It looks like you should remove the parameterless constructors from <code>BaseController</code> and <code>PublicController</code> as they should never actually be called when a logger is available.</p> <p>The problem of injecting dependencies into a base controller is a common one using ASP.NET MVC and IoC. There are several options/schools of thought.</p> <p>1.) Use aggregate services. To keep derived class constructors simple, create a single service that exposes or delegates to all the different services needed by the base controller (e.g. <code>IBaseControllerDependencies</code> or similar.) Then pass this one service to the <code>BaseController</code> just as you are doing with <code>ILogger</code> here.</p> <p>There are various pros/cons depending on your application and the number of base classes you're using. Google for 'Autofac aggregate services' to see more on this.</p> <p>2.) Use property injection. Make the <code>ILogger</code> property on your base class public, and configure the container using:</p> <pre><code>builder.RegisterControllers().PropertiesAutowired(); </code></pre> <p>Property injection isn't really a preferred technique in Autofac. The constructor's role <em>is</em> to accept dependencies, while writeable properties are often seen as a code smell, so Autofac doesn't really optimise for this case. One of the drawbacks is that writeable properties that <em>shouldn't</em> be injected often are mistakenly, with odd consequences.</p> <p>3.) Refactor base controller functionality into various action filters. Autofac can inject action filters into the MVC action invocation pipeline. Thus the filters can take the dependencies that were on the base class, and the same concerns might be applied in a cross-cutting way. More info on this out on the web, <code>ExtensibleActionInvoker</code> and <code>.InjectActionInvoker()</code> point to the info you'd need. Not always possible with all concerns.</p> <p>4, also the answer to your second question.) Resolve base controller dependencies using service location from <code>DependencyResolver.Current</code>.</p> <pre><code>var logger = DependencyResolver.Current.GetService&lt;ILogger&gt;(); </code></pre> <p>The reason this isn't encouraged is that it makes the resulting application harder to understand because it is no longer possible to see what services a component depends upon by looking in one place (the constructor.) To determine what must be configured in the container before a particular component can be used, one has to look at the entire codebase of the component to find the <code>GetService()</code> calls. A noticeable impediment when unit testing.</p> <p>Hope this helps, bit of a brain dump I know :) Others can probably add some more ideas to these.</p>
7,550,638
Should F# functions be placed in modules, classes, or another structure?
<p>I'm starting to code in F# and am calling functions from functions with functions as parameters - there are plenty of learning resources online. Now I am trying to put together the pieces into something more than just a collection of functions. Unfortunately I'm not finding many resources dealing with structure, design, or even how the 'bits' tie together.</p> <p>I've found the <code>namespace</code> keyword (e.g. <code>namespace MyOnlyNamespace</code>) but I get a compiler error on the functions that I've placed inside the namespace:</p> <blockquote> <p>Namespaces cannot contain values. Consider using a module to hold your value declarations.</p> </blockquote> <p>When I add <code>module CoolFunctions</code> I get </p> <blockquote> <p>Unexpected start of structured construct in definition. Expected '=' or other token</p> </blockquote> <p>So I have a multi-part question (but please answer any part that you can)</p> <ul> <li>What is a module? </li> <li>Is it like a class (something like a VB.NET module) or is it something else altogether?</li> <li>If something else, then are there classes in F#?</li> <li>Are there other structures that I should be using instead?</li> <li>How do I declare a module?</li> </ul>
7,553,653
3
0
null
2011-09-26 04:24:29.647 UTC
11
2011-09-26 10:20:10.617 UTC
null
null
null
null
146,077
null
1
31
f#|functional-programming
6,257
<p>To give some specific recommendations about choosing between namespaces, modules abd classes in F#:</p> <ul> <li><p>If you're writing functions using <code>let</code> that are expected to be used from F#, then putting them inside a module is the best choice. This gives you API similar to <code>List.map</code> and other basic F# functions.</p> <p>Regarding naming, you should use <code>camelCase</code> unless you expect C# users to call the functions too. In that case, you should use <code>PascalCase</code> (and note that module will be compiled to a static class).</p> </li> <li><p>If you're writing type delcarations, then these should generally be placed in a namespace. They are allowed inside modules too, but then they'll be compiled as nested classes.</p> </li> <li><p>If you're writing F# classes, then they should be placed in namespaces too. In generall, if you're writing F# code that will be called by C#, then using classes is the best mechanism as you get full control of what the user will see (F# class is compiled to just a class).</p> </li> </ul> <p>If you have a file, it can either start with <code>namespace Foo.Bar</code> or <code>module Foo.Bar</code>, which places all code in the file inside a namespace or a module. You can always nest more modules inside this top-level declaration. A common pattern is to start with a single <code>namespace</code> and then include some type and module declarations in the file:</p> <pre><code>namespace MyLibrary type SomeType = // ... module SomeFuncs = let operation (st:SomeType) = // ... </code></pre>
7,507,038
Semicolons superfluous at the end of a line in shell scripts?
<p>I have a shell script which contains the following:</p> <pre><code>case $1 in 0 ) echo $1 = 0; OUTPUT=3;; 1 ) echo $1 = 1; OUTPUT=4;; 2 ) echo $1 = 2; OUTPUT=4;; esac HID=$2; BUNCH=16; LR=.008; </code></pre> <p>Are <em>semicolons</em> completely superfluous in the snippet above? And is there any reason for some people using double semicolons?</p> <p>It appears semicolons are only a separator, something you would use instead of a new line.</p>
7,507,068
4
0
null
2011-09-21 21:42:11.157 UTC
18
2019-09-30 11:51:30.487 UTC
2019-03-24 11:02:30.25 UTC
null
10,607,772
null
662,939
null
1
120
bash|shell|syntax
74,222
<p>Single semicolons at the end of a line are superfluous, since the newline is also a command separator. <code>case</code> specifically needs double semicolons at the end of the last command in each pattern block; see <code>help case</code> for details.</p>
8,320,462
ggplot2: How to adjust fill colour in a boxplot (and change legend text)?
<p>How can I:</p> <ol> <li>Set the fill colors in the boxplot below? I tried the argument "colour" but that failed.</li> <li><p>Change the legend text from "0", "1" to something else?</p> <pre><code>require(ggplot2) ggplot(mtcars, aes(factor(cyl), mpg)) + geom_boxplot(aes(fill=factor(vs), colour=c("grey50", "white"))) </code></pre></li> </ol>
8,320,636
1
0
null
2011-11-30 02:34:50.07 UTC
4
2016-05-13 01:07:28.943 UTC
2011-11-30 04:55:20.78 UTC
null
324,364
null
961,264
null
1
11
r|ggplot2
47,189
<p>Instead of the colour aesthetic, you want to adjust the fill aesthetic. You can handle both of your questions (and much more) by adjusting the scale:</p> <pre><code>ggplot(mtcars, aes(factor(cyl), mpg, fill = factor(vs))) + geom_boxplot() + scale_fill_manual(name = "This is my title", values = c("pink", "green") , labels = c("0" = "Foo", "1" = "Bar")) </code></pre> <p>The ggplot2 website help page for <a href="http://docs.ggplot2.org/current/scale_manual.html" rel="noreferrer">scale_manual</a> is full of good examples.</p>
8,113,621
which constructor to be called for view?
<p>I have my custom view extended from <code>View</code>. There are 3 view constructors:</p> <ol> <li><code>View(Context context, AttributeSet attrs, int defStyle)</code></li> <li><code>View(Context context, AttributeSet attrs)</code></li> <li><code>View(Context context)</code></li> </ol> <p>From my activity I call <code>std.setContentView(R.layout.main)</code>. The second constructor is getting called in my view. Why the second one? How to know in advance which one will be called and why?</p>
8,113,768
1
0
null
2011-11-13 18:18:22.253 UTC
9
2015-12-28 18:41:24.183 UTC
2012-12-13 09:25:32.29 UTC
null
440,921
null
977,952
null
1
23
android|android-layout
7,357
<p>From the Android developer site under documentation for View:</p> <p><a href="http://developer.android.com/reference/android/view/View.html#View%28android.content.Context%29" rel="noreferrer"><code>public View (Context context)</code></a></p> <blockquote> <p>Simple constructor to use when creating a view from code.</p> </blockquote> <p>So this constructor is what you can use to create a View in Java. It will not be called when you inflate from XML.</p> <p><a href="http://developer.android.com/reference/android/view/View.html#View%28android.content.Context,%20android.util.AttributeSet%29" rel="noreferrer"><code>public View (Context context, AttributeSet attrs)</code></a></p> <blockquote> <p>Constructor that is called when inflating a view from XML. This is called when a view is being constructed from an XML file, supplying attributes that were specified in the XML file. This version uses a default style of 0, so the only attribute values applied are those in the Context's Theme and the given AttributeSet.</p> <p>The method onFinishInflate() will be called after all children have been added.</p> </blockquote> <p>So this constructor will be called when you inflate a View from XML when you don't specify a style.</p> <p><a href="http://developer.android.com/reference/android/view/View.html#View%28android.content.Context,%20android.util.AttributeSet,%20int%29" rel="noreferrer"><code>public View (Context context, AttributeSet attrs, int defStyle)</code></a></p> <blockquote> <p>Perform inflation from XML and apply a class-specific base style. This constructor of View allows subclasses to use their own base style when they are inflating. For example, a Button class's constructor would call this version of the super class constructor and supply R.attr.buttonStyle for defStyle; this allows the theme's button style to modify all of the base view attributes (in particular its background) as well as the Button class's attributes.</p> </blockquote> <p>You should implement all of these constructors, but you can put all of the work in the third one by calling <code>this(context, null)</code> and <code>this(context, attrs, 0)</code> for the first two, respectively.</p>
21,519,113
AngularJS: open a new browser window, yet still retain scope and controller, and services
<p>I'm writing an angularJS app. In this particular controller, I open a new browser window through the <code>$window.open</code> service. But in the new window, all the <code>$scope</code> variables are lost.</p> <p>I tried to use <code>window.parent</code> but this doesn't work. In fact in the new browser window all the app services, controllers, or scopes are not in effect at all, is this true? Is there a way to open a new browser window yet still makes the new window belongs to the same angular app in the old window? I need to have access to some angularJS services and the scope of the controller that open that new window. Is this possible at all?</p>
21,519,297
3
3
null
2014-02-03 03:08:36.02 UTC
19
2016-07-08 07:50:07.773 UTC
2014-02-03 03:26:43.483 UTC
null
354,577
null
267,476
null
1
29
javascript|angularjs|angularjs-scope|angularjs-service|angularjs-controller
65,544
<p>There is no [straightforward] way to make the new window belong to the same angular.js application, since the angular application is generally tied to the document, window, and events of the window where it was initialized either via an ng-app directive or by calling angular.bootstrap.</p> <p>However, you can create a new angular module and application for your popup window. You could use the same basic services and controllers from your original application by including the appropriate javascript files.</p> <p>Presuming your popup window needs data from the original application, you can pass that by using the window object returned from the window.open() method. For example, within your first angular application, open your popup window like so:</p> <pre><code>angular.module('originalModule').service('popupService', function(someOtherDataService) { var popupWindow = window.open('popupWindow.html'); popupWindow.mySharedData = someOtherDataService.importantData; }); </code></pre> <p>Once your secondary "popup" angular application is initialized, it can then reference the shared data by reading window.mySharedData.</p> <p>You can also create functions in each window that can be called from the other window. The popup window can call back into the original window by using the window.opener property. (window.parent refers to the parent window of frames, you want window.opener)</p> <p>[Agreed, I'm sure that if you studied the angular source code you could find some clever way to use the same angular app for both windows. Such an attempt is beyond my ambition this evening.]</p>
21,826,044
Kth minimum in a Range
<p>Given an array of integers and some query operations.<br> The query operations are of 2 types<br> 1.Update the value of the ith index to x.<br> 2.Given 2 integers find the kth minimum in that range.(Ex if the 2 integers are i and j ,we have to find out the kth minimum between i and j both inclusive).<br> I can find the Range minimum query using segment tree but could no do so for the kth minimum. Can anyone help me?</p>
22,075,025
4
3
null
2014-02-17 10:07:34.993 UTC
12
2017-05-16 19:20:07.037 UTC
2014-02-17 15:28:12.51 UTC
null
567,070
null
3,318,603
null
1
17
algorithm|data-structures|tree
5,455
<p>Here is a <code>O(polylog n)</code> per query solution that does actually not assume a constant <code>k</code>, so the <code>k</code> can vary between queries. The main idea is to use a segment tree, where every node represents an interval of array indices and contains a multiset (balanced binary search tree) of the values in the represened array segment. The update operation is pretty straightforward:</p> <ol> <li>Walk up the segment tree from the leaf (the array index you're updating). You will encounter all nodes that represent an interval of array indices that contain the updated index. At every node, remove the old value from the multiset and insert the new value into the multiset. Complexity: <code>O(log^2 n)</code></li> <li>Update the array itself.</li> </ol> <p>We notice that every array element will be in <code>O(log n)</code> multisets, so the total space usage is <code>O(n log n)</code>. With linear-time merging of multisets we can build the initial segment tree in <code>O(n log n)</code> as well (there's <code>O(n)</code> work per level).</p> <p>What about queries? We are given a range <code>[i, j]</code> and a rank <code>k</code> and want to find the k-th smallest element in <code>a[i..j]</code>. How do we do that?</p> <ol> <li>Find a disjoint coverage of the query range using the standard segment tree query procedure. We get <code>O(log n)</code> disjoint nodes, the union of whose multisets is exactly the multiset of values in the query range. Let's call those multisets <code>s_1, ..., s_m</code> (with <code>m &lt;= ceil(log_2 n)</code>). Finding the <code>s_i</code> takes <code>O(log n)</code> time.</li> <li>Do a <a href="http://en.wikipedia.org/wiki/Selection_algorithm" rel="nofollow"><code>select(k)</code></a> query on the union of <code>s_1, ..., s_m</code>. See below.</li> </ol> <p>So how does the selection algorithm work? There is one really simple algorithm to do this.</p> <p>We have <code>s_1, ..., s_n</code> and <code>k</code> given and want to find the smallest <code>x</code> in <code>a</code>, such that <code>s_1.rank(x) + ... + s_m.rank(x) &gt;= k - 1</code>, where <code>rank</code> returns the number of elements smaller than <code>x</code> in the respective BBST (this can be implemented in <code>O(log n)</code> if we store subtree sizes). Let's just use binary search to find <code>x</code>! We walk through the BBST of the root, do a couple of rank queries and check whether their sum is larger than or equal to <code>k</code>. It's a predicate monotone in <code>x</code>, so binary search works. The answer is then the minimum of the successors of <code>x</code> in any of the <code>s_i</code>.</p> <p><strong>Complexity</strong>: <code>O(n log n)</code> preprocessing and <code>O(log^3 n)</code> per query.</p> <p>So in total we get a runtime of <code>O(n log n + q log^3 n)</code> for <code>q</code> queries. I'm sure we could get it down to <code>O(q log^2 n)</code> with a cleverer selection algorithm.</p> <p><strong>UPDATE:</strong> If we are looking for an offline algorithm that can process all queries at once, we can get <code>O((n + q) * log n * log (q + n))</code> using the following algorithm: </p> <ul> <li>Preprocess all queries, create a set of all values that ever occured in the array. The number of those will be at most <code>q + n</code>.</li> <li>Build a segment tree, but this time not on the array, but on the set of possible values.</li> <li>Every node in the segment tree represents an interval of values and maintains a set of positions where these values occurs.</li> <li>To answer a query, start at the root of the segment tree. Check how many positions in the left child of the root lie in the query interval (we can do that by doing two searches in the BBST of positions). Let that number be <code>m</code>. If <code>k &lt;= m</code>, recurse into the left child. Otherwise recurse into the right child, with <code>k</code> decremented by <code>m</code>.</li> <li>For updates, remove the position from the <code>O(log (q + n))</code> nodes that cover the old value and insert it into the nodes that cover the new value.</li> </ul> <p>The advantage of this approach is that we don't need subtree sizes, so we can implement this with most standard library implementations of balanced binary search trees (e.g. <code>set&lt;int&gt;</code> in C++).</p> <p>We can turn this into an online algorithm by changing the segment tree out for a <a href="http://www.eli.sdsu.edu/courses/fall95/cs660/notes/BB/BBtrees.html" rel="nofollow">weight-balanced tree such as a BB[α] tree</a>. It has logarithmic operations like other balanced binary search trees, but allows us to rebuild an entire subtree from scratch when it becomes unbalanced by charging the rebuilding cost to the operations that must have caused the imbalance.</p>
1,944,577
win32 window in WPF
<p>Recently our application encountered a strange problem.</p> <p>The application has a win32 window in the WPF window, when resize the WPF window, the problem occurred.</p> <p><strong>StackTrace:</strong></p> <pre><code>Exception object: 0000000002ab2c78 Exception type: System.OutOfMemoryException InnerException: &lt;none&gt; StackTrace (generated): SP IP Function 0048D94C 689FB82F PresentationCore_ni!System.Windows.Media.Composition.DUCE+Channel.SyncFlush()+0x80323f 0048D98C 681FEE37 PresentationCore_ni!System.Windows.Media.Composition.DUCE+CompositionTarget.UpdateWindowSettings(ResourceHandle, RECT, System.Windows.Media.Color, Single, System.Windows.Media.Composition.MILWindowLayerType, System.Windows.Media.Composition.MILTransparencyFlags, Boolean, Boolean, Boolean, Int32, Channel)+0x127 0048DA38 681FEAD1 PresentationCore_ni!System.Windows.Interop.HwndTarget.UpdateWindowSettings(Boolean, System.Nullable`1&lt;ChannelSet&gt;)+0x301 0048DBC8 6820718F PresentationCore_ni!System.Windows.Interop.HwndTarget.UpdateWindowSettings(Boolean)+0x2f 0048DBDC 68207085 PresentationCore_ni!System.Windows.Interop.HwndTarget.UpdateWindowPos(IntPtr)+0x185 0048DC34 681FFE9F PresentationCore_ni!System.Windows.Interop.HwndTarget.HandleMessage(Int32, IntPtr, IntPtr)+0xff 0048DC64 681FD0BA PresentationCore_ni!System.Windows.Interop.HwndSource.HwndTargetFilterMessage(IntPtr, Int32, IntPtr, IntPtr, Boolean ByRef)+0x3a 0048DC88 68C6668E WindowsBase_ni!MS.Win32.HwndWrapper.WndProc(IntPtr, Int32, IntPtr, IntPtr, Boolean ByRef)+0xbe 0048DCD4 68C665BA WindowsBase_ni!MS.Win32.HwndSubclass.DispatcherCallbackOperation(System.Object)+0x7a 0048DCE4 68C664AA WindowsBase_ni!System.Windows.Threading.ExceptionWrapper.InternalRealCall(System.Delegate, System.Object, Boolean)+0x8a 0048DD08 68C6639A WindowsBase_ni!System.Windows.Threading.ExceptionWrapper.TryCatchWhen(System.Object, System.Delegate, System.Object, Boolean, System.Delegate)+0x4a 0048DD50 68C64504 WindowsBase_ni!System.Windows.Threading.Dispatcher.WrappedInvoke(System.Delegate, System.Object, Boolean, System.Delegate)+0x44 0048DD70 68C63661 WindowsBase_ni!System.Windows.Threading.Dispatcher.InvokeImpl(System.Windows.Threading.DispatcherPriority, System.TimeSpan, System.Delegate, System.Object, Boolean)+0x91 0048DDB4 68C635B0 WindowsBase_ni!System.Windows.Threading.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority, System.Delegate, System.Object)+0x40 0048DDD8 68C65CFC WindowsBase_ni!MS.Win32.HwndSubclass.SubclassWndProc(IntPtr, Int32, IntPtr, IntPtr)+0xdc StackTraceString: &lt;none&gt; HResult: 8007000e </code></pre> <p>Also, I found some related links: </p> <p><a href="http://www.actiprosoftware.com/support/Forums/ViewForumTopic.aspx?ForumTopicID=3849" rel="noreferrer">relatedA</a></p> <p><a href="http://social.msdn.microsoft.com/Forums/en-IE/wpf/thread/0dc4100a-be99-4682-b757-18249f728f2b" rel="noreferrer">relatedB</a></p> <ol> <li><p>Is there any way to avoid or handle this problem?</p></li> <li><p>How to find out the real problem?</p></li> <li><p>From the call stack, Can we determine that the problem was came from .NET Framework?</p></li> </ol> <p>Thank you for your answer or comments!</p>
1,965,382
4
2
null
2009-12-22 06:50:41.05 UTC
9
2020-03-02 09:29:14.533 UTC
2010-01-17 11:33:20.433 UTC
null
201,794
null
201,794
null
1
16
.net|wpf|windbg|out-of-memory
9,538
<p>Your problem is not caused by a managed memory leak. Clearly you are tickling a bug somewhere in unmanaged code.</p> <p>The SyncFlush() method is called after several MILCore calls, and it appears to cause the changes that have been sent to be processed immediately instead of being left in queue for later processing. Since the call processes everything previously sent, nothing in your visual tree can be ruled out from the call stack you sent.</p> <p>A call stack that includes unmanaged calls may turn up more useful information. Run the application under VS.NET with native debugging, or with windbg or another native code debugger. Set the debugger to break on the exception, and get the call stack at the relative breakpoint.</p> <p>The call stack will of course descend into MILCore, and from there it may go into the DirectX layer and the DirectX driver. A clue as to which part of your code caused the problem may be found somewhere in this native call stack.</p> <p>Chances are that MILCore is passing a huge value of some parameter into DirectX based on what you are telling it. Check your application for anything that could cause a bug that would make DirectX to allocate a lot of memory. Examples of things to look for would be:</p> <ul> <li>BitmapSources that are set to load at very high resolution.</li> <li>Large WritableBitmaps</li> <li>Extremely large (or negative) transform or size values</li> </ul> <p>Another way to attack this problem is to progressively simplify your application until the problem disappears, then look very closedly at what you removed last. When convenient, it can be good to do this as a binary search: Initially cut out half of the visual complexity. If it works, put back half of what was removed, otherwise remove another half. Repeat until done.</p> <p>Also note that it is usually unnecssary to actually remove UI components to keep MILCore from seeing then. Any Visual with Visibility.Hidden may be skipped over entirely.</p> <p>There is no generalized way to avoid this problem, but the search technique will help you pinpoint what specifically needs to be changed to fix it in the particular case.</p> <p>It is safe to say from the call stack, that you have found a bug in either NET Framework or the DirectX drivers for a particular video card.</p> <p><strong>Regarding the second stack trace you posted</strong></p> <p>John Knoeller is correct that the transition from RtlFreeHeap to ConvertToUnicode is nonsense, but draws the wrong conclusion from it. What we are seeing is that your debugger got lost when tracing back the stack. It started correctly from the exception but got lost below the <code>Assembly.ExecuteMainMethod</code> frame because that part of the stack had been overwritten as the exception was handled and the debugger was invoked.</p> <p>Unfortunately any analysis of this stack trace is useless for your purposes because it was captured too late. What we are seeing is an exception occuring during processing of a WM_LBUTTONDOWN which is converted to a WM_SYSCOMMAND, which then catches an exception. In other words, you clicked on something that caused a system command (such as a resize), which caused an exception. At the point this stack trace was captured, the exception was already being handled. The reason you are seeing User32 and UxTheme calls is because these are involved in processing the button click. They have nothing to do with the real problem.</p> <p>You are on the right track, but you will need to capture a stack trace at the moment the allocation fails (or you can use one of the other approaches I suggested above).</p> <p>You will know you have the correct stack trace when the all the managed frames in your first stack trace appear in it and the top of the stack is a failing memory allocation. Note that we are really interested only in the unmanaged frames that appear above the <code>DUCE+Channel.SyncFlush</code> call -- everything below that will be NET Framework and your application code.</p> <p><strong>How to get a native stack trace at the right time</strong></p> <p>You want to get a stack trace at the time the first memory allocation failure within the <code>DUCE+Channel.SyncFlush</code> call shown. This may be tricky. There are three approaches I use: (note that in each case you start with a breakpoint inside the SyncFlush call - see note below for more details)</p> <ol> <li><p>Set the debugger to break on all exceptions (managed and unmanaged), then keep hitting go (F5, or "g") until it breaks on the memory allocation exception you are interested in. This is the first thing to try because it is quick, but it often fails when working with native code because the native code often returns an error code to the calling native code instead of throwing an exception.</p></li> <li><p>Set the debugger to break on all exceptions and also set breakpoints on common memory allocation routines, then hit F5 (go) repeatedly until the exception occurs, counting how many F5s you hit. Next time you run, use one fewer F5 and you may be on the allocation call that generated the exception. Capture the call stack to Notepad, then F10 (step over) repeatedly from there to see if it really was the allocation that failed.</p></li> <li><p>Set a breakpoint on the first native frame called by SyncFlush (this is wpfgfx_v0300!MilComposition_SyncFlush) to skip over the managed to native transition, then F5 to run to it. F10 (step over) through the function it until EAX contains one of the error codes E_OUTOFMEMORY (0x8007000E), ERROR_OUTOFMEMORY (0x0000000E), or ERROR_NOT_ENOUGH_MEMORY (0x0000008). Note the most recent "Call" instruction. The next time you run the program, run to there and step into it. Repeat this until you are down to the memory allocation call that caused the problem and dump the stack trace. Note that in many cases you will find yourself looping through a largish data structure, so some intelligence is required to set an appropriate breakpoint to skip over the loop so you can get where you need to be quickly. This technique is very reliable but very labor-intensive.</p></li> </ol> <p>Note: In each case you don't want to set breakpoints or start single-stepping until your application is inside the failing <code>DUCE+Channel.SyncFlush</code> call. To ensure this, start the application with all breakpoints disabled. When it is running, enable a breakpoint on <code>System.Windows.Media.Composition.DUCE+Channel.SyncFlush</code> and resize the window. The first time around just hit F5 to make sure the exception fails on the first SyncFlush call (if not, count how many times you have to hit F5 before the exception occurs). Then disable the breakpoint and restart the program. Repeat the procedure but this time after you hit the SyncFlush call the right time, set your breakpoints or do you single-stepping as described above.</p> <p><strong>Recommendations</strong></p> <p>The debugging techniques I describe above are labor-intensive: Plan to spend several hours at least. Because of this, I generally try repeatedly simplifying my application to find out exactly what tickles the bug before jumping into the debugger for something like this. This has two advantages: It will give you a good repro to send the graphics card vendor, and it will make your debugging faster because there will be less displayed and therefore less code to single-step through, fewer allocations, etc.</p> <p>Because the problem happens only with a specific graphics card, there is no doubt that the problem is either a bug in the graphics card driver or in the MilCore code that calls it. Most likely it is in the graphics card driver, but it is possible that MilCore is passing invalid values that are handled correctly by most graphics cards but not this one. The debugging techniques I describe above will tell you this is the case: For example, if MilCore is telling the graphics card to allocate a 1000000x1000000 pixel area and the graphics card is giving correct resolution information, the bug is in the MilCore. But if MilCore's requests are reasonable then the bug is in the graphics card driver.</p>
2,243,177
Get query back from PDO prepared statement
<p>Is there a way to retrieve the query that was used to generate a PDO Prepared statement object?</p>
2,243,512
4
0
null
2010-02-11 08:40:46.54 UTC
6
2019-12-13 17:34:24.7 UTC
null
null
null
null
187,018
null
1
58
php|mysql|pdo
57,291
<p>Try <a href="http://www.php.net/manual/en/class.pdostatement.php#pdostatement.props.querystring" rel="noreferrer">$statement->queryString</a>.</p>
10,384,080
MediaStore - Uri to query all types of files (media and non-media)
<p>In the class <a href="http://developer.android.com/reference/android/provider/MediaStore.Files.html" rel="noreferrer">MediaStore.Files</a> class, its mentioned that,</p> <blockquote> <p>Media provider table containing an index of all files in the media storage, including non-media files.</p> </blockquote> <p>I'm interested in querying for non-media files like PDF.</p> <p>I'm using CursorLoader to query the database. The second parameter for the constructor requires an Uri argument which is easy to get for the media types Audio, Images and Video as each of them have a <code>EXTERNAL_CONTENT_URI</code> and <code>INTERNAL_CONTENT_URI</code> constant defined for them.</p> <p>For MediaStore.Files there is no such defined constant. I tried using the <code>getContentUri()</code> method but couldn't figure out the argument value for <code>volumeName</code>. I tried giving "/mnt/sdcard" and also the volume name that appears when I connect the device to my system but in vain.</p> <p>I saw a <a href="https://groups.google.com/forum/?fromgroups#!topic/android-developers/6hUaqt_1ubY" rel="noreferrer">similar question on Google Groups</a> but that is not resolved.</p> <p>EDIT: I also tried using Uri.fromFile(new File("/mnt/sdcard/")) and Uri.parse(new File("/mnt/sdcard").toString()) but that didn't work out either.</p>
10,384,476
1
2
null
2012-04-30 12:55:21.603 UTC
22
2021-05-24 13:01:43.483 UTC
2012-04-30 13:12:46.917 UTC
null
712,413
null
712,413
null
1
34
android|mediastore
69,936
<p>It is <code>"external"</code> or <code>"internal"</code> although internal (system files) is probably not useful here.</p> <pre><code>ContentResolver cr = context.getContentResolver(); Uri uri = MediaStore.Files.getContentUri("external"); // every column, although that is huge waste, you probably need // BaseColumns.DATA (the path) only. String[] projection = null; // exclude media files, they would be here also. String selection = MediaStore.Files.FileColumns.MEDIA_TYPE + "=" + MediaStore.Files.FileColumns.MEDIA_TYPE_NONE; String[] selectionArgs = null; // there is no ? in selection so null here String sortOrder = null; // unordered Cursor allNonMediaFiles = cr.query(uri, projection, selection, selectionArgs, sortOrder); </code></pre> <p>If you want <code>.pdf</code> only you could check the mimetype</p> <pre><code>// only pdf String selectionMimeType = MediaStore.Files.FileColumns.MIME_TYPE + "=?"; String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension("pdf"); String[] selectionArgsPdf = new String[]{ mimeType }; Cursor allPdfFiles = cr.query(uri, projection, selectionMimeType, selectionArgsPdf, sortOrder); </code></pre>
7,250,413
Change tab name in uitabbarcontroller
<p>I have a TabBarController set as main controller tab, where names were defined using interface builder. Now I would like to change its names programmatically. </p> <p>How could it be done?</p>
7,250,538
7
0
null
2011-08-30 22:11:47.72 UTC
7
2018-03-26 04:25:41.973 UTC
2016-03-29 08:59:39.273 UTC
null
805,252
null
871,806
null
1
37
ios|objective-c|iphone|cocoa-touch|uitabbarcontroller
40,233
<h2>Updated to XCode 8</h2> <p>Since my original answer, a lot has happened: Swift 3, Storyboards, etc. Title is usually the one that all views share, and can be set in the attributes inspector</p> <p><a href="https://i.stack.imgur.com/8FAfY.png" rel="noreferrer"><img src="https://i.stack.imgur.com/8FAfY.png" alt="Title Setup"></a></p> <p>Also, for more control, you can always drag the <code>UITabBarItem</code>, and <code>UINavigationItem</code> elements from the designer view. You must drag them to the view that's gonna be displayed in the tab bar/navigation controller. Basically they store the info as "I wanna be displayed in tab bar like this".</p> <p><a href="https://i.stack.imgur.com/Xlxmm.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Xlxmm.png" alt="enter image description here"></a></p> <blockquote> <p>Hello Scene is getting a TabBarItem added to it, so it can be configured.</p> </blockquote> <p>These two elements behave exactly as accessing the view controller's <code>.tabBarItem</code> and <code>.navigationItem</code> properties via code. These properties always exist in code if they are child of the corresponding object (nav has navItem, and tab has tabItem), you don't need to add them in storyboard/xib to have them.</p> <p>This last thing is kinda confusing, since in the storyboard/xib it appears you're adding them to the view controller, but in truth you're just saying "the nib will configure these properties too".</p> <h2>Original Answer</h2> <p>The name that appears on the tab bar comes from the <code>UIViewController</code>'s <code>title</code> property,</p> <pre><code>self.title = @"Name me!"; </code></pre> <p>You can change the title at any point, and it should update the text appearing on the tab bar item. But be wary, <strong>do this as soon as possible</strong>, ideally, in the <code>init</code> method in use (or <code>initWithNibName:bundle:</code>, or <code>initWithCoder:</code>).</p> <p>The key here, is that the init methods are called as soon as the tab bar appears on screen, as it initialises all of its view controller. If you were to do it on <code>viewDidLoad</code>, that would only get called if you actually select the tab, then other family of calls, same goes for <code>awakeFromNib</code>, <code>viewWillAppear:</code>, <code>viewDidAppear:</code>, etc.</p> <p>The idea of having a title on the <code>UIViewController</code>, is to keep things consistent. If you show that viewController on a <code>UINavigationController</code>, the navigation bar on top should use the title property, as it does when using back. The <code>UITabBarController</code> also respects the same title property and changes accordingly.</p> <p>In terms of reusability, you should be setting the title only from the inside of the <code>UIViewController</code> subclass.</p> <h3>The way of the Nib</h3> <p>Using nibs or storyboards? If you have a <code>UIViewController</code>, you can give it the name straight up in the attributes inspector (or <kbd>⌥</kbd><kbd>⌘</kbd><kbd>4</kbd>)</p> <p><img src="https://i.stack.imgur.com/HkH18.png" alt="Using interface builder, in the Attributes Inspector"></p> <p>Unfortunately, if the File Owner is the <code>UIViewController</code> subclass, then you won't be able to access it this way, simply because, XCode registers the File Owner as an "External Object", and doesn't show a configuration panel for it. :(</p> <h3>Multiple titles, same view controller</h3> <p>But sometimes, you just want to have them named differently</p> <pre><code>// Modify the display title on the tab bar self.tabBarItem.title = @"World"; // Modify the display title on the navigation bar self.navigationItem.title = @"Hello World"; </code></pre> <h3>Screwing with the neighbours</h3> <p>Each UIViewController should handle his own name, what if you want to force it from the outside (and thus, completely violating the original thing I said about reusability)?</p> <pre><code>// Rename the other guy's .title property [[self.tabBarController.viewControllers objectAtIndex:&lt;#Index#&gt;] setTitle:@"Hello World"]; // Or do as before, and rename the other guy's tab bar [(UITabBarItem*)[self.tabBarController.tabBar.items objectAtIndex:&lt;#index#&gt;] setTitle:@"Hello World"]; </code></pre> <p>You could also probably do it with the navigation item, but that would require more gymnastics than I'm comfortable with.</p>
7,648,756
Is the order of iterating through std::map known (and guaranteed by the standard)?
<p>What I mean is - we know that the <code>std::map</code>'s elements are sorted according to the keys. So, let's say the keys are integers. If I iterate from <code>std::map::begin()</code> to <code>std::map::end()</code> using a <code>for</code>, does the standard guarantee that I'll iterate consequently through the elements with keys, sorted in ascending order?</p> <hr> <p>Example:</p> <pre><code>std::map&lt;int, int&gt; map_; map_[1] = 2; map_[2] = 3; map_[3] = 4; for( std::map&lt;int, int&gt;::iterator iter = map_.begin(); iter != map_.end(); ++iter ) { std::cout &lt;&lt; iter-&gt;second; } </code></pre> <p>Is this guaranteed to print <code>234</code> or is it implementation defined?</p> <hr> <p>Real life reason: I have a <code>std::map</code> with <code>int</code> keys. In very rare situations, I'd like to iterate through all elements, with key, greater than a concrete <code>int</code> value. Yep, it sounds like <code>std::vector</code> would be the better choice, but notice my "very rare situations".</p> <hr> <p><strong>EDIT</strong>: I know, that the elements of <code>std::map</code> are sorted.. no need to point it out (for most of the answers here). I even wrote it in my question.<br> I was asking about the iterators and the order when I'm iterating through a container. Thanks @Kerrek SB for the answer.</p>
7,648,812
7
5
null
2011-10-04 13:35:23.027 UTC
28
2021-12-31 04:48:03.763 UTC
2019-01-24 16:51:54.633 UTC
null
10,607,772
null
435,800
null
1
190
c++|dictionary|stl|standards
102,893
<p>Yes, that's guaranteed. Moreover, <code>*begin()</code> gives you the smallest and <code>*rbegin()</code> the largest element, as determined by the comparison operator, and two key values <code>a</code> and <code>b</code> for which the expression <code>!compare(a,b) &amp;&amp; !compare(b,a)</code> is true are considered equal. The default comparison function is <code>std::less&lt;K&gt;</code>.</p> <p>The ordering is not a lucky bonus feature, but rather, it is a fundamental aspect of the data structure, as the ordering is used to determine when two keys are the same (by the above rule) and to perform efficient lookup (essentially a binary search, which has logarithmic complexity in the number of elements).</p>
7,623,275
AFNetworking Post Request
<p>I'm a newbie in obj-c and have been using asihttp for some of my projects. When doing a post request in asihttp its done this way. </p> <pre><code> ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url]; [request setPostValue:height forKey:@"user[height]"]; [request setPostValue:weight forKey:@"user[weight]"]; [request setDelegate:self]; [request startAsynchronous]; </code></pre> <p>How would go about doing this is AFNetworking with a code example ?<br> I already got the get Json getrequest working in AFNetworking but this post request is giving me some problems. Thanks for help in advance. </p>
7,625,412
15
0
null
2011-10-01 22:08:59.827 UTC
57
2020-07-01 23:08:37.793 UTC
2013-11-25 13:57:37.74 UTC
null
292,166
null
974,912
null
1
82
ios|objective-c|afnetworking|afnetworking-2
117,800
<p>It's first worth adding (as this answer is still popular 6 years after I initially wrote it...) that the first thing you should consider is whether you should even use AFNetworking. NSURLSession was added in iOS 7 and means you don't need to use AFNetworking in many cases - and one less third party library is always a good thing.</p> <p>For AFNetworking 3.0:</p> <pre><code>AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; NSDictionary *params = @{@"user[height]": height, @"user[weight]": weight}; [manager POST:@"https://example.com/myobject" parameters:params progress:nil success:^(NSURLSessionTask *task, id responseObject) { NSLog(@"JSON: %@", responseObject); } failure:^(NSURLSessionTask *operation, NSError *error) { NSLog(@"Error: %@", error); }]; </code></pre> <p>For AFNetworking 2.0 (and also using the new NSDictionary syntax):</p> <pre><code>AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; NSDictionary *params = @{@"user[height]": height, @"user[weight]": weight}; [manager POST:@"https://example.com/myobject" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) { NSLog(@"JSON: %@", responseObject); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"Error: %@", error); }]; </code></pre> <p>If you are stuck using AFNetworking 1.0, you need to do it this way:</p> <pre><code>NSURL *url = [NSURL URLWithString:@"https://example.com/"]; AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url]; NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys: height, @"user[height]", weight, @"user[weight]", nil]; [httpClient postPath:@"/myobject" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) { NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]; NSLog(@"Request Successful, response '%@'", responseStr); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"[HTTPClient Error]: %@", error.localizedDescription); }]; </code></pre>
14,051,604
SSRS custom number format
<p>I am go to generate an excel file from SSRS, and</p> <p>I want to format the number like this...</p> <ul> <li><p>15 is displayed as 15</p></li> <li><p>14.3453453 is displayed as 14.35</p></li> <li><p>12.1 is displayed as 12.1</p></li> <li><p>0 is displayed as 0</p></li> <li><p>1 is displayed as 1</p></li> </ul> <p>I can apply this in Excel but unable to apply in SSRS</p> <blockquote> <p>[=0]0;[=1]1;0.##</p> </blockquote> <p><img src="https://i.stack.imgur.com/NtQ6d.png" alt="ssrs error message"></p> <p>Does anyone can suggest another way for me? Thanks!</p>
14,051,725
3
1
null
2012-12-27 08:27:02.153 UTC
4
2016-10-11 16:14:19.487 UTC
2012-12-27 08:49:55.99 UTC
null
1,648,393
null
1,648,393
null
1
23
reporting-services|number-formatting|custom-formatting
157,102
<p>am assuming that you want to know how to format numbers in SSRS</p> <p>Just <code>right click</code> the <code>TextBox</code> on which you want to apply formatting, go to its <code>expression</code>.</p> <p>suppose its expression is something like below</p> <pre><code>=Fields!myField.Value </code></pre> <p>then do this</p> <pre><code>=Format(Fields!myField.Value,"##.##") </code></pre> <p>or </p> <pre><code>=Format(Fields!myFields.Value,"00.00") </code></pre> <p>difference between the two is that former one would make 4 as 4 and later one would make 4 as 04.00</p> <p>this should give you an idea.</p> <p>also: you might have to convert your field into a numerical one. i.e.</p> <pre><code> =Format(CDbl(Fields!myFields.Value),"00.00") </code></pre> <p>so: 0 in format expression means, when no number is present, place a 0 there and # means when no number is present, leave it. Both of them works same when numbers are present ie. 45.6567 would be 45.65 for both of them:</p> <p><strong>UPDATE :</strong></p> <p>if you want to apply variable formatting on the same column based on row values i.e. you want <code>myField</code> to have no formatting when it has no decimal value but formatting with double precision when it has decimal then you can do it through logic. (though you should not be doing so)</p> <p>Go to the appropriate textbox and go to its expression and do this:</p> <pre><code>=IIF((Fields!myField.Value - CInt(Fields!myField.Value)) &gt; 0, Format(Fields!myField.Value, "##.##"),Fields!myField.Value) </code></pre> <p>so basically you are using <code>IIF(condition, true,false)</code> operator of SSRS, ur condition is to check whether the number has decimal value, if it has, you apply the formatting and if no, you let it as it is.</p> <p>this should give you an idea, how to handle variable formatting.</p>
29,040,064
Save canvas then restore, why is that?
<p>I often see the following code</p> <pre><code>canvas.save(). canvas translate or rotate some drawing canvas.restore </code></pre> <p>I don't understand why we save and then restore. What's the point of undoing what we just did! I am sure I am missing something here Thanks</p>
55,261,797
5
4
null
2015-03-13 19:04:51.543 UTC
15
2020-08-13 10:05:25.03 UTC
null
null
null
null
1,217,820
null
1
50
android|android-canvas
18,792
<p>I understand this question is a bit dated, but for anyone still looking for an answer I can ELI5;</p> <p>Imagine the canvas is a piece of paper, and you're tasked with drawing a picture of a robot right side up, at the bottom, and another robot upside down, slightly moved to the right, and about 40% smaller at the top. Something like this; <a href="https://i.stack.imgur.com/5Bg2b.png" rel="noreferrer"><img src="https://i.stack.imgur.com/5Bg2b.png" alt="Android canvas example"></a></p> <p>How would you start? What's easier to do first? </p> <p>You would probably draw the bigger robot at the bottom first since it's right-side up and it's a lot easier to draw in the direction that feels more natural. So you've got the first one done, now how do you approach the second upside down robot? </p> <ul> <li>You could attempt to draw it as is, but that would be a bit difficult since you're upside down. </li> </ul> <p><strong>or</strong></p> <ul> <li>You could rotate your paper 180°, move your starting point a bit, and start drawing at a smaller scale, and after you're all done you'd just rotate the paper back. </li> </ul> <p>This is what <code>canvas.save()</code> and <code>canvas.restore()</code> do, they allow you to modify your canvas in any way that makes it <em>easier</em> for you to draw what you need. You don't need to use these methods, but they sure do simplify a lot of the process. The above would look something like</p> <pre><code>drawRobot() canvas.save() canvas.rotate(180) canvas.translate(100, 0) canvas.scale(40,40) drawRobot() canvas.restore() </code></pre> <p>If we look at the <code>restore()</code> documentation it says </p> <blockquote> <p>is used to remove all <strong>modifications</strong> to the matrix/clip state since the last save call</p> </blockquote> <p>and to see what those modifications are we take a look at <code>save()</code> it says</p> <blockquote> <p>translate, scale, rotate, skew, concat or clipRect, clipPath</p> </blockquote> <p>Well look at that, we did in fact use <code>translate</code> <code>rotate</code> and <code>scale</code> but we also did call <code>drawRobot()</code> so wouldn't calling <code>restore</code> erase our drawing? No, because it doesn't affect the drawing, <strong>only</strong> the modifications. So when we call <code>restore</code> it will return our canvas to the state that it was in before we started the second drawing. </p>
43,676,415
How to include constraint layout to another constraint layout and set constraint between each
<p>I'm using constraintLyout v 1.0.1.</p> <p>I would like to include in my xml a sub ConstraintLayout corresponding to a part of my global layout (which itself is a ConstraintLayout). I split the layout in two xmls in order to use this sub part elsewhere</p> <p>I tried this but I have no control on where to place my sub constraint layout in the parent. I wonder if I have to place everything in the same xml file or if their is a solution to use separate files.</p> <p><em>tmp_1.xml</em></p> <pre><code>&lt;android.support.constraint.ConstraintLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot; android:orientation=&quot;vertical&quot; android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;match_parent&quot; &gt; &lt;TextView android:id=&quot;@+id/label&quot; android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; android:text=&quot;LABEL1&quot; app:layout_constraintStart_toStartOf=&quot;parent&quot; app:layout_constraintEnd_toEndOf=&quot;parent&quot; app:layout_constraintTop_toTopOf=&quot;parent&quot; android:layout_marginTop=&quot;16dp&quot; /&gt; &lt;TextView android:id=&quot;@+id/label_2&quot; android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; android:text=&quot;LABEL2&quot; app:layout_constraintStart_toStartOf=&quot;@id/label&quot; app:layout_constraintEnd_toEndOf=&quot;@id/label&quot; app:layout_constraintTop_toBottomOf=&quot;@id/label&quot; android:layout_marginTop=&quot;16dp&quot; /&gt; &lt;include layout=&quot;@layout/tmp_2&quot; /&gt; &lt;/android.support.constraint.ConstraintLayout&gt; </code></pre> <p><em>tmp_2.xml</em></p> <pre><code>&lt;android.support.constraint.ConstraintLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot; android:orientation=&quot;vertical&quot; android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;wrap_content&quot; &gt; &lt;TextView android:id=&quot;@+id/view_80&quot; android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; android:text=&quot;80th element&quot; app:layout_constraintStart_toStartOf=&quot;parent&quot; app:layout_constraintTop_toTopOf=&quot;parent&quot; android:layout_marginTop=&quot;10dp&quot; android:layout_marginStart=&quot;12dp&quot; /&gt; &lt;/android.support.constraint.ConstraintLayout&gt; </code></pre> <p>The result is this</p> <p><a href="https://i.stack.imgur.com/wfmjH.png" rel="noreferrer"><img src="https://i.stack.imgur.com/wfmjH.png" alt="Actual result" /></a></p> <p>But i want it to be this</p> <p><a href="https://i.stack.imgur.com/LCS3H.png" rel="noreferrer"><img src="https://i.stack.imgur.com/LCS3H.png" alt="Expected result" /></a></p> <p>I tried this but it does not work</p> <pre><code>&lt;include app:layout_constraintTop_toBottomOf=&quot;@id/label_2&quot; layout=&quot;@layout/tmp_2&quot; /&gt; </code></pre>
43,676,869
5
1
null
2017-04-28 09:12:26.267 UTC
12
2021-04-13 09:43:57.423 UTC
2021-04-13 09:43:57.423 UTC
null
5,829,679
null
7,301,610
null
1
83
android|xml|android-layout|include|android-constraintlayout
43,166
<p>Actually found a solution. Android Studio does not autocomplete constraintLayout parameters in an include tag but they do have an impact on it as long as you give that include a size.</p> <pre><code>&lt;include layout="@layout/tmp_2" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginTop="10dp" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toBottomOf="@+id/label_2" /&gt; </code></pre>
29,907,405
Cannot import Beautiful Soup
<p>I am trying to use BeautifulSoup, and despite using the import statement: </p> <p><code>from bs4 import BeautifulSoup</code></p> <p>I am getting the error: <code>ImportError: cannot import name BeautifulSoup</code></p> <p><code>import bs4</code> does not give any errors.</p> <p>I have also tried <code>import bs4.BeautifulSoup</code> and just importing bs4 and creating a BeautifulSoup object with: <code>bs4.BeautifulSoup()</code></p> <p>Any guidance would be appreciated.</p>
29,924,863
15
6
null
2015-04-27 22:57:08.147 UTC
2
2022-05-07 14:40:17.3 UTC
null
null
null
user4367461
null
null
1
19
python|beautifulsoup
50,932
<p>The issue was I named the file <code>HTMLParser.py</code> , and that name is already used somewhere in the bs4 module.</p> <p>Thanks to everyone that helped! </p>
9,155,336
MIPS assembly for a simple for loop
<p>I need to translate this C code to MIPS assembly. Here is the C code:</p> <pre><code>int tmp = 0; for (int j = 0; j &lt; 15; ++j) tmp = tmp * 2 + 3 </code></pre> <p>This is my MIPS assembly code. Is it a correct translation? If you see any mistakes I would really like to know.</p> <pre><code># tmp = $v0 # j = $t0 .globl main main: li $v0,0 loop: bgt $t0,15,exit addi $t0,$t0,1 mul $t1,$v0,2 add $v0,$t1, 3 j loop exit: </code></pre>
9,155,379
5
1
null
2012-02-06 03:40:22.863 UTC
6
2022-03-10 15:48:53.333 UTC
2022-03-10 15:48:53.333 UTC
null
224,132
null
977,154
null
1
12
loops|assembly|mips|mips32
108,501
<p>Your loop goes from 0 to 14, so your bgt instruction should be: <code>bgt $t0,14,exit</code> I think.</p> <p>.</p>
276,324
css horizontal navigation spacing
<p>I'm trying to create a horizontal navigation bar in css with 5 evenly spaced links. The html hopefully will remain like this:</p> <pre><code>&lt;div id="footer"&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="one.html"&gt;One&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="two.html"&gt;Two&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="three.html"&gt;Three&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="four.html"&gt;Four&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="five.html"&gt;Five&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre> <p>So with CSS, I want to space them evenly within the footer div. So far I'm using this:</p> <pre><code>div#footer{ height:1.5em; background-color:green; clear:both; padding-top:.5em; font-size:1.5em; width:800px; } div#footer ul{ margin:0; padding:0; list-style:none; } div#footer li{ width:155px; display:inline-block; text-align:center; } </code></pre> <p>This works pretty well, but there is spacing between the li's that I do not want. That is why I've used the 155px instead of 160px for their width, there is about 5px of space being put in between each li. Where is that spacing coming from? How can I get rid of it? If I increase the fontsize, the spacing increases as well. </p>
276,340
5
0
null
2008-11-09 19:10:56.56 UTC
5
2015-06-03 10:13:38.91 UTC
null
null
null
MacRae
null
null
1
26
css|navigation
85,743
<p>I've had this happen to me. Unfortunately it is caused by the browser taking the line breaks between the list items and rendering them as spaces. To fix, change your HTML to:</p> <pre><code>&lt;div id="footer"&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="one.html"&gt;One&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href="two.html"&gt;Two&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href="three.html"&gt;Three&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href="four.html"&gt;Four&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href="five.html"&gt;Five&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre>
1,131,484
Wait for bash background jobs in script to be finished
<p>To maximize CPU usage (I run things on a Debian Lenny in EC2) I have a simple script to launch jobs in parallel:</p> <pre><code>#!/bin/bash for i in apache-200901*.log; do echo &quot;Processing $i ...&quot;; do_something_important; done &amp; for i in apache-200902*.log; do echo &quot;Processing $i ...&quot;; do_something_important; done &amp; for i in apache-200903*.log; do echo &quot;Processing $i ...&quot;; do_something_important; done &amp; for i in apache-200904*.log; do echo &quot;Processing $i ...&quot;; do_something_important; done &amp; ... </code></pre> <p>I'm quite satisfied with this working solution; however, I couldn't figure out how to write further code to be executed only once ALL of the loops have been completed.</p> <p>Is there a way to do this?</p>
1,131,511
5
0
null
2009-07-15 13:44:15.027 UTC
12
2022-09-06 10:23:37.817 UTC
2022-03-26 15:06:10.54 UTC
null
-1
null
47,573
null
1
78
bash|scripting|job-control
50,058
<p>There's a <code>bash</code> builtin command for that.</p> <pre><code>wait [n ...] Wait for each specified process and return its termination sta‐ tus. Each n may be a process ID or a job specification; if a job spec is given, all processes in that job’s pipeline are waited for. If n is not given, all currently active child pro‐ cesses are waited for, and the return status is zero. If n specifies a non-existent process or job, the return status is 127. Otherwise, the return status is the exit status of the last process or job waited for. </code></pre>
457,276
JUnit 4 Test Suites
<p>How do I create test suites with JUnit 4?</p> <p>All the documentation I've seen doesn't seem to be working for me. And if I use the Eclipse wizard it doesn't give me an option to select any of the test classes I have created.</p>
457,299
5
1
null
2009-01-19 11:14:13.44 UTC
13
2019-01-28 15:02:29.687 UTC
2019-01-28 15:02:29.687 UTC
null
277,023
Adam Taylor
52,116
null
1
104
java|junit|test-suite
76,542
<pre><code>import org.junit.runners.Suite; import org.junit.runner.RunWith; @RunWith(Suite.class) @Suite.SuiteClasses({TestClass1.class, TestClass2.class}) public class TestSuite { //nothing } </code></pre>
166,132
Maximum length of the textual representation of an IPv6 address?
<p>I want to store the data returned by <code>$_SERVER["REMOTE_ADDR"]</code> in PHP into a DB field, pretty simple task, really. The problem is that I can't find any proper information about the maximum length of the <strong>textual representation</strong> of an IPv6 address, which is what a webserver provides through <code>$_SERVER["REMOTE_ADDR"]</code>. </p> <p>I'm not interested in converting the textual representation into the 128 bits the address is usually encoded in, I just want to know how many characters maximum are needed to store any IPv6 address returned by <code>$_SERVER["REMOTE_ADDR"]</code>.</p>
166,157
6
4
null
2008-10-03 09:51:51.87 UTC
85
2022-07-06 13:51:29.14 UTC
2017-04-11 21:14:21.09 UTC
null
1,709,587
Gilles
10,024
null
1
521
ip|ip-address|ipv6
188,982
<p><strong>45 characters</strong>.</p> <p>You might expect an address to be</p> <pre><code>0000:0000:0000:0000:0000:0000:0000:0000 </code></pre> <blockquote> <p>8 * 4 + 7 = 39</p> </blockquote> <p>8 groups of 4 digits with 7 <code>:</code> between them.</p> <p>But if you have an <a href="https://www.rfc-editor.org/rfc/rfc4291#section-2.5.5.2" rel="noreferrer">IPv4-mapped IPv6 address</a>, the last two groups can be written in base 10 separated by <code>.</code>, eg. <code>[::ffff:192.168.100.228]</code>. Written out fully:</p> <pre><code>0000:0000:0000:0000:0000:ffff:192.168.100.228 </code></pre> <blockquote> <p>(6 * 4 + 5) + 1 + (4 * 3 + 3) = 29 + 1 + 15 = <strong>45</strong></p> </blockquote> <p>Note, this is an input/display convention - it's still a 128 bit address and for storage it would probably be best to standardise on the raw colon separated format, i.e. <code>[0000:0000:0000:0000:0000:ffff:c0a8:64e4]</code> for the address above.</p>
1,276,091
Installer generator written in Java?
<p>I'm looking for a free cross-platform installer generator that is fully Java-driven (meaning workflow and plugins are written in Java). Ideally the installer should download the JRE on-demand instead of bundling it directly into the installer. Does something like this already exist?</p> <p>Please note that InstallAnywhere no longer offers a free edition.</p>
1,276,408
6
0
null
2009-08-14 04:50:57.377 UTC
13
2009-08-14 13:24:45.12 UTC
2009-08-14 13:13:42.053 UTC
null
14,731
null
14,731
null
1
15
java|installation|cross-platform
3,957
<ul> <li><a href="http://izpack.org/" rel="noreferrer">IzPack</a></li> <li><a href="http://antigen.sourceforge.net/" rel="noreferrer">Antigen</a></li> <li><a href="http://launch4j.sourceforge.net" rel="noreferrer">Launch4J</a></li> <li><a href="http://antinstaller.sourceforge.net" rel="noreferrer">Antstaller</a></li> <li><a href="http://wrapper.tanukisoftware.org/doc/english/introduction.html" rel="noreferrer">Java Service Wrapper</a></li> <li><a href="http://liftoff.sourceforge.net/index.en.html" rel="noreferrer">Lift Off Java Installer</a></li> <li><a href="http://jsmooth.sourceforge.net/" rel="noreferrer">JSmooth</a></li> <li><a href="http://vainstall.sourceforge.net/" rel="noreferrer">VAInstall</a></li> <li><a href="http://packlet.sourceforge.net/" rel="noreferrer">Packlet</a></li> <li><a href="http://www.yagga.net/java/miniinstaller/index.shtml" rel="noreferrer">Mini Installer</a></li> </ul>
1,196,191
Checking if a ValidationGroup is valid from code-behind
<p>Is there a method I can call that retrieves a boolean value of whether or not a particular ValidationGroup is valid? <strong>I don't want to actually display the validation message or summary</strong> - I just want to know whether it is valid or not.</p> <p>Something like:</p> <pre><code>Page.IsValid("MyValidationGroup") </code></pre>
1,197,500
6
0
null
2009-07-28 19:19:40.18 UTC
4
2014-09-19 15:50:05.673 UTC
2009-07-28 19:36:12.503 UTC
null
86,191
null
86,191
null
1
27
asp.net|validation
39,803
<pre><code>protected bool IsGroupValid(string sValidationGroup) { foreach (BaseValidator validator in Page.Validators) { if (validator.ValidationGroup == sValidationGroup) { bool fValid = validator.IsValid; if (fValid) { validator.Validate(); fValid = validator.IsValid; validator.IsValid = true; } if (!fValid) return false; } } return true; } </code></pre>
911,860
Does malloc lazily create the backing pages for an allocation on Linux (and other platforms)?
<p>On Linux if I were to <code>malloc(1024 * 1024 * 1024)</code>, what does malloc actually do?</p> <p>I'm sure it assigns a virtual address to the allocation (by walking the free list and creating a new mapping if necessary), but does it actually create 1 GiB worth of swap pages? Or does it <code>mprotect</code> the address range and create the pages when you actually touch them like <code>mmap</code> does?</p> <p>(I'm specifying Linux because <a href="http://www.opengroup.org/onlinepubs/009695399/functions/malloc.html" rel="noreferrer">the standard</a> is silent on these kinds of details, but I'd be interested to know what other platforms do as well.)</p>
911,897
6
2
null
2009-05-26 17:40:49.363 UTC
45
2015-02-02 18:33:43.687 UTC
null
null
null
null
2,603
null
1
75
linux|malloc
19,559
<p>Linux does deferred page allocation, aka. 'optimistic memory allocation'. The memory you get back from malloc is not backed by anything and when you touch it you may actually get an OOM condition (if there is no swap space for the page you request), in which case <a href="http://linux-mm.org/OOM_Killer" rel="noreferrer">a process is unceremoniously terminated</a>.</p> <p>See for example <a href="http://www.linuxdevcenter.com/pub/a/linux/2006/11/30/linux-out-of-memory.html" rel="noreferrer">http://www.linuxdevcenter.com/pub/a/linux/2006/11/30/linux-out-of-memory.html</a></p>
13,786,517
Eclipse Unable to Launch, the selection cannot be launched, and there are no recent launches
<p>I am getting the above error when i try to launch a Project which i checked out from SVN Repository. When i make my own Java Project on eclipse with a main class everything works fine, but when i try to run the main class from my repository project i get the above message.</p> <p>I did not have such a problem before. Repository projects were running fine, i got suddenly this error yesterday and after searching the internet i still can't fix it.</p> <p>I have now 3 Projects on eclipse, <strong>home</strong> which is a java project made by me and two projects from repository <strong>lech</strong> and <strong>kramerspitz</strong>.</p> <p>Under Run-> Run Configuration->Java Application->Project Browse i see only the home Project which i made, although the two other repository projects are also in my workspace but they don't show up. (Run As is empty)</p> <p>Does anyone know what i should do? Re-installing Eclipse does not help, cause the problem remains. </p> <p>The only difference i see is that the two repository projects are missing a .classpath file. Please help!</p> <p>Hear are some pics: <img src="https://i.stack.imgur.com/c1ebS.png" alt="eclipse"> <img src="https://i.stack.imgur.com/eOZNx.png" alt="Run Configuration"> <img src="https://i.stack.imgur.com/BNcZv.png" alt="Project Selection"> <img src="https://i.stack.imgur.com/IBgM6.png" alt="workspace"> <img src="https://i.stack.imgur.com/PGYVq.png" alt="home Project made by me"> <img src="https://i.stack.imgur.com/icrBJ.png" alt="kramerspitz repository project (cannot run main)"> <img src="https://i.stack.imgur.com/4VJyh.png" alt="reversi repository project (cannot run main method)"></p>
13,881,233
5
0
null
2012-12-09 10:10:21.293 UTC
null
2018-09-05 08:18:27.643 UTC
null
null
null
null
1,262,566
null
1
4
eclipse|svn
73,936
<p>As it seems I can't just check out on the project from the SVN repository. I have to choose from the project a specific project to check out, then everything works fine. </p>
17,734,343
How to insert javascript variables into a URL
<pre><code>var a = 1; var b = 2; var mylink = "http://website.com/page.aspx?list=' + a + '&amp;sublist=' + b + '"; </code></pre> <p>This doesn't work. Is there a simple way to insert these other variables into the url query?</p>
17,734,360
3
1
null
2013-07-18 21:34:41.51 UTC
5
2020-07-28 06:42:29.837 UTC
null
null
null
null
1,447,679
null
1
11
javascript|jquery
45,445
<p>By using the right quotes:</p> <pre><code>var a = 1; var b = 2; var mylink = "http://website.com/page.aspx?list=" + a + "&amp;sublist=" + b; </code></pre> <p>If you start a string with doublequotes, it can be ended with doublequotes and can contain singlequotes, same goes for the other way around.</p>
18,195,527
Typesafe config: Load additional config from path external to packaged scala application
<p>My scala application will be packaged into a jar. When I run my app, it needs to read an additional config file stored externally to my app jar. I am looking for functionality similar to the Typesafe Config library but other solutions are welcome too ! Is there a way to do something like below:</p> <pre><code>val hdfsConfig = ConfigFactory.load("my_path/hdfs.conf") </code></pre>
18,196,022
3
0
null
2013-08-12 19:50:25.047 UTC
14
2017-08-12 05:35:23.27 UTC
2013-08-12 20:28:55.367 UTC
null
238,012
null
238,012
null
1
53
scala|configuration|app-config|config|typesafe-stack
35,304
<p>I think what you want is:</p> <pre><code>val myCfg = ConfigFactory.parseFile(new File("my_path/hdfs.conf")) </code></pre>
1,515,873
shifting a piece of text down using CSS
<p>I want to shift a text label down by about 6px I am attaching the style:</p> <pre><code>.price-label{ font-family:Arial, Helvetica, sans-serif; font-size:small; position:relative; bottom:-6px; vertical-align:bottom; } </code></pre> <p>The HTML is:</p> <pre><code>&lt;table border="0" cellspacing="1" cellpadding="0"&gt; &lt;tr&gt; &lt;td height="45" colspan="2" align="center"&gt;&lt;p&gt;&lt;span class="text"&gt;Name&lt;/span&gt;&lt;span class="name-label"&gt;&lt;/span&gt;&lt;/p&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&amp;nbsp;&lt;/td&gt; &lt;td class="price-label"&gt;54.67&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td width="28" bgcolor="#CCCCCC"&gt;&amp;nbsp;&lt;/td&gt; &lt;td height="45"&gt;&amp;nbsp;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td width="28" bgcolor="#CC3300"&gt;&amp;nbsp;&lt;/td&gt; &lt;td height="112"&gt;&amp;nbsp;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td width="28" bgcolor="#CCCCCC"&gt;&amp;nbsp;&lt;/td&gt; &lt;td height="22"&gt;&amp;nbsp;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p>Visually I want the 54.67 label to appear horizontally parallel - to the gap where the grey cell (top one) and red cell (second from top) meet. As the number represents that point in the bar to the left.</p> <p>So if some other technqiue is better, please let me know, maybe I should be using DIVs would that give me more control?</p>
1,516,682
5
0
null
2009-10-04 08:01:41.097 UTC
1
2016-03-13 13:38:35.143 UTC
2009-10-04 08:23:12.133 UTC
null
69,803
null
69,803
null
1
14
html|css
72,684
<p>If I'm reading this correctly, then you're trying to straddle the border between two table cells which won't work. You'll need to consolidate the first two cells in the right column and then rowspan="2" the new cell with the number in it. Then top or bottom vertically align the text in the cell and add some padding-top until it's aligned properly. </p>
1,675,992
How do I set a background color for the whole window of a Qt application?
<p>Does anyone know how one would be able to set a background color for the whole window of a Qt application?</p> <p>So far I am using stylesheets but can only figure out how to assign a background color to a widget such as <code>QGroupBox</code> or <code>QPushButton</code>. Basically, if I want a black background how would I make it seamless without any borders of the original background?</p>
1,678,807
5
0
null
2009-11-04 19:18:17.903 UTC
10
2017-08-24 13:45:31.85 UTC
2017-08-24 13:45:31.85 UTC
null
6,165,833
null
117,543
null
1
28
c++|qt|qstylesheet|qwindow
85,089
<p>I would simply use a Style Sheet for the whole window.</p> <p>For instance, if your window is inheriting from QWidget, here is what I'm doing :</p> <pre><code>MainWindow::MainWindow(QWidget *parent) : QWidget(parent), ui(new Ui::MainWindow) { ui-&gt;setupUi(this); this-&gt;setStyleSheet("background-color: black;"); } </code></pre> <p>On my Mac, my whole application window is black (except the title bar).</p> <p>EDIT : according to comment, here is a solution without using ui files and loading an external style sheet</p> <pre><code>#include &lt;QtGui/QApplication&gt; #include &lt;QtGui/QMainWindow&gt; #include &lt;QtGui/QVBoxLayout&gt; #include &lt;QtGui/QPushButton&gt; #include &lt;QtCore/QFile&gt; int main(int ArgC, char* ArgV[]) { QApplication MyApp(ArgC, ArgV); QMainWindow* pWindow = new QMainWindow; QVBoxLayout* pLayout = new QVBoxLayout(pWindow); pWindow-&gt;setLayout(pLayout); QPushButton* pButton = new QPushButton("Test", pWindow); pLayout-&gt;addWidget(pButton); QFile file(":/qss/default.qss"); file.open(QFile::ReadOnly); QString styleSheet = QLatin1String(file.readAll()); qApp-&gt;setStyleSheet(styleSheet); pWindow-&gt;setVisible(true); MyApp.exec(); } </code></pre> <p>The style sheet file (default.qss) is as follow :</p> <pre><code>QWidget { background-color: black; } </code></pre> <p>This file is part of a resource file (stylesheet.qrc) :</p> <pre><code>&lt;RCC&gt; &lt;qresource prefix="/qss"&gt; &lt;file&gt;default.qss&lt;/file&gt; &lt;/qresource&gt; &lt;/RCC&gt; </code></pre> <p>And here is my project file :</p> <pre><code>TARGET = StyleSheet TEMPLATE = app SOURCES += main.cpp RESOURCES += stylesheet.qrc </code></pre>
2,324,030
java thread reuse
<p>I have always read that creating threads is expensive.<br> I also know that you cannot rerun a thread.</p> <p>I see in the doc of <code>Executors</code> class:</p> <blockquote> <p>Creates a thread pool that creates new threads as needed, but will reuse previously constructed threads when they are available.</p> </blockquote> <p>Mind the word 'reuse'.</p> <p>How do thread pools 'reuse' threads? </p>
2,324,114
5
0
null
2010-02-24 06:06:11.39 UTC
18
2022-08-05 17:44:35.077 UTC
2018-02-20 10:40:51.543 UTC
null
4,922,375
null
207,707
null
1
71
java|multithreading
32,032
<p>I think I understood what is confuzzabling you so here's my longer answer: the terminology is a tiny bit misleading (obviously, or you wouldn't ask that question specifically putting the emphasis on 'reuse'):</p> <p><em>How do thread pools 'reuse' threads?</em> </p> <p>What is happening is that a single thread can be used to process several tasks (typically passed as <code>Runnable</code>, but this depend on your 'executor' framework: the default executors accepts <code>Runnable</code>, but you could write your own "executor" / thread-pool accepting something more complex than a <code>Runnable</code> [like, say, a <code>CancellableRunnable</code>]).</p> <p>Now in the default <code>ExecutorService</code> implementation if a thread is somehow terminated while still in use, it is automatically replaced with a new thread, but this is not the 'reuse' they're talking about. There is no "reuse" in this case.</p> <p>So it is true that you cannot call <code>start()</code> on a Java Thread twice <em>but</em> you can pass as many <code>Runnable</code> as you want to an executor and each <code>Runnable</code>'s <code>run()</code> method shall be called once.</p> <p>You can pass 30 <code>Runnable</code> to 5 Java <code>Thread</code> and each worker thread may be calling, for example, <code>run()</code> 6 times (practically there's not guarantee that you'll be executing exactly 6 <code>Runnable</code> per <code>Thread</code> but that is a detail).</p> <p>In this example <code>start()</code> would have been called 6 times. Each one these 6 <code>start()</code> will call <em>exactly once</em> the <code>run()</code> method of each <code>Thread</code>:</p> <p>From <code>Thread.start()</code> Javadoc:</p> <blockquote> <pre><code> * Causes this thread to begin execution; the Java Virtual Machine * calls the &lt;code&gt;run&lt;/code&gt; method of this thread. </code></pre> </blockquote> <p><strong>BUT</strong> then inside each Thread's <code>run()</code> method <code>Runnable</code> shall be dequeued and the <code>run()</code> method of each <code>Runnable</code> is going to be called. So each thread can process several <code>Runnable</code>. That's what they refer to by "thread reuse".</p> <p>One way to do your own thread pool is to use a blocking queue on to which you enqueue runnables and have each of your thread, once it's done processing the <code>run()</code> method of a <code>Runnable</code>, dequeue the next <code>Runnable</code> (or block) and run its <code>run()</code> method, then rinse and repeat.</p> <p>I guess part of the confusion (and it is a bit confusing) comes from the fact that a <code>Thread</code> takes a <code>Runnable</code> and upon calling <code>start()</code> the Runnable 's <code>run()</code> method is called while the default thread pools <em>also</em> take <code>Runnable</code>.</p>
2,323,577
How can I use Google Chrome's V8 JavaScript interpreter from Delphi?
<p>I'd like to embed the V8 JavaScript interpreter that ships with Google Chrome within my Delphi application. I'm aware of the <a href="http://code.google.com/p/chromiumembedded/downloads/list" rel="noreferrer">chromium embedded</a> open-source project from Google, but I'd like to know if anyone was aware of any Pascal/Delphi wrappers?</p> <p>There is an example project included with the zip file on the site I linked, which is written in C++. If nothing else, I'll slowly and painfully work to convert it.</p> <p><strong>UPDATE</strong>:<br>I just want to embed the V8 JavaScript interpreter, <em>not</em> the Chromium browser.</p>
6,282,138
6
3
null
2010-02-24 03:59:07.653 UTC
12
2017-11-10 08:32:11.24 UTC
2010-02-24 13:49:29.063 UTC
null
12,458
null
12,458
null
1
18
javascript|delphi
7,986
<p>For the record: hgourvest has posted <a href="http://code.google.com/p/delphichromiumembedded/" rel="nofollow">Delphi Chromium Embedded</a> to Google Code. </p> <p>Edit 2013-01-15:</p> <p>Another project by the same author this time wrapping CEF3: <a href="http://code.google.com/p/dcef3/" rel="nofollow">DCEF3</a></p>
1,502,860
What are the most commonly used runtime exceptions in java?
<p>As a java programmer who wishes to perfect his programming skills, I often come across the situations that I have to create a runtime exception. I know it's a good practice if one use wisely. </p> <p>Personally, <strong>NullPointerException</strong> and <strong>IllegalStateException</strong> are the most commonly used in the softwares that I have created. How about you?</p> <p>What runtime exceptions do you often use? In what situations do you use them?</p>
1,502,892
6
0
null
2009-10-01 09:19:37.23 UTC
11
2017-12-14 04:32:10.44 UTC
null
null
null
null
113,037
null
1
46
java|exception|runtime
39,762
<p>I never throw <strong>NullPointerException</strong>. For me, it is one that appears naturally in the code when something goes wrong and that requires a developer to look at what happens. Then (s)he fixes the cause and it doesn't happen again.</p> <p>I use <strong>IllegalStateException</strong> to signal that an object is incorrectly configured or that calls are in an incorrect order. However, we all know that ideally, an object should ensure it can't be in a bad state and that you can't call it in incorrect order (make a builder and a resulting object ...).</p> <p>I use a lot of <strong>IllegalArgumentException</strong> when a method detects that its parameters are incorrect. This is the responsibility of any public method, to stop processing (to avoid indirect errors that are more difficult to understand). Also, a few <code>if</code>s in the beginning of a method serve a documentation purpose (documentation that never diverge from the code because it is the code :-) ).</p> <pre><code> public void myMethod(String message, Long id) { if (message == null) { throw new IllegalArgumentException("myMethod's message can't be null"); // The message doesn't log the argument because we know its value, it is null. } if (id == null) { throw new IllegalArgumentException("myMethod's id can't be null"); // This case is separated from the previous one for two reasons : // 1. to output a precise message // 2. to document clearly in the code the requirements } if (message.length()&lt;12) { throw new IllegalArgumentException("myMethod's message is too small, was '" + message + "'"); // here, we need to output the message itself, // because it is a useful debug information. } } </code></pre> <p>I also use <strong>specific Runtime Exceptions</strong> to signal higher level exceptional conditions. </p> <blockquote> <p>For example, if a module of my application couldn't start, I might have a <em>ModuleNotOperationalException</em> thrown (ideally by a generic code like an interceptor, otherwise by a specific code) when another module calls it. After that architectural decision, each module has to deal with this exception on operations that call other modules...</p> </blockquote>
1,823,341
How do I get this CSS text-decoration override to work?
<p>Some days I swear I'm going mad. This is one of those days. I thought my CSS was fairly straight-forward here, but it just doesn't seem to be working. What am I missing?</p> <p>My CSS looks like this:</p> <pre><code>ul &gt; li { text-decoration: none; } ul &gt; li.u { text-decoration: underline; } ul &gt; li &gt; ul &gt; li { text-decoration: none; } ul &gt; li &gt; ul &gt; li.u { text-decoration: underline; } </code></pre> <p>And my HTML looks like this:</p> <pre class="lang-html prettyprint-override"><code>&lt;ul&gt; &lt;li&gt;Should not be underlined&lt;/li&gt; &lt;li class="u"&gt;Should be underlined &lt;ul&gt; &lt;li&gt;Should not be underlined&lt;/li&gt; &lt;li class="u"&gt;Should be underlined&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre> <p>Yet it comes up like this:</p> <p><img src="https://imgur.com/MBXIo.gif" alt="Image"></p>
1,823,388
7
2
null
2009-12-01 00:38:43.223 UTC
6
2021-10-13 14:06:42.643 UTC
2011-12-30 17:34:56.08 UTC
null
106,224
null
5,454
null
1
38
html|css|text-decorations
25,350
<p><code>text-decoration</code> does not behave the same as other font/text related styling like <code>font-weight</code>. Applying <code>text-decoration</code> will affect all nested elements as well.</p> <p>Check this out: <a href="http://www.w3.org/TR/CSS21/text.html#propdef-text-decoration" rel="noreferrer">http://www.w3.org/TR/CSS21/text.html#propdef-text-decoration</a></p> <p>Excerpt: </p> <blockquote> <p>Text decorations on inline boxes are drawn across the entire element, going across any descendant elements without paying any attention to their presence. The 'text-decoration' property on descendant elements cannot have any effect on the decoration of the element<br> . . . .<br> Some user agents have implemented text-decoration by propagating the decoration to the descendant elements as opposed to simply drawing the decoration through the elements as described above. This was arguably allowed by the looser wording in CSS2.</p> </blockquote> <p>I've got the info from: <a href="http://csscreator.com/node/14951" rel="noreferrer">http://csscreator.com/node/14951</a></p>
1,651,113
Firefox plugin or way to monitor ALL request data, including headers and content downloaded to browser
<p>I am having problems getting ALL of the information that is downloaded to a browser. For example, I want a plugin, ideally a firefox plugin to download the HTML content and monitor when I get a 302 redirect, and all header information.</p> <p>So far, use Live HTTP Headers and Firebug. Both are fine.</p> <p>With Live HTTP headers, I can't monitor the data that is downloaded (e.g. the html data) Firebug is worse, because I can't monitor the headers and I can't monitor the full requests. For example, Firebug won't show you all of the content that is downloaded, just the last set of requests. E.g. redirects will clear the Firebug net monitoring.</p> <p>I am on win32</p>
1,651,131
8
1
null
2009-10-30 17:05:24.393 UTC
19
2020-04-24 17:19:31.37 UTC
null
null
null
null
10,522
null
1
27
http|firefox|firebug|header
56,191
<p>Try <strong><em><a href="https://addons.mozilla.org/en-US/firefox/addon/966" rel="noreferrer">Tamper data</a></em></strong> firefox add-on, an extension to <em>track and modify http/https requests</em>.</p> <p>You can find a <a href="http://jimbojw.com/wiki/index.php?title=Tamper_Data" rel="noreferrer">nice tutorial here</a>.</p> <p><strong>Firebug + Tamper Data is the best couple of firefox tools I cannot live without</strong>.</p>
1,813,853
#ifdef #ifndef in Java
<p>I doubt if there is a way to make compile-time conditions in Java like #ifdef #ifndef in C++.</p> <p>My problem is that have an algorithm written in Java, and I have different running time improves to that algorithm. So I want to measure how much time I save when each improve is used.</p> <p>Right now I have a set of boolean variables that are used to decide during the running time which improve should be used and which not. But even testing those variables influences the total running time. </p> <p>So I want to find out a way to decide during the compilation time which parts of the program should be compiled and used. </p> <p>Does someone knows a way to do it in Java. Or maybe someone knows that there is no such way (it also would be useful).</p>
1,813,873
8
0
null
2009-11-28 21:38:27.913 UTC
32
2020-12-17 19:37:47.047 UTC
2009-11-28 21:40:45.877 UTC
null
171,461
null
188,264
null
1
110
java|compilation|conditional|conditional-compilation
80,553
<pre><code>private static final boolean enableFast = false; // ... if (enableFast) { // This is removed at compile time } </code></pre> <p>Conditionals like that shown above are evaluated at compile time. If instead you use this</p> <pre><code>private static final boolean enableFast = "true".equals(System.getProperty("fast")); </code></pre> <p>Then any conditions dependent on enableFast will be evaluated by the JIT compiler. The overhead for this is negligible.</p>
1,938,855
How to store a large (10 digits) integer?
<p>Which Java data type would be able to store a big numerical value, like 9999999999?</p>
1,938,858
9
0
null
2009-12-21 08:22:45.077 UTC
10
2021-04-08 18:08:05.663 UTC
2017-11-09 18:11:56.367 UTC
null
452,775
null
193,133
null
1
29
java
153,735
<p>Your concrete example could be stored in <code>long</code> (or <code>java.lang.Long</code> if this is necessary).</p> <p>If at any point you need bigger numbers, you can try <a href="http://java.sun.com/javase/6/docs/api/java/math/BigInteger.html" rel="noreferrer"><code>java.math.BigInteger</code></a> (if integer), or <a href="http://java.sun.com/javase/6/docs/api/java/math/BigDecimal.html" rel="noreferrer"><code>java.math.BigDecimal</code></a> (if decimal)</p>
1,522,210
NSLocale currentLocale always returns "en_US" not user's current language
<p>I'm in the processes of internationalizing an iPhone app - I need to make programmatic changes to certain views based on what the user's current locale is. I'm going nuts because no matter what the language preference on the iPhone simulator or actual hardware are, <code>locale</code> always evaluates to "en_US":</p> <pre><code>NSString *locale = [[NSLocale currentLocale] localeIdentifier]; NSLog(@"current locale: %@", locale); </code></pre> <p>The crazy thing is that the rest of the application behaves as expected. The correct strings are selected from the Localization.strings file and used in the interface, and the correct .xib files for the selected locale are used.</p> <p>I have also tried the following, to no avail and with the same result:</p> <pre><code>NSString *locale = [[NSLocale autoupdatingCurrentLocale] localeIdentifier]; NSLog(@"current locale: %@", locale); </code></pre> <p>Is there something simple I'm missing? A preference or an import perhaps?</p> <p><strong>What I used to do:</strong></p> <p>As Darren's answer suggests, the preference I'm looking for is not in <code>NSLocale</code>, rather it is here:</p> <pre><code>NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults]; NSArray* languages = [userDefaults objectForKey:@"AppleLanguages"]; NSString* preferredLanguage = [languages objectAtIndex:0]; NSLog(@"preferredLanguage: %@", preferredLang); </code></pre> <p><strong>Peter's answer seems to be a better solution:</strong></p> <pre><code>NSArray* preferredLanguages = [NSLocale preferredLanguages]; NSLog(@"preferredLanguages: %@", preferredLanguages); </code></pre>
2,535,748
9
0
null
2009-10-05 20:28:56.16 UTC
22
2019-03-15 10:05:07.81 UTC
2014-10-14 04:09:39.08 UTC
null
27,462
null
27,462
null
1
84
iphone|objective-c|cocoa|internationalization
64,331
<p>Instead of querying defaults directly using an undocumented key, <a href="http://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSLocale_Class/Reference/Reference.html#//apple_ref/occ/clm/NSLocale/preferredLanguages" rel="noreferrer">ask the NSLocale <em>class</em> for the array of preferred languages</a>.</p>
2,023,130
Benefits of an enterprise service bus
<p><strong>Where can I find some information on the uses and benefits of an enterprise service bus (ESB)?</strong></p> <p>I am looking for information about:</p> <ol> <li>the kinds of problems and ESB helps to solve</li> <li>the alternatives to an ESB - and the tradeoffs in selecting between them</li> <li>what you need to do as a developer to build ESB-compatible systems</li> </ol> <p>I'm looking for a finer level of detail than just Wikipedia or online marketing brochures from vendors. Ideally, some example code would help to clarify what's involved in taking advantage of an ESB. Information from a .NET or Java perspective would be the most useful.</p> <p>Thanks.</p>
2,023,224
11
1
null
2010-01-07 19:42:54.413 UTC
17
2017-02-17 13:37:02.447 UTC
2010-12-11 21:30:00.797 UTC
null
21,234
null
91,671
null
1
31
java|.net|architecture|esb
28,396
<p>I'd suggest <a href="http://blogs.mulesoft.com/dev/mule-dev/to-esb-or-not-to-esb/" rel="nofollow noreferrer">To ESB or not to ESB</a> to start with, written by the creator of <a href="http://www.mulesoft.org" rel="nofollow noreferrer">Mule</a>.</p>
1,614,236
In Python, how do I convert all of the items in a list to floats?
<p>I have a script which reads a text file, pulls decimal numbers out of it as strings and places them into a list.</p> <p>So I have this list:</p> <pre><code>my_list = ['0.49', '0.54', '0.54', '0.55', '0.55', '0.54', '0.55', '0.55', '0.54'] </code></pre> <p>How do I convert each of the values in the list from a string to a float?</p> <p>I have tried:</p> <pre><code>for item in my_list: float(item) </code></pre> <p>But this doesn't seem to work for me.</p>
1,614,247
13
2
null
2009-10-23 15:33:00.873 UTC
77
2022-04-15 10:47:03.887 UTC
2021-11-12 10:17:21.41 UTC
null
6,705,902
snk
null
null
1
329
python|list|casting
982,166
<pre><code>[float(i) for i in lst] </code></pre> <p>to be precise, it creates a new list with float values. Unlike the <code>map</code> approach it will work in py3k.</p>
1,885,101
Delete data from all tables in MYSQL
<p>I have 100 tables, 40,000 rows in each table. I want to go into MySQL and delete <strong>all</strong> rows from <strong>all</strong> tables.</p> <p>...in 1 statement, if possible?</p> <p>I want to keep the database and tables.</p>
1,885,142
16
0
null
2009-12-11 00:36:18.927 UTC
12
2021-06-04 02:47:16.68 UTC
2009-12-11 00:55:54.467 UTC
null
135,152
null
179,736
null
1
46
sql|mysql
96,835
<p>I don't think so (but I've been wrong before). What I tend to do is those cases is a two-step process.</p> <p>If your DBMS has a command line interface, you can use it to create a script to do the bulk of the work, something like:</p> <pre><code>db2 "select 'db2 delete from ' | tblname from sysibm.systables where owner = 'pax'" &gt;p2.sh p2.sh </code></pre> <p>The first bit simply creates a <code>p2.sh</code> file (or a <code>p2.cmd</code> file under Windows) containing a <code>delete from</code> statement for every table owned by <code>pax</code>. Then you just run that command file to do the dirty work. You may want to check it first, of course :-)</p> <p>Not the one-step process you were looking for but still very simple. I'm assuming here that mysql also has a command line interface.</p> <p><em>Update:</em></p> <p>The MySQL version of the above looks like it should be:</p> <pre><code>echo "select 'mysql truncate table ' | table_name from information_schema.tables" | mysql &gt;p2.sh bash p2.sh </code></pre> <p>This uses the <code>truncate</code> command which is usually more efficient than <code>delete from</code> for deleting all rows. It also uses the proper MySQL system tables to get the table names.</p> <p>One point though - you may want to put a <code>where</code> clause on that select to limit the tables to those you want deleted. The query as it stands will try to delete every table. One possibility is to limit it with specific <code>table_schema</code> and/or <code>table_type</code> values.</p>
8,535,540
Exactly how many comparisons does merge sort make?
<p>I have read that quicksort is much faster than mergesort in practice, and the reason for this is the hidden constant.</p> <p>Well, the solution for the randomized quick sort complexity is 2nlnn=1.39nlogn which means that the constant in quicksort is 1.39.</p> <p>But what about mergesort? What is the constant in mergesort?</p>
8,539,280
6
2
null
2011-12-16 14:25:23.96 UTC
9
2021-07-05 18:13:58.617 UTC
2020-08-12 01:58:09.26 UTC
null
214,143
null
894,893
null
1
12
algorithm|sorting|complexity-theory|quicksort|mergesort
77,435
<p>Let's see if we can work this out!</p> <p>In merge sort, at each level of the recursion, we do the following:</p> <ol> <li>Split the array in half.</li> <li>Recursively sort each half.</li> <li>Use the merge algorithm to combine the two halves together.</li> </ol> <p>So how many comparisons are done at each step? Well, the divide step doesn't make any comparisons; it just splits the array in half. Step 2 doesn't (directly) make any comparisons; all comparisons are done by recursive calls. In step 3, we have two arrays of size n/2 and need to merge them. This requires at most n comparisons, since each step of the merge algorithm does a comparison and then consumes some array element, so we can't do more than n comparisons.</p> <p>Combining this together, we get the following recurrence:</p> <pre><code>C(1) = 0 C(n) = 2C(n / 2) + n </code></pre> <p>(As mentioned in the comments, the linear term is more precisely (n - 1), though this doesn’t change the overall conclusion. We’ll use the above recurrence as an upper bound.)</p> <p>To simplify this, let's define n = 2<sup>k</sup> and rewrite this recurrence in terms of k:</p> <pre><code>C'(0) = 0 C'(k) = 2C'(k - 1) + 2^k </code></pre> <p>The first few terms here are 0, 2, 8, 24, ... . This looks something like k 2<sup>k</sup>, and we can prove this by induction. As our base case, when k = 0, the first term is 0, and the value of k 2<sup>k</sup> is also 0. For the inductive step, assume the claim holds for some k and consider k + 1. Then the value is 2(k 2<sup>k</sup>) + 2<sup>k + 1</sup> = k 2<sup> k + 1</sup> + 2<sup>k + 1</sup> = (k + 1)2<sup>k + 1</sup>, so the claim holds for k + 1, completing the induction. Thus the value of C'(k) is k 2<sup>k</sup>. Since n = 2<sup> k</sup>, this means that, assuming that n is a perfect power of two, we have that the number of comparisons made is</p> <blockquote> <p>C(n) = n lg n</p> </blockquote> <p>Impressively, this is <em>better</em> than quicksort! So why on earth is quicksort faster than merge sort? This has to do with other factors that have nothing to do with the number of comparisons made. Primarily, since quicksort works in place while merge sort works out of place, the locality of reference is not nearly as good in merge sort as it is in quicksort. This is such a huge factor that quicksort ends up being much, much better than merge sort in practice, since the cost of a cache miss is pretty huge. Additionally, the time required to sort an array doesn't just take the number of comparisons into account. Other factors like the number of times each array element is moved can also be important. For example, in merge sort we need to allocate space for the buffered elements, move the elements so that they can be merged, then merge back into the array. These moves aren't counted in our analysis, but they definitely add up. Compare this to quicksort's partitioning step, which moves each array element exactly once and stays within the original array. These extra factors, not the number of comparisons made, dominate the algorithm's runtime.</p> <p>This analysis is a bit less precise than the optimal one, but <a href="http://en.wikipedia.org/wiki/Merge_sort#Analysis" rel="noreferrer">Wikipedia</a> confirms that the analysis is roughly n lg n and that this is indeed fewer comparisons than quicksort's average case.</p> <p>Hope this helps!</p>
8,773,299
How to cut an entire line in vim and paste it?
<p>I know how to use the <code>v</code> command in vim, but I need something which will delete an entire line and it should allow me to paste the same line somewhere else.</p>
15,653,788
10
2
null
2012-01-07 21:35:33.513 UTC
37
2020-11-24 20:41:56.117 UTC
2012-01-07 21:59:04.44 UTC
null
569,015
null
569,015
null
1
250
vim
169,500
<p>Pressing <kbd>Shift</kbd>+<kbd>v</kbd> would select that entire line and pressing <kbd>d</kbd> would delete it.</p> <p>You can also use <kbd>d</kbd><kbd>d</kbd>, which is does not require you to enter visual mode.</p>
17,800,008
How to find unused classes in my HTML?
<p>There are lots of tools for finding unused CSS rules in stylesheets, such as <a href="https://developer.chrome.com/devtools#audits" rel="noreferrer">Chrome Audits</a> and the <a href="https://addons.mozilla.org/nl/firefox/addon/dust-me-selectors/" rel="noreferrer">Dust-Me Selectors</a> add-on for Firefox (unfortunately not compatible with Firefox Quantum).</p> <p>But what about the other way around?</p> <p>How do I find classes that are in my HTML, that do not exist in my stylesheets?</p>
17,800,494
5
3
null
2013-07-23 01:17:25.503 UTC
7
2019-06-14 12:03:50.313 UTC
2018-02-01 08:53:28.753 UTC
null
962,603
null
574,240
null
1
30
html|css|optimization
6,087
<p>This may be helpful: <a href="https://code.google.com/p/find-unused-classes/" rel="noreferrer">https://code.google.com/p/find-unused-classes/</a> . According to the description: </p> <blockquote> <p>It shows classes that exist in css selectors and do not exist on html page and like-verse.</p> </blockquote> <p>As Jim said, be warned that some classes may be unused by your stylesheets but still used in JavaScript.</p>
6,377,695
Best practices and issues on using git-tfs bridge
<p>Well, I started this topic mainly to share the experience I had with git-tfs recently with the community.</p> <p>If anybody has anything else to share - it will be helpful for me as well.</p>
6,377,696
3
0
null
2011-06-16 19:48:33.75 UTC
11
2012-12-06 10:34:39.177 UTC
2011-06-17 01:32:41.033 UTC
null
1,864,976
null
104,344
null
1
14
git|tfs|git-tfs
3,458
<p>About work in environment where several developers use git-tfs simultaneously. About commit identity caveats actually: <a href="http://sparethought.wordpress.com/2011/06/16/first-git-tfs-usage-problems/" rel="noreferrer">http://sparethought.wordpress.com/2011/06/16/first-git-tfs-usage-problems/</a></p> <p>Is rebasing workflow with git-tfs possible? <a href="http://sparethought.wordpress.com/2011/06/21/gittfs-rebasing-workflow-is-it-possible/" rel="noreferrer">http://sparethought.wordpress.com/2011/06/21/gittfs-rebasing-workflow-is-it-possible/</a></p> <p>Not specifically git-tfs but affects it too. Problems with HOME directory on Windows: <a href="http://sparethought.wordpress.com/2011/06/16/troubleshooting-gitextensions-home-directory/" rel="noreferrer">http://sparethought.wordpress.com/2011/06/16/troubleshooting-gitextensions-home-directory/</a></p> <p>Establishing central git repository to avoid redundant TFS round-trips: <a href="http://sparethought.wordpress.com/2011/07/18/how-to-establish-git-central-repository-for-working-against-tfs-with-git-tfs-bridge/" rel="noreferrer">http://sparethought.wordpress.com/2011/07/18/how-to-establish-git-central-repository-for-working-against-tfs-with-git-tfs-bridge/</a></p> <p>My environment for day-to-day work with git-tfs: <a href="http://sparethought.wordpress.com/2012/08/23/my-environment-for-day-to-day-work-with-git-tfs/" rel="noreferrer">http://sparethought.wordpress.com/2012/08/23/my-environment-for-day-to-day-work-with-git-tfs/</a></p>
6,985,932
How do I compare two jQuery objects for identity?
<p>I'm trying to use jQuery to open / close control 'boxes' on a webpage. Unfortunately, it doesn't look very good to close a box just to re-open it if the user happens to click on the already opened box. (Boxes are mutually exclusive).</p> <p>The code I'm using doesn't work, and I'm not sure why. I still get a box closing just to open up anew, which isn't the desired functionality. I created the 'val' variable for debugging purposes; in the debugger, it shows 'val' as having the exact same value as $(this), which should prevent it from getting to the <code>.slideToggle()</code> inside the if statement, but doesn't.</p> <pre><code>function openBox(index) { val = $('#box' + index); $('.profilePageContentBox').each(function(){ if($(this).css('display') != 'none') { if($(this) != val) { $(this).slideToggle(200); } } }); val.slideToggle(200); } </code></pre>
6,985,990
3
1
null
2011-08-08 17:18:34.723 UTC
5
2015-02-23 02:20:40.027 UTC
2015-02-23 02:20:40.027 UTC
null
212,378
null
439,778
null
1
39
javascript|jquery
27,731
<p>Using the <code>$()</code> function will always create a new object, so no matter what, your equality check there will always fail.</p> <p>For example:</p> <pre><code>var div = document.getElementById('myDiv'); $(div) === $(div); // false! </code></pre> <p>Instead, you could try just storing the actual DOM elements, since those are just <em>referred</em> to inside jQuery objects.</p> <pre><code>val = $('#box'+index).get(0); ... if (this !== val) { } </code></pre>
6,776,050
How long to brute force a salted SHA-512 hash? (salt provided)
<p>Here is an algorithm in Java:</p> <pre><code>public String getHash(String password, String salt) throws Exception { String input = password + salt; MessageDigest md = MessageDigest.getInstance(SHA-512); byte[] out = md.digest(input.getBytes()); return HexEncoder.toHex(out); } </code></pre> <p>Assume the salt is known. I want to know the time to brute force for when the password is a dictionary word and also when it is not a dictionary word.</p>
6,783,054
3
3
null
2011-07-21 12:28:32.563 UTC
35
2022-04-05 18:24:02.443 UTC
2014-09-16 15:58:37.3 UTC
null
3,049,628
null
396,106
null
1
57
hash|cryptography|salt|brute-force|sha
112,092
<p>In your case, breaking the hash algorithm is equivalent to finding a collision in the hash algorithm. That means you don't need to find the password itself (which would be a <a href="http://en.wikipedia.org/wiki/Preimage_attack" rel="noreferrer">preimage attack</a>), you just need to find an output of the hash function that is equal to the hash of a valid password (thus "collision"). Finding a collision using a <a href="http://en.wikipedia.org/wiki/Birthday_attack" rel="noreferrer">birthday attack</a> takes O(2^(n/2)) time, where n is the output length of the hash function in bits. </p> <p>SHA-2 has an output size of 512 bits, so finding a collision would take O(2^256) time. Given there are no clever attacks on the algorithm itself (currently none are known for the SHA-2 hash family) this is what it takes to break the algorithm. </p> <p>To get a feeling for what 2^256 actually means: currently it is believed that the number of atoms in the (entire!!!) universe is roughly 10^80 which is roughly 2^266. Assuming 32 byte input (which is reasonable for your case - 20 bytes salt + 12 bytes password) my machine takes ~0,22s (~2^-2s) for 65536 (=2^16) computations. So 2^256 computations would be done in 2^240 * 2^16 computations which would take</p> <pre><code>2^240 * 2^-2 = 2^238 ~ 10^72s ~ 3,17 * 10^64 years </code></pre> <p>Even calling this millions of years is ridiculous. And it doesn't get much better with the fastest hardware on the planet computing thousands of hashes in parallel. No human technology will be able to crunch this number into something acceptable.</p> <p>So forget brute-forcing SHA-256 here. Your next question was about dictionary words. To retrieve such weak passwords <a href="http://en.wikipedia.org/wiki/Rainbow_table" rel="noreferrer">rainbow tables</a> were used traditionally. A rainbow table is generally just a table of precomputed hash values, the idea is if you were able to precompute and store every possible hash along with its input, then it would take you O(1) to look up a given hash and retrieve a valid preimage for it. Of course this is not possible in practice since there's no storage device that could store such enormous amounts of data. This dilemma is known as <a href="http://en.wikipedia.org/wiki/Space%E2%80%93time_tradeoff" rel="noreferrer">memory-time tradeoff</a>. As you are only able to store so many values typical rainbow tables include some form of hash chaining with intermediary reduction functions (this is explained in detail in the Wikipedia article) to save on space by giving up a bit of savings in time. </p> <p>Salts were a countermeasure to make such rainbow tables infeasible. To discourage attackers from precomputing a table for a specific salt it is recommended to apply per-user salt values. However, since users do not use secure, completely random passwords, it is still surprising how successful you can get if the salt is known and you just iterate over a large dictionary of common passwords in a simple trial and error scheme. The relationship between natural language and randomness is expressed as <a href="http://en.wikipedia.org/wiki/Entropy_%28information_theory%29" rel="noreferrer">entropy</a>. Typical password choices are generally of low entropy, whereas completely random values would contain a maximum of entropy.</p> <p>The low entropy of typical passwords makes it possible that there is a relatively high chance of one of your users using a password from a relatively small database of common passwords. If you google for them, you will end up finding torrent links for such password databases, often in the gigabyte size category. Being successful with such a tool is usually in the range of minutes to days if the attacker is not restricted in any way.</p> <p>That's why generally hashing and salting alone is not enough, you need to install other safety mechanisms as well. You should use an artificially slowed down entropy-enducing method such as PBKDF2 described in <a href="http://www.rsa.com/rsalabs/node.asp?id=2127" rel="noreferrer">PKCS#5</a> and you should enforce a waiting period for a given user before they may retry entering their password. A good scheme is to start with 0.5s and then doubling that time for each failed attempt. In most cases users don't notice this and don't fail much more often than three times on average. But it will significantly slow down any malicious outsider trying to attack your application.</p>
15,798,930
Batch script if else command
<p>I'm trying to make a simple batch script to wipe/zero a flash drive and reformat it. It's for others, so i'm attempting to make it relatively safe, by blocking formatting to C:, D:, etc.</p> <p>I'm looking for an IF ELSE type command i can use, to be an error catch-all.</p> <p>Here's (the main portion of) what i have ATM</p> <pre><code>:again echo. cls echo. echo Please select the drive letter for the flash echo drive you wish to erase echo. echo **** DO NOT SELECT C: OR D: **** echo. echo. echo *** Enter letter (no colon) ONLY e.g. "E" *** echo. set /p answer= cls echo. echo. echo. if /i "%answer:~,1%" EQU "e" format E: /x /fs:FAT32 /v:FORENSICS /p:2 if /i "%answer:~,1%" EQU "f" format F: /x /fs:FAT32 /v:FORENSICS /p:2 if /i "%answer:~,1%" EQU "g" format G: /x /fs:FAT32 /v:FORENSICS /p:2 if /i "%answer:~,1%" EQU "h" format H: /x /fs:FAT32 /v:FORENSICS /p:2 if /i "%answer:~,1%" NOT exist goto again &amp;&amp; echo Please provide a valid drive letter for flash drive echo. </code></pre> <p>Now I know that </p> <pre><code>if /i "%answer:~,1%" NOT exist goto again &amp;&amp; echo Please provide a valid drive letter for flash drive </code></pre> <p>is not valid syntax, but what could I use in order to achieve the same goal? I know there is a more effecient way to do this (e.g. instead of defining 4 variables for likely drive letters, put a single variable that listens to user input and accepts it if it exists.)</p> <p>This is my first foray into batch scripting (and scripting in general) and i'm learning on-the-fly, so the "dumber" you can make it, the better.</p> <p>Thanks in advance.</p>
15,799,112
1
3
null
2013-04-03 21:57:28.01 UTC
3
2016-08-26 20:14:41.563 UTC
null
null
null
null
2,242,454
null
1
8
windows|batch-file|cmd|command-prompt
56,343
<p>Try this:</p> <pre><code>echo.%answer:~,1% | findstr /r /i "[e-h]" if %errorlevel% equ 0 ( format %answer:~,1%: /x /fs:FAT32 /v:FORENSICS /p:2 ) else ( echo Please provide a valid drive letter for flash drive. goto again ) </code></pre>