id
int64
4
73.8M
title
stringlengths
10
150
body
stringlengths
17
50.8k
accepted_answer_id
int64
7
73.8M
answer_count
int64
1
182
comment_count
int64
0
89
community_owned_date
stringlengths
23
27
creation_date
stringlengths
23
27
favorite_count
int64
0
11.6k
last_activity_date
stringlengths
23
27
last_edit_date
stringlengths
23
27
last_editor_display_name
stringlengths
2
29
last_editor_user_id
int64
-1
20M
owner_display_name
stringlengths
1
29
owner_user_id
int64
1
20M
parent_id
null
post_type_id
int64
1
1
score
int64
-146
26.6k
tags
stringlengths
1
125
view_count
int64
122
11.6M
answer_body
stringlengths
19
51k
16,213,255
How to read cell values from existing excel file
<p>I want to read the each cell value in excel file, But i am not able to get the cell values even after trying different examples in NET. I am not getting result with the following code, can any one get back on this. I am using .net framework 2.0</p> <pre><code>string filePath = "F:/BulkTest.xlsx"; Microsoft.Office.Interop.Excel.Application ExcelApp = new Microsoft.Office.Interop.Excel.Application(); ExcelApp.Visible = true; Microsoft.Office.Interop.Excel.Workbook wb = ExcelApp.Workbooks.Open(filePath, Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value); Microsoft.Office.Interop.Excel.Worksheet sh = (Microsoft.Office.Interop.Excel.Worksheet)wb.Sheets["Sheet1"]; Range excelRange = sh.UsedRange; for (int i=2; i&lt;= excelRange.Count + 1 ; i++) { string values = sh.Cells[i,2].ToString(); } </code></pre>
16,213,877
3
7
null
2013-04-25 11:14:10.27 UTC
3
2016-11-22 05:15:24.82 UTC
2014-04-07 13:33:52.123 UTC
null
1,300,224
user2252365
null
null
1
2
c#|excel
58,579
<blockquote> <p>Till now i am trying to take cell values directly to variables, now i will try to take cell values to an array using Range. Thanks!!!! – Teja Varma 13 mins ago</p> </blockquote> <p>No. I didn't even mean that :) As I mentioned in the comment that you can store the entire range in an array. That doesn't mean that you need to loop though each cell to store it in an array. You can directly assign the values of the range to the array. See this example.</p> <pre><code>xlRng = xlWorkSheet.get_Range("A1", "A20"); Object arr = xlRng.Value; foreach (object s in (Array)arr) { MessageBox.Show(s.ToString()); } </code></pre>
51,873,516
Requires Babel "7.0.0-0" but was loaded with "6.26.3"
<p>Keep getting this error no matter what I tried installing (babel wise) as I follow other similar reports. this is the stack trace:</p> <blockquote> <pre><code>error: bundling failed: Error: Requires Babel "^7.0.0-0", but was loaded with "6.26.3". If you are sure you have a compatible version of @babel/core, it is likely that something in your build process is loading the wrong version. Inspect the stack trace of this error to look for the first entry that doesn't mention "@babel/core" or "babel-core" to see what is calling Babel. (While processing preset: "C:\\Users\\Admin-ESS\\Absent\\node_modules\\@babel\\preset-env\\lib\\index.js") at throwVersionError (C:\Users\Admin-ESS\Absent\node_modules\@babel\preset-env\node_modules\@babel\helper-plugin-utils\lib\index.js:65:11) at Object.assertVersion (C:\Users\Admin-ESS\Absent\node_modules\@babel\preset-env\node_modules\@babel\helper-plugin-utils\lib\index.js:13:11) at _default (C:\Users\Admin-ESS\Absent\node_modules\@babel\preset-env\lib\index.js:150:7) at C:\Users\Admin-ESS\Absent\node_modules\@babel\preset-env\node_modules\@babel\helper-plugin-utils\lib\index.js:19:12 at C:\Users\Admin-ESS\Absent\node_modules\metro\node_modules\babel-core\lib\transformation\file\options\option-manager.js:317:46 at Array.map (&lt;anonymous&gt;) at OptionManager.resolvePresets (C:\Users\Admin-ESS\Absent\node_modules\metro\node_modules\babel-core\lib\transformation\file\options\option-manager.js:275:20) at OptionManager.mergePresets (C:\Users\Admin-ESS\Absent\node_modules\metro\node_modules\babel-core\lib\transformation\file\options\option-manager.js:264:10) at OptionManager.mergeOptions (C:\Users\Admin-ESS\Absent\node_modules\metro\node_modules\babel-core\lib\transformation\file\options\option-manager.js:249:14) at OptionManager.init (C:\Users\Admin-ESS\Absent\node_modules\metro\node_modules\babel-core\lib\transformation\file\options\option-manager.js:368:12) at File.initOptions (C:\Users\Admin-ESS\Absent\node_modules\metro\node_modules\babel-core\lib\transformation\file\index.js:212:65) at new File (C:\Users\Admin-ESS\Absent\node_modules\metro\node_modules\babel-core\lib\transformation\file\index.js:135:24) at Pipeline.transform (C:\Users\Admin-ESS\Absent\node_modules\metro\node_modules\babel-core\lib\transformation\pipeline.js:46:16) at Object.transform (C:\Users\Admin-ESS\Absent\node_modules\metro\src\transformer.js:135:5) at Object.transformCode [as transform] (C:\Users\Admin-ESS\Absent\node_modules\metro\src\JSTransformer\worker\index.js:253:15) at execMethod (C:\Users\Admin-ESS\Absent\node_modules\jest-worker\build\child.js:92:29) at process.on (C:\Users\Admin-ESS\Absent\node_modules\jest-worker\build\child.js:42:7) at process.emit (events.js:180:13) at emit (internal/child_process.js:783:12) </code></pre> </blockquote> <p>and my package.json:</p> <pre><code>{ "name": "Absent", "version": "0.1.0", "private": true, "devDependencies": { "babel-preset-react-native-stage-0": "^1.0.1", "jest": "^23.5.0", "jest-react-native": "^18.0.0", "react-test-renderer": "16.3.1" }, "scripts": { "start": "react-native start", "android": "react-native run-android", "ios": "react-native run-ios", "test": "jest" }, "jest": { "preset": "react-native" }, "dependencies": { "@babel/core": "^7.0.0-rc.1", "@babel/preset-env": "^7.0.0-rc.1", "@babel/preset-react": "^7.0.0-rc.1", "jail-monkey": "^1.0.0", "prop-types": "^15.6.2", "react": "16.3.1", "react-native": "^0.55.4", "react-native-device-info": "^0.22.4", "react-native-elements": "^0.19.1", "react-native-firebase": "^4.3.8", "react-native-modal": "^6.5.0", "react-native-router-flux": "^4.0.1", "react-native-size-matters": "^0.1.2", "react-native-vector-icons": "^5.0.0", "react-redux": "^5.0.7", "redux": "^4.0.0", "redux-thunk": "^2.3.0" }, "rnpm": { "assets": [ "./assets/fonts/" ] } } </code></pre> <p>Any pointers would be greatly appreciated here...</p>
51,901,251
15
1
null
2018-08-16 09:14:08.533 UTC
14
2022-06-10 08:34:13.787 UTC
2018-08-17 20:50:51.977 UTC
null
785,065
null
9,628,544
null
1
74
reactjs|react-native|babeljs
54,509
<p>Looks like you need to install <code>babel-core</code> as the docs suggest: <a href="https://jestjs.io/docs/en/getting-started#using-babel" rel="noreferrer">https://jestjs.io/docs/en/getting-started#using-babel</a></p> <p><code>yarn add --dev babel-jest babel-core@^7.0.0-bridge.0 @babel/core regenerator-runtime</code></p>
29,461,831
libsass bindings not found when using node-sass in nodejs
<p>I want to use the <code>node-sass</code> module in my <code>node.js v0.12</code> application to benefit from the performance of <code>libsass</code>.<br> I executed <code>npm i node-sass</code> to install the module, no errors so far.<br></p> <p>Now the mess starts:<br> If I just open the <code>REPL</code> in a terminal to try out <code>node-sass</code> then everything works fine but if I include it in my project files and run <code>node myfile.js</code> then I get the following error message:<br></p> <pre><code>Error: `libsass` bindings not found. Try reinstalling `node-sass`? </code></pre> <p>The module's description at <a href="https://www.npmjs.com/package/node-sass#install">npmjs.com</a> states that there might be a problem with resolving <code>#!/usr/bin/env node</code> under Ubuntu and how to fix this but that is not the case on my machine.<br> I could not find anything useful so I hope that you might help me.<br></p> <p>I'm using node v0.12.2 under Ubuntu 14.10.</p> <p>P.S.: I already tried to reinstall node-sass but without success. Nothing changes.</p>
29,624,362
13
2
null
2015-04-05 20:23:41.08 UTC
38
2021-01-28 14:13:49.077 UTC
null
null
null
null
1,223,253
null
1
77
node.js|ubuntu|npm|libsass|node-sass
73,376
<p>You’ve probably tried to reinstall node-sass while using </p> <pre><code>npm install node-sass </code></pre> <p>or</p> <pre><code>npm uninstall node-sass npm install node-sass </code></pre> <p>But node-sass is a C version of Sass. You have to use <a href="https://docs.npmjs.com/cli/rebuild">npm rebuild</a>:</p> <pre><code>npm rebuild node-sass </code></pre>
32,334,312
Subtracting n days from date in Python
<p>I want to subtract n days from a file's timestamp, but it doesn't seem to be working. I have read <a href="https://stackoverflow.com/questions/6871016/adding-5-days-to-date-in-python">this post</a>, and I think I'm close.</p> <p>This is an excerpt from my code:</p> <pre><code>import os, time from datetime import datetime, timedelta def processData1( pageFile ): f = open(pageFile, "r") page = f.read() filedate = time.strftime('%m/%d/%Y', time.gmtime(os.path.getmtime(pageFile))) print filedate end_date = filedate - datetime.timedelta(days=10) print end_date </code></pre> <p>Printing <code>filedate</code> works, so that date is read correctly from the files. It's the subtraction bit that doesn't seem to be working.</p> <p>Desired output: If <code>filedate</code> is 06/11/2013, <code>print end_date</code> should yield <code>06/01/2013</code>.</p>
32,334,496
2
3
null
2015-09-01 14:30:57.517 UTC
1
2018-03-26 04:04:01.9 UTC
2017-05-23 11:54:30.703 UTC
null
-1
null
3,343,907
null
1
9
python|python-2.7|datetime|timedelta
48,070
<p>When you use <a href="https://docs.python.org/2/library/time.html#time.strftime" rel="noreferrer"><code>time.strftime()</code></a> you are actually converting a <a href="https://docs.python.org/2/library/time.html#time.struct_time" rel="noreferrer"><code>struct_time</code></a> to a string.</p> <p>so <code>filedate</code> is actually a string. When you try to <code>+</code> or <code>-</code> a <code>datetime.timedelta</code> from it, you would get an error. Example -</p> <pre><code>In [5]: s = time.strftime('%m/%d/%Y', time.gmtime(time.time())) In [6]: s Out[6]: '09/01/2015' In [8]: s - datetime.timedelta(days=10) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-8-fb1d19ed0b02&gt; in &lt;module&gt;() ----&gt; 1 s - datetime.timedelta(days=10) TypeError: unsupported operand type(s) for -: 'str' and 'datetime.timedelta' </code></pre> <p>To get a similar behavior to <a href="https://docs.python.org/2/library/time.html#time.gmtime" rel="noreferrer"><code>time.gmtime()</code></a> to can instead use <a href="https://docs.python.org/2/library/datetime.html#datetime.datetime.utcfromtimestamp" rel="noreferrer"><code>datetime.datetime.utcfromtimestamp()</code></a> , this would provide a datetime object, from which you can subtract the timedelta.</p> <p>And then if the end result you want is actually a string, you can use <code>datetime.strftime()</code> to convert it to string in required format. Example -</p> <pre><code>import os from datetime import datetime, timedelta def processData1( pageFile ): f = open(pageFile, "r") page = f.read() filedate = datetime.utcfromtimestamp(os.path.getmtime(pageFile))) print filedate end_date = filedate - timedelta(days=10) print end_date #end_date would be a datetime object. end_date_string = end_date.strftime('%m/%d/%Y') print end_date_string </code></pre>
54,809,410
Unresolved reference ActivityTestRule for AndroidX
<p>I'm trying to test my UI via instrumentation test, with androidX espresso library. In my grade I have:</p> <pre class="lang-kotlin prettyprint-override"><code>apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply plugin: 'kotlin-android-extensions' apply plugin: "kotlin-kapt" android { compileSdkVersion 28 defaultConfig { applicationId "it.zehus.mybike" minSdkVersion 21 targetSdkVersion 28 versionCode 1 versionName "1.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" android.defaultConfig.manifestPlaceholders = ['appAuthRedirectScheme': 'net.openid.appauthdemo'] } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) def lifecycle_version = "2.0.0" // ViewModel and LiveData implementation "androidx.lifecycle:lifecycle-extensions:$lifecycle_version" // room persistence library def room_version = "2.1.0-alpha04" implementation "androidx.room:room-runtime:$room_version" kapt "androidx.room:room-compiler:$room_version" // use kapt for Kotlin // optional - Coroutines support for Room implementation "androidx.room:room-coroutines:$room_version" implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" implementation 'androidx.appcompat:appcompat:1.0.2' implementation 'androidx.constraintlayout:constraintlayout:1.1.3' implementation 'com.google.android.material:material:1.0.0' // Espresso androidTestImplementation 'androidx.test:runner:1.1.0' androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0' implementation project(path: ':remotemanager') implementation "org.jetbrains.kotlin:kotlin-reflect:1.3.21" androidTestImplementation 'androidx.test.ext:junit:1.1.0' // required if you want to use Mockito for unit tests testImplementation 'org.mockito:mockito-core:2.24.5' // required if you want to use Mockito for Android tests androidTestImplementation 'org.mockito:mockito-android:2.24.5' // Bluetooth sdk implementation project(path: ':bluetoothmanager') // Custom views implementation project(path: ':customviews') } </code></pre> <p>As specified in the <a href="https://developer.android.com/training/testing/ui-testing/espresso-testing.html" rel="noreferrer">documentation</a> I'm attempting to import ActivityTestRule class in my test, however the reference is unresolved.</p> <pre class="lang-kotlin prettyprint-override"><code>import androidx.test.filters.LargeTest import androidx.test.runner.AndroidJUnit4 import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith // unresolved reference here import androidx.test.rule.ActivityTestRule import it.zehus.mybike.ui.ride.RideActivity /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ // deprecated here @RunWith(AndroidJUnit4::class) @LargeTest class FragmentDashboardUiTest { @get:Rule // unresolved reference here val activityRule = ActivityTestRule(RideActivity::class.java) @Test fun myClassMethod_ReturnsTrue() { } } </code></pre> <p>Am I doing something wrong or there's a problem within AndroidX testing libraries?</p>
54,810,885
2
5
null
2019-02-21 14:28:24.073 UTC
5
2020-11-06 06:17:57.423 UTC
2019-02-21 14:37:42.827 UTC
null
6,275,174
null
6,275,174
null
1
30
android|testing|kotlin|android-espresso|androidx
19,461
<p>I found out from <a href="https://developer.android.com/training/testing/set-up-project" rel="noreferrer">this</a> documentation page that class ActivityTestRule stays under <strong>androidx.test.rule</strong> in AndroidX. In order to import the package, I simply added: </p> <pre><code> androidTestImplementation 'androidx.test:rules:1.2.0' </code></pre> <p>to my gradle.</p> <p>To sum up my gradle now contains:</p> <pre class="lang-kotlin prettyprint-override"><code>// Espresso // Core library androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0' // AndroidJUnitRunner and JUnit Rules androidTestImplementation 'androidx.test:runner:1.2.0' androidTestImplementation 'androidx.test:rules:1.2.0' </code></pre>
26,576,260
Can I use the work-stealing behaviour of ForkJoinPool to avoid a thread starvation deadlock?
<p>A <em>thread starvation deadlock</em> occurs in a normal thread pool if all the threads in the pool are waiting for queued tasks in the same pool to complete. <code>ForkJoinPool</code> avoids this problem by stealing work from other threads from inside the <code>join()</code> call, rather than simply waiting. For example:</p> <pre><code>private static class ForkableTask extends RecursiveTask&lt;Integer&gt; { private final CyclicBarrier barrier; ForkableTask(CyclicBarrier barrier) { this.barrier = barrier; } @Override protected Integer compute() { try { barrier.await(); return 1; } catch (InterruptedException | BrokenBarrierException e) { throw new RuntimeException(e); } } } @Test public void testForkJoinPool() throws Exception { final int parallelism = 4; final ForkJoinPool pool = new ForkJoinPool(parallelism); final CyclicBarrier barrier = new CyclicBarrier(parallelism); final List&lt;ForkableTask&gt; forkableTasks = new ArrayList&lt;&gt;(parallelism); for (int i = 0; i &lt; parallelism; ++i) { forkableTasks.add(new ForkableTask(barrier)); } int result = pool.invoke(new RecursiveTask&lt;Integer&gt;() { @Override protected Integer compute() { for (ForkableTask task : forkableTasks) { task.fork(); } int result = 0; for (ForkableTask task : forkableTasks) { result += task.join(); } return result; } }); assertThat(result, equalTo(parallelism)); } </code></pre> <p>But when using the <code>ExecutorService</code> interface to a <code>ForkJoinPool</code>, work-stealing doesn't seem to occur. For example:</p> <pre><code>private static class CallableTask implements Callable&lt;Integer&gt; { private final CyclicBarrier barrier; CallableTask(CyclicBarrier barrier) { this.barrier = barrier; } @Override public Integer call() throws Exception { barrier.await(); return 1; } } @Test public void testWorkStealing() throws Exception { final int parallelism = 4; final ExecutorService pool = new ForkJoinPool(parallelism); final CyclicBarrier barrier = new CyclicBarrier(parallelism); final List&lt;CallableTask&gt; callableTasks = Collections.nCopies(parallelism, new CallableTask(barrier)); int result = pool.submit(new Callable&lt;Integer&gt;() { @Override public Integer call() throws Exception { int result = 0; // Deadlock in invokeAll(), rather than stealing work for (Future&lt;Integer&gt; future : pool.invokeAll(callableTasks)) { result += future.get(); } return result; } }).get(); assertThat(result, equalTo(parallelism)); } </code></pre> <p>From a cursory look at <code>ForkJoinPool</code>'s implementation, all the regular <code>ExecutorService</code> APIs are implemented using <code>ForkJoinTask</code>s, so I'm not sure why a deadlock occurs.</p>
26,617,505
3
2
null
2014-10-26 18:11:12.047 UTC
20
2019-11-26 09:35:37.537 UTC
null
null
null
null
502,399
null
1
18
java|multithreading|concurrency|java.util.concurrent|fork-join
9,272
<p>You are almost answering your own question. The solution is the statement that "<code>ForkJoinPool</code> avoids this problem by stealing work from other threads from inside the <code>join()</code> call". Whenever the threads are blocked for some other reason except <code>ForkJoinPool.join()</code>, this work stealing does not occur, and the threads just waits and does nothing.</p> <p>The reason for this is that in Java it is not possible for the <code>ForkJoinPool</code> to prevent its threads from blocking and instead give them something else to work on. The thread <em>itself</em> needs to avoid blocking and instead ask the pool for work it should do. And this is only implemented in the <code>ForkJoinTask.join()</code> method, not in any other blocking method. If you use a <code>Future</code> inside a <code>ForkJoinPool</code>, you will also see the starvation deadlock.</p> <p>Why is work stealing only implemented in <code>ForkJoinTask.join()</code> and not in any other blocking methods in the Java API? Well, there are many of such blocking methods (<code>Object.wait()</code>, <code>Future.get()</code>, any of the concurrency primitives in <code>java.util.concurrent</code>, I/O methods etc), and they have nothing to do with <code>ForkJoinPool</code>, which is just an arbitrary class in the API, so adding special cases to all these methods would be bad design. It would also lead to possibly very surprising and undesired effects. Imagine for example a user passing a task to an <code>ExecutorService</code> that waits on a <code>Future</code>, and then finding out that the task hangs very long in <code>Future.get()</code> just because the running thread stole some other (long-running) work item instead of waiting for the <code>Future</code> and continuing immediately after the result is available. Once a thread starts working on another task, it cannot return to the original task until the second task is finished. Thus it is actually a good thing that other blocking methods do not do work stealing. For a <code>ForkJoinTask</code>, this problem does not exist, because it is not important that the primary task is continued as soon as possible, it is only important that all tasks together are handled as efficiently as possible.</p> <p>It is also not possible to implement your own method for doing work stealing inside a <code>ForkJoinPool</code>, because all the relevant parts are not public.</p> <p>However, there is actually a second method how starvation deadlocks can be prevented. This is called <strong>managed blocking</strong>. It does not use work stealing (to avoid the problem mentioned above), but also needs the thread that is going to be block to actively cooperate with the thread pool. With managed blocking, the thread tells the thread pool that it may be blocked <em>before</em> it calls the potentially blocking method, and also informs the pool when the blocking method is finished. The thread pool then knows that there is a risk of a starvation deadlock, and may spawn additional threads if all of its threads are currently in some blocking operation and there are still other tasks to execute. Note that this is less efficient than work stealing, because of the overhead of the additional threads. If you implement a recursive parallel algorithm with ordinary futures and managed blocking instead of with <code>ForkJoinTask</code> and work stealing, the number of additional threads can get very large (because in the "divide" phase of the algorithm, a lot of tasks will be created and given to threads that immediately block and wait for results from sub-tasks). However, a starvation deadlock is still prevented, and it avoids the problem that a task has to wait a long time because its thread started working on another task in the mean time.</p> <p>The <code>ForkJoinPool</code> of Java also supports managed blocking. To use this, one needs to implement the interface <a href="http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ForkJoinPool.ManagedBlocker.html" rel="noreferrer"><code>ForkJoinPool.ManagedBlocker</code></a> such that the potentially-blocking method that the task wants to execute is called from within the <code>block</code> method of this interface. Then the task may not call the blocking method directly, but instead needs to call the static method <a href="http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ForkJoinPool.html#managedBlock-java.util.concurrent.ForkJoinPool.ManagedBlocker-" rel="noreferrer"><code>ForkJoinPool.managedBlock(ManagedBlocker)</code></a>. This method handles the communication with the thread pool before and after the blocking. It also works if the current task is not executed within a <code>ForkJoinPool</code>, then it just calls the blocking method.</p> <p>The only place I have found in the Java API (for Java 7) that actually uses managed blocking is the class <a href="http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Phaser.html" rel="noreferrer"><code>Phaser</code></a>. (This class is a synchronization barrier like mutexes and latches, but more flexible and powerful.) So synchronizing with a <code>Phaser</code> inside a <code>ForkJoinPool</code> task should use managed blocking and can avoid starvation deadlocks (but <code>ForkJoinTask.join()</code> is still preferable because it uses work stealing instead of managed blocking). This works regardless of whether you use the <code>ForkJoinPool</code> directly or via its <code>ExecutorService</code> interface. However, it will not work if you use any other <code>ExecutorService</code> like those created by the class <code>Executors</code>, because these do not support managed blocking.</p> <p>In Scala, the use of managed blocking is more widespread (<a href="http://docs.scala-lang.org/overviews/core/futures.html#blocking" rel="noreferrer">description</a>, <a href="http://www.scala-lang.org/api/current/index.html#scala.concurrent.package@blocking[T](body:=%3ET):T" rel="noreferrer">API</a>).</p>
20,122,583
Website in wordpress redirects to old URL after migration
<p>I had never done migrating a site on wordpress, I'll put step by step how I did, need to put the site on a new domain that are on the same server, so only the migrated files, the database is equal.</p> <p>I copied all the files from the old wordpress to the new site folder, I had the following result on the new site: Home - The site carries the theme but a message appears: 404: PAGE OR FILE NOT FOUND. newsite/wp-admin/ - redirect to oldsite/wp-admin/</p> <p>I have the option in the site administrator old put the new URL but I'm afraid I could never access. it can go?</p> <p>Thanks.</p>
20,122,853
9
2
null
2013-11-21 13:41:50.403 UTC
9
2022-05-07 17:36:55.58 UTC
null
null
null
null
2,729,508
null
1
38
php|wordpress|.htaccess
89,113
<p>You need to make a change to your database. In the database table wp_options (or whatever your database prefix is), you need to change two lines. </p> <p>One should be <code>option_id</code> 1, <code>option_name</code> siteurl. Change the <code>option_value</code> from the old url to the new url.</p> <p>Similarly there should also be <code>option_id</code> 36, <code>option_name</code> home. Change the <code>option_value</code> also from the old url to the new url.</p> <p>This should do the trick. Also check out <a href="http://wp.smashingmagazine.com/2013/04/08/moving-wordpress-website/">http://wp.smashingmagazine.com/2013/04/08/moving-wordpress-website/</a> for the best method to migrate.</p> <p><strong>Edit</strong></p> <p>In the comments Damon also mentions the issue with re-linking all the images. This for sure can be a right pain, but I suggest this plugin. </p> <p><a href="http://wordpress.org/plugins/search-and-replace/">http://wordpress.org/plugins/search-and-replace/</a></p> <p>Just search for the old url and replace with the new one. Before doing this though, make sure you have a backup of the database. You can never guarantee the results when using plugins to mess with your database. But this has always worked for me.</p>
6,403,055
Object destruction in C++
<p>When exactly are objects destroyed in C++, and what does that mean? Do I have to destroy them manually, since there is no Garbage Collector? How do exceptions come into play?</p> <p><sub><i> (Note: This is meant to be an entry to <a href="https://stackoverflow.com/questions/tagged/c++-faq">Stack Overflow's C++ FAQ</a>. If you want to critique the idea of providing an FAQ in this form, then <a href="https://meta.stackexchange.com/questions/68647/setting-up-a-faq-for-the-c-tag">the posting on meta that started all this</a> would be the place to do that. Answers to that question are monitored in the <a href="https://chat.stackoverflow.com/rooms/10/c-lounge">C++ chatroom</a>, where the FAQ idea started out in the first place, so your answer is very likely to get read by those who came up with the idea.) </i></sub></p>
6,403,057
2
19
null
2011-06-19 14:43:19.833 UTC
51
2021-08-10 15:25:10.08 UTC
2021-08-10 15:25:10.08 UTC
null
438,992
null
252,000
null
1
78
c++|exception|destructor|c++-faq|object-lifetime
37,931
<p>In the following text, I will distinguish between <em>scoped objects</em>, whose time of destruction is statically determined by their enclosing scope (functions, blocks, classes, expressions), and <em>dynamic objects</em>, whose exact time of destruction is generally not known until runtime.</p> <p>While the destruction semantics of class objects are determined by destructors, the destruction of a scalar object is always a no-op. Specifically, destructing a pointer variable does <em>not</em> destroy the pointee.</p> <h1>Scoped objects</h1> <h2>automatic objects</h2> <p>Automatic objects (commonly referred to as "local variables") are destructed, in reverse order of their definition, when control flow leaves the scope of their definition:</p> <pre><code>void some_function() { Foo a; Foo b; if (some_condition) { Foo y; Foo z; } &lt;--- z and y are destructed here } &lt;--- b and a are destructed here </code></pre> <p>If an exception is thrown during the execution of a function, all previously constructed automatic objects are destructed before the exception is propagated to the caller. This process is called <em>stack unwinding</em>. During stack unwinding, no further exceptions may leave the destructors of the aforementioned previously constructed automatic objects. Otherwise, the function <code>std::terminate</code> is called.</p> <p>This leads to one of the most important guidelines in C++:</p> <blockquote> <p>Destructors should never throw.</p> </blockquote> <h2>non-local static objects</h2> <p>Static objects defined at namespace scope (commonly referred to as "global variables") and static data members are destructed, in reverse order of their definition, after the execution of <code>main</code>:</p> <pre><code>struct X { static Foo x; // this is only a *declaration*, not a *definition* }; Foo a; Foo b; int main() { } &lt;--- y, x, b and a are destructed here Foo X::x; // this is the respective definition Foo y; </code></pre> <p>Note that the relative order of construction (and destruction) of static objects defined in different translation units is undefined.</p> <p>If an exception leaves the destructor of a static object, the function <code>std::terminate</code> is called.</p> <h2>local static objects</h2> <p>Static objects defined inside functions are constructed when (and if) control flow passes through their definition for the first time.<sup>1</sup> They are destructed in reverse order after the execution of <code>main</code>:</p> <pre><code>Foo&amp; get_some_Foo() { static Foo x; return x; } Bar&amp; get_some_Bar() { static Bar y; return y; } int main() { get_some_Bar().do_something(); // note that get_some_Bar is called *first* get_some_Foo().do_something(); } &lt;--- x and y are destructed here // hence y is destructed *last* </code></pre> <p>If an exception leaves the destructor of a static object, the function <code>std::terminate</code> is called.</p> <p><sub>1: This is an extremely simplified model. The initialization details of static objects are actually much more complicated.</sub></p> <h2>base class subobjects and member subobjects</h2> <p>When control flow leaves the destructor body of an object, its member subobjects (also known as its "data members") are destructed in reverse order of their definition. After that, its base class subobjects are destructed in reverse order of the base-specifier-list:</p> <pre><code>class Foo : Bar, Baz { Quux x; Quux y; public: ~Foo() { } &lt;--- y and x are destructed here, }; followed by the Baz and Bar base class subobjects </code></pre> <p>If an exception is thrown during the <em>construction</em> of one of <code>Foo</code>'s subobjects, then all its previously constructed subobjects will be destructed before the exception is propagated. The <code>Foo</code> destructor, on the other hand, will <em>not</em> be executed, since the <code>Foo</code> object was never fully constructed.</p> <p>Note that the destructor body is not responsible for destructing the data members themselves. You only need to write a destructor if a data member is a handle to a resource that needs to be released when the object is destructed (such as a file, a socket, a database connection, a mutex, or heap memory).</p> <h2>array elements</h2> <p>Array elements are destructed in descending order. If an exception is thrown during the <em>construction</em> of the n-th element, the elements n-1 to 0 are destructed before the exception is propagated.</p> <h2>temporary objects</h2> <p>A temporary object is constructed when a prvalue expression of class type is evaluated. The most prominent example of a prvalue expression is the call of a function that returns an object by value, such as <code>T operator+(const T&amp;, const T&amp;)</code>. Under normal circumstances, the temporary object is destructed when the full-expression that lexically contains the prvalue is completely evaluated:</p> <pre><code>__________________________ full-expression ___________ subexpression _______ subexpression some_function(a + " " + b); ^ both temporary objects are destructed here </code></pre> <p>The above function call <code>some_function(a + " " + b)</code> is a full-expression because it is not part of a larger expression (instead, it is part of an expression-statement). Hence, all temporary objects that are constructed during the evaluation of the subexpressions will be destructed at the semicolon. There are two such temporary objects: the first is constructed during the first addition, and the second is constructed during the second addition. The second temporary object will be destructed before the first.</p> <p>If an exception is thrown during the second addition, the first temporary object will be destructed properly before propagating the exception.</p> <p>If a local reference is initialized with a prvalue expression, the lifetime of the temporary object is extended to the scope of the local reference, so you won't get a dangling reference:</p> <pre><code>{ const Foo&amp; r = a + " " + b; ^ first temporary (a + " ") is destructed here // ... } &lt;--- second temporary (a + " " + b) is destructed not until here </code></pre> <p>If a prvalue expression of non-class type is evaluated, the result is a <em>value</em>, not a temporary object. However, a temporary object <em>will</em> be constructed if the prvalue is used to initialize a reference:</p> <pre><code>const int&amp; r = i + j; </code></pre> <h1>Dynamic objects and arrays</h1> <p>In the following section, <em>destroy X</em> means "first destruct X and then release the underlying memory". Similarly, <em>create X</em> means "first allocate enough memory and then construct X there".</p> <h2>dynamic objects</h2> <p>A dynamic object created via <code>p = new Foo</code> is destroyed via <code>delete p</code>. If you forget to <code>delete p</code>, you have a resource leak. You should never attempt to do one of the following, since they all lead to undefined behavior:</p> <ul> <li>destroy a dynamic object via <code>delete[]</code> (note the square brackets), <code>free</code> or any other means</li> <li>destroy a dynamic object multiple times</li> <li>access a dynamic object after it has been destroyed</li> </ul> <p>If an exception is thrown during the <em>construction</em> of a dynamic object, the underlying memory is released before the exception is propagated. (The destructor will <em>not</em> be executed prior to memory release, because the object was never fully constructed.)</p> <h2>dynamic arrays</h2> <p>A dynamic array created via <code>p = new Foo[n]</code> is destroyed via <code>delete[] p</code> (note the square brackets). If you forget to <code>delete[] p</code>, you have a resource leak. You should never attempt to do one of the following, since they all lead to undefined behavior:</p> <ul> <li>destroy a dynamic array via <code>delete</code>, <code>free</code> or any other means</li> <li>destroy a dynamic array multiple times</li> <li>access a dynamic array after it has been destroyed</li> </ul> <p>If an exception is thrown during the <em>construction</em> of the n-th element, the elements n-1 to 0 are destructed in descending order, the underlying memory is released, and the exception is propagated.</p> <p>(You should generally prefer <code>std::vector&lt;Foo&gt;</code> over <code>Foo*</code> for dynamic arrays. It makes writing correct and robust code much easier.)</p> <h2>reference-counting smart pointers</h2> <p>A dynamic object managed by several <code>std::shared_ptr&lt;Foo&gt;</code> objects is destroyed during the destruction of the last <code>std::shared_ptr&lt;Foo&gt;</code> object involved in sharing that dynamic object.</p> <p>(You should generally prefer <code>std::shared_ptr&lt;Foo&gt;</code> over <code>Foo*</code> for shared objects. It makes writing correct and robust code much easier.)</p>
1,488,162
jQuery: Refresh div after another jquery action?
<p>How do I refresh element (div, class whatever) after another jquery action?</p> <p>I have this action which is deleting a record from database and I need to refresh div which is fetching some other data from database as well...</p> <p>Well here's code:</p> <pre><code>$(function() { $(".delete").click(function() { var commentContainer = $(this).parent(); var id = $(this).attr("id"); var string = 'id='+ id ; $.ajax({ type: "POST", url: "delete.php", data: string, cache: false, success: function(){ commentContainer.slideUp('slow', function() {$(this).remove();}); } }); return false; }); }); </code></pre> <p>Thanks for all help! :)</p>
1,488,200
4
2
null
2009-09-28 16:59:43.76 UTC
2
2009-09-28 17:39:25.377 UTC
2009-09-28 17:39:25.377 UTC
null
53,162
null
124,962
null
1
5
jquery|refresh
43,624
<p>During an AJAX call you can use the success function to run commands after a successful call. You already have a function in your code so its a simple matter of updating that function. The second div that you will like to update can be loaded with AJAX too.</p> <pre><code> $.ajax({ //other options success:function(){ commentContainer.slideUp('slow', function() {$(this).remove();}); $('#otherdiv').load('urlofpagewith info.php'); } }); </code></pre>
1,563,961
How to find top n% of records in a column of a dataframe using R
<p>I have a dataset showing the exchange rate of the Australian Dollar versus the US dollar once a day over a period of about 20 years. I have the data in a data frame, with the first column being the date, and the second column being the exchange rate. Here's a sample from the data:</p> <pre><code>&gt;data V1 V2 1 12/12/1983 0.9175 2 13/12/1983 0.9010 3 14/12/1983 0.9000 4 15/12/1983 0.8978 5 16/12/1983 0.8928 6 19/12/1983 0.8770 7 20/12/1983 0.8795 8 21/12/1983 0.8905 9 22/12/1983 0.9005 10 23/12/1983 0.9005 </code></pre> <p>How would I go about displaying the top n% of these records? E.g. say I want to see the days and exchange rates for those days where the exchange rate falls in the top 5% of all exchange rates in the dataset?</p>
1,563,978
4
0
null
2009-10-14 02:28:40.603 UTC
12
2020-03-20 14:06:03.123 UTC
2015-01-03 21:47:32.33 UTC
null
4,015,623
null
129,475
null
1
27
r|dataframe
35,709
<p>For the top 5%:</p> <pre><code>n &lt;- 5 data[data$V2 &gt; quantile(data$V2,prob=1-n/100),] </code></pre>
1,604,815
How to use group by with union in T-SQL
<p>How can I using group by with union in T-SQL? I want to group by the first column of a result of union, I wrote the following SQL but it doesn't work. I just don't know how to reference the specified column (in this case is 1) of the union result.</p> <pre><code>SELECT * FROM ( SELECT a.id , a.time FROM dbo.a UNION SELECT b.id , b.time FROM dbo.b ) GROUP BY 1 </code></pre>
1,604,881
4
0
null
2009-10-22 03:08:27.147 UTC
3
2021-06-14 23:58:36.103 UTC
2021-06-14 23:58:36.103 UTC
null
1,127,428
null
170,931
null
1
32
sql|sql-server|tsql|group-by|union
166,139
<blockquote> <p>GROUP BY 1</p> </blockquote> <p>I've never known GROUP BY to support using ordinals, only ORDER BY. Either way, only MySQL supports GROUP BY's not including all columns without aggregate functions performed on them. Ordinals aren't recommended practice either because if they're based on the order of the SELECT - if that changes, so does your ORDER BY (or GROUP BY if supported).</p> <p>There's no need to run <code>GROUP BY</code> on the contents when you're using <code>UNION</code> - UNION ensures that duplicates are removed; <code>UNION ALL</code> is faster because it doesn't - and in that case you would need the GROUP BY...</p> <p>Your query only needs to be:</p> <pre><code>SELECT a.id, a.time FROM dbo.TABLE_A a UNION SELECT b.id, b.time FROM dbo.TABLE_B b </code></pre>
1,439,513
Creating a sequential list of letters with R
<p>I would like to be able to create a sequence of letters in R (to assist in importing data from a SPSS file)</p> <p>It's quite easy to create a sequence of numbers, for example:</p> <pre><code>seq(1,1000) [1] 1 2 3 4 5 6 ... 1000 paste("something_",1:12,sep="") [1] something1 something2 ... something12 </code></pre> <p>But is there any functionality for appending, pasting, or creating sequences of letters like this? </p> <pre><code>paste("This_",a:z,sep="") [1]This_a This_b This_c ... This_4z </code></pre> <p>Thanks in advance! </p>
1,439,843
4
0
null
2009-09-17 15:15:26.193 UTC
9
2020-03-21 15:52:49.787 UTC
null
null
null
null
170,352
null
1
48
r|alphabet
107,109
<p>This is what you're looking for:</p> <pre><code>&gt; paste("This_", letters, sep="") &gt; [1] "This_a" "This_b" "This_c" "This_d" "This_e" "This_f" "This_g" "This_h" [9] "This_i" "This_j" "This_k" "This_l" "This_m" "This_n" "This_o" "This_p" [17] "This_q" "This_r" "This_s" "This_t" "This_u" "This_v" "This_w" "This_x" [25] "This_y" "This_z" </code></pre>
10,270,452
JQuery change not firing until blur
<p>I use change(handler) to listen to change events to a textarea, but I only receive an event when the textarea loses focus, but I want to receive an event as soon as the value changes.</p> <pre><code>$("#text_object").change(listener); function listener(dom){ alert("I'm not getting here before the textarea loses focus"); } </code></pre>
10,270,535
7
2
null
2012-04-22 17:47:23.317 UTC
1
2021-02-25 17:32:13.78 UTC
null
null
null
null
821,562
null
1
39
jquery
23,949
<p>Unfortunately the browser only recognises a change when the field blurs, so you might want to try attaching a keyup listener. Not the most elegant solution, unfortunately.</p> <p>Details at <a href="http://api.jquery.com/keyup/" rel="noreferrer">http://api.jquery.com/keyup/</a>.</p>
28,806,092
How to find integer array size in java
<p>below is my code which is throwing error:</p> <pre><code>Cannot invoke size() on the array type int[] </code></pre> <p>Code:</p> <pre><code>public class Example{ int[] array={1,99,10000,84849,111,212,314,21,442,455,244,554,22,22,211}; public void Printrange(){ for (int i=0;i&lt;array.size();i++){ if(array[i]&gt;100 &amp;&amp; array[i]&lt;500) { System.out.println("numbers with in range ":+array[i]); } } </code></pre> <p>Even i tried with <code>array.length()</code> it also throwing the same error. When i used the same with <code>string_name.length()</code> is working fine.</p> <p>Why it is not working for an integer array?</p>
28,806,119
7
2
null
2015-03-02 09:14:28.853 UTC
6
2018-11-08 22:06:27.623 UTC
2015-03-02 09:15:10.873 UTC
user1907906
null
null
4,576,964
null
1
16
java|arrays|printing|size|range
139,453
<p>The length of an array is available as</p> <pre><code>int l = array.length; </code></pre> <p>The size of a <code>List</code> is availabe as </p> <pre><code>int s = list.size(); </code></pre>
36,285,155
Pandas: Get Dummies
<p>I have the following dataframe:</p> <pre><code> amount catcode cid cycle date di feccandid type 0 1000 E1600 N00029285 2014 2014-05-15 D H8TX22107 24K 1 5000 G4600 N00026722 2014 2013-10-22 D H4TX28046 24K 2 4 C2100 N00030676 2014 2014-03-26 D H0MO07113 24Z </code></pre> <p>I want to make dummy variables for the values in column <code>type</code>. There about 15. I have tried this:</p> <p><code>pd.get_dummies(df['type'])</code></p> <p>And it returns this:</p> <pre><code> 24A 24C 24E 24F 24K 24N 24P 24R 24Z date 2014-05-15 0 0 0 0 1 0 0 0 0 2013-10-22 0 0 0 0 1 0 0 0 0 2014-03-26 0 0 0 0 0 0 0 0 1 </code></pre> <p>What I would like is to have a dummy variable column for each unique value in <code>Type</code></p>
36,285,489
5
6
null
2016-03-29 13:05:36.237 UTC
12
2022-09-23 21:03:17.243 UTC
2018-03-02 22:24:58.3 UTC
null
5,411,817
null
5,211,377
null
1
52
python|pandas|dummy-variable
126,162
<p>You can try :</p> <pre><code>df = pd.get_dummies(df, columns=['type']) </code></pre>
7,331,923
How to use division in JavaScript
<p>I want to divide a number in JavaScript and it would return a decimal value.</p> <p>For example: <code>737/1070</code> - I want JavaScript to return <code>0.68</code>; however it keeps rounding it off and return it as <code>0</code>.</p> <p>How do I set it to return me either two decimals place or the full results?</p>
7,331,939
6
2
null
2011-09-07 09:53:53.11 UTC
3
2021-07-18 13:22:46.527 UTC
2019-01-27 10:03:34.363 UTC
null
4,298,200
null
502,963
null
1
67
javascript|division
96,772
<p>Make one of those numbers a float.</p> <pre><code>737/parseFloat(1070) </code></pre> <p>or a bit faster:</p> <pre><code>737*1.0/1070 </code></pre> <p>convert to 2 decimal places</p> <pre><code>Math.round(737 * 100.0 / 1070) / 100 </code></pre>
7,259,142
How to list all properties of a PowerShell WMI object
<p>When I look at the <a href="http://msdn.microsoft.com/en-us/library/aa394102%28v=VS.85%29.aspx" rel="noreferrer">Win32_ComputerSystem class</a>, it shows loads of properties like <code>Status</code>, <code>PowerManagementCapabilities</code>, etc. However, when in PowerShell I do the below I only get back a couple:</p> <pre class="lang-none prettyprint-override"><code>PS C:\Windows\System32\drivers&gt; Get-WmiObject -Class "Win32_computersystem" Domain : YYY.com Manufacturer : VMware, Inc. Model : VMware Virtual Platform Name : LONINEGFQEF58 PrimaryOwnerName : Authorised User TotalPhysicalMemory : 2147016704 </code></pre> <p>How can I see all properties?</p>
7,259,178
6
0
null
2011-08-31 15:10:18.227 UTC
30
2022-09-18 00:15:02.103 UTC
2022-09-16 05:57:30.09 UTC
null
25,702
null
461,030
null
1
140
powershell|wmi|get-wmiobject
279,090
<p>Try this:</p> <pre><code>Get-WmiObject -Class "Win32_computersystem" | Format-List * Get-WmiObject -Class "Win32_computersystem" | Format-List -Property * </code></pre> <p>For certain objects, PowerShell provides a set of formatting instructions that can affect either the table or list formats. These are usually meant to limit the display of reams of properties down to just the essential properties. However there are times when you really want to see everything. In those cases <code>Format-List *</code> will show all the properties. Note that in the case where you're trying to view a PowerShell error record, you need to use "Format-List * -Force" to truly see all the error information, for example,</p> <pre><code>$error[0] | Format-List * -force </code></pre> <p>Note that the wildcard can be used like a traditional wilcard this:</p> <pre><code>Get-WmiObject -Class "Win32_computersystem" | Format-List M* </code></pre>
7,203,251
javascript/html autocomplete textbox
<p>I am developing a web page which has a requirement of many autocomplete textboxes. As I am new to javascript, it is very tough for me to make my own autocomplete textbox. So I have searched many examples from the internet, but they only work for a single textbox. This means I cannot use the same js file to make another autocomplete textbox. I didn't find any such examples on stackoverflow either. Can someone help me in this? </p>
7,203,302
8
0
null
2011-08-26 10:17:14.457 UTC
6
2021-09-18 23:00:06.897 UTC
2014-06-25 21:32:26.54 UTC
null
-1
null
821,144
null
1
25
javascript|html
86,104
<p>Use JQuery with the AutoSuggest plugin.</p> <p><a href="http://docs.jquery.com/Plugins/autocomplete" rel="noreferrer">http://docs.jquery.com/Plugins/autocomplete</a></p> <p>Include the JS libraries (see the documentation above), then do this in HTML:</p> <pre><code>&lt;input type="text" class="autocomplete" name="n1" /&gt; &lt;input type="text" class="autocomplete" name="n2" /&gt; &lt;input type="text" class="autocomplete" name="n3" /&gt; &lt;input type="text" class="autocomplete" name="n4" /&gt; </code></pre> <p>Then add an Autocomplete to the CSS-class in your Javascript:</p> <pre><code>var data = "Core Selectors Attributes Traversing Manipulation CSS Events Effects Ajax Utilities".split(" "); $(".autocomplete").autocomplete(data); </code></pre>
13,884,293
Using a html select box with razor
<p>I have a html selector, and I want to use the selected value for my "model => model.type" in my form. Is there a way to set the value in my <code>@Html.EditorFor(model =&gt; model.type)</code> to the value of the selector?</p> <pre><code>@using (Html.BeginForm()) { @Html.ValidationSummary(true) &lt;fieldset&gt; &lt;legend&gt;Bet&lt;/legend&gt; &lt;div class="editor-label"&gt; @Html.LabelFor(model =&gt; model.type) &lt;/div&gt; &lt;div class="editor-field"&gt; &lt;select id ="type"&gt; &lt;option value="Football"&gt;Football&lt;/option&gt; &lt;option value="Rugby"&gt;Rugby&lt;/option&gt; &lt;option value="Horse Racing"&gt;Horse Racing&lt;/option&gt; &lt;/select&gt; @Html.EditorFor(model =&gt; model.type) @Html.ValidationMessageFor(model =&gt; model.type) &lt;/div&gt; &lt;p&gt; &lt;input type="submit" value="Create" /&gt; &lt;/p&gt; &lt;/fieldset&gt; </code></pre>
13,886,378
5
3
null
2012-12-14 18:25:56.117 UTC
2
2018-08-01 05:29:44.507 UTC
2012-12-14 18:40:19.85 UTC
null
727,208
null
1,505,482
null
1
12
asp.net-mvc|razor
54,042
<p>You can try with this options:</p> <p>Model:</p> <pre><code>public string Type { get; set; } public IEnumerable&lt;SelectListItem&gt; TypeList { get { return new List&lt;SelectListItem&gt; { new SelectListItem { Text = "Football", Value = "Football"}, new SelectListItem { Text = "Rugby", Value = "Rugby"}, new SelectListItem { Text = "Horse Racing", Value = "Horse Racing"} }; } } </code></pre> <p>HTML (Razor):</p> <pre><code>@Html.DropDownListFor(model =&gt; model.Type, Model.TypeList) </code></pre> <p>OR</p> <p>HTML (Razor):</p> <pre><code>@Html.DropDownListFor(model =&gt; model.Type, new SelectList(new string[] {"Football", "Rugby", "Horse Racing"}, Model.Type)) </code></pre>
14,062,932
libraries to CAPTURE panorama in iOS 6
<p>There are a lot of ways and libraries to show panorama picture in iOS, Although there is a panorama feature in the built-in camera there is no way to use it within an app.</p> <p>Is there any library I can use to capture a panorama image?</p> <p>Thanks!</p>
14,064,788
1
0
null
2012-12-28 00:03:29.527 UTC
24
2014-06-04 20:59:07.427 UTC
null
null
null
null
1,071,887
null
1
13
iphone|ios|ios6|panoramas
9,826
<p><a href="http://www.cs.bath.ac.uk/brown/autostitch/autostitch.html#licensing" rel="nofollow noreferrer">These people</a> might sell you a license for a c++ library. Their code goes into the brilliant Autostich app available in the App Store. </p> <p>Autostitch is based on SIFT image feature detection. SIFT and many other techniques are available in the <a href="http://openCv.org" rel="nofollow noreferrer">openCv c++ library</a>. A pre built iOS framework is available from that site. </p> <p><strong>update</strong> </p> <p>OpenCV has a <code>Stitcher</code> class with mounds of documentation... </p> <p><a href="http://docs.opencv.org/modules/stitching/doc/high_level.html#stitcher" rel="nofollow noreferrer">OpenCV Stitching pipline</a> </p> <p><a href="http://docs.opencv.org/modules/stitching/doc/high_level.html#stitcher" rel="nofollow noreferrer">OpenCV Stitcher class</a></p> <blockquote> <p>"High level image stitcher. It’s possible to use this class without being aware of the entire stitching pipeline. However, to be able to achieve higher stitching stability and quality of the final images at least being familiar with the theory is recommended (see <a href="http://docs.opencv.org/modules/stitching/doc/high_level.html#stitcher" rel="nofollow noreferrer">Stitching pipline</a> )."</p> </blockquote> <p><strong>update 2</strong></p> <p>If you haven't used openCV before, the first hurdle is to get the library compiled and installed into your project. Can be tricky, see my questions and answers <a href="https://stackoverflow.com/questions/13905471/opencv-2-4-3-ios-framework-compiler-trouble-recognising-some-c-headers">here</a> (getting openCV installed and working) and <a href="https://stackoverflow.com/questions/13958321/iosretrieve-rectangle-shaped-image-from-the-background-image/14123682#14123682">here</a> (an example how to keep c++ code separate from objective-c, with sample github project).</p> <p>When you have openCV working, this should be the quickest way to get started with your query:</p> <pre><code>Stitcher::stitch(InputArray images, OutputArray pano) </code></pre> <p>Parameters:<br> images – Input images.<br> pano – Final pano. </p> <p>Then to speed it up - if you have them - provide regions of interest rects (indicating where photos overlap)</p> <pre><code>Stitcher::stitch(InputArray images, const std::vector&lt;std::vector&lt;Rect&gt;&gt;&amp; rois, OutputArray pano) </code></pre> <p>You can dig into the stitching pipeline to optimise many details of the process, but this should be enough to get you started.</p> <p>If you look in the samples/cpp folder of the openCV distro, you will see a couple of stitching examples, <a href="https://github.com/Itseez/opencv/blob/master/samples/cpp/stitching.cpp" rel="nofollow noreferrer"><code>stitching.cpp</code></a> and <a href="https://github.com/Itseez/opencv/blob/master/samples/cpp/stitching_detailed.cpp" rel="nofollow noreferrer"><code>stitching_detailed.cpp</code></a>.</p> <p>To provide the input images you will want to hook up with the camera and design a decent user interface to assist the user in taking the right kind of pictures (eg with good overlaps).</p> <p>If you want to look at an existing project using openCV, <a href="https://code.google.com/p/android-opencv-panorama/" rel="nofollow noreferrer">here is one for android</a> that claims to do what you are after - different platform, but the principles will be the same (using a java interface into the same libraries). Take a look especially at <a href="https://code.google.com/p/android-opencv-panorama/source/browse/android/pano/src/net/pandorica/opencv/pano/PanoActivity.java" rel="nofollow noreferrer">PanoActivity.java</a>.</p> <p><strong>update 3</strong><br> I've uploaded <a href="https://github.com/foundry/OpenCVStitch" rel="nofollow noreferrer">a very basic sample to github</a>. I'm impressed how good a job it does, without any optimising or tweaking. It stitches the sample photos in my github project almost as well as the Autostitch app.</p> <p><strong>update 4</strong> <em>some time later...</em> I've made a new sample project <a href="https://github.com/foundry/OpenCVSwiftStitch" rel="nofollow noreferrer">updated for use with Swift and Cocoapods</a></p>
14,228,151
Datepicker plugin for birth date textbox
<p>I've found a very easy to use datepicker called jquery datepicker. But the problem is when I want to use it for birth date. For example: my birth year is 1986 and the current year is 2013, then I need to click left arrow many times to decrease the months until I find 1986. It will be more troublesome if my birth year is 1960 or below.</p> <p>Does anybody know any datepicker plugin that suitable for this? Perhaps a datepicker which year or month can be selected from dropbox or something?</p>
14,228,178
3
0
null
2013-01-09 04:11:29.243 UTC
2
2017-07-26 08:07:52.78 UTC
2013-01-18 13:25:19.8 UTC
null
1,437,962
null
1,799,794
null
1
14
jquery|jquery-plugins|datepicker
48,099
<p><strong>In short:</strong> you may do that bythe Restricting Datepicker section in the <a href="http://jqueryui.com/datepicker/#dropdown-month-year">demo page</a>.</p> <p>If you look down the <a href="http://jqueryui.com/datepicker/#dropdown-month-year">demo page</a> a bit, you'll see a "Restricting Datepicker" section. Use the dropdown to specify the "<code>Year dropdown shows last 20 years</code>" demo , and hit view source:</p> <pre><code>$("#restricting").datepicker({ yearRange: "-20:+0", // this is the option you're looking for showOn: "both", buttonImage: "templates/images/calendar.gif", buttonImageOnly: true }); </code></pre> <p>You'll want to do the same (obviously changing <code>-20</code> to <code>-100</code> or something).</p> <p><strong>Option # 2:</strong> is using the <code>changeMonth</code> and <code>changeYear</code> options of the api.</p> <p>Try using 'yy' for the current year like:</p> <pre><code>$('.datepicker').datepicker({changeYear: true, yearRange : 'yy-50:yy+1'}); </code></pre> <p>for more information view <a href="http://api.jqueryui.com/datepicker/#option-yearRange">http://api.jqueryui.com/datepicker/#option-yearRange</a></p>
13,857,331
SQL Server 2008 thousands separator for a column
<p>I have a column called <code>TotalArea</code> and its format is <code>numeric (12,2)</code>.</p> <p>I want it to display the numbers with a thousand separator so when I </p> <pre><code>select TotalArea from table </code></pre> <p>to show me a format like <code>1,234.00</code>.</p> <p>How could I do that? Thanks!</p>
13,857,441
4
1
null
2012-12-13 10:01:24.017 UTC
5
2020-05-04 12:37:51.42 UTC
2012-12-13 10:17:15.857 UTC
null
13,302
null
1,820,705
null
1
35
sql|sql-server|database|sql-server-2008|tsql
96,983
<p>Try this way:</p> <pre><code>SELECT REPLACE(CONVERT(VARCHAR, CONVERT(MONEY, TotalArea), 1), '.00', '') FROM table </code></pre> <p>or</p> <pre><code>SELECT CAST(CONVERT(VARCHAR, CAST(123456 AS MONEY), 1) AS VARCHAR) FROM table </code></pre>
14,245,769
Check all Checkboxes in Page via Developer Tools
<p>I have a loop that creates 20 <strong><em>check-boxes</em></strong> in the same page (it creates different forms). I want via <strong><em>chrome developer tools</em></strong> to run a JavaScript without the use of any library that <strong><em>CHECK</em></strong> all <em>check-boxes</em> at the same time.</p> <h2>This is as far as I got:</h2> <pre><code>function() { var aa= document.getElementsByTagName("input"); for (var i =0; i &lt; aa.length; i++){ aa.elements[i].checked = checked; } } </code></pre> <p>PS: I have searched and found a lot of Questions in Stack-Overflow but none worked for me, I'll be glad if someone could find me the correct answer.</p>
14,245,862
9
1
null
2013-01-09 20:22:25.29 UTC
21
2022-04-24 23:17:12.153 UTC
2013-08-08 19:52:33.137 UTC
null
1,699,961
null
1,699,961
null
1
55
javascript|google-chrome|checkbox|google-chrome-devtools
52,039
<pre><code>(function() { var aa= document.getElementsByTagName("input"); for (var i =0; i &lt; aa.length; i++){ if (aa[i].type == 'checkbox') aa[i].checked = true; } })() </code></pre> <p>With up to date browsers can use <a href="https://developer.mozilla.org/en-US/docs/Web/API/Document.querySelectorAll">document.querySelectorAll</a></p> <pre><code>(function() { var aa = document.querySelectorAll("input[type=checkbox]"); for (var i = 0; i &lt; aa.length; i++){ aa[i].checked = true; } })() </code></pre>
14,158,868
Python: skip comment lines marked with # in csv.DictReader
<p>Processing CSV files with <a href="http://docs.python.org/2/library/csv.html#csv.DictReader" rel="noreferrer">csv.DictReader</a> is great - but I have CSV files with comment lines (indicated by a hash at the start of a line), for example:</p> <pre class="lang-none prettyprint-override"><code># step size=1.61853 val0,val1,val2,hybridisation,temp,smattr 0.206895,0.797923,0.202077,0.631199,0.368801,0.311052,0.688948,0.597237,0.402763 -169.32,1,1.61853,2.04069e-92,1,0.000906546,0.999093,0.241356,0.758644,0.202382 # adaptation finished </code></pre> <p>The csv module <a href="http://bugs.python.org/issue1225769" rel="noreferrer">doesn't include any way to skip such lines</a>.</p> <p>I could easily do something hacky, but I imagine there's a nice way to wrap a <code>csv.DictReader</code> around some other iterator object, which preprocesses to discard the lines.</p>
14,158,869
4
0
null
2013-01-04 14:20:30.043 UTC
18
2021-11-04 05:28:15.317 UTC
2021-11-04 05:28:15.317 UTC
null
10,794,031
null
1,563,927
null
1
86
python|csv|comments
33,407
<p>Actually this works nicely with <code>filter</code>:</p> <pre><code>import csv fp = open('samples.csv') rdr = csv.DictReader(filter(lambda row: row[0]!='#', fp)) for row in rdr: print(row) fp.close() </code></pre>
43,177,074
How to fix this violation of this 'react/no-unescaped-entitie' of eslint rule?
<p>This is my code:</p> <pre><code>const func = () =&gt; { return ( &lt;div &gt; you're free &lt;/div&gt; )} </code></pre> <p>Somehow eslint flags the line "you're free" with error <code>error HTML entities must be escaped react/no-unescaped-entities</code></p> <p>However from what I can see jsx has escaped the apostrophes already. I can see the words <code>you're free</code> is rendered without issue. If I escape it as <code>&amp;#39;</code>, then it will be very hard for me to search for the string (I would expect a search of <code>you're free</code> in an editor to return a hit. But obviously the editor will miss because the text is actually <code>you&amp;#39;re free</code>)</p> <p>So what is the best way to address this eslint exception?</p>
45,898,131
6
1
null
2017-04-03 05:29:15.553 UTC
9
2022-04-26 08:29:01.153 UTC
2017-04-07 09:20:30.653 UTC
null
58,129
null
58,129
null
1
74
reactjs|eslint|eslint-config-airbnb
65,526
<p>Recommended solution is to use <code>&amp;apos;</code>, <code>&amp;lsquo;</code> or <code>&amp;rsquo;</code> instead of wrapping it as a variable. So like this:</p> <pre><code>const func = () =&gt; { return ( &lt;div &gt; you&amp;apos;re free &lt;/div&gt; )} </code></pre> <p>For search-ability, it's recommended you have files for localization/internationalization and call them into your app.</p>
43,351,596
Activating Anaconda Environment in VsCode
<p>I have Anaconda working on my system and VsCode working, but how do I get VsCode to activate a specific environment when running my python script?</p>
43,352,598
15
1
null
2017-04-11 16:33:50.373 UTC
37
2021-12-18 16:51:51.393 UTC
null
null
null
null
30,889
null
1
94
python|visual-studio-code|anaconda
185,341
<p>If Anaconda is your default Python install then it just works if you install the <a href="https://marketplace.visualstudio.com/items?itemName=ms-python.python" rel="noreferrer">Microsoft Python extension</a>.</p> <p>The following should work regardless of Python editor or if you need to point to a specific install:</p> <p>In settings.json edit python.path with something like</p> <pre><code>"python.pythonPath": "C:\\Anaconda3\\envs\\py34\\python.exe" </code></pre> <p><a href="https://code.visualstudio.com/docs/getstarted/settings" rel="noreferrer">Instructions</a> to edit settings.json</p>
19,334,542
Why can I type alias functions and use them without casting?
<p>In Go, if you define a new type e.g.:</p> <pre><code>type MyInt int </code></pre> <p>You can't then pass a <code>MyInt</code> to a function expecting an int, or vice versa:</p> <pre><code>func test(i MyInt) { //do something with i } func main() { anInt := 0 test(anInt) //doesn't work, int is not of type MyInt } </code></pre> <p>Fine. But why is it then that the same does not apply to functions? e.g.:</p> <pre><code>type MyFunc func(i int) func (m MyFunc) Run(i int) { m(i) } func run(f MyFunc, i int) { f.Run(i) } func main() { var newfunc func(int) //explicit declaration newfunc = func(i int) { fmt.Println(i) } run(newfunc, 10) //works just fine, even though types seem to differ } </code></pre> <p>Now, I'm not complaining because it saves me having to explicitly cast <code>newfunc</code> to type <code>MyFunc</code>, as I would have to do in the first example; it just seems inconsistent. I'm sure there is a good reason for it; can anyone enlighten me?</p> <p>The reason I ask is mainly because I would like to shorten some of my rather long function types in this way, but I want to make sure it's expected and acceptable to do this :)</p>
19,334,952
4
3
null
2013-10-12 13:07:47.11 UTC
55
2022-09-20 16:15:16.61 UTC
2016-08-02 05:28:13.587 UTC
user6169399
null
null
1,339,698
null
1
117
types|casting|go
56,482
<p>Turns out, this is a misunderstanding that I had about how Go dealt with types, which can be resolved by reading the relevant part of the spec:</p> <p><a href="http://golang.org/ref/spec#Type_identity">http://golang.org/ref/spec#Type_identity</a></p> <p>The relevant distinction that I was unaware of was that of <strong>named</strong> and <strong>unnamed</strong> types.</p> <p><strong>Named</strong> types are types with a name, such as int, int64, float, string, bool. In addition, any type you create using 'type' is a named type.</p> <p><strong>Unnamed</strong> types are those such as []string, map[string]string, [4]int. They have no name, simply a description corresponding to how they are to be structured. </p> <p>If you compare two named types, the names must match in order for them to be interchangeable. If you compare a named and an unnamed type, then <strong>as long as the underlying representation matches</strong>, you're good to go!</p> <p>e.g. given the following types:</p> <pre><code>type MyInt int type MyMap map[int]int type MySlice []int type MyFunc func(int) </code></pre> <p>the following is invalid:</p> <pre><code>var i int = 2 var i2 MyInt = 4 i = i2 //both named (int and MyInt) and names don't match, so invalid </code></pre> <p>the following is fine:</p> <pre><code>is := make([]int) m := make(map[int]int) f := func(i int){} //OK: comparing named and unnamed type, and underlying representation //is the same: func doSlice(input MySlice){...} doSlice(is) func doMap(input MyMap){...} doMap(m) func doFunc(input MyFunc){...} doFunc(f) </code></pre> <p>I'm a bit gutted I didn't know that sooner, so I hope that clarifies the type lark a little for someone else! And means much less casting than I at first thought :)</p>
19,645,527
Trying to get PyCharm to work, keep getting "No Python interpreter selected"
<p>I'm trying to learn Python and decided to use PyCharm. When I try to start a new project I get a dialog that says "No Python interpreter selected". It has a drop down to select a interpreter, but the drop down is empty.</p>
19,676,884
12
3
null
2013-10-28 21:36:35.777 UTC
13
2021-09-18 10:20:23.42 UTC
2014-03-27 15:22:06.957 UTC
null
258,523
null
564,653
null
1
65
python|pycharm
251,837
<p>Your problem probably is that you haven't <em>installed</em> python. Meaning that, if you are using Windows, you have not downloaded the installer for Windows, that you can find on the official Python website.</p> <p>In case you have, chances are that PyCharm cannot find your Python installation because its not in the default location, which is usually <code>C:\Python27</code> or <code>C:\Python33</code> (for me at least).</p> <p>So, if you <em>have</em> installed Python and it still gives this error, then there can be two things that have happened:</p> <ol> <li>You use a <code>virtualenv</code> and that <code>virtualenv</code> has been deleted or the filepath changed. In this case, you will have to find proceed to the next part of this answer.</li> <li>Your python installation is not in its default place, in which case you will need to find its location, and locate the <code>python.exe</code> file.</li> </ol> <p>Once you have located the necessary binaries, you will need to tell PyCharm were to look:</p> <ol> <li>Open your settings dialogue <kbd>CTRL</kbd> + <kbd>ALT</kbd> + <kbd>S</kbd></li> <li><p>Then you will need to type in <code>interpreter</code> in the search box:</p> <p><img src="https://i.stack.imgur.com/pXdOR.png" alt="enter image description here"></p></li> <li><p>As you can see above, you will need to go to <code>Project Interpreter</code> and then go to <code>Python Interpreter</code>. The location has been selected for you in the above image.</p></li> <li><p>To the side you will see a couple of options as icons, click the big <code>+</code> icon, then click on <code>local</code>, because your interpreter is on <em>this</em> computer.</p></li> <li><p>This will open up a dialogue box. Make sure to select the <code>python.exe</code> file of that directory, do not give pycharm the whole directory. It just wants the interpreter.</p></li> </ol>
34,275,076
use locale (ltr/rtl) for gravity in TextView
<p>I have a simple TextView which should have <code>android:gravity="left"</code> for ltr system locales and <code>android:gravity="right"</code> for rtl system locales.</p> <p>The obvious choice would be: <code>android:gravity="start"</code> but then e.g. english text will always be left-aligned and hebrew right-aligned.</p> <p>Here is how it looks with <code>android:gravity="start"</code>:</p> <p>LTR locale:</p> <pre><code>| לורם| // incorrect |test | // correct </code></pre> <p>RTL locale:</p> <pre><code>| לורם| // correct |test | // incorrect </code></pre> <p>it's supposed to look like that:</p> <p>LTR locale:</p> <pre><code>|לורם | |test | </code></pre> <p>RTL locale:</p> <pre><code>| לורם| | test| </code></pre> <p>Is it possible to do that without using a layout-ldrtl folder with a modified xml file? This would complicate development a lot because I would have to edit a lot of layout files twice...</p> <p><em>edit:</em> a solution for API 17+ is enough. I wrote system locale, but actually I'm allowing the user to change the app language like that:</p> <pre class="lang-java prettyprint-override"><code>Configuration configuration = context.getResources().getConfiguration(); configuration.setLayoutDirection(selectedLocale); configuration.locale = selectedLocale; context.getResources().updateConfiguration(configuration, context.getResources().getDisplayMetrics()); </code></pre> <p>so it would be great if this locale would be considered for the rtl &lt;-> ltr choice.</p>
34,298,259
5
5
null
2015-12-14 19:28:51.673 UTC
14
2022-06-11 02:23:26.197 UTC
2015-12-15 07:47:49.323 UTC
null
3,755,928
null
3,755,928
null
1
32
android|layout|right-to-left
15,989
<p>I'm using this solution now, I would prefer a simple xml solution, but this seems minimal so far:</p> <pre><code>if (VERSION.SDK_INT &gt;= VERSION_CODES.JELLY_BEAN_MR1) { if (DynamicLanguage.getLayoutDirection(getContext()) == View.LAYOUT_DIRECTION_RTL) { this.textView.setGravity(Gravity.RIGHT); } else { this.textView.setGravity(Gravity.LEFT); } } </code></pre>
274,308
How does geographic lookup by IP work?
<p>Is which IPs are assigned to which ISPs public information? How do geo IP services obtain this information and maintain this information?</p> <p>How can I personally figure out where a certain IP belongs without using one of these services?</p>
277,537
5
1
null
2008-11-08 03:35:25.873 UTC
17
2017-02-10 15:58:53.507 UTC
2010-05-01 21:24:14.437 UTC
null
164,901
Brian R. Bondy
3,153
null
1
28
dns|ip|ip-geolocation
18,502
<p>For what it's worth, I worked at a senior level in the ISP industry for more than a decade so I have quite some experience with this.</p> <p>Large IP ranges are allocated as needed by <a href="http://www.iana.org/" rel="noreferrer">IANA</a> to each of the <a href="http://en.wikipedia.org/wiki/Regional_Internet_Registry" rel="noreferrer">Regional Internet Registries</a>.</p> <p>The regions are generally continental in size - IP addresses are <strong>not</strong> assigned on a per-country basis.</p> <p>The RIRs in turn then allocate IP addresses to ISPs, who in turn assign them to end-users.</p> <p>Each of the RIRs maintain a <code>whois</code> server which can be queried to find out not only which ISP has been assigned any netblock, but to a certain extent which end-user, and that end-user's address.</p> <p>Note that many ISPs do not fill out this information for every single customer. Hence if you're a residential subscriber of a DSL service, it's likely that the Geo records will give the address of your ISP, and not your own address.</p> <p>The various GeoLocation providers mostly work by mining these <code>whois</code> records. Note that the legality of doing so is something of a gray area - RIPE's database copyright statement is <a href="http://www.ripe.net/db/copyright.html" rel="noreferrer">here</a>.</p> <p>IANA also maintains the root zone for the DNS, but that is completely separate from any IP allocation functions. It is very important to maintain the distinction between domain name operations and IP addresses.</p>
261,815
Upper limit for autoincrement primary key in SQL Server
<p>What is the upper limit for an autoincrement primary key in SQL Server? What happens when an SQL Server autoincrement primary key reaches its upper limit?</p>
261,868
5
0
null
2008-11-04 13:02:51.047 UTC
10
2011-04-21 18:18:04.213 UTC
null
null
null
Dema
407,003
null
1
36
sql|sql-server|auto-increment
29,451
<p>Joel's answer is correct, it is the upper limit of whatever datatype you use.</p> <p>Here's an example of two of them:</p> <ul> <li>int: 2^31-1 (2,147,483,647) </li> <li>bigint: 2^63-1 (9,223,372,036,854,775,807)</li> </ul> <p>I have actually hit the limit at a job I worked at. The actual error is:</p> <pre> Msg 8115, Level 16, State 1, Line 1 Arithmetic overflow error converting IDENTITY to data type int. Arithmetic overflow occurred. </pre> <p>There are a couple fixes to this I can think of off the top of my head. Number 1 is probably very hard and not very likely, number 2 is easy, but will probably cause problems in your code base.</p> <ol> <li>If the identity column doesn't matter to you (it's not a Foreign Key, etc.) then you can just reseed the database and reset the identity column.</li> <li>Change your identity column to a bigger number. So for example if you've overflowed an int, change your identity column to a big int. Good luck overflowing that :)</li> </ol> <p>There are probably other fixes, but there is no magic bullet easy one. I just hope this doesn't happen in a table that is the center of a bunch of relationships, because if it does, you're in for a lot of pain. It's not a hard fix, just a tedious and long one.</p>
309,496
Initializing an Array of Structs in C#
<p>How can I initialize a const / static array of structs as clearly as possible?</p> <pre><code>class SomeClass { struct MyStruct { public string label; public int id; }; const MyStruct[] MyArray = { {"a", 1} {"b", 5} {"q", 29} }; }; </code></pre>
309,528
5
0
null
2008-11-21 17:09:14.267 UTC
25
2019-05-03 15:23:19.243 UTC
2017-02-23 17:52:47.003 UTC
null
4,066
Adam Tegen
4,066
null
1
54
c#|arrays|struct
149,075
<p>Firstly, do you <em>really</em> have to have a mutable struct? They're almost always a bad idea. Likewise public fields. There are some very occasional contexts in which they're reasonable (usually both parts together, as with <code>ValueTuple</code>) but they're pretty rare in my experience.</p> <p>Other than that, I'd just create a constructor taking the two bits of data:</p> <pre><code>class SomeClass { struct MyStruct { private readonly string label; private readonly int id; public MyStruct (string label, int id) { this.label = label; this.id = id; } public string Label { get { return label; } } public string Id { get { return id; } } } static readonly IList&lt;MyStruct&gt; MyArray = new ReadOnlyCollection&lt;MyStruct&gt; (new[] { new MyStruct ("a", 1), new MyStruct ("b", 5), new MyStruct ("q", 29) }); } </code></pre> <p>Note the use of <a href="http://msdn.microsoft.com/en-us/library/ms132474.aspx" rel="noreferrer">ReadOnlyCollection</a> instead of exposing the array itself - this will make it immutable, avoiding <a href="http://blogs.msdn.com/ericlippert/archive/2008/09/22/arrays-considered-somewhat-harmful.aspx" rel="noreferrer">the problem exposing arrays directly</a>. (The code show does initialize an array of structs - it then just passes the reference to the constructor of <code>ReadOnlyCollection&lt;&gt;</code>.)</p>
605,519
Does Git-Svn Store Svn Passwords?
<p>I'm using git-svn with a couple of work projects and I've noticed that for just about every action I take, I get prompted for my Svn password. For some actions, I get prompted multiple times (presumably b/c there are several actions going on behind the scenes). For example, when cloning a repository, I'm prompted 5 times before the cloning actually begins.</p> <p>Projects for which I'm using Svn directly don't do this. Is this expected? Is there anything I can do to cache my credentials?</p> <p>Thanks.</p>
760,406
6
0
null
2009-03-03 08:15:46.653 UTC
11
2019-04-16 12:06:19.59 UTC
null
null
null
Rob Wilkerson
1,665
null
1
31
svn|git-svn
15,470
<p>I ended up having to delete the auth directory all together and allow Subversion to rebuild it for me. Nothing else seemed to work. For anyone who doesn't know, the auth directory is in ~/.subversion (Mac/Linux).</p>
704,616
Something wrong with Emacs shell
<p>I use Ubuntu8.10 and emacs-snapshot. Running shell-mode on emacs and input "ls" shows escape codes:</p> <p><a href="http://lh3.ggpht.com/_os_zrveP8Ns/SdMmohKNjmI/AAAAAAAADB4/VlKpr5H_7ZA/s512/screen.png">screenshot http://lh3.ggpht.com/_os_zrveP8Ns/SdMmohKNjmI/AAAAAAAADB4/VlKpr5H_7ZA/s512/screen.png</a></p> <p>How can I get the output I expect?</p>
704,811
6
1
null
2009-04-01 08:39:11.397 UTC
10
2011-09-04 01:23:10.747 UTC
2011-09-04 01:23:10.747 UTC
Roger Pate
133
linjunhalida
73,048
null
1
31
emacs
9,896
<p>You can use <a href="http://www.emacswiki.org/emacs/AnsiTerm" rel="noreferrer">AnsiTerm</a> which does support colors or you can enable <a href="http://www.emacswiki.org/emacs/AnsiColor" rel="noreferrer">AnsiColor</a> for the normal shell:</p> <pre><code>(autoload 'ansi-color-for-comint-mode-on "ansi-color" nil t) (add-hook 'shell-mode-hook 'ansi-color-for-comint-mode-on) </code></pre>
32,594,710
Generate all combinations of mathematical expressions that add to target (Java homework/interview)
<p>I've tried to solve the problem below for a coding challenge but could not finish it in 1 hour. I have an idea on how the algorithm works but I'm not quite sure how to best implement it. I have my code and problem below.</p> <blockquote> <p>The first 12 digits of pi are 314159265358. We can make these digits into an expression evaluating to 27182 (first 5 digits of e) as follows:</p> <pre><code>3141 * 5 / 9 * 26 / 5 * 3 - 5 * 8 = 27182 </code></pre> <p>or</p> <pre><code>3 + 1 - 415 * 92 + 65358 = 27182 </code></pre> <p>Notice that the order of the input digits is not changed. Operators (+,-,/, or *) are simply inserted to create the expression.</p> <p>Write a function to take a list of numbers and a target, and return all the ways that those numbers can be formed into expressions evaluating to the target</p> <p>For example:<br> f("314159265358", 27182) should print:</p> <pre><code>3 + 1 - 415 * 92 + 65358 = 27182 3 * 1 + 4 * 159 + 26535 + 8 = 27182 3 / 1 + 4 * 159 + 26535 + 8 = 27182 3 * 14 * 15 + 9 + 26535 + 8 = 27182 3141 * 5 / 9 * 26 / 5 * 3 - 5 * 8 = 27182 </code></pre> </blockquote> <p>This problem is difficult since you can have any combination of numbers and you don't consider one number at a time. I wasn't sure how to do the combinations and recursion for that step. Notice that parentheses are not provided in the solution, however order of operations is preserved.</p> <p>My goal is to start off with say</p> <pre><code>{"3"} then {"31", "3+1", "3-1", "3*1" "3/1"} then {"314", "31+4", "3+1+4", "3-1-4", "31/4", "31*4", "31-4"} etc. </code></pre> <p>then look at the every value in the list each time and see if it is target value. If it is, add that string to result list.</p> <p>Here is my code</p> <pre><code>public static List&lt;String&gt; combinations(String nums, int target) { List&lt;String&gt; tempResultList = new ArrayList&lt;String&gt;(); List&lt;String&gt; realResultList = new ArrayList&lt;String&gt;(); String originalNum = Character.toString(nums.charAt(0)); for (int i = 0; i &lt; nums.length(); i++) { if (i &gt; 0) { originalNum += nums.charAt(i); //start off with a new number to decompose } tempResultList.add(originalNum); char[] originalNumCharArray = originalNum.toCharArray(); for (int j = 0; j &lt; originalNumCharArray.length; j++) { //go through every character to find the combinations? // maybe recursion here instead of iterative would be easier... } for (String s : tempResultList) { //try to evaluate int temp = 0; if (s.contains("*") || s.contains("/") || s.contains("+") || s.contains("-")) { //evaluate expression } else { //just a number } if (temp == target) { realResultList.add(s); } } tempResultList.clear(); } return realResultList; } </code></pre> <p><strong>Could someone help with this problem? Looking for an answer with coding in it, since I need help with the generation of possibilities</strong></p>
32,597,870
3
6
null
2015-09-15 20:06:56.72 UTC
12
2016-03-28 18:42:56.953 UTC
2016-02-23 17:31:08.527 UTC
null
1,269,037
null
2,476,537
null
1
16
java|algorithm|math|expression
7,546
<p>I don't think it's necessary to build a tree, you should be able to calculate as you go -- you just need to delay additions and subtractions slightly in order to be able take the precedence into account correctly:</p> <pre><code>static void check(double sum, double previous, String digits, double target, String expr) { if (digits.length() == 0) { if (sum + previous == target) { System.out.println(expr + " = " + target); } } else { for (int i = 1; i &lt;= digits.length(); i++) { double current = Double.parseDouble(digits.substring(0, i)); String remaining = digits.substring(i); check(sum + previous, current, remaining, target, expr + " + " + current); check(sum, previous * current, remaining, target, expr + " * " + current); check(sum, previous / current, remaining, target, expr + " / " + current); check(sum + previous, -current, remaining, target, expr + " - " + current); } } } static void f(String digits, double target) { for (int i = 1; i &lt;= digits.length(); i++) { String current = digits.substring(0, i); check(0, Double.parseDouble(current), digits.substring(i), target, current); } } </code></pre>
43,925,337
Matplotlib returning a plot object
<p>I have a function that wraps <code>pyplot.plt</code> so I can quickly create graphs with oft-used defaults:</p> <pre><code>def plot_signal(time, signal, title='', xlab='', ylab='', line_width=1, alpha=1, color='k', subplots=False, show_grid=True, fig_size=(10, 5)): # Skipping a lot of other complexity here f, axarr = plt.subplots(figsize=fig_size) axarr.plot(time, signal, linewidth=line_width, alpha=alpha, color=color) axarr.set_xlim(min(time), max(time)) axarr.set_xlabel(xlab) axarr.set_ylabel(ylab) axarr.grid(show_grid) plt.suptitle(title, size=16) plt.show() </code></pre> <p>However, there are times where I'd want to be able to return the plot so I can manually add/edit things for a specific graph. For example, I want to be able to change the axis labels, or add a second line to the plot after calling the function:</p> <pre><code>import numpy as np x = np.random.rand(100) y = np.random.rand(100) plot = plot_signal(np.arange(len(x)), x) plot.plt(y, 'r') plot.show() </code></pre> <p>I've seen a few questions on this (<a href="https://stackoverflow.com/questions/14936646/how-to-return-a-matplotlib-figure-figure-object-from-pandas-plot-function">How to return a matplotlib.figure.Figure object from Pandas plot function?</a> and <a href="https://stackoverflow.com/questions/38701137/attributeerror-figure-object-has-no-attribute-plot">AttributeError: &#39;Figure&#39; object has no attribute &#39;plot&#39;</a>) and as a result I've tried adding the following to the end of the function:</p> <ul> <li><p><code>return axarr</code></p></li> <li><p><code>return axarr.get_figure()</code></p></li> <li><p><code>return plt.axes()</code></p></li> </ul> <p>However, they all return a similar error: <code>AttributeError: 'AxesSubplot' object has no attribute 'plt'</code></p> <p>Whats the correct way to return a plot object so it can be edited later?</p>
43,926,055
3
2
null
2017-05-11 20:52:56.47 UTC
17
2022-04-04 05:23:44.74 UTC
2017-05-23 11:47:12.323 UTC
null
-1
null
2,605,604
null
1
48
python|matplotlib|plot
89,197
<p>I think the error is pretty self-explanatory. There is no such thing as <code>pyplot.plt</code>, or similar. <code>plt</code> is the quasi-standard abbreviated form of <code>pyplot</code> when being imported, i.e., <code>import matplotlib.pyplot as plt</code>.</p> <p>Concerning the problem, the first approach, <code>return axarr</code> is the most versatile one. You get an axis, or an array of axes, and can plot to it.</p> <p>The code may look like:</p> <pre><code>def plot_signal(x,y, ..., **kwargs): # Skipping a lot of other complexity here f, ax = plt.subplots(figsize=fig_size) ax.plot(x,y, ...) # further stuff return ax ax = plot_signal(x,y, ...) ax.plot(x2, y2, ...) plt.show() </code></pre>
17,760,299
Android FragmentTransaction Custom Animation (Unknown Animator Name: Translate)
<p>I'm trying to get a custom animation to work with my fragment.</p> <p>I've followed the online tutorials but I've been getting the below error:</p> <p><strong>java.lang.RuntimeException: Unknown animator name: translate</strong></p> <p>The XML for the animation is below:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;set xmlns:android="http://schemas.android.com/apk/res/android"&gt; &lt;translate android:fromXDelta="100%" android:toXDelta="0" android:duration="300" /&gt; &lt;/set&gt; </code></pre> <p>The Java file is shown below:</p> <pre><code>public void goCategory(View v) { FragmentTransaction ft = fm.beginTransaction(); ft.setCustomAnimations(R.animator.anim_in_left, R.animator.anim_out_left); ft.show(fragment); ft.commit(); } </code></pre> <p>I'm having trouble understanding the solutions in the other threads. If someone could dumb it down for me, I'd really appreciate it.</p>
19,769,903
3
1
null
2013-07-20 08:25:02.277 UTC
19
2019-02-17 21:37:03.92 UTC
2019-02-17 21:37:03.92 UTC
null
4,505,446
null
2,021,478
null
1
71
android|android-fragments|android-animation
55,380
<p>It will not work, you should use object animator </p> <p>animator/slide_in_left.xml</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;set xmlns:android="http://schemas.android.com/apk/res/android" &gt; &lt;objectAnimator xmlns:android="http://schemas.android.com/apk/res/android" android:duration="500" android:propertyName="x" android:valueFrom="1000" android:valueTo="0" android:valueType="floatType" /&gt; &lt;/set&gt; </code></pre> <p>animator/slide_out_right.xml</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;set xmlns:android="http://schemas.android.com/apk/res/android" &gt; &lt;objectAnimator xmlns:android="http://schemas.android.com/apk/res/android" android:duration="500" android:propertyName="x" android:valueFrom="0" android:valueTo="-1000" android:valueType="floatType" /&gt; &lt;/set&gt; </code></pre> <p>Class Subcategory</p> <pre><code> public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO Auto-generated method stub // return super.onCreateView(inflater, container, savedInstanceState); View view = (ViewGroup) inflater.inflate(R.layout.product_frame, null); getFragmentManager().beginTransaction() .replace(R.id.sub_header, new Sub_Header()).commit(); getFragmentManager() .beginTransaction() .setCustomAnimations(R.animator.slide_in_left, R.animator.slide_out_right, 0, 0) .replace(R.id.product_frame, new Sub_Catagory_Grid()).commit(); view.getWidth(); return view; } </code></pre>
54,600,273
.NET Core 3.0: Razor views don't automatically recompile on change
<p>According to <a href="https://docs.microsoft.com/en-us/aspnet/core/mvc/views/view-compilation?view=aspnetcore-3.0" rel="nofollow noreferrer">the documentation</a>, Razor views should, by default, recompile on change on local environments for ASP.NET Core 3.0.</p> <p>However, my project doesn't do this locally. If I change a view and refresh when I'm debugging locally, the change is not reflected. I have to stop the solution, re-run, and then see the change.</p> <p>I am doing this on a default ASP.NET Core Web Application template on Visual Studio 2019 with ASP.NET Core 3.0.0 Preview 2 using Razor pages. Any idea if I need to change settings to enable this feature?</p>
54,876,499
9
5
null
2019-02-08 21:11:42.94 UTC
23
2022-06-06 11:16:38.287 UTC
2022-06-06 11:16:38.287 UTC
null
6,296,561
null
3,164,096
null
1
123
c#|asp.net-core|razor-pages|asp.net-core-3.0
48,134
<p>OK it looks like it's not supported yet :(</p> <blockquote> <p>Runtime compilation removed As a consequence of cleaning up the ASP.NET Core shared framework to not depend on Roslyn, support for runtime compilation of pages and views has also been removed in this preview release. Instead compilation of pages and views is performed at build time. In a future preview update we will provide a NuGet packages for optionally enabling runtime compilation support in an app.</p> </blockquote> <p>You can read more about the issue here <a href="https://github.com/aspnet/Announcements/issues/343" rel="noreferrer">https://github.com/aspnet/Announcements/issues/343</a></p> <p>Applications that require runtime compilation or re-compilation of Razor files should:</p> <ul> <li>Add a reference to the <code>Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation</code> package. It'll be available as part of the <strong>3.0.0-preview3</strong> release.</li> <li>Update the application's <code>ConfigureServices</code> to include a call to <code>AddMvcRazorRuntimeCompilation</code>:</li> </ul>
33,092,891
makefile "no such file or directory"
<p>I am trying to compile a C++ program using make. After reading quite a few tutorials, I have come upon the following make file.</p> <p>It reads source files from src directory, puts objects in the build directory, and puts the exe in the bin directory.</p> <p>When I try running the following makefile, I get the subsequent error.</p> <pre><code>CC := g++ CFLAGS := -g -O2 BIN_DIR := /bin BUILD_DIR := /build SRC_DIR := /src TARGET := wavfiletool.exe SOURCES := $(wildcard $(SRC_DIR)/*.c) OBJECTS := $(SOURCES:$(SRCDIR)/%.cpp=$(BUILD_DIR)/%.o) $(BIN_DIR)/$(TARGET): $(OBJECTS) $(CC) $@ $(CFLAGS) $(OBJECTS) $(OBJECTS): $(BUILD_DIR)/%.o : $(SRC_DIR)/%.c @$(CC) $(CFLAGS) -c $&lt; -o $@ </code></pre> <blockquote> <p>++ /bin/wavfiletool.exe -g -O2 g++: error: /bin/wavfiletool.exe: No such file or directory g++: fatal error: no input files compilation terminated. make: *** [/bin/wavfiletool.exe] Error 1 [Finished in 0.1s with exit code 2]</p> </blockquote> <p>UPDATE:</p> <p>I have edited the makefile. One typo in the previous version was that I have .c when I am using .cpp and c++. I am now getting a different error.</p> <p>UPDATED MAKEFILE</p> <pre><code>CC := g++ CFLAGS := -g -O2 BIN_DIR := bin BUILD_DIR := build SRC_DIR := src TARGET := wavfiletool.exe SOURCES := $(wildcard $(SRC_DIR)/*.cpp) OBJECTS := $(SOURCES:$(SRCDIR)/%.cpp=$(BUILD_DIR)/%.o) $(BIN_DIR)/$(TARGET): $(OBJECTS) $(CC) $(OBJECTS) $(CFLAGS) -o $@ $(OBJECTS): $(BUILD_DIR)/%.o : $(SRC_DIR)/%.cpp @$(CC) $(CFLAGS) -c $&lt; -o $@ </code></pre> <p>new error</p> <pre><code>makefile:13: target `src/WavFile.cpp' doesn't match the target pattern makefile:13: target `src/WavFileTool.cpp' doesn't match the target pattern g++ src/WavFile.cpp src/WavFileTool.cpp -g -O2 -o bin/wavfiletool.exe </code></pre>
33,092,967
1
3
null
2015-10-13 01:55:15.403 UTC
1
2015-10-14 01:22:18.903 UTC
2015-10-14 01:22:18.903 UTC
null
3,321,579
null
3,321,579
null
1
2
makefile|gnu-make
61,764
<p>Unless all of your directories (i.e., BIN_DIR, SRC_DIR) are in the root directory (/) then that is why you're getting the error. You either want to remove the initial slash or you can use an environment variable prefix like <code>SRC_DIR = $(MY_PROJECT_BASE_DIRECTORY)/src</code>.</p>
46,771,315
Angular: Cannot Get /
<p>I am trying to open, build and run someone else's Angular 4 project but I am not able to view the project when I run it my way. I don't see what is going wrong or what I should do now. I already had everything in place to use NPM and NodeJS</p> <p>The steps I took were:</p> <ul> <li>Open up the project</li> <li>npm install</li> <li>ng serve</li> </ul> <p>The project compiles the right way. (I have an own Angular app and I know how this looks like) The console is showing: </p> <blockquote> <p>'** NG Live Development Server is listening on localhost:4200, open your browser on <a href="http://localhost:4200" rel="noreferrer">http://localhost:4200</a> **'.</p> </blockquote> <p>Then, when I opened up a web browser, I navigated to localhost:4200 and a web page with the following text were shown: </p> <blockquote> <p>'Cannot GET /'</p> </blockquote> <p>And on the console was the following text:</p> <blockquote> <p>'GET <a href="http://localhost:4200/" rel="noreferrer">http://localhost:4200/</a> 404 (Not Found)'</p> </blockquote> <p>The project should work fine but I am not able to navigate to a working URL on the web page. Routing is set-up another way as I am used to doing this. In app.module.ts the following is implemented:</p> <p>app.module.ts</p> <pre><code>const appRoutes: Routes = [ { path: '', redirectTo: 'tree', pathMatch: 'full' }, { path: 'admin', component: AdminPanelComponent, canActivate: [AuthGuard], children: [{path:'', component: PanelComponent},{path: 'add', component: AddTreeComponent}, {path:'manage-trees', component:ManageTreesComponent}, {path:'manage-users', component: ManageUsersComponent}, {path:'view-trees', component: ViewTreeComponent}]}, {path:'tree', component: TreeComponent}, {path:'error', component: ErrorComponent}, {path:'unauthorized', component: UnauthorizedComponent}, {path:'login', component: LoginComponent}, {path:'entire-tree', component: EntireTreeComponent}, { path: '**', component: PageNotFoundComponent }, ]; </code></pre> <p>Also opening up a web page like; localhost:4200/tree does not work. When I let angular stop serving the web page, the web page displays: "this site can't be reached'. So I think there is running something at localhost:4200... Also, another project of this person behaves the same way.</p> <p><a href="https://i.stack.imgur.com/PKZlU.png" rel="noreferrer"><img src="https://i.stack.imgur.com/PKZlU.png" alt="enter image description here"></a></p> <p>Does anybody know what is going on? </p> <p><strong>EDIT</strong></p> <p>app.module.ts</p> <pre><code>RouterModule.forRoot(appRoutes, { useHash: true }) </code></pre> <p>Package.json</p> <pre><code>{ "name": "xxx", "version": "0.0.0", "license": "MIT", "scripts": { "ng": "ng", "start": "ng serve", "build": "ng build", "test": "ng test", "lint": "ng lint", "e2e": "ng e2e" }, "private": true, "dependencies": { "@angular/animations": "^4.0.0", "@angular/common": "^4.0.0", "@angular/compiler": "^4.0.0", "@angular/core": "^4.0.0", "@angular/forms": "^4.0.0", "@angular/http": "^4.0.0", "@angular/platform-browser": "^4.0.0", "@angular/platform-browser-dynamic": "^4.0.0", "@angular/router": "^4.0.0", "angular-oauth2-oidc": "^1.0.20", "angular-polyfills": "^1.0.1", "angular2-jwt": "^0.2.3", "angular2-spinner": "^1.0.10", "bootstrap": "^3.3.7", "core-js": "^2.4.1", "ngx-bootstrap": "^1.8.0", "rxjs": "^5.1.0", "zone.js": "^0.8.4" }, "devDependencies": { "@angular/cli": "1.2.4", "@angular/compiler-cli": "^4.0.0", "@angular/language-service": "^4.0.0", "@types/jasmine": "2.5.45", "@types/node": "~6.0.60", "codelyzer": "~3.0.1", "jasmine-core": "~2.6.2", "jasmine-spec-reporter": "~4.1.0", "karma": "~1.7.0", "karma-chrome-launcher": "~2.1.1", "karma-cli": "~1.0.1", "karma-jasmine": "~1.1.0", "karma-jasmine-html-reporter": "^0.2.2", "karma-coverage-istanbul-reporter": "^1.2.1", "protractor": "~5.1.2", "ts-node": "~3.0.4", "tslint": "~5.3.2", "typescript": "~2.3.3" } } </code></pre> <p>I also see an icon next to the tab name with the label: "Error".</p> <p><strong>OBSERVATION:</strong></p> <p>New observation:</p> <p>After I ran <code>npm install -g angular-cli</code> I wasn't able to run <code>ng serve</code>. (You have to be inside an angular-cli project in order to use the build command after reinstall of angular-cli)</p> <p>Then I ran <code>npm install -g @angular/cli@latest</code> and I was able to use <code>ng serve</code> again. </p> <p><strong>OBSERVATION 2:</strong></p> <p>After building the app with: 'ng build ...' there is no index.html in the 'dist' folder... When I set the website online, there is just a folder structure instead of a nice website. I think that's because there is no index.html.</p>
46,810,936
26
10
null
2017-10-16 13:16:31.443 UTC
9
2022-04-28 08:54:03.557 UTC
2018-12-07 08:01:58.18 UTC
null
3,181,492
null
3,181,492
null
1
85
javascript|node.js|angular|typescript
172,581
<p>The problem was that I ran the commands within the folder <code>/project/src/app</code>. Navigating back to the project folder so to <code>/project</code> and running <code>ng serve</code> from there solved my problem.</p>
2,128,755
use event.target to get the class value?
<p>i have a DOM element with class='tag'.</p> <p>i want to check if the class value is tag and alert a message if it's true.</p> <p>i wrote:</p> <pre><code> $("#thread").each(function(event) { if(event.target.class == 'tag') alert('yes'); }); </code></pre> <p>but it didn't work. you can get the id with event.target.id but not the class with this code? what are all the values you can have after event.target?</p>
2,128,761
5
0
null
2010-01-24 20:49:06.837 UTC
7
2013-02-16 16:50:02.83 UTC
2012-06-18 19:27:56.213 UTC
null
114,029
null
206,446
null
1
12
jquery
51,692
<p>At first, the <code>event</code> argument work only for event handlers, and you are using the <code>$.each</code> method.</p> <p>I don't really think that you want/need to use the <code>$.each</code> method, since you are using an <code>#id</code> selector, and id's should be unique.</p> <p>To check if an element contains an specific class you can use the <a href="http://api.jquery.com/hasClass/" rel="noreferrer"><code>hasClass</code></a> method:</p> <pre><code>if ($("#thread").hasClass('tag')) { //... } </code></pre> <p>Also if you have a DOM element, to get it's class attribute, you should access it with <code>className</code> instead <code>class</code>, that's because <code>class</code> is a <em>future reserved word</em> in JavaScript, the same thing happens with other attributes like <code>for</code>, should be accessed as <code>htmlFor</code>...</p>
2,263,681
c++ compile error: ISO C++ forbids comparison between pointer and integer
<p>I am trying an example from Bjarne Stroustrup's C++ book, third edition. While implementing a rather simple function, I get the following compile time error:</p> <pre><code>error: ISO C++ forbids comparison between pointer and integer </code></pre> <p>What could be causing this? Here is the code. The error is in the <code>if</code> line:</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; using namespace std; bool accept() { cout &lt;&lt; "Do you want to proceed (y or n)?\n"; char answer; cin &gt;&gt; answer; if (answer == "y") return true; return false; } </code></pre> <p>Thanks!</p>
2,263,700
5
2
null
2010-02-15 02:05:53.047 UTC
12
2021-10-26 05:19:54.697 UTC
2010-03-09 00:51:12.733 UTC
null
253,197
null
253,197
null
1
41
c++|compiler-errors
169,821
<p>You have two ways to fix this. The preferred way is to use:</p> <pre><code>string answer; </code></pre> <p>(instead of <code>char</code>). The other possible way to fix it is:</p> <pre><code>if (answer == 'y') ... </code></pre> <p>(note single quotes instead of double, representing a <code>char</code> constant).</p>
2,135,096
What is the best architecture for tracking field changes on objects?
<p>We have a web application that is built on top of a SQL database. Several different types of objects can have comments added to them, and some of these objects need field-level tracking, similar to how field changes are tracked on most issue-tracking systems (such as status, assignment, priority). We'd like to show who the change is by, what the previous value was, and what the new value is.</p> <p>At a pure design level, it would be most straightforward to track each change from any object in a generic table, with columns for the object type, object primary key, primary key of the user that made the change, the field name, and the old and new values. In our case, these would also optionally have a comment ID if the user entered a comment when making the changes.</p> <p>However, with how quickly this data can grow, is this the best architecture? What are some methods commonly employed to add this type of functionality to an already large-scale application?</p> <p>[<strong>Edit</strong>] I'm starting a bounty on this question mainly because I'd like to find out in particular what is the best architecture in terms of handling scale very well. Tom H.'s answer is informative, but the recommended solution seems to be fairly size-inefficient (a new row for every new state of an object, even if many columns did not change) and not possible given the requirement that we must be able to track changes to user-created fields as well. In particular, I'm likely to accept an answer that can explain how a common issue-tracking system (JIRA or similar) has implemented this.</p>
2,135,193
7
0
null
2010-01-25 19:45:29.677 UTC
10
2012-07-15 21:38:06.423 UTC
2010-02-24 22:54:03.373 UTC
null
16,398
null
143,295
null
1
26
sql|architecture|scalability|change-tracking
8,000
<p>There are several options available to you for this. You could have audit tables which basically mirror the base tables but also include a change date/time, change type and user. These can be updated through a trigger. This solution is typically better for behind the scenes auditing (IMO) though, rather than to solve an application-specific requirement.</p> <p>The second option is as you've described. You can have a generic table that holds each individual change with a type code to show which attribute was changed. I personally don't like this solution as it prevents the use of check constraints on the columns and can also prevent foreign key constraints.</p> <p>The third option (which would be my initial choice with the information given) would be to have a separate historical change table which is updated through the application and includes the PK for each table as well as the column(s) which you would be tracking. It's slightly different from the first option in that the application would be responsible for updating the table as needed. I prefer this over the first option in your case because you really have a business requirement that you're trying to solve, not a back-end technical requirement like auditing. By putting the logic in the application you have a bit more flexibility. Maybe some changes you don't want to track because they're maintenance updates, etc.</p> <p>With the third option you can either have the "current" data in the base table or you can have each column that is kept historically in the historical table only. You would then need to look at the latest row to get the current state for the object. I prefer that because it avoids the problem of duplicate data in your database or having to look at multiple tables for the same data.</p> <p>So, you might have:</p> <p>Problem_Ticket (ticket_id, ticket_name) Problem_Ticket_History (ticket_id, change_datetime, description, comment, username)</p> <p>Alternatively, you could use:</p> <p>Problem_Ticket (ticket_id, ticket_name) Problem_Ticket_Comments (ticket_id, change_datetime, comment, username) Problem_Ticket_Statuses (ticket_id, change_datetime, status_id, username)</p>
1,842,370
UIWebView didFinishLoading fires multiple times
<p>I have some code that needs to run after the a <code>UIWebView</code> finishes loading a document. For that I've set the <code>UIWebView</code>'s delegate to my controller, and implemented the <code>webViewDidFinishLoading</code> method.</p> <p>This gets called multiple times, depending on the type of page to load. I'm not sure if it's because of ajax requests, requests for images, or maybe even iframes.</p> <p>Is there a way to tell that the main request has finished, meaning the HTML is completely loaded?</p> <p>Or perhaps delay my code from firing until all of those events are done firing?</p>
1,855,267
9
1
null
2009-12-03 19:38:55.583 UTC
17
2016-06-07 22:30:02.457 UTC
2013-03-28 17:32:15.847 UTC
null
1,371,070
null
3,381
null
1
54
iphone|ios|objective-c|xcode|uiwebview
38,981
<p>It could be enlightening (if you haven't gone this far yet) to NSLog a trace of load starts and finishes.</p> <pre><code> - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { NSLog(@"Loading: %@", [request URL]); return YES; } - (void)webViewDidFinishLoad:(UIWebView *)webView { NSLog(@"didFinish: %@; stillLoading: %@", [[webView request]URL], (webView.loading?@"YES":@"NO")); } - (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error { NSLog(@"didFail: %@; stillLoading: %@", [[webView request]URL], (webView.loading?@"YES":@"NO")); } </code></pre> <p>I just watched the calls to all three in one of my projects which loads a help page from my bundle and contains embedded resources (external css, YUI!, images). The only request that comes through is the initial page load, <code>shouldStartLoadWithRequest</code> isn't called for any of the dependencies. So it is curious why your didFinishLoad is called multiple times.</p> <p>Perhaps what you're seeing is due to redirects, or as mentioned, ajax calls within a loaded page. But you at least should be able balance calls to <code>shouldStartLoad</code> and either of the other two delegate functions and be able to determine when the loading is finished.</p>
1,672,655
How to open windows explorer on selected resource in Eclipse
<p>I was looking for a small plugin for Eclipse that would allow to open windows explorer on currently selected resource from Package Explorer tree.</p> <p>I know that Aptana Studio provides this functionality via context menu on the resource, but it has tons of other stuff that I am not interested to. </p> <p>Are there other solutions?</p>
1,673,081
11
1
null
2009-11-04 09:35:57.447 UTC
36
2019-08-21 08:23:35.933 UTC
2009-11-04 09:51:31.153 UTC
null
42,512
null
42,512
null
1
93
eclipse|eclipse-plugin
43,004
<p>I use this plugin, it seems ok</p> <p>New Eclipse Update Link <a href="https://fabioz.github.com/startexplorer/update/" rel="noreferrer">https://fabioz.github.com/startexplorer/update/</a></p> <p>Old link for reference </p> <ul> <li><p><a href="http://sourceforge.net/projects/startexplorer/" rel="noreferrer">http://sourceforge.net/projects/startexplorer/</a>*</p></li> <li><p><a href="http://basti1302.github.com/startexplorer/update/" rel="noreferrer">http://basti1302.github.com/startexplorer/update/</a></p></li> </ul>
2,330,197
How to disable mouse scroll wheel scaling with Google Maps API
<p>I am using Google Maps API (v3) to draw a few maps on a page. One thing I'd like to do is disable zooming when you scroll the mouse wheel over the map, but I'm unsure how.</p> <p>I have disabled the scaleControl (i.e. removed the scaling UI element), but this doesn't prevent scroll wheel scaling.</p> <p>Here is part of my function (it's a simple jQuery plugin):</p> <pre><code>$.fn.showMap = function(options, addr){ options = $.extend({ navigationControl: false, mapTypeControl: false, scaleControl: false, draggable: false, mapTypeId: google.maps.MapTypeId.ROADMAP }, options); var map = new google.maps.Map(document.getElementById($(this).attr('id')), options); // Code cut from this example as not relevant }; </code></pre>
2,330,272
14
2
null
2010-02-24 22:39:35.047 UTC
109
2017-10-10 15:24:21.627 UTC
2016-12-14 17:11:04.887 UTC
null
63,550
null
151,409
null
1
570
jquery|google-maps|google-maps-api-3|jquery-plugins
552,487
<p>In version 3 of the Maps API you can simply set the <code>scrollwheel</code> option to false within the <a href="http://code.google.com/apis/maps/documentation/v3/reference.html#MapOptions" rel="noreferrer">MapOptions</a> properties:</p> <pre><code>options = $.extend({ scrollwheel: false, navigationControl: false, mapTypeControl: false, scaleControl: false, draggable: false, mapTypeId: google.maps.MapTypeId.ROADMAP }, options); </code></pre> <p>If you were using version 2 of the Maps API you would have had to use the <a href="http://code.google.com/apis/maps/documentation/reference.html#GMap2.disableScrollWheelZoom" rel="noreferrer">disableScrollWheelZoom()</a> API call as follows:</p> <pre><code>map.disableScrollWheelZoom(); </code></pre> <p>The <code>scrollwheel</code> zooming is enabled by default in version 3 of the Maps API, but in version 2 it is disabled unless explicitly enabled with the <code>enableScrollWheelZoom()</code> API call.</p>
2,155,453
jQuery Toggle Text?
<p>How to toggle HTML text of an anchor tag using jQuery? I want an anchor that when clicked the text alternates between <code>Show Background</code> &amp; <code>Show Text</code> as well as fading in &amp; out another div. This was my best guess:</p> <pre><code>$(function() { $(&quot;#show-background&quot;).click(function () { $(&quot;#content-area&quot;).animate({opacity: 'toggle'}, 'slow'); }); $(&quot;#show-background&quot;).toggle(function (){ $(this).text(&quot;Show Background&quot;) .stop(); }, function(){ $(this).text(&quot;Show Text&quot;) .stop(); }); }); </code></pre>
2,155,582
20
2
null
2010-01-28 15:07:15.04 UTC
33
2020-07-13 07:14:32.233 UTC
2020-07-13 07:14:32.233 UTC
null
12,825,713
null
246,285
null
1
82
jquery|toggle
180,360
<p>Sorry the problem is me! the was out of sync but this was because I have the HTML text the wrong way around. On the first click I want the div to fade out and the text to say "Show Text".</p> <p>Will check more thoroughly next time before I ask!</p> <p>My code is now:</p> <pre><code>$(function() { $("#show-background").toggle(function (){ $("#content-area").animate({opacity: '0'}, 'slow') $("#show-background").text("Show Text") .stop(); }, function(){ $("#content-area").animate({opacity: '1'}, 'slow') $("#show-background").text("Show Background") .stop(); }); }); </code></pre> <p>Thanks again for the help!</p>
8,538,343
How to get element by class name
<p>I want to know if there is a way to <code>getElementByClassName("classname").innerHTML</code> function or something to the equivalent of <code>getElementById("ClassName").innerHTML</code>.</p>
8,538,395
4
2
null
2011-12-16 18:13:03.633 UTC
2
2014-12-19 11:43:26.413 UTC
2014-04-14 00:01:23.267 UTC
null
1,484,957
null
1,098,699
null
1
12
javascript|html|css|dom
71,997
<p>You are missing an <code>s</code> in your function name. <code>getElementsByTagName</code> returns a collection of elements, of elements, which you need to iterate over:</p> <pre><code>var elements = document.getElementsByClassName("classname"); for (var i = 0; i &lt; elements.length; i++) { elements[i].innerHTML = 'foo'; } </code></pre> <p>IE8 and below don't support <code>getElementsByClassName</code>, so you'll have to find a polyfill or use <code>querySelectorAll</code> (IE8).</p>
8,367,646
redefinition of typedef
<p><i>I am possibly doing this incorrectly and this is much a question about why it works in one compiler and not the other.</i></p> <p>I have a large C application, and I am trying to follow the style of not including header files from within other header files. Instead, using forward declarations; thus I am trying the following.</p> <pre><code>// in A.h typedef struct A_ A; typedef struct B_ B; struct A_ { double a; B *b; }; // in B.h typedef struct B_ B; struct B_ { int c; }; // in C.h typedef struct A_ A; typedef struct B_ B; void function_do_something(A*, B*); // in C.c #include "A.h" #include "B.h" #include "C.h" void function_do_something(A* a, B* b) { ... } </code></pre> <p>This paradigm compiles and runs in Ubuntu 11.10 gcc -- but it gives compiler erros in OpenSUSE gcc that say "redefinition of typedef".</p> <p>I have been doing my development in Ubunutu and so hadn't realised that this paradigm might be incorrect. Is it just that this is plain wrong and Ubuntu's gcc is being too nice?</p>
8,367,810
7
2
null
2011-12-03 12:29:53.917 UTC
9
2022-03-27 15:32:56.89 UTC
2011-12-03 12:51:36.897 UTC
null
758,811
null
758,811
null
1
26
c|gcc|typedef
46,839
<p>I was surprised by this because I'm fairly sure that redeclaring the same typedef in the same scope is legal in C++, but apparently it is not legal in C prior to the 2011 standard.</p> <p>First, typedef names have no linkage:</p> <p>ISO/IEC 9899:1999 + TC3 6.2.2/6 (Linkages of identifiers):</p> <blockquote> <p>The following identifiers have no linkage: an identifier declared to be anything other than an object or a function [...]</p> </blockquote> <p>and 6.7/3 (Declarations):</p> <blockquote> <p>If an identifier has no linkage, there shall be no more than one declaration of the identifier (in a declarator or type specifier) with the same scope and in the same name space, except for tags as specified in 6.7.2.3.</p> </blockquote> <p>So you need to ensure that each typedef declaration appears only once at file scope in each translation unit.</p> <p>The 2011 C standard allows redeclaration of typedef names. 6.7 3 says:</p> <blockquote> <p>… a typedef name may be redefined to denote the same type as it currently does, provided that type is not a variably modified type;…</p> </blockquote>
8,430,022
what is the Java equivalent of sscanf for parsing values from a string using a known pattern?
<p>So I come from a C background (originally originally, though I haven't used that language for almost 5 years) and I'm trying to parse some values from a string in Java. In C I would use sscanf. In Java people have told me "use Scanner, or StringTokenizer", but I can't see how to use them to achieve my purpose.</p> <p>My input string looks like "17-MAR-11 15.52.25.000000000". In C I would do something like:</p> <pre><code>sscanf(thestring, "%d-%s-%d %d.%d.%d.%d", day, month, year, hour, min, sec, fracpart); </code></pre> <p>But in Java, all I can do is things like:</p> <pre><code>scanner.nextInt(); </code></pre> <p>This doesn't allow me to check the pattern, and for "MAR" I end up having to do things like:</p> <pre><code>str.substring(3,6); </code></pre> <p>Horrible! Surely there is a better way?</p>
8,430,204
8
2
null
2011-12-08 11:10:01.007 UTC
8
2019-12-25 06:29:47.14 UTC
2011-12-08 11:49:14.983 UTC
null
201,601
null
191,761
null
1
39
java|scanf
80,202
<p>The problem is Java hasn't out parameters (or passing by reference) as C or C#.</p> <p>But there is a better way (and more solid). Use regular expressions:</p> <pre><code>Pattern p = Pattern.compile("(\\d+)-(\\p{Alpha}+)-(\\d+) (\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)") Matcher m = p.matcher("17-MAR-11 15.52.25.000000000"); day = m.group(1); month= m.group(2); .... </code></pre> <p>Of course C code is more concise, but this technique has one profit: Patterns specifies format more precise than '%s' and '%d'. So you can use \d{2} to specify that day MUST be compose of exactly 2 digits.</p>
46,547,540
Meaning of a double star (**) in a file path
<p>I was reading <a href="https://stackoverflow.com/a/32604767/2275800">here on Stack Overflow</a> about ** in a path, as in this example:</p> <pre><code>src/js/**/*.js </code></pre> <p>I would like to ask if &quot; ** &quot; means &quot;any nested directory&quot; please?!</p>
46,547,653
2
3
null
2017-10-03 14:54:21.167 UTC
14
2021-10-17 12:50:33.903 UTC
2020-07-25 00:31:32.177 UTC
null
2,275,800
null
2,275,800
null
1
48
javascript|path
29,248
<p>The double star in this case means <em>all folders within the current folder</em>, with the current folder being <code>src/js</code></p> <p>So in full, <em>find all files with a .js extension, in all subfolders of src/js</em></p>
17,895,013
Renaming column header in DataGridView Control using vb.net
<p>I tried out the following code but the columns still inherit the table's field names</p> <pre><code> DataGridView1.DataSource = ds.Tables("student_attendance_table") With DataGridView1 .RowHeadersVisible = False .Columns(0).Name = "Register No." .Columns(1).Name = "Date" .Columns(2).Name = "Year" .Columns(3).Name = "Batch" .Columns(4).Name = "Hour 1" .Columns(5).Name = "Hour 2" .Columns(6).Name = "Hour 3" .Columns(7).Name = "Hour 4" .Columns(8).Name = "Hour 2" .Columns(9).Name = "Attendance" End With </code></pre> <p>Content follows:</p> <pre><code>1138M0345 27-07-2013 3 1 P P P P P P 1138M0346 27-07-2013 3 1 P P P P P P 1138M0347 27-07-2013 3 1 P P P P P P 1138M0348 27-07-2013 3 1 P P P P P P 1138M0349 27-07-2013 3 1 P P P P P P 1138M0350 27-07-2013 3 1 P P P P P P 1138M0343 27-07-2013 3 1 A A A A A A 1138M0344 27-07-2013 3 1 A A A A A A </code></pre> <p>Also I need to sort the content in ascending order using REGNO (The first column)</p> <p>I am using vb.net </p>
17,895,063
4
0
null
2013-07-27 06:36:08.323 UTC
1
2017-08-28 10:11:39.667 UTC
null
null
null
null
2,602,377
null
1
3
vb.net|datagridview
54,172
<p>To change the column header use the <code>.HeaderCell.Value = "Display Value"</code></p> <pre><code>DataGridView1.DataSource = ds.Tables("student_attendance_table") With DataGridView1 .RowHeadersVisible = False .Columns(0).HeaderCell.Value = "Register No." .Columns(1).HeaderCell.Value = "Date" .Columns(2).HeaderCell.Value = "Year" .Columns(3).HeaderCell.Value = "Batch" .Columns(4).HeaderCell.Value = "Hour 1" .Columns(5).HeaderCell.Value = "Hour 2" .Columns(6).HeaderCell.Value = "Hour 3" .Columns(7).HeaderCell.Value = "Hour 4" .Columns(8).HeaderCell.Value = "Hour 2" .Columns(9).HeaderCell.Value = "Attendance" End With </code></pre> <p>and for initial sorting you can use</p> <pre><code>DataGridView1.Sort(DataGridView1.Columns(0), System.ComponentModel.ListSortDirection.Ascending) </code></pre>
6,666,382
Can I use __syncthreads() after having dropped threads?
<p>Is it safe to use <code>__syncthreads()</code> in a block where I have purposefully dropped threads using <code>return</code>?</p> <p>The documentation states that <code>__syncthreads()</code> <em>must be called by every thread in the block</em> or else it will lead to a deadlock, but in practice I have never experienced such behavior.</p> <p><strong>Sample code:</strong></p> <pre><code>__global__ void kernel(float* data, size_t size) { // Drop excess threads if user put too many in kernel call. // After the return, there are `size` active threads. if (threadIdx.x &gt;= size) { return; } // ... do some work ... __syncthreads(); // Is this safe? // For the rest of the kernel, we need to drop one excess thread // After the return, there are `size - 1` active threads if (threadIdx.x + 1 == size) { return; } // ... do more work ... __syncthreads(); // Is this safe? } </code></pre>
6,667,067
3
0
null
2011-07-12 15:04:12.497 UTC
19
2022-06-07 20:27:14.02 UTC
2015-05-27 11:45:10.333 UTC
null
703,016
null
703,016
null
1
42
synchronization|cuda
8,380
<p>The answer to the short question is "No". Warp level branch divergence around a <code>__syncthreads()</code> instruction will cause a deadlock and result in a kernel hang. Your code example is not guaranteed to be safe or correct. The correct way to implement the code would be like this:</p> <pre><code>__global__ void kernel(...) if (tidx &lt; N) { // Code stanza #1 } __syncthreads(); if (tidx &lt; N) { // Code stanza #2 } // etc } </code></pre> <p>so that the <code>__syncthreads()</code> instructions are executed unconditionally.</p> <hr> <p>EDIT: Just to add a bit of additional information which confirms this assertion, <code>__syncthreads()</code> calls get compiled into the PTX <code>bar.sync</code> instruction on all architectures. The PTX2.0 guide (p133) documents <code>bar.sync</code> and includes the following warning:</p> <blockquote> <p>Barriers are executed on a per-warp basis as if all the threads in a warp are active. Thus, if any thread in a warp executes a bar instruction, it is as if all the threads in the warp have executed the bar instruction. All threads in the warp are stalled until the barrier completes, and the arrival count for the barrier is incremented by the warp size (not the number of active threads in the warp). In conditionally executed code, a bar instruction should only be used if it is known that all threads evaluate the condition identically (the warp does not diverge). Since barriers are executed on a per-warp basis, the optional thread count must be a multiple of the warp size.</p> </blockquote> <p>So despite any assertions to the contrary, it is not safe to have conditional branching around a <code>__syncthreads()</code> call unless you can be 100% certain that every thread in any given <strong>warp</strong> follows the same code path and no warp divergence can occur.</p>
6,333,814
How does the paste image from clipboard functionality work in Gmail and Google Chrome 12+?
<p>I noticed a <a href="http://gmailblog.blogspot.com/2011/06/pasting-images-into-messages-just-got.html" rel="noreferrer">blog post from Google</a> that mentions the ability to paste images directly from the clipboard into a Gmail message if you're using the latest version of Chrome. I tried this with my version of Chrome (12.0.742.91 beta-m) and it works great using control keys or the context menu. </p> <p>From that behavior I need to assume that the latest version of webkit used in Chrome is able to deal with images in the Javascript paste event, but I have been unable to locate any references to such an enhancement. I believe <a href="http://code.google.com/p/zeroclipboard/" rel="noreferrer">ZeroClipboard</a> binds to keypress events to trigger its flash functionality and as such wouldn't work through the context menu (also, ZeroClipboard is cross-browser and the post says this works only with Chrome). </p> <p>So, how does this work and where the enhancement was made to Webkit (or Chrome) that enables the functionality?</p>
6,338,207
3
1
null
2011-06-13 17:18:37.443 UTC
143
2021-04-05 18:32:50.35 UTC
2011-06-13 18:18:02.677 UTC
null
19,750
null
113,225
null
1
167
javascript|html|google-chrome|webkit
99,316
<p>I spent some time experimenting with this. It seems to sort of follow the new <a href="http://dev.w3.org/2006/webapi/clipops/" rel="noreferrer">Clipboard API spec</a>. You can define a &quot;paste&quot; event handler and look at event.clipboardData.items, and call getAsFile() on them to get a Blob. Once you have a Blob, you can use <a href="https://developer.mozilla.org/en/DOM/FileReader" rel="noreferrer">FileReader</a> on it to see what's in it. This is how you can get a data url for the stuff you just pasted in Chrome:</p> <pre><code>document.onpaste = function (event) { var items = (event.clipboardData || event.originalEvent.clipboardData).items; console.log(JSON.stringify(items)); // might give you mime types for (var index in items) { var item = items[index]; if (item.kind === 'file') { var blob = item.getAsFile(); var reader = new FileReader(); reader.onload = function (event) { console.log(event.target.result); // data url! }; reader.readAsDataURL(blob); } } }; </code></pre> <p>Once you have a data url you can display the image on the page. If you want to upload it instead, you could use readAsBinaryString, or you could put it into an XHR using <a href="https://developer.mozilla.org/en/XMLHttpRequest/FormData" rel="noreferrer">FormData</a>.</p> <p>Edit: Note that the item is of type <a href="https://developer.mozilla.org/en-US/docs/Web/API/DataTransferItem" rel="noreferrer">DataTransferItem</a>. <code>JSON.stringify</code> might not work on the items list, but you should be able to get mime type when you loop over items.</p>
6,969,604
Recursion down DOM tree
<p>This is code from Crockford's JavaScript: The Good Parts.</p> <pre><code>var results = []; var walkDOM = function (node,func) { func(node); //What does this do? node = node.firstChild; while(node) { walkDOM(node,func); node = node.nextSibling; } }; </code></pre> <p>I understand the code except for <code>func(node)</code>. I guess the point is to pass <code>node</code> as a parameter in function <code>func</code>, but how will the browser understand it this way? <code>node</code> and <code>func</code> could be anything--so when the function is called it could read like this:</p> <pre><code>walkDOM(document.body,function(att) { node.getAttribute(att); results.push(node); }); </code></pre> <p>When <code>func</code> is passed, <code>walkDOM</code> will process function(att) {...}(document.body)--which wouldn't make any sense. So why has Crockford chosen to include func(node)? </p>
6,969,630
4
6
null
2011-08-06 23:11:16.56 UTC
12
2020-03-04 13:14:52.317 UTC
2015-02-20 02:03:49.4 UTC
null
359,284
null
858,962
null
1
3
javascript|dom|recursion
16,928
<p>Looks to me like the <code>func</code> is used for doing something to every node in the tree.</p> <p>For example, if I wanted to alert the tag name for every node in the entire tree:</p> <pre><code>walkDOM(document.body, function(node) { alert(node.tagName); }); </code></pre> <p>In your example function: </p> <pre><code>walkDOM(document.body,function(att) { node.getAttribute(att); results.push(node); }); </code></pre> <p>... you have named the <code>node</code> parameter to <code>att</code>, but that doesn't magically make in a name of an attribute. I would expect a "variable 'node' is not defined" when <code>node.getAttribute(att)</code> is ran, because node is being set to <code>att</code>... there is no <code>node</code> in that function's scope.</p>
6,471,019
Can/Should I inherit from an STL iterator?
<p>Can/Should i inherit from STL iterator to implement my own iterator class? If no, why not?</p>
22,211,034
4
3
null
2011-06-24 16:45:06.807 UTC
12
2020-11-10 14:50:35.887 UTC
2020-11-10 14:50:35.887 UTC
null
895,245
null
593,177
null
1
33
c++|stl|iterator
13,649
<h3>Short answer</h3> <p>Many consider that the class <code>std::iterator</code> does not offer much compared to regular type aliases, and even obfuscates them a bit by not explicitly providing the names and relying on the order of the template parameters instead. It is deprecated in C++17 and is likely to be gone in a few years.</p> <p>This means that you shouldn't use <code>std::iterator</code> anymore. You can read the whole post below if you're interested in the full story (there's a bit of redundancy since it has been started before the deprecation proposal).</p> <hr> <h3>Legacy answer</h3> <p><em>You can ignore everything below if you're not interested in history. The following fragments even contradict themselves several times.</em></p> <p>As of today (C++11/C++14), the standard seems to imply that it isn't a good idea anymore to inherit from <code>std::iterator</code> to implement custom iterators. Here is a brief explanation, from <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n3931.html#52" rel="noreferrer">N3931</a>:</p> <blockquote> <p>Although the Standard has made this mistake almost a dozen times, I recommend not depicting <code>directory_iterator</code> and <code>recursive_directory_iterator</code> as deriving from <code>std::iterator</code>, since that's a binding requirement on implementations. Instead they should be depicted as having the appropriate typedefs, and leave it up to implementers to decide how to provide them. (The difference is observable to users with <code>is_base_of</code>, not that they should be asking that question.)</p> <p><em>[2014-02-08 Daniel comments and provides wording]</em></p> <p>This issue is basically similar to the kind of solution that had been used to remove the requirement to derive from <code>unary_function</code> and friends as described by <a href="https://wg21.link/N3198" rel="noreferrer">N3198</a> and I'm strongly in favour to follow that spirit here as well. I'd like to add that basically all "newer" iterator types (such as the <code>regex</code> related iterator) don't derive from <code>std::iterator</code> either.</p> </blockquote> <p>The paper cites <a href="https://wg21.link/N3198" rel="noreferrer">N3198</a> which itself states that it follows the deprecation discussed in <a href="https://wg21.link/N3145" rel="noreferrer">N3145</a>. The reasons for deprecating the classes that only exist to provide <code>typedef</code>s are given as such:</p> <blockquote> <p>Our experience with concepts gives us confidence that it is rarely necessary to depend on specific base class-derived class relations, if availability of types and functions is sufficient. The new language tools allow us even in the absence of language-supported concepts to deduce the existence of typenames in class types, which would introduce a much weaker coupling among them. Another advantage of replacing inheritance by associated types is the fact, that this will reduce the number of cases, where ambiguities arise: This can easily happen, if a type would inherit both from <code>unary_function</code> and <code>binary_function</code> (This makes sense, if a functor is both an unary and a binary function object).</p> </blockquote> <p><strong>tl;dr</strong>: classes which only provide <code>typedef</code>s are now deemed useless. Moreover, they increase coupling when it is not needed, are more verbose, and can have unwanted side effects in some corner cases (see the previous quotation).</p> <hr> <p><strong>Update:</strong> <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4245.html#2438" rel="noreferrer">issue 2438 from N4245</a> seems to actually contradict what I asserted earlier:</p> <blockquote> <p>For LWG convenience, nine STL iterators are depicted as deriving from <code>std::iterator</code> to get their <code>iterator_category</code>/etc. typedefs. Unfortunately (and unintentionally), this also mandates the inheritance, which is observable (not just through <code>is_base_of</code>, but also overload resolution). This is unfortunate because it confuses users, who can be misled into thinking that their own iterators must derive from <code>std::iterator</code>, or that overloading functions to take <code>std::iterator</code> is somehow meaningful. This is also unintentional because the STL's most important iterators, the container iterators, aren't required to derive from <code>std::iterator</code>. (Some are even allowed to be raw pointers.) Finally, this unnecessarily constrains implementers, who may not want to derive from <code>std::iterator</code>. (For example, to simplify debugger views.)</p> </blockquote> <p>To sum up, I was wrong, @aschepler was right: it <em>can</em> be used, but it is certainely not required - it isn't discouraged either. The whole "let's remove <code>std::iterator</code>" thing exists for the standard not to constrain the standard library implementers.</p> <hr> <p><strong>Round 3:</strong> <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0174r0.html#2.1" rel="noreferrer">P0174R0</a> proposes to deprecate <code>std::iterator</code> for a possible removal in the future. The proposal is already pretty good at explaining why it should be deprecated, so here we go:</p> <blockquote> <p>The long sequence of void arguments is much less clear to the reader than simply providing the expected typedefs in the class definition itself, which is the approach taken by the current working draft, following the pattern set in C++14 where we deprecated the derivation throughout the library of functors from unary_function and binary_function.</p> <p>In addition to the reduced clarity, the iterator template also lays a trap for the unwary, as in typical usage it will be a dependent base class, which means it will not be looking into during name lookup from within the class or its member functions. This leads to surprised users trying to understand why the following simple usage does not work:</p> <pre><code>#include &lt;iterator&gt; template &lt;typename T&gt; struct MyIterator : std::iterator&lt;std::random_access_iterator_tag, T&gt; { value_type data; // Error: value_type is not found by name lookup // ... implementations details elided ... }; </code></pre> <p>The reason of clarity alone was sufficient to persuade the LWG to update the standard library specification to no longer mandate the standard iterator adapators as deriving from std::iterator, so there is no further use of this template within the standard itself. Therefore, it looks like a strong candidate for deprecation.</p> </blockquote> <p>This is becoming a bit tiring and not everyone seems to agree, so I will let you draw your own conclusions. If the committee eventually decides that <code>std::iterator</code> should be deprecated, then it will make it pretty clear that you shouldn't use it anymore. Note that the <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0174r1.html#2.1" rel="noreferrer">follow-up paper</a> highlights a great support for the removal of <code>std::iterator</code>:</p> <blockquote> <p><strong>Update from Jacksonville, 2016:</strong></p> <p><strong>Poll:</strong> Deprecate <code>iterator</code> for C++17?? <br/> <strong>SF  F   N   A   SA</strong> <br/> 6    10  1    0   0</p> </blockquote> <p>In the above poll results, <em>SF</em>, <em>F</em>, <em>N</em>, <em>A</em> and <em>SA</em> stand for <em>Strongly For</em>, <em>For</em>, <em>Neutral</em>, <em>Against</em> and <em>Strongly Against</em>.</p> <blockquote> <p><strong>Update from Oulu, 2016:</strong></p> <p><strong>Poll:</strong> Still want to deprecate <code>std::iterator?</code> <br/> <strong>SF F N A SA</strong> <br/> 3   6  3  2  0</p> </blockquote> <p><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/p0619r1.html#3.13" rel="noreferrer">P0619R1</a> proposes to remove <code>std::iterator</code>, possibly as soon as C++20, and also proposes to enhance <code>std::iterator_traits</code> so that it can automatically deduce the types <code>difference_type</code>, <code>pointer</code> and <code>reference</code> the way <code>std::iterator</code> does when they're not explicitly provided.</p>
35,109,307
mkdir() works while inside internal flash storage, but not SD card?
<p>I am currently building a file management app that allows the user to browse the file system of their device. The user starts off in the root directory <code>/</code> of their device, but can browse to any location they want such as the internal flash storage or SD card.</p> <p>One of the critical requirements of this app is to allow the user to create new folders anywhere. A feature like this would be immensely useful for the app. However, the <a href="http://developer.android.com/reference/java/io/File.html#mkdir()"><code>File#mkdir()</code></a> method does not work at all in the SD card directory.</p> <p>I added the appropriate permissions to the manifest file. I also wrote a test to see which directories (all of which exist on my Lollipop 5.0 device) allow the creation of a new folder. From my observations, <a href="http://developer.android.com/reference/java/io/File.html#mkdir()"><code>File#mkdir()</code></a> only works when inside the internal flash storage directory.</p> <p><strong>Note:</strong> please don't confuse <a href="http://developer.android.com/reference/android/os/Environment.html#getExternalStorageDirectory()"><code>Environment#getExternalStorageDirectory()</code></a> with the SD card location, as explained by <a href="https://commonsware.com/blog/2014/04/08/storage-situation-external-storage.html">this article</a>. Also on Lollipop 5.0, I believe <code>/storage/emulated/0/</code> and <code>/storage/sdcard0/</code> refer to the internal flash storage while <code>/storage/emulated/1/</code> and <code>/storage/sdcard1/</code> refer to the SD card (which is at least true for the device I am testing with).</p> <p>How can I create new files and folders in areas outside the external storage path on non-rooted Android devices?</p> <hr> <p><strong>Manifest:</strong></p> <pre><code>... &lt;uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /&gt; &lt;uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /&gt; ... </code></pre> <p><strong>Test:</strong></p> <pre><code>... public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final String NEW_FOLDER_NAME = "TestFolder"; testPath(new File(Environment.getExternalStorageDirectory(), NEW_FOLDER_NAME)); testPath(new File("/storage/emulated/0/", NEW_FOLDER_NAME)); testPath(new File("/storage/emulated/1/", NEW_FOLDER_NAME)); testPath(new File("/storage/sdcard0/Download/", NEW_FOLDER_NAME)); testPath(new File("/storage/sdcard1/Pictures/", NEW_FOLDER_NAME)); } private void testPath(File path) { String TAG = "Debug.MainActivity.java"; String FOLDER_CREATION_SUCCESS = " mkdir() success: "; boolean success = path.mkdir(); Log.d(TAG, path.getAbsolutePath() + FOLDER_CREATION_SUCCESS + success); path.delete(); } } </code></pre> <p><strong>Output:</strong></p> <pre><code>/storage/emulated/0/TestFolder mkdir() success: true /storage/emulated/0/TestFolder mkdir() success: true /storage/emulated/1/TestFolder mkdir() success: false /storage/sdcard0/Download/TestFolder mkdir() success: true /storage/sdcard1/Pictures/TestFolder mkdir() success: false </code></pre>
35,175,460
4
7
null
2016-01-31 01:28:07.223 UTC
10
2017-01-31 05:51:21.84 UTC
2016-07-21 19:27:53.87 UTC
null
5,622,632
null
4,590,317
null
1
32
android|file-permissions
3,756
<p>First, you should note that <code>file.mkdir()</code> and <code>file.mkdirs()</code> returns <code>false</code> if the directory already existed. If you want to know whether the directory exists on return, either use <code>(file.mkdir() || file.isDirectory())</code> or simply ignore the return value and call <code>file.isDirectory()</code> (see the documentation).</p> <p>That said, your real problem is that you need permission to create the directory on removable storage on Android 5.0+. Working with removable SD cards on Android is horrendous.</p> <p>On Android 4.4 (KitKat), Google restricted access to SD cards (see <a href="https://groups.google.com/forum/#!msg/android-platform/14VUiIgwUjY/UsxMYwu02z0J" rel="noreferrer">here</a>, <a href="https://code.google.com/p/android/issues/detail?id=67570#c4444" rel="noreferrer">here</a>, and <a href="http://www.androidpolice.com/2014/02/17/external-blues-google-has-brought-big-changes-to-sd-cards-in-kitkat-and-even-samsung-may-be-implementing-them/" rel="noreferrer">here</a>). See this <a href="https://stackoverflow.com/a/25872432/1048340">StackOverflow answer</a> which leads to this <a href="http://forum.xda-developers.com/showthread.php?t=2634840" rel="noreferrer">XDA post</a> if you need to create a directory on a removable SD card on Android 4.4 (KitKat).</p> <p>On Android 5.0 (Lollipop), Google introduced new SD card access APIs. For sample usage please refer to this <a href="https://stackoverflow.com/a/26765884/1048340">stackoverflow answer</a>.</p> <p>Basically, you need to use <a href="http://developer.android.com/reference/android/support/v4/provider/DocumentFile.html#createDirectory(java.lang.String)" rel="noreferrer"><code>DocumentFile#createDirectory(String displayName)</code></a> to create your directory. You will need to ask the user to grant permissions to your app before creating this directory.</p> <hr> <p><strong>NOTE:</strong> This is for removable storage. Using <code>File#mkdirs()</code> will work on internal storage (which is often confused with external storage on Android) if you have the permission <code>android.permission.WRITE_EXTERNAL_STORAGE</code>.</p> <hr> <p><strong>I will post some example code below:</strong></p> <p>Check if you need to ask for permission:</p> <pre><code>File sdcard = ... // the removable SD card List&lt;UriPermission&gt; permissions = context.getContentResolver().getPersistedUriPermissions(); DocumentFile documentFile = null; boolean needPermissions = true; for (UriPermission permission : permissions) { if (permission.isWritePermission()) { documentFile = DocumentFile.fromTreeUri(context, permission.getUri()); if (documentFile != null) { if (documentFile.lastModified() == sdcard.lastModified()) { needPermissions = false; break; } } } } </code></pre> <p>Next (if <code>needPermissions</code> is <code>true</code>), you can display a dialog to explain to the user that they need to select the "SD Card" to give your app permissions to create files/directories and then start the following activity:</p> <pre><code>if (needPermissions) { // show a dialog explaining that you need permission to create the directory // here, we will just launch to chooser (what you need to do after showing the dialog) startActivityForResult(new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE), STORAGE_REQUEST_CODE); } else { // we already have permission to write to the removable SD card // use DocumentFile#createDirectory } </code></pre> <p>You will now need to check the <code>resultCode</code> and <code>requestCode</code> in <a href="http://developer.android.com/reference/android/app/Activity.html#onActivityResult(int,%20int,%20android.content.Intent)" rel="noreferrer"><code>onActivityResult</code></a>:</p> <pre><code>@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == STORAGE_REQUEST_CODE &amp;&amp; resultCode == RESULT_OK) { File sdcard = ... // get the removable SD card boolean needPermissions = true; DocumentFile documentFile = DocumentFile.fromTreeUri(MainActivity.this, data.getData()); if (documentFile != null) { if (documentFile.lastModified() == sdcard.lastModified()) { needPermissions = false; } } if (needPermissions) { // The user didn't select the "SD Card". // You should try the process over again or do something else. } else { // remember this permission grant so we don't need to ask again. getContentResolver().takePersistableUriPermission(data.getData(), Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION); // Now we can work with DocumentFile and create our directory DocumentFile doc = DocumentFile.fromTreeUri(this, data.getData()); // do stuff... } return; } super.onActivityResult(requestCode, resultCode, data); } </code></pre> <hr> <p>That should give you a good start on working with <code>DocumentFile</code> and removable SD cards on Android 5.0+. It can be a PITA.</p> <hr> <p>Also, there is no public API to get the path to a removable SD card (if one even exists). You should not rely on hardcoding <code>"/storage/sdcard1"</code>! There are quite a few posts about it on StackOverflow. Many of the solutions use the environment variable <code>SECONDARY_STORAGE</code>. Below is two methods you can use to find removable storage devices:</p> <pre><code>public static List&lt;File&gt; getRemovabeStorages(Context context) throws Exception { List&lt;File&gt; storages = new ArrayList&lt;&gt;(); Method getService = Class.forName("android.os.ServiceManager") .getDeclaredMethod("getService", String.class); if (!getService.isAccessible()) getService.setAccessible(true); IBinder service = (IBinder) getService.invoke(null, "mount"); Method asInterface = Class.forName("android.os.storage.IMountService$Stub") .getDeclaredMethod("asInterface", IBinder.class); if (!asInterface.isAccessible()) asInterface.setAccessible(true); Object mountService = asInterface.invoke(null, service); Object[] storageVolumes; if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.M) { String packageName = context.getPackageName(); int uid = context.getPackageManager().getPackageInfo(packageName, 0).applicationInfo.uid; Method getVolumeList = mountService.getClass().getDeclaredMethod( "getVolumeList", int.class, String.class, int.class); if (!getVolumeList.isAccessible()) getVolumeList.setAccessible(true); storageVolumes = (Object[]) getVolumeList.invoke(mountService, uid, packageName, 0); } else { Method getVolumeList = mountService.getClass().getDeclaredMethod("getVolumeList"); if (!getVolumeList.isAccessible()) getVolumeList.setAccessible(true); storageVolumes = (Object[]) getVolumeList.invoke(mountService, (Object[]) null); } for (Object storageVolume : storageVolumes) { Class&lt;?&gt; cls = storageVolume.getClass(); Method isRemovable = cls.getDeclaredMethod("isRemovable"); if (!isRemovable.isAccessible()) isRemovable.setAccessible(true); if ((boolean) isRemovable.invoke(storageVolume, (Object[]) null)) { Method getState = cls.getDeclaredMethod("getState"); if (!getState.isAccessible()) getState.setAccessible(true); String state = (String) getState.invoke(storageVolume, (Object[]) null); if (state.equals("mounted")) { Method getPath = cls.getDeclaredMethod("getPath"); if (!getPath.isAccessible()) getPath.setAccessible(true); String path = (String) getPath.invoke(storageVolume, (Object[]) null); storages.add(new File(path)); } } } return storages; } public static File getRemovabeStorageDir(Context context) { try { List&lt;File&gt; storages = getRemovabeStorages(context); if (!storages.isEmpty()) { return storages.get(0); } } catch (Exception ignored) { } final String SECONDARY_STORAGE = System.getenv("SECONDARY_STORAGE"); if (SECONDARY_STORAGE != null) { return new File(SECONDARY_STORAGE.split(":")[0]); } return null; } </code></pre>
5,547,393
BULK INSERT with variable file name
<p>i am trying to bulk insert into Db using sql server 2005</p> <p>Below is the code. </p> <pre><code>declare @path varchar(500) set @path = 'E:\Support\test.csv'; Create table #mytable( name varchar(max), class varchar(max), roll varchar(max) ) BULK INSERT #mytable FROM @path &lt;-- Error line WITH ( FIELDTERMINATOR = ',', ROWTERMINATOR = '\n' ); Go select * from #mytable drop table #mytable </code></pre> <p><strong>Problem</strong>: issue is that my file path is dynamic and comes from a variable instead of hard coding which is not working If i change the error line to below it works</p> <pre><code> BULK INSERT #mytable FROM 'E:\Support\test.csv'; </code></pre> <p>Please advise how to fix this</p>
5,547,437
2
1
null
2011-04-05 05:00:24.513 UTC
5
2013-12-05 11:36:18.187 UTC
2012-11-30 20:25:05.423 UTC
null
105,264
null
405,818
null
1
34
sql|sql-server
51,551
<p>Try to use Dynamic SQL:</p> <pre><code>declare @sql varchar(max) set @sql = 'BULK INSERT #mytable FROM ''' + @path + ''' WITH ... exec (@sql) </code></pre>
16,299,727
C: scanf to array
<p>I'm absolutely new to C, and right now I am trying master the basics and have a problem reading data from scanf straight into an array.</p> <p>Right now the code looks like this:</p> <pre><code>int main() { int array[11]; printf("Write down your ID number!\n"); scanf("%d", array); if (array[0]=1) { printf("\nThis person is a male."); } else if (array[0]=2) { printf("\nThis person is a female."); } return 0; } </code></pre> <p>As you can see, the program's aim is to ask for an ID, and determine from the first number whether the given the person is male(1) or female(2). However it seems I can't get it to work, because the array is not filled properly (this is checked via a printf(array) right after scanf, that results in random numbers). Running the program like this will give the result that the person is a male, no matter what number you read in.</p> <p>So trivial it may seem, I couldn't figure out the problem.</p>
16,299,747
4
4
null
2013-04-30 12:18:03.123 UTC
6
2019-02-22 15:36:44.48 UTC
2013-04-30 12:19:22.97 UTC
null
192,702
null
2,335,726
null
1
3
c
201,945
<p><code>if (array[0]=1)</code> should be <code>if (array[0]==1)</code>.</p> <p>The same with <code>else if (array[0]=2)</code>.</p> <p>Note that the expression of the assignment returns the <strong>assigned value</strong>, in this case <code>if (array[0]=1)</code> will be <strong>always true</strong>, that's why the code below the if-statement will be always executed if you don't change the <code>=</code> to <code>==</code>.</p> <p><code>=</code> is the assignment operator, you want to compare, not to assign. So you need <code>==</code>.</p> <p>Another thing, if you want only one integer, why are you using array? You might want also to <code>scanf("%d", &amp;array[0]);</code></p>
719,788
Property vs. instance variable
<p>I'm trying to understand how strategies some folks use to distinguish instance vars vs. properties. A common pattern is the following:</p> <pre><code>@interface MyClass : NSObject { NSString *_myVar; } @property (nonatomic, retain) NSString *myVar; @end @implementation MyClass @synthesize myVar = _myVar; </code></pre> <p>Now, I thought the entire premise behind this strategy is so that one can easily distinguish the difference between an ivar and property. So, if I want to use the memory management inherited by a synthesized property, I'd use something such as:</p> <pre><code>myVar = @"Foo"; </code></pre> <p>The other way would be referencing it via self.[ivar/property here]. </p> <p>The problem with using the @synthesize myVar = _myVar strategy, is I figured that writing code such as:</p> <pre><code>myVar = some_other_object; // doesn't work. </code></pre> <p>The compiler complains that myVar is undeclared. Why is that the case?</p> <p>Thanks.</p>
719,816
7
0
null
2009-04-05 22:06:03.553 UTC
26
2013-08-20 15:46:39.04 UTC
null
null
null
anon
null
null
1
32
iphone|objective-c|cocoa|cocoa-touch
14,330
<p>Properties are just setters and getters for <code>ivars</code> and should (almost) always be used instead of direct access.</p> <pre><code>@interface APerson : NSObject { // NSString *_name; // necessary for legacy runtime } @property(readwrite) NSString *name; @end @implementation APerson @synthesize name; // use name = _name for legacy runtime @end </code></pre> <p><code>@synthesize</code> creates in this case those two methods (not 100% accurate):</p> <pre><code>- (NSString *)name { return [[_name copy] autorelease]; } - (void)setName:(NSString *)value { [value retain]; [_name release]; _name = value; } </code></pre> <p>It's easy now to distinguish between <code>ivars</code> and getters/setters. The accessors have got the <code>self.</code> prefix. You shouldn't access the variables directly anyway.</p> <hr> <p>Your sample code doesn't work as it should be:</p> <pre><code>_myVar = some_other_object; // _myVar is the ivar, not myVar. self.myVar = some_other_object; // works too, uses the accessors </code></pre>
1,339,394
Passing NSInteger variable to NSMutableDictionary or NSMutableArray
<p>Why does this not work:</p> <pre><code>NSInteger temp = 20; [userSettingsFromFile setObject:temp forKey:@"aTemp"]; </code></pre> <p>but this does:</p> <pre><code>[userSettingsFromFile setObject:@"someObject" forKey:@"aTemp"]; </code></pre> <p>How can I use the <code>NSInteger</code> variable?</p>
1,339,407
7
2
null
2009-08-27 07:24:04.267 UTC
7
2017-01-11 00:28:21.097 UTC
2013-06-01 11:50:14.347 UTC
null
1,571,232
null
40,106
null
1
41
objective-c|iphone
36,763
<p><code>NSInteger</code> isn't an object -- it's simply typecast to <code>int</code> on 32-bit or <code>long</code> on 64-bit. Since <code>NSDictionary</code> can only store objects, you need to wrap the integer into an object before you can store it. Try this:</p> <pre><code>NSInteger temp = 20; [userSettingsFromFile setObject:[NSNumber numberWithInteger:temp] forKey:@"aTemp"]; </code></pre>
1,086,054
How to convert int[] to byte[]
<p>I have an array of integers which represent a RGB image and would like to convert it to a byte array and save it to a file.</p> <p>What's the best way to convert an array of integers to the array of bytes in Java?</p>
1,086,092
7
1
null
2009-07-06 08:47:45.587 UTC
15
2021-03-25 09:01:29.993 UTC
2014-12-12 13:54:21.783 UTC
null
1,536,976
null
22,996
null
1
65
java|arrays|type-conversion
88,973
<p>As <a href="https://stackoverflow.com/a/1086067/1536976">Brian</a> says, you need to work out how what sort of conversion you need.</p> <p>Do you want to save it as a "normal" image file (jpg, png etc)?</p> <p>If so, you should probably use the <a href="http://docs.oracle.com/javase/7/docs/technotes/guides/imageio/" rel="noreferrer">Java Image I/O</a> API.</p> <p>If you want to save it in a "raw" format, the order in which to write the bytes must be specified, and then use an <code>IntBuffer</code> and NIO.</p> <p>As an example of using a ByteBuffer/IntBuffer combination:</p> <pre><code>import java.nio.*; import java.net.*; class Test { public static void main(String [] args) throws Exception // Just for simplicity! { int[] data = { 100, 200, 300, 400 }; ByteBuffer byteBuffer = ByteBuffer.allocate(data.length * 4); IntBuffer intBuffer = byteBuffer.asIntBuffer(); intBuffer.put(data); byte[] array = byteBuffer.array(); for (int i=0; i &lt; array.length; i++) { System.out.println(i + ": " + array[i]); } } } </code></pre>
229,851
Overcoming "It is being used by another person or program."
<p>Is there a way to unlock Windows files without downloading a utility?</p> <p>I have a few files on my Windows XP C: drive that are very old and very useless. When I try to delete these files I get the following message:</p> <pre> Cannot delete FILENAME.zip: It is being used by another person or program Close any programs that might be using the file and try again. </pre> <p>No one is accessing this file. No program is using it currently. Windows has screwed up the file locking mechanism. </p> <p>Is there a way to delete this file without downloading someone's unlocking utility? I find the sites offering these programs to be a tad sketchy.</p> <p>How could you force the file to unlock from within a program? I'm competent in Java, Perl, and Ruby, but I haven't seen anything among their libraries that would aid me here.</p>
229,894
8
5
null
2008-10-23 14:08:54.003 UTC
1
2021-05-25 00:45:49.247 UTC
2008-10-23 18:45:43.993 UTC
Adrian Dunston
8,344
Adrian Dunston
8,344
null
1
25
windows|permissions|locking
52,672
<p>I've successfully used Process Explorer to find out which process has the file open. It saves a reboot that may not fix the problem anyway.</p> <p>In process explorer: Find &gt; Handle or DLL... then search for the name of the folder/file, then double click one of the search results. It'll select a handle in the main window, which you can right click and close.</p>
702,301
How to determine the IP address of a Solaris system
<p>What command do I want to issue when I want to know the IP address of the Solaris machine I'm logged onto?</p>
702,533
8
1
null
2009-03-31 18:02:13.03 UTC
7
2018-12-27 20:49:19.71 UTC
2018-04-26 01:11:24.607 UTC
null
85,248
monocongo
85,248
null
1
35
unix|networking|ip-address|solaris|ip
197,754
<p>If you're a normal user (i.e., not 'root') <strong><code>ifconfig</code></strong> isn't in your path, but it's the command you want.</p> <p>More specifically: <strong><code>/usr/sbin/ifconfig -a</code></strong></p>
1,113,819
Arrays, heap and stack and value types
<pre><code>int[] myIntegers; myIntegers = new int[100]; </code></pre> <p>In the above code, is new int[100] generating the array on the heap? From what I've read on CLR via c#, the answer is yes. But what I can't understand, is what happens to the actual int's inside the array. As they are value types, I'd guess they'd have to be boxed, as I can, for example, pass myIntegers to other parts of the program and it'd clutter up the stack if they were left on it all the time. Or am I wrong? I'd guess they'd just be boxed and would live on the heap for as long the array existed.</p>
1,114,152
8
0
null
2009-07-11 14:30:11.58 UTC
121
2021-06-30 14:15:12.95 UTC
2021-06-30 14:15:12.95 UTC
null
5,459,839
null
130,758
null
1
151
c#|arrays|memory|heap-memory|stack-memory
61,756
<p>Your array is allocated on the heap, and the ints are not boxed.</p> <p>The source of your confusion is likely because people have said that reference types are allocated on the heap, and value types are allocated on the stack. This is not an entirely accurate representation.</p> <p>All local variables and parameters are allocated on the stack. This includes both value types and reference types. The difference between the two is only what is <em>stored</em> in the variable. Unsurprisingly, for a value type, the <em>value</em> of the type is stored directly in the variable, and for a reference type, the value of the type is stored on the heap, and a <em>reference</em> to this value is what is stored in the variable.</p> <p>The same holds for fields. When memory is allocated for an instance of an aggregate type (a <code>class</code> or a <code>struct</code>), it must include storage for each of its instance fields. For reference-type fields, this storage holds just a reference to the value, which would itself be allocated on the heap later. For value-type fields, this storage holds the actual value.</p> <p>So, given the following types:</p> <pre><code>class RefType{ public int I; public string S; public long L; } struct ValType{ public int I; public string S; public long L; } </code></pre> <p>The values of each of these types would require 16 bytes of memory (assuming a 32-bit word size). The field <code>I</code> in each case takes 4 bytes to store its value, the field <code>S</code> takes 4 bytes to store its reference, and the field <code>L</code> takes 8 bytes to store its value. So the memory for the value of both <code>RefType</code> and <code>ValType</code> looks like this:</p> <pre> 0 ┌───────────────────┐ │ I │ 4 ├───────────────────┤ │ S │ 8 ├───────────────────┤ │ L │ │ │ 16 └───────────────────┘ </pre> <p>Now if you had three local variables in a function, of types <code>RefType</code>, <code>ValType</code>, and <code>int[]</code>, like this:</p> <pre><code>RefType refType; ValType valType; int[] intArray; </code></pre> <p>then your stack might look like this:</p> <pre> 0 ┌───────────────────┐ │ refType │ 4 ├───────────────────┤ │ valType │ │ │ │ │ │ │ 20 ├───────────────────┤ │ intArray │ 24 └───────────────────┘ </pre> <p>If you assigned values to these local variables, like so:</p> <pre><code>refType = new RefType(); refType.I = 100; refType.S = "refType.S"; refType.L = 0x0123456789ABCDEF; valType = new ValType(); valType.I = 200; valType.S = "valType.S"; valType.L = 0x0011223344556677; intArray = new int[4]; intArray[0] = 300; intArray[1] = 301; intArray[2] = 302; intArray[3] = 303; </code></pre> <p>Then your stack might look something like this:</p> <pre> 0 ┌───────────────────┐ │ 0x4A963B68 │ -- heap address of `refType` 4 ├───────────────────┤ │ 200 │ -- value of `valType.I` │ 0x4A984C10 │ -- heap address of `valType.S` │ 0x44556677 │ -- low 32-bits of `valType.L` │ 0x00112233 │ -- high 32-bits of `valType.L` 20 ├───────────────────┤ │ 0x4AA4C288 │ -- heap address of `intArray` 24 └───────────────────┘ </pre> <p>Memory at address <code>0x4A963B68</code> (value of <code>refType</code>) would be something like:</p> <pre> 0 ┌───────────────────┐ │ 100 │ -- value of `refType.I` 4 ├───────────────────┤ │ 0x4A984D88 │ -- heap address of `refType.S` 8 ├───────────────────┤ │ 0x89ABCDEF │ -- low 32-bits of `refType.L` │ 0x01234567 │ -- high 32-bits of `refType.L` 16 └───────────────────┘ </pre> <p>Memory at address <code>0x4AA4C288</code> (value of <code>intArray</code>) would be something like:</p> <pre> 0 ┌───────────────────┐ │ 4 │ -- length of array 4 ├───────────────────┤ │ 300 │ -- `intArray[0]` 8 ├───────────────────┤ │ 301 │ -- `intArray[1]` 12 ├───────────────────┤ │ 302 │ -- `intArray[2]` 16 ├───────────────────┤ │ 303 │ -- `intArray[3]` 20 └───────────────────┘ </pre> <p>Now, if you passed <code>intArray</code> to another function, the value pushed onto the stack would be <code>0x4AA4C288</code>, the address of the array, <strong>not</strong> a copy of the array.</p>
771,453
Copy map values to vector in STL
<p>Working my way through Effective STL at the moment. Item 5 suggests that it's usually preferable to use range member functions to their single element counterparts. I currently wish to copy all the values in a map (i.e. - I don't need the keys) to a vector.</p> <p>What is the cleanest way to do this?</p>
771,463
13
1
null
2009-04-21 07:30:42.763 UTC
32
2022-01-12 16:41:38.227 UTC
null
null
null
null
11,515
null
1
97
c++|stl|containers
146,203
<p>You can't easily use a range here because the iterator you get from a map refers to a std::pair, where the iterators you would use to insert into a vector refers to an object of the type stored in the vector, which is (if you are discarding the key) not a pair.</p> <p>I really don't think it gets much cleaner than the obvious:</p> <pre><code>#include &lt;map&gt; #include &lt;vector&gt; #include &lt;string&gt; using namespace std; int main() { typedef map &lt;string, int&gt; MapType; MapType m; vector &lt;int&gt; v; // populate map somehow for( MapType::iterator it = m.begin(); it != m.end(); ++it ) { v.push_back( it-&gt;second ); } } </code></pre> <p>which I would probably re-write as a template function if I was going to use it more than once. Something like:</p> <pre><code>template &lt;typename M, typename V&gt; void MapToVec( const M &amp; m, V &amp; v ) { for( typename M::const_iterator it = m.begin(); it != m.end(); ++it ) { v.push_back( it-&gt;second ); } } </code></pre>
775,726
What's the fuss about Haskell?
<p>I know a few programmers who keep talking about Haskell when they are among themselves, and here on SO everyone seems to love that language. Being good at Haskell seems somewhat like the hallmark of a genius programmer.</p> <p>Can someone give a few Haskell examples that show why it is so elegant / superior?</p>
775,759
17
0
2009-04-22 11:12:01.503 UTC
2009-04-22 04:45:47.05 UTC
63
2020-01-04 19:01:45.26 UTC
2012-05-01 10:05:19.037 UTC
null
1,140,748
null
60,628
null
1
111
haskell|functional-programming
39,153
<p>The way it was pitched to me, and what I think is true after having worked on learning on Haskell for a month now, is the fact that functional programming twists your brain in interesting ways: it forces you to think about familiar problems in different ways: instead of loops, think in maps and folds and filters, etc. In general, if you have more than one perspective on a problem, it makes you better enabled to reason about this problem, and switch viewpoints as necessary.</p> <p>The other really neat thing about Haskell is its type system. It's strictly typed, but the type inference engine makes it feel like a Python program that magically tells you when you've done a stupid type-related mistake. Haskell's error messages in this regard are somewhat lacking, but as you get more acquainted with the language you'll say to yourself: this is what typing is supposed to be!</p>
985,384
Delete duplicate records from a SQL table without a primary key
<p>I have the below table with the below records in it</p> <pre><code>create table employee ( EmpId number, EmpName varchar2(10), EmpSSN varchar2(11) ); insert into employee values(1, 'Jack', '555-55-5555'); insert into employee values (2, 'Joe', '555-56-5555'); insert into employee values (3, 'Fred', '555-57-5555'); insert into employee values (4, 'Mike', '555-58-5555'); insert into employee values (5, 'Cathy', '555-59-5555'); insert into employee values (6, 'Lisa', '555-70-5555'); insert into employee values (1, 'Jack', '555-55-5555'); insert into employee values (4, 'Mike', '555-58-5555'); insert into employee values (5, 'Cathy', '555-59-5555'); insert into employee values (6 ,'Lisa', '555-70-5555'); insert into employee values (5, 'Cathy', '555-59-5555'); insert into employee values (6, 'Lisa', '555-70-5555'); </code></pre> <p>I dont have any primary key in this table .But i have the above records in my table already. I want to remove the duplicate records which has the same value in EmpId and EmpSSN fields.</p> <p>Ex : Emp id 5 </p> <p>Can any one help me to frame a query to delete those duplicate records</p> <p>Thanks in advance</p>
985,426
20
4
null
2009-06-12 07:12:06.95 UTC
24
2022-03-08 09:26:13.953 UTC
2010-07-16 07:47:57.16 UTC
null
41,956
null
40,521
null
1
58
sql|sql-server-2005|tsql|duplicate-removal
123,193
<p>Add a Primary Key (code below)</p> <p>Run the correct delete (code below)</p> <p>Consider WHY you woudln't want to keep that primary key.</p> <hr /> <p>Assuming MSSQL or compatible:</p> <pre><code>ALTER TABLE Employee ADD EmployeeID int identity(1,1) PRIMARY KEY; WHILE EXISTS (SELECT COUNT(*) FROM Employee GROUP BY EmpID, EmpSSN HAVING COUNT(*) &gt; 1) BEGIN DELETE FROM Employee WHERE EmployeeID IN ( SELECT MIN(EmployeeID) as [DeleteID] FROM Employee GROUP BY EmpID, EmpSSN HAVING COUNT(*) &gt; 1 ) END </code></pre>
6,405,083
Is it possible to boot the Linux kernel without creating an initrd image?
<p>As I understand, initrd is a small image that is loadable in the RAM. It is used to boot a complete kernel with all the loadable modules. As part of the process, we need the vmlinuz kernel image which is a renamed version of bzImage. </p> <p>Is it possible to boot the kernel without creating the initrd image? </p>
6,405,171
5
3
null
2011-06-19 20:57:58.037 UTC
9
2020-08-02 20:14:19.507 UTC
2018-02-16 10:17:51.577 UTC
null
895,245
null
350,129
null
1
20
linux|boot|initrd
25,731
<p>initrd/initramfs is optional and not a requirement. bzImage is the pure kernel image and can be booted directly by the bootloader. However it might be neccesary to execute some tasks (loading filesystem modules, drivers for disk access, mounting the root file system from some exchangeable media without fixed name/path, etc.) that would usually require access to a filesystem and userspace tools.</p> <p>That's what <em>initramfs</em> is for: It is a CPIO archive that gets attached to the kernel image (the kernel image is the container for the initramfs not other way round) either in the kernel image itself, or by the bootloader at boot time.</p> <p>That CPIO archive contains an initial rootfs with the modules required to setup all devices to access the proper root filesystem and some programs to identify those devices, load the modules, do some other startup tasks remount the proper root file system to / and start /sbin/init</p> <p><em>initrd</em> is similar, with the main difference that it is an filesystem image, that may be and usually is compressed. The kernel must have support for the filesystem used built in and will mount this image as the initial /.</p> <p>Since CPIO is simpler by several orders of magnitudes, initramfs is prefered over initrd, as this saves both the requirement for any filesystem modules being built in and also makes initramfs creation easier. Instead of having to create an ext2 image, loopdevice mount and populate it, it boils down to a simple archive creation, not unlike using tar.</p> <p>However if you compile your kernel with all required drivers and modules built into the kernel image, and your root file system device has a fixed name in the system you don't need a initramfs as the kernel can do things by itself then.</p>
6,433,900
Syncing HTML5 <video> with <audio> playback
<p>I am having track from one source, mute, and I'd like to play background music over it using element. The tracks contain some time critical elements.</p> <p>What would be the options to sync these two different media players in HTML5 / Javascript? would give the master clock as it audio playback is very time sensitive - loosing video frames now and then is not critical.</p>
11,285,638
6
1
null
2011-06-22 01:26:31.01 UTC
16
2021-09-18 15:22:48.123 UTC
null
null
null
null
315,168
null
1
22
javascript|html|video|audio
19,094
<p>Mikko Ohtamaa provided a solution in a comment, which I actually think is the best option here - it doesn't require a framework, and it doesn't require you to edit your video files.</p> <p>Essentially, just grab the current time from the video element when it is "unmuted", and apply that time to the audio element. Some code might look like this:</p> <pre><code>function unmute() { var vid = document.getElementById("video"); var aud = document.getElementById("audio"); aud.currentTime = vid.currentTime; aud.play(); } </code></pre>
6,587,879
How to elegantly check the existence of an object/instance/variable and simultaneously assign it to variable if it exists in python?
<p>I am using SQLAlchemy to populate a database and often I need to check if a orm object exists in a database before processing. This may be an unconventional question, but I found myself encountering this pattern often:</p> <pre><code>my_object = session.query(SomeObject).filter(some_fiter).first() if my_object: # Mostly in databases... # Juchee it exists # process else: # It does not exist. :-( my_object = SomeObject() # process </code></pre> <p>What I am <strong>dreaming</strong> of would be something like:</p> <pre><code>if my_object = session.query(someObject).blabla.first(): # if my_object is None this scope is left alone # if my_object is not None I can work with my_object here... </code></pre> <p>I know, that this syntax is wrong, but I wanted to explain, what I mean by this example. Any equivalent way would make me happy.</p> <p>Is there an elegant python approach for this pattern? This question aims not only at SQLAlchemy, but to each equivalent scenario.</p> <p><em>closing my eyes hitting "Post your question" and waiting for the smart people and pythonistas by heart to hunt me down for asking something mayhaps inappropriate</em> ;-)</p>
16,003,360
9
2
null
2011-07-05 19:33:12.587 UTC
23
2020-02-25 18:09:45.853 UTC
2016-06-01 17:56:28.647 UTC
null
2,665,591
null
641,514
null
1
78
python|sqlalchemy
70,173
<p>You want to execute a Exist query to be efficient</p> <pre><code>(ret, ), = Session.query(exists().where(SomeObject.field==value)) </code></pre> <p>Mike Bayer explain it in his blog post:<br> <a href="http://techspot.zzzeek.org/2008/09/09/selecting-booleans/" rel="noreferrer">http://techspot.zzzeek.org/2008/09/09/selecting-booleans/</a></p> <p>You can use scalar if you don't want to have a tuple as result:</p> <pre><code>ret = Session.query(exists().where(SomeObject.field==value)).scalar() </code></pre>
6,880,232
Disable / Check for Mock Location (prevent gps spoofing)
<p>Looking to find the best way to prevent / detect GPS spoofing on Android. Any suggestions on how this is accomplished, and what can be done to stop it? I am guessing the user has to turn on mock locations to spoof GPS, if this is done, then they can spoof GPS? </p> <p>I guess I would need to just detect if Mock Locations are enabled? Any other suggestions?</p>
16,776,891
10
2
null
2011-07-30 00:14:59.34 UTC
70
2021-10-09 13:02:17.933 UTC
null
null
null
null
393,258
null
1
99
android|gps|spoof
177,070
<p>I have done some investigation and sharing my results here,this may be useful for others.</p> <p>First, we can check whether MockSetting option is turned ON</p> <pre><code>public static boolean isMockSettingsON(Context context) { // returns true if mock location enabled, false if not enabled. if (Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ALLOW_MOCK_LOCATION).equals(&quot;0&quot;)) return false; else return true; } </code></pre> <p>Second, we can check whether are there other apps in the device, which are using <code>android.permission.ACCESS_MOCK_LOCATION</code> (Location Spoofing Apps)</p> <pre><code>public static boolean areThereMockPermissionApps(Context context) { int count = 0; PackageManager pm = context.getPackageManager(); List&lt;ApplicationInfo&gt; packages = pm.getInstalledApplications(PackageManager.GET_META_DATA); for (ApplicationInfo applicationInfo : packages) { try { PackageInfo packageInfo = pm.getPackageInfo(applicationInfo.packageName, PackageManager.GET_PERMISSIONS); // Get Permissions String[] requestedPermissions = packageInfo.requestedPermissions; if (requestedPermissions != null) { for (int i = 0; i &lt; requestedPermissions.length; i++) { if (requestedPermissions[i] .equals(&quot;android.permission.ACCESS_MOCK_LOCATION&quot;) &amp;&amp; !applicationInfo.packageName.equals(context.getPackageName())) { count++; } } } } catch (NameNotFoundException e) { Log.e(&quot;Got exception &quot; , e.getMessage()); } } if (count &gt; 0) return true; return false; } </code></pre> <p>If both above methods, first and second are true, then there are good chances that location may be spoofed or fake.</p> <p>Now, spoofing can be avoided by using Location Manager's API.</p> <p>We can remove the test provider before requesting the location updates from both the providers (Network and GPS)</p> <pre><code>LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE); try { Log.d(TAG ,&quot;Removing Test providers&quot;) lm.removeTestProvider(LocationManager.GPS_PROVIDER); } catch (IllegalArgumentException error) { Log.d(TAG,&quot;Got exception in removing test provider&quot;); } lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, locationListener); </code></pre> <p>I have seen that removeTestProvider(~) works very well over Jelly Bean and onwards version. This API appeared to be unreliable till Ice Cream Sandwich.</p> <p><strong>Flutter Update:</strong> Use <a href="https://pub.dev/packages/geolocator" rel="noreferrer">Geolocator</a> and check <code>Position</code> object's <code>isMocked</code> property.</p>
6,316,540
How to make layout with View fill the remaining space?
<p>I'm designing my application UI. I need a layout looks like this:</p> <p><img src="https://i.stack.imgur.com/t5Ulu.png" alt="Example of desired layout"></p> <p>(&lt; and > are Buttons). The problem is, I don't know how to make sure the TextView will fill the remaining space, with two buttons have fixed size.</p> <p>If I use fill_parent for Text View, the second button (>) can't be shown.</p> <p>How can I craft a layout that looks like the image?</p>
25,781,167
12
2
null
2011-06-11 14:45:56.43 UTC
40
2021-10-22 05:30:34.423 UTC
2015-12-30 00:00:40.937 UTC
null
3,063,884
null
653,457
null
1
211
android|layout|android-layout
186,703
<p>Answer from woodshy worked for me, and it is simpler than the answer by Ungureanu Liviu since it does not use <code>RelativeLayout</code>. I am giving my layout for clarity:</p> <pre><code>&lt;LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" &gt; &lt;Button android:layout_width = "80dp" android:layout_weight = "0" android:layout_height = "wrap_content" android:text="&amp;lt;"/&gt; &lt;TextView android:layout_width = "fill_parent" android:layout_height = "wrap_content" android:layout_weight = "1"/&gt; &lt;Button android:layout_width = "80dp" android:layout_weight = "0" android:layout_height = "wrap_content" android:text="&amp;gt;"/&gt; &lt;/LinearLayout&gt; </code></pre>
38,069,719
Setting custom header using HttpURLConnection
<p>I am simply making a <code>GET</code> request to a Rest API using <code>HttpURLConnection</code>.</p> <p>I need to add some custom headers but I am getting <code>null</code> while trying to retrieve their values.</p> <p><strong>Code:</strong></p> <pre><code>URL url; try { url = new URL("http://www.example.com/rest/"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // Set Headers conn.setRequestProperty("CustomHeader", "someValue"); conn.setRequestProperty("accept", "application/json"); // Output is null here &lt;-------- System.out.println(conn.getHeaderField("CustomHeader")); // Request not successful if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new RuntimeException("Request Failed. HTTP Error Code: " + conn.getResponseCode()); } // Read response BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuffer jsonString = new StringBuffer(); String line; while ((line = br.readLine()) != null) { jsonString.append(line); } br.close(); conn.disconnect(); } catch (IOException e) { e.printStackTrace(); } </code></pre> <p>What am I missing?</p>
38,070,019
2
1
null
2016-06-28 07:27:44.543 UTC
5
2018-04-10 08:05:09.723 UTC
2018-04-10 08:05:09.723 UTC
null
1,009,479
null
4,362,001
null
1
12
java|rest|http-headers|httpurlconnection|urlconnection
46,989
<p>The <code>conn.getHeaderField("CustomHeader")</code> returns the <em>response</em> header not the request one.</p> <p>To return the request header use: <code>conn.getRequestProperty("CustomHeader")</code></p>
50,637,666
Where do I find a list of all mat-icons -- Angular
<p>I started using <code>&lt;mat-icon&gt;</code> of angular-material and I wonder if there is any collection of the names of all the included icons. Past a few months, I used this already and I think, back then, I found a homepage where a bunch of them were listed. But this site is not findable anymore. </p> <p>Is there any list of this icons out there or something else to look for these?</p>
50,640,595
3
6
null
2018-06-01 06:51:46.983 UTC
10
2022-09-24 14:58:26.437 UTC
2021-02-03 14:09:43.39 UTC
null
8,458,652
null
9,739,585
null
1
121
icons|material-design|angular-material
256,367
<p><strong>Edit:</strong></p> <p>As the icons listed on the website are slightly outdated, here's the correct resources:</p> <ul> <li><a href="https://jossef.github.io/material-design-icons-iconfont/" rel="nofollow noreferrer">Material Design Icons DX - (forked version)</a></li> </ul> <hr /> <p>The old Material.io link now redirects to the <a href="https://fonts.google.com/icons" rel="nofollow noreferrer">Icons</a> page on Google Fonts.</p> <hr /> <p>Isn't it <a href="https://material.io/resources/icons" rel="nofollow noreferrer">Material Icons</a> (as stated by @RobbyCornelissen)? The Google Material Design team had recently (last month) updated their website.</p> <p>Anyways, the Angular Material team expects developers to include the Google Material Design Icon Font themselves (Google Fonts/self-host/whatever you fancy).</p>
50,688,998
Using ApolloClient with node.js. "fetch is not found globally and no fetcher passed"
<p>I am attempting to use an Apollo Client on a node.js server to interface with another GraphQL API using the following code:</p> <pre><code>import fetch from 'node-fetch' import { createHttpLink } from 'apollo-link-http' import ApolloClient from 'apollo-boost' import { API_URL } from '...' const client = new ApolloClient({ link: createHttpLink({ uri: API_URL, fetch: fetch, }), }) </code></pre> <p>Which yields the following error:</p> <pre><code>module initialization error: Error fetch is not found globally and no fetcher passed, to fix pass a fetch for your environment like https://www.npmjs.com/package/node-fetch. For example: import fetch from 'node-fetch'; import { createHttpLink } from 'apollo-link-http'; const link = createHttpLink({ uri: '/graphql', fetch: fetch }); at Object.checkFetcher (/var/task/node_modules/apollo-link-http-common/lib/bundle.umd.js:78:19) at createHttpLink (/var/task/node_modules/apollo-link-http/lib/bundle.umd.js:32:30) at new HttpLink (/var/task/node_modules/apollo-link-http/lib/bundle.umd.js:203:38) at new DefaultClient (/var/task/node_modules/apollo-boost/lib/index.js:80:24) </code></pre> <p>I understand that the Apollo Client by default is expecting to be run in a browser context where a <code>fetch</code> method will be available, and that in a node.js I need to polyfill or otherwise provide a <code>fetch</code> method, but I having trouble figuring out exactly how to do this.</p> <p>Following the example code at <a href="https://www.apollographql.com/docs/link/#apollo-client" rel="noreferrer">https://www.apollographql.com/docs/link/#apollo-client</a> it appears that I should be able to pass this information in using the <code>link</code> option, and reading the <code>apollo-boost</code> source code seems to suggest that you can pass this information in using <code>fetcherOptions</code>, but neither of these solutions seem to work.</p> <p>Can anyone provide some example code for initializing an Apollo Client in node.js with a fetcher?</p> <p>For reference here is my <code>package.json</code></p> <pre><code>{ "name": "API-Service", "version": "1.0.0", "description": "", "private": true, "scripts": {}, "dependencies": { "apollo-boost": "^0.1.6", "apollo-link-http": "^1.5.4", "graphql": "^0.13.2", "babel-polyfill": "^6.26.0", "json-rules-engine": "^2.1.0", "node-fetch": "^2.1.2", "mysql": "^2.15.0" } } </code></pre>
50,689,652
6
1
null
2018-06-04 21:25:51.203 UTC
4
2020-06-21 16:47:24.317 UTC
2018-06-04 21:40:05.96 UTC
null
1,291,473
null
1,291,473
null
1
38
node.js|polyfills|apollo-client
31,432
<p>It turns out that the <code>ApolloClient</code> provided by the <code>apollo-boost</code> library does not accept a <code>link</code> option. Switching to use the vanilla <code>apollo-client</code> allows you to specify your fetching mechanism.</p> <p>Although <code>apollo-boost</code> and <code>apollo-client</code> both export an <code>ApolloClient</code> in the docs, they take wildly different options.</p> <pre><code>import fetch from 'node-fetch' import { createHttpLink } from 'apollo-link-http' import { InMemoryCache } from 'apollo-cache-inmemory' import ApolloClient from 'apollo-client' import { API_URL } from '...' const client = new ApolloClient({ link: createHttpLink({ uri: API_URL, fetch: fetch, }), cache: new InMemoryCache(), }) </code></pre>
10,792,163
change <audio> src with javascript
<p>I have multiple audio files that I want to stream based on the user selects. How do I do that? This is what I have so far and it doesn't seem to work. </p> <p>*UPDATE: Made a few changes and now its claiming that <code>audio.load();</code> is not a function. Can anyone tell me why that is? The Code is updated to reflect the changes. </p> <p>JavaScript:</p> <pre><code>function updateSource(){ var audio = document.getElementById('oggSource'); audio.src = 'audio/ogg/' + document.getElementById('song1').getAttribute('data-value'); audio.load(); } </code></pre> <p>HTML:</p> <pre><code>&lt;audio id="audio" controls="controls"&gt; &lt;source id="oggSource" src="" type="audio/ogg"&gt;&lt;/source&gt; &lt;source id="mp3Source" type="audio/mp3"&gt;&lt;/source&gt; Your browser does not support the audio format. &lt;/audio&gt; &lt;ul style="list-style: none"&gt; &lt;li&gt;Sunday May 27, 2012 &lt;ul style="display: none"&gt; &lt;li id="song1" data-value="song1.ogg"&gt; &lt;button onclick="updateSource();"&gt;Item1&lt;/button&gt; &lt;/li&gt; &lt;li&gt;Item2&lt;/li&gt; &lt;li&gt;Item3&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre> <p><code>Item2</code> and <code>Item3</code> I will want to play a different audio file when they are clicked on.</p>
10,792,564
7
4
null
2012-05-29 01:33:41.843 UTC
13
2021-08-16 05:48:26.85 UTC
2012-05-29 03:12:27.413 UTC
null
283,863
null
1,284,810
null
1
63
javascript|html|html5-audio
136,765
<p>Try this snippet</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>list.onclick = function(e) { e.preventDefault(); var elm = e.target; var audio = document.getElementById('audio'); var source = document.getElementById('audioSource'); source.src = elm.getAttribute('data-value'); audio.load(); //call this to just preload the audio without playing audio.play(); //call this to play the song right away };</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;ul style="list-style: none"&gt; &lt;li&gt;Audio Files &lt;ul id="list"&gt; &lt;li&gt;&lt;a href="#" data-value="http://media.w3.org/2010/07/bunny/04-Death_Becomes_Fur.oga"&gt;Death_Becomes_Fur.oga&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#" data-value="http://media.w3.org/2010/07/bunny/04-Death_Becomes_Fur.mp4"&gt;Death_Becomes_Fur.mp4&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#" data-value="http://media.w3.org/2010/11/rrs006.oga"&gt;rrs006.oga&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#" data-value="http://media.w3.org/2010/05/sound/sound_90.mp3"&gt;sound_90.mp3&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;audio id="audio" controls="controls"&gt; &lt;source id="audioSource" src=""&gt;&lt;/source&gt; Your browser does not support the audio format. &lt;/audio&gt;</code></pre> </div> </div> </p> <p>JSFiddle <a href="http://jsfiddle.net/jm6ky/2/" rel="noreferrer">http://jsfiddle.net/jm6ky/2/</a></p>
33,938,206
Check if method exists in the same class
<p>So, <code>method_exists()</code> requires an object to see if a method exists. But I want to know if a method exists from within the same class.</p> <p>I have a method that process some info and can receive an action, that runs a method to further process that info. I want to check if the method exists before calling it. How can I achieve it?</p> <p>Example:</p> <pre><code>class Foo{ public function bar($info, $action = null){ //Process Info $this-&gt;$action(); } } </code></pre>
33,938,381
4
10
null
2015-11-26 12:01:46.94 UTC
2
2017-04-21 02:23:24.3 UTC
null
null
null
null
4,611,298
null
1
32
php|class|methods|exists
40,797
<p>You can do something like this:</p> <pre><code>class A{ public function foo(){ echo "foo"; } public function bar(){ if(method_exists($this, 'foo')){ echo "method exists"; }else{ echo "method does not exist"; } } } $obj = new A; $obj-&gt;bar(); </code></pre>
41,105,586
Android - Firebase - TaskSnapshot - Method should only be accessed within private scope?
<p>Everything was working great... until I came back to work from a 3 month break and updated my Firebase from 9.8 to 10.0.1</p> <p>Now all of my calls to <code>TaskSnapshot</code> are giving me an error.</p> <p>Here is the example code that worked fine before:</p> <pre><code>OnSuccessListener&lt;UploadTask.TaskSnapshot&gt; successListener = new OnSuccessListener&lt;UploadTask.TaskSnapshot&gt;() { @Override public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { attachments.add(fileName + "*-*" + taskSnapshot.getDownloadUrl().toString()); numberOfCallbacks++; if (numberOfFiles == numberOfCallbacks) { currentUpload = false; onClickSendAlert(sendingView); } } }; </code></pre> <p>The error that I now get is regarding <code>taskSnapshot.getDownloadUrl()</code>.</p> <p>Android Studio underlines that line in red and says:</p> <blockquote> <p>This method should only be accessed from tests or within private scope</p> </blockquote> <p>Can someone explain why this is happening? I have been researching all day for two days straight now and can't for the life of me figure this out (embarrassing).</p> <p>For what it's worth, this code is used to upload a file to Firebase Storage, then when it is complete (<code>OnSuccess</code>), it gets the download URL and stores it in the Firebase Database. This worked great before I updated to 10.0.1. I get the same error on my download tasks in another module.</p> <p>Here is a screenshot to give you a better visual of my situation:</p> <p><a href="https://i.stack.imgur.com/2yHZZ.png"><img src="https://i.stack.imgur.com/2yHZZ.png" alt="enter image description here"></a></p>
42,616,488
4
8
null
2016-12-12 16:47:14.083 UTC
14
2022-03-03 11:59:45.147 UTC
2016-12-12 18:20:44.617 UTC
null
209,103
null
2,254,886
null
1
47
android|firebase|firebase-storage
14,838
<p>The problem seems to be caused by an overzealous Lint check. Try something like this:</p> <pre><code>@SuppressWarnings("VisibleForTests") Uri downloadUrl = taskSnapshot.getDownloadUrl(); </code></pre> <p>This trick worked for me. If the problem's related to <a href="https://code.google.com/p/android/issues/detail?id=235661" rel="noreferrer">this bug report</a>, then it should be fixed in 2.4.</p>
22,874,155
Video tag to fill 100% div regardless of ratios
<p>I am tying to have a video tag to fill 100% of a div:</p> <p>a) it doesn't need to keep the ratios(otherwise we need to use the overflow:none);</p> <p>b) fill a div, not the whole background;</p> <p>c) it would be a plus to be responsible. Now it is as long as you re-size window diagonally. Keeping height and re-sizing horizontally cuts the video. </p> <p>I have tried dozens if not hundreds of alternative, and all of them keep the initial video ratio. </p> <p>it works in the <a href="http://jsfiddle.net/Gloak/FCPW2/" rel="noreferrer">fidlle</a> .... maybe because the screen is small, maybe because fiddle is a better browser...</p> <pre><code>&lt;body&gt; &lt;div class="wrapper"&gt; &lt;div class="header"&gt; ..... &lt;/div&gt; &lt;div class="out-video"&gt; &lt;video autoplay loop poster="mel.jpg" id="bgvid" width="100%" height="100%"&gt; &lt;source src="http://www.mysite.braaasil.com/video/mel.webm" type="video/webm"&gt; &lt;source src="http://www.mysite.braaasil.com/video/mel.mp4" type="video/mp4"&gt; &lt;/video&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p></p> <p>The site is here but as I try the solutions, it will change... There is a right and left sidebar empty. I would like the video to fill the whole width. When it covers the div, the height change and the video does not show in full. I would like something like the background-size 100% 100% that stretches the images to the end of the div, but it does not work for video. </p> <p>Thank you for any suggestion in advance. </p> <p>PS. It seems that android family does not play the video!</p> <p>l</p>
22,874,277
4
2
null
2014-04-04 22:36:55.647 UTC
7
2021-09-20 14:31:43.867 UTC
2018-08-11 18:18:32.393 UTC
null
2,060,451
null
2,060,451
null
1
22
html|css|responsive-design
63,673
<p>You can use a solution like <a href="http://jsfiddle.net/aloisdg/FCPW2/2/" rel="nofollow noreferrer">this one</a>. Ratio dont change, but you may lose the right part of the video.</p> <pre><code>video#bgvid { position: absolute; z-index: 0; background: url(mel.jpg) no-repeat; background-size: 100% 100%; top: 0px; left: 0px; /* fixed to left. Replace it by right if you want.*/ min-width: 100%; min-height: 100%; width: auto; height: auto; } </code></pre> <p>The video will be fix to top left corner. If you want to improve it, I think you will need some JavaScript.</p> <p><strong>Edit :</strong></p> <p>Just a find a solution with JQuery who can fit your need : <a href="https://stackoverflow.com/questions/10797632/simulate-background-sizecover-on-video-or-img">simulate background-size:cover on <code>&lt;video&gt;</code> or <code>&lt;img&gt;</code></a></p> <p><a href="http://jsfiddle.net/aloisdg/cYAx3/1/" rel="nofollow noreferrer">Demo</a></p>
13,531,576
Oracle: export a table with blobs to an .sql file that can be imported again
<p>I have a table "Images" with two fields:</p> <ul> <li>Name VARCHAR2</li> <li>Data BLOB</li> </ul> <p>I would like to export that table to a .sql file which I could import on another system. I tried to do so using the "Database unload" assistant of Oracle SQL Developer. However the generated file does just have the content for the names in it but not the data. Thus after importing I would end up with all the names but the data field would be null everywhere.</p> <p>I'd really prefer it just to be one file (I saw some examples that included dumping the data to one file per field on the fs...)</p> <p>Is it possible to generate such a script with SQL Developer? or is there any other way/tool to do so?</p>
13,532,301
5
1
null
2012-11-23 15:03:00.63 UTC
4
2020-05-19 14:24:10.123 UTC
null
null
null
null
685,428
null
1
14
oracle|export|blob|oracle-sqldeveloper
50,048
<p>I don't think this is possible with SQL Developer (but then I don't use it very often).</p> <p>The SQL client I am using - <a href="http://www.sql-workbench.eu" rel="nofollow noreferrer">SQL Workbench/J</a> - can do this. </p> <p>There are several ways to export this data. </p> <h3>Generate a proprietary script</h3> <p>It can create a SQL script that uses a special (tool specific) notation to reference an external file, something like:</p> <pre><code>INSERT INTO images (name, data) VALUES ('foobar', {$blobfile='blob_r1_c2.data'}); </code></pre> <p>The above statement can only be executed with SQL Workbench again. It is not compatible with any other SQL client.</p> <h3>Use utl_raw</h3> <p>Another alternative is to use a "blob literal", but due to Oracle's limit on 4000 bytes for a character literal, this only works for <strong><em>really</em></strong> small blob values:</p> <pre><code>INSERT INTO images (name, data) VALUES ('foobar', to_blob(utl_raw.cast_to_raw('......'))); </code></pre> <p>where the character literal for the <code>cast_to_raw</code> call would contain the hex values of the BLOB. As this requires 2 characters per "blob byte", you can't handle BLOBs larger than 2000 bytes with that. But that syntax would work for nearly all Oracle SQL tools (if they can handle scripts with very long lines).</p> <h3>SQL*Loader input file</h3> <p>The third alternative is to export the data into a text file that can be imported using SQL*Loader:</p> <p>The text file would contain something like this:</p> <pre> NAME DATA foobar blob_r1_c2.data </pre> <p>Together with the following SQL*Loader control file:</p> <pre> OPTIONS (skip=1) LOAD DATA CHARACTERSET 'WE8ISO8859P15' INFILE 'images.txt' APPEND INTO TABLE IMAGES FIELDS TERMINATED BY '\t' TRAILING NULLCOLS ( NAME, lob_file_data FILLER, DATA LOBFILE(lob_file_data) TERMINATED BY EOF ) </pre> <p>This can be loaded using SQL*Loader and is thus doesn't need SQL Workbench to import the data.</p> <p>More details are in <a href="http://www.sql-workbench.eu/manual/command-export.html" rel="nofollow noreferrer">the manual</a></p> <p><strong>Edit</strong></p> <p>As Alex has pointed out in his comment, you can also use a DataPump export - but that requires that you have access to the file system on the server. The above solutions all store the data on the client.</p>
13,666,346
from sys import argv - what is the function of "script"
<p>I am reading "Learn Python the Hard Way" and was confused by the "script" part of the second line.</p> <pre><code>from sys import argv script, filename = argv </code></pre> <p>From what I understand, the second line says: <code>script</code> and <code>filename</code> comprise <code>argv</code>. I tried running my code without the "script" part and it worked just fine. I'm not sure what the purpose of it is.</p>
13,666,377
4
2
null
2012-12-02 04:15:33.85 UTC
6
2017-08-27 20:34:32.577 UTC
2012-12-02 04:26:16.907 UTC
null
374,866
null
1,869,775
null
1
15
python|argv
44,407
<p>Generally, the first argument to a command-line executable is the script name, and the rest are the expected arguments.</p> <p>Here, <code>argv</code> is a list that is expected to contain two values: the script name and an argument. Using Python's unpacking notation, you can write</p> <pre><code>script = argv[0] filename = argv[1] </code></pre> <p>as</p> <pre><code>script, filename = argv </code></pre> <p>while also throwing errors if there are an unexpected number of arguments (like one or three). This can be a good idea, depending on one's code, because it also ensures that there are no unexpected arguments.</p> <p>However, the following code will not result in <code>filename</code> actually containing the filename:</p> <pre><code>filename = argv </code></pre> <p>This is because <code>filename</code> is now the argument list. To illustrate:</p> <pre><code>script, filename = argv print("Script:", script) # Prints script name print("Filename:", filename) # Prints the first argument filename = argv print("Filname:", filename) # Prints something like ["my-script.py", "my-file.txt"] </code></pre>
13,786,083
Create two threads, one display odd & other even numbers
<p>I'm trying to create two threads, one thread display even integers from 0 to 10, one thread display odd integers from 1 to 11. Is the following code suitable for designing this program?</p> <pre><code>public class Mythread { public static void main(String[] args) { Runnable r = new Runnable1(); Thread t = new Thread(r); t.start(); Runnable r2 = new Runnable2(); Thread t2 = new Thread(r2); t2.start(); } } class Runnable2 implements Runnable{ public void run(){ for(int i=0;i&lt;11;i++){ if(i%2 == 1) System.out.println(i); } } } class Runnable1 implements Runnable{ public void run(){ for(int i=0;i&lt;11;i++){ if(i%2 == 0) System.out.println(i); } } } </code></pre>
13,786,175
21
3
null
2012-12-09 09:07:45.767 UTC
10
2021-07-03 16:26:47.56 UTC
2012-12-09 09:10:02.537 UTC
null
418,556
null
1,679,519
null
1
22
java|multithreading
127,730
<p>I would just change a few details (no need to use the modulo operator here...):</p> <pre><code>public class Mythread { public static void main(String[] args) { Runnable r = new Runnable1(); Thread t = new Thread(r); Runnable r2 = new Runnable2(); Thread t2 = new Thread(r2); t.start(); t2.start(); } } class Runnable2 implements Runnable{ public void run(){ for(int i=0;i&lt;11;i+=2) { System.out.println(i); } } } class Runnable1 implements Runnable{ public void run(){ for(int i=1;i&lt;=11;i+=2) { System.out.println(i); } } } </code></pre>
13,235,317
Using a XML File (log4j2.xml) to configure Log4j 2
<p>I want to use the new Log4J 2 - Java Logging Framework. Everything work fine, but I tried since a hour to load a custom configuration file to configure the logging (like log level).</p> <p>This is my log4j2.xml:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;configuration status="OFF"&gt; &lt;appenders&gt; &lt;Console name="Console" target="SYSTEM_OUT"&gt; &lt;PatternLayout pattern="%d{HH:mm:ss} [%t] %-5level %logger{36} - %msg%n"/&gt; &lt;/Console&gt; &lt;/appenders&gt; &lt;loggers&gt; &lt;root level="error"&gt; &lt;appender-ref ref="Console"/&gt; &lt;/root&gt; &lt;/loggers&gt; &lt;/configuration&gt; </code></pre> <p>I tried the following, but nothing works:</p> <ul> <li>Move the log4j2.xml file so it's located in the default package.</li> <li>Move the log4j2.xml file anywhere in the project</li> <li>Name the log4j2.xml file as "log4j.xml" </li> <li>Create a folder in your project, place your log4j2.xml file there and add that folder to your runtime classpath</li> </ul> <p>Since the <a href="http://logging.apache.org/log4j/2.x/" rel="noreferrer">official website</a> can't help me, I hope you can help me get Log4j 2 working with my configuration file.</p>
13,235,751
7
1
null
2012-11-05 15:34:53.233 UTC
10
2019-04-05 20:50:54.71 UTC
2013-06-06 17:56:02.487 UTC
null
542,517
null
3,597,614
null
1
27
java|eclipse|log4j
57,345
<p><strong>Important:</strong> make sure the name of the configuration file is <code>log4j2.xml</code> (note the <code>2</code> before the period) as opposed to <code>log4j.xml</code></p> <p>My guess is nothing's happening because nothing is logged using the error level. You may want to try adding another logger like so:</p> <pre><code>&lt;logger name="com.foo.Bar" level="trace"&gt; &lt;appender-ref ref="Console"/&gt; &lt;/logger&gt; </code></pre> <p>Looks like the <a href="http://logging.apache.org/log4j/2.x/manual/configuration.html">Configuration</a> section might be a good resource.</p> <p>To elaborate further, you're specifying a logger with the level set to "error":</p> <pre><code>&lt;root level="error"&gt; &lt;appender-ref ref="Console"/&gt; &lt;/root&gt; </code></pre> <p>This means that only the messages logged using Level.ERROR will show up in the log. Adding a logger with a less restrictive level will allow for more messages to appear in the log. I recommend taking a look at the <a href="https://logging.apache.org/log4j/2.x/manual/architecture.html">Architecture</a> section of the manual (if you scroll down the page you'll see the table that explains logging levels). Alternatively, you could just change the level of the root logger to trace (instead of adding a new logger)</p> <p>Given the configuration you specified, executing the code below yields something like <code>13:27:50.244 [main] ERROR com.example.Log4j2Tester - testing ERROR level</code></p> <pre><code>package com.example; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class Log4j2Tester { private static final Logger LOG = LogManager.getLogger(Log4j2Tester.class); public static void main(String[] args) { LOG.error("testing ERROR level"); //if you change the level of root logger to 'trace' //then you'll also see something like // 13:27:50.244 [main] TRACE com.example.Log4j2Tester - exiting application LOG.trace("exiting application"); } } </code></pre>
13,661,788
How to set minimum DatePicker date to current date
<p>I want to set the minimum date the user can choose in a DatePicker to the current date. I've tried this:</p> <pre><code>DatePicker datePicker = (DatePicker) findViewById(R.id.event_date); datePicker.setMinDate(System.currentTimeMillis()); </code></pre> <p>That gives me the following exception:</p> <pre><code>12-01 12:23:31.226: E/AndroidRuntime(10311): Caused by: java.lang.IllegalArgumentException: fromDate: Sat Dec 01 12:23:31 EST 2012 does not precede toDate: Sat Dec 01 12:23:31 EST 2012 </code></pre> <p>How do I do this?</p>
13,661,947
11
0
null
2012-12-01 17:26:33.68 UTC
14
2022-03-21 18:15:16.307 UTC
null
null
null
null
803,801
null
1
60
android|android-datepicker
88,907
<p>The error says you cannot set the minimum date to <em>exactly</em> now. Try subtracting a second:</p> <pre><code>datePicker.setMinDate(System.currentTimeMillis() - 1000); </code></pre> <hr> <p>From the source code the minimum date must be before, not equal to, the current date:</p> <pre><code>if (date.before(mMinDate)) { throw new IllegalArgumentException("fromDate: " + mMinDate.getTime() + " does not precede toDate: " + date.getTime()); } </code></pre> <p>So you simply need to subtract enough time from now (<code>System.currentTimeMillis()</code>) pass <code>date.before(mMinDate)</code>.</p>
20,821,465
How do you create a UIImageView programmatically in Xcode
<p>I just want to make an UIImageView programmatically that displays a 20by20 dot at point (50,50).(The image of the dot is called draw.png). For some reason nothing shows up on the screen.</p> <p>Heres my code:</p> <pre><code>- (void)viewDidLoad { UIImageView *dot =[[UIImageView alloc] initWithFrame:CGRectMake(50,50,20,20)]; dot.image=[UIImage imageNamed:@"draw.png"]; [self.view addSubview:dot]; [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib } </code></pre>
20,844,677
6
3
null
2013-12-29 02:11:44.613 UTC
4
2018-04-02 12:13:38.13 UTC
2013-12-30 17:43:37.003 UTC
null
3,143,098
null
3,143,098
null
1
16
xcode|uiimageview
58,496
<p>First, make sure draw.png exists in your project and that you are referencing it exactly (so if it's draw.PNG you should put <code>@"draw.PNG"</code>). Also, call <code>[super viewDidLoad]</code> before everything.</p> <pre><code>- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib UIImageView *dot =[[UIImageView alloc] initWithFrame:CGRectMake(50,50,20,20)]; dot.image=[UIImage imageNamed:@"draw.png"]; [self.view addSubview:dot]; } </code></pre>
24,152,925
Using JQuery to set CSS Keyframe
<p>I'm trying to determine the height of a <code>div</code> which is dynamic depending on the size of the text. I was trying to set this dynamically within the CSS as my original question <a href="https://stackoverflow.com/questions/24150538/defining-a-height-in-css-for-animation-keyframe-within-itself?noredirect=1#comment37269329_24150538">https://stackoverflow.com/questions/24150538/defining-a-height-in-css-for-animation-keyframe-within-itself?noredirect=1#comment37269329_24150538</a>. </p> <p>I have now seem that there is a JQuery that may enable you to do so at <a href="https://github.com/jQueryKeyframes/jQuery.Keyframes" rel="noreferrer">https://github.com/jQueryKeyframes/jQuery.Keyframes</a>. So I've followed their example and removed the <code>keyframe</code> in my <code>CSS</code> file and included it in the script as in the below code fragment:</p> <pre><code>&lt;body&gt; &lt;script src="http://code.jquery.com/jquery-latest.js"&gt;&lt;/script&gt; &lt;script src="/pathToFile/jquery.keyframes.min.js"&gt;&lt;/script&gt; &lt;div id="test"&gt; hello&lt;/div&gt; &lt;script&gt; var supportedFlag = $.keyframe.isSupported(); $.keyframe.define([{ name: 'myfirst', '0%': {top:$("#test").innerHeight()*-1; left:0px}, '50%': {top:100%; left:0px}, '100%': {top:$("#test").innerHeight()*-1; left:0px} }]); $(selector).playKeyframe({ name: 'myfirst', // name of the keyframe you want to bind to the selected element duration: 90, // [optional, default: 0, in ms] how long you want it to last in milliseconds timingFunction: 'linear', // [optional, default: ease] specifies the speed curve of the animation delay: 0, //[optional, default: 0, in ms] how long you want to wait before the animation starts in milliseconds, default value is 0 repeat: 'infinite', //[optional, default:1] how many times you want the animation to repeat, default value is 1 direction: 'alternate', //[optional, default: 'normal'] which direction you want the frames to flow, default value is normal fillMode: 'running', //[optional, default: 'forward'] how to apply the styles outside the animation time, default value is forwards complete: function(){} //[optional] Function fired after the animation is complete. If repeat is infinite, the function will be fired every time the animation is restarted. }); &lt;/script&gt; &lt;/body&gt; </code></pre> <p></p> <p>My CSS:</p> <pre><code>#test{ height: auto; width: 100%; position: relative; } </code></pre> <p>I would like to know why this isn't working.</p>
24,152,989
2
2
null
2014-06-11 00:29:50.793 UTC
5
2017-03-01 15:04:08.773 UTC
2017-05-23 12:17:08.46 UTC
null
-1
null
1,742,006
null
1
13
javascript|jquery|css
43,979
<p>The SyntaxError is being caused by your semicolon-delimited javascript objects here:</p> <pre><code>'0%': {top:$("#test").innerHeight()*-1; left:0px}, '50%': {top:100%; left:0px}, '100%': {top:$("#test").innerHeight()*-1; left:0px} </code></pre> <p>Replace your semicolons with commas inside the objects:</p> <pre><code>'0%': {top:$("#test").innerHeight()*-1, left:0}, '50%': {top:"100%", left:0}, '100%': {top:$("#test").innerHeight()*-1, left:0} </code></pre> <p>That will fix the syntax error.</p> <p>EDIT: In addition, your values for <code>left</code> need to be changed from <code>0px</code> to <code>0</code> or <code>"0px"</code>, as <code>0px</code> by itself is not valid syntax.</p> <p>EDIT 2: I played around a bit with this <a href="http://jsfiddle.net/7P9yY/2/">http://jsfiddle.net/7P9yY/2/</a> and got it to work close to what I believe you're asking.</p> <p>The keyframe is defined as:</p> <pre><code>$.keyframe.define([{ name: 'myfirst', '0%': {top:"0px"}, '50%': {top:$("#testcontainer").innerHeight() + "px"}, '100%': {top:"0px"} }]); </code></pre> <p>This keyframe defines a motion starting at the top of the page (you can change this to be the top of the div if you need), down to the bottom, and back up to the top. Fire the animation with:</p> <pre><code>$("#test").playKeyframe({ name: 'myfirst', duration: 2000 }); </code></pre> <p>HTML (example):</p> <pre><code>&lt;div id="testcontainer"&gt; &lt;div id="test"&gt;hello&lt;/div&gt; &lt;/div&gt; </code></pre> <p>CSS (example):</p> <pre><code>#test { position: absolute; } #testcontainer { position: relative; background: pink; width: 300px; height: 300px; } </code></pre> <p>Hopefully that helps a little bit.</p>
3,763,735
Rails Mailer: sending emails to a local file
<p>Is there any way to send emails in rails 3 to a local file or so, instead of using an SMTP server? I'd like to test the email's contents without using any kind of SMTP, ideally only in DEV environment.</p> <p>The best would be a local SMTP or something that allowed me to inspect emails, check email addresses, etc.</p>
3,763,802
2
0
null
2010-09-21 19:28:00.5 UTC
11
2014-01-15 15:57:34.203 UTC
null
null
null
null
22,992
null
1
16
ruby-on-rails|email
8,853
<p>You can use the :test system delivery</p> <pre><code>ActionMailer::Base.delivery_method = :test </code></pre> <p>There are also a :file delivery_method</p> <pre><code>ActionMailer::Base.delivery_method = :file </code></pre> <p>You can define where put all email with file_settings</p> <pre><code>ActionMailer::Base.file_settings = { :location =&gt; Rails.root.join('tmp/mail') } </code></pre>
3,243,743
Eclipse: Files opened by multiple searches using same editor tab
<p>When using the "file search" function in eclipse to find a bit of text in a ".java" file, I may get a list of several search results. Let's say I double click on the file "A.java" which then opens A.java in a new editor tab. If I then use the "file search" function again to find some other bit of text and this time double click on the file "B.java", this file will replace "A.java" in the editor. </p> <p>I'd like Eclipse to open a new editor for B.java so that both A.java and B.java are available in my editor tabs. Is this possible? I've had a look around in the preferences but I'm not sure what option would give me this bit of functionality.</p>
3,243,806
2
1
null
2010-07-14 06:06:49.183 UTC
21
2013-11-12 22:43:36.867 UTC
2013-11-12 22:43:36.867 UTC
null
30,563
null
30,563
null
1
133
eclipse|search
24,887
<p>Disable the option</p> <p>Preferences > General > Search > Reuse editors to show matches</p>
9,074,556
Why use object.prototype.constructor in OOP javascript?
<p>I've recently started reading up on OOP javascript and one thing that authors seem to skip over is when an object A has been declared and suddenly I see "A.prototype.constructor =A; For example, </p> <pre><code>var A = function(){}; // This is the constructor of "A" A.prototype.constructor = A; A.prototype.value = 1; A.prototype.test = function() { alert(this.value); } var a = new A(); // create an instance of A alert(a.value); // =&gt; 1 </code></pre> <p>So I run the command in firebug "var A = function(){};" and then "A.Constructor" Which reveals it's a function. I understand this.<br> I run the code "A.prototype.constructor = A;" and I thought this changes the A constructor from Function to A. </p> <p>The constructor property of A has been changed right? Instead when I run "A.constructor" it gives me function () still. </p> <p>What's the point? </p> <p>I also see A.constructor.prototype.constructor.prototype.. what is going on? </p>
9,074,696
5
2
null
2012-01-31 04:50:33.163 UTC
17
2015-07-02 05:13:54.403 UTC
2015-03-29 19:44:15.157 UTC
null
104,085
null
672,178
null
1
22
javascript|oop
8,500
<p>If A inherit B using <code>A.prototype = new B();</code>, you need to reset the constructor property for the class A using <code>A.prototype.constructor=A;</code>, otherwise instances of A would have a constructor of B.</p> <p>In your case, <code>A.prototype.constructor === A</code> will return true, so <code>A.prototype.constructor = A</code> did nothing.</p>
29,803,045
How to clear an angularJS array
<pre><code> $scope.itemarray = ['A', 'B', 'C']; </code></pre> <p>this will clear the array but the ui wont be updated.</p> <pre><code>$scope.itemarray = []; </code></pre> <p>this works fine! why?</p> <pre><code> $scope.itemarray.length = 0; </code></pre>
29,803,364
1
3
null
2015-04-22 16:02:14.76 UTC
5
2019-06-18 09:21:02.89 UTC
2019-06-18 09:21:02.89 UTC
null
4,154,643
null
1,164,901
null
1
60
javascript|angularjs
90,991
<p><code>$scope.itemarray.length = 0;</code> &lt;&lt; this is correct. Length is read-write property.</p> <p><code>$scope.itemarray = [];</code> &lt;&lt; this creates new empty array. If you have bindings to old itemarray, they may be lost. (Html binding like <code>ng-if="itemarray[0]"</code> wont be lost)</p>
29,661,574
Normalize numpy array columns in python
<p>I have a numpy array where each cell of a specific row represents a value for a feature. I store all of them in an 100*4 matrix.</p> <pre><code>A B C 1000 10 0.5 765 5 0.35 800 7 0.09 </code></pre> <p>Any idea how I can normalize rows of this numpy.array where each value is between 0 and 1?</p> <p>My desired output is:</p> <pre><code>A B C 1 1 1 0.765 0.5 0.7 0.8 0.7 0.18(which is 0.09/0.5) </code></pre> <p>Thanks in advance :)</p>
29,661,707
2
3
null
2015-04-15 21:51:13.89 UTC
16
2017-05-30 08:45:20.1 UTC
2015-04-15 21:58:59.967 UTC
null
2,827,771
null
2,827,771
null
1
61
python|numpy|normalize
132,297
<p>If I understand correctly, what you want to do is divide by the maximum value in each column. You can do this easily using <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="noreferrer">broadcasting</a>.</p> <p>Starting with your example array:</p> <pre><code>import numpy as np x = np.array([[1000, 10, 0.5], [ 765, 5, 0.35], [ 800, 7, 0.09]]) x_normed = x / x.max(axis=0) print(x_normed) # [[ 1. 1. 1. ] # [ 0.765 0.5 0.7 ] # [ 0.8 0.7 0.18 ]] </code></pre> <p><code>x.max(0)</code> takes the maximum over the 0th dimension (i.e. rows). This gives you a vector of size <code>(ncols,)</code> containing the maximum value in each column. You can then divide <code>x</code> by this vector in order to normalize your values such that the maximum value in each column will be scaled to 1.</p> <hr> <p>If <code>x</code> contains negative values you would need to subtract the minimum first:</p> <pre><code>x_normed = (x - x.min(0)) / x.ptp(0) </code></pre> <p>Here, <code>x.ptp(0)</code> returns the "peak-to-peak" (i.e. the range, max - min) along axis 0. This normalization also guarantees that the minimum value in each column will be 0.</p>
16,150,152
Secure FTP using Windows batch script
<p>I currently have batch scripts on different servers that transfer a csv file to an FTP server at a different location. My script looks similar to this:</p> <pre><code>echo user ftp_user&gt; ftpcmd.dat echo password&gt;&gt; ftpcmd.dat echo put c:\directory\%1-export-%date%.csv&gt;&gt; ftpcmd.dat echo quit&gt;&gt; ftpcmd.dat ftp -n -s:ftpcmd.dat ftp.MyFTPSite.com del ftpcmd.dat </code></pre> <p>If I wanted to require a secure transmission, is how would my script be updated?</p> <p>Thanks.</p>
16,151,814
3
0
null
2013-04-22 14:53:22.233 UTC
9
2022-09-07 16:48:52 UTC
2016-10-19 05:42:00.363 UTC
null
850,848
null
862,132
null
1
20
windows|batch-file|ftp|sftp
143,390
<p>First, make sure you understand, if you need to use <a href="https://en.wikipedia.org/wiki/FTPS" rel="nofollow noreferrer">Secure FTP</a> (=FTPS, as per your text) or <a href="https://en.wikipedia.org/wiki/SSH_File_Transfer_Protocol" rel="nofollow noreferrer">SFTP</a> (as per tag you have used).</p> <p>Neither is supported by Windows command-line <code>ftp.exe</code>. As you have suggested, you can use <a href="https://winscp.net/" rel="nofollow noreferrer">WinSCP</a>. It supports both FTPS and SFTP.</p> <p>Using WinSCP, your batch file would look like (for SFTP):</p> <pre><code>echo open sftp://ftp_user:[email protected] -hostkey=&quot;...&quot; &gt;&gt; ftpcmd.dat echo put c:\directory\%1-export-%date%.csv &gt;&gt; ftpcmd.dat echo exit &gt;&gt; ftpcmd.dat winscp.com /script=ftpcmd.dat del ftpcmd.dat </code></pre> <p>And the batch file:</p> <pre><code>winscp.com /log=ftpcmd.log /script=ftpcmd.dat /parameter %1 %date% </code></pre> <hr /> <p>Though using all capabilities of WinSCP (particularly <a href="https://winscp.net/eng/docs/commandline#scripting" rel="nofollow noreferrer">providing commands directly on command-line</a> and the <a href="https://winscp.net/eng/docs/scripting#timestamp" rel="nofollow noreferrer"><code>%TIMESTAMP%</code> syntax</a>), the batch file simplifies to:</p> <pre><code>winscp.com /log=ftpcmd.log /command ^ &quot;open sftp://ftp_user:[email protected] -hostkey=&quot;&quot;...&quot;&quot;&quot; ^ &quot;put c:\directory\%1-export-%%TIMESTAMP#yyyymmdd%%.csv&quot; ^ &quot;exit&quot; </code></pre> <p>For the purpose of <code>-hostkey</code> switch, see <a href="https://winscp.net/eng/docs/scripting#hostkey" rel="nofollow noreferrer">verifying the host key in script</a>.</p> <p>Easier than assembling the script/batch file manually is to setup and test the connection settings in WinSCP GUI and then have it <a href="https://winscp.net/eng/docs/guide_automation#generating" rel="nofollow noreferrer">generate the script or batch file for you</a>:</p> <p><a href="https://i.stack.imgur.com/2zI7t.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2zI7t.png" alt="Generate batch file" /></a></p> <p>All you need to tweak is the source file name (use the <code>%TIMESTAMP%</code> syntax as shown previously) and the path to the log file.</p> <hr /> <p>For FTPS, replace the <code>sftp://</code> in the <a href="https://winscp.net/eng/docs/scriptcommand_open" rel="nofollow noreferrer"><code>open</code> command</a> with <code>ftpes://</code> (<a href="https://winscp.net/eng/docs/ftps#methods" rel="nofollow noreferrer">explicit TLS/SSL</a>) or <code>ftps://</code> (<a href="https://winscp.net/eng/docs/ftps#methods" rel="nofollow noreferrer">implicit TLS/SSL</a>). And remove the <code>-hostkey</code> switch.</p> <pre><code>winscp.com /log=ftpcmd.log /command ^ &quot;open ftps://ftp_user:[email protected] -explicit&quot; ^ &quot;put c:\directory\%1-export-%%TIMESTAMP#yyyymmdd%%.csv&quot; ^ &quot;exit&quot; </code></pre> <p>You may need to add the <code>-certificate</code> switch, if your server's certificate is <a href="https://winscp.net/eng/docs/scripting#hostkey" rel="nofollow noreferrer">not issued by a trusted authority</a>.</p> <p>Again, as with the SFTP, easier is to setup and test the connection settings in WinSCP GUI and then have it <a href="https://winscp.net/eng/docs/guide_automation#generating" rel="nofollow noreferrer">generate the script or batch file for you</a>.</p> <hr /> <p>See a complete <a href="https://winscp.net/eng/docs/guide_ftp_script_to_sftp" rel="nofollow noreferrer">conversion guide from <code>ftp.exe</code> to WinSCP</a>.</p> <p>You should also read the <a href="https://winscp.net/eng/docs/guide_automation" rel="nofollow noreferrer">Guide to automating file transfers to FTP server or SFTP server</a>.</p> <hr /> <p>Note to using <code>%TIMESTAMP#yyyymmdd%</code> instead of <code>%date%</code>: A format of <code>%date%</code> variable value is locale-specific. So make sure you test the script on the same locale you are actually going to use the script on. For example on my Czech locale the <code>%date%</code> resolves to <code>čt 06. 11. 2014</code>, what might be problematic when used as a part of a file name.</p> <p>For this reason WinSCP supports <a href="https://winscp.net/eng/docs/scripting#timestamp" rel="nofollow noreferrer">(locale-neutral) timestamp formatting natively</a>. For example <code>%TIMESTAMP#yyyymmdd%</code> resolves to <code>20170515</code> on any locale.</p> <p><em>(I'm the author of WinSCP)</em></p>
16,144,455
Mocha tests with extra options or parameters
<p>I am writing test cases for my Node.js application using Mocha. The test cases need an API key as an extra input option or parameter. The API key is private, so I don't want to include it directly in the test files as everyone then can see it on GitHub. I know there are some options available for Mocha at:</p> <p><a href="http://mochajs.org/#usage">http://mochajs.org/#usage</a></p> <p>But is it possible to include some parameters to let testers specify their own API key for the test in the commandline? Such as:</p> <pre><code>./node_modules/mocha/bin/mocha test/*.js --key YOUR_KEY </code></pre>
16,145,019
10
0
null
2013-04-22 10:08:11.22 UTC
16
2020-07-31 08:10:25.917 UTC
2015-06-30 16:00:13.317 UTC
null
1,480,391
null
1,472,418
null
1
94
node.js|mocha.js
89,708
<p>I don't think Mocha itself supports passing extra parameters to your tests, but you could use environment variables:</p> <pre><code>env KEY=YOUR_KEY mocha test/*.js # assumes some sort of Unix-type OS. </code></pre> <p>And read them in your test files:</p> <pre><code>var key = process.env.KEY; </code></pre>
29,092,193
NodeJS Count how many objects in array?
<p>How would I count how many objects there are inside an array?</p> <p>The array looking like:</p> <pre><code>[ {id: 1}, {id: 2}, ...] </code></pre> <p>I assume I could use count() if it was PHP, but what about NodeJS/Javascript?</p> <p>Edit: </p> <p><img src="https://i.stack.imgur.com/G9TxO.png" alt="asd"></p> <pre><code>if (offer.items_to_receive.length &gt; 0) { console.log("items: " + offer.items_to_receive.length); for(var i = 0; i &lt; offer.items_to_receive.length; i++) { usersInRound.push(offer.steamid_other); } } logData('Accepted trade offer from ' + offer.steamid_other + '. (tradeofferid: ' + offer.tradeofferid + ')\nWorth ' + offer.items_to_receive.length + ' tickets. '); </code></pre> <p>How come it can read the "worth X tickets", but not the other part?</p>
29,092,219
3
6
null
2015-03-17 05:53:33.06 UTC
1
2015-06-24 07:01:18.357 UTC
2015-06-24 07:01:18.357 UTC
null
463,059
null
2,805,114
null
1
11
javascript|node.js
51,622
<p>Use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length" rel="noreferrer"><code>.length</code></a></p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var data = [{ id: 1 }, { id: 2 }]; console.log(data.length);</code></pre> </div> </div> </p> <p><strong>Update</strong>, in your edit I see that </p> <p><code>offer.items_to_receive</code> is <code>undefined</code>, ensure that object <code>offer</code> has property <code>items_to_receive</code> (should be array);</p>
29,219,688
Present modal view controller in half size parent controller
<p>I am trying to present modal view controller on other viewcontroller sized to half parent view controller. But it always present in full screen view.</p> <p>I have created freeform sized View controller in my storyboard with fixed frame size. 320 X 250.</p> <pre><code>var storyboard = UIStoryboard(name: "Main", bundle: nil) var pvc = storyboard.instantiateViewControllerWithIdentifier("CustomTableViewController") as ProductsTableViewController self.presentViewController(pvc, animated: true, completion: nil) </code></pre> <p>I have tried to set frame.superview and it doesn't help.</p> <p><img src="https://i.stack.imgur.com/VXlSF.png" alt="Picture example"></p> <p>Please advice.</p>
29,220,983
10
7
null
2015-03-23 20:25:35.247 UTC
34
2021-10-03 12:46:02.963 UTC
2017-09-25 00:49:48.357 UTC
null
2,114,482
null
2,263,359
null
1
53
ios|swift|uiviewcontroller|presentmodalviewcontroller
81,556
<p>You can use a <code>UIPresentationController</code> to achieve this.</p> <p>For this you let the presenting <code>ViewController</code> implement the <code>UIViewControllerTransitioningDelegate</code> and return your <code>PresentationController</code> for the half sized presentation:</p> <pre class="lang-swift prettyprint-override"><code>func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -&gt; UIPresentationController? { return HalfSizePresentationController(presentedViewController: presented, presenting: presentingViewController) } </code></pre> <p>When presenting you set the presentation style to <code>.Custom</code> and set your transitioning delegate:</p> <pre class="lang-swift prettyprint-override"><code>pvc.modalPresentationStyle = .custom pvc.transitioningDelegate = self </code></pre> <p>The presentation controller only returns the frame for your presented view controller:</p> <pre class="lang-swift prettyprint-override"><code>class HalfSizePresentationController: UIPresentationController { override var frameOfPresentedViewInContainerView: CGRect { guard let bounds = containerView?.bounds else { return .zero } return CGRect(x: 0, y: bounds.height / 2, width: bounds.width, height: bounds.height / 2) } } </code></pre> <p>Here is the working code in its entirety:</p> <pre class="lang-swift prettyprint-override"><code>class ViewController: UIViewController, UIViewControllerTransitioningDelegate { @IBAction func tap(sender: AnyObject) { let storyboard = UIStoryboard(name: &quot;Main&quot;, bundle: nil) let pvc = storyboard.instantiateViewController(withIdentifier: &quot;CustomTableViewController&quot;) as! UITableViewController pvc.modalPresentationStyle = .custom pvc.transitioningDelegate = self pvc.view.backgroundColor = .red present(pvc, animated: true) } func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -&gt; UIPresentationController? { return HalfSizePresentationController(presentedViewController: presented, presenting: presentingViewController) } } class HalfSizePresentationController: UIPresentationController { override var frameOfPresentedViewInContainerView: CGRect { guard let bounds = containerView?.bounds else { return .zero } return CGRect(x: 0, y: bounds.height / 2, width: bounds.width, height: bounds.height / 2) } } </code></pre>
29,299,206
PHPUnit - 'No tests executed' when using configuration file
<h1>The Problem</h1> <p>To improve my quality of code, I've decided to try to learn how to test my code using Unit Testing instead of my mediocre-at-best testing solutions.</p> <p>I decided to install PHPUnit using composer for a personal library that allows me to achieve common database functions. At first I didn't have a configuration file for PHPUnit and when I ran commands like:</p> <pre><code>$ phpunit tests/GeneralStringFunctions/GeneralStringFunctionsTest </code></pre> <p>Please note that this is a terminal command, so I didn't include the <code>.php</code> extension. The GeneralStringFunctionsTest referred to above is actually a <code>GeneralStringFunctionsTest.php</code> file.</p> <p>The output is what I expected:</p> <blockquote> <p>Time: 31 ms, Memory: 2.75Mb</p> <p>OK (1 test, 1 assertion)</p> </blockquote> <p>I then tried to use a configuration file to automatically load the test suite instead of having to manually type in the file every time. I created a file called <code>phpunit.xml</code> in my root directory, and entered the following into the file: <a href="http://pastebin.com/0j0L4WBD">http://pastebin.com/0j0L4WBD</a>:</p> <pre><code>&lt;?xml version = "1.0" encoding="UTF-8" ?&gt; &lt;phpunit&gt; &lt;testsuites&gt; &lt;testsuite name="Tests"&gt; &lt;directory&gt;tests&lt;/directory&gt; &lt;/testsuite&gt; &lt;/testsuites&gt; &lt;/phpunit&gt; </code></pre> <p>Now, when I run the command:</p> <pre><code>phpunit </code></pre> <p>I get the following output:</p> <blockquote> <p>PHPUnit 4.5.0 by Sebastian Bergmann and contributors.</p> <p>Configuration read from /Users/muyiwa/Projects/DatabaseHelper/phpunit.xml</p> <p>Time: 16 ms, Memory: 1.50Mb</p> <p>No tests executed!</p> </blockquote> <p>In case it's helpful, my directory structure is as follows:<br> src - Top level directory (with all my source code)<br> tests - Top level directory (with all my tests, structured the same as my <em>src</em> folder)<br> vendor - Composer third party files </p> <p>I also have the composer json and lock file, as well as the phpunit xml file in the top level as files.</p> <h1>Things I've Tried</h1> <ul> <li>Changing the directory in <code>phpunit.xml</code> to <code>tests/GeneralStringFunctions</code></li> <li>Changing the directory in <code>phpunit.xml</code> to <code>./tests</code></li> <li>Moving the <code>phpunit.xml</code> file to the <code>tests</code> directory and then changing the directory to be <code>./</code> instead of <code>tests</code>.</li> <li>Adding a suffix attribute to the directory tag in <code>phpunit.xml</code> to specify "Tests" as the explicit suffix.</li> </ul>
42,260,682
28
8
null
2015-03-27 11:03:49.997 UTC
12
2022-04-13 12:15:06.823 UTC
2016-01-15 18:14:09.41 UTC
null
2,678,454
user4165455
null
null
1
107
php|unit-testing|phpunit
68,915
<p>For what it's worth (being late), I ran into this recently while I was making a new Laravel 5.1 project for a simple website. I tried to debug it and was confused when I tried:</p> <pre><code>php artisan make:test homeTest </code></pre> <p>(which has a default test that just asserts true is true)</p> <p>and saw the output</p> <pre><code>No tests executed! </code></pre> <p>What the problem ended up being for me was related to my PHP installation -- "phpunit" was globally registered and configured differently, whereas the phpunit that came with the Laravel installation was configured just right and ran perfectly.</p> <p>So the fix is running the vendor's configured phpunit (from the same root directory as app/ and tests/):</p> <pre><code>./vendor/bin/phpunit </code></pre> <p>Hope that helps someone else!</p>
28,918,861
Is there a pre-defined built-in function to convert a number to its binary format in C++?
<pre><code>Integer.toString(n,8) // decimal to octal Integer.toString(n,2) // decimal to binary Integer.toString(n,16) //decimal to Hex </code></pre> <p>We have these functions in java ... do we have such built-in functions in c++</p>
28,919,045
4
12
null
2015-03-07 19:09:34.56 UTC
5
2021-04-22 04:06:39.48 UTC
2015-03-07 23:01:38.29 UTC
null
10,559
null
2,749,191
null
1
11
c++
41,905
<p>You can use <code>std::bitset</code> to convert a number to its binary format.</p> <p>Use the following code snippet: </p> <pre><code> std::string binary = std::bitset&lt;8&gt;(n).to_string(); </code></pre>
17,154,317
how to pass data in an hidden field from one jsp page to another?
<p>I have some data in an hidden field on a jsp page</p> <pre><code>&lt;input type=hidden id="thisField" name="inputName"&gt; </code></pre> <p>how to access or pass this field onsubmit to another page?</p>
17,155,121
2
0
null
2013-06-17 18:30:24.347 UTC
2
2015-12-16 19:54:37.417 UTC
null
null
null
null
2,415,379
null
1
5
jsp|hidden-field
117,288
<p>To pass the value you must included the hidden value <code>value="hiddenValue"</code> in the <code>&lt;input&gt;</code> statement like so:</p> <pre><code>&lt;input type="hidden" id="thisField" name="inputName" value="hiddenValue"&gt; </code></pre> <p>Then you recuperate the hidden form value in the same way that you recuperate the value of visible input fields, by accessing the parameter of the request object. Here is an example:</p> <p>This code goes on the page where you want to hide the value.</p> <pre><code>&lt;form action="anotherPage.jsp" method="GET"&gt; &lt;input type="hidden" id="thisField" name="inputName" value="hiddenValue"&gt; &lt;input type="submit"&gt; &lt;/form&gt; </code></pre> <p>Then on the 'anotherPage.jsp' page you recuperate the value by calling the <code>getParameter(String name)</code> method of the implicit <code>request</code> object, as so:</p> <pre><code>&lt;% String hidden = request.getParameter("inputName"); %&gt; The Hidden Value is &lt;%=hidden %&gt; </code></pre> <p>The output of the above script will be:</p> <pre><code>The Hidden Value is hiddenValue </code></pre>
21,733,228
Can RaspberryPi with BLE Dongle detect iBeacons?
<p>I bought a developer kit from <code>Radius Networks</code> that includes a <code>ioGear GBU521 BLE 4.0 dongle</code> and a <code>Raspberry Pi</code>. I also bought one of their <code>RadBeacon iBeacons</code>. They both work as advertised, but I was kind of surprised by what I got.</p> <p>I had assumed that the <code>RaspPi</code> could detect <code>iBeacons</code>. Instead, the kit is setup to <strong>create</strong> an <code>iBeacon</code>. My use case is to detect when a <code>forklift</code> enters a particular room so I can send work to them. My thought was to put an iBeacon on the forklift then put a RaspPi searching for iBeacons. And when an iBeacon (forklift) was detected, you could conclude that it is nearby. I would wire the RaspPi into the <code>LAN</code> and have it communicate the information via <code>REST or similar</code>. I know I could put a suitable <code>Android or Apple device</code> and accomplish it that way, but I don't see why this dongle can't detect these <code>iBeacons</code> and tell me what their <code>UUID's</code> are? What am I missing?</p>
21,790,504
3
5
null
2014-02-12 16:07:34.357 UTC
49
2015-04-30 13:00:06.627 UTC
2014-03-20 03:19:10.573 UTC
null
2,888,581
null
1,153,660
null
1
39
raspberry-pi|ibeacon
59,153
<p>Yes! You can use your Raspberry Pi to scan for iBeacons. We've put together a script below that does this, you can also do it yourself with these steps:</p> <ol> <li><p>Start a background process that does a bluetooth LE scan:</p> <pre><code>sudo hcitool lescan --duplicates &amp; </code></pre> <p>With the <code>--duplicates</code> setting the scan will not ignore multiple packets from the same iBeacon. </p></li> <li><p>Start an <code>hcidump</code> and pipe the raw output to a script that will filter for iBeacon packets:</p> <pre><code>sudo hcidump --raw </code></pre></li> </ol> <p>The filtering is the tricky part, the raw output from <code>hcidump</code> isn't formatted nicely and also shows packets that aren't iBeacon transmissions. To solve this, we made a filter script that reads in the output line by line and separates out the raw packets from the other output (i.e., MAC addresses, etc.). We've done a lot of research at Radius Networks on the <a href="https://stackoverflow.com/a/19040616/3100143">iBeacon bluetooth profile</a>, which we used to identify iBeacon packets and filter them out from packets from other devices. </p> <p>We've put this all together into an <code>ibeacon_scan</code> script that does everything, including converting the raw identifiers into human-readable form. You can download it <a href="http://developer.radiusnetworks.com/ibeacon/idk/ibeacon_scan" rel="noreferrer">here</a>. Soon, we'll include this in the <a href="http://www.radiusnetworks.com/ibeacon/ibeacon-dev-kit.html" rel="noreferrer">iBeacon Development Kit</a> to add scanning capability. </p> <p>Here's an example of the output from the script:</p> <pre><code>$ ./ibeacon_scan UUID: 74278BDA-B644-4520-8F0C-720EAF059935 MAJOR: 0 MINOR: 73 POWER: -50 UUID: 2F234454-CF6D-4A0F-ADF2-F4911BA9FFA6 MAJOR: 1 MINOR: 6 POWER: -59 UUID: E2C56DB5-DFFB-48D2-B060-D0F5A71096E0 MAJOR: 6 MINOR: 9 POWER: -55 </code></pre> <p>We've also included a <code>-b</code> option for bare output that is easy to parse into other scripts, here's an example:</p> <pre><code>$ ./ibeacon_scan -b 2F234454-CF6D-4A0F-ADF2-F4911BA9FFA6 1 6 -59 E2C56DB5-DFFB-48D2-B060-D0F5A71096E0 6 9 -55 74278BDA-B644-4520-8F0C-720EAF059935 0 73 -50 </code></pre> <p>You can use this option and pipe the script's output to your script to trigger actions when iBeacons with certain identifiers are detected.</p> <p><strong>EDIT:</strong> We've reworked this script to make it more responsive and robust and incorporated it into the latest version of the <a href="http://www.radiusnetworks.com/ibeacon/ibeacon-dev-kit.html" rel="noreferrer">development kit</a>. The update is available to download <a href="http://developer.radiusnetworks.com/ibeacon/beacon-dev-kit-update.html" rel="noreferrer">here</a>.</p> <p><strong>EDIT2:</strong> As pointed out by <a href="https://stackoverflow.com/users/2036432/sai-ramachandran">@sai-ramachandran</a>, you can augment this script to capture the RSSI of each iBeacon packet in addition to POWER. To do this, add the following lines to the script:</p> <pre><code> RSSI=`echo $packet | sed 's/^.\{132\}\(.\{2\}\).*$/\1/'` RSSI=`echo "ibase=16; $RSSI" | bc` RSSI=$[RSSI - 256] </code></pre> <p>and be sure to add RSSI to the output:</p> <pre><code> echo "UUID: $UUID MAJOR: $MAJOR MINOR: $MINOR POWER: $POWER RSSI: $RSSI" </code></pre>