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
19,299,508
How can I check if given int exists in array?
<p>For example, I have this array:</p> <pre><code>int myArray[] = { 3, 6, 8, 33 }; </code></pre> <p>How to check if given variable x is in it?</p> <p>Do I have to write my own function and loop the array, or is there in modern c++ equivalent to <code>in_array</code> in PHP?</p>
19,299,611
6
1
null
2013-10-10 15:06:40.987 UTC
9
2017-10-18 19:52:39.483 UTC
2015-07-25 05:39:13.043 UTC
null
3,696,113
null
393,087
null
1
32
c++|arrays
137,590
<p>You can use <a href="http://en.cppreference.com/w/cpp/algorithm/find" rel="noreferrer"><code>std::find</code></a> for this:</p> <pre><code>#include &lt;algorithm&gt; // for std::find #include &lt;iterator&gt; // for std::begin, std::end int main () { int a[] = {3, 6, 8, 33}; int x = 8; bool exists = std::find(std::begin(a), std::end(a), x) != std::end(a); } </code></pre> <p><code>std::find</code> returns an iterator to the first occurrence of <code>x</code>, or an iterator to one-past the end of the range if <code>x</code> is not found.</p>
19,216,076
Oracle SQL comparing dates
<pre><code>SQL&gt; select * from porder ; OID BILL ODATE ------ ---------- --------- 10 200 06-OCT-13 4 39878 05-OCT-13 5 430000 05-OCT-13 11 427 06-OCT-13 12 700 06-OCT-13 14 11000 06-OCT-13 15 35608 06-OCT-13 13 14985 06-OCT-13 8 33000 06-OCT-13 9 600 06-OCT-13 16 200 06-OCT-13 OID BILL ODATE ------ ---------- --------- 1 200 04-OCT-13 2 35490 04-OCT-13 3 1060 04-OCT-13 6 595 05-OCT-13 7 799 05-OCT-13 16 rows selected. SQL&gt; select * from porder where odate='04-Oct-2013'; no rows selected </code></pre> <p>please someone help...why isn't the query working..??</p>
19,216,260
1
1
null
2013-10-07 02:01:26.303 UTC
2
2013-10-07 04:35:05.95 UTC
2013-10-07 04:35:05.95 UTC
null
13,302
null
2,806,673
null
1
2
sql|oracle
69,831
<p>In Oracle, a <code>DATE</code> always has a time component. Your client may or may not display the time component, but it is still there when you try to do an equality comparison. You also always want to compare dates with dates rather than strings which use the current session's <code>NLS_DATE_FORMAT</code> for doing implicit conversions thus making them rather fragile. THat will involve either ANSI date literals or explicit <code>to_date</code> calls</p> <p>You can use the <code>TRUNC</code> function to truncate the <code>DATE</code> to midnight</p> <pre><code>SELECT * FROM porder WHERE trunc(odate) = date '2013-10-04' </code></pre> <p>Or you can do a range comparison (which will be more efficient if you can benefit from an index on <code>odate</code>)</p> <pre><code>SELECT * FROM porder WHERE odate &gt;= to_date( '04-Oct-2013', 'DD-Mon-YYYY' ) AND odate &lt; to_date( '05-Oct-2013', 'DD-Mon-YYYY' ); </code></pre>
18,917,871
How to compare Timestamp in where clause
<p>I have a table with timestamp column i want to get the values where the timestamp in specific month (for example where the timpestamp between 1 september and 30 septemper) taking in considration if the month is 31 day. I use this query:</p> <pre><code>SELECT users.username, users.id, count(tahminler.tahmin)as tahmins_no FROM users LEFT JOIN tahminler ON users.id = tahminler.user_id GROUP BY users.id having count(tahminler.tahmin) &gt; 0 </code></pre> <p>Can i add <code>where timestamp IN(dates_array)</code>??</p> <p>date_array will be the dates of the whole month?? </p>
18,917,907
3
1
null
2013-09-20 13:20:03.033 UTC
3
2013-09-20 14:18:26.923 UTC
2013-09-20 13:35:43.213 UTC
null
592,898
null
2,451,817
null
1
6
mysql|sql|timestamp|where-clause
60,113
<pre> SELECT users.username, users.id, count(tahminler.tahmin)as tahmins_no FROM users LEFT JOIN tahminler ON users.id = tahminler.user_id <b>where year(timestamp) = 2013 and month(timestamp) = 9</b> GROUP BY users.id having count(tahminler.tahmin) > 0 </pre> <p>To make it work with indexes you can do </p> <pre><code>SELECT users.username, users.id, count(tahminler.tahmin)as tahmins_no FROM users LEFT JOIN tahminler ON users.id = tahminler.user_id where timestamp &gt;= '2013-09-01' and timestamp &lt; '2013-10-01' GROUP BY users.id having count(tahminler.tahmin) &gt; 0 </code></pre>
17,766,405
Android VpnService to capture packets won't capture packets
<p>I been searching for my answer for a couple of hours now and I can't figure it out. Please help.</p> <p>What I want to do is to use the VpnService in Android to grab network packets like the application <a href="https://play.google.com/store/apps/details?id=jp.co.taosoftware.android.packetcapture&amp;hl=en" rel="noreferrer">tPacketCapture</a></p> <p>I started by using the ToyVpn sample code from google and modifying it so I don't send the data to a server. However, I'm not sure if this is correct.</p> <p>My configure method uses the wlan ip address for binder.addAddress() before calling establish(). I am using a nexus 7 and I used "adb shell netcfg | grep wlan0" to get the address:</p> <p>wlan0 UP 192.168.0.6/24 0x00001043 10:bf:48:bf:5f:9d</p> <p>And add it in my method:</p> <pre><code> private void configure() throws Exception { // If the old interface has exactly the same parameters, use it! if (mInterface != null) { Log.i(TAG, "Using the previous interface"); return; } // Configure a builder while parsing the parameters. Builder builder = new Builder(); builder.setMtu(1500); builder.addAddress("192.168.0.6", 24); try { mInterface.close(); } catch (Exception e) { // ignore } mInterface = builder.establish(); } </code></pre> <p>After calling this, I call the run method which I modified to pass a String instead of a InetSocketAddress and this is not important because I am not using it anywhere:</p> <pre><code> private void run(String run) throws Exception { configure(); FileInputStream in = new FileInputStream(mInterface.getFileDescriptor()); // Allocate the buffer for a single packet. ByteBuffer packet = ByteBuffer.allocate(32767); // We use a timer to determine the status of the tunnel. It // works on both sides. A positive value means sending, and // any other means receiving. We start with receiving. int timer = 0; // We keep forwarding packets till something goes wrong. while (true) { // Assume that we did not make any progress in this iteration. boolean idle = true; // Read the outgoing packet from the input stream. int length = in.read(packet.array()); if (length &gt; 0) { Log.i(TAG,"************new packet"); while (packet.hasRemaining()) { Log.i(TAG,""+packet.get()); //System.out.print((char) packet.get()); } // Write the outgoing packet to the tunnel. packet.limit(length); // tunnel.write(packet); packet.clear(); // There might be more outgoing packets. idle = false; // If we were receiving, switch to sending. if (timer &lt; 1) { timer = 1; } } } } </code></pre> <p>When I do adb logcat, nothing is happening. Am I going about this correctly? I feel like I am missing something.</p> <p>Thank you!</p> <p>EDIT: </p> <p>From the logs I see the following lines:</p> <pre><code>I/ActivityManager( 460): START u0 {act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=com.example.android.toyvpn/.ToyVpnClient} from pid 10247 I/ActivityManager( 460): Start proc com.example.android.toyvpn for activity com.example.android.toyvpn/.ToyVpnClient: pid=10287 uid=10122 gids={50122, 3003, 1028} I/ActivityManager( 460): Displayed com.example.android.toyvpn/.ToyVpnClient: +1s144ms I/Vpn ( 460): Switched from [Legacy VPN] to com.example.android.toyvpn D/Vpn ( 460): setting state=IDLE, reason=prepare I/ToyVpnService(10287): running vpnService D/Vpn ( 460): setting state=CONNECTING, reason=establish D/VpnJni ( 460): Address added on tun0: 192.168.0.6/24 I/Vpn ( 460): Established by com.example.android.toyvpn.ToyVpnService on tun0 W/ContextImpl( 460): Calling a method in the system process without a qualified user: android.app.ContextImpl.bindService:1406 com.android.server.connectivity.Vpn.establish:289 com.android.server.ConnectivityService.establishVpn:3263 android.net.IConnectivityManager$Stub.onTransact:504 android.os.Binder.execTransact:351 D/Vpn ( 460): setting state=AUTHENTICATING, reason=establish </code></pre> <p>So it seems to be connecting.</p> <p>Full source:</p> <pre><code>public class ToyVpnService extends VpnService implements Handler.Callback, Runnable { private static final String TAG = "ToyVpnService"; private Handler mHandler; private Thread mThread; private ParcelFileDescriptor mInterface; @Override public int onStartCommand(Intent intent, int flags, int startId) { // The handler is only used to show messages. if (mHandler == null) { mHandler = new Handler(this); } // Stop the previous session by interrupting the thread. if (mThread != null) { mThread.interrupt(); } // Start a new session by creating a new thread. mThread = new Thread(this, "ToyVpnThread"); mThread.start(); return START_STICKY; } @Override public void onDestroy() { if (mThread != null) { mThread.interrupt(); } } @Override public boolean handleMessage(Message message) { if (message != null) { Toast.makeText(this, message.what, Toast.LENGTH_SHORT).show(); } return true; } @Override public synchronized void run() { Log.i(TAG,"running vpnService"); try { runVpnConnection(); } catch (Exception e) { e.printStackTrace(); //Log.e(TAG, "Got " + e.toString()); } finally { try { mInterface.close(); } catch (Exception e) { // ignore } mInterface = null; mHandler.sendEmptyMessage(R.string.disconnected); Log.i(TAG, "Exiting"); } } private boolean runVpnConnection() throws Exception { configure(); FileInputStream in = new FileInputStream(mInterface.getFileDescriptor()); // Allocate the buffer for a single packet. ByteBuffer packet = ByteBuffer.allocate(32767); // We keep forwarding packets till something goes wrong. while (true) { // Assume that we did not make any progress in this iteration. boolean idle = true; // Read the outgoing packet from the input stream. int length = in.read(packet.array()); if (length &gt; 0) { Log.i(TAG,"************new packet"); System.exit(-1); while (packet.hasRemaining()) { Log.i(TAG,""+packet.get()); //System.out.print((char) packet.get()); } packet.limit(length); // tunnel.write(packet); packet.clear(); // There might be more outgoing packets. idle = false; } Thread.sleep(50); } } public String getLocalIpAddress() { try { for (Enumeration&lt;NetworkInterface&gt; en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) { NetworkInterface intf = en.nextElement(); for (Enumeration&lt;InetAddress&gt; enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) { InetAddress inetAddress = enumIpAddr.nextElement(); Log.i(TAG,"****** INET ADDRESS ******"); Log.i(TAG,"address: "+inetAddress.getHostAddress()); Log.i(TAG,"hostname: "+inetAddress.getHostName()); Log.i(TAG,"address.toString(): "+inetAddress.getHostAddress().toString()); if (!inetAddress.isLoopbackAddress()) { //IPAddresses.setText(inetAddress.getHostAddress().toString()); Log.i(TAG,"IS NOT LOOPBACK ADDRESS: "+inetAddress.getHostAddress().toString()); return inetAddress.getHostAddress().toString(); } else{ Log.i(TAG,"It is a loopback address"); } } } } catch (SocketException ex) { String LOG_TAG = null; Log.e(LOG_TAG, ex.toString()); } return null; } private void configure() throws Exception { // If the old interface has exactly the same parameters, use it! if (mInterface != null) { Log.i(TAG, "Using the previous interface"); return; } // Configure a builder while parsing the parameters. Builder builder = new Builder(); builder.setMtu(1500); builder.addAddress("192.168.0.6", 24); try { mInterface.close(); } catch (Exception e) { // ignore } mInterface = builder.establish(); } } </code></pre>
17,820,461
2
6
null
2013-07-20 20:29:24.737 UTC
26
2015-10-27 09:32:10.197 UTC
2015-09-20 21:53:54.993 UTC
null
427,328
null
983,464
null
1
34
android|capture|packet
20,568
<p>Ok, it was not easy at all but I figured out how to capture packets. Since I am not extremely familiar with networking (but this new job is requesting that I am) I had difficulty with setting everything correctly. Basically after setting the right route in the VpnService.builder I got to receiving packets correctly.</p> <p>So:</p> <pre><code>builder.addAddress("192.168.0.6", 24); // was wrong, you need to put an internal IP (10.0.2.0 for example) </code></pre> <p>and </p> <pre><code>builder.addRoute("0.0.0.0", 0); // needs to be this. </code></pre> <p>you don't need to set up a DnsServer through builder.addDnsServer() to make it work. Hope this helps anyone!</p>
35,722,904
Saving the API Key in gradle.properties
<p>I am new to android and working on a project where I see that the API key that I got is saved in <code>gradle.properties</code> as :</p> <p><code>MyOpenWeatherMapApiKey="1c3ae96f93a0094e8a7chsjdgfid04aed3f10"</code></p> <p>And then in <code>build.gradle(module:app)</code> I am adding the following lines : </p> <pre><code>buildTypes.each { it.buildConfigField 'String', 'OPEN_WEATHER_MAP_API_KEY', MyOpenWeatherMapApiKey } </code></pre> <p>So, in my main program I am accessing the data using this api whose URL is got by this piece of code :</p> <pre><code>final String FORECAST_BASE_URL = "http://api.openweathermap.org/data/2.5/forecast/daily?"; final String QUERY_PARAM = "q"; final String FORMAT_PARAM = "mode"; final String UNITS_PARAM = "units"; final String DAYS_PARAM = "cnt"; final String APPID_PARAM = "APPID"; Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon() .appendQueryParameter(QUERY_PARAM, params[0]) .appendQueryParameter(FORMAT_PARAM, format) .appendQueryParameter(UNITS_PARAM, units) .appendQueryParameter(DAYS_PARAM, Integer.toString(numDays)) .appendQueryParameter(APPID_PARAM, BuildConfig.OPEN_WEATHER_MAP_API_KEY) .build(); URL url = new URL(builtUri.toString()); </code></pre> <p>So, my question is that why taking all the tension of doing changes to store the appid in the gradle part. Can't we access directly in the main program only ?</p> <p>And the second part of my question is what is actually happening in the gradle part especially with the <code>buildTypes.each{}</code> block ?</p>
35,723,310
3
1
null
2016-03-01 12:25:25.93 UTC
19
2022-07-02 22:44:01.17 UTC
2016-03-01 13:02:08.73 UTC
null
5,624,602
null
6,366,458
null
1
38
android|api
30,307
<ol> <li>The idea of this indirection is to allow you to store API key in files that are not uploaded to the version control: <code>gradle.properties</code> is a local file and should not be stored under the version control, and <code>BuildConfig</code> is a generated class, so it will only be created at build time. It's definitely easier to store the API key somewhere as a plain String, but then you'll have to commit it to the repo.</li> <li>During build time, Gradle will generate the <code>BuildConfig</code> file to store some build-related constants. You can use <code>buildConfigField</code> command to instruct Gradle to add custom fields into <code>BuildConfig</code>. After the project is built, you can reference these constants inside your source code.</li> </ol>
3,817,478
Setting up Git Server on Windows With git-http-backend.exe
<p>I am in the process of setting up a Git server (1.7.2.3) on a WS 2008 machine using Apache and git-http-backend.exe. I have been following a good tut <a href="http://www.jeremyskinner.co.uk/2010/07/31/hosting-a-git-server-under-apache-on-windows/" rel="noreferrer">here</a>. I have the GUI working, I can annoymously clone and if I put the following in the config of a repo I can annoymously push:</p> <pre><code>[http] receivepack = true </code></pre> <p>I have added the following to the httpd.conf file:</p> <pre><code>SetEnv GIT_PROJECT_ROOT C:/GIT/Repositories SetEnv GIT_HTTP_EXPORT_ALL ScriptAliasMatch \ "(?x)^/(.*/(HEAD | \ info/refs | \ objects/(info/[^/]+ | \ [0-9a-f]{2}/[0-9a-f]{38} | \ pack/pack-[0-9a-f]{40}\.(pack|idx)) | \ git-(upload|receive)-pack))$" \ "C:/Program Files (x86)/git/libexec/git-core/git-http-backend.exe/$1" &lt;Directory /&gt; Allow from all &lt;/Directory&gt; &lt;LocationMatch "^/git/.*/git-receive-pack$"&gt; AuthType Basic AuthName "Git Access" AuthUserFile C:/GIT/ApacheConfig/users AuthGroupFile C:/GIT/ApacheConfig/groups Require group repogeneral &lt;/LocationMatch&gt; </code></pre> <p>When I add the "LocationMatch" I can still clone annoymously or by specifying a name in the URL, git clone <a href="http://[email protected]" rel="noreferrer">http://[email protected]</a></p> <p>It will prompt for a password and clone.</p> <p>but when I try to push back to the repo I get the following:</p> <p>error: Cannot access URL <a href="http://[email protected]/newtestrepo.git/" rel="noreferrer">http://[email protected]/newtestrepo.git/</a>, return code 22 fatal: git-http-push failed</p> <p>I have been looking at the <a href="http://www.kernel.org/pub/software/scm/git/docs/git-http-backend.html" rel="noreferrer">http-backend.exe man page</a> for examples but can not get them to work.</p> <p>here is my groups file, (this is just testing out examples so nothing that would be used in prod):</p> <pre><code>admin: jon steve admin webview: jon steve web repogeneral: jon steve testrepo: jon admin testrepo2: jon steve web </code></pre> <p>here is the users file:</p> <pre><code>jon:$apr1$kEKVExYx$guIF9oYV8buGhFLZr16XN0 steve:$apr1$jvgjF9nv$PvWsHH.cSOBN5ymk6NT1B0 admin:$apr1$vzXgDskN$oszCei3tkHNUgtLj2HkHF/ web:$apr1$wS0do7hb$VA9tsc9c9LwY5PcjfhdwK0 </code></pre> <p>I know the username jon works as if I put the directory requirement on the gui section I can login with the username jon no problem, (points at the same user and group files as the locationmatch does).</p> <p>I am not sure what configuration I have missed off at this point, (assuming its a configuration issue).</p> <p>Any advice on getting over this last hurdle would be fantastic.</p> <p><strong>EDIT</strong></p> <p>I have been playing some more and here is the information I have:</p> <p>if I clone a repo with:</p> <pre><code>git clone http://[email protected]/remotetest.git </code></pre> <p>I can get the repository out, but when I try and push back with:</p> <p>git push origin master</p> <p>I get asked for my password, I enter it, then it asks for it again, then I get the following error:</p> <p>C:\temp\remotetest\remotetest>git push origin master Password: Password: error: Cannot access URL <a href="http://[email protected]/remotetest.git/" rel="noreferrer">http://[email protected]/remotetest.git/</a>, return code 22 fatal: git-http-push failed</p> <p>In my Apache access.log I get the following:</p> <pre><code>192.168.1.2 - - [29/Sep/2010:21:58:19 +0100] "GET /remotetest.git/info/refs?service=git-upload-pack HTTP/1.1" 200 38 192.168.1.2 - - [29/Sep/2010:21:58:51 +0100] "GET /remotetest.git/info/refs?service=git-receive-pack HTTP/1.1" 403 - 192.168.1.2 - - [29/Sep/2010:21:58:51 +0100] "GET /remotetest.git/info/refs HTTP/1.1" 200 - 192.168.1.2 - - [29/Sep/2010:21:58:51 +0100] "GET /remotetest.git/HEAD HTTP/1.1" 200 23 </code></pre> <p>Interestingly when I clone with the username in the URL it doesn't matter what password I put in, it will still work. I am assuming this is because I should be able to pull anonymously. Not sure why it asks for a password at all at that point.</p> <p>I also see this in the logs error:</p> <pre><code>[Wed Sep 29 22:33:00 2010] [error] [client 192.168.1.2] client denied by server configuration: C:/Program Files (x86)/Git/libexec/git-core/git-http-backend.exe [Wed Sep 29 22:33:00 2010] [error] [client 192.168.1.2] client denied by server configuration: C:/Program Files (x86)/Git/libexec/git-core/git-http-backend.exe </code></pre> <p><strong>EDIT 2</strong></p> <p>I tried recreating the password file by doing:</p> <pre><code>htpasswd -c -m C:/git/apacheconfig/users jon </code></pre> <p>but this didn't help.</p> <p><strong>EDIT 3</strong></p> <p>the PHP config in httpd.conf where it uses the same users file for basic auth:</p> <pre><code>&lt;Directory "C:/Program Files (x86)/Apache Software Foundation/Apache2.2/htdocs"&gt; AuthName "GitUsers" AuthType Basic AuthUserFile C:/GIT/ApacheConfig/users AuthGroupFile C:/GIT/ApacheConfig/groups require group webview &lt;/Directory&gt; </code></pre> <p><strong>EDIT 4</strong></p> <p>OK so I can get to cloning and pushing in annoymous mode happily, but authentication fails for the push.</p> <pre><code>C:\temp\test2\temp\test&gt;git push origin master Password: Password: error: Cannot access URL http://[email protected]:8000/repositories/test.git/, return code 22 fatal: git-http-push failed </code></pre> <p>I changed the httpd.conf to use the following:</p> <pre><code>&lt;VirtualHost *:80&gt; SetEnv GIT_PROJECT_ROOT "C:/Program Files (x86)/Apache Software Foundation/Apache2.2/htdocs/repositories" SetEnv GIT_HTTP_EXPORT_ALL &lt;Directory "C:/Program Files (x86)/Apache Software Foundation/Apache2.2/htdocs/repositories"&gt; Options Indexes FollowSymLinks MultiViews Includes ExecCGI AllowOverride None Order allow,deny Allow from all &lt;/Directory&gt; &lt;LocationMatch "^/repositories/.*/git-receive-pack$"&gt; AuthType Basic AuthName "Git Access" AuthUserFile "C:/Program Files (x86)/Apache Software Foundation/Apache2.2/htdocs/repositories/.htpasswd" Require valid-user &lt;/LocationMatch&gt; ScriptAliasMatch \ "(?x)^/repositories/(.*/(HEAD | \ info/refs | \ objects/(info/[^/]+ | \ [0-9a-f]{2}/[0-9a-f]{38} | \ pack/pack-[0-9a-f]{40}\.(pack|idx)) | \ git-(upload|receive)-pack))$" \ "C:/Program Files (x86)/Git/libexec/git-core/git-http-backend/$1" ErrorLog C:/GIT/error_log CustomLog C:/GIT/access_log combined &lt;/VirtualHost&gt; </code></pre> <p>Interestingly, when I created a new repo (git init --bare newrepo.git) It didn't create a info/refs file. I had to do the "git update-server-info" command to create that.</p> <p>The Apache Access logs have something interesting that could be a clue:</p> <pre><code>192.168.10.97 - - [05/Oct/2010:22:48:26 +0100] "GET /repositories/test.git/info/refs?service=git-receive-pack HTTP/1.1" 200 - 192.168.10.97 - - [05/Oct/2010:22:48:26 +0100] "GET /repositories/test.git/HEAD HTTP/1.1" 200 23 192.168.10.97 - - [05/Oct/2010:22:48:28 +0100] "PROPFIND /repositories/test.git/ HTTP/1.1" 405 248 </code></pre> <p>That is when I was trying to "push" back to the repo, but they are GET commands and no POST. not sure what the PROPFIND is, not found much info on that yet. I think, (reading around), there might be some sort of rewrite going on, that is changing the POST to a GET and killing it, or something. I am out of my depth at this point though.</p> <p>Thanks</p>
3,982,493
1
4
null
2010-09-28 22:28:31.06 UTC
17
2020-03-28 07:46:54.95 UTC
2017-02-11 02:35:56.13 UTC
null
1,190,388
null
6,486
null
1
23
git|apache2|git-http-backend
27,443
<p>OK, so hell has frozen over and I have finally got this working!</p> <p>I believe there were two things that were fundamentally wrong with my setup.</p> <p>1) The user was not getting authentication passed through, I found this helped:</p> <pre><code>SetEnv REMOTE_USER=$REDIRECT_REMOTE_USER </code></pre> <p>Secondly I couldn't get the physical "Directory" to work.</p> <pre><code>&lt;Directory "C:/GIT/Apache/repositories"&gt; Options +ExecCGI AuthType Basic AuthName intranet AuthUserFile "C:/GIT/Apache/config/users" Require valid-user &lt;/Directory&gt; </code></pre> <p>To resolve this I used locationMatch for both the pull and push. This means you have to authenticate to pull and push. If you wanted annoy pulling you can remove the "git-upload-pack" section.</p> <p>Hope this may help someone else.</p> <p>Here is my final httpd.conf file:</p> <pre><code>DocumentRoot "C:/GIT/Apache/www" &lt;Directory /&gt; Options +ExecCGI Allow from all &lt;/Directory&gt; &lt;Directory "C:/GIT/Apache/www"&gt; Allow from all &lt;/Directory&gt; &lt;Directory "C:/GIT/Apache/www/secure"&gt; AuthType Basic AuthName intranet AuthUserFile "C:/GIT/Apache/config/users" require valid-user &lt;/Directory&gt; SetEnv GIT_PROJECT_ROOT C:/GIT/Apache/repositories SetEnv GIT_HTTP_EXPORT_ALL SetEnv REMOTE_USER=$REDIRECT_REMOTE_USER ScriptAliasMatch \ "(?x)^/(.*/(HEAD | \ info/refs | \ objects/(info/[^/]+ | \ [0-9a-f]{2}/[0-9a-f]{38} | \ pack/pack-[0-9a-f]{40}\.(pack|idx)) | \ git-(upload|receive)-pack))$" \ "C:/Program Files/git/libexec/git-core/git-http-backend.exe/$1" &lt;LocationMatch "^/.*/git-receive-pack$"&gt; Options +ExecCGI AuthType Basic AuthName intranet AuthUserFile "C:/GIT/Apache/config/users" Require valid-user &lt;/LocationMatch&gt; &lt;LocationMatch "^/.*/git-upload-pack$"&gt; Options +ExecCGI AuthType Basic AuthName intranet AuthUserFile "C:/GIT/Apache/config/users" Require valid-user &lt;/LocationMatch&gt; </code></pre>
21,059,124
Is it .yaml or .yml?
<p>According to <a href="http://www.yaml.org/faq.html">yaml.org</a>, the official file extension is <code>.yaml</code>. </p> <p>Quote: </p> <blockquote> <h3>Is there an official extension for YAML files?</h3> <p>Please use ".yaml" when possible.</p> </blockquote> <p>However there seems to be a disagreement on the internet on which extension to use. If you look up <a href="https://github.com/gitlabhq/gitlabhq/tree/6-4-stable/config">examples on the web</a>, many of them use the unsanctioned <code>.yml</code> extension. </p> <p>Searching Google returns nearly 3 times as many results for the shorter one.</p> <hr> <p><img src="https://i.stack.imgur.com/PC5Gn.png" alt="enter image description here"><br> 49,100</p> <hr> <p><img src="https://i.stack.imgur.com/vqc4S.png" alt="enter image description here"><br> 15,400</p> <hr> <p>So which am I supposed to use? The proper 4 letter extension suggested by the creator, or the 3 letter extension found in the wild west of the internet? </p>
21,059,164
4
3
null
2014-01-11 06:06:02.777 UTC
56
2022-09-20 18:38:37.897 UTC
2016-04-09 16:05:15.403 UTC
null
1,626,687
null
1,626,687
null
1
484
yaml|configuration-files|app.yaml
189,075
<p>The nature and even existence of file extensions is platform-dependent (some obscure platforms don't even have them, remember) -- in other systems they're only conventional (UNIX and its ilk), while in still others they have definite semantics and in some cases specific limits on length or character content (Windows, etc.).</p> <p>Since the maintainers have asked that you use ".yaml", that's as close to an "official" ruling as you can get, but the habit of <a href="https://en.wikipedia.org/wiki/8.3_filename" rel="noreferrer">8.3</a> is hard to get out of (and, appallingly, still occasionally relevant in 2013).</p>
28,181,627
How to convert a QJsonObject to QString
<p>I have a QJsonObject data and want to convert to QString. How can I do this? Searched for help in Qt, it only can convert QJsonObject to QVariantMap...</p> <p>Thanks in advance.</p>
28,191,005
3
1
null
2015-01-27 22:59:15.173 UTC
9
2020-06-05 09:38:53.037 UTC
null
null
null
null
4,500,723
null
1
39
qt|qstring|qjsonobject
52,146
<p>Remembering when I first needed to do this, the documentation can be a bit lacking and assumes you have knowledge of other QJson classes.</p> <p>To obtain a QString of a QJsonObject, you need to use the QJsonDocument class, like this: -</p> <pre><code>QJsonObject jsonObj; // assume this has been populated with Json data QJsonDocument doc(jsonObj); QString strJson(doc.toJson(QJsonDocument::Compact)); </code></pre>
1,102,406
AVG in Sql - Float number problem
<pre><code>SELECT AVG(variable) AS Expr1, SUM(variable) AS Expr2 FROM ...... </code></pre> <p>result for AVG is 2, but it is not true, it must be 2.95. What is the problem, any idea?</p>
1,102,412
1
1
null
2009-07-09 07:48:24.86 UTC
2
2016-08-23 06:27:24.71 UTC
null
null
null
null
66,018
null
1
38
sql|average
33,201
<p>Try</p> <pre><code>Select AVG(Cast(variable as Float)), SUM(variable) From Table </code></pre>
19,569,213
Are the Font Awesome 3.2 docs still accessible?
<p>I am using Font Awesome 3.2. Font Awesome just released version 4.0. Prior to the 4.0 release I would view Font Awesome's documentation at <a href="http://fortawesome.github.io/Font-Awesome/icons/">http://fortawesome.github.io/Font-Awesome/icons/</a>. The new version has differing icon names and makes it difficult to work between the old and new documentation.</p> <p>Are the 3.2 docs still available? Can I download 3.2 docs?</p>
19,569,853
3
0
null
2013-10-24 14:48:09.723 UTC
4
2013-12-23 14:36:29.097 UTC
2013-10-24 21:49:24.747 UTC
null
61,654
null
2,808,440
null
1
29
font-awesome|font-awesome-3.2
17,417
<p>The documentation for 3.2.1 has been archived at:</p> <ul> <li><a href="http://fortawesome.github.io/Font-Awesome/3.2.1/">http://fortawesome.github.io/Font-Awesome/3.2.1/</a></li> </ul> <p>There's an article for upgrading from 3.1.2 to 4 on the Github wiki for the Font Awesome project:</p> <ul> <li><a href="https://github.com/FortAwesome/Font-Awesome/wiki/Upgrading-from-3.2.1-to-4">Upgrading from 3.2.1 to 4</a></li> </ul> <p>You can also download earlier releases from the project's <a href="http://github.com/FortAwesome/Font-Awesome/releases">Releases</a> page. The 3.2.1 release does include docs, but they must be compiled to be useful.</p> <p>Generally speaking, you can always check the Wayback Machine as a last resort, which has cached versions of some of the docs from previous releases based on date:</p> <ul> <li><a href="http://web.archive.org/web/20130929055652/http://fontawesome.io/">Cached version of FontAwesome site from 3.2.1 release</a></li> </ul>
52,580,111
How do I set the column width when using pandas.DataFrame.to_html?
<p>I have read <a href="https://pandas.pydata.org/pandas-docs/stable/style.html" rel="noreferrer">this</a>, but I am still confused about how I set the column width when using <code>pandas.DataFrame.to_html</code>.</p> <pre><code>import datetime import pandas data = {'Los Angles': {datetime.date(2018, 9, 24): 20.5, datetime.date(2018, 9, 25): 1517.1}, 'London': {datetime.date(2018, 9, 24): 0, datetime.date(2018, 9, 25): 1767.4}, 'Kansas City': {datetime.date(2018, 9, 24): 10, datetime.date(2018, 9, 25): 1.4}} df = pandas.DataFrame(data=data) html = df.to_html() </code></pre> <p>The above code results in : <a href="https://i.stack.imgur.com/6lTTx.png" rel="noreferrer"><img src="https://i.stack.imgur.com/6lTTx.png" alt="df.to_html result"></a></p> <p>How do I go about forcing the column width so that they are the same?</p>
52,580,495
4
0
null
2018-09-30 16:58:08.697 UTC
1
2022-06-23 10:38:09.003 UTC
2018-09-30 17:34:27.84 UTC
null
9,517,769
null
10,431,516
null
1
14
python|pandas
51,975
<p>Try this: </p> <pre><code>import datetime import pandas data = {'Los Angles': {datetime.date(2018, 9, 24): 20.5, datetime.date(2018, 9, 25): 1517.1}, 'London': {datetime.date(2018, 9, 24): 0, datetime.date(2018, 9, 25): 1767.4}, 'Kansas City': {datetime.date(2018, 9, 24): 10, datetime.date(2018, 9, 25): 1.4}} df = pandas.DataFrame(data=data) pandas.set_option('display.max_colwidth', 40) html = df.to_html() </code></pre>
38,420,396
How to get value of textbox in React?
<p>I just started using React.js, and I'm just not sure whether there is a special way to get the value of a textbox, returned in a component like this:</p> <pre><code>var LoginUsername = React.createClass({ render: function () { return ( &lt;input type="text" autofocus="autofocus" onChange={this.handleChange} /&gt; ) }, handleChange: function (evt) { this.setState({ value: evt.target.value.substr(0, 100) }); } }); </code></pre>
38,420,437
2
0
null
2016-07-17 10:46:46.19 UTC
2
2016-07-17 11:12:35.553 UTC
null
null
null
null
1,136,709
null
1
32
javascript|html|reactjs
98,333
<p>As described in <a href="https://facebook.github.io/react/docs/forms.html" rel="noreferrer">documentation</a> You need to use <strong>controlled input</strong>. To make an input - <strong>controlled</strong> you need to specify two props on it</p> <ol> <li><strong><code>onChange</code></strong> - function that would set component <code>state</code> to an input <code>value</code> every time input is changed</li> <li><strong><code>value</code></strong> - input value from the component <code>state</code> (<code>this.state.value</code> in example)</li> </ol> <p>Example:</p> <pre><code> getInitialState: function() { return {value: 'Hello!'}; }, handleChange: function(event) { this.setState({value: event.target.value}); }, render: function() { return ( &lt;input type="text" value={this.state.value} onChange={this.handleChange} /&gt; ); } </code></pre> <p>More specifically about textarea - <a href="https://facebook.github.io/react/docs/forms.html#why-textarea-value" rel="noreferrer">here</a></p>
38,329,201
How to add an icon to a nuget package?
<p>We are hosting our own nuget server through Teamcity. Is there any other way to add an icon to a .nuspec file other than specifying a web url (<a href="http://..." rel="noreferrer">http://...</a>.)?</p> <p>Or is there a place in Teamcity that these icons could be hosted?</p>
38,348,317
7
0
null
2016-07-12 12:40:33.217 UTC
2
2022-05-17 18:04:11.417 UTC
null
null
null
null
4,783,205
null
1
29
teamcity|nuget-package
20,801
<p>No, this is the only option using the iconUrl property - See the <a href="https://docs.nuget.org/create/nuspec-reference" rel="noreferrer">NuSpec Reference</a></p> <p>I would generally choose to host shared images like this on a CDN service rather than TeamCity - CloudFlare provide a free service.</p>
21,423,397
What is the custom function(p,a,c,k,e,d) used for?
<p>I have seen a lot of websites with some <code>function (p,a,c,k,e,d)</code> in their JavaScript code. The different websites may have different bodies of this function, but they all use the same parameter names <code>(p,a,c,k,e,d)</code>. Is it a standard or a library or something?</p> <p>Secondly, it seems that this function is supposed to be executed as soon as the page loads. Like the following snippet from a website.</p> <p>Can you help me in understanding this code? <code>eval()</code> is used to evaluate expressions like <code>2+3</code> but how is the following code passing a function to it?</p> <pre><code>try{ eval( function(p,a,c,k,e,d) { //some code goes here } }catch(err){} </code></pre>
21,423,538
3
0
null
2014-01-29 06:09:34.887 UTC
9
2022-03-09 07:44:25.61 UTC
2019-11-12 15:49:22.287 UTC
null
2,756,409
null
1,460,665
null
1
31
javascript
33,055
<p>So if you use <a href="http://matthewfl.com/unPacker.html" rel="noreferrer">http://matthewfl.com/unPacker.html</a> as I posted in the comments, it "unpacks" the code into this:</p> <pre><code>(function() { var b="some sample packed code"; function something(a) { alert(a) } something(b) } )(); </code></pre> <p>It doesn't seem to be malicious. For a soft argument on why you would use this, see <a href="https://stackoverflow.com/questions/3158869/javascript-packer-versus-minifier">javascript packer versus minifier</a>:</p> <blockquote> <p>Packed is smaller but is slower.</p> <p>And even harder to debug.</p> <p>Most of the well known frameworks and plugins are only minified. <hr /> Packer does more then just rename vars and arguments, it actually maps the source code using Base62 which then must be rebuilt on the client side via eval() in order to be usable.</p> <p>Side stepping the eval() is evil issues here, this can also create a large amount of overhead on the client during page load when you start packing larger JS libraries, like jQuery. This why only doing minify on your production JS is recommend, since if you have enough code to need to do packing or minify, you have enough code to make eval() choke the client during page load. <hr /> Minifier only removes unnecessary things like white space characters where as a Packer goes one step further and does whatever it can do to minimize the size of javascript. For example it renames variables to smaller names.</p> </blockquote>
30,079,438
How do I layout nested RecyclerViews, while remaining performant?
<p>I am trying to achieve something similar to Google Play Music's "Listen Now" layout. Every example I have found on the web is a single, simple <code>RecyclerView</code>. I am trying to achieve something much more complex. Something like </p> <p><img src="https://i.stack.imgur.com/CDuOY.png" alt="enter image description here"></p> <p>Can the whole layout (minus the toolbar) be a single <code>RecyclerView</code>, that contains two more RecyclerViews? Something like</p> <p>Ultimately, what I want to achieve is a layout like the below, and stay performant.</p> <pre><code>&lt;RecyclerView&gt; //vertical &lt;RecyclerView/&gt; //vertical &lt;RecyclerView/&gt; //horizontal &lt;LinearLayout/&gt; //horizontal &lt;/RecyclerView&gt; </code></pre>
33,096,208
2
1
null
2015-05-06 14:18:11.473 UTC
12
2022-04-04 19:02:34.187 UTC
2018-03-05 14:26:00.353 UTC
null
1,000,551
null
891,242
null
1
35
android|performance|android-layout|android-recyclerview
45,619
<p>You can't take recyclerview inside recyclerview tag. Rather in your first adapter's bindViewHolder call again recyclerview adapter like:-</p> <pre><code>InnerRecyclerviewAdapter adapter=new InnerRecyclerviewAdapter(context,urlistArray); holder.recyclerView.setAdapter(adapter); holder.recyclerView.setHasFixedSize(true); LinearLayoutManager layoutManager = new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false); recyclerView.setLayoutManager(layoutManager); </code></pre> <p><code>wrap_content</code> will also work with <strong><em>latest</em></strong> recyclerview</p> <p>for more info check out this link <a href="https://guides.codepath.com/android/Heterogenous-Layouts-inside-RecyclerView" rel="noreferrer">https://guides.codepath.com/android/Heterogenous-Layouts-inside-RecyclerView</a></p>
35,120,250
Python 3 Get and parse JSON API
<p>How would I parse a json api response with python? I currently have this:</p> <pre><code>import urllib.request import json url = 'https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty' def response(url): with urllib.request.urlopen(url) as response: return response.read() res = response(url) print(json.loads(res)) </code></pre> <p>I'm getting this error: TypeError: the JSON object must be str, not 'bytes'</p> <p>What is the pythonic way to deal with json apis?</p>
35,120,519
5
0
null
2016-01-31 22:21:12.01 UTC
12
2022-07-02 02:02:10.36 UTC
2022-07-02 02:02:10.36 UTC
null
523,612
null
4,178,623
null
1
50
python|json|api
99,557
<p>Version 1: (do a <code>pip install requests</code> before running the script)</p> <pre><code>import requests r = requests.get(url='https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty') print(r.json()) </code></pre> <p>Version 2: (do a <code>pip install wget</code> before running the script)</p> <pre><code>import wget fs = wget.download(url='https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty') with open(fs, 'r') as f: content = f.read() print(content) </code></pre>
20,823,535
How to write data into a JSON file using jquery
<p>Am making an hybrid mobile app and i need to store some of the data like for example if its a game : the high score etc .. so far am able to read data from JSON file using jquery .., but is it possible to write to JSON file ??! </p> <p>Or is there any other way to do so ?</p> <p>IDE - Eclipse ( plugin - IBM worklight studio )</p> <p>Only HTML 5 and JS and JQ can be used ! </p> <p>Thanks (: </p>
20,823,621
2
0
null
2013-12-29 08:47:40.967 UTC
7
2013-12-29 09:17:38.13 UTC
null
null
null
null
2,796,343
null
1
12
javascript|jquery|json|html
64,774
<p>You can write JSON into local storage and just use JSON.stringify (non-jQuery) to serialize a JavaScript object. You cannot write to any file using JavaScript alone. Just cookies or local (or session) storage.</p> <pre><code>var obj = { name: 'Dhayalan', score: 100 }; localStorage.setItem('gameStorage', JSON.stringify(obj)); </code></pre> <p>And to retrieve the object later, such as on page refresh or browser close/open...</p> <pre><code>var obj = JSON.parse(localStorage.getItem('gameStorage')); </code></pre>
18,964,833
Bootstrap 3: Scroll bars
<p>I am using Bootstrap 3 and have a list of subjects inside a side nav. The sidenav is long and I would like to make it that there is a scrollbar inside of the sidenav that displays 8 elements before having to scroll down.</p> <p>Here is my code below:</p> <pre><code> &lt;div class="col-xs-6 col-sm-3 sidebar-offcanvas" id="sidebar" role="navigation" style="float:left"&gt; &lt;div class="well sidebar-nav"&gt; &lt;ul class="nav"&gt; &lt;li&gt;&lt;strong&gt;Select a subject&lt;/strong&gt;&lt;/li&gt; &lt;li class="active"&gt;&lt;a href="#"&gt;Maths&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;English&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Art and Design&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Drama&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Music&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Physics&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Chemistry&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Biology&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Home economics&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Physical Education&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Computing Science&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;French&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;German&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Mandarin&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Religious Education&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Modern Studies&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Geography&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;History&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Creative computing&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Craft, Design and Technology&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt;&lt;!--/.well --&gt; &lt;/div&gt;&lt;!--/span--&gt; &lt;/div&gt;&lt;!--/row--&gt; </code></pre>
18,964,968
2
0
null
2013-09-23 16:59:01.247 UTC
11
2021-11-08 10:57:17.907 UTC
2015-12-21 21:22:40.83 UTC
null
37,966
null
2,697,493
null
1
31
javascript|html|twitter-bootstrap|twitter-bootstrap-3
106,770
<p>You need to use overflow option like below:</p> <pre><code>.nav{ max-height: 300px; overflow-y: scroll; } </code></pre> <p>Change the height according to amount of items you need to show</p>
24,337,413
Where to put `implicit none` in Fortran
<p>Do I need to put <code>implicit none</code> inside every function and subroutine?</p> <p>Or is it enough to put it at the beginning of the module containing these functions and subroutines?</p> <p>Or is it enough to put it at the beginning of the program that is using these modules?</p> <p>From observation of other's working code, <code>implicit none</code> is included in all these places. I am not sure if this is done redundantly because removing <code>implicit none</code> from subroutines still compiled and produced the same output.</p> <p>By the way, I am using <code>gfortran fortran 90</code>.</p>
24,337,734
4
0
null
2014-06-21 01:21:38.377 UTC
11
2021-03-19 17:27:54.327 UTC
2015-07-29 18:12:38.763 UTC
null
3,157,076
null
3,678,068
null
1
36
fortran|fortran90|gfortran
18,751
<p>The <code>implicit</code> statement (including <code>implicit none</code>) applies to a <em>scoping unit</em>. Such a thing is defined as</p> <blockquote> <p>BLOCK construct, derived-type definition, interface body, program unit, or subprogram, excluding all nested scoping units in it</p> </blockquote> <p>This &quot;excluding all nested scoping units in it&quot; suggests that it may be necessary/desirable to have <code>implicit none</code> in each function and subroutine (collectively, procedures) defined in a module. However, inside procedures contained within a module there is a default mapping based on the <em>host</em> scoping unit. So, with <code>implicit none</code> in the module it isn't necessary to have that in contained procedures.</p> <p>This host scoping unit rule applies equally to internal programs. This means that <code>implicit none</code> in the main program covers all procedures contained in it; and that the same applies for internal programs of module procedures. Block constructs see this also, and the <code>implicit</code> statement isn't even allowed within one of these.</p> <p>However, external functions/subroutines will not inherit implicit behaviour from a program or module, and modules don't inherit it from programs/other modules which <code>use</code> them. This clearly makes sense as the implicit typing must be known at compile time and be well defined regardless of their ultimate use.</p> <p>Further, one cannot apply implicit rules from one program unit to a module it uses, such as in:</p> <pre><code>implicit none use somemodule end program </code></pre> <p>An <code>implicit</code> statement must follow all <code>use</code> statements.</p> <p>Equally, a submodule is a program unit in itself, distinct from its ancestors. A module or submodule is a <em>parent</em>, not a <em>host</em>, of a submodule which extends it: the host scoping unit rule doesn't apply and the submodule doesn't inherit the mapping rules from its parent. Without an <code>implicit</code> statement in the submodule's scope the default rules will apply there.</p> <p>The host scoping unit rule notably doesn't apply to interface bodies. <a href="https://stackoverflow.com/a/24337736">IanH's answer</a> motivates that exception, but it's an important enough thing to re-stress. It has caused much confusion.</p> <pre><code>module mod implicit none interface subroutine external_sub() ! The default implicit typing rules apply here unless ! there is an implicit statement, such as implicit none. ! Those from the module aren't in force here. end subroutine end interface end module </code></pre> <p>Regarding the test of removing <code>implicit none</code> from a subroutine: if the code is valid with <code>implicit none</code> then it must be valid and identical without that statement. All entities must be explicitly declared in the former case, so no implicit rules would be applied in the latter.</p>
30,354,258
Android google maps marker disable navigation option
<p>Im creating an app where users need to walk to a point on a map. But they need to find a route to the point by them selves. Ive created a map with markers but by default if a user clicks on the marker a "start navigation" and "view in google maps" option is shown. Is it possible to disable these options ?</p> <p><img src="https://i.stack.imgur.com/iNPGr.png" alt="The options that are shown on marker click"></p> <p>The options that are shown on marker click</p>
30,354,428
4
0
null
2015-05-20 15:35:57.28 UTC
14
2019-04-09 14:46:32.71 UTC
2018-01-02 14:42:57.04 UTC
null
1,667,868
null
1,667,868
null
1
74
android|google-maps-markers|google-maps-android-api-2|android-maps-v2
17,729
<p>This thing is called <a href="https://developers.google.com/maps/documentation/android/interactivity#map_toolbar" rel="noreferrer">Map Toolbar</a>. You can disable it by calling <a href="https://developer.android.com/reference/com/google/android/gms/maps/UiSettings.html#setMapToolbarEnabled(boolean)" rel="noreferrer"> UiSettings.setMapToolbarEnabled(false)</a>:</p> <pre><code>GoogleMap map; ....... //init map map.getUiSettings().setMapToolbarEnabled(false); </code></pre>
26,706,846
Apache virtual host without domain name
<p>I have a VPS with apache2 installed and I would like to access some PHP projects without a domain name just with the IP address. For example:</p> <pre><code>http://162.243.93.216/projecta/index.php http://162.243.93.216/projectb/index.php </code></pre> <p>I have other projects with domain like example.com, in my directory /var/www/</p> <pre><code>/html/ info.php /projecta/ /projectb/ /example/ </code></pre> <p>When I go to </p> <pre><code>http://162.243.93.216/info.php then /var/www/html/info.php is opened. </code></pre> <p>My file <strong>000-default.conf</strong></p> <pre><code>&lt;VirtualHost *:80&gt; ServerAdmin webmaster@localhost DocumentRoot /var/www/html &lt;Directory /var/www/&gt; Options Indexes FollowSymLinks MultiViews AllowOverride All Order allow,deny allow from all &lt;/Directory&gt; ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined &lt;/VirtualHost&gt; </code></pre>
26,709,098
3
0
null
2014-11-03 02:14:32.23 UTC
10
2018-01-28 20:52:27.747 UTC
2014-11-03 03:42:04.487 UTC
null
2,837,356
null
2,837,356
null
1
23
php|apache|dns|virtualhost
41,042
<pre><code>" http://162.243.93.216/info.php then /var/www/html/info.php is opened " </code></pre> <p>I am assuming this already works (If not, uncomment the <code>ServerAlias</code> line shown in the conf below)</p> <p>You now want to map</p> <p><code>http://162.243.93.216/projecta/</code> to <code>/var/www/projecta</code><br> <code>http://162.243.93.216/projectb/</code> to <code>/var/www/projectb</code></p> <p>For this you need to use the Apache <strong><code>Alias</code></strong> directive.</p> <h3>Update your <code>000-default.conf</code> file to:</h3> <pre><code>&lt;VirtualHost *:80&gt; # ServerAlias 162.243.93.216 ServerAdmin webmaster@localhost DocumentRoot /var/www/html Alias /projecta /var/www/projecta Alias /projectb /var/www/projectb &lt;Directory /var/www/&gt; Options Indexes FollowSymLinks MultiViews AllowOverride All Order allow,deny allow from all &lt;/Directory&gt; ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined &lt;/VirtualHost&gt; </code></pre>
44,710,877
How do I add days to a Chrono UTC?
<p>I am trying to find the preferred way to add days to a Chrono <code>UTC</code>. I want to add 137 days to the current time: </p> <pre><code>let dt = UTC::now(); </code></pre>
44,710,935
2
0
null
2017-06-22 23:33:47.977 UTC
1
2021-06-16 14:51:45.27 UTC
2017-06-23 00:24:37.747 UTC
null
155,423
null
26,685
null
1
45
rust|rust-chrono
15,788
<p>Just use <a href="https://docs.rs/chrono/0.4.19/chrono/struct.Duration.html" rel="noreferrer"><code>Duration</code></a> and appropriate <a href="https://doc.rust-lang.org/std/ops/index.html" rel="noreferrer">operator</a>:</p> <pre class="lang-rust prettyprint-override"><code>use chrono::{Duration, Utc}; fn main() { let dt = Utc::now() + Duration::days(137); println!(&quot;today date + 137 days {}&quot;, dt); } </code></pre> <p><a href="https://play.integer32.com/?version=stable&amp;mode=debug&amp;edition=2018&amp;gist=d6e36d1660566d1b60487b681c8ba199" rel="noreferrer">Test on playground</a>.</p>
41,829,146
"left side of comma operator.." error in html content of render
<p>Its straightforward process;</p> <p>Here is the origin render method I want it to be(I want my table outside of div): <a href="https://i.stack.imgur.com/P8S6B.png" rel="noreferrer"><img src="https://i.stack.imgur.com/P8S6B.png" alt="enter image description here"></a></p> <p>but jsx compiler dont allow it for some reason? </p> <p>but if i move the table inside of div element; everything looks ok. <a href="https://i.stack.imgur.com/Gj0Is.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Gj0Is.png" alt="enter image description here"></a></p> <p>so only diff is place of table. <strong>why jsx interfere this process ? why its necessary ?</strong></p>
41,829,228
4
0
null
2017-01-24 13:13:22.377 UTC
3
2020-06-14 04:12:13.983 UTC
null
null
null
null
2,959,783
null
1
60
reactjs|react-native
58,501
<p>In <code>JSX</code>, we can return only one <code>html</code> element from <code>return</code>, can't return multiple elements, if you want to return multiple elements then wrap all the html code in a <code>div</code> or by any other wrapper component. </p> <p>Same thing is happening in your 1st case, you are returning 2 elements, one <code>div</code> and one <code>table</code>. when you are wrapping them in one <code>div</code> everything is working properly.</p> <p>Same rule you have to follow for <code>conditional rendering</code> of components. </p> <p>Example:</p> <p><strong>Correct:</strong> </p> <pre><code>{ 1==1 /* some condition */ ? &lt;div&gt; True &lt;/div&gt; : &lt;div&gt; False &lt;/div&gt; } </code></pre> <p><strong>Wrong:</strong> </p> <pre><code>{ 1==1 /* some condition */ ? &lt;div&gt; True 1 &lt;/div&gt; &lt;div&gt; True 2 &lt;/div&gt; : &lt;div&gt; False 1 &lt;/div&gt; &lt;div&gt; False 2 &lt;/div&gt; } </code></pre>
39,084,491
Unable to find a @SpringBootConfiguration when doing a JpaTest
<p>I'm new to frameworks (just passed the class) and this is my first time using Spring Boot.</p> <p>I'm trying to run a simple Junit test to see if my CrudRepositories are indeed working.</p> <p>The error I keep getting is:</p> <blockquote> <p>Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test java.lang.IllegalStateException</p> </blockquote> <p>Doesn't Spring Boot configure itself?</p> <p>My Test Class:</p> <pre><code>@RunWith(SpringRunner.class) @DataJpaTest @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) public class JpaTest { @Autowired private AccountRepository repository; @After public void clearDb(){ repository.deleteAll(); } @Test public void createAccount(){ long id = 12; Account u = new Account(id,"Tim Viz"); repository.save(u); assertEquals(repository.findOne(id),u); } @Test public void findAccountByUsername(){ long id = 12; String username = "Tim Viz"; Account u = new Account(id,username); repository.save(u); assertEquals(repository.findByUsername(username),u); } </code></pre> <p>My Spring Boot application starter:</p> <pre><code>@SpringBootApplication @EnableJpaRepositories(basePackages = {"domain.repositories"}) @ComponentScan(basePackages = {"controllers","domain"}) @EnableWebMvc @PropertySources(value {@PropertySource("classpath:application.properties")}) @EntityScan(basePackages={"domain"}) public class Application extends SpringBootServletInitializer { public static void main(String[] args) { ApplicationContext ctx = SpringApplication.run(Application.class, args); } } </code></pre> <p>My Repository:</p> <pre><code>public interface AccountRepository extends CrudRepository&lt;Account,Long&gt; { public Account findByUsername(String username); } } </code></pre>
39,084,906
15
0
null
2016-08-22 16:30:02.07 UTC
39
2020-10-30 11:24:02.953 UTC
2019-08-07 09:08:14.163 UTC
null
3,345,375
null
2,295,156
null
1
226
java|spring|junit|spring-boot|spring-data
251,318
<p>Indeed, Spring Boot does set itself up for the most part. You can probably already get rid of a lot of the code you posted, especially in <code>Application</code>.</p> <p>I wish you had included the package names of all your classes, or at least the ones for <code>Application</code> and <code>JpaTest</code>. The thing about <code>@DataJpaTest</code> and a few other annotations is that they look for a <code>@SpringBootConfiguration</code> annotation in the current package, and if they cannot find it there, they traverse the package hierarchy until they find it.</p> <p>For example, if the fully qualified name for your test class was <code>com.example.test.JpaTest</code> and the one for your application was <code>com.example.Application</code>, then your test class would be able to find the <code>@SpringBootApplication</code> (and therein, the <code>@SpringBootConfiguration</code>).</p> <p>If the application resided in a different branch of the package hierarchy, however, like <code>com.example.application.Application</code>, it would <em>not</em> find it.</p> <h2>Example</h2> <p>Consider the following Maven project:</p> <pre><code>my-test-project +--pom.xml +--src +--main +--com +--example +--Application.java +--test +--com +--example +--test +--JpaTest.java </code></pre> <p>And then the following content in <code>Application.java</code>:</p> <pre><code>package com.example; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } </code></pre> <p>Followed by the contents of <code>JpaTest.java</code>:</p> <pre><code>package com.example.test; @RunWith(SpringRunner.class) @DataJpaTest public class JpaTest { @Test public void testDummy() { } } </code></pre> <p>Everything should be working. If you create a new folder inside <code>src/main/com/example</code> called <code>app</code>, and then put your <code>Application.java</code> inside it (and update the <code>package</code> declaration inside the file), running the test will give you the following error:</p> <blockquote> <p>java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test</p> </blockquote>
8,678,370
Background image repeating even with 'background-repeat: no-repeat'
<p>I can't stop the image repetition in my <code>td</code> elements. It looks very ugly. How do I solve this? I've added <code>background-repeat: no-repeat</code> code also, but it's still not working. Please don't suggest removing the <code>%</code> from the width of my <code>td</code>. </p> <p><img src="https://i.stack.imgur.com/wC5tY.png" alt="enter image description here"></p> <pre><code>&lt;table bgcolor="#d0e9ff" width= "100%"&gt; &lt;td width="9%" height="40" background="images/button.jpg" background-repeat: no-repeat&gt; &lt;div align="center" border="0"&gt;&lt;font face="arial, verdana, san-serif" size="2" &gt;&lt;a href="index.html " style="text-decoration:none"&gt; &lt;font color="#ffffff"&gt;&lt;b&gt;Home&lt;/a&gt;&lt;/font&gt;&lt;/div&gt; &lt;/td&gt; &lt;td width="9%" height="40" background="images/button.jpg" background-repeat: no-repeat&gt; &lt;div align="center"&gt;&lt;font face="arial, verdana, san-serif" size="2"&gt;&lt;a href="aboutus.html" style="text-decoration:none"&gt; &lt;font color="#ffffff"&gt;&lt;b&gt;About Us&lt;/a&gt;&lt;/font&gt;&lt;/div&gt; &lt;/td&gt; &lt;td width="9%" height="40" background="images/button.jpg" background-repeat: no-repeat&gt; &lt;div align="center"&gt;&lt;font face="arial, verdana, san-serif" size="2"&gt;&lt;a href="T&amp;C.html" style="text-decoration:none"&gt; &lt;font color="#ffffff"&gt;&lt;b&gt;Training and Certifications&lt;/a&gt;&lt;/font&gt;&lt;/div&gt; &lt;/td&gt; &lt;td width="9%" height="40" background="images/button.jpg" background-repeat: no-repeat&gt; &lt;div align="center"&gt;&lt;font face="arial, verdana, san-serif" size="2"&gt;&lt;a href="services.html" style="text-decoration:none"&gt; &lt;font color="#ffffff"&gt;&lt;b&gt;Services&lt;/a&gt;&lt;/font&gt;&lt;/div&gt; &lt;/td&gt; &lt;td width="9%" height="40" background="images/button.jpg" background-repeat: no-repeat&gt; &lt;div align="center"&gt;&lt;font face="arial, verdana, san-serif" size="2"&gt;&lt;a href="Contactus.html" style="text-decoration:none"&gt; &lt;font color="#ffffff"&gt;&lt;b&gt;Contact Us&lt;/a&gt;&lt;/font&gt;&lt;/div&gt; &lt;/td&gt; &lt;/table&gt; </code></pre>
8,678,727
5
1
null
2011-12-30 10:12:02.747 UTC
null
2017-10-10 07:11:56.787 UTC
2012-01-02 02:55:52.9 UTC
null
918,414
null
776,226
null
1
5
html|css
72,301
<p>You've got plenty of answers telling you how to fix your repeating image problem, but in case you decide to use a CSS design, here is something to get you started. This will eliminate the need for an image. You'll use a lot less HTML and it's more configurable.</p> <p>Demo: <a href="http://jsfiddle.net/ThinkingStiff/fJEJf/" rel="nofollow noreferrer">http://jsfiddle.net/ThinkingStiff/fJEJf/</a></p> <p>HTML:</p> <pre><code>&lt;ul&gt; &lt;li&gt;&lt;a class="a" href="index.html"&gt;Home&lt;/a&gt;&lt;/li&gt;&lt;!-- --&gt;&lt;li&gt;&lt;a class="a" href="aboutus.html"&gt;About Us&lt;/a&gt;&lt;/li&gt;&lt;!-- --&gt;&lt;li&gt;&lt;a class="a" href="T&amp;C.html"&gt;Training&lt;/a&gt;&lt;/li&gt;&lt;!-- --&gt;&lt;li&gt;&lt;a class="a" href="services.html"&gt;Services&lt;/a&gt;&lt;/li&gt;&lt;!-- --&gt;&lt;li&gt;&lt;a class="a" href="Contactus.html"&gt;Contact Us&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>CSS:</p> <pre class="lang-css prettyprint-override"><code>ul { background-color: #d0e9ff; margin: 0; padding: 0; white-space: nowrap; } li { display: inline-block; padding: 4px; width: 19.5%; } a { background-color: gray; border-radius: 16px; color: white; display: block; font: bold 13px arial, verdana, san-serif; height: 32px; line-height: 32px; text-align: center; text-decoration: none; } </code></pre> <p>Output:</p> <p><img src="https://i.stack.imgur.com/xA0mK.png" alt="enter image description here"></p>
8,563,473
Unbalanced calls to begin/end appearance transitions for UITabBarController
<p>I have an UITabBarController, when initial run, I want to overlay a login view controller but received error.</p> <blockquote> <p>Unbalanced calls to begin/end appearance transitions for &lt; UITabBarController: 0x863ae00 >.</p> </blockquote> <p>Below is the code. </p> <pre><code>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Override point for customization after application launch. self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease]; // Override point for customization after application launch. UIViewController *lessonVC = [[[LessonViewController alloc] initWithNibName:@"LessonViewController" bundle:nil] autorelease]; UIViewController *programVC = [[[ProgramViewController alloc] initWithNibName:@"ProgramViewController" bundle:nil] autorelease]; UIViewController *flashcardVC = [[[FlashCardViewController alloc] initWithNibName:@"FlashCardViewController" bundle:nil] autorelease]; UIViewController *moreVC = [[[MoreViewController alloc] initWithNibName:@"MoreViewController" bundle:nil] autorelease]; UINavigationController *lessonNVC = [[[UINavigationController alloc] initWithRootViewController:lessonVC] autorelease]; UINavigationController *programNVC = [[[UINavigationController alloc] initWithRootViewController:programVC] autorelease]; UINavigationController *flashcardNVC = [[[UINavigationController alloc] initWithRootViewController:flashcardVC] autorelease]; UINavigationController *moreNVC = [[[UINavigationController alloc] initWithRootViewController:moreVC] autorelease]; self.tabBarController = [[[UITabBarController alloc] init/*WithNibName:nil bundle:nil*/] autorelease]; self.tabBarController.viewControllers = [NSArray arrayWithObjects:lessonNVC, programNVC, flashcardNVC, moreNVC, nil]; self.tabBarController.selectedIndex = 0; self.window.rootViewController = self.tabBarController; [self.window makeKeyAndVisible]; if (![[ZYHttpRequest sharedRequest] userID]) { // should register or login firstly LoginViewController *loginVC = [[LoginViewController alloc] initWithNibName:@"LoginViewController" bundle:nil]; loginVC.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal; [self.tabBarController presentModalViewController:loginVC animated:YES]; ZY_SAFE_RELEASE(loginVC); } return YES; } </code></pre> <p>Anyone who can help me? Thanks in advance!</p>
8,650,092
5
1
null
2011-12-19 15:24:17.427 UTC
23
2016-05-13 18:07:18.733 UTC
2011-12-21 04:04:09.447 UTC
null
171,206
null
527,539
null
1
28
iphone|ipad|uitabbarcontroller|transitions
25,982
<p>You need to wait to present the modal view controller until the next run loop. I ended up using a block (to make things more simple) to schedule the presentation for the next run loop:</p> <p><strong>Update:</strong><br> As mentioned by Mark Amery below, just a simple <code>dispatch_async</code> works, there's no need for a timer:</p> <pre><code>dispatch_async(dispatch_get_main_queue(), ^(void){ [self.container presentModalViewController:nc animated:YES]; }); </code></pre> <hr> <pre><code>/* Present next run loop. Prevents "unbalanced VC display" warnings. */ double delayInSeconds = 0.1; dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC); dispatch_after(popTime, dispatch_get_main_queue(), ^(void){ [self.container presentModalViewController:nc animated:YES]; }); </code></pre>
19,463,904
Double border with different color
<p>With Photoshop, I can put two different border to an element with two different color. And with that, I can make many dynamic shade-effect with my elements. Even with Photoshop effects, I can manage that with Drop Shadow and Inner Shadow.</p> <p>On the Web Design concern, if I have design like the image below, how can I achieve that with CSS? Is it really possible?<br/> <img src="https://i.stack.imgur.com/vtvIz.jpg" alt="border with different color"></p> <p><strong>NOTE:</strong> I'm giving two borders to the white element: the outer border is white, and the inner border is greyish. Together, they create a dynamic look so that it feels like an inset element, and the white element is pillow embossed. So thing is a bit:</p> <pre><code>div.white{ border: 2px solid white; border: 1px solid grey; } </code></pre> <p>But you know it's a double declaration, and is invalid. So how can I manage such thing in CSS?</p> <p>And if I put <code>border-style: double</code> then you know I can't pass two different color for the singe <code>double</code> border.</p> <pre><code>div.white{ border: double white grey; } </code></pre> <p>Additionally, I'm familiar with LESS CSS Preprocessor. So if such a thing is possible using CSS Preprocessor, please let me know.</p>
19,464,014
8
1
null
2013-10-19 08:07:32.393 UTC
14
2020-06-30 21:50:36.317 UTC
2017-10-11 09:21:44.187 UTC
null
1,685,157
null
1,743,124
null
1
66
css|border|less
179,831
<p>Alternatively, you can use pseudo-elements to do so :) the advantage of the pseudo-element solution is that you can use it to space the inner border at an arbitrary distance away from the actual border, and the background will show through that space. The markup:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>body { background-image: linear-gradient(180deg, #ccc 50%, #fff 50%); background-repeat: no-repeat; height: 100vh; } .double-border { background-color: #ccc; border: 4px solid #fff; padding: 2em; width: 16em; height: 16em; position: relative; margin: 0 auto; } .double-border:before { background: none; border: 4px solid #fff; content: ""; display: block; position: absolute; top: 4px; left: 4px; right: 4px; bottom: 4px; pointer-events: none; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="double-border"&gt; &lt;!-- Content --&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>If you want borders that are consecutive to each other (no space between them), you can use multiple <code>box-shadow</code> declarations (separated by commas) to do so:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>body { background-image: linear-gradient(180deg, #ccc 50%, #fff 50%); background-repeat: no-repeat; height: 100vh; } .double-border { background-color: #ccc; border: 4px solid #fff; box-shadow: inset 0 0 0 4px #eee, inset 0 0 0 8px #ddd, inset 0 0 0 12px #ccc, inset 0 0 0 16px #bbb, inset 0 0 0 20px #aaa, inset 0 0 0 20px #999, inset 0 0 0 20px #888; /* And so on and so forth, if you want border-ception */ margin: 0 auto; padding: 3em; width: 16em; height: 16em; position: relative; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="double-border"&gt; &lt;!-- Content --&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
19,496,821
Clicking a checkbox with ng-click does not update the model
<p>Clicking on a checkbox and calling ng-click: the model is not updated before ng-click kicks in so the checkbox value is wrongly presented in the UI:</p> <p>This works in AngularJS 1.0.7 and seems broken in Angualar 1.2-RCx.</p> <pre><code>&lt;div ng-app="myApp" ng-controller="Ctrl"&gt; &lt;li ng-repeat="todo in todos"&gt; &lt;input type='checkbox' ng-click='onCompleteTodo(todo)' ng-model="todo.done"&gt; {{todo.text}} &lt;/li&gt; &lt;hr&gt; task: {{todoText}} &lt;hr&gt;&lt;h2&gt;Wrong value&lt;/h2&gt; done: {{doneAfterClick}} </code></pre> <p></p> <p>and controller:</p> <pre><code>angular.module('myApp', []) .controller('Ctrl', ['$scope', function($scope) { $scope.todos=[ {'text': "get milk", 'done': true }, {'text': "get milk2", 'done': false } ]; $scope.onCompleteTodo = function(todo) { console.log("onCompleteTodo -done: " + todo.done + " : " + todo.text); $scope.doneAfterClick=todo.done; $scope.todoText = todo.text; }; }]); </code></pre> <p>Broken Fiddle w/ Angular 1.2 RCx - <a href="http://jsfiddle.net/supercobra/ekD3r/" rel="noreferrer">http://jsfiddle.net/supercobra/ekD3r/</a></p> <p>Working fidddle w/ Angular 1.0.0 - <a href="http://jsfiddle.net/supercobra/8FQNw/" rel="noreferrer">http://jsfiddle.net/supercobra/8FQNw/</a></p>
20,143,838
10
2
null
2013-10-21 14:09:08.913 UTC
18
2016-10-24 11:04:48.077 UTC
2013-10-21 17:06:52.64 UTC
null
210,006
null
210,006
null
1
85
angularjs|checkbox
116,506
<p>How about changing</p> <pre><code>&lt;input type='checkbox' ng-click='onCompleteTodo(todo)' ng-model=&quot;todo.done&quot;&gt; </code></pre> <p>to</p> <pre><code>&lt;input type='checkbox' ng-change='onCompleteTodo(todo)' ng-model=&quot;todo.done&quot;&gt; </code></pre> <p>From <a href="http://docs.angularjs.org/api/ng.directive:ngChange" rel="noreferrer">docs</a>:</p> <blockquote> <p>Evaluate given expression when user changes the input. The expression is not evaluated when the value change is coming from the model.</p> <p>Note, this directive requires <code>ngModel</code> to be present.</p> </blockquote>
252,249
How do you run Lucene on .net?
<p>Lucene is an excellent search engine, but the .NET version is behind the official Java release (latest stable .NET release is 2.0, but the latest Java Lucene version is 2.4, which has more features).</p> <p>How do you get around this?</p>
252,254
4
1
null
2008-10-31 00:34:15.697 UTC
14
2012-03-20 12:07:30.65 UTC
2008-11-24 23:34:59.713 UTC
kurious
109
kurious
109
null
1
9
java|.net|search|indexing|lucene
3,009
<p>One way I found, which was surprised could work: Create a .NET DLL from a Java .jar file! Using <a href="http://www.ikvm.net/" rel="noreferrer">IKVM</a> you can <a href="http://www.apache.org/dyn/closer.cgi/lucene/java/" rel="noreferrer">download Lucene</a>, get the .jar file, and run:</p> <pre><code>ikvmc -target:library &lt;path-to-lucene.jar&gt; </code></pre> <p>which generates a .NET dll like this: lucene-core-2.4.0.dll</p> <p>You can then just reference this DLL from your project and you're good to go! There are some java types you will need, so also reference IKVM.OpenJDK.ClassLibrary.dll. Your code might look a bit like this:</p> <pre><code>QueryParser parser = new QueryParser("field1", analyzer); java.util.Map boosts = new java.util.HashMap(); boosts.put("field1", new java.lang.Float(1.0)); boosts.put("field2", new java.lang.Float(10.0)); MultiFieldQueryParser multiParser = new MultiFieldQueryParser (new string[] { "field1", "field2" }, analyzer, boosts); multiParser.setDefaultOperator(QueryParser.Operator.OR); Query query = multiParser.parse("ABC"); Hits hits = isearcher.search(query); </code></pre> <p>I never knew you could have Java to .NET interoperability so easily. The best part is that C# and Java is "almost" source code compatible (where Lucene examples are concerned). Just replace <code>System.Out</code> with <code>Console.Writeln</code> :).</p> <p>=======</p> <p>Update: When building libraries like the Lucene highlighter, make sure you reference the core assembly (else you'll get warnings about missing classes). So the highlighter is built like this:</p> <pre><code>ikvmc -target:library lucene-highlighter-2.4.0.jar -r:lucene-core-2.4.0.dll </code></pre>
1,080,068
how to get zend studio autocomplete with codeigniter
<p>I'm looking for a good way to get autocomplete and click-for-reference (whatever that's called) for libraries in codeigniter working in Zend Studio for Eclipse.</p> <p>for instance, if i do $this->load->library('dx_auth'); $this->dx_auth->get_user_id();</p> <p>zend studio doesn't know what it is..</p> <p>There is this sortof hacky way to do it (see below, <a href="http://codeigniter.com/forums/viewthread/115310/#583621" rel="noreferrer">source</a>), but i feel like there should be a better way of doing it..</p> <p>Anyone have any ideas?</p> <pre><code>// All of these are added so I get real auto complete // I don't have to worry about it causing any problems with deployment // as this file never gets called as I'm in PHP5 mode // Core CI libraries $config = new CI_Config(); $db = new CI_DB_active_record(); $email = new CI_Email(); $form_validation = new CI_Form_validation(); $input = new CI_Input(); $load = new CI_Loader(); $router = new CI_Router(); $session = new CI_Session(); $table = new CI_Table(); $unit = new CI_Unit_test(); $uri = new CI_URI(); </code></pre>
1,080,142
4
0
null
2009-07-03 16:36:16.81 UTC
9
2013-09-20 08:42:15.69 UTC
2010-04-29 20:57:31.643 UTC
null
111,033
null
111,033
null
1
9
php|codeigniter|autocomplete|zend-studio
10,588
<p>Add CI's library path as an include path to your project.</p> <ol> <li>In the <strong>PHP Explorer</strong>, open your project and right-click on <strong>Include Paths</strong></li> <li>Select <strong>Configure</strong> from the context menu</li> <li>Then in the include path dialog, select the <strong>Library</strong> tab</li> <li>Click <strong>Add External Folder...</strong></li> <li>Browse to a local copy of CI and choose it's library directory (wherever it keeps those class files)</li> <li>Click <strong>Done</strong></li> </ol> <p>Voila, there you go!</p> <p>I should note that you can also define include paths at the time of project creation.</p>
1,311,920
Lagging Variables in R
<p>What is the most efficient way to make a matrix of lagged variables in R for an arbitrary variable (i.e. not a regular time series)</p> <p>For example:</p> <p><strong><em>Input</em></strong>:</p> <pre><code>x &lt;- c(1,2,3,4) </code></pre> <p><strong><em>2 lags, output</em></strong>:</p> <pre><code>[1,NA, NA] [2, 1, NA] [3, 2, 1] [4, 3, 2] </code></pre>
1,313,568
4
0
null
2009-08-21 13:23:57.003 UTC
12
2015-12-24 11:58:25.87 UTC
2015-12-24 11:58:25.87 UTC
null
5,414,452
null
160,794
null
1
11
r|time-series
19,711
<p>You can achieve this using the built-in <code>embed()</code> function, where its second 'dimension' argument is equivalent to what you've called 'lag':</p> <pre><code>x &lt;- c(NA,NA,1,2,3,4) embed(x,3) ## returns [,1] [,2] [,3] [1,] 1 NA NA [2,] 2 1 NA [3,] 3 2 1 [4,] 4 3 2 </code></pre> <p><code>embed()</code> was discussed in a <a href="https://stackoverflow.com/questions/1169376/cumulative-sums-moving-averages-and-sql-group-by-equivalents-in-r/1172367#1172367">previous answer</a> by Joshua Reich. (Note that I prepended x with NAs to replicate your desired output). </p> <p>It's not particularly well-named but it is quite useful and powerful for operations involving sliding windows, such as rolling sums and moving averages.</p>
471,546
Any way to override the and operator in Python?
<p>I tried overriding <code>__and__</code>, but that is for the &amp; operator, not <em>and</em> - the one that I want. Can I override <em>and</em>?</p>
471,561
4
0
null
2009-01-23 01:36:42.417 UTC
2
2019-02-28 01:31:59.43 UTC
null
null
null
toby
5,304
null
1
39
python
11,225
<p>You cannot override the <code>and</code>, <code>or</code>, and <code>not</code> boolean operators.</p>
602,580
How can I use C++ class in Python?
<p>I have implemented a class in C++. I want to use it with Python. <strong>Please suggest step by step method and elaborate each step.</strong> Somthing like this...</p> <pre><code>class Test{ private: int n; public: Test(int k){ n=k; } void setInt(int k){ n = k; } int getInt(){ return n; } }; </code></pre> <p>Now, in Python </p> <pre><code>&gt;&gt;&gt; T1 = Test(12) &gt;&gt;&gt; T1.getInt() 12 &gt;&gt;&gt; T1.setInt(32) &gt;&gt;&gt; T1.getInt() 32 </code></pre> <p>Please suggest.How can I do this ? NOTE: I would like to know manual way to do that. I don't want any third party library dependency.</p>
602,594
4
1
null
2009-03-02 14:47:11.48 UTC
16
2022-04-24 02:45:45.627 UTC
2009-03-02 14:53:12.353 UTC
david makcenzie
58,737
david makcenzie
58,737
null
1
46
c++|python|class
40,201
<p>Look into <a href="http://www.boost.org/doc/libs/1_38_0/libs/python/doc/index.html" rel="noreferrer">Boost.Python</a>. It's a library to write python modules with C++.</p> <p>Also look into <a href="http://www.swig.org/" rel="noreferrer">SWIG</a> which can also handle modules for other scripting languages. I've used it in the past to write modules for my class and use them within python. Works great.</p> <p>You can do it manually by using the <a href="http://docs.python.org/c-api/" rel="noreferrer">Python/C API</a>, writing the interface yourself. It's pretty lowlevel, but you will gain a lot of additional knowledge of how Python works behind the scene (And you will need it when you use SWIG anyway).</p>
1,208,467
How to add items to a unordered list <ul> using jquery
<p>In my json response, I want to loop through it using $.each and then append items to a <code>&lt;ul&gt;&lt;/ul&gt;</code> element.</p> <pre><code> $.each(data, function(i, item) { // item.UserID // item.Username } </code></pre> <p>I want to add a <li>, and create a href tag that links to the users page.</p>
1,208,505
4
0
null
2009-07-30 18:31:45.15 UTC
21
2019-01-27 15:41:59.363 UTC
2010-10-14 19:40:44.103 UTC
null
41,688
null
68,183
null
1
50
jquery|json
89,538
<p>The most efficient way is to create an array and append to the dom once.</p> <p>You can make it better still by losing all the string concat from the string. Either push multiple times to the array or build the string using += and then push but it becomes a bit harder to read for some. </p> <p>Also you can wrap all the items in a parent element (in this case the ul) and append that to the container for best performance. Just push the '<code>&lt;ul&gt;'</code> and <code>'&lt;/ul&gt;'</code> before and after the each and append to a div.</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>data = [ { "userId": 1, "Username": "User_1" }, { "userId": 2, "Username": "User_2" } ]; var items = []; $.each(data, function(i, item) { items.push('&lt;li&gt;&lt;a href="yourlink?id=' + item.UserID + '"&gt;' + item.Username + '&lt;/a&gt;&lt;/li&gt;'); }); // close each() $('#yourUl').append(items.join(''));</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt; &lt;ul id="yourUl"&gt; &lt;/ul&gt;</code></pre> </div> </div> </p>
54,542,318
Using an enum as a dictionary key
<p>I'm trying to create a guaranteed lookup for a given enum. As in, there should be exactly one value in the lookup for every key of the enum. I want to guarantee this through the type system so that I won't forget to update the lookup if the enum expands. I tried this:</p> <pre><code>type EnumDictionary&lt;T, U&gt; = { [K in keyof T]: U; }; enum Direction { Up, Down, } const lookup: EnumDictionary&lt;Direction, number&gt; = { [Direction.Up]: 1, [Direction.Down]: -1, }; </code></pre> <p>But I'm getting this weird error:</p> <blockquote> <p>Type '{ [Direction.Up]: number; [Direction.Down]: number; }' is not assignable to type 'Direction'.</p> </blockquote> <p>Which seems weird to me because it's saying that the type of <code>lookup</code> should be <code>Direction</code> instead of <code>EnumDictionary&lt;Direction, number&gt;</code>. I can confirm this by changing the <code>lookup</code> declaration to:</p> <pre><code>const lookup: EnumDictionary&lt;Direction, number&gt; = Direction.Up; </code></pre> <p>and there are no errors.</p> <p>How can I create a lookup type for an enum that guarantees every value of the enum will lead to another value of a different type?</p> <p>TypeScript version: 3.2.1</p>
54,542,503
4
1
null
2019-02-05 20:13:25.677 UTC
8
2022-09-18 22:10:32.913 UTC
null
null
null
null
371,184
null
1
41
typescript|dictionary|enums
23,700
<p>You can do it as follows:</p> <pre><code>type EnumDictionary&lt;T extends string | symbol | number, U&gt; = { [K in T]: U; }; enum Direction { Up, Down, } const a: EnumDictionary&lt;Direction, number&gt; = { [Direction.Up]: 1, [Direction.Down]: -1 }; </code></pre> <p>I found it surprising until I realised that enums can be thought of as a <a href="https://www.typescriptlang.org/docs/handbook/enums.html" rel="noreferrer">specialised union type</a>.</p> <blockquote> <p>The other change is that enum types themselves effectively become a union of each enum member. While we haven’t discussed union types yet, all that you need to know is that with union enums, the type system is able to leverage the fact that it knows the exact set of values that exist in the enum itself.</p> </blockquote> <p>The <code>EnumDictionary</code> defined this way is basically the built in <a href="https://www.typescriptlang.org/docs/handbook/advanced-types.html" rel="noreferrer"><code>Record</code></a> type:</p> <pre><code>type Record&lt;K extends string, T&gt; = { [P in K]: T; } </code></pre>
40,217,140
SQL Merge Error : The MERGE statement attempted to UPDATE or DELETE
<p>I have a source table</p> <pre><code>select 54371 Id, 'foo' [CreateBy], '2016-10-24 09:29:18.548'[CreateDate], 'foo'[UpdateBy], '2016-10-24 09:29:18.548'[UpdateDate], 'E'[MT], 185761[MID], 3[BGID] union select 54372, 'foo', '2016-10-24 09:30:18.548', 'foo', '2016-10-24 09:30:18.548', 'E', 185761, 2 </code></pre> <p>and a target table</p> <pre><code>select 54379 Id, 'foo' [CreateBy], '2016-10-24 09:29:18.548'[CreateDate], 'foo'[UpdateBy], '2016-10-24 10:29:18.548'[UpdateDate], 'E'[MT], 185761[MID], 3[BGID] </code></pre> <p>What I want is to match based on MT, MID and</p> <ol> <li>Insert if not exists</li> <li>update if BGID matches</li> <li>delete if BGID does not matches</li> </ol> <p>When I use SQL Merge Statement I get error</p> <blockquote> <p>The MERGE statement attempted to UPDATE or DELETE the same row more than once. This happens when a target row matches more than one source row. A MERGE statement cannot UPDATE/DELETE the same row of the target table multiple times. Refine the ON clause to ensure a target row matches at most one source row, or use the GROUP BY clause to group the source rows.`</p> </blockquote> <p>My Merge is like this</p> <pre><code>MERGE FooBar AS target USING ( SELECT E.[Id], E.[CreateBy], E.[CreateDate], E.[UpdateBy], E.[UpdateDate], E.[MT], E.[MID], E.[BGID] FROM @FooBar E ) AS source ON source.MID = target.MID AND source.MT = target.MT WHEN MATCHED and target.[BGID] = source.[BGID] THEN UPDATE SET target.[UpdateBy] = Source.[UpdateBy] ,target.[UpdateDate] = Source.[UpdateDate] When Matched and source.BGID &lt;&gt; target.BGID THEN DELETE WHEN NOT MATCHED THEN INSERT([CreateBy] ,[CreateDate] ,[UpdateBy] ,[UpdateDate] ,[MT] ,[MID] ,[BGID]) VALUES ( Source.[CreateBy] ,Source.[CreateDate] ,Source.[UpdateBy] ,Source.[UpdateDate] ,Source.[MT] ,Source.[MID] ,Source.[BGID] ); </code></pre> <p>What am I missing?</p>
40,217,720
1
2
null
2016-10-24 11:23:12.407 UTC
2
2020-09-16 19:16:42.887 UTC
2017-09-25 09:39:39.037 UTC
null
1,011,959
null
1,011,959
null
1
15
sql-server|tsql|merge
64,979
<p>You are joining the tables on <code>ON source.MappingId = target.MappingId</code>.</p> <p>In your data sample, there are more than 1 row with same <code>MappingId = 185761</code>. So here you got:</p> <blockquote> <p>A MERGE statement cannot UPDATE/DELETE the same row of the target table multiple times.</p> </blockquote> <p>You need to specify some <strong>unique column combination</strong> to join the <code>source</code> and the <code>target</code> tables.</p>
16,061,599
Using a variable as a sheet name
<p>I am getting a RunTime 13 error when trying to use a variable for a sheetname as per below:</p> <pre><code>Sub inputdata() Set asheet1 = ThisWorkbook.Worksheets("input").Range("D12") Set rangeDate = ThisWorkbook.Worksheets("input").Range("inputdate") Range("F12:M12").Copy Sheets(asheet1).Select </code></pre> <p>It is erroring on the line Sheets(asheet1).Select</p> <p>Any help would be great thanks!</p>
16,061,730
2
1
null
2013-04-17 13:38:02.927 UTC
null
2019-02-12 06:57:11.077 UTC
null
null
null
null
1,776,642
null
1
1
vba|excel
43,767
<p>The asheet1 is not a string, you are asigning a range object to it . You should declare asheet1 as string and the change this line to</p> <pre><code>Dim asheet1 as string asheet1 = ThisWorkbook.Worksheets("input").Range("D12").Value </code></pre> <p>That should make it work!</p> <p>Edit</p> <p>removed the Set keyword from the string var.</p>
25,447,324
How to use cut with multiple character delimiter in Unix?
<p>My file looks like this</p> <pre><code>abc ||| xyz ||| foo bar hello world ||| spam ham jam ||| blah blah </code></pre> <p>I want to extract a specific column, e.g. I could have done:</p> <pre><code>sed 's/\s|||\s/\\t/g' file | cut -f1 </code></pre> <p>But is there another way of doing that?</p>
25,448,669
2
1
null
2014-08-22 12:42:33.43 UTC
8
2021-01-12 18:01:18.457 UTC
2021-01-12 18:01:18.457 UTC
null
775,954
null
610,569
null
1
40
sed|delimiter|cut
62,068
<p>Since <code>|</code> is a valid regex expression, it needs to be escaped with <code>\\|</code> or put in square brackets: <code>[|]</code>.</p> <p>You can do this:</p> <pre><code>awk -F' \\|\\|\\| ' '{print $1}' file </code></pre> <p>Some other variations that work as well:</p> <pre><code>awk -F' [|][|][|] ' '{print &quot;$1&quot;}' file awk -F' [|]{3} ' '{print &quot;$1&quot;}' file awk -F' \\|{3} ' '{print &quot;$1&quot;}' file awk -F' \\|+ ' '{print &quot;$1&quot;}' file awk -F' [|]+ ' '{print &quot;$1&quot;}' file </code></pre> <blockquote> <p><code>\</code> as separator does not work well in square brackets, only escaping, and many escape chars :)</p> </blockquote> <pre><code>cat file abc \\\ xyz \\\ foo bar </code></pre> <p>Example: 4 <code>\</code> for every <code>\</code> in the expression, so 12 <code>\</code> in total.</p> <pre><code>awk -F' \\\\\\\\\\\\ ' '{print $2}' file xyz </code></pre> <p>or</p> <pre><code>awk -F' \\\\{3} ' '{print $2}' file xyz </code></pre> <p>or this but it's not much simpler</p> <pre><code>awk -F' [\\\\]{3} ' '{print $2}' file xyz awk -F' [\\\\][\\\\][\\\\] ' '{print $2}' file xyz </code></pre>
20,638,040
glob exclude pattern
<p>I have a directory with a bunch of files inside: <code>eee2314</code>, <code>asd3442</code> ... and <code>eph</code>.</p> <p>I want to exclude all files that start with <code>eph</code> with the <code>glob</code> function.</p> <p>How can I do it?</p>
36,295,481
12
0
null
2013-12-17 15:26:28.107 UTC
35
2022-09-23 14:10:56.663 UTC
2014-10-16 07:59:25.057 UTC
null
2,521,769
null
1,067,688
null
1
165
python|glob
176,631
<p>The pattern rules for glob are not regular expressions. Instead, they follow standard Unix path expansion rules. There are only a few special characters: two different wild-cards, and character ranges are supported [from <a href="https://pymotw.com/2/glob/" rel="noreferrer">pymotw: glob – Filename pattern matching</a>].</p> <p>So you can exclude some files with patterns.<br /> For example to exclude manifests files (files starting with <code>_</code>) with glob, you can use:</p> <pre><code>files = glob.glob('files_path/[!_]*') </code></pre>
26,880,526
Performing a segue from a button within a custom UITableViewCell
<p>I want to perform a segue from a button within a custom UITableViewCell, but I don't know how to access the cell's contents when I push that button. I realize that this could be accomplished through didSelectRowAtIndexPath, however I have that method performing another function, and I would like to use the button I have created within the table cell.</p> <p>Here is my perform segue method I'm having trouble with:</p> <pre><code>override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showComments" { let vc:CommentOnPostViewController = segue.destinationViewController as CommentOnPostViewController var buttonPosition:CGPoint = sender?.convertPoint(CGPointZero, toView: self.feed) as CGPoint! var path:NSIndexPath = self.feed.indexPathForRowAtPoint(buttonPosition) as NSIndexPath! var postToCommentOn:PFObject = feedList[path.row] as PFObject vc.post = postToCommentOn as PFObject } } </code></pre> <p>I tag the button in the cell when displaying it, and give it a target action:</p> <pre><code>func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -&gt; UITableViewCell { // There is code that goes here for creating and displaying the cell. cell.commentButton.tag = indexPath.row cell.commentButton.addTarget(self, action: "addComment", forControlEvents: UIControlEvents.TouchUpInside) } </code></pre> <p>Here is the action that is called when pressing the button:</p> <pre><code>func addComment() { self.performSegueWithIdentifier("showComments", sender: self) } </code></pre> <p>Any help is appreciated. Thanks!</p>
26,912,345
3
2
null
2014-11-12 06:18:30.663 UTC
19
2019-10-04 04:54:02.907 UTC
null
null
null
null
3,353,890
null
1
20
ios|uitableview|swift
13,597
<p>Create a Protocol with the Method, that will be called by the CustomCell's Delegate, defined on your TableViewController</p> <pre><code>//Pass any objects, params you need to use on the //segue call to send to the next controller. protocol MyCustomCellDelegator { func callSegueFromCell(myData dataobject: AnyObject) } </code></pre> <p>Now use the Protocol on your UITableViewController</p> <pre><code>class MyTableViewController : UITableViewController, MyCustomCellDelegator { //The usual Defined methods by UIViewController and UITableViewController func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -&gt; UITableViewCell { //Set the CustomCell new Delegate var cell = tableView.dequeueReusableCellWithIdentifier(customIdentifier) as MyCustomCell cell.delagete = self return cell } //MARK: - MyCustomCellDelegator Methods func callSegueFromCell(myData dataobject: AnyObject) { //try not to send self, just to avoid retain cycles(depends on how you handle the code on the next controller) self.performSegueWithIdentifier("showComments", sender:dataobject ) } } </code></pre> <p>Define the Delegate on your Custom Cell and the Call inside your New Button the Delegate Function.</p> <pre><code>class MyCustomCell : UITableViewCell { var delegate:MyCustomCellDelegator! @IBOutlet weak var myButton:UIButton @IBAction func buttonPressed(sender:AnyObject){ var mydata = "Anydata you want to send to the next controller" if(self.delegate != nil){ //Just to be safe. self.delegate.callSegueFromCell(mydata) } } } </code></pre> <p>Hopefully this can be clean and clear for you to understand and implement in your code. </p>
20,021,983
What is the difference between SERIAL and AUTO_INCREMENT in mysql
<p>I have come across two ways to increment the ids in mysql automatically.</p> <p>One is <strong>SERIAL</strong> and other is <strong>AUTOINCREMENT</strong>.</p> <p>So Suppose i want to create a table myfriends. I can create it in two ways like:</p> <p>1) </p> <pre><code>mysql&gt; create table myfriends(id int primary key auto_increment,frnd_name varchar(50) not null); </code></pre> <p>2)</p> <pre><code>mysql&gt; create table myfriends(id serial primary key,frnd_name varchar(50) not null); </code></pre> <p>What is difference between the two ?</p> <p>OR</p> <p>Do anyone way has advantages over other ?</p> <p>Please Help.</p>
20,022,067
3
1
null
2013-11-16 18:16:03.557 UTC
8
2021-01-10 14:34:16.007 UTC
null
null
null
user2737223
null
null
1
69
mysql
48,240
<p>As per the <a href="https://dev.mysql.com/doc/refman/8.0/en/numeric-type-syntax.html" rel="noreferrer">docs</a></p> <blockquote> <p>SERIAL is an alias for BIGINT UNSIGNED NOT NULL AUTO_INCREMENT UNIQUE.</p> </blockquote> <p>So, be careful when creating a reference to a SERIAL PK, since that reference column has to be of this exact type.</p>
6,801,585
How to properly implement "Confirm Password" in ASP.NET MVC 3?
<p>There's already an <a href="http://davidhayden.com/blog/dave/archive/2011/01/01/CompareAttributeASPNETMVC3.aspx">answered question</a> about the same subject but as it's from '09 I consider it outdated.</p> <p>How to properly implement "Confirm Password" in ASP.NET MVC 3?</p> <p>I'm seeing a lot of options on the Web, most of them using the <code>CompareAttribute</code> in the model <a href="http://davidhayden.com/blog/dave/archive/2011/01/01/CompareAttributeASPNETMVC3.aspx">like this one</a></p> <p>The problem is that definitely <code>ConfirmPassword</code> shound't be in the model as it shouldn't be persisted.</p> <p>As the whole unobstrusive client validation from MVC 3 rely on the model and I don't feel like putting a ConfirmPassword property on my model, what should I do?</p> <p>Should I inject a custom client validation function? If so.. How?</p>
6,802,706
2
3
null
2011-07-23 15:59:51.24 UTC
13
2016-02-13 15:56:38.47 UTC
null
null
null
null
192,729
null
1
35
.net|asp.net-mvc-3
46,944
<blockquote> <p>As the whole unobstrusive client validation from MVC 3 rely on the model and I don't feel like putting a ConfirmPassword property on my model, what should I do?</p> </blockquote> <p>A completely agree with you. That's why you should use view models. Then on your view model (a class specifically designed for the requirements of the given view) you could use the <code>[Compare]</code> attribute:</p> <pre><code>public class RegisterViewModel { [Required] public string Username { get; set; } [Required] public string Password { get; set; } [Compare("Password", ErrorMessage = "Confirm password doesn't match, Type again !")] public string ConfirmPassword { get; set; } } </code></pre> <p>and then have your controller action take this view model</p> <pre><code>[HttpPost] public ActionResult Register(RegisterViewModel model) { if (!ModelState.IsValid) { return View(model); } // TODO: Map the view model to a domain model and pass to a repository // Personally I use and like AutoMapper very much (http://automapper.codeplex.com) return RedirectToAction("Success"); } </code></pre>
7,691,468
Can I host a Windows Form inside a control
<p>I have a customer which as a Visual Basic Project in single instance mode with a wired presentation logic.</p> <p>The main form contains a TabControl with mutliple TabPages. If I click on TabPageA another form is shown in front of the Form and resized to have the same size as the TabPage.</p> <p>If I click on TabPageB the first form is hidden and another form is displayed. So basically for the user it looks like you have a TabControl with different TabPages which is not the case.</p> <p>I tried converting the Forms to UserControls and put them inside the TabPage, but, thanks to the SingleInstance app, this would take a whole lot of refactoring. I tried it but eventually gave up because of many many runtime errors and I don't want to put any more effort in this.</p> <p>My Ideam was that, at runtime, I could add the forms to the TabPages and let them act like UserControls, is this even possible?</p>
7,692,113
3
2
null
2011-10-07 18:36:06.71 UTC
9
2011-10-07 19:48:34.053 UTC
null
null
null
null
98,491
null
1
11
.net|vb.net|winforms|user-controls
7,022
<p>You can turn a Form class back to a child control by setting its TopLevel property to False. It becomes essentially a UserControl with some unused overhead. Make it look similar to this:</p> <pre><code>Public Class Form1 Public Sub New() InitializeComponent() Dim frm As New Form2 frm.TopLevel = False frm.FormBorderStyle = Windows.Forms.FormBorderStyle.None frm.Visible = True frm.Dock = DockStyle.Fill TabPage1.Controls.Add(frm) End Sub End Class </code></pre>
8,081,234
How to properly install and configure JSF libraries via Maven?
<p>I'm trying to deploy a JSF based application to Tomcat 6. The way my build system is setup, the WAR itself doesn't have any libraries in it, because this server is serving a total of 43 apps. Instead, the libraries are copied into a shared library folder and shared among the apps. When I deploy, I get this error</p> <pre><code>SEVERE: Error deploying configuration descriptor SSOAdmin.xml java.lang.ClassFormatError: Absent Code attribute in method that is not native or abstract in class file javax/faces/webapp/FacesServlet at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClassCond(ClassLoader.java:631) at java.lang.ClassLoader.defineClass(ClassLoader.java:615) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141) at java.net.URLClassLoader.defineClass(URLClassLoader.java:283) at java.net.URLClassLoader.access$000(URLClassLoader.java:58) at java.net.URLClassLoader$1.run(URLClassLoader.java:197) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:190) at java.lang.ClassLoader.loadClass(ClassLoader.java:306) at java.lang.ClassLoader.loadClass(ClassLoader.java:247) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1667) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1526) at org.apache.catalina.startup.WebAnnotationSet.loadApplicationServletAnnotations(WebAnnotationSet.java:108) at org.apache.catalina.startup.WebAnnotationSet.loadApplicationAnnotations(WebAnnotationSet.java:58) at org.apache.catalina.startup.ContextConfig.applicationAnnotationsConfig(ContextConfig.java:297) at org.apache.catalina.startup.ContextConfig.start(ContextConfig.java:1078) at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:261) at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:142) at org.apache.catalina.core.StandardContext.start(StandardContext.java:4611) at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:799) at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:779) at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:601) at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:675) at org.apache.catalina.startup.HostConfig.deployDescriptors(HostConfig.java:601) at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:502) at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1315) at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:324) at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:142) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1061) at org.apache.catalina.core.StandardHost.start(StandardHost.java:840) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1053) at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:463) at org.apache.catalina.core.StandardService.start(StandardService.java:525) at org.apache.catalina.core.StandardServer.start(StandardServer.java:754) at org.apache.catalina.startup.Catalina.start(Catalina.java:595) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289) at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414) </code></pre> <p>Now in my research, I see that this is supposed to be solved by downloading the JSF source code and compiling it myself. That is a horrible solution in my case. That will cause huge problems on my team with the various configurations we have to contend with. Is there another fix for this?</p> <p>Here is my <code>pom.xml</code>:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;groupId&gt;com.nms.sso&lt;/groupId&gt; &lt;artifactId&gt;SSOAdmin&lt;/artifactId&gt; &lt;version&gt;09142011-BETA&lt;/version&gt; &lt;packaging&gt;war&lt;/packaging&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;asm&lt;/groupId&gt; &lt;artifactId&gt;asm&lt;/artifactId&gt; &lt;scope&gt;${myExeScope}&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;cglib&lt;/groupId&gt; &lt;artifactId&gt;cglib&lt;/artifactId&gt; &lt;scope&gt;${myExeScope}&lt;/scope&gt; &lt;/dependency&gt; &lt;!-- &lt;dependency&gt; --&gt; &lt;!-- &lt;groupId&gt;com.sun.faces&lt;/groupId&gt; --&gt; &lt;!-- &lt;artifactId&gt;jsf-api&lt;/artifactId&gt; --&gt; &lt;!-- &lt;scope&gt;${myExeScope}&lt;/scope&gt; --&gt; &lt;!-- &lt;/dependency&gt; --&gt; &lt;!-- &lt;dependency&gt; --&gt; &lt;!-- &lt;groupId&gt;com.sun.faces&lt;/groupId&gt; --&gt; &lt;!-- &lt;artifactId&gt;jsf-impl&lt;/artifactId&gt; --&gt; &lt;!-- &lt;scope&gt;${myExeScope}&lt;/scope&gt; --&gt; &lt;!-- &lt;/dependency&gt; --&gt; &lt;dependency&gt; &lt;groupId&gt;commons-codec&lt;/groupId&gt; &lt;artifactId&gt;commons-codec&lt;/artifactId&gt; &lt;scope&gt;${myExeScope}&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;javax&lt;/groupId&gt; &lt;artifactId&gt;javaee-api&lt;/artifactId&gt; &lt;version&gt;6.0&lt;/version&gt; &lt;scope&gt;provided&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;javax.faces&lt;/groupId&gt; &lt;artifactId&gt;javax.faces-api&lt;/artifactId&gt; &lt;scope&gt;${myExeScope}&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;junit&lt;/groupId&gt; &lt;artifactId&gt;junit&lt;/artifactId&gt; &lt;scope&gt;${myExeScope}&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;net.sf.jt400&lt;/groupId&gt; &lt;artifactId&gt;jt400&lt;/artifactId&gt; &lt;scope&gt;${myExeScope}&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;nmsc&lt;/groupId&gt; &lt;artifactId&gt;nmsc_api&lt;/artifactId&gt; &lt;version&gt;09142011-BETA&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.hibernate&lt;/groupId&gt; &lt;artifactId&gt;hibernate-core&lt;/artifactId&gt; &lt;scope&gt;${myExeScope}&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.icefaces&lt;/groupId&gt; &lt;artifactId&gt;icefaces&lt;/artifactId&gt; &lt;scope&gt;${myExeScope}&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.icefaces&lt;/groupId&gt; &lt;artifactId&gt;icefaces-ace&lt;/artifactId&gt; &lt;scope&gt;${myExeScope}&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.icefaces&lt;/groupId&gt; &lt;artifactId&gt;icefaces-compat&lt;/artifactId&gt; &lt;scope&gt;${myExeScope}&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.javassist&lt;/groupId&gt; &lt;artifactId&gt;javassist&lt;/artifactId&gt; &lt;scope&gt;${myExeScope}&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.jibx&lt;/groupId&gt; &lt;artifactId&gt;jibx-extras&lt;/artifactId&gt; &lt;scope&gt;${myExeScope}&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.jibx&lt;/groupId&gt; &lt;artifactId&gt;jibx-run&lt;/artifactId&gt; &lt;scope&gt;${myExeScope}&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.slf4j&lt;/groupId&gt; &lt;artifactId&gt;slf4j-log4j12&lt;/artifactId&gt; &lt;scope&gt;${myExeScope}&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-context&lt;/artifactId&gt; &lt;scope&gt;${myExeScope}&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-orm&lt;/artifactId&gt; &lt;scope&gt;${myExeScope}&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-tx&lt;/artifactId&gt; &lt;scope&gt;${myExeScope}&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-web&lt;/artifactId&gt; &lt;scope&gt;${myExeScope}&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;postgresql&lt;/groupId&gt; &lt;artifactId&gt;postgresql&lt;/artifactId&gt; &lt;scope&gt;${myExeScope}&lt;/scope&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;parent&gt; &lt;groupId&gt;nmsc&lt;/groupId&gt; &lt;artifactId&gt;nmsc_lib&lt;/artifactId&gt; &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt; &lt;relativePath&gt;../libs&lt;/relativePath&gt; &lt;/parent&gt; &lt;build&gt; &lt;finalName&gt;SSOAdmin&lt;/finalName&gt; &lt;/build&gt; &lt;name&gt;SSOAdmin Maven Webapp&lt;/name&gt; &lt;/project&gt; </code></pre> <p>There has got to be a solution here. I can't for a second believe that the Maven distributable for JSF is only good for compiling and not good for deployment.</p>
8,081,384
1
0
null
2011-11-10 14:41:28.997 UTC
12
2022-06-20 08:34:20.703 UTC
2016-05-17 07:39:15.973 UTC
null
157,882
null
425,715
null
1
17
maven|jsf|tomcat|configuration|installation
28,778
<p>When you're facing a &quot;weird&quot; exception suggesting that classes/methods/files/components/tags are absent or different while they are seemingly explicitly included in the web application such as the ones below,</p> <blockquote> <p>java.lang.ClassFormatError: Absent Code attribute in method that is not native or abstract in class file javax/faces/webapp/FacesServlet</p> </blockquote> <blockquote> <p>java.util.MissingResourceException: Can't find javax.faces.LogStrings bundle</p> </blockquote> <blockquote> <p>com.sun.faces.vendor.WebContainerInjectionProvider cannot be cast to com.sun.faces.spi.InjectionProvider</p> </blockquote> <blockquote> <p>com.sun.faces.config.ConfigurationException: CONFIGURATION FAILED</p> </blockquote> <blockquote> <p>The tag named inputFile from namespace http://xmlns.jcp.org/jsf/html has a null handler-class defined.</p> </blockquote> <blockquote> <p>java.lang.NullPointerException at javax.faces.CurrentThreadToServletContext.getFallbackFactory</p> </blockquote> <blockquote> <p>java.lang.AbstractMethodError at javax.faces.application.ViewHandlerWrapper.getWebsocketURL</p> </blockquote> <blockquote> <p>java.lang.NullPointerException at com.sun.faces.config.InitFacesContext.cleanupInitMaps</p> </blockquote> <p>or when you're facing &quot;weird&quot; runtime behavior such as broken HTTP sessions (<code>jsessionid</code> appears in link URLs over all place), and/or broken JSF view scope (it behaves as request scoped), and/or broken CSS/JS/image resources, then the chance is big that the webapp's runtime classpath is polluted with duplicate different versioned JAR files.</p> <p>In your specific case with the <code>ClassFormatError</code> on the <code>FacesServlet</code>, it means that the JAR file containing the mentioned class has been found for the first time is actually a &quot;blueprint&quot; API JAR file, intented for implementation vendors (such as developers working for Mojarra and MyFaces). It contains class files with only class and method signatures, without any code bodies and resource files. That's exactly what &quot;absent code attribute&quot; means. It's purely intented for javadocs and compilation.</p> <h2>Always mark server-provided libraries as <code>provided</code></h2> <p>All dependencies marked &quot;<a href="https://mvnrepository.com/open-source/java-specs" rel="nofollow noreferrer">Java Specifications</a>&quot; in Maven and having <code>-api</code> suffix in the artifact ID are those blueprint APIs. You should absolutely not have them in the runtime classpath. You should always mark them <code>&lt;scope&gt;provided&lt;/scope&gt;</code> if you really need to have it in your pom. A well known example is the <a href="https://mvnrepository.com/artifact/jakarta.platform/jakarta.jakartaee-api" rel="nofollow noreferrer">Jakarta EE (Web) API</a> (formerly known as Java EE):</p> <pre><code>&lt;dependency&gt; &lt;groupId&gt;jakarta.platform&lt;/groupId&gt; &lt;artifactId&gt;jakarta.jakartaee-api&lt;/artifactId&gt; &lt;version&gt;&lt;!-- 8.0.0 or 9.0.0 or 9.1.0 or newer --&gt;&lt;/version&gt; &lt;scope&gt;provided&lt;/scope&gt; &lt;/dependency&gt; </code></pre> <p>If the <code>provided</code> scope is absent, then this JAR will end up in webapp's <code>/WEB-INF/lib</code>, causing all trouble you're facing now. This JAR also contains the blueprint class of <code>FacesServlet</code>.</p> <p>In your specific case, you have an unnecessary <a href="https://mvnrepository.com/artifact/jakarta.faces/jakarta.faces-api" rel="nofollow noreferrer">JSF API</a> dependency:</p> <pre><code>&lt;dependency&gt; &lt;groupId&gt;jakarta.faces&lt;/groupId&gt; &lt;artifactId&gt;jakarta.faces-api&lt;/artifactId&gt; &lt;/dependency&gt; </code></pre> <p>This is causing trouble because this contains the blueprint class of <code>FacesServlet</code>. Removing it and relying on a <code>provided</code> Jakarta EE (Web) API as shown above should solve it.</p> <p>Tomcat as being a barebones JSP/Servlet container already provides JSP, Servlet and EL (and since 8 also WebSocket) out the box. So you should mark at least <code>jsp-api</code>, <code>servlet-api</code>, and <code>el-api</code> as <code>provided</code>. Tomcat only doesn't provide JSF (and <a href="https://stackoverflow.com/tags/jstl/info">JSTL</a>) out the box. So you'd need to install it via the webapp.</p> <p>Full fledged Jakarta EE servers such as WildFly, TomEE, GlassFish, Payara, WebSphere, etc already provide the entire Jakarta EE API out the box, including JSF. So you do absolutely not need to install JSF via the webapp. It would only result in conflicts if the server already provides a different implementation and/or version out the box. The only dependency you need is the <code>jakartaee-api</code> exactly as shown here above.</p> <h2>Installing JSF on Tomcat 10 or newer</h2> <p>You'll need a minimum JSF version of 3.0 instead of 2.3 because the <code>javax.*</code> package has been renamed to <code>jakarta.*</code> since 3.0 only.</p> <p>Installing Mojarra 3.0 on Tomcat 10 or newer:</p> <pre><code>&lt;dependency&gt; &lt;groupId&gt;org.glassfish&lt;/groupId&gt; &lt;artifactId&gt;jakarta.faces&lt;/artifactId&gt; &lt;version&gt;&lt;!-- Check https://eclipse-ee4j.github.io/mojarra --&gt;&lt;/version&gt; &lt;/dependency&gt; </code></pre> <p>You can also check <a href="https://mvnrepository.com/artifact/org.glassfish/jakarta.faces" rel="nofollow noreferrer"><code>org.glassfish:jakarta.faces</code> repository</a> for current latest 3.0.x release version (which is currently <code>3.0.2</code>). See also <a href="https://eclipse-ee4j.github.io/mojarra/" rel="nofollow noreferrer">Mojarra installation instructions</a> for other necessary dependencies (CDI, BV, JSONP).</p> <p>Installing MyFaces 3.0 on Tomcat 10 or newer:</p> <pre><code>&lt;dependency&gt; &lt;groupId&gt;org.apache.myfaces.core&lt;/groupId&gt; &lt;artifactId&gt;myfaces-impl&lt;/artifactId&gt; &lt;version&gt;&lt;!-- Check http://myfaces.apache.org --&gt;&lt;/version&gt; &lt;/dependency&gt; </code></pre> <p>You can also check <a href="https://mvnrepository.com/artifact/org.apache.myfaces.core/myfaces-impl" rel="nofollow noreferrer"><code>org.apache.myfaces.core:myfaces-impl</code> repository</a> for current latest 3.0.x release version (which is currently <code>3.0.2</code>).</p> <p>Don't forget to install JSTL API along, by the way. This is also absent in Tomcat.</p> <pre><code>&lt;dependency&gt; &lt;groupId&gt;jakarta.servlet.jsp.jstl&lt;/groupId&gt; &lt;artifactId&gt;jakarta.servlet.jsp.jstl-api&lt;/artifactId&gt; &lt;version&gt;2.0.0&lt;/version&gt; &lt;/dependency&gt; </code></pre> <p>Also note that since JSF 2.3, CDI has become a required dependency. This is available out the box in normal Jakarta EE servers but not on servletcontainers such as Tomcat. In this case head to <a href="https://stackoverflow.com/questions/18995951/how-to-install-and-use-cdi-on-tomcat/19003725#19003725">How to install and use CDI on Tomcat?</a></p> <h2>Installing JSF on Tomcat 9 or older</h2> <p>There are two JSF implementations: <a href="https://stackoverflow.com/questions/4530746/difference-between-mojarra-and-myfaces">Mojarra and MyFaces</a>. You should choose to install one of them and thus <strong>not</strong> both.</p> <p>Installing Mojarra 2.3 on Tomcat 9 or older:</p> <pre><code>&lt;dependency&gt; &lt;groupId&gt;org.glassfish&lt;/groupId&gt; &lt;artifactId&gt;jakarta.faces&lt;/artifactId&gt; &lt;version&gt;&lt;!-- Check https://eclipse-ee4j.github.io/mojarra --&gt;&lt;/version&gt; &lt;/dependency&gt; </code></pre> <p>You can also check <a href="https://mvnrepository.com/artifact/org.glassfish/jakarta.faces" rel="nofollow noreferrer"><code>org.glassfish:jakarta.faces</code> repository</a> for current latest 2.3.x release version (which is currently <code>2.3.16</code>). See also <a href="https://eclipse-ee4j.github.io/mojarra/" rel="nofollow noreferrer">Mojarra installation instructions</a> for other necessary dependencies (CDI, BV, JSONP).</p> <p>Installing MyFaces 2.3 on Tomcat 9 or older:</p> <pre><code>&lt;dependency&gt; &lt;groupId&gt;org.apache.myfaces.core&lt;/groupId&gt; &lt;artifactId&gt;myfaces-impl&lt;/artifactId&gt; &lt;version&gt;&lt;!-- Check http://myfaces.apache.org --&gt;&lt;/version&gt; &lt;/dependency&gt; </code></pre> <p>You can also check <a href="https://mvnrepository.com/artifact/org.apache.myfaces.core/myfaces-impl" rel="nofollow noreferrer"><code>org.apache.myfaces.core:myfaces-impl</code> repository</a> for current latest 2.3.x release version (which is currently <code>2.3.9</code>).</p> <p>Note that Tomcat 6 as being Servlet 2.5 container supports max JSF 2.1.</p> <p>Don't forget to install JSTL API along, by the way. This is also absent in Tomcat.</p> <pre><code>&lt;dependency&gt; &lt;groupId&gt;jakarta.servlet.jsp.jstl&lt;/groupId&gt; &lt;artifactId&gt;jakarta.servlet.jsp.jstl-api&lt;/artifactId&gt; &lt;version&gt;1.2.7&lt;/version&gt; &lt;/dependency&gt; </code></pre> <p>Also note that since JSF 2.3, CDI has become a required dependency. This is available out the box in normal Jakarta EE servers but not on servletcontainers such as Tomcat. In this case head to <a href="https://stackoverflow.com/questions/18995951/how-to-install-and-use-cdi-on-tomcat/19003725#19003725">How to install and use CDI on Tomcat?</a></p> <h3>See also:</h3> <ul> <li><a href="https://stackoverflow.com/questions/7295096/what-exactly-is-java-ee">What exactly is Java EE?</a></li> <li><a href="https://stackoverflow.com/questions/20268095/java-lang-noclassdeffounderror-javax-servlet-jsp-jstl-core-config/">java.lang.NoClassDefFoundError: javax/servlet/jsp/jstl/core/Config</a></li> <li><a href="https://stackoverflow.com/questions/18995951/how-to-install-and-use-cdi-on-tomcat/">How to install and use CDI on Tomcat?</a></li> <li><a href="https://stackoverflow.com/questions/3112946/jsf-returns-blank-unparsed-page-with-plain-raw-xhtml-xml-el-source-instead-of-re">JSF returns blank/unparsed page with plain/raw XHTML/XML/EL source instead of rendered HTML output</a></li> </ul>
10,553,469
Automatically expand all in Eclipse Search results
<p>I usually want to have all the search results (from <code>ctrl-H</code>) fully expanded, but only the first leaf node is expanded by default.</p> <p>What I end up doing is clicking the "Expand All" button in the Search view but this is tedious.</p> <p><strong>Is there a way to automatically have results fully expanded?</strong></p>
10,554,304
3
2
null
2012-05-11 14:36:44.32 UTC
null
2017-10-11 08:53:02.38 UTC
null
null
null
null
892,191
null
1
31
eclipse|search
5,587
<p>No but you can use the keyboard shortcuts of your OS. On Linux, use <kbd>Nk*</kbd> (<code>*</code> on the numpad) to expand the current node and all children.</p> <p>Windows user can use <kbd>Shift+Nk*</kbd></p> <p>On the Mac, select all nodes with <kbd>Command+A</kbd> and then expand them with <kbd>Command+Right Arrow</kbd></p>
7,157,029
call php page under Javascript function
<p>Is it Possible to call php page under Javascript function? I have an javascript function and I want to call php page if someone press okk </p> <p>Here is my code so far </p> <pre><code>function show_confirm() { var r=confirm("Do You Really want to Refund money! Press ok to Continue "); if (r==true) { alert("You pressed OK!"); return true; } else { alert("You pressed Cancel!"); } } </code></pre> <p>and this Js function i m using here </p> <pre><code>&lt;td align="center"&gt;&lt;input name="Refund" onclick="show_confirm()" type="submit" value="Refund" /&gt;&lt;/td&gt; </code></pre> <p>now i want if user press okk then <code>call other php page</code> ...</p>
7,157,074
5
4
null
2011-08-23 06:22:47.67 UTC
null
2012-12-18 17:11:50.263 UTC
2012-12-18 17:11:50.263 UTC
null
367,456
null
899,827
null
1
3
php|javascript|function
43,424
<p>if you want to redirect to a page:yourphppage.php if the user pressed ok.</p> <pre><code> function show_confirm() { var r=confirm("Do You Really want to Refund money! Press ok to Continue "); if (r==true) { window.location="yourphppage.php"; return true; } else { alert("You pressed Cancel!"); } } </code></pre>
7,075,572
Using LINQ to convert List<U> to List<T>
<p>I have 2 classes which have some identical properties. I stock into a list properties from 1st class, and after that, I want to take some needed properties and put them into a list of 2nd class type. I've made cast sequence through C# and that runs OK, but I must do with LINQ. I tried to do something but without good results. Help me please with suggestions.</p> <p>1st Class:</p> <pre><code> public class ServiceInfo { private long _id; public long ID { get { return this._id; } set { _id = value; } } private string _name; public string Name { get { return this._name; } set { _name = value; } } private long _qty; public long Quantity { get { return this._qty; } set { _qty = value; } } private double _amount; public double Amount { get { return this._amount; } set { _amount = value; } } private string _currency; public string Currency { get { return this._currency; } set { _currency = value; } } private DateTime? _date; public DateTime? Date { get { return this._date; } set { _date = value; } } } </code></pre> <p>2nd Class:</p> <pre><code>class InvoiceWithEntryInfo { private string currencyField; private long IdField; public long IdIWEI { get { return this.IdField; } set { IdIWEI = value; } } private string nameField; public string NameIWEI { get { return this.nameField; } set { NameIWEI = value; } } private long qtyField; public long QuantityIWEI { get { return this.qtyField; } set { QuantityIWEI = value; } } private double amountField; public double AmountIWEI { get { return this.amountField; } set { AmountIWEI = value; } } private DateTime dateField; public DateTime? DateIWEI { get { return this.dateField; } set { DateIWEI = value; } } public string OwnerIWEI { get; set; } } </code></pre> <p>C# sample which runs OK: ...</p> <pre><code>var sil = new List&lt;ServiceInfo&gt;(); var iweil = new List&lt;InvoiceWithEntryInfo&gt;(); </code></pre> <p>...</p> <pre><code>if (sil != null) { foreach (ServiceInfo item in sil) { iweil.Add(new InvoiceWithEntryInfo { IdIWEI = item.ID, AmountIWEI = item.Amount, DateIWEI = item.Date }); } </code></pre> <p>LINQ sample which doesn't run OK:</p> <pre><code>iweilCOPY = sil.ConvertAll&lt;InvoiceWithEntryInfo&gt;(a =&gt; (InvoiceWithEntryInfo)a); iweilCOPY = sil.FindAll(a =&gt; (sil is InvoiceWithEntryInfo)).ConvertAll&lt;InvoiceWithEntryInfo&gt;(a =&gt; (InvoiceWithEntryInfo)a); </code></pre>
7,075,667
5
0
null
2011-08-16 08:38:40.34 UTC
8
2020-07-31 04:30:55.607 UTC
2020-07-31 04:30:55.607 UTC
null
214,143
null
896,258
null
1
55
c#|linq|list|.net-3.5|casting
87,074
<pre><code>var iweilCopy = sil.Select(item =&gt; new InvoiceWithEntryInfo() { IdWEI = item.Id, NameWEI = item.Name, .... }).ToList(); </code></pre>
7,365,575
How to get text between two characters?
<p><code>|text to get| Other text.... migh have "|"'s ...</code></p> <p>How can I get the <code>text to get</code> stuff from the string (and remove it)?</p> <p>It should be just the first match</p>
7,365,658
6
1
null
2011-09-09 17:58:31.267 UTC
3
2011-09-09 18:07:20.65 UTC
null
null
null
null
937,302
null
1
22
javascript|jquery|string
62,991
<pre><code>var test_str = "|text to get| Other text.... migh have \"|\"'s ..."; var start_pos = test_str.indexOf('|') + 1; var end_pos = test_str.indexOf('|',start_pos); var text_to_get = test_str.substring(start_pos,end_pos) alert(text_to_get); </code></pre>
7,114,604
NUnit parameterized tests with datetime
<p>Is it not possible with NUnit to go the following?</p> <pre class="lang-cs prettyprint-override"><code>[TestCase(new DateTime(2010,7,8), true)] public void My Test(DateTime startdate, bool expectedResult) { ... } </code></pre> <p>I really want to put a <code>datetime</code> in there, but it doesn't seem to like it. The error is:</p> <blockquote> <p>An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type</p> </blockquote> <p>Some documentation I read seems to suggest you should be able to, but I can't find any examples.</p>
7,114,955
6
1
null
2011-08-18 21:54:55.36 UTC
9
2021-07-05 09:33:41.87 UTC
2020-07-28 22:31:21.003 UTC
null
63,550
null
822,229
null
1
79
unit-testing|nunit
32,738
<p>I'd probably use something like the <a href="http://www.nunit.org/index.php?p=valueSource&amp;r=2.5" rel="noreferrer">ValueSource</a> attribute to do this:</p> <pre class="lang-cs prettyprint-override"><code>public class TestData { public DateTime StartDate{ get; set; } public bool ExpectedResult{ get; set; } } private static TestData[] _testData = new[]{ new TestData(){StartDate= new DateTime(2010, 7, 8), ExpectedResult= true}}; [Test] public void TestMethod([ValueSource(&quot;_testData&quot;)]TestData testData) { } </code></pre> <p>This will run the TestMethod for each entry in the _testData collection.</p>
14,144,892
In Java, how to convert a list of objects to byte array?
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/5837698/converting-any-object-to-a-byte-array-in-java">Converting any object to a byte array in java</a> </p> </blockquote> <p>I have a class that needs to be cached. The cache API provides an interface that caches <code>byte[]</code>. My class contains a field as <code>List&lt;Author&gt;</code>, where <code>Author</code> is another class. What is the correct way for me to turn <code>List&lt;Author&gt;</code> to <code>byte[]</code> for caching? And retrieve the <code>byte[]</code> from cache to reconstruct the <code>List&lt;Author&gt;</code>?</p> <p>More detail about <code>Author</code> class: it is very simple, only has two <code>String</code> fields. One <code>String</code> field is possible to be <code>null</code>.</p>
14,144,946
3
1
null
2013-01-03 18:26:07.463 UTC
1
2013-01-03 18:57:52.48 UTC
2017-05-23 11:54:10.047 UTC
null
-1
null
136,733
null
1
13
java|caching
42,932
<p>Author class should implement <code>Serializable</code></p> <p>Then you can use <code>ObjectOutputStream</code> to serialize the object and <code>ByteArrayOutputStream</code> to get it written as bytes.</p> <p>Then deserialize it using ObjectInputStream and convert back.</p> <pre><code> ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(list); byte[] bytes = bos.toByteArray(); </code></pre>
14,262,798
How to change setting inside SBT command?
<p>I want to have a command <code>publish-snapshot</code> that would run the <code>publish</code> task with modified <code>version</code> setting (that setting is to be computed at the time of execution of the command).</p> <p>I figured out how to get the current value of the <code>version</code> inside command, and <code>Project.runTask("task", "scope", ...)</code> seems to be a right call for invoking the <code>publish</code> task.</p> <p>The only thing that I'm confused with is how to modify the <code>State</code> instance with a new version value. All my attempts seem to do nothing to the original version setting. </p> <p>My last attempt:</p> <pre><code>val printVers = TaskKey[Unit]("printvers") val printVersTask = TaskKey[Unit]("printvers") &lt;&lt;= {version map println} def publishSnapshot = Command.command("publish-snapshot") { state =&gt; val newState = SessionSettings.reapply(state.get(sessionSettings).get.appendRaw(version := "???"), state) Project.runTask(printVers in Compile, newState, true) state } lazy val root = Project("main", file("."), settings = Defaults.defaultSettings ++ Seq(printVersTask)).settings(commands += publishSnapshot) </code></pre> <p>Is there some way to fix that behavior?</p>
29,597,441
3
0
null
2013-01-10 16:37:30.533 UTC
11
2015-05-06 19:49:43.04 UTC
2014-01-09 22:46:12.1 UTC
null
1,305,344
null
486,057
null
1
35
scala|sbt
4,999
<p>This actually did not work for me. I'm using SBT 0.13.7</p> <p>Adapting what I had to do to the above example, I had to do something like:</p> <pre><code>def publishSnapshot = Command.command("publish-snapshot") { state =&gt; val extracted = Project extract state val newState = extracted.append(Seq(version := "newVersion"), state) val (s, _) = Project.extract(newState).runTask(publish in Compile, newState) s } </code></pre> <p>Or alternatively do:</p> <pre><code>def publishSnapshot = Command.command("publish-snapshot") { state =&gt; val newState = Command.process("""set version := "newVersion" """, state) val (s, _) = Project.extract(newState).runTask(publish in Compile, newState) s } </code></pre>
14,171,111
Cocoa error 3840 using JSON (iOS)
<p>I'm trying to send data to a server and receive the response in JSON format. The problem is that the server has to return "success" or "fail" but it returns "(null)".</p> <p>Here's the returned error: </p> <blockquote> <p>Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.) UserInfo=XXXXXXXXX {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}</p> </blockquote> <p>Is it possible that the error is in the server script?</p> <p>Here's my function to send the data and receive the response:</p> <pre><code>- (void) putData:(NSString *)parameter valor:(NSString *)valor { NSString *rawString = [NSString stringWithFormat:@"%@=%@", parameter, valor]; NSData *data = [rawString dataUsingEncoding:NSUTF8StringEncoding]; NSURL *url = [NSURL URLWithString:@"http://www.xxx.xxx/xxx.php"]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; [request setHTTPMethod:@"PUT"]; [request setHTTPBody:data]; NSURLResponse *response; NSError *error; NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&amp;response error:&amp;error]; NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&amp;error]; NSLog(@"responseData: %@ error: %@", json, error); } </code></pre>
14,171,349
3
0
null
2013-01-05 11:01:21.49 UTC
11
2018-01-31 10:22:30.647 UTC
2018-01-31 10:22:30.647 UTC
null
1,033,581
null
1,936,438
null
1
38
objective-c|ios|json|cocoa-touch
84,059
<p>Unless you pass the option <code>NSJSONReadingAllowFragments</code> to <code>[NSJSONSerialization JSONObjectWithData:options:error:]</code> the response from the server must be valid JSON with a top level container which is an array or dictionary. </p> <p>for example:</p> <pre><code> { "response" : "Success" } </code></pre> <p>P.S. If you want a mutable dictionary you must also include <code>NSJSONReadingMutableContainers</code> in your options.</p>
14,010,895
Bind key to increase / decrease font size in emacs
<p>In my terminal (I have <a href="http://linux.die.net/man/1/terminator">terminator</a>) I can use the key combinations <kbd>Ctrl</kbd> <kbd>+</kbd> and <kbd>Ctrl</kbd> <kbd>-</kbd> to increase / decrease the font size.</p> <p>In emacs I can do the following to set the font-height:</p> <pre><code>(set-face-attribute 'default nil :height 70) </code></pre> <p>But I do not know how to increase / decrease it. How could I easily add this to my emacs configuration?</p>
14,012,138
5
3
null
2012-12-23 12:20:29.217 UTC
17
2022-09-21 16:35:49.643 UTC
2014-11-23 04:05:35.453 UTC
null
729,907
null
647,991
null
1
43
emacs|elisp|font-size
12,395
<p>I think you want <code>C-x C-+</code> or <code>C-x C--</code>.</p>
14,001,278
Why isn't smoothsort more common?
<p>From reading <a href="http://en.wikipedia.org/wiki/Sorting_algorithm">this</a> article from Wikipedia on sorting algorithms, it would seem that smoothsort is the best sorting algorithm there is. It has top performance in all categories: best, average, and worst. Nothing beats it in any category. It also has constant memory requirements. The only downside is that it isn't stable.</p> <p>It beats timsort in memory, and it beats quicksort in both worst-case performance and memory.</p> <p>But I never hear about smoothsort. Nobody ever mentions it, and most discussions seem to revolve around other sorting algorithms.</p> <p>Why is that?</p>
14,001,626
3
1
null
2012-12-22 08:30:38.41 UTC
4
2017-02-19 14:12:14.813 UTC
2012-12-24 22:47:05.34 UTC
null
501,557
null
1,029,146
null
1
44
algorithm|sorting|timsort|smoothsort
9,229
<p>Big-O performance is great for publishing papers, but in the real world we have to look at the constants too. Quicksort has been the algorithm of choice for unstable, in-place, in-memory sorting for so long because we can implement its inner loop very efficiently and it is very cache-friendly. Even if you can implement smoothsort's inner loop as efficiently, or nearly as efficiently, as quicksort's, you will probably find that its cache miss rate makes it slower.</p> <p>We mitigate quicksort's worst-case performance by spending a little more effort choosing good pivots (to reduce the number of pathological cases) and detecting pathological cases. Look up <a href="http://en.wikipedia.org/wiki/Introsort" rel="noreferrer">introsort</a>. Introsort runs quicksort first, but switches to heapsort if it detects excessive recursion (which indicates a pathological case for quicksort).</p>
14,130,679
jsdoc valid param types
<p>Is there a list somewhere of valid types for param tags for jsdoc? For example,</p> <pre><code>@param {type} myParam Some parameter description </code></pre> <p>I know that things like <code>number</code> and <code>String</code> are valid, but what if I want to document that the number is an integer. Is <code>int</code> valid?</p> <p>I've done some googling, but I can't seem to find a full list.</p>
14,131,405
2
0
null
2013-01-02 23:07:37.547 UTC
9
2019-12-11 16:17:40.883 UTC
null
null
null
null
121,993
null
1
65
javascript|jsdoc
34,264
<p>The JS Documentation tooling I've used just tokenizes the comments into strings anyway, making it possible to put anything you want in the {type} section.</p> <p>You could stick with JavaScript types if you wanted like {number} or {string}, or if you want to specify you could do {integer}... but I would probably recommend something like:</p> <p><code>@param {number} myParam must be an integer</code></p> <p>cheers</p>
14,076,296
@Nullable annotation usage
<p>I saw some method in java declared as:</p> <pre><code>void foo(@Nullable Object obj) { ... } </code></pre> <p>What's the meaning of <code>@Nullable</code> here? Does it mean the input could be <code>null</code>?</p> <p>Without the annotation, the input can still be null, so I guess that's not just it?</p>
14,076,320
4
3
null
2012-12-28 21:54:07.233 UTC
68
2021-08-21 06:29:08.73 UTC
2019-08-14 01:11:37.933 UTC
null
212,378
null
1,508,893
null
1
414
java|annotations
293,823
<p>It makes it clear that the method accepts null values, and that if you override the method, you should also accept null values.</p> <p>It also serves as a hint for code analyzers like <a href="http://findbugs.sourceforge.net/">FindBugs</a>. For example, if such a method dereferences its argument without checking for null first, FindBugs will emit a warning.</p>
29,011,841
How do I implement a password Reset Link
<p>I currently have a system where if a user has forgotten their password, they can reset it by clicking on a forgot password link. They will be taken to a page where they enter in their username/email and then an email will be sent to the user, I wanted to know how can I implement a password reset link in the email so once the user clicks on the link he/she is taken to a page which will allow them to reset their password.</p> <p>This is the code in my controller </p> <pre><code>public ActionResult ForgotPassword() { //verify user id string UserId = Request.Params ["txtUserName"]; string msg = ""; if (UserId == null) { msg = "You Have Entered An Invalid UserId - Try Again"; ViewData["ForgotPassword"] = msg; return View("ForgotPassword"); } SqlConnection lsql = null; lsql = DBFactory.GetInstance().getMyConnection(); String sqlstring = "SELECT * from dbo.[USERS] where USERID = '" + UserId.ToString() + "'"; SqlCommand myCommand = new SqlCommand(sqlstring, lsql); lsql.Open(); Boolean validUser; using (SqlDataReader myReader = myCommand.ExecuteReader()) { validUser = false; while (myReader.Read()) { validUser = true; } myReader.Close(); } myCommand.Dispose(); if (!validUser) { msg = "You Have Entered An Invalid UserId - Try Again"; ViewData["ForgotPassword"] = msg; lsql.Close(); return View("ForgotPassword"); } //run store procedure using (lsql) { SqlCommand cmd = new SqlCommand("Stock_Check_Test.dbo.RESET_PASSWORD", lsql); cmd.CommandType = CommandType.StoredProcedure; SqlParameter paramUsername = new SqlParameter("@var1", UserId); cmd.Parameters.Add(paramUsername); SqlDataReader rdr = cmd.ExecuteReader(); while (rdr.Read()) { if (Convert.ToInt32(rdr["RC"]) == 99) { msg = "Unable to update password at this time"; ViewData["ForgotPassword"] = msg; lsql.Close(); return View("ForgotPassword"); } } } msg = "new password sent"; ViewData["ForgotPassword"] = msg; lsql.Close(); return View("ForgotPassword"); } </code></pre> <p>This is my current stored procedure which sends the user an email</p> <pre><code>ALTER PROCEDURE [dbo].[A_SEND_MAIL] @var1 varchar (200), -- userid @var2 varchar (200) -- email address AS BEGIN declare @bodytext varchar(200); set @bodytext = 'Password Reset for user: ' +@var1 + ' @' + cast (getDate() as varchar) + ' ' ; EXEC msdb.dbo.sp_send_dbmail @profile_name='Test', @recipients=@var2, @subject='Password Reset', @body=@bodytext END GO </code></pre>
29,012,284
2
2
null
2015-03-12 14:00:36.623 UTC
13
2020-05-17 22:24:59.22 UTC
null
null
null
null
4,614,967
null
1
15
c#|sql-server|visual-studio-2010|password-recovery
22,205
<p>Create a table that has a structure like</p> <pre><code>create table ResetTickets( username varchar(200), tokenHash varbinary(16), expirationDate datetime, tokenUsed bit) </code></pre> <p>Then in your code when the user clicks the reset password button you will generate a random token then put a entry in that table with the hashed value of that <code>token</code> and a expiration date of something like <code>DATEADD(day, 1, GETDATE())</code> and appends that token value on the url you email to the user for the password reset page.</p> <pre><code>www.example.com/passwordReset?username=Karan&amp;token=ZB71yObR </code></pre> <p>On the password reset page you take the username and token passed in, hash the token again then compare that with the <code>ResetTickets</code> table, and if the expiration date has not passed yet and the token has not been used yet then take the user to a page that lets them enter a new password. </p> <p><strong>Things to be careful about</strong>:</p> <ol> <li><strong>Make sure to expire the token</strong>, don't let a email from two years ago reset the password.</li> <li><strong>Make sure to mark the token as used</strong>, don't let other users of the computer use the browser's history to reset other users passwords.</li> <li><strong>Make sure you generate the random token safely</strong>. Don't use <code>Rand</code> and use it to generate the token, two users who reset at the same time would get the same token (I could reset my password and your password at the same time then use my token to reset your account). Instead make a static <a href="https://msdn.microsoft.com/en-us/library/system.security.cryptography.rngcryptoserviceprovider(v=vs.110).aspx" rel="noreferrer"><code>RNGCryptoServiceProvider</code></a> and use the <code>GetBytes</code> method from that, the class is thread safe so you don't need to worry about two threads using the same instance.</li> <li><strong>Be sure to <a href="https://stackoverflow.com/questions/7505808/using-parameters-in-sql-statements">parameterize your queries</a>.</strong> In your current code if I typed in the userid <code>'; delete dbo.[USERS] --</code> it would delete all the users in your database. See the linked SO post for more info on how to fix it.</li> <li><strong>Be sure you hash the token, your <code>passwordReset</code> page only accepts the unhashed version, and you never store the unhashed version anywhere</strong> (including email logs of outgoing messages to users). This prevents an attacker who has read access to the database from making a token for some other user, reading the value that was sent in the email, then sending the same value himself (and perhaps getting access to an administrator user who can do more stuff than just read values).</li> </ol>
30,150,251
find all prime numbers from array
<p>I want to create a program that will ask the user to input 5 integers using array and determine all the prime numbers entered. But I have difficulty with it. What seems to be the problem? I use JCreator for this.</p> <pre><code>import java.util.Scanner; public class PrimeNumbers{ public static void main (String[] args){ int[] array = new int [5]; Scanner in = new Scanner (System.in); System.out.println(&quot;Enter the elements of the array: &quot;); for(int i=0; i&lt;5; i++) { array[i] = in.nextInt(); } //loop through the numbers one by one for(int i=0; i&lt;array.length; i++){ boolean isPrime = true; //check to see if the numbers are prime for (int j=2; j&lt;array[i]; j++){ if(array[i]%j==0){ isPrime = false; break; } } //print the number if(isPrime) System.out.println(array[i] + &quot; are the prime numbers in the array &quot;); } } } </code></pre>
30,150,386
8
5
null
2015-05-10 10:22:47.017 UTC
null
2022-03-30 11:46:31.323 UTC
2022-03-30 11:46:31.323 UTC
null
16,806,694
null
4,879,433
null
1
-1
java|arrays
66,428
<p>You are checking the loop counters, not the values in the array. Try something like</p> <pre><code>for (int j=2; j&lt;array[i]; j++){ if(array[I]%j==0){ isPrime = false; break; } </code></pre> <p>I haven't tested this.</p> <p><strong>UPDATE</strong></p> <p>To print out the results either print each on as it is found, or, copy the prime numbers into an output array and then print that when you have finished the checks. The details will depend on the language you are using.</p> <p>Please note, you are not using a very efficient detection algorithm; Google for a better one.</p>
9,609,738
Is it possible to pass arguments to a fragment after it's been added to an activity?
<p>I know that when you're first instantiating a fragment you can pass arguments using <code>setArguments(Bundle)</code> and retrieve them in the fragment using <code>getArguments()</code>.</p> <p>However, in my app I have fragments that will be detached and attached several times after they've been added to an activity. On re-attach, I may need to pass a fragment an argument to modify its content prior to reattaching it. I can use <code>setArguments</code> the first time I display the fragment, but on subsequent occasions that won't work. The <code>savedInstanceState</code> will not work in this case as I won't know the value of the argument prior to detaching the fragment.</p> <p>I know I could just implement a method that I would call before attaching the fragment that would set an argument, but it just seems like this is something that might already be in the API and I'm just not seeing it.</p> <p>Is there something built-in that will allow me to do this, or will I have to implement this on my own? For the record, I am using the support package (v4).</p> <p>Many thanks!</p>
9,610,048
4
1
null
2012-03-07 21:58:24.647 UTC
7
2022-07-13 13:34:10.08 UTC
2016-04-17 21:02:16.217 UTC
null
334,493
null
1,192,669
null
1
30
android|android-fragments
22,868
<p>You can just expose a method on your fragment that set whatever you want to pass to it. To call it you can e.g. retrieve the fragment from the backstack by tag or keep an instance reference around from wherever you are calling it from. </p> <p>This works nicely for me although you need to be defensive in terms of null checks and such as well as aware of the lifecyle your fragment goes through when you attach it or restart it.</p> <p>From what I can tell there is nothing in the API... </p> <p>Update: This is still true and works just fine. I found that once this is more complex it is much cleaner and easier to use something like the <a href="http://square.github.com/otto/">Otto</a> eventbus. Highly recommended imho.</p>
9,423,892
How to rotate a flat object around its center in perspective view?
<p>What I'm trying to do seems like it should be easy enough: I created a 2D top-down view of an old phonograph record. I want to rotate it (lay it back) in its X axis and then spin it around its Z axis.</p> <p>I've read every question here that has CATransform3D in the body, I've read Steve Baker's <a href="http://www.sjbaker.org/steve/omniv/matrices_can_be_your_friends.html" rel="noreferrer">"Matrices can be your friends"</a> article as well as Bill Dudney's book "Core Animation for Mac OS X and the iPhone" I think Brad Larson's <a href="http://www.sunsetlakesoftware.com/2008/10/22/3-d-rotation-without-trackball" rel="noreferrer">"3-D Rotation without a trackball"</a> has all the right code, but since he's permitting the user to adjust all three axis, I'm having a hard time shrinking his code into what I perceive to be just one dimension (a rotated z axis).</p> <p>Here's the image I'm testing with, not that the particulars are important to the problem:</p> <p><img src="https://i.stack.imgur.com/EXhku.png" alt="Gold Record"></p> <p>I bring that onscreen the usual way: (in a subclass of UIView)</p> <pre><code>- (void)awakeFromNib { UIImage *recordImage = [UIImage imageNamed:@"3DgoldRecord"]; if (recordImage) { recordLayer = [CALayer layer]; [recordLayer setFrame:CGRectMake(0.0, 0.0, 1024, 1024)]; [recordLayer setContents:(id)[[UIImage imageNamed:@"3DgoldRecord"] CGImage]]; [self.layer addSublayer:recordLayer]; } } </code></pre> <p>That's the first test, just getting it on the screen ;-)</p> <p>Then, to "lay it back" I apply a transform to rotate about the layer's X axis, inserting this code after setting the contents of the layer to the image and before adding the sublayer:</p> <pre><code> CATransform3D myRotationTransform = CATransform3DRotate(recordLayer.transform, (M_PI_2 * 0.85), //experiment with flatness 1.0, // rotate only across the x-axis 0.0, // no y-axis transform 0.0); // no z-axis transform recordLayer.transform = myRotationTransform; </code></pre> <p>That worked as expected: The record is laying back nicely.</p> <p>And for the next step, causing the record to spin, I tied this animation to the touchesEnded event, although once out of the testing/learning phase this rotation won't be under user control:</p> <pre><code>CATransform3D currentTransform = recordLayer.transform; // to come back to at the end CATransform3D myRotationTransform = CATransform3DRotate(currentTransform, 1.0, // go all the way around once (M_PI_2 * 0.85), // x-axis change 1.00, // y-axis change ? 0.0); // z-axis change ? recordLayer.transform = myRotationTransform; CABasicAnimation *myAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"]; myAnimation.duration = 5.0; myAnimation.fromValue = [NSNumber numberWithFloat:0.0]; myAnimation.toValue = [NSNumber numberWithFloat:M_PI * 2.0]; myAnimation.delegate = self; [recordLayer addAnimation:myAnimation forKey:@"transform.rotation"]; </code></pre> <p>So I'm pretty sure what I'm hung up on is the vector in the CATransform3DRotate call (trust me: I've been trying simple changes in that vector to watch the change... what's listed there now is simply the last change I tried). As I understand it, the values for x, y, and z in the transform are, in essence, the percentage of the value passed in during the animation ranging from fromValue to toValue.</p> <p>If I'm on the right track understanding this, is it possible to express this in a single transform? Or must I, for each effective frame of animation, rotate the original upright image slightly around the z axis and then lay the result down with an x axis rotation? I saw a question/answer that talked about combining transforms, but that was a scale transform followed by a rotation transform. I have messed around with transforming the transform, but isn't doing what I think I should be getting (i.e. passing the result of one transform into the transform argument of the next seemed to just execute one completely and then animate the other).</p>
9,425,938
2
1
null
2012-02-24 01:00:38.927 UTC
27
2016-01-07 15:46:48.773 UTC
null
null
null
null
496,969
null
1
31
ios|catransform3d
17,814
<p>This is easiest if you use a <code>CATransformLayer</code> as the parent of the image view's layer. So you'll need a custom view subclass that uses <code>CATransformLayer</code> as its layer. This is trivial:</p> <pre><code>@interface TransformView : UIView @end @implementation TransformView + (Class)layerClass { return [CATransformLayer class]; } @end </code></pre> <p>Put a <code>TransformView</code> in your nib, and add a <code>UIImageView</code> as a subview of the <code>TransformView</code>. Connect these views to outlets in your view controller called <code>transformView</code> and <code>discView</code>.</p> <p>In your view controller, set the transform of <code>transformView</code> to apply perspective (by setting <code>m34</code>) and the X-axis tilt:</p> <pre><code>- (void)viewDidLoad { [super viewDidLoad]; CATransform3D transform = CATransform3DIdentity; transform.m34 = -1 / 500.0; transform = CATransform3DRotate(transform, .85 * M_PI_2, 1, 0, 0); self.transformView.layer.transform = transform; } </code></pre> <p>Add an animation for key path <code>transform.rotation.z</code> to <code>discView</code> in <code>viewWillAppear:</code> and remove it in <code>viewDidDisappear:</code>:</p> <pre><code>- (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"]; animation.fromValue = [NSNumber numberWithFloat:0]; animation.toValue = [NSNumber numberWithFloat:2 * M_PI]; animation.duration = 1.0; animation.repeatCount = HUGE_VALF; animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]; [self.discView.layer addAnimation:animation forKey:@"transform.rotation.z"]; } - (void)viewDidDisappear:(BOOL)animated { [super viewDidDisappear:animated]; [self.discView.layer removeAllAnimations]; } </code></pre> <p>Result:</p> <p><img src="https://i.stack.imgur.com/JI7zA.gif" alt="spinning disc"></p> <h3>UPDATE</h3> <p>Here's a Swift playground demonstration:</p> <pre><code>import UIKit import XCPlayground class TransformView: UIView { override class func layerClass() -&gt; AnyClass { return CATransformLayer.self } } let view = UIView(frame: CGRectMake(0, 0, 300, 150)) view.backgroundColor = UIColor.groupTableViewBackgroundColor() XCPlaygroundPage.currentPage.liveView = view let transformView = TransformView(frame: view.bounds) view.addSubview(transformView) var transform = CATransform3DIdentity transform.m34 = CGFloat(-1) / transformView.bounds.width transform = CATransform3DRotate(transform, 0.85 * CGFloat(M_PI_2), 1, 0, 0) transformView.layer.transform = transform let image = UIImage(named: "3DgoldRecord")! let imageView = UIImageView(image: image) imageView.bounds = CGRectMake(0, 0, 200, 200) imageView.center = CGPointMake(transformView.bounds.midX, transformView.bounds.midY) transformView.addSubview(imageView) let animation = CABasicAnimation(keyPath: "transform.rotation.z") animation.fromValue = 0 animation.toValue = 2 * M_PI animation.duration = 1 animation.repeatCount = Float.infinity animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) imageView.layer.addAnimation(animation, forKey: animation.keyPath) </code></pre> <p>Copy the image from the question into the playground Resources folder and name it <code>3DgoldRecord.png</code>. Result:</p> <p><a href="https://i.stack.imgur.com/jSCcv.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/jSCcv.gif" alt="playground result"></a></p>
32,757,565
java.lang.Long cannot be cast to java.lang.Double
<p>I have a method which takes object as an input and if the input is instanceOF Long then converting the value to double value. Below is the code :</p> <pre><code>public static void main(String[] args) { Long longInstance = new Long(15); Object value = longInstance; convertDouble(value); } static double convertDouble(Object longValue){ double valueTwo = (double)longValue; System.out.println(valueTwo); return valueTwo; } </code></pre> <p>but when I am executing the above code I am getting below exception :</p> <pre><code>Exception in thread "main" java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Double at com.datatypes.LongTest.convertDouble(LongTest.java:12) at com.datatypes.LongTest.main(LongTest.java:8) </code></pre> <p>Kindly let me know why its giving me exception.</p> <p>But if directly try to cast Long object into double then there is no Exception of classCast is coming.</p> <pre><code>Long longInstance = new Long(15); double valueOne = (double)longInstance; System.out.println(valueOne); </code></pre> <p>This is confusing.</p>
32,770,324
5
5
null
2015-09-24 09:12:29.57 UTC
2
2021-06-21 11:52:49.53 UTC
2015-09-24 09:27:26.257 UTC
null
5,254,476
null
5,254,476
null
1
9
java
46,372
<p>Found explaination in JLS, <a href="https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.5" rel="noreferrer">https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.5</a> <br/>Under <strong>Table 5.1. Casting conversions to primitive types</strong></p> <pre><code> Long l = new Long(15); Object o = l; </code></pre> <p>When converting Object Type to primitive then it will <strong>narrowing and then unboxing</strong>.</p> <pre><code> double d1=(double)o; </code></pre> <p>in above statement we are trying to <strong>narrow Object to Double</strong>, but since the <strong>actual value is Long</strong> so at runtime it throws <strong>ClassCastException</strong>, as per narrowing conversion rule defined in <strong>5.1.6. Narrowing Reference Conversion</strong></p> <p>When converting Long Type to double, it will do <strong>unboxing and then widening</strong>.</p> <pre><code> double d2 =(double)l; </code></pre> <p>it will first unbox the Long value by calling longvalue() method and then do the widening from long to double, which can be without error.</p>
46,050,840
sequelize - Cannot add foreign key constraint
<p>I'm trying to set a 1:1 relation between two tables. RefreshToken table will have two foreignKey releated to Users table, as in this image: <a href="https://i.stack.imgur.com/B2fcU.png" rel="noreferrer"><img src="https://i.stack.imgur.com/B2fcU.png" alt="enter image description here"></a></p> <p>I used sequelize-auto to generate my sequelize models.</p> <p><strong>Users model:</strong></p> <pre><code>module.exports = function(sequelize, DataTypes) { return sequelize.define('Users', { idUsers: { type: DataTypes.INTEGER(11), allowNull: false, primaryKey: true }, name: { type: DataTypes.STRING(45), allowNull: true }, mail: { type: DataTypes.STRING(45), allowNull: false, primaryKey: true } }, { tableName: 'Users' }); }; </code></pre> <p><strong>RefreshToken model:</strong></p> <pre><code>module.exports = function(sequelize, DataTypes) { return sequelize.define('RefreshToken', { idRefreshToken: { type: DataTypes.INTEGER(11), allowNull: false, primaryKey: true }, token: { type: DataTypes.TEXT, allowNull: true }, userId: { type: DataTypes.INTEGER(11), allowNull: false, primaryKey: true, references: { model: 'Users', key: 'idUsers' } }, userEmail: { type: DataTypes.STRING(45), allowNull: false, primaryKey: true, references: { model: 'Users', key: 'mail' } } }, { tableName: 'RefreshToken' }); }; </code></pre> <p>When I run the application, I receive this error:</p> <blockquote> <p>Unhandled rejection Error: SequelizeDatabaseError: ER_CANNOT_ADD_FOREIGN: Cannot add foreign key constraint</p> </blockquote> <p>I tried to add explicit the relation, adding in Users table:</p> <pre><code>User.associate = (models) =&gt; { User.hasOne(models.RefreshToken, { foreignKey: 'userId' }); User.hasOne(models.RefreshToken, { foreignKey: 'userEmail' }); }; </code></pre> <p>and in RefreshToken:</p> <pre><code>RefreshToken.associate = (models) =&gt; { RefreshToken.belongsTo(models.Users, { foreignKey: 'userId' }); RefreshToken.belongsTo(models.Users, { foreignKey: 'userEmail' }); }; </code></pre> <p>But I receive again the same error. If I remove the references in the RefreshToken table I don't see any error, but when I check the database I don't see any foreign key relation constraint with email and id of the User</p>
52,470,901
2
3
null
2017-09-05 08:53:27.093 UTC
5
2018-09-23 22:51:05.59 UTC
null
null
null
null
4,105,895
null
1
20
javascript|mysql|node.js|express|sequelize.js
40,657
<p>This is common type error mainly occurs because of </p> <h3>1. When the primary key data type and the foreign key <strong>data type</strong> did not matched</h3> <pre><code>return sequelize.define('RefreshToken', { userId: { type: DataTypes.INTEGER(11), // The data type defined here and references: { model: 'Users', key: 'idUsers' } }, return sequelize.define('Users', { idUsers: { type: DataTypes.INTEGER(11), // This data type should be the same }, </code></pre> <hr> <h3>2. When the referenced key is not a primary or unique key.</h3> <p>You can not have two primary keys, so other referenced keys should be defined unique. <code>unique:true</code></p> <pre><code> return sequelize.define('Users', { idUsers: { primaryKey: true }, mail: { type: DataTypes.STRING(45), allowNull: false, primaryKey: true // You should change this to 'unique:true'. you cant hv two primary keys in one table. } </code></pre>
56,263,200
How to define string literal union type from constants in Typescript
<p>I know I can define string union types to restrict variables to one of the possible string values:</p> <pre><code>type MyType = 'first' | 'second' let myVar:MyType = 'first' </code></pre> <p>I need to construct a type like that from constant strings, e.g:</p> <pre><code>const MY_CONSTANT = 'MY_CONSTANT' const SOMETHING_ELSE = 'SOMETHING_ELSE' type MyType = MY_CONSTANT | SOMETHING_ELSE </code></pre> <p>But for some reason it doesn't work; it says <code>MY_CONSTANT refers to a value, but it being used as a type here</code>.</p> <p>Why does Typescript allow the first example, but doesn't allow the second case? I'm on Typescript 3.4.5</p>
56,263,257
4
5
null
2019-05-22 18:50:21.17 UTC
3
2022-07-05 20:56:54.687 UTC
null
null
null
null
811,405
null
1
80
typescript|string-literals|typescript3.0|union-types
36,026
<p>To get the type of a variable you need to use the <code>typeof</code> type operator:</p> <pre><code>const MY_CONSTANT = 'MY_CONSTANT' // must be const, no annotation. let or var will not work const SOMETHING_ELSE = 'SOMETHING_ELSE' // must be const, no annotation. let or var will not work type MyType = typeof MY_CONSTANT | typeof SOMETHING_ELSE </code></pre> <p><a href="https://www.typescriptlang.org/play/#code/MYewdgzgLgBAsgTQPoGEDyA5AygFQIIY4wC8MA5IqprgTmQFCiSxZpwCiOAEgJIYDiSdgBks7EuVYdufQSLEMoATwAOAU3hKcqjaWXqQAM3jJ02fIRgAfGPrVGYUzrwFDR7evQA2a2AA8ALk1tdQBuej8JACIomBgAeniYNQAnFJAUiOjKMxpCKKA" rel="noreferrer">Playground</a></p> <p><strong>Note:</strong></p> <p>Since there seems to be a lot of confusion when people use this. The <code>const</code> matters. If you use other types of declarations (<code>let</code> or <code>var</code>) the final type would be string. Only <code>const </code> preserves string literal types.</p> <p><strong>Note 2:</strong></p> <p>For this solution to work you must <strong>not</strong> specify any type annotation on the <code>const</code>, and let the compiler infer the type of the constants (ex this will <strong>not work</strong> :<code>const MY_CONSTANT: string = 'MY_CONSTANT'</code>)</p>
24,731,791
Is double read atomic on an Intel architecture?
<p>My colleague and I are having an argument on atomicity of reading a double on an Intel architecture using C# .NET 4.0. He is arguing that we should use <code>Interlocked.Exchange</code> method for writing into a <code>double</code>, but just reading the double value (in some other thread) is guaranteed to be atomic. My argument is that .NET doesn't guarantee this atomicity, but his argument is that on an Intel architecture this is guaranteed (maybe not on <a href="https://en.wikipedia.org/wiki/List_of_AMD_chipsets">AMD</a>, <a href="http://en.wikipedia.org/wiki/SPARC">SPARC</a>, etc.). </p> <p>Any Intel and .NET experts share some lights on this?</p> <p>Reader is OK to read a stale (previous) value, but not incorrect value (partial read before and after write giving a garbage value).</p>
24,731,936
3
3
null
2014-07-14 07:45:49.23 UTC
2
2014-07-15 09:46:33.67 UTC
2014-07-15 00:32:04.197 UTC
null
63,550
null
899,811
null
1
30
c#|.net|intel
4,276
<p>Yes and no. On 32-bit processors, it is not guaranteed atomic, because double is larger than the native wordsize. On a 64-bit processor properly aligned access is atomic. The 64-bit <a href="http://en.wikipedia.org/wiki/Common_Language_Infrastructure" rel="nofollow noreferrer">CLI</a> guarantees everything up to a 64-bit read as atomic. So you'd need to build your assembly for <em>x64</em> (not <em>Any CPU</em>). Otherwise if your assembly may be run on 32-bit, you better use <strong>Interlocked</strong>, see <em><a href="http://blogs.msdn.com/b/ericlippert/archive/2011/05/31/atomicity-volatility-and-immutability-are-different-part-two.aspx" rel="nofollow noreferrer">Atomicity, volatility and immutability are different, part two</a></em> by Eric Lippert. I think you can rely on Eric Lippert's knowledge of the Microsoft <a href="http://en.wikipedia.org/wiki/Common_Language_Runtime" rel="nofollow noreferrer">CLR</a>.</p> <p>The ECMA CLI standard also supports this, even though C# itself does not guarantee it:</p> <blockquote> <p>A conforming CLI shall guarantee that read and write access to properly aligned memory locations no larger than the native word size (the size of type native int) is atomic (see §I.12.6.2)</p> </blockquote> <p>It also says that on processors where operations are atomic, <strong>Interlocked</strong> methods are often compiled to a single instruction, so in my book there is no performance penalty in using it. On the other hand, there may be a worse penalty to not using it when you should.</p> <p>Another related Stack Overflow question is <em><a href="https://stackoverflow.com/questions/11745440">What operations are atomic in C#?</a></em>.</p>
732,272
Best Way to Build a Game Map
<p>I'm in the process of writing a small overhead view RPG much in the vein of the classic Ultima series. I need a quick and dirty (more quick than dirty) way of designing large maps - say 1000 tiles x 1000 tiles, and i need some help thinking through how to go about doing this. </p> <p>I would say there are a good 50-60 different types of tiles - woods, rivers, plains, etc. </p> <p>So far, the best I could come up with was</p> <ul> <li><p>define an array (or some similar structure) to hold two key pieces of information - a location/coordinate identifier, and an integer from 1-60 defining what type of tile it is. </p></li> <li><p>in a raster editing application, draw a 1000px x 1000px image. Using a palette of 50 different colors, i draw my map - 1 pixel corresponds to 1 tile. Say for a given water tile, i'll draw a group of pixels in a certain shade of blue. Save as a .gif or .png.</p></li> <li><p>write some processor that then analyzes the aforementioned gif/jpg and analyze it pixel by pixel. Depending on the RGB value of the pixel, it determines the tile type. Processor then code-generates some routines that populate the map array. </p></li> </ul> <p>So far, i'm thinking there must be an easier way. </p>
732,284
5
0
null
2009-04-08 23:26:38.297 UTC
9
2009-04-09 20:59:29.457 UTC
null
null
null
null
85,942
null
1
10
language-agnostic
6,880
<p>Try sourceforge: <a href="http://sourceforge.net/search/?type_of_search=soft&amp;words=tile+editor" rel="nofollow noreferrer">http://sourceforge.net/search/?type_of_search=soft&amp;words=tile+editor</a></p> <p>Several of those editors will save out to some standard format, which you can then pull into your game as you like.</p> <p><a href="http://tilestudio.sourceforge.net/" rel="nofollow noreferrer">TileStudio</a> will even output header/source files that can be compiled directly into your engine (not sure what your needs are)</p>
787,894
Ruby-OpenID: Requiring email-address from OpenID provider
<p>I'm playing with the <a href="http://github.com/binarylogic/authlogic_example/tree/with-openid" rel="nofollow noreferrer">authlogic-example-app</a> and I'm failing to get the email address from the OpenID provider (in my case: Google and Yahoo) when I register a user, resp. I get an empty response instead of an email address (check the comments in code below).</p> <p>This is how my user model looks like (everything else looks like the "with_openid"-branch of the authlogic-example-app mentioned above). Besides the missing 'email', the openid-authentication-process works as expected:</p> <pre><code>class User &lt; ActiveRecord::Base acts_as_authentic do |c| # not needed because I use OpenID c.validate_login_field = false # avoid failed validation before OpenID request c.validate_email_field = false # this one sets 'openid.sreg.required=email' c.required_fields = [:email] end private # overwriting the existing method in '/lib/authlogic_openid/acts_as_authentic.rb' def map_openid_registration(registration) # this is my problem: 'registration' is an empty hash self.email ||= registration[:email] if respond_to?(:email) &amp;&amp; !registration[:email].blank? end end </code></pre> <p>Any idea how to solve this? Has anyone here done this before using <a href="http://github.com/binarylogic/authlogic_openid/tree/master" rel="nofollow noreferrer">authlogic</a>? Or even better: Do you have a working example?</p> <p><strong>Update</strong>: I checked the <a href="http://code.google.com/apis/accounts/docs/OpenID.html" rel="nofollow noreferrer">Google Account Authentication API</a> and compared the request submitted by <a href="http://github.com/binarylogic/authlogic_openid/tree/master" rel="nofollow noreferrer">authlogic</a> (using <a href="http://openidenabled.com/ruby-openid/" rel="nofollow noreferrer">ruby-openid-gem</a> and <a href="http://github.com/rails/open_id_authentication/tree/master" rel="nofollow noreferrer">openid-authentication-plugin</a>) with the <a href="http://code.google.com/apis/accounts/docs/OpenID.html#Samples" rel="nofollow noreferrer">example requests</a> on the Google Account Authentication API docs:</p> <hr> <p><strong>Example request to authenticate and fetch email address by Google</strong>:</p> <pre><code>https://www.google.com/accounts/o8/ud ?openid.ns=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0 &amp;openid.claimed_id=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select &amp;openid.identity=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select &amp;openid.return_to=http%3A%2F%2Fwww.example.com%2Fcheckauth &amp;openid.realm=http%3A%2F%2Fwww.example.com%2F &amp;openid.assoc_handle=ABSmpf6DNMw &amp;openid.mode=checkid_setup &amp;openid.ns.ext1=http%3A%2F%2Fopenid.net%2Fsrv%2Fax%2F1.0 &amp;openid.ext1.mode=fetch_request &amp;openid.ext1.type.email=http%3A%2F%2Faxschema.org%2Fcontact%2Femail &amp;openid.ext1.required=email </code></pre> <hr> <p><strong>Request submitted by my appliation</strong>:</p> <pre><code>https://www.google.com/accounts/o8/ud ?openid.assoc_handle=AOQobUcdICerEyK6SXJfukaz8ygXiBqF_gKXv68OBtPXmeafBSdZ6576 &amp;openid.ax.mode=fetch_request &amp;openid.claimed_id=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select &amp;openid.identity=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select &amp;openid.mode=checkid_setup &amp;openid.ns=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0 &amp;openid.ns.ax=http%3A%2F%2Fopenid.net%2Fsrv%2Fax%2F1.0 &amp;openid.ns.sreg=http%3A%2F%2Fopenid.net%2Fextensions%2Fsreg%2F1.1 &amp;openid.realm=http%3A%2F%2Flocalhost%3A3000%2F &amp;openid.return_to=http%3A%2F%2Flocalhost%3A3000%2Faccount%3Ffor_model%3D1%26_method%3Dpost%26open_id_complete%3D1 &amp;openid.sreg.required=email </code></pre> <p>While debugging the whole setup, I've found out that the <a href="http://github.com/rails/open_id_authentication/tree/master" rel="nofollow noreferrer">openid-authentication-plugin</a> never receives an email in the response it receives from the openid provider, this at least explains why the <code>registration</code> hash in my user-model is empty...</p> <p><strong>UPDATE</strong>: If you're playing around with authlogic and openid, don't forget to check out the <a href="http://railscasts.com/episodes/170-openid-with-authlogic" rel="nofollow noreferrer">latest railscast on this subject</a>!</p>
809,540
5
0
null
2009-04-25 00:04:28.28 UTC
12
2010-02-04 03:12:09.623 UTC
2009-07-13 19:31:05.31 UTC
null
61,427
null
61,427
null
1
10
ruby-on-rails|ruby|openid|authlogic|ruby-openid
3,352
<p>As nobody could help me, I helped myself. :-)</p> <p>The short answer to my question is:</p> <pre><code>c.required_fields = [:email,"http://axschema.org/contact/email"] </code></pre> <p>Using this line, the application requests the email-address using sreg and ax (request-type supported by Google).</p> <p>You can find a more detailed answer and a working implementation of authlogic-openid with the <a href="http://code.google.com/p/openid-selector/" rel="nofollow noreferrer">Javascript OpenID-Selector</a> right here:</p> <p><a href="http://github.com/vazqujav/authlogic_openid_selector_example/" rel="nofollow noreferrer">http://github.com/vazqujav/authlogic_openid_selector_example/</a></p>
1,268,174
PHP's strtotime() in Java
<p>strtotime() in PHP can do the following transformations:</p> <p>Inputs:</p> <pre> strtotime(’2004-02-12T15:19:21+00:00′); strtotime(’Thu, 21 Dec 2000 16:01:07 +0200′); strtotime(’Monday, January 1st’); strtotime(’tomorrow’); strtotime(’-1 week 2 days 4 hours 2 seconds’); </pre> <p>Outputs:</p> <pre> 2004-02-12 07:02:21 2000-12-21 06:12:07 2009-01-01 12:01:00 2009-02-12 12:02:00 2009-02-06 09:02:41 </pre> <p>Is there an easy way to do this in java?</p> <p>Yes, this is a <a href="https://stackoverflow.com/questions/1236678/phps-strtotime-in-java">duplicate</a>. However, the original question was not answered. I typically need the ability to query dates from the past. I want to give the user the ability to say 'I want all events from "-1 week" to "now"'. It will make scripting these types of requests much easier.</p>
1,268,380
5
1
null
2009-08-12 19:19:31.613 UTC
9
2013-11-08 14:37:38.403 UTC
2017-05-23 11:53:35.447 UTC
null
-1
null
125,380
null
1
26
java|php|strtotime
12,896
<p>I tried to implement a simple (static) class that emulates some of the patterns of PHP's <code>strtotime</code>. This class is designed to be <strong>open for modification</strong> (simply add a new <code>Matcher</code> via <code>registerMatcher</code>):</p> <pre><code>public final class strtotime { private static final List&lt;Matcher&gt; matchers; static { matchers = new LinkedList&lt;Matcher&gt;(); matchers.add(new NowMatcher()); matchers.add(new TomorrowMatcher()); matchers.add(new DateFormatMatcher(new SimpleDateFormat("yyyy.MM.dd G 'at' HH:mm:ss z"))); matchers.add(new DateFormatMatcher(new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z"))); matchers.add(new DateFormatMatcher(new SimpleDateFormat("yyyy MM dd"))); // add as many format as you want } // not thread-safe public static void registerMatcher(Matcher matcher) { matchers.add(matcher); } public static interface Matcher { public Date tryConvert(String input); } private static class DateFormatMatcher implements Matcher { private final DateFormat dateFormat; public DateFormatMatcher(DateFormat dateFormat) { this.dateFormat = dateFormat; } public Date tryConvert(String input) { try { return dateFormat.parse(input); } catch (ParseException ex) { return null; } } } private static class NowMatcher implements Matcher { private final Pattern now = Pattern.compile("now"); public Date tryConvert(String input) { if (now.matcher(input).matches()) { return new Date(); } else { return null; } } } private static class TomorrowMatcher implements Matcher { private final Pattern tomorrow = Pattern.compile("tomorrow"); public Date tryConvert(String input) { if (tomorrow.matcher(input).matches()) { Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.DAY_OF_YEAR, +1); return calendar.getTime(); } else { return null; } } } public static Date strtotime(String input) { for (Matcher matcher : matchers) { Date date = matcher.tryConvert(input); if (date != null) { return date; } } return null; } private strtotime() { throw new UnsupportedOperationException(); } } </code></pre> <h2>Usage</h2> <p>Basic usage:</p> <pre><code> Date now = strtotime("now"); Date tomorrow = strtotime("tomorrow"); </code></pre> <pre> Wed Aug 12 22:18:57 CEST 2009 Thu Aug 13 22:18:57 CEST 2009 </pre> <h2>Extending</h2> <p>For example let's add <strong>days matcher</strong>:</p> <pre><code>strtotime.registerMatcher(new Matcher() { private final Pattern days = Pattern.compile("[\\-\\+]?\\d+ days"); public Date tryConvert(String input) { if (days.matcher(input).matches()) { int d = Integer.parseInt(input.split(" ")[0]); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.DAY_OF_YEAR, d); return calendar.getTime(); } return null; } }); </code></pre> <p>then you can write:</p> <pre><code>System.out.println(strtotime("3 days")); System.out.println(strtotime("-3 days")); </code></pre> <p>(now is <code>Wed Aug 12 22:18:57 CEST 2009</code>)</p> <pre> Sat Aug 15 22:18:57 CEST 2009 Sun Aug 09 22:18:57 CEST 2009 </pre>
653,887
Equivalent for LinkedHashMap in Python
<p><a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/LinkedHashMap.html" rel="noreferrer">LinkedHashMap</a> is the Java implementation of a Hashtable like data structure (dict in Python) with predictable iteration order. That means that during a traversal over all keys, they are ordered by insertion. This is done by an additional linked list maintaining the insertion order.</p> <p>Is there an equivalent to that in Python? </p>
653,987
5
0
null
2009-03-17 11:46:11.223 UTC
3
2020-03-30 12:25:07.113 UTC
2009-03-17 11:49:48.127 UTC
John Nolan
1,116
dmeister
4,194
null
1
29
python
20,618
<p>If you're on Python 2.7 or Python >=3.1 you can use <a href="https://docs.python.org/2/library/collections.html#collections.OrderedDict" rel="noreferrer">collections.OrderedDict</a> in the standard library.</p> <p><a href="https://stackoverflow.com/questions/60848/how-do-you-retrieve-items-from-a-dictionary-in-the-order-that-theyre-inserted/61031#61031">This answer</a> to the question <a href="https://stackoverflow.com/questions/60848/how-do-you-retrieve-items-from-a-dictionary-in-the-order-that-theyre-inserted">How do you retrieve items from a dictionary in the order that they’re inserted?</a> contains an implementation of an ordered dict, in case you're not using Python 3.x and don't want to give yourself a dependency on the third-party <a href="http://www.xs4all.nl/~anthon/Python/ordereddict/" rel="noreferrer">ordereddict module</a>.</p>
1,084,194
Is it possible to add HTML5 validation to Visual Studio?
<p>I'm working on a page using <code>&lt;canvas&gt;</code>, which is a HTML5 tag, in Visual Web Developer Express Edition 2008, and the validator in the HTML editor is telling me it's an invalid tag. That's because it's set to validate against XHTML 1.0 Transitional. I'd prefer for it to not do that and tell me what's valid or invalid based on the HTML5 doctype, but I can't find anywhere in the preferences that suggests this would be possible.</p> <p>Is there a way to tell Visual Studio to validate against HTML5, or add a new spec reference manually? I'd prefer not to have to go in and add tags manually, which appears to be the only option at the moment.</p>
1,848,536
5
1
null
2009-07-05 14:42:45.06 UTC
10
2012-03-06 20:20:02.823 UTC
null
null
null
null
16,308
null
1
36
visual-studio|validation|html|visual-web-developer
29,161
<p>It looks like the Visual Web Developer team solved the problem by adding HTML5 support themselves: <a href="http://blogs.msdn.com/webdevtools/archive/2009/11/18/html-5-intellisense-and-validation-schema-for-visual-studio-2008-and-visual-web-developer.aspx" rel="noreferrer">http://blogs.msdn.com/webdevtools/archive/2009/11/18/html-5-intellisense-and-validation-schema-for-visual-studio-2008-and-visual-web-developer.aspx</a></p> <blockquote> <p>You all probably know that new HTML 5 standard is coming. We made a new intellisense schema that you can add to VS 2008 or VWD Express 2008 and get intellisense and validation on HTML 5 elements.</p> </blockquote>
120,180
How to do query auto-completion/suggestions in Lucene?
<p>I'm looking for a way to do query auto-completion/suggestions in Lucene. I've Googled around a bit and played around a bit, but all of the examples I've seen seem to be setting up filters in Solr. We don't use Solr and aren't planning to move to using Solr in the near future, and Solr is obviously just wrapping around Lucene anyway, so I imagine there must be a way to do it!</p> <p>I've looked into using EdgeNGramFilter, and I realise that I'd have to run the filter on the index fields and get the tokens out and then compare them against the inputted Query... I'm just struggling to make the connection between the two into a bit of code, so help is much appreciated!</p> <p>To be clear on what I'm looking for (I realised I wasn't being overly clear, sorry) - I'm looking for a solution where when searching for a term, it'd return a list of suggested queries. When typing 'inter' into the search field, it'll come back with a list of suggested queries, such as 'internet', 'international', etc.</p>
121,456
5
1
null
2008-09-23 10:12:10.56 UTC
56
2019-05-22 07:55:16.153 UTC
2012-07-11 21:21:04.813 UTC
Gortok
416,224
Mat Mannion
6,282
null
1
51
java|autocomplete|lucene
54,935
<p>Based on @Alexandre Victoor's answer, I wrote a little class based on the Lucene Spellchecker in the contrib package (and using the LuceneDictionary included in it) that does exactly what I want.</p> <p>This allows re-indexing from a single source index with a single field, and provides suggestions for terms. Results are sorted by the number of matching documents with that term in the original index, so more popular terms appear first. Seems to work pretty well :)</p> <pre><code>import java.io.IOException; import java.io.Reader; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.ISOLatin1AccentFilter; import org.apache.lucene.analysis.LowerCaseFilter; import org.apache.lucene.analysis.StopFilter; import org.apache.lucene.analysis.TokenStream; import org.apache.lucene.analysis.ngram.EdgeNGramTokenFilter; import org.apache.lucene.analysis.ngram.EdgeNGramTokenFilter.Side; import org.apache.lucene.analysis.standard.StandardFilter; import org.apache.lucene.analysis.standard.StandardTokenizer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.index.CorruptIndexException; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.Term; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.Sort; import org.apache.lucene.search.TermQuery; import org.apache.lucene.search.TopDocs; import org.apache.lucene.search.spell.LuceneDictionary; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; /** * Search term auto-completer, works for single terms (so use on the last term * of the query). * &lt;p&gt; * Returns more popular terms first. * * @author Mat Mannion, [email protected] */ public final class Autocompleter { private static final String GRAMMED_WORDS_FIELD = "words"; private static final String SOURCE_WORD_FIELD = "sourceWord"; private static final String COUNT_FIELD = "count"; private static final String[] ENGLISH_STOP_WORDS = { "a", "an", "and", "are", "as", "at", "be", "but", "by", "for", "i", "if", "in", "into", "is", "no", "not", "of", "on", "or", "s", "such", "t", "that", "the", "their", "then", "there", "these", "they", "this", "to", "was", "will", "with" }; private final Directory autoCompleteDirectory; private IndexReader autoCompleteReader; private IndexSearcher autoCompleteSearcher; public Autocompleter(String autoCompleteDir) throws IOException { this.autoCompleteDirectory = FSDirectory.getDirectory(autoCompleteDir, null); reOpenReader(); } public List&lt;String&gt; suggestTermsFor(String term) throws IOException { // get the top 5 terms for query Query query = new TermQuery(new Term(GRAMMED_WORDS_FIELD, term)); Sort sort = new Sort(COUNT_FIELD, true); TopDocs docs = autoCompleteSearcher.search(query, null, 5, sort); List&lt;String&gt; suggestions = new ArrayList&lt;String&gt;(); for (ScoreDoc doc : docs.scoreDocs) { suggestions.add(autoCompleteReader.document(doc.doc).get( SOURCE_WORD_FIELD)); } return suggestions; } @SuppressWarnings("unchecked") public void reIndex(Directory sourceDirectory, String fieldToAutocomplete) throws CorruptIndexException, IOException { // build a dictionary (from the spell package) IndexReader sourceReader = IndexReader.open(sourceDirectory); LuceneDictionary dict = new LuceneDictionary(sourceReader, fieldToAutocomplete); // code from // org.apache.lucene.search.spell.SpellChecker.indexDictionary( // Dictionary) IndexReader.unlock(autoCompleteDirectory); // use a custom analyzer so we can do EdgeNGramFiltering IndexWriter writer = new IndexWriter(autoCompleteDirectory, new Analyzer() { public TokenStream tokenStream(String fieldName, Reader reader) { TokenStream result = new StandardTokenizer(reader); result = new StandardFilter(result); result = new LowerCaseFilter(result); result = new ISOLatin1AccentFilter(result); result = new StopFilter(result, ENGLISH_STOP_WORDS); result = new EdgeNGramTokenFilter( result, Side.FRONT,1, 20); return result; } }, true); writer.setMergeFactor(300); writer.setMaxBufferedDocs(150); // go through every word, storing the original word (incl. n-grams) // and the number of times it occurs Map&lt;String, Integer&gt; wordsMap = new HashMap&lt;String, Integer&gt;(); Iterator&lt;String&gt; iter = (Iterator&lt;String&gt;) dict.getWordsIterator(); while (iter.hasNext()) { String word = iter.next(); int len = word.length(); if (len &lt; 3) { continue; // too short we bail but "too long" is fine... } if (wordsMap.containsKey(word)) { throw new IllegalStateException( "This should never happen in Lucene 2.3.2"); // wordsMap.put(word, wordsMap.get(word) + 1); } else { // use the number of documents this word appears in wordsMap.put(word, sourceReader.docFreq(new Term( fieldToAutocomplete, word))); } } for (String word : wordsMap.keySet()) { // ok index the word Document doc = new Document(); doc.add(new Field(SOURCE_WORD_FIELD, word, Field.Store.YES, Field.Index.UN_TOKENIZED)); // orig term doc.add(new Field(GRAMMED_WORDS_FIELD, word, Field.Store.YES, Field.Index.TOKENIZED)); // grammed doc.add(new Field(COUNT_FIELD, Integer.toString(wordsMap.get(word)), Field.Store.NO, Field.Index.UN_TOKENIZED)); // count writer.addDocument(doc); } sourceReader.close(); // close writer writer.optimize(); writer.close(); // re-open our reader reOpenReader(); } private void reOpenReader() throws CorruptIndexException, IOException { if (autoCompleteReader == null) { autoCompleteReader = IndexReader.open(autoCompleteDirectory); } else { autoCompleteReader.reopen(); } autoCompleteSearcher = new IndexSearcher(autoCompleteReader); } public static void main(String[] args) throws Exception { Autocompleter autocomplete = new Autocompleter("/index/autocomplete"); // run this to re-index from the current index, shouldn't need to do // this very often // autocomplete.reIndex(FSDirectory.getDirectory("/index/live", null), // "content"); String term = "steve"; System.out.println(autocomplete.suggestTermsFor(term)); // prints [steve, steven, stevens, stevenson, stevenage] } } </code></pre>
1,196,059
iTextSharp - Sending in-memory pdf in an email attachment
<p>I've asked a couple of questions here but am still having issues. I'd appreciate if you could tell me what I am doing wrong in my code. I run the code above from a ASP.Net page and get "Cannot Access a Closed Stream". </p> <pre><code>var doc = new Document(); MemoryStream memoryStream = new MemoryStream(); PdfWriter.GetInstance(doc, memoryStream); doc.Open(); doc.Add(new Paragraph("First Paragraph")); doc.Add(new Paragraph("Second Paragraph")); doc.Close(); //if I remove this line the email attachment is sent but with 0 bytes MailMessage mm = new MailMessage("[email protected]", "[email protected]") { Subject = "subject", IsBodyHtml = true, Body = "body" }; mm.Attachments.Add(new Attachment(memoryStream, "test.pdf")); SmtpClient smtp = new SmtpClient { Host = "smtp.gmail.com", Port = 587, EnableSsl = true, Credentials = new NetworkCredential("[email protected]", "my_password") }; smtp.Send(mm); //the "Cannot Access a Closed Stream" error is thrown here </code></pre> <p>Thanks!!!</p> <h2>EDIT:</h2> <p>Just to help somebody looking for the answer to this question, the code to send a pdf file attached to an email without having to physically create the file is below (thanks to Ichiban and Brianng):</p> <pre><code>var doc = new Document(); MemoryStream memoryStream = new MemoryStream(); PdfWriter writer = PdfWriter.GetInstance(doc, memoryStream); doc.Open(); doc.Add(new Paragraph("First Paragraph")); doc.Add(new Paragraph("Second Paragraph")); writer.CloseStream = false; doc.Close(); memoryStream.Position = 0; MailMessage mm = new MailMessage("[email protected]", "[email protected]") { Subject = "subject", IsBodyHtml = true, Body = "body" }; mm.Attachments.Add(new Attachment(memoryStream, "filename.pdf")); SmtpClient smtp = new SmtpClient { Host = "smtp.gmail.com", Port = 587, EnableSsl = true, Credentials = new NetworkCredential("[email protected]", "password") }; smtp.Send(mm); </code></pre>
1,196,125
5
6
null
2009-07-28 18:54:17.423 UTC
22
2015-07-17 11:49:07.717 UTC
2009-07-28 22:19:04.047 UTC
null
28,029
null
28,029
null
1
101
c#|email|pdf|itextsharp
52,719
<p>Have you tried:</p> <pre><code>PdfWriter writer = PdfWriter.GetInstance(doc, memoryStream); // Build pdf code... writer.CloseStream = false; doc.Close(); // Build email memoryStream.Position = 0; mm.Attachments.Add(new Attachment(memoryStream, "test.pdf")); </code></pre> <p>If my memory serves me correctly, this solved a similar problem in a previous project.</p> <p>See <a href="http://forums.asp.net/t/1093198.aspx" rel="noreferrer">http://forums.asp.net/t/1093198.aspx</a></p>
1,289,557
How do you discover model attributes in Rails?
<p>I am finding it difficult to easily see what attributes/properties exist on all of my model classes since they are not explicitly defined in my class files.</p> <p>To discover model attributes, I keep the schema.rb file open and flip between it and whatever code I'm writing as needed. This works but is clunky because I have to switch between reading the schema file to pick up attributes, the model class file to check methods, and whatever new code that I'm writing to call attributes &amp; methods. </p> <p>My question is, how do you discover model attributes when you're analyzing a Rails codebase for the first time? Do you keep the schema.rb file open all the time, or is there a better way that doesn't involve jumping between schema file &amp; model file constantly? </p>
1,291,395
5
1
null
2009-08-17 18:21:38.52 UTC
75
2020-05-12 09:10:15.037 UTC
2018-06-09 13:30:15.21 UTC
null
1,029,146
null
1,667
null
1
176
ruby-on-rails|activerecord
123,223
<p>For Schema related stuff</p> <pre><code>Model.column_names Model.columns_hash Model.columns </code></pre> <p>For instance variables/attributes in an AR object</p> <pre><code>object.attribute_names object.attribute_present? object.attributes </code></pre> <p>For instance methods without inheritance from super class</p> <pre><code>Model.instance_methods(false) </code></pre>
547,074
SQL Server: How do I add a constraint to an existing table but only if the constraint does not already exist?
<p>I need to add a constraint to an existing SQL server table but only if it does not already exist.</p> <p>I am creating the constraint using the following SQL.</p> <pre><code>ALTER TABLE [Foo] ADD CONSTRAINT [FK_Foo_Bar] FOREIGN KEY ([BarId]) REFERENCES [Bar] ([BarId]) ON UPDATE CASCADE ON DELETE CASCADE </code></pre> <p>I'm hoping I can add some SQL to the begining of the SQL to test for the existence of the constraint but I have no idea how.</p>
547,090
6
0
null
2009-02-13 18:16:30.817 UTC
2
2019-02-01 10:06:40.967 UTC
null
null
null
jmatthias
2,768
null
1
19
sql-server|sql-server-2005
44,532
<p>Personally I would drop the existing constraint, and recreate it - in case the one that is already there is in some way different</p> <pre><code>IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[MyFKName]') AND OBJECTPROPERTY(id, N'IsForeignKey') = 1) ALTER TABLE dbo.MyTableName DROP CONSTRAINT MyFKName GO ALTER TABLE dbo.MyTableName ADD CONSTRAINT [MyFKName] ... </code></pre> <p>The current, more modern, code I am using is:</p> <pre><code>IF EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[MyFKName]') AND parent_object_id = OBJECT_ID(N'[dbo].[MyTableName]')) ALTER TABLE dbo.[MyTableName] DROP CONSTRAINT [MyFKName] GO ALTER TABLE dbo.[MyTableName] ADD CONSTRAINT [MyFKName] FOREIGN KEY ... </code></pre> <p>not sure if there is any advantage of checking sys.objects ... or sys.foreign_keys ... but at some point I decided on sys.foreign_keys</p> <p>Starting with SQL2016 new "IF EXISTS" syntax was added which is a lot more readable:</p> <pre><code>-- For SQL2016 onwards: ALTER TABLE dbo.[MyTableName] DROP CONSTRAINT IF EXISTS [MyFKName] GO ALTER TABLE dbo.[MyTableName] ADD CONSTRAINT [MyFKName] FOREIGN KEY ... </code></pre>
1,221,512
When to use abstract class or interface?
<p>Why are abstract or interface classes created, or when should we use abstract or interface classes?</p>
1,221,524
6
3
null
2009-08-03 09:59:17.853 UTC
21
2018-04-23 19:01:39.77 UTC
2011-11-11 22:40:56.627 UTC
user166390
null
null
148,453
null
1
28
java|interface|abstract-class
30,456
<p>Interface is used when you only want to declare which methods and members a class MUST have. Anyone implementing the interface will have to declare and implement the methods listed by the interface.</p> <p>If you also want to have a default implementation, use abstract class. Any class extending the abstract class will have to implement only its abstract methods and members, and will have some default implementation of the other methods of the abstract class, which you may override or not.</p> <p>--EDIT - forgot to mention, Earwicker reminded me</p> <p>Finally, you can implement as many interfaces as you want, but only extend one class (being it abstract or not). Keep that in mind before choosing.</p>
303,488
In PHP how can you clear a WSDL cache?
<p>In through <code>php_info()</code> where the WSDL cache is held (<code>/tmp</code>), but I don't necessarily know if it is safe to delete all files starting with WSDL. </p> <p>Yes, I <em>should</em> be able to just delete everything from <code>/tmp</code>, but I don't know what else this could effect if I delete any all WSDL files.</p>
303,514
6
0
null
2008-11-19 21:46:57.733 UTC
9
2020-01-23 17:49:17.153 UTC
2017-02-21 14:17:57.913 UTC
null
1,306,684
jW
8,880
null
1
97
php|soap|caching|wsdl
150,530
<p>You can safely delete the WSDL cache files. If you wish to prevent future caching, use:</p> <pre><code>ini_set("soap.wsdl_cache_enabled", 0); </code></pre> <p>or dynamically:</p> <pre><code>$client = new SoapClient('http://somewhere.com/?wsdl', array('cache_wsdl' =&gt; WSDL_CACHE_NONE) ); </code></pre>
392,721
Difference between shadowing and overriding in C#?
<p>What's difference between <strong>shadowing</strong> and <strong>overriding</strong> a method in C#?</p>
392,727
6
0
null
2008-12-25 10:45:53.133 UTC
45
2020-03-26 19:25:46.78 UTC
2008-12-29 18:04:15.167 UTC
Jay Bazuzi
5,314
Jox
35,425
null
1
107
c#
84,933
<p>Well inheritance...</p> <p>suppose you have this classes:</p> <pre><code>class A { public int Foo(){ return 5;} public virtual int Bar(){return 5;} } class B : A{ public new int Foo() { return 1;} //shadow public override int Bar() {return 1;} //override } </code></pre> <p>then when you call this:</p> <pre><code>A clA = new A(); B clB = new B(); Console.WriteLine(clA.Foo()); // output 5 Console.WriteLine(clA.Bar()); // output 5 Console.WriteLine(clB.Foo()); // output 1 Console.WriteLine(clB.Bar()); // output 1 //now let's cast B to an A class Console.WriteLine(((A)clB).Foo()); // output 5 &lt;&lt;&lt;-- shadow Console.WriteLine(((A)clB).Bar()); // output 1 </code></pre> <p>Suppose you have a base class and you use the base class in all your code instead of the inherited classes, and you use shadow, it will return the values the base class returns instead of following the inheritance tree of the real type of the object.</p> <p><a href="https://dotnetfiddle.net/ApUlvE" rel="noreferrer">Run code here</a></p> <p>Hope I'm making sense :)</p>
639,171
What is causing this ActiveRecord::ReadOnlyRecord error?
<p>This follows <a href="https://stackoverflow.com/questions/628000/rails-whats-wrong-with-this-multiple-join-with-conditions-on-the-associations" title="this">this</a> prior question, which was answered. I actually discovered I could remove a join from that query, so now the working query is</p> <pre><code>start_cards = DeckCard.find :all, :joins =&gt; [:card], :conditions =&gt; ["deck_cards.deck_id = ? and cards.start_card = ?", @game.deck.id, true] </code></pre> <p>This appears to work. However, when I try to move these DeckCards into another association, I get the ActiveRecord::ReadOnlyRecord error.</p> <p>Here's the code</p> <pre><code>for player in @game.players player.tableau = Tableau.new start_card = start_cards.pop start_card.draw_pile = false player.tableau.deck_cards &lt;&lt; start_card # the error occurs on this line end </code></pre> <p>and the relevant Models (tableau are the players cards on the table)</p> <pre><code>class Player &lt; ActiveRecord::Base belongs_to :game belongs_to :user has_one :hand has_one :tableau end class Tableau &lt; ActiveRecord::Base belongs_to :player has_many :deck_cards end class DeckCard &lt; ActiveRecord::Base belongs_to :card belongs_to :deck end </code></pre> <p>I am doing a similar action just after this code, adding <code>DeckCards</code> to the players hand, and that code is working fine. I wondered if I needed <code>belongs_to :tableau</code> in the DeckCard Model, but it works fine for the adding to player's hand. I do have a <code>tableau_id</code> and <code>hand_id</code> columns in the DeckCard table.</p> <p>I looked up ReadOnlyRecord in the rails api, and it doesn't say much beyond the description.</p>
639,844
6
0
null
2009-03-12 15:28:33.733 UTC
45
2019-03-18 06:37:40.73 UTC
2017-05-23 10:30:44.547 UTC
Vlad Romascanu
-1
null
26,270
null
1
208
ruby-on-rails|ruby|activerecord|join|associations
70,758
<p><strong>Rails 2.3.3 and lower</strong></p> <p>From the <a href="https://raw.github.com/rails/rails/3-0-stable/activerecord/CHANGELOG" rel="noreferrer">ActiveRecord <code>CHANGELOG</code></a><sup>(v1.12.0, October 16th, 2005)</sup>:</p> <blockquote> <p>Introduce read-only records. If you call object.readonly! then it will mark the object as read-only and raise ReadOnlyRecord if you call object.save. object.readonly? reports whether the object is read-only. Passing :readonly => true to any finder method will mark returned records as read-only. <strong>The :joins option now implies :readonly, so if you use this option, saving the same record will now fail.</strong> Use find_by_sql to work around.</p> </blockquote> <p>Using <code>find_by_sql</code> is not really an alternative as it returns raw row/column data, not <code>ActiveRecords</code>. You have two options:</p> <ol> <li>Force the instance variable <code>@readonly</code> to false in the record (hack)</li> <li>Use <code>:include =&gt; :card</code> instead of <code>:join =&gt; :card</code></li> </ol> <p><strong>Rails 2.3.4 and above</strong></p> <p>Most of the above no longer holds true, after September 10 2012:</p> <ul> <li>using <code>Record.find_by_sql</code> <strong>is</strong> a viable option</li> <li><code>:readonly =&gt; true</code> is automatically inferred <strong>only</strong> if <code>:joins</code> was specified <strong>without</strong> an explicit <code>:select</code> <strong>nor</strong> an explicit (or finder-scope-inherited) <code>:readonly</code> option (see the implementation of <code>set_readonly_option!</code> in <code>active_record/base.rb</code> for Rails 2.3.4, or the implementation of <code>to_a</code> in <code>active_record/relation.rb</code> and of <code>custom_join_sql</code> in <code>active_record/relation/query_methods.rb</code> for Rails 3.0.0)</li> <li>however, <code>:readonly =&gt; true</code> is always automatically inferred in <code>has_and_belongs_to_many</code> if the join table has more than the two foreign keys columns and <code>:joins</code> was specified without an explicit <code>:select</code> (i.e. user-supplied <code>:readonly</code> values are ignored -- see <code>finding_with_ambiguous_select?</code> in <code>active_record/associations/has_and_belongs_to_many_association.rb</code>.)</li> <li>in conclusion, unless dealing with a special join table and <code>has_and_belongs_to_many</code>, then <code>@aaronrustad</code>'s answer applies just fine in Rails 2.3.4 and 3.0.0.</li> <li>do <em>not</em> use <code>:includes</code> if you want to achieve an <code>INNER JOIN</code> (<code>:includes</code> implies a <code>LEFT OUTER JOIN</code>, which is less selective and less efficient than <code>INNER JOIN</code>.)</li> </ul>
58,728,435
How to get the address of a C++ lambda function within the lambda itself?
<p>I'm trying to figure out how to get the address of a lambda function within itself. Here is a sample code:</p> <pre><code>[]() { std::cout &lt;&lt; "Address of this lambda function is =&gt; " &lt;&lt; ???? }(); </code></pre> <p>I know that I can capture the lambda in a variable and print the address, but I want to do it in place when this anonymous function is executing.</p> <p>Is there a simpler way to do so?</p>
58,728,827
5
14
null
2019-11-06 10:52:22.48 UTC
15
2021-05-28 14:25:03.587 UTC
2019-11-07 22:55:28.247 UTC
null
9,835,872
null
5,662,469
null
1
56
c++|c++11|lambda|c++14|c++17
7,268
<p>It is not directly possible.</p> <p>However, lambda captures are classes and the address of an object coincides with the address of its first member. Hence, if you capture one object by value as the first capture, the address of the first capture corresponds to the address of the lambda object:</p> <pre><code>int main() { int i = 0; auto f = [i]() { printf("%p\n", &amp;i); }; f(); printf("%p\n", &amp;f); } </code></pre> <p>Outputs:</p> <pre><code>0x7ffe8b80d820 0x7ffe8b80d820 </code></pre> <hr> <p>Alternatively, you can create a <a href="https://en.wikipedia.org/wiki/Decorator_pattern" rel="noreferrer">decorator design pattern</a> lambda that passes the reference to the lambda capture into its call operator:</p> <pre><code>template&lt;class F&gt; auto decorate(F f) { return [f](auto&amp;&amp;... args) mutable { f(f, std::forward&lt;decltype(args)&gt;(args)...); }; } int main() { auto f = decorate([](auto&amp; that) { printf("%p\n", &amp;that); }); f(); } </code></pre>
18,062,759
error "no such file or directory" when reading in csv file in python
<p>Currently I am trying to read in a csv file using the csv module in python. When I run the piece of code below I get an error that states the file does not exist. My first guess is that maybe, I have the file saved in the wrong place or I need to provide pyton with a file path. currently I have the file saved in C:\Documents and Settings\eag29278\My Documents\python test code\test_satdata.csv. </p> <p>one side note im note sure wether having set the mode to 'rb' (read binary) was the right move.</p> <pre><code>import csv with open('test_satdata.csv', 'rb') as csvfile: satreader = csv.reader(csvfile, delimiter=' ', lineterminator=" ") for row in satreader: print ', '.join(row) </code></pre> <p>Here is the errror code.</p> <pre><code>Traceback (most recent call last): File "C:/Python27/test code/test csv parse.py", line 2, in &lt;module&gt; with open('test_satdata.csv', 'rb') as csvfile: IOError: [Errno 2] No such file or directory: 'test_satdata.csv' </code></pre>
18,062,798
4
0
null
2013-08-05 16:09:04.283 UTC
null
2019-10-01 02:20:52.04 UTC
2013-08-05 16:15:57.36 UTC
null
2,055,853
null
2,643,162
null
1
6
python|csv|filepath
40,475
<p>Your code is using a relative path; python is looking in the current directory (whatever that may be) to load your file. What the current directory <em>is</em> depends on how you started your Python script and if you executed any code that may have changed the current working directory.</p> <p>Use a full absolute path instead:</p> <pre><code>path = r'C:\Documents and Settings\eag29278\My Documents\python test code\test_satdata.csv' with open(path, 'rb') as csvfile: </code></pre> <p>Using <code>'rb'</code> is entirely correct, the <a href="http://docs.python.org/2/library/csv.html#csv.reader" rel="noreferrer"><code>csv</code> module</a> recommends you do so:</p> <blockquote> <p>If <em>csvfile</em> is a file object, it must be opened with the ‘b’ flag on platforms where that makes a difference.</p> </blockquote> <p>Windows <em>is</em> such a platform.</p>
1,614,651
Do sequence points prevent code reordering across critical section boundaries?
<p>Suppose that one has some lock based code like the following where mutexes are used to guard against inappropriate concurrent read and write</p> <pre><code>mutex.get() ; // get a lock. T localVar = pSharedMem-&gt;v ; // read something pSharedMem-&gt;w = blah ; // write something. pSharedMem-&gt;z++ ; // read and write something. mutex.release() ; // release the lock. </code></pre> <p>If one assumed that the generated code was created in program order, there is still a requirement for appropriate <em>hardware</em> memory barriers like isync,lwsync,.acq,.rel. I'll assume for this question that the mutex implementation takes care of this part, providing a guarentee that the pSharedMem reads and writes all occur "after" the get, and "before" the release() [but that surrounding reads and writes can get into the critical section as I expect is the norm for mutex implementations]. I'll also assume that volatile accesses are used in the mutex implementation where appropriate, but that volatile is NOT used for the data protected by the mutex (understanding why volatile does not appear to be a requirement for the mutex protected Data is really part of this question).</p> <p>I'd like to understand what prevents the <em>compiler</em> from moving the pSharedMem accesses outside of the critical region. In the C and C++ standards I see that there is a concept of sequence point. Much of the sequence point text in the standards docs I found incomprehensible, but if I was to guess what it was about, it is a statement that code should not be reordered across a point where there is a call with unknown side effects. Is that the jist of it? If that is the case what sort of optimization freedom does the compiler have here?</p> <p>With compilers doing tricky optimizations like profile driven interprocedural inlining (even across file boundaries), even the concept of unknown side effect gets kind of blurry.</p> <p>It is perhaps beyond the scope of a simple question to explain this in a self contained way here, so I am open to being pointed at references (preferrably online and targetted at mortal programmers not compiler writers and language designers).</p> <p>EDIT: (in response to Jalf's reply)</p> <p>I'd mentioned the memory barrier instructions like lwsync and isync because of the CPU reordering issues you also mentioned. I happen to work in the same lab as the compiler guys (for one of our platforms at least), and having talked to the implementers of the intrinsics I happen to know that at least for the xlC compiler __isync() and __lwsync() (and the rest of the atomic intrinsics) are also a code reordering barrier. In our spinlock implementation this is visible to the compiler since this part of our critical section is inlined.</p> <p>However, suppose you weren't using a custom build lock implementation (like we happen to be, which is likely uncommon), and just called a generic interface such as pthread_mutex_lock(). There the compiler isn't informed anything more than the prototype. I've never seen it suggested that code would be non-functional </p> <pre> pthread_mutex_lock( &m ) ; pSharedMem->someNonVolatileVar++ ; pthread_mutex_unlock( &m ) ; pthread_mutex_lock( &m ) ; pSharedMem->someNonVolatileVar++ ; pthread_mutex_unlock( &m ) ; </pre> <p>would be non-functional unless the variable was changed to volatile. That increment is going to have a load/increment/store sequence in each of the back to back blocks of code, and would not operate correctly if the value of the first increment is retained in-register for the second.</p> <p>It seems likely that the unknown side effects of the pthread_mutex_lock() is what protects this back to back increment example from behaving incorrectly.</p> <p>I'm talking myself into a conclusion that the semantics of a code sequence like this in a threaded environment is not really strictly covered by the C or C++ language specs.</p>
1,615,226
5
3
null
2009-10-23 16:46:56.797 UTC
9
2010-01-17 20:17:41.397 UTC
2009-10-23 19:59:51.553 UTC
null
189,270
null
189,270
null
1
17
c++|multithreading|concurrency|locking
3,708
<p>In short, the compiler is allowed to reorder or transform the program as it likes, as long as the <em>observable behavior</em> on a C++ virtual machine does not change. The C++ standard has no concept of threads, and so this fictive VM only runs a single thread. And on such an imaginary machine, we don't have to worry about what <em>other</em> threads see. As long as the changes don't alter the outcome of the <em>current</em> thread, all code transformations are valid, including reordering memory accesses across sequence points.</p> <blockquote> <p>understanding why volatile does not appear to be a requirement for the mutex protected Data is really part of this question</p> </blockquote> <p>Volatile ensures one thing, and one thing only: reads from a volatile variable will be read from memory every time -- the compiler won't assume that the value can be cached in a register. And likewise, writes will be written through to memory. The compiler won't keep it around in a register "for a while, before writing it out to memory".</p> <p>But that's all. When the write occurs, a write will be performed, and when the read occurs, a read will be performed. But it doesn't guarantee anything about <em>when</em> this read/write will take place. The compiler may, as it usually does, reorder operations as it sees fit (as long as it doesn't change the observable behavior in the current thread, the one that the imaginary C++ CPU knows about). So volatile doesn't really solve the problem. On the other hand, it offers a guarantee that we don't <em>really</em> need. We don't need <em>every</em> write to the variable to be written out immediately, we just want to ensure that they get written out before crossing <em>this</em> boundary. It's fine if they're cached until then - and likewise, once we've crossed the critical section boundary, subsequent writes can be cached again for all we care -- until we cross the boundary the next time. So volatile offers a too strong guarantee which we don't need, but doesn't offer the one we <em>do</em> need (that reads/writes won't get reordered)</p> <p>So to implement critical sections, we need to rely on compiler magic. We have to tell it that "ok, forget about the C++ standard for a moment, I don't care what optimizations it would have allowed if you'd followed that strictly. You must NOT reorder <em>any</em> memory accesses across this boundary".</p> <p>Critical sections are typically implemented via special compiler intrinsics (essentially special functions that are understood by the compiler), which 1) force the compiler to avoid reordering across that intrinsic, and 2) makes it emit the necessary instructions to get the CPU to respect the same boundary (because the CPU reorders instructions too, and without issuing a memory barrier instruction, we'd risk the CPU doing the same reordering that we just prevented the compiler from doing)</p>
1,665,868
How to detect and remove a column that contains only null values?
<p>In my table <strong>table1</strong> there are 6 columns Locations,a,b,c,d,e.</p> <pre><code>Locations [a] [b] [c] [d] [e] [1] 10.00 Null Null 20.00 Null [2] Null 30.00 Null Null Null </code></pre> <p>i need the result like</p> <pre><code>Locations [a] [b] [d] [1] 10.00 Null 20.00 [2] Null 30.00 Null </code></pre> <p>My question is how to detect and delete column that contains all null values using sql query. Is it possible?</p> <p>If yes then please help and give sample.</p>
1,666,461
6
4
null
2009-11-03 07:58:58.987 UTC
5
2020-05-05 22:33:58.68 UTC
2015-07-04 13:10:27.637 UTC
null
4,370,109
null
173,655
null
1
7
sql|sql-server-2005
60,434
<p>How to detect whether a given column has only the <code>NULL</code> value:</p> <pre><code>SELECT 1 -- no GROUP BY therefore use a literal FROM Locations HAVING COUNT(a) = 0 AND COUNT(*) &gt; 0; </code></pre> <p>The resultset will either consist of zero rows (column <code>a</code> has a non-<code>NULL</code> value) or one row (column <code>a</code> has only the <code>NULL</code> value). FWIW this code is Standard SQL-92.</p>
1,867,482
C# Getting value of params using reflection
<p>How can I get the values of parms (in a loop using reflection). In previous question, someone showed me how to loop through the parms using reflection. </p> <pre><code>static void Main(string[] args) { ManyParms("a","b","c",10,20,true,"end"); Console.ReadLine(); } static void ManyParms(string a, string b, string c, int d, short e, bool f, string g) { var parameters = MethodBase.GetCurrentMethod().GetParameters(); foreach (ParameterInfo parameter in parameters) { string parmName = parameter.Name; Console.WriteLine(parmName); //Following idea required an object first //Type t = this.GetType(); //t.GetField(parmName).GetValue(theObject)); } } </code></pre> <p>If you must know why I want to do this, please see here: <a href="https://stackoverflow.com/questions/1862433/net-reflection-of-all-method-parameters">.NET Reflection of all method parameters</a></p> <hr> <p>Thanks all - it seems like in Python, PERL, PHP this would be easy.<br> Even though it may not be reflection, if I use reflection to get the field name, seems like there would be an easy dynamic way to get the value based on the name. I haven't tried AOP (Aspect Oriented Programming) the solutions yet. This is one of those things that if I can't do it in an hour or two, I probably won't do it. </p>
1,868,507
7
1
null
2009-12-08 14:53:33.767 UTC
6
2021-05-18 22:36:48.027 UTC
2021-05-18 22:36:48.027 UTC
null
764,371
null
160,245
null
1
29
c#|reflection
36,714
<p>You can hack your way around this by creating an anonymous type inside your method and taking advantage of projection initialisers. You can then interrogate the anonymous type's properties using reflection. For example:</p> <pre><code>static void ManyParms( string a, string b, string c, int d, short e, bool f, string g) { var hack = new { a, b, c, d, e, f, g }; foreach (PropertyInfo pi in hack.GetType().GetProperties()) { Console.WriteLine("{0}: {1}", pi.Name, pi.GetValue(hack, null)); } } </code></pre>
2,167,360
Lambda for Dummies....anyone, anyone? I think not
<p>In my quest to understand the very odd looking ' => ' operator, I have found a good <a href="http://blah.winsmarts.com/2006/05/19/demystifying-c-30--part-4-lambda-expressions.aspx" rel="nofollow noreferrer">place to start</a>, and the author is very concise and clear:</p> <blockquote> <pre><code>parameters =&gt; expression </code></pre> </blockquote> <p>Does anyone have any tips on understanding the basics of lambdas so that it becomes easier to 'decipher' the more complex lambda statements?</p> <p>For instance: if I am given something like (from an <a href="https://stackoverflow.com/questions/2137399/attribute-interface-or-abstract-class/2137423#2137423">answer I received here</a>):</p> <pre><code>filenames.SelectMany(f =&gt; Assembly.LoadFrom(f).GetCustomAttributes(typeof(PluginClassAttribute), true) .Cast&lt;PluginClassAttribute&gt;() .Select(a =&gt; a.PluginType) ).ToList(); </code></pre> <p>How can I go about breaking this down into more simple pieces? </p> <hr> <p>UPDATE: wanted to show off my first lambda expression. Don't laugh at me, but I did it without copying someone's example...and it worked the first time:</p> <pre><code>public ModuleData[] GetStartModules( ) { return modules.FindAll(start =&gt; start.IsBatch == true).ToArray(); } </code></pre>
2,167,537
10
6
null
2010-01-30 09:07:41.32 UTC
22
2017-11-03 21:18:07.747 UTC
2017-11-03 21:18:07.747 UTC
null
3,885,376
null
210,709
null
1
36
c#-3.0|lambda
8,653
<p>Let's dissect your code sample:</p> <pre><code>filenames.SelectMany(f =&gt; Assembly.LoadFrom(f).GetCustomAttributes(typeof(PluginClassAttribute), true) .Cast&lt;PluginClassAttribute&gt;() .Select(a =&gt; a.PluginType) ).ToList(); </code></pre> <p>So, we start off with a <code>string[]</code> called <code>filenames</code>. We invoke the <code>SelectMany</code> extension method on the array, and then we invoke <code>ToList</code> on the result:</p> <pre><code>filenames.SelectMany( ... ).ToList(); </code></pre> <p><code>SelectMany</code> takes a delegate as parameter, in this case the delegate must take one parameter of the type <code>string</code> as input, and return an <code>IEnumerable&lt;T&gt;</code> (Where the type of <code>T</code> is inferred). This is where lambdas enter the stage:</p> <pre><code>filenames.SelectMany(f =&gt; Assembly.LoadFrom(f).GetCustomAttributes(typeof(PluginClassAttribute), true) ).ToList() </code></pre> <p>What will happen here is that <em>for each</em> element in the <code>filenames</code> array, the delegate will be invoked. <code>f</code> is the input parameter, and whatever comes to the right of <code>=&gt;</code> is the method body that the delegate refers to. In this case, <code>Assembly.LoadFrom</code> will be invoked for filename in the array, passing he filename into the <code>LoadFrom</code> method using the <code>f</code> argument. On the <code>AssemblyInstance</code> that is returned, <code>GetCustomAttributes(typeof(PluginClassAttribute), true)</code> will be invoked, which returns an array of <code>Attribute</code> instances. So the compiler can not infer that the type of <code>T</code> mentioned earlier is <code>Assembly</code>.</p> <p>On the <code>IEnumerable&lt;Attribute&gt;</code> that is returned, <code>Cast&lt;PluginClassAttribute&gt;()</code> will be invoked, returning an <code>IEnumerable&lt;PluginClassAttribute&gt;</code>.</p> <p>So now we have an <code>IEnumerable&lt;PluginClassAttribute&gt;</code>, and we invoke <code>Select</code> on it. The <code>Select</code> method is similar to <code>SelectMany</code>, but returns a single instance of type <code>T</code> (which is inferred by the compiler) instead of an <code>IEnumerable&lt;T&gt;</code>. The setup is identical; for each element in the <code>IEnumerable&lt;PluginClassAttribute&gt;</code> it will invoke the defined delegate, passing the current element value into it:</p> <pre><code>.Select(a =&gt; a.PluginType) </code></pre> <p>Again, <code>a</code> is the input parameter, <code>a.PluginType</code> is the method body. So, for each <code>PluginClassAttribute</code> instance in the list, it will return the value of the <code>PluginType</code> property (I will assume this property is of the type <code>Type</code>).</p> <p><strong>Executive Summary</strong><br> If we glue those bits and pieces together:</p> <pre><code>// process all strings in the filenames array filenames.SelectMany(f =&gt; // get all Attributes of the type PluginClassAttribute from the assembly // with the given file name Assembly.LoadFrom(f).GetCustomAttributes(typeof(PluginClassAttribute), true) // cast the returned instances to PluginClassAttribute .Cast&lt;PluginClassAttribute&gt;() // return the PluginType property from each PluginClassAttribute instance .Select(a =&gt; a.PluginType) ).ToList(); </code></pre> <hr> <p><strong>Lambdas vs. Delegates</strong><br> Let's finish this off by comparing lambdas to delegates. Take the following list:</p> <pre><code>List&lt;string&gt; strings = new List&lt;string&gt; { "one", "two", "three" }; </code></pre> <p>Say we want to filter out those that starts with the letter "t":</p> <pre><code>var result = strings.Where(s =&gt; s.StartsWith("t")); </code></pre> <p>This is the most common approach; set it up using a lambda expression. But there are alternatives:</p> <pre><code>Func&lt;string,bool&gt; func = delegate(string s) { return s.StartsWith("t");}; result = strings.Where(func); </code></pre> <p>This is essentially the same thing: first we create a delegate of the type <code>Func&lt;string, bool&gt;</code> (that means that it takes a <code>string</code> as input parameter, and returns a <code>bool</code>). Then we pass that delegate as parameter to the <code>Where</code> method. This is what the compiler did for us behind the scenes in the first sample (<code>strings.Where(s =&gt; s.StartsWith("t"));</code>).</p> <p>One third option is to simply pass a delegate to a non-anonymous method:</p> <pre><code>private bool StringsStartingWithT(string s) { return s.StartsWith("t"); } // somewhere else in the code: result = strings.Where(StringsStartingWithT); </code></pre> <p>So, in the case that we are looking at here, the lambda expression is a rather compact way of defining a delegate, typically referring an anonymous method.</p> <p>And if you had the energy read all the way here, well, thanks for your time :)</p>
1,780,341
Do I need <class> elements in persistence.xml?
<p>I have very simple persistance.xml file:</p> <pre class="lang-xml prettyprint-override"><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"&gt; &lt;persistence-unit name="eventractor" transaction-type="RESOURCE_LOCAL"&gt; &lt;class&gt;pl.michalmech.eventractor.domain.User&lt;/class&gt; &lt;class&gt;pl.michalmech.eventractor.domain.Address&lt;/class&gt; &lt;class&gt;pl.michalmech.eventractor.domain.City&lt;/class&gt; &lt;class&gt;pl.michalmech.eventractor.domain.Country&lt;/class&gt; &lt;properties&gt; &lt;property name="hibernate.hbm2ddl.auto" value="validate" /&gt; &lt;property name="hibernate.show_sql" value="true" /&gt; &lt;/properties&gt; &lt;/persistence-unit&gt; &lt;/persistence&gt; </code></pre> <p>and it works.</p> <p>But when I remove <code>&lt;class&gt;</code> elements application doesn't see entities (all classes are annotated with <code>@Entity</code>).</p> <p>Is there any automatic mechanism to scan for <code>@Entity</code> classes?</p>
1,780,362
11
0
null
2009-11-22 22:57:42.523 UTC
46
2020-06-25 07:26:54.207 UTC
2015-08-25 12:20:03.863 UTC
null
1,281,433
null
154,496
null
1
114
java|hibernate|orm|jpa|annotations
161,164
<p>The persistence.xml has a <code>jar-file</code> that you can use. From <a href="https://docs.oracle.com/cd/E19159-01/819-3669/bnbrj/index.html" rel="nofollow noreferrer">the Java EE 5 tutorial</a>:</p> <blockquote> <pre class="lang-xml prettyprint-override"><code>&lt;persistence&gt; &lt;persistence-unit name=&quot;OrderManagement&quot;&gt; &lt;description&gt;This unit manages orders and customers. It does not rely on any vendor-specific features and can therefore be deployed to any persistence provider. &lt;/description&gt; &lt;jta-data-source&gt;jdbc/MyOrderDB&lt;/jta-data-source&gt; &lt;jar-file&gt;MyOrderApp.jar&lt;/jar-file&gt; &lt;class&gt;com.widgets.Order&lt;/class&gt; &lt;class&gt;com.widgets.Customer&lt;/class&gt; &lt;/persistence-unit&gt; &lt;/persistence&gt; </code></pre> </blockquote> <p>This file defines a persistence unit named <code>OrderManagement</code>, which uses a JTA-aware data source <code>jdbc/MyOrderDB</code>. The <code>jar-file</code> and <code>class</code> elements specify managed persistence classes: entity classes, embeddable classes, and mapped superclasses. The <code>jar-file</code> element specifies JAR files that are visible to the packaged persistence unit that contain managed persistence classes, while the <code>class</code> element explicitly names managed persistence classes.</p> <p>In the case of Hibernate, have a look at the <a href="http://docs.jboss.org/hibernate/stable/entitymanager/reference/en/html/configuration.html" rel="nofollow noreferrer">Chapter2. Setup and configuration</a> too for more details.</p> <p><strong>EDIT:</strong> Actually, If you don't mind not being spec compliant, Hibernate supports auto-detection even in Java SE. To do so, add the <code>hibernate.archive.autodetection</code> property:</p> <pre class="lang-xml prettyprint-override"><code>&lt;persistence-unit name=&quot;eventractor&quot; transaction-type=&quot;RESOURCE_LOCAL&quot;&gt; &lt;!-- This is required to be spec compliant, Hibernate however supports auto-detection even in JSE. &lt;class&gt;pl.michalmech.eventractor.domain.User&lt;/class&gt; &lt;class&gt;pl.michalmech.eventractor.domain.Address&lt;/class&gt; &lt;class&gt;pl.michalmech.eventractor.domain.City&lt;/class&gt; &lt;class&gt;pl.michalmech.eventractor.domain.Country&lt;/class&gt; --&gt; &lt;properties&gt; &lt;!-- Scan for annotated classes and Hibernate mapping XML files --&gt; &lt;property name=&quot;hibernate.archive.autodetection&quot; value=&quot;class, hbm&quot;/&gt; &lt;property name=&quot;hibernate.hbm2ddl.auto&quot; value=&quot;validate&quot; /&gt; &lt;property name=&quot;hibernate.show_sql&quot; value=&quot;true&quot; /&gt; &lt;/properties&gt; &lt;/persistence-unit&gt; </code></pre>
2,043,259
How to Join to first row
<p>I'll use a concrete, but hypothetical, example.</p> <p>Each <strong>Order</strong> normally has only one <strong>line item</strong>:</p> <p><strong>Orders:</strong></p> <pre class="lang-none prettyprint-override"><code>OrderGUID OrderNumber ========= ============ {FFB2...} STL-7442-1 {3EC6...} MPT-9931-8A </code></pre> <p><strong>LineItems:</strong></p> <pre class="lang-none prettyprint-override"><code>LineItemGUID Order ID Quantity Description ============ ======== ======== ================================= {098FBE3...} 1 7 prefabulated amulite {1609B09...} 2 32 spurving bearing </code></pre> <p>But occasionally there will be an order with two line items:</p> <pre class="lang-none prettyprint-override"><code>LineItemID Order ID Quantity Description ========== ======== ======== ================================= {A58A1...} 6,784,329 5 pentametric fan {0E9BC...} 6,784,329 5 differential girdlespring </code></pre> <p>Normally when showing the orders to the user:</p> <pre><code>SELECT Orders.OrderNumber, LineItems.Quantity, LineItems.Description FROM Orders INNER JOIN LineItems ON Orders.OrderID = LineItems.OrderID </code></pre> <p>I want to show the single item on the order. But with this occasional order containing two (or more) items, the orders would <em>appear</em> be <strong>duplicated</strong>:</p> <pre class="lang-none prettyprint-override"><code>OrderNumber Quantity Description =========== ======== ==================== STL-7442-1 7 prefabulated amulite MPT-9931-8A 32 spurving bearing KSG-0619-81 5 panametric fan KSG-0619-81 5 differential girdlespring </code></pre> <p>What I really want is to have SQL Server <em>just pick one</em>, as it will be <em>good enough</em>:</p> <pre class="lang-none prettyprint-override"><code>OrderNumber Quantity Description =========== ======== ==================== STL-7442-1 7 prefabulated amulite MPT-9931-8A 32 differential girdlespring KSG-0619-81 5 panametric fan </code></pre> <p>If I get adventurous, I might show the user, an ellipsis to indicate that there's more than one:</p> <pre class="lang-none prettyprint-override"><code>OrderNumber Quantity Description =========== ======== ==================== STL-7442-1 7 prefabulated amulite MPT-9931-8A 32 differential girdlespring KSG-0619-81 5 panametric fan, ... </code></pre> <p>So the question is how to either</p> <ul> <li>eliminate "duplicate" rows</li> <li>only join to one of the rows, to avoid duplication</li> </ul> <h2>First attempt</h2> <p>My first naive attempt was to only join to the "<strong>TOP 1</strong>" line items:</p> <pre class="lang-sql prettyprint-override"><code>SELECT Orders.OrderNumber, LineItems.Quantity, LineItems.Description FROM Orders INNER JOIN ( SELECT TOP 1 LineItems.Quantity, LineItems.Description FROM LineItems WHERE LineItems.OrderID = Orders.OrderID) LineItems2 ON 1=1 </code></pre> <p>But that gives the error:</p> <blockquote> <p>The column or prefix 'Orders' does not<br> match with a table name or alias name<br> used in the query. </p> </blockquote> <p>Presumably because the inner select doesn't see the outer table.</p>
2,043,290
11
2
null
2010-01-11 16:44:37.123 UTC
217
2021-01-12 08:46:08.16 UTC
2020-05-30 23:24:56.287 UTC
null
792,066
null
12,597
null
1
899
sql|sql-server|tsql|sql-server-2000
747,502
<pre><code>SELECT Orders.OrderNumber, LineItems.Quantity, LineItems.Description FROM Orders JOIN LineItems ON LineItems.LineItemGUID = ( SELECT TOP 1 LineItemGUID FROM LineItems WHERE OrderID = Orders.OrderID ) </code></pre> <p>In SQL Server 2005 and above, you could just replace <code>INNER JOIN</code> with <code>CROSS APPLY</code>:</p> <pre><code>SELECT Orders.OrderNumber, LineItems2.Quantity, LineItems2.Description FROM Orders CROSS APPLY ( SELECT TOP 1 LineItems.Quantity, LineItems.Description FROM LineItems WHERE LineItems.OrderID = Orders.OrderID ) LineItems2 </code></pre> <p>Please note that <code>TOP 1</code> without <code>ORDER BY</code> is not deterministic: this query you will get you one line item per order, but it is not defined which one will it be.</p> <p>Multiple invocations of the query can give you different line items for the same order, even if the underlying did not change.</p> <p>If you want deterministic order, you should add an <code>ORDER BY</code> clause to the innermost query.</p> <p><a href="http://sqlfiddle.com/#!18/44d008/6" rel="noreferrer">Example sqlfiddle</a></p>
2,151,959
Using Interface variables
<p>I'm still trying to get a better understanding of Interfaces. I know about what they are and how to implement them in classes.</p> <p>What I don't understand is when you create a variable that is of one of your Interface types:</p> <pre><code>IMyInterface somevariable; </code></pre> <p>Why would you do this? I don't understand how IMyInterface can be used like a class...for example to call methods, so:</p> <pre><code>somevariable.CallSomeMethod(); </code></pre> <p>Why would you use an IMyInterface variable to do this?</p>
2,151,993
12
2
null
2010-01-28 02:51:21.45 UTC
24
2017-02-13 13:25:12.707 UTC
null
null
null
null
93,468
null
1
47
c#
49,338
<p>You are not creating an instance of the interface - you are creating an instance of something that implements the interface.</p> <p>The point of the interface is that it guarantees that what ever implements it will provide the methods declared within it.</p> <p>So now, using your example, you could have:</p> <pre><code>MyNiftyClass : IMyInterface { public void CallSomeMethod() { //Do something nifty } } MyOddClass : IMyInterface { public void CallSomeMethod() { //Do something odd } } </code></pre> <p>And now you have:</p> <pre><code>IMyInterface nifty = new MyNiftyClass() IMyInterface odd = new MyOddClass() </code></pre> <p>Calling the CallSomeMethod method will now do either something nifty or something odd, and this becomes particulary useful when you are passing in using IMyInterface as the type.</p> <pre><code>public void ThisMethodShowsHowItWorks(IMyInterface someObject) { someObject.CallSomeMethod(); } </code></pre> <p>Now, depending on whether you call the above method with a nifty or an odd class, you get different behaviour.</p> <pre><code>public void AnotherClass() { IMyInterface nifty = new MyNiftyClass() IMyInterface odd = new MyOddClass() // Pass in the nifty class to do something nifty this.ThisMethodShowsHowItWorks(nifty); // Pass in the odd class to do something odd this.ThisMethodShowsHowItWorks(odd); } </code></pre> <p><strong>EDIT</strong></p> <p>This addresses what I think your intended question is - Why would you declare a variable to be of an interface type?</p> <p>That is, why use:</p> <pre><code>IMyInterface foo = new MyConcreteClass(); </code></pre> <p>in preference to:</p> <pre><code>MyConcreteClass foo = new MyConcreteClass(); </code></pre> <p>Hopefully it is clear why you would use the interface when declaring a method signature, but that leaves the question about locally scoped variables:</p> <pre><code>public void AMethod() { // Why use this? IMyInterface foo = new MyConcreteClass(); // Why not use this? MyConcreteClass bar = new MyConcreteClass(); } </code></pre> <p>Usually there is no technical reason why the interface is preferred. I usually use the interface because:</p> <ul> <li>I typically inject dependencies so the polymorphism is needed</li> <li>Using the interface clearly states my intent to only use members of the interface</li> </ul> <p>The one place where you would <em>technically</em> need the interface is where you are utilising the polymorphism, such as creating your variable using a factory or (as I say above) using dependency injection.</p> <p>Borrowing an example from itowlson, using concrete declaration you could not do this:</p> <pre><code>public void AMethod(string input) { IMyInterface foo; if (input == "nifty") { foo = new MyNiftyClass(); } else { foo = new MyOddClass(); } foo.CallSomeMethod(); } </code></pre>
2,028,697
Dialogs / AlertDialogs: How to "block execution" while dialog is up (.NET-style)
<p>Coming from the .NET-environment, I'm now looking to understand how Dialogs work in Android.</p> <p>In .NET, when calling <code>MessageBox.Show(...)</code> that creates and shows a popup dialog. In the call to Show I can specify what buttons should be available in the popup, for example:</p> <pre><code>DialogResult myDialogResult = MessageBox.Show("My text here", "My caption here", MessageBoxButtons.YesNoCancel); </code></pre> <p>As you can see, the call to Show returns a DialogResult when a button is pressed in the popup, informing me what button was clicked. Note that in .NET, execution is halted at the line where the call to <code>Show(...)</code> is made, so it can return the value when a button is pressed.</p> <p>If I in the above example press "No" the myDialogResult will be equal to </p> <pre><code>myDialogResult == DialogResult.No </code></pre> <p>Since I find the .NET-way of using/creating popups very easy and intuitive, I would like that way of creating popups in Android too. </p> <p>So, the question is if anyone know how to "halt execution" like with the <code>MessageBox.Show</code>, and then return a value whenever the Button is pressed (and the dialog goes away)?</p> <h2>Edit 1</h2> <p>To be a little bit more clear:</p> <p>I need for the execution to halt and wait until the user has chosen a button to click in the popup. The code that follow the call to show the Dialog is dependent on what button is clicked in the Dialog.</p> <p>That's why I cannot use what Erich and Alex suggest, since writing code in the onClick-methods as suggested below is not going to work. The reason is that I cannot continue the "normal execution". Let me take an example:</p> <p>Let me take an example:</p> <pre><code>int nextStep = 0; // this variable will not be reached from within the onClick-methods AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage("Hello!") .setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { nextStep = 1; // *** COMPILER ERROR!! *** } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { nextStep = 2; // *** COMPILER ERROR!! *** } }) .create().show(); if (nextStep == 1) { // then do some damage } else if (nextStep == 2 // dont do damage </code></pre> <p>If I wanted the execution to be dependent on the choice in the popup, I would somehow have to make all the variables in the "normal execution" (in this case <code>nextStep</code>) available in the onClick-methods, and that sounds like hell to me.</p> <h2>Edit 2</h2> <p>Another obvious example would be a popup asking <i>"Do you want to continue"</i> with the options <i>"Yes"</i> and <i>"No"</i>.</p> <p>If the user presses "Yes", the whole method should be aborted otherwise it should continue execution. How do you solve that nicely?</p>
2,029,128
20
6
null
2010-01-08 15:46:56.817 UTC
26
2021-02-11 17:57:29.377 UTC
2019-05-12 21:40:55.883 UTC
null
472,495
null
178,143
null
1
73
android
105,602
<p>Ted, you don't want to do this, really :) The biggest reason is that if you block the UI thread while you are displaying a Dialog, you will block the thread that's in charge of drawing and handling the events of your Dialog. Which means your dialog will be unresponsive. You will also cause ANRs if the user takes more than a few seconds to click the dialog.</p> <p>Erich's answer is exactly what you need. I know it's not what you <em>want</em>, but that doesn't matter. We've designed Android to prevent developers from writing synchronous dialogs so you don't really have much of a choice.</p>
8,440,490
Pretty URLs in PHP frameworks
<p>I know that you can add rules in htaccess, but I see that PHP frameworks don't do that and somehow you still have pretty URLs. How do they do that if the server is not aware of the URL rules?</p> <p>I've been looking <a href="http://en.wikipedia.org/wiki/Yii" rel="nofollow noreferrer">Yii's</a> <a href="http://code.google.com/p/yii/source/browse/tags/1.1.8/framework/web/CUrlManager.php#119" rel="nofollow noreferrer">url manager class</a> but I don't understand how it does it.</p>
8,441,266
1
2
null
2011-12-09 02:58:21.917 UTC
12
2020-05-09 20:24:34.113 UTC
2019-11-30 20:38:47.56 UTC
null
63,550
null
376,947
null
1
19
php|apache|mod-rewrite|url-rewriting
5,355
<p>This is usually done by routing all requests to a single entry point (a file that executes different code based on the request) with a rule like:</p> <pre><code># Redirect everything that doesn't match a directory or file to index.php RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule .* index.php [L] </code></pre> <p>This file then compares the request (<code>$_SERVER["REQUEST_URI"]</code>) against a list of routes - a mapping of a pattern matching the request to a controller action (in MVC applications) or another path of execution. Frameworks often include a route that can infer the controller and action from the request itself, as a backup route.</p> <p>A small, simplified example:</p> <pre><code>&lt;?php // Define a couple of simple actions class Home { public function GET() { return 'Homepage'; } } class About { public function GET() { return 'About page'; } } // Mapping of request pattern (URL) to action classes (above) $routes = array( '/' =&gt; 'Home', '/about' =&gt; 'About' ); // Match the request to a route (find the first matching URL in routes) $request = '/' . trim($_SERVER['REQUEST_URI'], '/'); $route = null; foreach ($routes as $pattern =&gt; $class) { if ($pattern == $request) { $route = $class; break; } } // If no route matched, or class for route not found (404) if (is_null($route) || !class_exists($route)) { header('HTTP/1.1 404 Not Found'); echo 'Page not found'; exit(1); } // If method not found in action class, send a 405 (e.g. Home::POST()) if (!method_exists($route, $_SERVER["REQUEST_METHOD"])) { header('HTTP/1.1 405 Method not allowed'); echo 'Method not allowed'; exit(1); } // Otherwise, return the result of the action $action = new $route; $result = call_user_func(array($action, $_SERVER["REQUEST_METHOD"])); echo $result; </code></pre> <p>Combined with the first configuration, this is a simple script that will allow you to use URLs like <code>domain.com/about</code>. Hope this helps you make sense of what's going on here.</p>
8,439,639
mongodb & max connections
<p>i am going to have a website with 20k+ concurrent users.</p> <p>i am going to use mongodb using one management node and 3 or more nodes for data sharding.</p> <p>now my problem is maximum connections. if i have that many users accessing the database, how can i make sure they don't reach the maximum limit? also do i have to change anything maybe on the kernel to increase the connections?</p> <p>basically the database will be used to keep hold of connected users to the site, so there are going to be heavy read/write operations.</p> <p>thank you in advance.</p>
8,439,729
1
2
null
2011-12-09 00:29:38.993 UTC
6
2015-01-13 17:42:08.707 UTC
null
null
null
null
1,084,439
null
1
23
mongodb|connection
44,840
<p>You don't want to open a new database connection each time a new user connects. I don't know if you'll be able to scale to 20k+ concurrent users easily, since MongoDB uses a new thread for each new connection. You want your web app backend to have just one to a few database connections open and just use those in a pool, particularly since web usage is very asynchronous and event driven.</p> <p>see: <a href="http://www.mongodb.org/display/DOCS/Connections">http://www.mongodb.org/display/DOCS/Connections</a></p> <blockquote> <p>The server will use one thread per TCP connection, therefore it is highly recomended that your application use some sort of connection pooling. Luckily, most drivers handle this for you behind the scenes. One notable exception is setups where your app spawns a new process for each request, such as CGI and some configurations of PHP.</p> </blockquote> <p>Whatever driver you're using, you'll have to find out how they handle connections and if they pool or not. For instance, Node's Mongoose is non-blocking and so you use one connection per app usually. This is the kind of thing you probably want.</p>
46,387,760
Match the same start and end character of a string with Regex
<p>I'm trying to match the start and end character of a string to be the same vowel. My regex is working in most scenarios, but failing in others:</p> <pre><code>var re = /([aeiou]).*\1/; re.test(str); </code></pre> <p>Sample input:</p> <ul> <li><code>abcde</code>, output - false (Valid)</li> <li><code>abcda</code>, output - true (Valid)</li> <li><code>aabcdaa</code>, output - true (Valid)</li> <li><code>aeqwae</code>, output - true (Not valid)</li> <li><code>ouqweru</code>, output - true (Not valid)</li> </ul>
46,387,831
4
4
null
2017-09-24 07:40:20.55 UTC
5
2019-12-22 03:01:48.73 UTC
2017-09-24 08:54:41.437 UTC
null
3,130,281
null
4,818,458
null
1
37
javascript|regex|validation
47,537
<p>You need to add anchors to your string.</p> <p>When you have, for example:</p> <pre><code>aeqwae </code></pre> <p>You say the output is true, but it's not valid because <code>a</code> is not the same as <code>e</code>. Well, regex simply matches the previous character (before <code>e</code>), which is <code>a</code>. Thus, the match is valid. So, you get this:</p> <pre><code>[aeqwa]e </code></pre> <p>The string enclosed in the brackets is the actual match and why it returns <code>true</code>.</p> <p>If you change your regex to this:</p> <pre><code>/^([aeiou]).*\1$/ </code></pre> <p>By adding <code>^</code>, you tell it that the start of the match <em>must</em> be the start of the string and by adding <code>$</code> you tell it that the end of the match <em>must</em> be the end of the string. This way, if there's a match, the whole string must be matched, meaning that <code>aeqwae</code> will no longer get matched.</p> <p>A great tool for testing regex is <a href="https://regex101.com/" rel="noreferrer">Regex101</a>. Give it a try!</p> <p><strong>Note:</strong> Depending on your input, you might need to set the global (g) or multi-line (m) flag. The global flag prevents regex from returning after the first match. The multi-line flag makes <code>^</code> and <code>$</code> match the start and end of the <strong>line</strong> (not the string). I used both of them when testing with your input.</p>
17,779,735
How do I make the bottom bar with dots of a UIPageViewController translucent?
<p>I'm in the process of making a tutorial, and I'm trying to emulate the style of Path's tutorial like so:</p> <p><a href="http://www.appcoda.com/wp-content/uploads/2013/06/UIPageViewController-Tutorial-Screen.jpg" rel="noreferrer">http://www.appcoda.com/wp-content/uploads/2013/06/UIPageViewController-Tutorial-Screen.jpg</a> <img src="https://i.stack.imgur.com/kVBPF.jpg" alt="enter image description here"></p> <p>My issue is that if set the delegate method as so:</p> <pre><code>- (NSInteger)presentationCountForPageViewController:(UIPageViewController *)pageViewController { // The number of items reflected in the page indicator. return 5; } </code></pre> <p>Then I get this stupid black bar under the dots:</p> <p><a href="https://i.stack.imgur.com/pUEdh.png" rel="noreferrer">http://i.stack.imgur.com/pUEdh.png</a> <img src="https://i.stack.imgur.com/vGJtJ.png" alt="enter image description here"></p> <p>Is there a way to make this bar translucent in a way thats similar to setting a UINavigationBar to translucent?</p>
19,140,401
12
0
null
2013-07-22 04:01:30.26 UTC
30
2020-01-29 12:41:56.697 UTC
2016-02-11 19:53:41.697 UTC
null
1,486,275
null
2,565,551
null
1
45
iphone|ios|uipageviewcontroller
34,201
<p>It is very easy to make it work. You just only have to make the pageviewcontroller taller, and place a PageControl into the XIB file. The trick is put the PageControl in the foreground (and all the other common controls) at the beginning, and update the content of the PageControl with the PageViewController. Here is the code:</p> <pre><code>- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view from its nib. self.pageController = [[UIPageViewController alloc] initWithTransitionStyle:UIPageViewControllerTransitionStyleScroll navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal options:nil]; self.pageController.dataSource = self; // We need to cover all the control by making the frame taller (+ 37) [[self.pageController view] setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, [[self view] bounds].size.height + 37)]; TutorialPageViewController *initialViewController = [self viewControllerAtIndex:0]; NSArray *viewControllers = [NSArray arrayWithObject:initialViewController]; [self.pageController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:nil]; [self addChildViewController:self.pageController]; [[self view] addSubview:[self.pageController view]]; [self.pageController didMoveToParentViewController:self]; // Bring the common controls to the foreground (they were hidden since the frame is taller) [self.view bringSubviewToFront:self.pcDots]; [self.view bringSubviewToFront:self.btnSkip]; } - (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController { NSUInteger index = [(TutorialPageViewController *)viewController index]; [self.pcDots setCurrentPage:index]; if (index == 0) { return nil; } index--; return [self viewControllerAtIndex:index]; } - (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController { NSUInteger index = [(TutorialPageViewController *)viewController index]; [self.pcDots setCurrentPage:index]; index++; if (index == 3) { return nil; } return [self viewControllerAtIndex:index]; } - (TutorialPageViewController *)viewControllerAtIndex:(NSUInteger)index { TutorialPageViewController *childViewController = [[TutorialPageViewController alloc] initWithNibName:@"TutorialPageViewController" bundle:nil]; childViewController.index = index; return childViewController; } - (NSInteger)presentationCountForPageViewController:(UIPageViewController *)pageViewController { // The number of items reflected in the page indicator. NSInteger tutorialSteps = 3; [self.pcDots setNumberOfPages:tutorialSteps]; return tutorialSteps; } - (NSInteger)presentationIndexForPageViewController:(UIPageViewController *)pageViewController { // The selected item reflected in the page indicator. return 0; } </code></pre>
44,499,041
Web API: Configure JSON serializer settings on action or controller level
<p>Overriding the default JSON serializer settings for web API on application level has been covered in a lot of SO threads. But how can I configure its settings on action level? For example, I might want to serialize using camelcase properties in one of my actions, but not in the others.</p>
44,499,722
3
9
null
2017-06-12 12:07:33.23 UTC
12
2020-06-25 18:03:30.037 UTC
null
null
null
null
598,511
null
1
37
c#|asp.net-web-api|json.net
26,255
<h3>Option 1 (quickest)</h3> <p>At action level you may always use a custom <code>JsonSerializerSettings</code> instance while using <code>Json</code> method:</p> <pre><code>public class MyController : ApiController { public IHttpActionResult Get() { var settings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }; var model = new MyModel(); return Json(model, settings); } } </code></pre> <h3>Option 2 (controller level)</h3> <p>You may create a new <code>IControllerConfiguration</code> attribute which customizes the JsonFormatter:</p> <pre><code>public class CustomJsonAttribute : Attribute, IControllerConfiguration { public void Initialize(HttpControllerSettings controllerSettings, HttpControllerDescriptor controllerDescriptor) { var formatter = controllerSettings.Formatters.JsonFormatter; controllerSettings.Formatters.Remove(formatter); formatter = new JsonMediaTypeFormatter { SerializerSettings = { ContractResolver = new CamelCasePropertyNamesContractResolver() } }; controllerSettings.Formatters.Insert(0, formatter); } } [CustomJson] public class MyController : ApiController { public IHttpActionResult Get() { var model = new MyModel(); return Ok(model); } } </code></pre>
36,111,915
Why is a double semicolon a SyntaxError in Python?
<p>I know that semicolons are unnecessary in Python, but they can be used to cram multiple statements onto a single line, e.g.</p> <pre class="lang-none prettyprint-override"><code>&gt;&gt;&gt; x = 42; y = 54 </code></pre> <p>I always thought that a semicolon was equivalent to a line break. So I was a bit surprised to learn (h/t <a href="https://twitter.com/nedbat/status/709326204051005440" rel="noreferrer">Ned Batchelder on Twitter</a>) that a double semicolon is a SyntaxError:</p> <pre class="lang-none prettyprint-override"><code>&gt;&gt;&gt; x = 42 &gt;&gt;&gt; x = 42; &gt;&gt;&gt; x = 42;; File "&lt;stdin&gt;", line 1 x = 42;; ^ SyntaxError: invalid syntax </code></pre> <p></p></p> <p>I assumed the last program was equivalent to <code>x = 42\n\n</code>. I’d have thought the statement between the semicolons was treated as an empty line, a no-op. Apparently not.</p> <p><strong>Why is this an error?</strong></p>
36,111,947
2
4
null
2016-03-20 09:07:56.13 UTC
5
2016-04-05 08:28:36.063 UTC
2016-03-20 17:12:35.117 UTC
null
4,962,868
null
1,558,022
null
1
68
python|syntax-error|language-lawyer
4,041
<p>From the Python grammar, we can see that <code>;</code> is not defined as <code>\n</code>. The parser expects another statement after a <code>;</code>, except if there's a newline after it:</p> <pre><code> Semicolon w/ statement Maybe a semicolon Newline \/ \/ \/ \/ simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE </code></pre> <p>That's why <code>x=42;;</code> doesn't work; because there isn't a statement between the two semicolons, as "nothing" isn't a statement. If there was any complete statement between them, like a <code>pass</code> or even just a <code>0</code>, the code would work.</p> <pre><code>x = 42;0; # Fine x = 42;pass; # Fine x = 42;; # Syntax error if x == 42:; print("Yes") # Syntax error - "if x == 42:" isn't a complete statement </code></pre>
15,674,097
Output aligned columns
<p>I am learning C++. I have a problem formatting the output of my program. I would like to print there columns perfectly aligned but so far I cannot do it, here is my code:</p> <pre><code>int main() { employee employees[5]; employees[0].setEmployee("Stone", 35.75, 053); employees[1].setEmployee("Rubble", 12, 163); employees[2].setEmployee("Flintstone", 15.75, 97); employees[3].setEmployee("Pebble", 10.25, 104); employees[4].setEmployee("Rockwall", 22.75, 15); printEmployees(employees, 5); return 0; } // print the employees in my array void printEmployees(employee employees[], int number) { int i; for (i=0; i&lt;number; i++) { employees[i].printEmployee();// this is the method that give me problems } cout &lt;&lt; "\n"; } </code></pre> <p>in the class employee I have the print employee method:</p> <pre><code>void printEmployee() const { cout &lt;&lt; fixed; cout &lt;&lt; surname &lt;&lt; setw(10) &lt;&lt; empNumber &lt;&lt; "\t" &lt;&lt; setw(4) &lt;&lt; hourlyRate &lt;&lt; "\n"; } </code></pre> <p>Problem is when I print "flinstones" line the emp number and rate are not lined up. something like this happens:</p> <pre> Stone 43 35.750000 Rubble 163 12.000000 Flintstone 97 15.750000 Pebble 104 10.250000 Rockwall 15 22.750000 </pre> <p>Can anybody help me? (I tried to add tabs.. but it didn't help)</p>
15,674,259
3
1
null
2013-03-28 04:05:31.56 UTC
5
2020-11-11 00:54:42.893 UTC
2013-03-28 04:14:31.243 UTC
null
82,682
null
1,291,994
null
1
8
c++|cout
75,797
<p>In the class employee of print employee method: Use this line to print.</p> <pre><code>cout &lt;&lt; setw(20) &lt;&lt; left &lt;&lt; surname &lt;&lt; setw(10) &lt;&lt; left &lt;&lt; empNumber &lt;&lt; setw(4) &lt;&lt; hourlyRate &lt;&lt; endl; </code></pre> <p>You forgot to add "<code>&lt;&lt; left</code>". This is required if you want left aligned.</p> <p>Hope it ll useful.</p>
18,988,977
How do I access phpMyAdmin?
<p>I installed phpMyAdmin on my computer. I used Apache as my http server. However, every time I go to <code>http://localhost/phpMyAdmin/</code>, this screen appears:</p> <p><img src="https://i.stack.imgur.com/IUnOs.jpg" alt="enter image description here"></p> <p>How do I make it so that this login screen appears instead:</p> <p><img src="https://i.stack.imgur.com/3zTH8.jpg" alt="enter image description here"></p>
18,989,122
5
3
null
2013-09-24 18:12:33.173 UTC
0
2020-06-15 08:21:44.397 UTC
null
null
null
null
2,042,272
null
1
2
php|apache|http|phpmyadmin
39,547
<p>You may be better off to install an integrated suite, such as:</p> <p><a href="http://www.apachefriends.org/en/xampp-windows.html" rel="nofollow">XAMPP - Linux/Windows/Apple</a> * store web pages in htdocs</p> <p><a href="http://www.wampserver.com/en/" rel="nofollow">WAMP - Windows</a></p> <p><a href="http://www.mamp.info/en/downloads/" rel="nofollow">MAMP - Apple</a></p> <p>Then, just going to the address <code>localhost</code> will give you a menu, with all components (apache, phpmyadmin, tomcat, etc etc)</p> <p>They are all free, so why not?</p>
27,899,104
How to create a defconfig file from a .config?
<p>I have done <code>make menuconfig</code> for a board <code>defconfig</code> and modified few configurations. When I select save, a new <code>.config</code> was created in the Kernel top directory.</p> <p>I want to create new <code>defconfig</code> for this <code>.config</code> file created.</p> <p>Can I copy the <code>.config</code> as a new <code>defconfig</code> and copy to <code>arch/arm/configs/</code>?</p> <pre><code>$ cp .config arch/arm/configs/board_new_defconfig </code></pre>
27,918,677
2
2
null
2015-01-12 09:47:24.077 UTC
11
2021-10-21 06:08:59.387 UTC
2019-01-24 18:31:56.913 UTC
null
2,511,795
null
3,693,586
null
1
28
linux-kernel|embedded-linux|kbuild|archlinux-arm
56,568
<p>I think you have to do just one command and use the created file as you want to.</p> <pre><code>% make savedefconfig % cp defconfig arch/arm/configs/my_cool_defconfig </code></pre> <p>(Pay attention to the <a href="https://elixir.bootlin.com/linux/latest/source/scripts/kconfig/Makefile#L93" rel="nofollow noreferrer">filename template</a> that is used for <em>defconfig</em>)</p> <p>To get all possible targets just run</p> <pre><code>% make help </code></pre> <p>As noted by <a href="https://stackoverflow.com/users/1337526/adam-miller">Adam Miller</a> followed by <a href="https://stackoverflow.com/users/1588913/jeremy">Jeremy</a>, users of Buildroot distribution can use wrappers for that purpose, i.e. (per Buildroot manual, <a href="https://buildroot.org/downloads/manual/manual.html#make-tips" rel="nofollow noreferrer">section 8.1</a>):</p> <ul> <li><strong>linux-savedefconfig</strong> for <code>linux</code></li> <li><strong>barebox-savedefconfig</strong> for <code>barebox</code> bootloader</li> <li><strong>uboot-savedefconfig</strong> for <code>U-Boot</code> bootloader</li> </ul> <p><code>make savedefconfig</code> <a href="https://github.com/torvalds/linux/blob/v4.17/scripts/kconfig/confdata.c#L665" rel="nofollow noreferrer">minimizes the generated <code>defconfig</code></a> skipping redundant configs that are implied by others.</p>
27,595,749
Douglas Crockford on Class Free OOP in JavaScript
<p>Douglas Crockford has a really good talk on "The Better Parts" of ES6. Among other things, he <a href="https://www.youtube.com/watch?v=PSGEjv3Tqo0&amp;t=6m">encourages a move away from prototypal inheritance in favor of class free OOP</a>.</p> <p>Here he says he stopped using <code>new</code>, <code>Object.create</code>, and <code>this</code>, but didn't really explain an alternative. Could anyone fill me in on how that might look?</p>
27,595,904
2
4
null
2014-12-22 02:06:24.4 UTC
26
2021-08-17 17:52:53.067 UTC
2014-12-22 02:09:46.877 UTC
null
707,111
null
3,421,392
null
1
47
javascript|oop|ecmascript-6
7,938
<p>You should watch the whole video, he explains it at <a href="https://www.youtube.com/watch?v=PSGEjv3Tqo0#t=1395" rel="noreferrer">later in the video</a>.</p> <pre><code>function constructor(spec) { let {member} = spec, {other} = other_constructor(spec), method = function () { // accesses member, other, method, spec }; return Object.freeze({ method, other }); } </code></pre> <p>It's the <a href="http://addyosmani.com/resources/essentialjsdesignpatterns/book/#revealingmodulepatternjavascript" rel="noreferrer">revealing module pattern</a> returning a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze" rel="noreferrer">frozen object</a>.</p>
51,170,417
In C++, what do braces on the left-hand side of a variable declaration mean?
<p>The code at <a href="https://github.com/HertzDevil/0CC-FamiTracker/blob/e643e8cbad1c8bf01ff706245d72f93c33417de8/Source/FamiTracker.cpp#L446" rel="noreferrer">this GitHub file</a> uses a C++ variable "declaration" syntax I'm not familiar with:</p> <pre><code>std::unique_ptr&lt;CRecentFileList&gt; {m_pRecentFileList} = std::make_unique&lt;CRecentFileList&gt;(... </code></pre> <p>(<code>m_pRecentFileList</code> is declarared in a superclass.)</p> <p>What does it mean when you wrap a variable <strong>declaration</strong> in braces? (not an initializer list)</p> <hr> <p>I extracted a minimal test case which compiles:</p> <pre><code>class foo { int* p; void f(){ std::unique_ptr&lt;int&gt; {p} = std::make_unique&lt;int&gt;(1); } }; </code></pre> <p>Changing <code>int* p</code> to <code>std::unique_ptr&lt;int&gt; p</code> creates a compilation error due to <code>unique_ptr(const unique_ptr&amp;) = delete;</code></p> <p>This makes me think braced declaration assigns to a outer-scope variable with the same name. I tried creating a test program, but it fails to compile:</p> <pre><code>int main(){ int x; int {x} = 1; } </code></pre> <blockquote> <p><code>error: using temporary as lvalue [-fpermissive]</code></p> </blockquote>
51,170,503
1
4
null
2018-07-04 09:33:25.837 UTC
3
2018-07-06 04:10:58.16 UTC
2018-07-06 04:10:58.16 UTC
null
2,181,238
null
2,683,842
null
1
50
c++
3,086
<p>It's not a declaration. It's an assignment to a temporary.</p> <p>In <code>std::unique_ptr&lt;int&gt; {p} = std::make_unique&lt;int&gt;(1);</code>, <code>std::unique_ptr&lt;int&gt; {p}</code> creates a <code>unique_ptr</code> temporary that takes ownership of the object <code>p</code> points to, then <code>std::make_unique&lt;int&gt;(1)</code> is assigned to that temporary, which causes the object <code>p</code> points to to be deleted and the temporary to take ownership of the <code>int</code> created by the <code>make_unique</code>; finally, at the <code>;</code>, the temporary itself is destroyed, deleting the <code>make_unique</code>-created <code>int</code>.</p> <p>The net result is <code>delete p</code> plus a useless new/delete cycle.</p> <p>(It would be a declaration had it used parentheses rather than braces: <code>std::unique_ptr&lt;int&gt; (p) = std::make_unique&lt;int&gt;(1);</code> is exactly equivalent to <code>std::unique_ptr&lt;int&gt; p = std::make_unique&lt;int&gt;(1);</code>.)</p>
885,485
How do I get started using BouncyCastle?
<p>So after <a href="http://www.codinghorror.com/blog/archives/001267.html" rel="noreferrer">CodingHorror's fun with encryption</a> and the thrashing comments, we are reconsidering doing our own encryption.</p> <p>In this case, we need to pass some information that identifies a user to a 3rd party service which will then call back to a service on our website with the information plus a hash. </p> <p>The 2nd service looks up info on that user and then passes it back to the 3rd party service.</p> <p>We want to encrypt this user information going into the 3rd party service and decrypt it after it comes out. So it is not a long lived encryption.</p> <p>On the coding horror article, Coda Hale recommended BouncyCastle and a high level abstraction in the library to do the encryption specific to a particular need. </p> <p>My problem is that the BouncyCastle namespaces are huge and the documentation is non-existant. Can anyone point me to this high level abstraction library? (Or another option besides BouncyCastle?)</p>
887,544
7
5
null
2009-05-19 23:11:41.417 UTC
9
2016-06-06 21:46:54.237 UTC
null
null
null
null
13,100
null
1
27
cryptography|bouncycastle
29,087
<p>High level abstraction? I suppose the highest level abstractions in the Bouncy Castle library would include:</p> <ul> <li>The <a href="http://www.bouncycastle.org/docs/docs1.6/org/bouncycastle/crypto/BlockCipher.html" rel="noreferrer">BlockCipher</a> interface (for symmetric ciphers)</li> <li>The <a href="http://www.bouncycastle.org/docs/docs1.6/org/bouncycastle/crypto/BufferedBlockCipher.html" rel="noreferrer">BufferedBlockCipher</a> class</li> <li>The <a href="http://www.bouncycastle.org/docs/docs1.6/org/bouncycastle/crypto/AsymmetricBlockCipher.html" rel="noreferrer">AsymmetricBlockCipher</a> interface</li> <li>The <a href="http://www.bouncycastle.org/docs/docs1.6/org/bouncycastle/crypto/BufferedAsymmetricBlockCipher.html" rel="noreferrer">BufferedAsymmetricBlockCipher</a> class</li> <li>The <a href="http://www.bouncycastle.org/docs/docs1.6/org/bouncycastle/crypto/CipherParameters.html" rel="noreferrer">CipherParameters</a> interface (for initializing the block ciphers and asymmetric block ciphers)</li> </ul> <p>I am mostly familiar with the Java version of the library. Perhaps this code snippet will offer you a high enough abstraction for your purposes (example is using AES-256 encryption):</p> <pre><code>public byte[] encryptAES256(byte[] input, byte[] key) throws InvalidCipherTextException { assert key.length == 32; // 32 bytes == 256 bits CipherParameters cipherParameters = new KeyParameter(key); /* * A full list of BlockCiphers can be found at http://www.bouncycastle.org/docs/docs1.6/org/bouncycastle/crypto/BlockCipher.html */ BlockCipher blockCipher = new AESEngine(); /* * Paddings available (http://www.bouncycastle.org/docs/docs1.6/org/bouncycastle/crypto/paddings/BlockCipherPadding.html): * - ISO10126d2Padding * - ISO7816d4Padding * - PKCS7Padding * - TBCPadding * - X923Padding * - ZeroBytePadding */ BlockCipherPadding blockCipherPadding = new ZeroBytePadding(); BufferedBlockCipher bufferedBlockCipher = new PaddedBufferedBlockCipher(blockCipher, blockCipherPadding); return encrypt(input, bufferedBlockCipher, cipherParameters); } public byte[] encrypt(byte[] input, BufferedBlockCipher bufferedBlockCipher, CipherParameters cipherParameters) throws InvalidCipherTextException { boolean forEncryption = true; return process(input, bufferedBlockCipher, cipherParameters, forEncryption); } public byte[] decrypt(byte[] input, BufferedBlockCipher bufferedBlockCipher, CipherParameters cipherParameters) throws InvalidCipherTextException { boolean forEncryption = false; return process(input, bufferedBlockCipher, cipherParameters, forEncryption); } public byte[] process(byte[] input, BufferedBlockCipher bufferedBlockCipher, CipherParameters cipherParameters, boolean forEncryption) throws InvalidCipherTextException { bufferedBlockCipher.init(forEncryption, cipherParameters); int inputOffset = 0; int inputLength = input.length; int maximumOutputLength = bufferedBlockCipher.getOutputSize(inputLength); byte[] output = new byte[maximumOutputLength]; int outputOffset = 0; int outputLength = 0; int bytesProcessed; bytesProcessed = bufferedBlockCipher.processBytes( input, inputOffset, inputLength, output, outputOffset ); outputOffset += bytesProcessed; outputLength += bytesProcessed; bytesProcessed = bufferedBlockCipher.doFinal(output, outputOffset); outputOffset += bytesProcessed; outputLength += bytesProcessed; if (outputLength == output.length) { return output; } else { byte[] truncatedOutput = new byte[outputLength]; System.arraycopy( output, 0, truncatedOutput, 0, outputLength ); return truncatedOutput; } } </code></pre> <p><strong>Edit</strong>: Whoops, I just read the article you linked to. It sounds like he is talking about even higher level abstractions than I thought (e.g., "send a confidential message"). I am afraid I don't quite understand what he is getting at.</p>
732,666
Converting TMemoryStream to 'String' in Delphi 2009
<p>We had the following code prior to Delphi 2009:</p> <pre><code>function MemoryStreamToString(M : TMemoryStream): String; var NewCapacity: Longint; begin if (M.Size = &gt; 0) or (M.Memory = nil) then Result:= '' else begin if TMemoryStreamProtected(M).Capacity = M.Size then begin NewCapacity:= M.Size+1; TMemoryStreamProtected(M).Realloc(NewCapacity); end; NullString(M.Memory^)[M.Size]:= #0; Result:= StrPas(M.Memory); end; end; </code></pre> <p>How might we convert this code to support Unicode now with Delphi 2009?</p>
733,322
7
0
null
2009-04-09 03:24:23.233 UTC
18
2019-07-19 12:51:57.403 UTC
2018-10-10 10:31:38.97 UTC
null
5,855,039
null
23,640
null
1
33
delphi|string|unicode|delphi-2009|memorystream
81,674
<p>The code you have is unnecessarily complex, even for older Delphi versions. Why should fetching the string version of a stream force the stream's memory to be reallocated, after all?</p> <pre><code>function MemoryStreamToString(M: TMemoryStream): string; begin SetString(Result, PChar(M.Memory), M.Size div SizeOf(Char)); end; </code></pre> <p>That works in all Delphi versions, not just Delphi 2009. It works when the stream is empty without any special case. <a href="http://www.delphibasics.co.uk/RTL.asp?Name=SetString" rel="noreferrer"><code>SetString</code></a> is an under-appreciated function.</p> <p>If the contents of your stream aren't changing to Unicode with your switch to Delphi 2009, then you should use this function instead:</p> <pre><code>function MemoryStreamToString(M: TMemoryStream): AnsiString; begin SetString(Result, PAnsiChar(M.Memory), M.Size); end; </code></pre> <p>That's equivalent to your original code, but skips the special cases.</p>