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
25,771,412
Read integer from numeric cell using Apache POI in java
<p>I have an application which reads xls sheet using apache poi. When the cell has numeric value, i read it by row.getCell(i).getNumericValue(). But it returns floating point digit. like if the cell value is 1, it returns 1.0. Can i convert it to int ? Any helpwould be appreciated. I tried Integer.parseInt(value)- but it throws NumberFormat exception.Any help is appreciated.Here is the pseudo code:</p> <pre><code>FileInputStream file = new FileInputStream(new File("C:\\test.xls")); HSSFWorkbook workbook = new HSSFWorkbook(file); HSSFSheet sheet = workbook.getSheetAt(0); Iterator&lt;Row&gt; rowIterator = sheet.iterator(); while(rowIterator.hasNext()) { Row row = rowIterator.next(); Iterator&lt;Cell&gt; cellIterator = row.cellIterator(); while(cellIterator.hasNext()) { Cell cell = cellIterator.next(); switch(cell.getCellType()) { case Cell.CELL_TYPE_NUMERIC: String value= String.valueOf(cell.getNumericCellValue()); int intVal = Integer.parseInt(value)--&gt;&gt;throws Exception </code></pre>
38,790,371
8
2
null
2014-09-10 17:21:26.56 UTC
2
2020-04-20 20:38:33.747 UTC
2016-07-22 11:34:04.273 UTC
null
3,318,377
null
1,081,319
null
1
5
java|apache-poi|xls|numberformatexception
44,170
<p>You can read int value as string apache poi using simple steps</p> <p>First count rows in sheets using below method</p> <pre><code>private int getRowCount(Sheet currentSheet) { int rowCount = 0; Iterator&lt;Row&gt; rowIterator = currentSheet.iterator(); while(rowIterator.hasNext()) { Row row = rowIterator.next(); if(row == null || row.getCell(0) == null || row.getCell(0).getStringCellValue().trim().equals("") || row.getCell(0).toString().trim().equals("") || row.getCell(0).getCellType()==Cell.CELL_TYPE_BLANK){ break; } else rowCount=rowCount + 1; } return rowCount; } </code></pre> <p>Then use below code in your method</p> <pre><code> Workbook workbook = WorkbookFactory.create(new File("c:/test.xls"); Sheet marksSheet = (Sheet) workbook.getSheet("Sheet1"); int zoneLastCount = 0; if(marksSheet !=null ) { zoneLastCount = getRowCount(marksSheet); } int zone = zoneLastCount-1; int column=1 for(int i = 0; i &lt; zone; i++) { Row currentrow = marksSheet.getRow(i); double year = Double.parseDouble(currentrow.getCell(columnno).toString()); int year1 = (int)year; String str = String.valueOf(year1); } </code></pre>
18,746,185
Why doesn't the Scanner class have a nextChar method?
<p>This is really a curiosity more than a problem...</p> <p>Why doesn't the <code>Scanner</code> class have a <code>nextChar()</code> method? It seems like it should when you consider the fact that it has <code>next</code>, <code>nextInt</code>, <code>nextLine</code> etc method.</p> <p>I realize you can simply do the following:</p> <pre><code>userChar = in.next().charAt(0); System.out.println( userChar ); </code></pre> <p>But why not have a <code>nextChar()</code> method?</p>
18,746,385
5
2
null
2013-09-11 16:09:07.26 UTC
5
2013-09-12 02:41:04.413 UTC
null
null
null
null
1,100,874
null
1
33
java
120,271
<blockquote> <p>The reason is that the Scanner class is designed for reading in whitespace-separated tokens. It's a convenience class that wraps an underlying input stream. Before scanner all you could do was read in single bytes, and that's a big pain if you want to read words or lines. With Scanner you pass in System.in, and it does a number of read() operations to tokenize the input for you. Reading a single character is a more basic operation. <a href="http://www.overclockers.com/forums/showpost.php?s=485dc4f3e4a00c001ae516c9f9d5539b&amp;p=7222035&amp;postcount=10">Source</a></p> </blockquote> <p>You can use <code>(char) System.in.read();</code>.</p>
18,442,753
A required class was missing while executing org.apache.maven.plugins:maven-war-plugin:2.1.1:war
<p>Here is my clean install -x result:</p> <pre><code>[INFO] Scanning for projects... [INFO] [INFO] ------------------------------------------------------------------------ [INFO] Building test Maven Webapp 0.0.1-SNAPSHOT [INFO] ------------------------------------------------------------------------ [INFO] [INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ test --- [INFO] Deleting C:\Users\utopcu\workspace\test\target [INFO] [INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ test --- [WARNING] Using platform encoding (Cp1254 actually) to copy filtered resources, i.e. build is platform dependent! [INFO] Copying 0 resource [INFO] [INFO] --- maven-compiler-plugin:2.5.1:compile (default-compile) @ test --- [INFO] No sources to compile [INFO] [INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ test --- [WARNING] Using platform encoding (Cp1254 actually) to copy filtered resources, i.e. build is platform dependent! [INFO] skip non existing resourceDirectory C:\Users\utopcu\workspace\test\src\test\resources [INFO] [INFO] --- maven-compiler-plugin:2.5.1:testCompile (default-testCompile) @ test --- [INFO] No sources to compile [INFO] [INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ test --- [INFO] No tests to run. [INFO] [INFO] --- maven-war-plugin:2.1.1:war (default-war) @ test --- [WARNING] Error injecting: org.apache.maven.plugin.war.WarMojo java.lang.NoClassDefFoundError: org/apache/maven/shared/filtering/MavenFilteringException at java.lang.Class.getDeclaredConstructors0(Native Method) at java.lang.Class.privateGetDeclaredConstructors(Class.java:2483) at java.lang.Class.getDeclaredConstructors(Class.java:1891) at com.google.inject.spi.InjectionPoint.forConstructorOf(InjectionPoint.java:245) at com.google.inject.internal.ConstructorBindingImpl.create(ConstructorBindingImpl.java:99) at com.google.inject.internal.InjectorImpl.createUninitializedBinding(InjectorImpl.java:653) at com.google.inject.internal.InjectorImpl.createJustInTimeBinding(InjectorImpl.java:863) at com.google.inject.internal.InjectorImpl.createJustInTimeBindingRecursive(InjectorImpl.java:790) at com.google.inject.internal.InjectorImpl.getJustInTimeBinding(InjectorImpl.java:278) at com.google.inject.internal.InjectorImpl.getBindingOrThrow(InjectorImpl.java:210) at com.google.inject.internal.InjectorImpl.getProviderOrThrow(InjectorImpl.java:986) at com.google.inject.internal.InjectorImpl.getProvider(InjectorImpl.java:1019) at com.google.inject.internal.InjectorImpl.getProvider(InjectorImpl.java:982) at com.google.inject.internal.InjectorImpl.getInstance(InjectorImpl.java:1032) at org.eclipse.sisu.reflect.AbstractDeferredClass.get(AbstractDeferredClass.java:44) at com.google.inject.internal.ProviderInternalFactory.provision(ProviderInternalFactory.java:86) at com.google.inject.internal.InternalFactoryToInitializableAdapter.provision(InternalFactoryToInitializableAdapter.java:55) at com.google.inject.internal.ProviderInternalFactory$1.call(ProviderInternalFactory.java:70) at com.google.inject.internal.ProvisionListenerStackCallback$Provision.provision(ProvisionListenerStackCallback.java:100) at org.eclipse.sisu.plexus.lifecycles.PlexusLifecycleManager.onProvision(PlexusLifecycleManager.java:134) at com.google.inject.internal.ProvisionListenerStackCallback$Provision.provision(ProvisionListenerStackCallback.java:109) at com.google.inject.internal.ProvisionListenerStackCallback.provision(ProvisionListenerStackCallback.java:55) at com.google.inject.internal.ProviderInternalFactory.circularGet(ProviderInternalFactory.java:68) at com.google.inject.internal.InternalFactoryToInitializableAdapter.get(InternalFactoryToInitializableAdapter.java:47) at com.google.inject.internal.InjectorImpl$2$1.call(InjectorImpl.java:997) at com.google.inject.internal.InjectorImpl.callInContext(InjectorImpl.java:1047) at com.google.inject.internal.InjectorImpl$2.get(InjectorImpl.java:993) at com.google.inject.Scopes$1$1.get(Scopes.java:59) at org.eclipse.sisu.locators.LazyBeanEntry.getValue(LazyBeanEntry.java:82) at org.eclipse.sisu.plexus.locators.LazyPlexusBean.getValue(LazyPlexusBean.java:52) at org.codehaus.plexus.DefaultPlexusContainer.lookup(DefaultPlexusContainer.java:259) at org.codehaus.plexus.DefaultPlexusContainer.lookup(DefaultPlexusContainer.java:251) at org.apache.maven.plugin.internal.DefaultMavenPluginManager.getConfiguredMojo(DefaultMavenPluginManager.java:459) at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:97) at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:208) at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153) at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:84) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59) at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183) at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161) at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:318) at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:153) at org.apache.maven.cli.MavenCli.execute(MavenCli.java:555) at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:214) at org.apache.maven.cli.MavenCli.main(MavenCli.java:158) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:290) at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:230) at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:414) at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:357) at org.codehaus.classworlds.Launcher.main(Launcher.java:47) Caused by: java.lang.ClassNotFoundException: org.apache.maven.shared.filtering.MavenFilteringException at org.codehaus.plexus.classworlds.strategy.SelfFirstStrategy.loadClass(SelfFirstStrategy.java:50) at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClass(ClassRealm.java:244) at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClass(ClassRealm.java:230) ... 55 more [INFO] ------------------------------------------------------------------------ [INFO] BUILD FAILURE [INFO] ------------------------------------------------------------------------ [INFO] Total time: 3.342s [INFO] Finished at: Mon Aug 26 14:09:27 EEST 2013 [INFO] Final Memory: 11M/105M [INFO] ------------------------------------------------------------------------ [ERROR] Failed to execute goal org.apache.maven.plugins:maven-war-plugin:2.1.1:war (default-war) on project test: Execution default-war of goal org.apache.maven.plugins:maven-war-plugin:2.1.1:war failed: A required class was missing while executing org.apache.maven.plugins:maven-war-plugin:2.1.1:war: org/apache/maven/shared/filtering/MavenFilteringException [ERROR] ----------------------------------------------------- [ERROR] realm = plugin&gt;org.apache.maven.plugins:maven-war-plugin:2.1.1 [ERROR] strategy = org.codehaus.plexus.classworlds.strategy.SelfFirstStrategy [ERROR] urls[0] = file:/C:/Users/utopcu/.m2/repository/org/apache/maven/plugins/maven-war-plugin/2.1.1/maven-war-plugin-2.1.1.jar [ERROR] urls[1] = file:/C:/Users/utopcu/.m2/repository/org/apache/maven/reporting/maven-reporting-api/2.0.6/maven-reporting-api-2.0.6.jar [ERROR] urls[2] = file:/C:/Users/utopcu/.m2/repository/org/apache/maven/doxia/doxia-sink-api/1.0-alpha-7/doxia-sink-api-1.0-alpha-7.jar [ERROR] urls[3] = file:/C:/Users/utopcu/.m2/repository/commons-cli/commons-cli/1.0/commons-cli-1.0.jar [ERROR] urls[4] = file:/C:/Users/utopcu/.m2/repository/org/codehaus/plexus/plexus-interactivity-api/1.0-alpha-4/plexus-interactivity-api-1.0-alpha-4.jar [ERROR] urls[5] = file:/C:/Users/utopcu/.m2/repository/org/apache/maven/maven-archiver/2.4.1/maven-archiver-2.4.1.jar [ERROR] urls[6] = file:/C:/Users/utopcu/.m2/repository/org/codehaus/plexus/plexus-archiver/1.2/plexus-archiver-1.2.jar [ERROR] urls[7] = file:/C:/Users/utopcu/.m2/repository/org/codehaus/plexus/plexus-io/1.0.1/plexus-io-1.0.1.jar [ERROR] urls[8] = file:/C:/Users/utopcu/.m2/repository/org/codehaus/plexus/plexus-interpolation/1.13/plexus-interpolation-1.13.jar [ERROR] urls[9] = file:/C:/Users/utopcu/.m2/repository/junit/junit/3.8.1/junit-3.8.1.jar [ERROR] urls[10] = file:/C:/Users/utopcu/.m2/repository/com/thoughtworks/xstream/xstream/1.3.1/xstream-1.3.1.jar [ERROR] urls[11] = file:/C:/Users/utopcu/.m2/repository/xpp3/xpp3_min/1.1.4c/xpp3_min-1.1.4c.jar [ERROR] urls[12] = file:/C:/Users/utopcu/.m2/repository/org/codehaus/plexus/plexus-utils/2.0.5/plexus-utils-2.0.5.jar [ERROR] urls[13] = file:/C:/Users/utopcu/.m2/repository/org/apache/maven/shared/maven-filtering/1.0-beta-2/maven-filtering-1.0-beta-2.jar [ERROR] Number of foreign imports: 1 [ERROR] import: Entry[import from realm ClassRealm[maven.api, parent: null]] [ERROR] [ERROR] -----------------------------------------------------: org.apache.maven.shared.filtering.MavenFilteringException [ERROR] -&gt; [Help 1] [ERROR] [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch. [ERROR] Re-run Maven using the -X switch to enable full debug logging. [ERROR] [ERROR] For more information about the errors and possible solutions, please read the following articles: [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/PluginContainerException </code></pre> <p>And here is my pom.xml:</p> <pre><code>&lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;groupId&gt;trest&lt;/groupId&gt; &lt;artifactId&gt;test&lt;/artifactId&gt; &lt;packaging&gt;war&lt;/packaging&gt; &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt; &lt;name&gt;test Maven Webapp&lt;/name&gt; &lt;url&gt;http://maven.apache.org&lt;/url&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;junit&lt;/groupId&gt; &lt;artifactId&gt;junit&lt;/artifactId&gt; &lt;version&gt;3.8.1&lt;/version&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-war-plugin&lt;/artifactId&gt; &lt;version&gt;2.1.1&lt;/version&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; &lt;/project&gt; </code></pre> <p>I tried to delete repositories and install again. I got this error always. It looks like I need help. I think my mojo plugin is broken but i re installed it several times. Any suggestions?</p>
18,443,696
9
2
null
2013-08-26 11:12:22.163 UTC
4
2020-09-03 12:00:03.06 UTC
2013-09-27 08:51:25.477 UTC
null
217,079
null
2,399,421
null
1
29
java|eclipse|maven|mojo
130,555
<p>Does the class <code>org.apache.maven.shared.filtering.MavenFilteringException</code> exist in <code>file:/C:/Users/utopcu/.m2/repository/org/apache/maven/shared/maven-filtering/1.0-beta-2/maven-filtering-1.0-beta-2.jar</code>?</p> <p>The error message suggests that it doesn't. Maybe the JAR was corrupted somehow.</p> <p>I'm also wondering where the version <code>1.0-beta-2</code> comes from; I have <code>1.0</code> on my disk. Try version <code>2.3</code> of the WAR plugin.</p>
20,306,204
Using querySelector with IDs that are numbers
<p>From what I understand the HTML5 spec lets you use IDs that are numbers like this.</p> <pre><code>&lt;div id="1"&gt;&lt;/div&gt; &lt;div id="2"&gt;&lt;/div&gt; </code></pre> <p>I can access these fine using <code>getElementById</code> but not with <code>querySelector</code>. If I try do the following I get <strong>SyntaxError: DOM Exception 12</strong> in the console.</p> <pre><code>document.querySelector("#1") </code></pre> <p>I'm just curious why using numbers as IDs does not work <code>querySelector</code> when the HTML5 spec says these are valid. I tried multiple browsers.</p>
20,306,237
7
3
null
2013-11-30 22:06:13.607 UTC
26
2022-07-02 12:58:09.353 UTC
2014-05-18 13:44:03.237 UTC
null
106,224
null
284,714
null
1
139
javascript|html|css-selectors|selectors-api
135,237
<p>It is valid, but requires some special handling. From here: <a href="http://mathiasbynens.be/notes/css-escapes">http://mathiasbynens.be/notes/css-escapes</a></p> <blockquote> <p>Leading digits</p> <p>If the first character of an identifier is numeric, you’ll need to escape it based on its Unicode code point. For example, the code point for the character 1 is U+0031, so you would escape it as \000031 or \31 .</p> <p>Basically, to escape any numeric character, just prefix it with \3 and append a space character ( ). Yay Unicode!</p> </blockquote> <p>So your code would end up as (CSS first, JS second):</p> <pre><code>#\31 { background: hotpink; } document.getElementById('1'); document.querySelector('#\\31 '); </code></pre>
15,373,147
Make display table-cell use percentage width
<p><a href="http://jsfiddle.net/qy7ad/">Fiddle</a></p> <p>I've got this table feel going, using an unordered list. But I can't figure out how to get the table-cells to have 50% width (I want each row to be 100% width). The reason I am using <code>display: table-row;</code> and <code>display: table-cell;</code> is so that I can vertical-align the data if the parameter text is more than one line. I don't want to use an actual pixel or em value for the width, because, well, I just want it in percentage if its possible. I would rather give up the vertical-align. Please no javascript. Thanks!</p> <p>HTML:</p> <pre><code>&lt;div class="group group2"&gt; &lt;h2&gt;Health Indicies&lt;/h2&gt; &lt;ul&gt; &lt;li&gt;&lt;p class="parameter"&gt;GGP&lt;/p&gt;&lt;p class="data"&gt;265&lt;/p&gt;&lt;/li&gt; &lt;li&gt;&lt;p class="parameter"&gt;Comfort&lt;/p&gt;&lt;p class="data"&gt;blah&lt;/p&gt;&lt;/li&gt; &lt;li&gt;&lt;p class="parameter"&gt;Energy&lt;/p&gt;&lt;p class="data"&gt;gooo&lt;/p&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre> <p>CSS:</p> <pre><code>ul { margin: 0; padding: 0; list-style: none; } .group { width: 50%; margin-bottom: 20px; outline: 1px solid black; background: white; box-shadow: 1px 1px 5px 0px gray; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } .group h2 { display: block; font-size: 14px; background: gray; text-align: center; padding: 5px; } .group li { clear: both; } .group p { padding: 3%; text-align: center; font-size: 14px; } .group2 li { display: table-row; } .group2 p { display: table-cell; vertical-align: middle; width: 46%; border-bottom: 2px solid gray; } .group li:last-child p { border-bottom: 0; } </code></pre>
15,373,222
5
1
null
2013-03-12 22:05:29.2 UTC
2
2020-03-19 14:40:45.63 UTC
null
null
null
null
1,388,017
null
1
40
html|css
76,074
<p>You're almost there. You just need to add <code>display: table</code> and <code>width: 100%</code> to your <code>ul.group2</code>. You could probably also get away with not supplying a <code>width</code> on your <code>.group2 p</code> elements.</p> <p>This should work: <a href="http://jsfiddle.net/6Kn88/2/" rel="nofollow noreferrer">http://jsfiddle.net/6Kn88/2/</a></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-css lang-css prettyprint-override"><code>ul { margin: 0; padding: 0; list-style: none; } .group { width: 50%; margin-bottom: 20px; outline: 1px solid black; background: white; box-shadow: 1px 1px 5px 0px gray; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } .group h2 { display: block; font-size: 14px; background: gray; text-align: center; padding: 5px; } .group li { clear: both; } .group p { padding: 3%; text-align: center; font-size: 14px; } .group2 ul { display: table; width: 100%; } .group2 li { display: table-row; } .group2 p { display: table-cell; vertical-align: middle; width: 46%; border-bottom: 2px solid gray; } .group li:last-child p { border-bottom: 0; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="group group2"&gt; &lt;h2&gt;Health Indicies&lt;/h2&gt; &lt;ul&gt; &lt;li&gt;&lt;p class="parameter"&gt;GGP&lt;/p&gt;&lt;p class="data"&gt;265&lt;/p&gt;&lt;/li&gt; &lt;li&gt;&lt;p class="parameter"&gt;Comfort&lt;/p&gt;&lt;p class="data"&gt;blah&lt;/p&gt;&lt;/li&gt; &lt;li&gt;&lt;p class="parameter"&gt;Energy&lt;/p&gt;&lt;p class="data"&gt;gooo&lt;/p&gt;&lt;/li&gt; &lt;/ul&gt; &lt;span class="clear"&gt;&lt;/span&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
14,940,660
What's Mongoose error Cast to ObjectId failed for value XXX at path "_id"?
<p>When sending a request to <code>/customers/41224d776a326fb40f000001</code> and a document with <code>_id</code> <code>41224d776a326fb40f000001</code> does not exist, <code>doc</code> is <code>null</code> and I'm returning a <code>404</code>:</p> <pre><code> Controller.prototype.show = function(id, res) { this.model.findById(id, function(err, doc) { if (err) { throw err; } if (!doc) { res.send(404); } return res.send(doc); }); }; </code></pre> <p>However, when <code>_id</code> does not match what Mongoose expects as "format" (I suppose) for example with <code>GET /customers/foo</code> a strange error is returned:</p> <blockquote> <p>CastError: Cast to ObjectId failed for value "foo" at path "_id".</p> </blockquote> <p>So what's this error?</p>
14,942,113
33
0
null
2013-02-18 16:18:03.7 UTC
49
2022-09-23 09:33:46.887 UTC
null
null
null
null
220,180
null
1
191
mongodb|mongoose
319,981
<p>Mongoose's <code>findById</code> method casts the <code>id</code> parameter to the type of the model's <code>_id</code> field so that it can properly query for the matching doc. This is an ObjectId but <code>"foo"</code> is not a valid ObjectId so the cast fails.</p> <p>This doesn't happen with <code>41224d776a326fb40f000001</code> because that string is a valid ObjectId.</p> <p>One way to resolve this is to add a check prior to your <code>findById</code> call to see if <code>id</code> is a valid ObjectId or not like so:</p> <pre class="lang-js prettyprint-override"><code>if (id.match(/^[0-9a-fA-F]{24}$/)) { // Yes, it's a valid ObjectId, proceed with `findById` call. } </code></pre>
28,222,548
How to disable context menu on right click/long touch in a kiosk mode of Chrome?
<p>We are working on the software for a museum. There are several interactive kiosks with touch screen running on Windows 8.1 which are connected into local network. No keyboard, no mouse. The server with Apache on it contains several local websites. Each kiosk runs a copy of Google Chrome in a kiosk mode. So, we have some kind of local web applications which provide a museum visitor with information.</p> <p>Now, the problem. If a visitor does long touch on screen it works like an analogue of right click. Context menu appears. We don't want it at all. I've added "oncontextmenu = return false" into the body tag and it helped. But. We have a couple of external websites running in iframes (the museum has a connection to Internet). And context menu <strong>does</strong> appear on iframes. AFAIK, there is no way to disable it using javascript.</p> <p>Our system engineer got a software which completely disables right click in Windows. Anywhere including Chrome. But. It works for a mouse. And as for touches... well, it disables touch events anywhere <strong>besides</strong> Chrome. Maybe Chrome has its own touch events handler, I don't know.</p> <p>So, after all. We need to get rid off context menu on iframes on right click/long touch in a kiosk mode of Chrome. Please give me some advice.</p>
28,223,205
2
3
null
2015-01-29 19:03:19.8 UTC
10
2019-11-14 04:48:24.61 UTC
null
null
null
null
4,179,987
null
1
20
javascript|google-chrome|iframe|kiosk-mode
32,453
<p>I assume you're displaying a plain <code>http://...</code> (or possibly <code>https://...</code> or <code>file://...</code>) Web page on your kiosk. If you're actually showing an app (i.e., <code>chrome-extension://...</code>), then this strategy will not work.</p> <p>A Chrome extension that injects <code>window.addEventListener("contextmenu", function(e) { e.preventDefault(); })</code> into every browsing context would probably do the trick to block context menus on iframes.</p> <p><strong>manifest.json:</strong></p> <pre><code>{ "manifest_version": 2, "name": "Context Menu Blocker", "version": "1.0", "content_scripts": [ { "matches": ["&lt;all_urls&gt;"], "js": ["contextblocker.js"], "all_frames": true, "match_about_blank": true } ] } </code></pre> <p><strong>contextblocker.js:</strong></p> <pre><code>window.addEventListener("contextmenu", function(e) { e.preventDefault(); }) </code></pre> <p>Simply create a folder and place the two files inside. Then, go to <code>chrome://extensions/</code>, check the <code>Developer Mode</code> box. Finally, click <code>Load unpacked extension...</code> and select the folder you just created.</p> <p>This should prevent the context menu from appearing in anywhere extension content scripts are allowed to run, include any page loaded inside of an iframe. There are few notable points where it fails:</p> <ul> <li>Extensions are not allowed to run on <code>chrome://</code> or <code>chrome-extension://</code> pages, or on Google's Web Store. If your kiosk is displaying an app, this whole strategy won't work, because this extension won't be able to access iframes inside of another app or extension (even if the source of the iframe is an origin that it would normally have permission to access).</li> <li>If you navigate directly to <code>about:blank</code>, the content script will not run and the context menu can appear. (If <code>about:blank</code> is loaded in an iframe, however, the block will work correctly.)</li> <li>If an iframe has a <code>sandbox</code> attribute that does not include the <code>allow-scripts</code> permission, then the extension cannot block context menus from that iframe.</li> </ul> <p>As long as none of those restrictions apply (and as long as a script on the page itself does not clear all event listeners on <code>window</code>), then it should work.</p> <p>I have used the code above to create <a href="https://chrome.google.com/webstore/detail/gomhdignfhgeamkdgnhaimjigoppgihh">a simple extension in the Chrome Web Store</a>. (Developer-mode extensions now produce a warning on start-up, while Web Store extensions do not.)</p>
9,376,837
Difference between C standard library and C POSIX library
<p>I'm a little confused by "C standard lib" and "C POSIX lib", because I found that, many header files defined in "C POSIX lib" are also part of "C standard lib". </p> <p>So, I assume that, "C standard lib" is a lib defined by ANSI C organization, and there are different implementation on different platforms (Win32/Unix-like), and "C POSIX lib" is just a implementation for "C standard lib" on Unix-like OSes, right?</p> <p>But "C POSIX lib" contains some headers not specified in "C standard lib", such as <code>&lt;sys/types.h&gt;</code>, <code>&lt;sys/wait.h&gt;</code>, and <code>&lt;pthread.h&gt;</code>.</p> <p>Take <code>&lt;pthread.h&gt;</code> as an example, I presume its "C standard lib" counterpart is <code>&lt;threads.h&gt;</code>, then if I want to write a multi-threaded program on Linux, which header file should I include, <code>&lt;pthread.h&gt;</code> or <code>&lt;threads.h&gt;</code>?</p>
9,377,007
4
8
null
2012-02-21 11:32:57.82 UTC
43
2019-06-19 10:55:18.973 UTC
2016-06-22 14:28:34.247 UTC
null
598,057
null
888,051
null
1
84
c|posix|standard-library
38,079
<p>POSIX is a superset of the standard C library, and it's important to note that it defers to it. If C and POSIX is ever in conflict, C wins.</p> <p>Sockets, file descriptors, shared memory etc. are all part of POSIX, but do not exist in the C library.</p> <p><code>pthread.h</code> is used for POSIX threads and <code>threads.h</code> is a new header for C11 and is part of the C library. Perhaps pthreads will be deprecated sometime in the future in favor of the C ones, however you probably can't count on C11 to have widespread deployment yet. Therefore if you want portability you should prefer pthreads for now. If portability is not a concern, and you have C11 threads available, you should probably use those.</p>
23,681,221
How retrieve responseJSON property of a jquery $.ajax object
<p>I have this javascript:</p> <pre><code>$ajax = $.ajax({ type: 'GET', url: 'DBConnect.php', data: '', dataType: 'json', success: function(data) {}, error:function (xhr, ajaxOptions, thrownError) { dir(thrownError); dir(xhr); dir(ajaxOptions); } }); console.dir($ajax); console.dir($ajax.responseJSON); </code></pre> <p>console.dir($ajax) shows it has a property named responseJSON, but when I try to access it with $ajax.responseJSON it returns undefined: <img src="https://i.stack.imgur.com/jKopz.jpg" alt="enter image description here"></p>
26,036,688
4
5
null
2014-05-15 14:29:53.613 UTC
6
2018-07-26 11:23:03.793 UTC
null
null
null
null
1,028,270
null
1
21
javascript|jquery|ajax|json
87,414
<p>Well, of course it's undefined, because at the moment when you run <code>console</code> at last lines of your code, response hasn't yet came from the server. </p> <p><code>$.ajax</code> returns promise, which you can use to attach <code>done()</code> and <code>fail()</code> callbacks, where you can use all the properties that you see. And you have actually used callback <code>error</code> and <code>success</code>, and that's where you can run code and other functions that rely on data in the response.</p>
23,584,201
Conditionally add target="_blank" to links with Angular JS
<p>I am building a navigation tree in Angular JS. Most links in the tree will point to pages within my website, but some may point to external sites.</p> <p>If the href of a link begins with http:// or https:// then I am assuming the link is for an external site (a regex like <code>/^https?:\/\//</code> does the trick).</p> <p>I would like to apply the target="_blank" attribute to these links. I was hoping to do this with angular when I am creating my links:</p> <pre><code>&lt;ul&gt; &lt;li ng-repeat="link in navigation"&gt; &lt;a ng-href="{{link.href}}" [add target="_blank" if link.href matches /^https?:\/\//]&gt;{{link.title}}&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre> <p>Can anyone help me out?</p> <p>Thanks</p>
30,599,954
4
8
null
2014-05-10 17:29:13.25 UTC
4
2016-02-25 03:17:45.983 UTC
2015-10-09 03:29:37.377 UTC
null
1,891,190
null
1,891,190
null
1
37
javascript|angularjs
52,163
<p>I was just about to create a directive as suggested and then realised that all you actually need to do is this:</p> <pre><code>&lt;a ng-attr-target="{{(condition) ? '_blank' : undefined}}"&gt; ... &lt;/a&gt; </code></pre> <p><code>ng-attr-xyz</code> lets you dynamically create <code>@xyz</code>, and if the value is <code>undefined</code> no attribute is created -- just what we want.</p>
23,448,403
The parameterized query ..... expects the parameter '@units', which was not supplied
<p>I'm getting this exception:</p> <blockquote> <p>The parameterized query '(@Name nvarchar(8),@type nvarchar(8),@units nvarchar(4000),@rang' expects the parameter '@units', which was not supplied.</p> </blockquote> <p>My code for inserting is:</p> <pre><code>public int insertType(string name, string type, string units = "N\\A", string range = "N\\A", string scale = "N\\A", string description = "N\\A", Guid guid = new Guid()) { using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); SqlCommand command = new SqlCommand(); command.CommandText = "INSERT INTO Type(name, type, units, range, scale, description, guid) OUTPUT INSERTED.ID VALUES (@Name, @type, @units, @range, @scale, @description, @guid) "; command.Connection = connection; command.Parameters.AddWithValue("@Name", name); command.Parameters.AddWithValue("@type", type); command.Parameters.AddWithValue("@units", units); command.Parameters.AddWithValue("@range", range); command.Parameters.AddWithValue("@scale", scale); command.Parameters.AddWithValue("@description", description); command.Parameters.AddWithValue("@guid", guid); return (int)command.ExecuteScalar(); } } </code></pre> <p>The exception was a surprise because I'm using the <code>AddWithValue</code> function and making sure I added a default parameters for the function. </p> <p>SOLVED:</p> <p>The problem was that the some parameters where empty Strings (that override the default)</p> <p>This is the working code: </p> <pre><code>public int insertType(string name, string type, string units = "N\\A", string range = "N\\A", string scale = "N\\A", string description = "N\\A", Guid guid = new Guid()) { using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); SqlCommand command = new SqlCommand(); command.CommandText = "INSERT INTO Type(name, type, units, range, scale, description, guid) OUTPUT INSERTED.ID VALUES (@Name, @type, @units, @range, @scale, @description, @guid) "; command.Connection = connection; command.Parameters.AddWithValue("@Name", name); command.Parameters.AddWithValue("@type", type); if (String.IsNullOrEmpty(units)) { command.Parameters.AddWithValue("@units", DBNull.Value); } else command.Parameters.AddWithValue("@units", units); if (String.IsNullOrEmpty(range)) { command.Parameters.AddWithValue("@range", DBNull.Value); } else command.Parameters.AddWithValue("@range", range); if (String.IsNullOrEmpty(scale)) { command.Parameters.AddWithValue("@scale", DBNull.Value); } else command.Parameters.AddWithValue("@scale", scale); if (String.IsNullOrEmpty(description)) { command.Parameters.AddWithValue("@description", DBNull.Value); } else command.Parameters.AddWithValue("@description", description); command.Parameters.AddWithValue("@guid", guid); return (int)command.ExecuteScalar(); } } </code></pre>
23,448,939
5
14
null
2014-05-03 18:34:40.543 UTC
10
2019-07-12 16:07:49.4 UTC
2014-05-03 19:51:10.22 UTC
null
3,497,723
null
3,497,723
null
1
92
c#|sql-server|exception
102,557
<p>Try this code:</p> <pre><code>SqlParameter unitsParam = command.Parameters.AddWithValue("@units", units); if (units == null) { unitsParam.Value = DBNull.Value; } </code></pre> <p>And you must check all other parameters for null value. If it null you must pass <code>DBNull.Value</code> value.</p>
5,306,741
Do JSON keys need to be unique?
<p>The following question is related to a question that I had asked earlier: <a href="https://stackoverflow.com/questions/5303859/help-parsing-simple-json-using-json-for-java-me">Help parsing simple JSON (using JSON for JAVA ME)</a></p> <p>Do JSON keys need to be unique? For example, I was having trouble parsing the following XML (with JSON ME):</p> <pre><code>{ &quot;name&quot; : &quot;JACK&quot;, &quot;name&quot; : &quot;JILL&quot;, &quot;name&quot; : &quot;JOHN&quot;, &quot;name&quot; : &quot;JENNY&quot;, &quot;name&quot; : &quot;JAMES&quot;, &quot;name&quot; : &quot;JIM&quot; } </code></pre> <p>And, apparently, its because the keys must be unique. I'm just wondering if thats true in all cases or not. For example, if I were using something other than JSON ME, would I be able to parse all of these names?</p> <p>Thanks.</p>
5,306,792
5
1
null
2011-03-15 02:07:52.147 UTC
10
2021-06-28 05:26:06.663 UTC
2021-06-28 05:26:06.663 UTC
null
330,457
null
123,891
null
1
39
java|json|parsing|key|unique
72,186
<p>There is no "error" if you use more than one key with the same name, but in JSON, the last key with the same name is the one that is going to be used. </p> <p>In your case, the key "name" would be better to contain an array as it's value, instead of having a number of keys "name". It doesn't make much sense the same object or "thing" to have two names, or two of the same properties that are in conflict.</p> <p>E.g.:</p> <pre><code>{ "name" : [ "JOHN", "JACK", "...", ... ] } </code></pre>
5,034,755
SVN folder does not have green icon in Windows7
<p>I am setting up a repository, and for some reason when I create a repository, the directory does not change to displaying the common SVN checkbox.</p> <p>Are there any common well-known mistakes that cause that?</p> <p>I am using Windows7</p> <p>Thanks, Alex</p>
5,034,793
6
0
null
2011-02-17 21:15:31.133 UTC
1
2017-12-27 04:45:36.813 UTC
2011-02-17 21:17:52.9 UTC
null
424,509
null
478,573
null
1
6
svn|tortoisesvn
46,856
<p>Not sure if that's exactly your problem, but there is a common problem with the TortoiseSVN overlay icons not showing up in Windows 7:</p> <ul> <li><a href="https://stackoverflow.com/questions/1057734/tortoisesvn-icons-not-showing-up-under-windows-7">TortoiseSVN icons not showing up under Windows 7</a></li> </ul>
4,954,389
Measuring cellular signal strength
<p>I am developing a non-appstore app for iOS. I want to read the cellular signal strength in my code.</p> <p>I know Apple doesn't provide any API by which we can achieve this. </p> <p>Is there any private API that can be used to achieve this? I have gone through the various threads regarding this issue but could not find any relevant info.</p> <p>It is completely possible because there is an <a href="http://itunes.apple.com/us/app/baralarm/id364878555?mt=8" rel="noreferrer">app in the app-store</a> for detecting the carrier's signal strength.</p>
4,955,390
6
1
null
2011-02-10 07:17:54.73 UTC
24
2017-06-14 01:01:42.513 UTC
2015-02-09 22:30:13 UTC
null
2,615,940
null
437,701
null
1
32
ios|iphone|objective-c|cocoa-touch
37,534
<p>I briefly looked at the VAFieldTest project located at <a href="https://github.com/valexa/VAFieldTest" rel="noreferrer">Github</a>.</p> <p>There seems to be <code> getSignalStrength()</code> and <code>register_notification()</code> functions in Classes/VAFieldTestViewController.m that might be interesting to you as they call into <code>CoreTelephony.framework</code>. </p> <p>I am pretty confident that some of the used calls are undocumented in the <a href="http://developer.apple.com/library/ios/#documentation/NetworkingInternet/Reference/CoreTelephonyFrameworkReference/_index.html" rel="noreferrer">CoreTelephony framework documentation from Apple</a> and therefore private - any app in the AppStore must have slipped passed inspection. </p>
5,121,976
Is there a date format to display the day of the week in java?
<p>I know of date formats such as <br/> <code>"yyyy-mm-dd"</code> -which displays date in format <code>2011-02-26</code><br/> <code>"yyyy-MMM-dd"</code>-which displays date in format <code>2011-FEB-26</code></p> <p>to be used in eg:</p> <pre><code>SimpleDateFormat formatter = new SimpleDateFormat( "yyyy/MMM/dd "); </code></pre> <p>I want a format which would help me display the day of the week like <code>2011-02-MON</code> or anything. I just want the day of the week to be displayed in characters with the month and the year. Can you tell me of a format like this?</p>
5,122,016
6
4
null
2011-02-25 19:56:19.307 UTC
25
2019-06-14 14:40:11.25 UTC
2016-06-21 12:11:55.34 UTC
null
6,343,685
null
598,714
null
1
162
java|date|simpledateformat|date-formatting
209,519
<p>This should display 'Tue':</p> <pre><code>new SimpleDateFormat("EEE").format(new Date()); </code></pre> <p>This should display 'Tuesday':</p> <pre><code>new SimpleDateFormat("EEEE").format(new Date()); </code></pre> <p>This should display 'T':</p> <pre><code>new SimpleDateFormat("EEEEE").format(new Date()); </code></pre> <p>So your specific example would be:</p> <pre><code>new SimpleDateFormat("yyyy-MM-EEE").format(new Date()); </code></pre>
4,943,857
How is Linux kernel live debugging done and what tools are used?
<p>What are the most common and why are uncommon methods and tools used not to do live debugging on the Linux kernel?</p> <p>I know that <a href="https://en.wikipedia.org/wiki/Linus_Torvalds" rel="nofollow noreferrer">Linus</a>, for example, <a href="http://lwn.net/2000/0914/a/lt-debugger.php3" rel="nofollow noreferrer">is against</a> this kind of debugging for the Linux Kernel or it least was and thus nothing much has been done in that sense in those years, but honestly a lot of time has passed since 2000 and I am interested if that mentality has changed regarding the Linux project and what current methods are used to do live debugging on the Linux kernel at the moment (either local or remote)?</p> <p>References to walkthroughs and tutorials on mentioned techniques and tools are welcome.</p>
4,966,975
11
2
null
2011-02-09 10:53:01.697 UTC
46
2022-07-03 09:19:50.14 UTC
2022-07-01 17:46:25.073 UTC
null
63,550
null
473,612
null
1
57
debugging|linux-kernel|kernel
46,033
<p>Another option is to use an <a href="http://en.wikipedia.org/wiki/In-circuit_emulator" rel="nofollow noreferrer">ICE</a> or <a href="https://en.wikipedia.org/wiki/Joint_Test_Action_Group" rel="nofollow noreferrer">JTAG</a> controller, and GDB. This 'hardware' solution is especially used with embedded systems.</p> <p>But for instance <a href="https://en.wikipedia.org/wiki/QEMU" rel="nofollow noreferrer">QEMU</a> offers similar features:</p> <ul> <li><p>start QEMU with a GDB 'remote' stub which listens on 'localhost:1234' : <code>qemu -s ...</code>,</p> </li> <li><p>then with GDB, you open the kernel file <code>vmlinux</code> compiled with debug information (you can take a look a <a href="https://lkml.org/lkml/2010/11/28/211" rel="nofollow noreferrer">this mailing list thread</a> where they discuss the unoptimization of the kernel).</p> </li> <li><p>connect GDB and QEMU: <code>target remote localhost:1234</code></p> </li> <li><p>see your <em>live</em> kernel:</p> <pre><code> (gdb) where #0 cpu_v7_do_idle () at arch/arm/mm/proc-v7.S:77 #1 0xc0029728 in arch_idle () atarm/mach-realview/include/mach/system.h:36 #2 default_idle () at arm/kernel/process.c:166 #3 0xc00298a8 in cpu_idle () at arch/arm/kernel/process.c:199 #4 0xc00089c0 in start_kernel () at init/main.c:713 </code></pre> </li> </ul> <p>Unfortunately, user-space debugging is not possible so far with GDB (no task list information, no <a href="https://en.wikipedia.org/wiki/Memory_management_unit" rel="nofollow noreferrer">memory management unit</a> reprogramming to see different process contexts, ...), but if you stay in kernel-space, that's quite convenient.</p> <ul> <li><code>info threads</code> will give you the list and states of the different <em>CPUs</em></li> </ul> <p>You can get more details about the procedure in this PDF:</p> <p><em><a href="http://files.meetup.com/1590495/debugging-with-qemu.pdf" rel="nofollow noreferrer">Debugging Linux systems using GDB and QEMU</a></em>.</p>
4,933,075
NSTimeInterval to HH:mm:ss?
<p>If I have an NSTimeInterval that is set to say 200.0, is there a way to convert that into 00:03:20, I was thinking I could initialise an NSDate with it and then use NSDateFormatter using HH:mm:ss. My question is, is there a quick way to do this or do I have to break up the number myself and use <code>[NSString stringWithFormat: %02d:%02d:%02d, myHour, myMin, mySec]</code>?</p>
4,933,139
12
0
null
2011-02-08 12:36:59.42 UTC
23
2018-12-17 09:57:41.997 UTC
2015-09-04 11:25:22.797 UTC
null
544,094
null
164,216
null
1
86
iphone|objective-c|cocoa-touch
56,404
<p>No need to use <code>NSDateFormatter</code> or anything else than division and modulo. <code>NSTimeInterval</code> is just a double containing seconds.</p> <p><strong>Swift</strong></p> <pre><code>func stringFromTimeInterval(interval: NSTimeInterval) -&gt; String { let interval = Int(interval) let seconds = interval % 60 let minutes = (interval / 60) % 60 let hours = (interval / 3600) return String(format: "%02d:%02d:%02d", hours, minutes, seconds) } </code></pre> <p><strong>Objective-C</strong></p> <pre><code>- (NSString *)stringFromTimeInterval:(NSTimeInterval)interval { NSInteger ti = (NSInteger)interval; NSInteger seconds = ti % 60; NSInteger minutes = (ti / 60) % 60; NSInteger hours = (ti / 3600); return [NSString stringWithFormat:@"%02ld:%02ld:%02ld", (long)hours, (long)minutes, (long)seconds]; } </code></pre>
4,976,658
On EC2: sudo node command not found, but node without sudo is ok
<p>I have just installed nodejs on a new EC2 micro instance.</p> <p>I installed it normally, ./configure -> make -> sudo make install.</p> <p><strong>Problem:</strong> When I run "node" under ec2-user, it runs perfectly. When I run "sudo node", it fails.</p> <p>I found out that node is in:</p> <pre><code>[ec2-user@XXXX ~]$ whereis node node: /usr/local/bin/node /usr/local/lib/node </code></pre> <p>and the current path is</p> <pre><code>[ec2-user@XXXX ~]$ echo $PATH /usr/local/bin:/bin:/usr/bin:/opt/aws/bin:/home/ec2-user/bin </code></pre> <p>but, the sudo path is</p> <pre><code>[root@ip-10-112-222-32 ~]# echo $PATH /usr/local/sbin:/sbin:/bin:/usr/sbin:/usr/bin:/opt/aws/bin:/root/bin </code></pre> <p>then I tried to edit the root PATH to include the paths to node, so "node" runs when I'm logged in as root - but it still won't work when I log in as ec2-user and run "sudo node".</p> <p>I need this to install npm properfly. Any idea on how to include the node path while running "sudo node"?</p>
5,062,718
15
2
null
2011-02-12 06:14:07.207 UTC
73
2022-06-25 09:40:14.65 UTC
2013-10-05 06:03:31.573 UTC
null
2,235,132
null
389,122
null
1
130
node.js|bash|amazon-ec2|sudo
110,384
<p>Yes, it is a bit annoying but you can fix it with some links:</p> <pre><code>sudo ln -s /usr/local/bin/node /usr/bin/node sudo ln -s /usr/local/lib/node /usr/lib/node sudo ln -s /usr/local/bin/npm /usr/bin/npm sudo ln -s /usr/local/bin/node-waf /usr/bin/node-waf </code></pre> <p>There might be more but that is all I have run across so far. Lack of node-waf will cause some <code>npm</code> installs to fail with a rather cryptic error message.</p>
16,692,647
Why when I insert a DateTime null I have "0001-01-01" in SQL Server?
<p>I try to insert the value null (DateTime) in my database for a field typed 'date' but I always get a <em>'0001-01-01'</em>. I don't understand, this field "allow nulls" and I don't know why I have this default value.</p> <p>I'm using C# asp .net with MVC (Entity Framework), this is my code :</p> <pre><code>Budget_Synthesis newBS = new Budget_Synthesis { Budget_Code = newBudgetCode, Last_Modified_Date = null }; db.Budget_Synthesis.AddObject(newBS); </code></pre> <p>Last_Modified_Date is typed System.DateTime? so I don't know why they change this 'null'.</p> <p>If I try to display the value on my application I get <code>01/01/0001 00:00:00</code></p> <p>And <code>0001-01-01</code> with SSMS</p> <p>Someone can explain me why I can't get a real 'NULL' ?</p> <p>Best regards</p>
16,692,702
5
15
null
2013-05-22 13:08:26.273 UTC
5
2021-08-09 13:01:41.01 UTC
2013-05-22 13:35:27.317 UTC
null
2,377,449
null
2,377,449
null
1
10
c#|sql|sql-server|null|default
52,974
<p>I think this is the value corresponding to the null</p>
12,320,198
R package reshape function melt error: id variables not found in data when working with a lot of factors
<p>I am working with a rarefaction output from <a href="http://www.mothur.org/" rel="noreferrer">mothur</a>, which basically gives me a dataset containing the number of sequences sampled and the number of unique sequences in several samples. I would like to use ggplot2 to visualize this data and therefore need to use <code>melt</code> to go from a <code>wide</code> to a <code>long</code> format. </p> <p>The problem is that I find no way to make this work due to an error of <code>melt</code>. Which basically states </p> <blockquote> <p>Error: id variables not found in data: 1,3,6, (... and so on)</p> </blockquote> <p>Because of the size of the original dataset it would be impractcal to share it here nonetheless one should be able to recreate the same problem using the following code:</p> <pre><code>a&lt;-seq(0,300,3) b&lt;-runif(length(a)) c&lt;-runif(length(a)) d&lt;-as.data.frame(cbind(a,b,c)) d$a&lt;-as.factor(d$a) melt(d,d$a) </code></pre> <p>Which gives exactly the same error:</p> <blockquote> <p>Error: id variables not found in data: 0,3,6,9, (...)</p> </blockquote> <p>I fail to see what I am doing wrong. I am using R 2.15.1 on ubuntu server 12.04. Both the function <code>reshape::melt</code> and <code>reshape2::melt</code> result in the same error.</p>
12,320,266
1
0
null
2012-09-07 14:35:08.153 UTC
2
2017-09-15 02:49:32.313 UTC
2017-09-15 02:49:32.313 UTC
null
7,669,809
null
1,654,947
null
1
20
r|reshape|melt|mothur
38,335
<p>You should use:</p> <pre><code>melt(d, id.vars="a") a variable value 1 0 b 0.019199459 2 3 b 0.693699677 3 6 b 0.937592641 4 9 b 0.299259963 5 12 b 0.485403439 ... </code></pre> <hr> <p>From the help of <code>?melt.data.frame</code>:</p> <blockquote> <p>data<br> data frame to melt</p> <p>id.vars<br> vector of id variables. Can be integer (variable position) or string (variable name)If blank, will use all non-measured variables</p> </blockquote> <p>Thus your <code>id.vars</code> argument should be a character vector of names, e.g. "a" or a numeric vector, e.g. <code>1</code>. The length of this vector should equal the number of columns you want as your id.</p> <p>Instead, you used a factor that contained far more elements than you have columns in your data.</p>
12,127,311
VBA: What happens to Range objects if user deletes cells?
<p>Suppose I have some module in <a href="/questions/tagged/vba" class="post-tag" title="show questions tagged 'vba'" rel="tag">vba</a> with some variable <code>r</code> of type <code>Range</code>. Suppose that, at some point, I store a Range object there (e.g. the active cell). Now my question: What happens to the value of <code>r</code> if the user deletes the cell (the cell, not only its value)?</p> <p>I tried to figure this out in VBA, but without success. The result is strange. <code>r</code> is not <code>Nothing</code>, the value of <code>r</code> is reported to be of type <code>Range</code>, but if I try to look at its properties in the debugger window, each property's value is reported as "object required".</p> <p>How can I, programmatically, determine whether variable <code>r</code> is in this state or not?</p> <p><em>Can I do this without generating an error and catching it?</em></p>
12,127,596
4
3
null
2012-08-26 03:00:56.103 UTC
3
2016-10-29 13:43:40.093 UTC
2012-08-28 01:39:26.583 UTC
null
641,067
null
1,419,315
null
1
30
vba|excel
4,288
<p>Nice question! I've never thought about this before, but this function will, I think, identify a range that was initialzed - is not Nothing - but is now in the "Object Required" state because its cells were deleted:</p> <pre><code>Function RangeWasDeclaredAndEntirelyDeleted(r As Range) As Boolean Dim TestAddress As String If r Is Nothing Then Exit Function End If On Error Resume Next TestAddress = r.Address If Err.Number = 424 Then 'object required RangeWasDeclaredAndEntirelyDeleted = True End If End Function </code></pre> <p>You can test is like this:</p> <pre><code>Sub test() Dim r As Range Debug.Print RangeWasDeclaredAndEntirelyDeleted(r) Set r = ActiveSheet.Range("A1") Debug.Print RangeWasDeclaredAndEntirelyDeleted(r) r.EntireRow.Delete Debug.Print RangeWasDeclaredAndEntirelyDeleted(r) End Sub </code></pre>
12,229,572
PHP generated XML shows invalid Char value 27 message
<p>I am generating XML using PHP library as below:</p> <pre><code>$dom = new DOMDocument("1.0","utf-8"); </code></pre> <p>Doing above results in a page which shows a message on top of the output.</p> <p><strong>This page contains the following errors: error on line 16 at column 274505: PCDATA invalid Char value 27 Below is a rendering of the page up to the first error.</strong></p> <p>I have tried rectifying using Tidy library.. used iconv to get the chinese character in UTF-8.</p>
12,265,956
2
1
null
2012-09-01 16:44:43.643 UTC
17
2021-04-01 10:47:29.15 UTC
2015-12-16 10:17:15.97 UTC
null
569,101
null
1,529,481
null
1
35
php|character-encoding|xml-parsing|runtime-error|tidy
37,766
<blockquote> <p>A useful function to get rid of that error is suggested on this website. <a href="http://www.phpwact.org/php/i18n/charsets#common_problem_areas_with_utf-8">http://www.phpwact.org/php/i18n/charsets#common_problem_areas_with_utf-8</a></p> </blockquote> <p>When you put utf-8 encoded strings in a XML document you should remember that not all utf-8 valid chars are accepted in a XML document <a href="http://www.w3.org/TR/REC-xml/#charsets">http://www.w3.org/TR/REC-xml/#charsets</a></p> <p>So you should strip away the unwanted chars, else you’ll have an XML fatal parsing error such as above</p> <pre><code>function utf8_for_xml($string) { return preg_replace ('/[^\x{0009}\x{000a}\x{000d}\x{0020}-\x{D7FF}\x{E000}-\x{FFFD}]+/u', ' ', $string); } </code></pre> <p>Hope that saves someone else some time..</p>
12,168,002
How to remove the last border of the last cell in UITableView?
<p>In my app, I use a <code>UITableView</code> My problem is that I want to remove the last border of the last cell in <code>UITableView</code>.</p> <p>Please check the following image:</p> <p><img src="https://i.stack.imgur.com/GVJau.png" alt="enter image description here"> </p>
12,168,077
21
1
null
2012-08-28 21:48:25.603 UTC
18
2022-06-08 09:55:19.46 UTC
2017-10-04 04:48:18.78 UTC
null
1,075,341
user2289379
null
null
1
81
iphone|objective-c|ios|xcode|uitableview
57,920
<p>Updated on 9/14/15. My original answer become obsolete, but it is still a universal solution for all iOS versions:</p> <p>You can hide <code>tableView</code>'s standard separator line, and add your custom line at the top of each cell. The easiest way to add custom separator is to add simple <code>UIView</code> of 1px height:</p> <pre><code>UIView* separatorLineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, cell.bounds.size.width, 1)]; separatorLineView.backgroundColor = [UIColor grayColor]; [cell.contentView addSubview:separatorLineView]; </code></pre> <p>To date, I subscribe to <a href="https://stackoverflow.com/a/5377569/1357250">another way</a> for hiding extra separators below cells (works for iOS 6.1+):</p> <pre><code>self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero]; </code></pre>
44,098,709
How can I filter an ArrayList in Kotlin so I only have elements which match my condition?
<p>I have an array:</p> <pre><code>var month: List&lt;String&gt; = arrayListOf("January", "February", "March") </code></pre> <p>I have to filter the list so I am left with only <code>"January"</code>.</p>
44,098,722
6
4
null
2017-05-21 15:40:59.227 UTC
10
2021-05-06 13:50:13.983 UTC
2019-04-16 16:09:16.283 UTC
null
1,000,551
null
7,013,334
null
1
96
list|kotlin|filtering
149,276
<p>You can use this code to filter out January from array, by using this code</p> <pre><code>var month: List&lt;String&gt; = arrayListOf("January", "February", "March") // to get the result as list var monthList: List&lt;String&gt; = month.filter { s -&gt; s == "January" } // to get a string var selectedMonth: String = month.filter { s -&gt; s == "January" }.single() </code></pre>
24,337,657
Wildcard matching in Java
<p>I'm writing a simple debugging program that takes as input simple strings that can contain stars to indicate a wildcard match-any</p> <pre><code>*.wav // matches &lt;anything&gt;.wav (*, a) // matches (&lt;anything&gt;, a) </code></pre> <p>I thought I would simply take that pattern, escape any regular expression special characters in it, then replace any <code>\\*</code> back to <code>.*</code>. And then use a regular expression matcher.</p> <p>But I can't find any Java function to escape a regular expression. The best match I could find is <code>Pattern.quote</code>, which however just puts <code>\Q</code> and <code>\E</code> at the begin and end of the string. </p> <p>Is there anything in Java that allows you to simply do that wildcard matching without you having to implement the algorithm from scratch?</p>
24,337,711
7
6
null
2014-06-21 02:11:31.263 UTC
7
2022-04-18 07:54:15.18 UTC
null
null
null
null
34,509
null
1
14
java|regex|wildcard
44,687
<p><strong>Using A Simple Regex</strong></p> <p>One of this method's benefits is that we can easily add tokens besides <code>*</code> (see <strong>Adding Tokens</strong> at the bottom).</p> <p>Search: <code>[^*]+|(\*)</code></p> <ul> <li>The left side of the <code>|</code> matches any chars that are not a star</li> <li>The right side captures all stars to Group 1</li> <li>If Group 1 is empty: replace with <code>\Q</code> + Match + <code>E</code></li> <li>If Group 1 is set: replace with <code>.*</code></li> </ul> <p>Here is some working code (see the output of the <a href="https://ideone.com/uzw3NZ" rel="noreferrer">online demo</a>).</p> <p>Input: <code>audio*2012*.wav</code></p> <p>Output: <code>\Qaudio\E.*\Q2012\E.*\Q.wav\E</code></p> <pre><code>String subject = "audio*2012*.wav"; Pattern regex = Pattern.compile("[^*]+|(\\*)"); Matcher m = regex.matcher(subject); StringBuffer b= new StringBuffer(); while (m.find()) { if(m.group(1) != null) m.appendReplacement(b, ".*"); else m.appendReplacement(b, "\\\\Q" + m.group(0) + "\\\\E"); } m.appendTail(b); String replaced = b.toString(); System.out.println(replaced); </code></pre> <p><strong>Adding Tokens</strong></p> <p>Suppose we also want to convert the wildcard <code>?</code>, which stands for a single character, by a dot. We just add a capture group to the regex, and exclude it from the matchall on the left: </p> <p>Search: <code>[^*?]+|(\*)|(\?)</code></p> <p>In the replace function we the add something like:</p> <pre><code>else if(m.group(2) != null) m.appendReplacement(b, "."); </code></pre>
38,331,277
How to copy a struct and modify one of its properties at the same time?
<p>If I want to represent my view controller's state as a single struct and then implement an undo mechanism, how would I change, say, one property on the struct and, at the same time, get a copy of the the previous state?</p> <pre><code>struct A { let a: Int let b: Int init(a: Int = 2, b: Int = 3) { self.a = a self.b = b } } let state = A() </code></pre> <p>Now I want a copy of <code>state</code> but with b = 4. How can I do this without constructing a new object and having to specify a value for every property?</p>
66,623,586
5
14
null
2016-07-12 14:09:17.57 UTC
5
2022-05-27 22:02:24.49 UTC
2016-07-12 14:44:49.257 UTC
null
221,683
null
221,683
null
1
31
swift|immutability
20,053
<p>The answers here are ridiculous, especially in case struct's members change.</p> <p>Let's understand how Swift works.</p> <p>When a struct is set from one variable to another, the struct is automatically cloned in the new variable, i.e. the same structs are not related to each other.</p> <pre><code>struct A { let x: Int var y: Int } let a = A(x: 5, y: 10) var a1 = a a1.y = 69 print(&quot;a.y = \(a.y); a1.y = \(a1.y)&quot;) // prints &quot;a.y = 10; a1.y = 69&quot; </code></pre> <p>Keep in mind though that members in struct must be marked as <code>var</code>, not <code>let</code>, if you plan to change them.</p> <p>More info here: <a href="https://docs.swift.org/swift-book/LanguageGuide/ClassesAndStructures.html" rel="nofollow noreferrer">https://docs.swift.org/swift-book/LanguageGuide/ClassesAndStructures.html</a></p> <p>That's good, but if you still want to copy and modify in one line, add this function to your struct:</p> <pre><code>func changing&lt;T&gt;(path: WritableKeyPath&lt;A, T&gt;, to value: T) -&gt; A { var clone = self clone[keyPath: path] = value return clone } </code></pre> <p>Now the example from before changes to this:</p> <pre><code>let a = A(x: 5, y: 10) let a1 = a.changing(path: \.y, to: 69) print(&quot;a.y = \(a.y); a1.y = \(a1.y)&quot;) // prints &quot;a.y = 10; a1.y = 69&quot; </code></pre> <p>I see that adding 'changing' to a lot of struct would be painful, but an extension would be great:</p> <pre><code>protocol Changeable {} extension Changeable { func changing&lt;T&gt;(path: WritableKeyPath&lt;Self, T&gt;, to value: T) -&gt; Self { var clone = self clone[keyPath: path] = value return clone } } </code></pre> <p>Extend your struct with 'Changeable' and you will have your 'changing' function.</p> <p>With the 'changing' function approach, too, any property that you specify in the 'changing' function's call sites (i.e. of type <code>WritableKeyPath</code>) should be marked in the original struct as <code>var</code>, not <code>let</code>.</p>
8,401,812
using Object_id() function with #tables
<p>I want to ensure if a temporary table exists in my database or not.</p> <p>I tried to use <code>OBJECT_ID()</code> function but it seems that I can't use it with temporary tables.</p> <p>How can I resolve this problem?</p>
8,401,854
4
7
null
2011-12-06 14:51:22.283 UTC
1
2011-12-06 14:58:13.54 UTC
2011-12-06 14:55:05.807 UTC
null
27,535
null
632,319
null
1
24
sql|sql-server
38,095
<p>Use</p> <pre><code>OBJECT_ID('tempdb..#foo') </code></pre> <p>to get the id for a temporary table when running in the context of another database.</p>
26,369,046
Push / Pop View Controller With Navigation Bar from View Controller Without Navigation Bar
<p>I'm trying to push a view controller with a visible navigation bar from a view controller with a hidden navigation bar. </p> <p>I tried all sorts of combinations of <code>[[self navigationController] setNavigationBarHidden:YES animated:NO];</code> in viewWillAppear, viewDidAppear, viewWillDisappear... etc. </p> <pre><code>// First View Controller @implementation FirstViewController - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; [[self navigationController] setNavigationBarHidden:YES animated:NO]; NSLog(@"[%@ viewWillAppear]", self); } @end // Second View Controller @implementation SecondViewController - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; [[self navigationController] setNavigationBarHidden:NO animated:NO]; NSLog(@"[%@ viewWillAppear]", self); } @end </code></pre> <p>Nothing worked. I also tried custom code to "animate" a push and pop, which works, BUT I lose the edge swipe and view panning. Before I dig deeper, just want to make sure I'm not reinventing the wheel. </p> <p>The Starbucks app is what I'm trying to mimic. </p> <p>The root view controller of the app (the dark background view) is full screen and notice how it doesn't have a UINavigationBar. But when you tap on one of the buttons, it pushes on a view controller (the light background view) WITH a UINavigationBar. From there, if you tap the "back" arrow, it view controller pops with the navigation bar. Interactive pop swipe gesture also works.</p> <p><img src="https://i.stack.imgur.com/QHPz7.png" alt="Starbucks iOS App"></p>
27,748,007
2
9
null
2014-10-14 19:43:47.92 UTC
8
2015-01-02 22:46:07.26 UTC
2014-10-14 20:27:50.137 UTC
null
1,563,181
null
1,563,181
null
1
18
ios|objective-c|iphone
11,819
<p>It is possible without hacking together a solution by yourself. Here is what you do:</p> <p>Your root viewController:</p> <pre><code>@implementation ViewController .... - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; [self.navigationController setNavigationBarHidden:YES animated:animated]; } @end </code></pre> <p>And the pushed viewController:</p> <pre><code>@implementation SecondViewController - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; [self.navigationController setNavigationBarHidden:NO animated:animated]; } @end </code></pre> <p>This will do. It also keeps the interactive transition working ;)</p> <p>I find it disturbing, however, that this type of functionality is not documented at all by apple. - You can also hide and show toolbars with these 'call-points' (inside viewWillAppear:)</p> <p><strong>EDIT</strong></p> <p>I just realized that this is the same code you wrote in your question. Please test it again. I am 100% sure that this works - I used this functionality in one of my apps, too. <br><br> Please also note that my code does use <code>animated:animated</code> instead of your <code>animated:NO</code>. This may be the crucial point here :)</p>
11,029,444
javax.mail.MessagingException: Could not connect to SMTP host?
<p>following is my code to send mail:</p> <pre><code>import java.util.Properties; import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.Message.RecipientType; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class SendMail { public void sendMail(String m_from,String m_to,String m_subject,String m_body){ try { Session m_Session; Message m_simpleMessage; InternetAddress m_fromAddress; InternetAddress m_toAddress; Properties m_properties; m_properties = new Properties(); m_properties.put("mail.smtp.host", "usdc2spam2.slingmedia.com"); m_properties.put("mail.smtp.socketFactory.port", "465"); m_properties.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory"); m_properties.put("mail.smtp.auth", "true"); m_properties.put("mail.smtp.port", "9000"); m_Session=Session.getDefaultInstance(m_properties,new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("aaaaa","bbbbb@1"); // username and the password } }); m_simpleMessage = new MimeMessage(m_Session); m_fromAddress = new InternetAddress(m_from); m_toAddress = new InternetAddress(m_to); m_simpleMessage.setFrom(m_fromAddress); m_simpleMessage.setRecipient(RecipientType.TO, m_toAddress); m_simpleMessage.setSubject(m_subject); m_simpleMessage.setContent(m_body, "text/html"); //m_simpleMessage.setContent(m_body,"text/plain"); Transport.send(m_simpleMessage); } catch (MessagingException ex) { ex.printStackTrace(); } } public static void main(String[] args) { SendMail send_mail = new SendMail(); String empName = "xxxxx"; String title ="&lt;b&gt;Hi !"+empName+"&lt;/b&gt;"; send_mail.sendMail("[email protected]", "[email protected]", "Please apply for leave for the following dates", title+"&lt;br&gt;by&lt;br&gt;&lt;b&gt;HR&lt;b&gt;"); } } </code></pre> <p>but when i run the code it gives me the following exception.</p> <pre><code>javax.mail.MessagingException: Could not connect to SMTP host: usdc2spam2.slingmedia.com, port: 9000; nested exception is: java.net.ConnectException: Connection refused: connect at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1934) at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:638) at javax.mail.Service.connect(Service.java:317) at javax.mail.Service.connect(Service.java:176) at javax.mail.Service.connect(Service.java:125) at javax.mail.Transport.send0(Transport.java:194) at javax.mail.Transport.send(Transport.java:124) at samples.SendMail.sendMail(SendMail.java:46) at samples.SendMail.main(SendMail.java:55) Caused by: java.net.ConnectException: Connection refused: connect at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.PlainSocketImpl.doConnect(Unknown Source) at java.net.PlainSocketImpl.connectToAddress(Unknown Source) at java.net.PlainSocketImpl.connect(Unknown Source) at java.net.SocksSocketImpl.connect(Unknown Source) at java.net.Socket.connect(Unknown Source) at java.net.Socket.connect(Unknown Source) at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:288) at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:231) at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1900) </code></pre> <p>when i ping this <code>usdc2spam2.slingmedia.com</code> it gives me reply without any problem. I am using <code>windows 7</code></p> <p>Please help me to resolve this.</p>
11,032,290
4
2
null
2012-06-14 08:34:35.07 UTC
3
2017-02-15 11:09:27.543 UTC
null
null
null
null
1,277,859
null
1
8
java|email|servlets
103,237
<p>This is these two lines which was casting me the problem :</p> <pre><code>m_properties.put("mail.smtp.socketFactory.port", "465"); m_properties.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory"); </code></pre> <p>and added this line : </p> <pre><code>m_properties.put("mail.smtp.starttls.enable", "true"); </code></pre> <p>After removing and adding the above lines of code it worked fine.</p>
11,363,676
Will Dart execute isolates in parallel in a multi-core environment?
<h3>Question</h3> <p>Will isolates in Dart run in parallel utilizing all available cores on a multiple core environment, or will it multiplex on a single core?</p> <h3>Background</h3> <p>Google has described <em>isolates</em> (a single-threaded unit of concurrency) in the Dart programming language as a &quot;light weight thread&quot; that operates on the main stack, without blocking.</p> <p>Thus, it seems to me as it will only be able to multiplex on a single core and not be able to run in parallel over multiple cores in a SMP, dualcore, multicore or clustered environment.</p> <p>Though, I can't find any information on this, hence my humble question.</p>
11,364,519
3
3
null
2012-07-06 13:59:25.747 UTC
9
2017-08-21 11:49:26.61 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
150,926
null
1
21
multithreading|parallel-processing|dart|dart-isolates
9,134
<h2>Warning: the code below is out of date and does not work with Dart 1.0.</h2> <h3>Short answer</h3> <p>Maybe.</p> <h3>Long Answer</h3> <p>The <a href="http://www.dartlang.org/docs/library-tour/#dartisolate---concurrency-with-isolates" rel="nofollow noreferrer">dart:isolate library guide</a> states: "<em>Isolates <strong>might</strong> run in a separate process or thread, depending on the implementation. For web applications, isolates can be compiled to Web workers, if they are available.</em>" (my emphasis)</p> <p>Running this code and observing your CPU load will tell you if your implementation does this or not.</p> <pre class="lang-dart prettyprint-override"><code>#import('dart:isolate'); main() { for (var tmp = 0; tmp &lt; 5; ++tmp) { SendPort sendPort = spawnFunction(runInIsolate); sendPort.call(tmp).then((reply) { print(reply); }); } } runInIsolate() { port.receive((msg, SendPort reply) { var k = 0; var max = (5 - msg) * 100000000; for (var i = 0; i &lt; max; ++i) { i = ++i - 1; k = i; } reply.send("I received: $msg and calculated $k"); }); } </code></pre> <p>The standalone dartvm <strong>will</strong> run isolates in parallel, utilizing all available cores. Browser implementations of Dart <em>will likely vary</em> depending on whether Web Workers are implemented or not.</p>
11,213,057
Set default database connection Rails
<p>My rails app has its own MySql database (and requires the mysql2 gem) but also needs to connect with an external MongoDB database for one particular model (and so I've included mongoid and bson_ext in the Gemfile). Now when I try to generate a migration for a new model, it tells me that </p> <pre><code>$ rails g migration CreateLocations error mongoid [not found] </code></pre> <p>When I generated the Location model it included Mongoid::Document, so Rails obviously thinks it is using the external database as my primary datastore.</p> <p>databse.yml:</p> <pre><code>development: adapter: mysql2 encoding: utf8 reconnect: false database: associalize_development pool: 5 username: root password: socket: /tmp/mysql.sock </code></pre> <p>mongoid.yml:</p> <pre><code>development: host: pearl.mongohq.com port: 27019 username: asfasdf password: sadfasdf database: app4574678 test: host: pearl.mongohq.com port: 27019 username: asdfadhasdfa password: hadsadfas database: app4574678 production: host: pearl.mongohq.com port: 27019 username: asdfdfsasda password: afdasdfdasdf database: app4574678 </code></pre> <p><strong>UPDATE</strong> Model that uses Mongo</p> <pre><code>class ExternalMongoModel include Mongoid::Document field :title field :long_title field :deal_type field :merchandise_type field :market_id field :market_name field :market_location, type: Array field :featureType field :country_code field :subtitle field :offer_ends_at field :price field :value field :merchant_type field :content field :merchant index( [[:division_latlon, Mongo::GEO2D]], background: true ) end </code></pre>
12,418,264
3
2
null
2012-06-26 17:46:22.527 UTC
12
2020-11-26 10:03:38.237 UTC
2012-06-26 18:39:56.433 UTC
null
765,357
null
765,357
null
1
24
ruby-on-rails|database|activerecord|mongoid
7,204
<p>Add this to the Application block in <code>config/application.rb</code>:</p> <pre><code>config.generators do |g| g.orm :active_record end </code></pre> <p>(found <a href="https://groups.google.com/forum/?fromgroups=#!topic/mongoid/3yeKEduk0zE" rel="noreferrer">here</a>)</p>
11,038,579
Cross-compiling Node.js for ARM6 (Raspberry Pi)
<p>I'm trying to get node.js v0.7.9 to compile for the raspberry pi, but as node and v8 are quite large, I'm hoping to be able to cross-compile on another more powerful PC. I'm using the linux-x86 <code>arm-bcm2708-linux-gnueabi</code> toolchain from <a href="https://github.com/raspberrypi/tools" rel="noreferrer">https://github.com/raspberrypi/tools</a> and have used them to successfully build other executables for the system. I ended up setting the CC,CXX,CPP,STRIP,OBJCOPY,etc. variables to the toolchain equivalents in the environmental variables and ran configure with: <code>./configure --dest-cpu=arm --without-snapshot</code> to get the final executable. Copying it over to the system and running it however produces the following error:</p> <pre><code>Extension or internal compilation error at line 0. Segmentation fault </code></pre> <p>However, the segmentation fault doesn't happen for any of the non-javascript tasks like <code>node --version</code> and <code>node --help</code>. Are there any CFLAGS/CXXFLAGS I might be missing causing this problem? Bit confused....</p>
12,873,232
7
2
null
2012-06-14 17:49:06.487 UTC
11
2015-02-19 17:36:54.32 UTC
null
null
null
null
108,302
null
1
25
node.js|arm|cross-compiling|v8|raspberry-pi
13,873
<p>I've been working on this a bit since the question was originally asked, even added some patches to help auto-detect cross-compiler settings. Node.js in the repositories is (at the moment) a rather old version, and may or may not support the full hard-float (VFP) architecture.</p> <p>For a full detailed HOWTO, see Nathan Rajlich's write up at <a href="http://n8.io/cross-compiling-nodejs-v0.8/" rel="nofollow">http://n8.io/cross-compiling-nodejs-v0.8/</a></p> <p>I've posted binaries for others who don't want to go through all this hassle for the same hardware at <a href="https://gist.github.com/3245130" rel="nofollow">https://gist.github.com/3245130</a></p>
11,038,590
A way to do multiple statements per bash test && statement
<p>Does anyone know of a way to execute multiple statements within a bash test? So if I use:</p> <pre><code>[[ $Var = 1 ]] &amp;&amp; echo "yes-1" || echo "no-1" </code></pre> <p>And set <code>Var=1</code> then output is: <code>yes-1</code><br> If i set <code>Var=2</code> then output is: <code>no-1</code></p> <p>And this work as I expected. But If i try to add another statement to execute in the mix and it doesn't work:</p> <pre><code>[[ $Var = 1 ]] &amp;&amp; echo "yes-1";echo "yes-2" || echo "no-1";echo "no-2" </code></pre> <p>Which makes sense as bash sees the command ending at; but... this is not what I want.</p> <p>I've tried grouping and evals and functions and have had failures and successes but I'd really just like to do is have this work on one line. Anyone have any ideas? </p>
11,039,851
3
0
null
2012-06-14 17:50:24.783 UTC
11
2012-06-14 19:45:30.633 UTC
2012-06-14 18:23:40.867 UTC
null
236,871
null
34,475
null
1
26
bash
34,832
<p>Simple command grouping should work; the syntax can be a little tricky though.</p> <pre><code>[[ $Var = 1 ]] &amp;&amp; { echo "yes-1"; echo "yes-2"; } || { echo "no-1"; echo "no-2"; } </code></pre> <p>A few things to note:</p> <ol> <li><p>Heed @tvm's advice about using an <code>if-then-else</code> statement if you do anything more complicated.</p></li> <li><p><em>Every</em> command inside the braces needs to be terminated with a semi-colon, even the last one.</p></li> <li><p>Each brace must be separated from the surrounding text by spaces on both sides. Braces don't cause word breaks in <code>bash</code>, so "{echo" is a single word, "{ echo" is a brace followed by the word "echo".</p></li> </ol>
11,161,120
What's the point of MethodImplOptions.InternalCall?
<p>Many methods in the BCL are marked with the <code>[MethodImpl(MethodImplOptions.InternalCall)]</code> attribute. This <a href="http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.methodimploptions.aspx" rel="noreferrer">indicates</a> that the "method is implemented within the common language runtime itself".</p> <p>What was the point of designing the framework in this way over having specified explicit CIL instructions that the runtime would be forced to implement? Ultimately, the attribute is creating contractual obligations for the runtime, but in a way that appears to me to be confusing and not immediately obvious.</p> <p>For example, <code>Math.Pow</code> could have been written this way (excuse my informal mixture of C# + IL and the IL itself if it is bad; this is only a sample to explain my point):</p> <pre><code>public static double Pow(double x, double y) { ldarg.0 ldarg.1 pow // Dedicated CIL instruction ret } </code></pre> <p>instead of the current way:</p> <pre><code>[MethodImpl(MethodImplOptions.InternalCall)] public static double Pow(double x, double y); </code></pre> <p>Why does <code>MethodImplOptions.InternalCall</code> exist?</p>
11,161,727
4
4
null
2012-06-22 17:19:42.707 UTC
6
2021-05-16 18:48:45.88 UTC
null
null
null
null
412,770
null
1
35
.net|clr|cil|framework-design
13,966
<p>I think a big reason is that it's quite hard to create a new IL instruction and it could affect a lot of tools, including external ones (<code>ILGenerator</code>, ilasm, ildasm, PEVerify, Reflector, PostSharp, …).</p> <p>But creating a new <code>InternalCall</code> method? That's almost as simple as writing the method in C# (I assume, I didn't look at Rotor to verify) and it doesn't affect anything.</p> <p>And it's not just about creating it, I think the same applies to maintenance.</p>
11,285,065
Limiting framerate in Three.js to increase performance, requestAnimationFrame?
<p>I was thinking that for some projects I do 60fps is not totally needed. I figured I could have more objects and things that ran at 30fps if I could get it to run smoothly at that framerate. I figured if I edited the requestAnimationFrame shim inside of three.js I could limit it to 30 that way. But I was wondering if there was a better way to do this using three.js itself as provided. Also, will this give me the kind of performance increase I am thinking. Will I be able to render twice as many objects at 30fps as I will at 60? I know the difference between running things at 30 and 60, but will I be able to get it to run at a smooth constant 30fps?</p> <p>I generally use the WebGLRenderer, and fall back to Canvas if needed except for projects that are targeting one specifically, and typically those are webgl shader projects.</p>
11,295,465
5
0
null
2012-07-01 19:39:20.963 UTC
15
2020-04-13 13:06:57.237 UTC
2012-07-01 20:04:49.763 UTC
null
1,137,134
null
1,359,785
null
1
39
javascript|html|canvas|three.js|requestanimationframe
33,792
<p>What about something like this:</p> <pre><code>function animate() { setTimeout( function() { requestAnimationFrame( animate ); }, 1000 / 30 ); renderer.render(); } </code></pre>
11,340,298
Certificate is trusted by PC but not by Android
<p>Since this morning, my certificate is not trusted anymore on Android and then my application cannot connect anymore: </p> <pre><code> Catch exception while startHandshake: javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found. return an invalid session with invalid cipher suite of SSL_NULL_WITH_NULL_NULL javax.net.ssl.SSLPeerUnverifiedException: No peer certificate at org.apache.harmony.xnet.provider.jsse.SSLSessionImpl.getPeerCertificates(SSLSessionImpl.java:137) at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:93) at org.apache.http.conn.ssl.SSLSocketFactory.createSocket(SSLSocketFactory.java:381) at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:165) at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164) at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119) at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360) at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:591) at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:807) at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:781) at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:770) </code></pre> <p>If I try in Google Chrome (on PC) there's no problem and the certificate is trusted but if I try in Chrome browser on Android it tells me the certificate isn't trusted. What can I do?</p>
11,340,510
14
2
null
2012-07-05 08:12:36.707 UTC
31
2018-11-19 09:57:04.237 UTC
2016-12-15 11:59:12.18 UTC
null
165,071
null
507,323
null
1
82
android|ssl-certificate
117,096
<p>You might be missing an intermediate certificate in your cert file. If you have already visited another website which has the same certificate seller, the intermediate certificate is remembered in your browser. This might not - or even better - will not be the case with every visitor to your website. To solve a missing intermediate certificate in the SSL connection, you will need to add the intermediate certificate to your own certificate file.</p> <p>GoDaddy has some info on the intermediate certificates (but the best source is always your certificate provider): <a href="http://support.godaddy.com/help/article/868/what-is-an-intermediate-certificate" rel="noreferrer">http://support.godaddy.com/help/article/868/what-is-an-intermediate-certificate</a></p> <p>I once had this issue of an intermediate cert (with Commodo too) and had to combine my own cert file with the intermediate CA's to work. Once done no errors occurred anymore.</p> <p>Installation instructions per webserver by Godaddy: <a href="http://support.godaddy.com/help/article/5346/installing-an-ssl-server-instructions?locale=en" rel="noreferrer">http://support.godaddy.com/help/article/5346/installing-an-ssl-server-instructions?locale=en</a></p> <p>And here is a list of the most common installation guides by Commodo themselves: <a href="https://support.comodo.com/index.php?/Default/Knowledgebase/Article/View/1145/0/how-do-i-make-my-own-bundle-file-from-crt-files" rel="noreferrer">https://support.comodo.com/index.php?/Default/Knowledgebase/Article/View/1145/0/how-do-i-make-my-own-bundle-file-from-crt-files</a></p> <p>Depending on what webserver you are using, you'll need to specify all certificates (domain certificate, intermediate and root) or combine them into one (eg for Nginx) in the order: </p> <ol> <li>domain certificate</li> <li>intermediate certificate</li> <li>root certificate</li> </ol> <p>An easy way of doing this in an SSH terminal is by typing: </p> <pre><code>cat domainfile intermediatefile rootfile &gt; targetfile </code></pre> <hr> <h3>Certificate test tool</h3> <p>If you encounter further problems or are unsure whether the certificate is correct, please try an online tool to verify your SSL certificate. For instance: networking4all.com/en/ssl+certificates/quickscan </p> <h3>SNI support for android 2.2 and lower</h3> <p>Please note android 2.2 (and probably older) do not support SNI, which allows multiple SSL certificates for different hostnames to work without issues on one single IP address. Thanks to @technyquist for providing that information. Please review <a href="https://stackoverflow.com/questions/5879894/android-ssl-sni-support">this SO question about SNI</a> for more information on this issue.</p>
10,945,643
Correct way of using JQuery-Mobile/Phonegap together?
<p>What is the correct way (to this date) to use JQuery Mobile and Phonegap together?</p> <p>Both frameworks need to load before they can be used. How can I be sure that both are loaded before I can use them?</p>
12,821,151
9
4
null
2012-06-08 08:45:48.79 UTC
88
2015-10-22 19:36:24.273 UTC
2012-06-08 15:05:37.16 UTC
null
609,387
null
1,444,075
null
1
108
jquery|jquery-mobile|cordova
68,045
<p>You can use deferred feature of JQuery.</p> <pre><code>var deviceReadyDeferred = $.Deferred(); var jqmReadyDeferred = $.Deferred(); document.addEventListener("deviceReady", deviceReady, false); function deviceReady() { deviceReadyDeferred.resolve(); } $(document).one("mobileinit", function () { jqmReadyDeferred.resolve(); }); $.when(deviceReadyDeferred, jqmReadyDeferred).then(doWhenBothFrameworksLoaded); function doWhenBothFrameworksLoaded() { // TBD } </code></pre>
13,167,367
CakePHP 2.x Auth with Two Separate Logins
<p>Back in May, I posted <a href="https://stackoverflow.com/questions/10739402/cakephp-auth-component-possible-to-have-two-separate-logins">this question</a>. I'm trying to do the same thing again on a different app, but I haven't found a solution to this problem. I do have more information and better code, so I'm hoping you guys can help me sort this out. </p> <p>Use Case: Doctor's office has a website with admin users. The users login successfully with CakePHP's Auth via <code>User</code> model and <code>UsersController</code>. </p> <p>Doctors have referring physicians with completely different profiles and actions. Doctors need to login via <code>example.com/physicians/login</code>. However, this login is failing with this </p> <p><code>authError =&gt; 'You are not authorized to access that location.'</code></p> <p>Here is my code in <code>AppController</code>: </p> <pre><code>class AppController extends Controller { public $helpers = array('Form', 'Html', 'Time', 'Session', 'Js' =&gt; array('Jquery')); public $components = array( 'Session', 'Auth' =&gt; array( 'autoRedirect' =&gt; false, 'authorize' =&gt; 'Controller' ) ); public function beforeFilter() { $this-&gt;Auth-&gt;allow('index', 'view', 'edit', 'display', 'featured', 'events', 'contact', 'signup', 'search', 'view_category', 'view_archive', 'addComment', 'schedule', 'login'); } </code></pre> <p>}</p> <p>And here is my <code>UsersController</code> that is working: </p> <pre><code>class UsersController extends AppController { public $components = array( 'Auth' =&gt; array( 'authenticate' =&gt; array( 'Form' =&gt; array( 'userModel' =&gt; 'User', 'fields' =&gt; array( 'username' =&gt; 'username', 'password' =&gt; 'password' ) ) ), 'loginRedirect' =&gt; array('controller' =&gt; 'users', 'action' =&gt; 'admin'), 'logoutRedirect' =&gt; array('controller' =&gt; 'pages', 'action' =&gt; 'index'), 'loginAction' =&gt; array('controller' =&gt; 'users', 'action' =&gt; 'login'), 'sessionKey' =&gt; 'Admin' ) ); public function beforeFilter() { parent::beforeFilter(); $this-&gt;Auth-&gt;allow('add', 'login', 'logout'); } function isAuthorized() { return true; } public function login() { if ($this-&gt;request-&gt;is('post')) { if ($this-&gt;Auth-&gt;login()) { $this-&gt;redirect($this-&gt;Auth-&gt;redirect()); } else { $this-&gt;Session-&gt;setFlash(__('Invalid username or password, try again')); } } } public function logout() { $this-&gt;Session-&gt;destroy(); $this-&gt;redirect($this-&gt;Auth-&gt;logout()); } </code></pre> <p>Here is my <code>PhysiciansController</code> code that is NOT working: </p> <pre><code>class PhysiciansController extends AppController { public $components = array( 'Auth' =&gt; array( 'authenticate' =&gt; array( 'Form' =&gt; array( 'userModel' =&gt; 'Physician', 'fields' =&gt; array( 'username' =&gt; 'username', 'password' =&gt; 'password' ) ) ), 'loginRedirect' =&gt; array('controller' =&gt; 'physicians', 'action' =&gt; 'dashboard'), 'logoutRedirect' =&gt; array('controller' =&gt; 'pages', 'action' =&gt; 'index'), 'loginAction' =&gt; array('controller' =&gt; 'physicians', 'action' =&gt; 'login'), 'sessionKey' =&gt; 'Physician' ) ); public function beforeFilter() { parent::beforeFilter(); $this-&gt;Auth-&gt;authorize = array( 'Actions' =&gt; array( 'userModel' =&gt; 'Physician', 'actionPath' =&gt; 'physicians' ) ); $this-&gt;Auth-&gt;allow('login', 'logout'); // $this-&gt;Session-&gt;write('Auth.redirect','/physicians/index'); } function isAuthorized() { return true; } public function login() { if ($this-&gt;request-&gt;is('post')) { if ($this-&gt;Auth-&gt;login()) { $this-&gt;redirect(array('controller' =&gt; 'physicians', 'action' =&gt; 'dashboard')); } else { $this-&gt;Session-&gt;read(); debug($this-&gt;Auth); $this-&gt;Session-&gt;setFlash(__('Invalid username or password, try again')); } } } public function logout() { $this-&gt;Session-&gt;destroy(); $this-&gt;redirect($this-&gt;Auth-&gt;logout()); } </code></pre> <p>I really don't want to start over and switch to ACL -- I'm not sure that's necessary for just two logins. Help would be very much appreciated!</p> <p>EDIT: Joshua's answer below is awesome and super helpful. I implemented it, but I'm still receiving an unauthorized error when I try to login as a Physician via /phys/physican/login (prefix/controller/action). The Admin setup works great. Here's the debug code when I try to login:</p> <pre><code>object(AuthComponent) { components =&gt; array( (int) 0 =&gt; 'Session', (int) 1 =&gt; 'RequestHandler' ) authenticate =&gt; array( 'Form' =&gt; array( 'userModel' =&gt; 'Physician' ) ) authorize =&gt; false ajaxLogin =&gt; null flash =&gt; array( 'element' =&gt; 'default', 'key' =&gt; 'auth', 'params' =&gt; array() ) loginAction =&gt; array( 'controller' =&gt; 'physicians', 'action' =&gt; 'phys_login' ) loginRedirect =&gt; null logoutRedirect =&gt; '/' authError =&gt; 'You are not authorized to access that location.' allowedActions =&gt; array() request =&gt; object(CakeRequest) { params =&gt; array( 'prefix' =&gt; '*****', 'plugin' =&gt; null, 'controller' =&gt; 'physicians', 'action' =&gt; 'phys_login', 'named' =&gt; array(), 'pass' =&gt; array(), 'phys' =&gt; true, '_Token' =&gt; array( 'key' =&gt; 'ad1ea69c3b2c7b9e833bbda03ef18b04079b23c3', 'unlockedFields' =&gt; array() ), 'isAjax' =&gt; false ) data =&gt; array( 'Physician' =&gt; array( 'password' =&gt; '*****', 'username' =&gt; 'deewilcox' ) ) query =&gt; array() url =&gt; 'phys/physicians/login' base =&gt; '' webroot =&gt; '/' here =&gt; '/phys/physicians/login' } response =&gt; object(CakeResponse) { } settings =&gt; array() </code></pre> <p>}</p>
13,168,148
2
0
null
2012-10-31 21:01:51.09 UTC
12
2016-09-20 09:32:45.35 UTC
2017-05-23 11:47:05.547 UTC
null
-1
null
967,773
null
1
12
authentication|cakephp-2.1
14,011
<p>OK I've got a way to do it. You know about prefix routing? If not, read my answer here: <a href="https://stackoverflow.com/questions/11324158/cakephp-mvc-admin-functions-placement/11324496#11324496">CakePHP/MVC Admin functions placement</a> That answer describes how to set up a single routing prefix ('admin'). But you can have any number - just like this:</p> <pre><code>Configure::write('Routing.prefixes', array('admin','phys','member','user')); // now we have admin, phys, member and user prefix routing enabled. </code></pre> <p>What you can do is have all the doctor's methods use 'admin' prefix routing, and all the physicians methods use 'phys' prefix routing.</p> <p>So the below is code I've hacked together pretty quickly, so it might not be perfect but it should show the concept. Here it is in pseudo code for the before filter method of your app controller:</p> <pre><code>if (USER IS TRYING TO ACCESS AN ADMIN PREFIXED METHOD) { Then use the users table for auth stuff } else if (USER IS TRYING TO ACCESS A PHYS PREFIXED METHOD) { Then use the physicians table for auth stuff } else { It's neither an admin method, not a physicians method. So just always allow access. Or always deny access - depending on your site } </code></pre> <p>Here's my app controller code:</p> <pre><code>App::uses('Controller', 'Controller'); class AppController extends Controller { public $components = array('Security','Cookie','Session','Auth','RequestHandler'); public $helpers = array('Cache','Html','Session','Form'); function beforeFilter() { if ($this-&gt;request-&gt;prefix == 'admin') { $this-&gt;layout = 'admin'; // Specify which controller/action handles logging in: AuthComponent::$sessionKey = 'Auth.Admin'; // solution from https://stackoverflow.com/questions/10538159/cakephp-auth-component-with-two-models-session $this-&gt;Auth-&gt;loginAction = array('controller'=&gt;'administrators','action'=&gt;'login'); $this-&gt;Auth-&gt;loginRedirect = array('controller'=&gt;'some_other_controller','action'=&gt;'index'); $this-&gt;Auth-&gt;logoutRedirect = array('controller'=&gt;'administrators','action'=&gt;'login'); $this-&gt;Auth-&gt;authenticate = array( 'Form' =&gt; array( 'userModel' =&gt; 'User', ) ); $this-&gt;Auth-&gt;allow('login'); } else if ($this-&gt;request-&gt;prefix == 'phys') { // Specify which controller/action handles logging in: AuthComponent::$sessionKey = 'Auth.Phys'; // solution from https://stackoverflow.com/questions/10538159/cakephp-auth-component-with-two-models-session $this-&gt;Auth-&gt;loginAction = array('controller'=&gt;'users','action'=&gt;'login'); $this-&gt;Auth-&gt;logoutRedirect = '/'; $this-&gt;Auth-&gt;authenticate = array( 'Form' =&gt; array( 'userModel' =&gt; 'Physician', ) ); } else { // If we get here, it is neither a 'phys' prefixed method, not an 'admin' prefixed method. // So, just allow access to everyone - or, alternatively, you could deny access - $this-&gt;Auth-&gt;deny(); $this-&gt;Auth-&gt;allow(); } } public function isAuthorized($user){ // You can have various extra checks in here, if needed. // We'll just return true though. I'm pretty certain this method has to exist, even if it just returns true. return true; } } </code></pre> <p>Note the lines:</p> <pre><code>AuthComponent::$sessionKey = 'Auth.Admin'; // solution from https://stackoverflow.com/questions/10538159/cakephp-auth-component-with-two-models-session </code></pre> <p>and</p> <pre><code>AuthComponent::$sessionKey = 'Auth.Phys'; // solution from https://stackoverflow.com/questions/10538159/cakephp-auth-component-with-two-models-session </code></pre> <p>What that does is allows a person to be logged in as both a physician, and an admin, in the one browser, without interfering with each other's session. You may not need it in the live site, but it's certainly handy while testing.</p> <p>Now, in you're respective controllers, you'll need straight-forward login/logout methods, with the appropriate prefix.</p> <p>So, for admin prefixing, in your users controller:</p> <pre><code>public function admin_login() { if ($this-&gt;request-&gt;is('post')) { if ($this-&gt;Auth-&gt;login()) { return $this-&gt;redirect($this-&gt;Auth-&gt;redirect()); } else { $this-&gt;Session-&gt;setFlash(__('Username or password is incorrect'), 'default', array(), 'auth'); } } } public function admin_logout() { $this-&gt;Session-&gt;setFlash('Successfully Logged Out'); $this-&gt;redirect($this-&gt;Auth-&gt;logout()); } </code></pre> <p>And in your physicians controller:</p> <pre><code>public function phys_login() { if ($this-&gt;request-&gt;is('post')) { if ($this-&gt;Auth-&gt;login()) { return $this-&gt;redirect($this-&gt;Auth-&gt;redirect()); } else { $this-&gt;Session-&gt;setFlash(__('Username or password is incorrect'), 'default', array(), 'auth'); } } } public function phys_logout() { $this-&gt;Session-&gt;setFlash('Successfully Logged Out'); $this-&gt;redirect($this-&gt;Auth-&gt;logout()); } </code></pre> <p>Like I said, that all code I hacked together pretty quickly, so it might not work verbatim, but it should show the concept. Let me know if you have any questions.</p>
13,059,540
Using Python, reverse an integer, and tell if palindrome
<p>Using Python, reverse an integer and determine if it is a palindrome. Here is my definition of reverse and palindrome. Do I have a correct logic?</p> <pre><code>def reverse(num): s=len(num) newnum=[None]*length for i in num: s=s-1 newnum[s]=i return newnum def palindrome(num): a=str(num) l=len(z)/2 if a[:1]==a[-1:][::-1]: b=True else: b=False </code></pre> <p>I am having some trouble to write <code>def main</code>.</p>
13,059,602
14
4
null
2012-10-24 23:42:44.973 UTC
5
2022-03-29 16:19:54.647 UTC
2016-07-13 20:38:52.65 UTC
null
832,230
null
1,769,897
null
1
19
python|string|list|program-entry-point|function
97,570
<pre><code>def palindrome(num): return str(num) == str(num)[::-1] </code></pre>
12,744,245
How to find the highest number in an array?
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/7442417/how-to-sort-an-array-in-bash">How to sort an array in BASH</a> </p> </blockquote> <p>I have numbers in the array <code>10 30 44 44 69 12 11...</code>. How to display the highest from array?</p> <pre><code>echo $NUM //result 69 </code></pre>
12,744,322
2
2
null
2012-10-05 10:24:03.93 UTC
1
2018-01-31 09:30:48.62 UTC
2018-01-31 09:30:48.62 UTC
null
1,671,066
null
1,518,153
null
1
27
bash
59,657
<p>You can use <code>sort</code> to find out.</p> <pre><code>#! /bin/bash ar=(10 30 44 44 69 12 11) IFS=$'\n' echo "${ar[*]}" | sort -nr | head -n1 </code></pre> <p>Alternatively, search for the maximum yourself:</p> <pre><code>max=${ar[0]} for n in "${ar[@]}" ; do ((n &gt; max)) &amp;&amp; max=$n done echo $max </code></pre>
12,688,503
Jackson - How to specify a single implementation for interface-referenced deserialization?
<p>I want to deserialize a JSON-Object with Jackson. Because the target is an interface I need to specify which implementation should be used.</p> <p>This information could be stored in the JSON-Object, using @JsonTypeInfo-Annotation. But I want to specify the implementation in source code because it's always the same.</p> <p>Is this possible?</p>
12,688,574
3
1
null
2012-10-02 10:19:12.687 UTC
7
2020-05-26 12:55:47.797 UTC
2016-08-24 13:29:55.12 UTC
null
1,055,284
null
946,328
null
1
38
java|json|jackson|deserialization
34,296
<p>Use a <a href="https://fasterxml.github.io/jackson-databind/javadoc/2.4/com/fasterxml/jackson/databind/module/SimpleAbstractTypeResolver.html" rel="noreferrer">SimpleAbstractTypeResolver</a>:</p> <pre><code>ObjectMapper mapper = new ObjectMapper(); SimpleModule module = new SimpleModule("CustomModel", Version.unknownVersion()); SimpleAbstractTypeResolver resolver = new SimpleAbstractTypeResolver(); resolver.addMapping(Interface.class, Implementation.class); module.setAbstractTypes(resolver); mapper.registerModule(module); </code></pre>
13,049,340
Initializing a std::map when the size is known in advance
<p>I would like to initialize a <code>std::map</code>. For now I am using <code>::insert</code> but I feel I am wasting some computational time since I already know the size I want to allocate. Is there a way to allocate a fixed size map and then fill the map ?</p>
13,049,484
5
5
null
2012-10-24 12:35:13.213 UTC
9
2021-06-18 13:42:29.283 UTC
2014-12-28 16:49:12.543 UTC
null
1,373,463
null
1,373,463
null
1
49
c++|dictionary|std
50,722
<p>No, the members of the map are internally stored in a tree structure. There is no way to build the tree until you know the keys and values that are to be stored.</p>
13,115,692
encoding UTF8 does not match locale en_US; the chosen LC_CTYPE setting requires encoding LATIN1
<p>While trying to install opennms :</p> <pre><code>/usr/share/opennms/bin/install -l /usr/local/lib -dis </code></pre> <p>I get the error:</p> <blockquote> <p>ERROR: encoding UTF8 does not match locale en_US Detail: The chosen LC_CTYPE setting requires encoding LATIN1.</p> </blockquote> <p>and I'm not sure how to proceed, as I've tried creating the DB several different ways (see below).</p> <p>Full log:</p> <pre><code>============================================================================== OpenNMS Installer ============================================================================== Configures PostgreSQL tables, users, and other miscellaneous settings. - searching for jicmp: - trying to load /usr/local/lib/libjicmp.so: NO - trying to load /usr/lib/jni/libjicmp.so: OK - searching for jicmp6: - trying to load /usr/local/lib/libjicmp6.so: NO - trying to load /usr/lib/jni/libjicmp6.so: OK - searching for jrrd: - trying to load /usr/local/lib/libjrrd.so: NO - trying to load /usr/lib/jni/libjrrd.so: NO - trying to load /usr/lib/jni/libjrrd.so: NO - trying to load /usr/lib/jvm/jdk1.6.0_34/jre/lib/amd64/server/libjrrd.so: NO - trying to load /usr/lib/jvm/jdk1.6.0_34/jre/lib/amd64/libjrrd.so: NO - trying to load /usr/lib/jvm/jdk1.6.0_34/jre/../lib/amd64/libjrrd.so: NO - trying to load /libjrrd.so: NO - trying to load /usr/share/opennms/lib/libjrrd.so: NO - trying to load /usr/share/opennms/lib/linux64/libjrrd.so: NO - trying to load /usr/java/packages/lib/amd64/libjrrd.so: NO - trying to load /usr/lib64/libjrrd.so: NO - trying to load /lib64/libjrrd.so: NO - trying to load /lib/libjrrd.so: NO - trying to load /usr/lib/libjrrd.so: NO - trying to load /usr/lib/jni/libjrrd.so: NO - trying to load /usr/lib/libjrrd.so: NO - trying to load /usr/local/lib/libjrrd.so: NO - trying to load /opt/NMSjicmp/lib/32/libjrrd.so: NO - trying to load /opt/NMSjicmp/lib/64/libjrrd.so: NO - trying to load /opt/NMSjicmp6/lib/32/libjrrd.so: NO - trying to load /opt/NMSjicmp6/lib/64/libjrrd.so: NO - Failed to load the optional jrrd library. - This error is not fatal, since jrrd is only required for optional features. - For more information, see http://www.opennms.org/index.php/jrrd - using SQL directory... /usr/share/opennms/etc - using create.sql... /usr/share/opennms/etc/create.sql * using 'postgres' as the PostgreSQL user for OpenNMS * using 'opennms' as the PostgreSQL database name for OpenNMS Exception in thread "main" org.opennms.core.schema.MigrationException: an error occurred creating the OpenNMS database at org.opennms.core.schema.Migrator.createDatabase(Migrator.java:428) at org.opennms.core.schema.Migrator.prepareDatabase(Migrator.java:444) at org.opennms.install.Installer.install(Installer.java:236) at org.opennms.install.Installer.main(Installer.java:949) Caused by: org.postgresql.util.PSQLException: ERROR: encoding UTF8 does not match locale en_US Detail: The chosen LC_CTYPE setting requires encoding LATIN1. at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2102) at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1835) at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:257) at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:500) at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:374) at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:366) at org.opennms.core.schema.Migrator.createDatabase(Migrator.java:425) ... 3 more </code></pre> <p>List of databases:</p> <pre><code> Name | Owner | Encoding | Collate | Ctype | Access privileges -----------+----------+----------+---------+-------+----------------------- postgres | postgres | LATIN1 | en_US | en_US | rhq | rhqadmin | LATIN1 | en_US | en_US | template0 | postgres | LATIN1 | en_US | en_US | =c/postgres + | | | | | postgres=CTc/postgres template1 | postgres | LATIN1 | en_US | en_US | =c/postgres + | | | | | postgres=CTc/postgres (4 rows) </code></pre> <p>I have used the following 3 initdb options but none of them work</p> <pre><code>/usr/local/pgsql/bin/initdb -E UTF-8 --pgdata=/usr/local/pgsql/data /usr/local/pgsql/bin/initdb -E LATIN1 --pgdata=/usr/local/pgsql/data /usr/local/pgsql/bin/initdb -E en_US.UTF8 --pgdata=/usr/local/pgsql/data </code></pre> <p>Also, do i need to delete all data in <code>/usr/local/pgsql/data</code> before i use <code>initdb</code> ?</p> <p>appending locale command stdout:</p> <p>$locale</p> <pre><code>LANG=en_US LANGUAGE=en_US: LC_CTYPE="en_US" LC_NUMERIC="en_US" LC_TIME="en_US" LC_COLLATE="en_US" LC_MONETARY="en_US" LC_MESSAGES="en_US" LC_PAPER="en_US" LC_NAME="en_US" LC_ADDRESS="en_US" LC_TELEPHONE="en_US" LC_MEASUREMENT="en_US" LC_IDENTIFICATION="en_US" LC_ALL= </code></pre>
13,115,967
8
5
null
2012-10-29 04:02:39.387 UTC
28
2021-09-25 07:43:47.05 UTC
2012-10-29 04:23:53.217 UTC
null
454,488
null
454,488
null
1
54
postgresql|encoding|opennms
71,057
<p>Thanks for <code>locale</code> output. OpenNMS seems to be using your en_US (non-UTF-8) locale in order to create postgres db, and this is wrong. This should work:</p> <pre><code>export LANG=en_US.UTF-8 locale # confirm that it shows only en_US.UTF-8 for all settings # finally, run your opennms installer /usr/share/opennms/bin/install -l /usr/local/lib -dis </code></pre>
13,002,626
How to Set Variables in a Laravel Blade Template
<p>I'm reading the Laravel Blade <a href="https://laravel.com/docs/master/blade" rel="noreferrer">documentation</a> and I can't figure out how to assign variables inside a template for use later. I can't do <code>{{ $old_section = "whatever" }}</code> because that will echo "whatever" and I don't want that.</p> <p>I understand that I can do <code>&lt;?php $old_section = "whatever"; ?&gt;</code>, but that's not elegant.</p> <p>Is there a better, elegant way to do that in a Blade template?</p>
13,019,365
31
5
null
2012-10-21 22:02:08.483 UTC
67
2022-02-23 11:39:48.07 UTC
2022-02-23 11:39:48.07 UTC
null
6,244
null
291,557
null
1
324
php|laravel|laravel-blade
478,768
<p>It is discouraged to do in a view so there is no blade tag for it. If you do want to do this in your blade view, you can either just open a php tag as you wrote it or register a new blade tag. Just an example:</p> <pre class="lang-php prettyprint-override"><code>&lt;?php /** * &lt;code&gt; * {? $old_section = "whatever" ?} * &lt;/code&gt; */ Blade::extend(function($value) { return preg_replace('/\{\?(.+)\?\}/', '&lt;?php ${1} ?&gt;', $value); }); </code></pre>
12,789,141
Access object properties within object
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/12659792/access-javascript-object-literal-value-in-same-object">Access JavaScript Object Literal value in same object</a> </p> </blockquote> <p>First look at the following JavaScript object </p> <pre><code>var settings = { user:"someuser", password:"password", country:"Country", birthplace:country } </code></pre> <p>I want to set <code>birthplace</code> value same as <code>country</code>, so i put the object value <code>country</code> in-front of <code>birthplace</code> but it didn't work for me, I also used <code>this.country</code> but it still failed. My question is how to access the property of object within object.</p> <p>Some users are addicted to ask "what you want to do or send your script etc" the answer for those people is simple "I want to access object property within object" and the script is mentioned above.</p> <p>Any help will be appreciated :) </p> <p>Regards</p>
12,789,163
2
2
null
2012-10-08 20:41:06.65 UTC
13
2020-02-13 09:16:58.8 UTC
2020-02-13 09:16:58.8 UTC
null
12,409,240
null
1,348,422
null
1
74
javascript|object|properties
55,473
<p>You can't reference an object during initialization when using <em>object literal</em> syntax. You need to reference the object after it is created.</p> <pre><code>settings.birthplace = settings.country; </code></pre> <hr> <p>Only way to reference an object during initialization is when you use a constructor function.</p> <p>This example uses an anonymous function as a constructor. The new object is reference with <code>this</code>.</p> <pre><code>var settings = new function() { this.user = "someuser"; this.password = "password"; this.country = "Country"; this.birthplace = this.country; }; </code></pre>
13,181,725
Append file contents to the bottom of existing file in Bash
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/5586293/shell-script-to-append-text-to-each-file">Shell script to append text to each file?</a><br> <a href="https://stackoverflow.com/questions/6207573/how-to-append-output-to-the-end-of-text-file-in-shell-script">How to append output to the end of text file in SHELL Script?</a> </p> </blockquote> <p>I'm trying to work out the best way to insert api details into a pre-existing config. I thought about using <code>sed</code> to insert the contents of the api text file to the bottom of the config.inc file. I've started the script but it doesn't work and it wipes the file. </p> <pre><code>#!/bin/bash CONFIG=/home/user/config.inc API=/home/user/api.txt sed -e "\$a $API" &gt; $CONFIG </code></pre> <p>What am I doing wrong?</p>
13,181,820
1
0
null
2012-11-01 16:46:34.187 UTC
17
2019-03-18 08:16:48.3 UTC
2019-03-18 08:16:48.3 UTC
null
608,639
null
718,534
null
1
116
bash|sed|awk|append
185,227
<p>This should work:</p> <pre><code> cat "$API" &gt;&gt; "$CONFIG" </code></pre> <p>You need to use the <code>&gt;&gt;</code> operator to append to a file. Redirecting with <code>&gt;</code> causes the file to be overwritten. (truncated).</p>
16,697,721
How to pass HTML to angular directive?
<p>I am trying to create an angular directive with a template, but I also don't want to lose the HTML inside of the div. For example, here is how I would like to call my directive from HTML:</p> <pre><code>&lt;div my-dir&gt; &lt;div class="contents-i-want-to-keep"&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> <p>Then, there is my directive:</p> <pre><code>app.directive('myDir', [ '$compile', function($compile) { return { restrict: 'E', link: function(scope, iElement, iAttrs){ // assigning things from iAttrs to scope goes here }, scope: '@', replace: false, templateUrl: 'myDir.html' }; }]); </code></pre> <p>and then there is myDir.html, where I define a new element:</p> <pre><code>&lt;div class="example" style="background: blue; height: 30px; width: 30px"&gt;&lt;/div&gt; </code></pre> <p>Even when I set replace to false, I lose the inner contents-i-want-to-keep div - my understanding of the angular docs was that this would be appended after my template. Is there some way to preserve this (possibly through my linking function?) so that the result will be</p> <pre><code>&lt;div class="example" style="background: blue; height: 30px; width: 30px"&gt; &lt;div class="contents-i-want-to-keep"&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> <p>Thanks!</p>
16,697,788
1
2
null
2013-05-22 17:08:19.987 UTC
8
2016-11-20 19:37:28.51 UTC
null
null
null
null
1,598,426
null
1
36
angularjs|angularjs-directive
24,824
<p>You'll need to use <a href="https://docs.angularjs.org/api/ng/directive/ngTransclude" rel="noreferrer"><code>ng-transclude</code></a>, add <code>transclude: true</code> in your directive options, and add <code>ng-transclude</code> to your template:</p> <pre><code>&lt;div class="example" style="…" ng-transclude&gt;&lt;/div&gt;` </code></pre> <p>This plunkr has an example on how to use ng-transclude with a template, to keep the original dom element.</p> <p><a href="http://plnkr.co/edit/efyAiTmcKjnhRZMTlNGf" rel="noreferrer">http://plnkr.co/edit/efyAiTmcKjnhRZMTlNGf</a></p>
16,594,904
python list comprehension to produce two values in one iteration
<p>I want to generate a list in python as follows - </p> <pre><code>[1, 1, 2, 4, 3, 9, 4, 16, 5, 25 .....] </code></pre> <p>You would have figured out, it is nothing but <code>n, n*n</code></p> <p>I tried writing such a list comprehension in python as follows - </p> <pre><code>lst_gen = [i, i*i for i in range(1, 10)] </code></pre> <p>But doing this, gives a syntax error. </p> <p>What would be a good way to generate the above list via list comprehension?</p>
16,594,936
13
0
null
2013-05-16 18:33:41.177 UTC
10
2021-07-20 16:37:19.537 UTC
2016-05-21 18:03:09.54 UTC
null
423,105
null
1,629,366
null
1
74
python|list|list-comprehension
46,944
<p>Use <a href="http://docs.python.org/2/library/itertools.html#itertools.chain.from_iterable"><code>itertools.chain.from_iterable</code></a>:</p> <pre><code>&gt;&gt;&gt; from itertools import chain &gt;&gt;&gt; list(chain.from_iterable((i, i**2) for i in xrange(1, 6))) [1, 1, 2, 4, 3, 9, 4, 16, 5, 25] </code></pre> <p>Or you can also use a <a href="http://wiki.python.org/moin/Generators">generator</a> function:</p> <pre><code>&gt;&gt;&gt; def solve(n): ... for i in xrange(1,n+1): ... yield i ... yield i**2 &gt;&gt;&gt; list(solve(5)) [1, 1, 2, 4, 3, 9, 4, 16, 5, 25] </code></pre>
26,753,839
Efficiently getting all divisors of a given number
<p>According to this <a href="https://stackoverflow.com/questions/11995069/finding-factors-of-a-number-not-getting-accurate-results">post</a>, we can get all divisors of a number through the following codes.</p> <pre><code>for (int i = 1; i &lt;= num; ++i){ if (num % i == 0) cout &lt;&lt; i &lt;&lt; endl; } </code></pre> <p>For example, the divisors of number <code>24</code> are <code>1 2 3 4 6 8 12 24</code>.</p> <p>After searching some related posts, I did not find any good solutions. Is there any efficient way to accomplish this?</p> <p>My solution:</p> <ol> <li>Find all prime factors of the given number through this <a href="http://www.geeksforgeeks.org/print-all-prime-factors-of-a-given-number/" rel="noreferrer">solution</a>.</li> <li>Get all possible combinations of those prime factors.</li> </ol> <p>However, it doesn't seem to be a good one.</p>
26,753,963
15
11
null
2014-11-05 09:42:09.677 UTC
26
2021-10-27 20:44:36.08 UTC
2017-05-23 11:33:26.967 UTC
null
-1
null
3,011,380
null
1
61
c++|algorithm|math|factorization
117,587
<p>Factors are paired. <code>1</code> and <code>24</code>, <code>2</code> and <code>12</code>, <code>3</code> and <code>8</code>, <code>4</code> and <code>6</code>. </p> <p>An improvement of your algorithm could be to iterate to the square root of <code>num</code> instead of all the way to <code>num</code>, and then calculate the paired factors using <code>num / i</code>.</p>
9,679,574
Android : Is there any way to change the default language of android to new language?
<p>I'm trying to know whether it is possible to change the default android OS language to other. For which the language is not in the settings for instance: how to set the device 's language to burmese programmatically.</p>
9,866,954
3
4
null
2012-03-13 06:57:18.887 UTC
9
2017-05-10 05:57:46.803 UTC
null
null
null
null
905,230
null
1
6
java|android
15,953
<p>Use this to change the language by programmatically--</p> <pre><code>Locale locale = new Locale("en_US"); Locale.setDefault(locale); Configuration config = new Configuration(); config.locale = locale; context.getApplicationContext().getResources().updateConfiguration(config, null); </code></pre> <p>Write the countrycode of language in place of "en_US" whatever language you want...like for japanese--"ja_JP" For Arabic--"ar" or check this link for code of country--</p> <p><a href="http://code.google.com/apis/igoogle/docs/i18n.html" rel="noreferrer">http://code.google.com/apis/igoogle/docs/i18n.html</a></p> <p>And make a folder in <strong>res/values-ja</strong> for japanese or <strong>res/values-ar</strong> for arabic..</p> <p>And make <strong>string.xml file</strong> And put the languages whatever you want on your layout.. It will fetch the default language from values folder otherwise you want it manually then it will fetch from your external folder values-ar etc. like...</p> <p>Its example of <strong>res/values-ar for arabic</strong>--</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;resources&gt; &lt;string name="spinner_label"&gt;تصفية حسب&lt;/string&gt; &lt;string name="app_name"&gt;2011 فرق&lt;/string&gt; &lt;string name="search"&gt;بحث :&lt;/string&gt; &lt;/resource&gt; </code></pre> <p>Hope It will help you..</p>
10,130,163
Solr Query - HTTP error 404 undefined field text
<p>I've got a Solr instance running on my Ubuntu machine using the default Jetty server that the Solr download comes with. Whenever I start Solr using </p> <blockquote> <p>java -jar start.jar</p> </blockquote> <p>The server starts fine but there is always an exception thrown:</p> <pre><code>INFO: SolrDispatchFilter.init() done Apr 12, 2012 2:01:56 PM org.apache.solr.common.SolrException log SEVERE: org.apache.solr.common.SolrException: undefined field text </code></pre> <p>As I said though, the server will still start and I can see the Solr admin interface. I defined my schema as follows.</p> <pre><code>&lt;fields&gt; &lt;field name="id" type="string" indexed="true" stored="true" /&gt; &lt;field name="phraseID" type="int" indexed="true" stored="true" /&gt; &lt;field name="translation" type="string" indexed="true" stored="true" /&gt; &lt;/fields&gt; &lt;uniqueKey&gt;id&lt;/uniqueKey&gt; </code></pre> <p>I was also able to perform a JSON update - I submitted a sample array of data that was accepted. Up to this point everything is fine.</p> <p>When I attempt to run a query:</p> <pre><code>http://localhost:8983/solr/select/?q=*:*&amp;version=2.2&amp;start=0&amp;rows=10&amp;indent=on </code></pre> <p>It correctly returns all the data that I submitted in my sample earlier.</p> <p>However, the moment I try to query using text, I receive an HTTP ERROR 404.</p> <pre><code>http://localhost:8983/solr/select/?q=fruit&amp;version=2.2&amp;start=0&amp;rows=10&amp;indent=on --- returns --- HTTP ERROR 400 Problem accessing /solr/select/. Reason: undefined field text Powered by Jetty:// </code></pre>
10,130,462
5
0
null
2012-04-12 19:11:18.773 UTC
10
2018-06-05 05:43:43.873 UTC
null
null
null
null
338,632
null
1
24
solr|lucene
30,161
<p>Default solr configuration has defined some request handlers with defaults that match the default schema included in the solr tarball.</p> <p>Check the request handlers defined in solrconfig and you might find that <code>&lt;str name="qf"&gt;</code> and other configuration values include some fields you haven't defined in the schema.</p> <p>Also, check your schema.xml, that the default search field isn't set to <strong>text</strong> like this: <code>&lt;defaultSearchField&gt;text&lt;/defaultSearchField&gt;</code></p>
10,143,682
KnockoutJS subscribe to property changes with Mapping Plugin
<p>Is there anyway I can tell the knockout mapping plugin to subscribe to all property changes call a certain function?</p> <p>I realize I can manually subscribe to the property change event in this manner:</p> <pre><code>var viewModel = { name: ko.observable('foo'), } // subscribe manually here viewModel.name.subscribe(function(newValue){ // do work }) </code></pre> <p>I would like to be able to generically subscribe though, since my view models may vary, I don't want to hardcode the property names. I created a function that does this, but it may not be the best approach. It works over all browsers except IE7 and below.</p> <p>Here I take a viewmodel as an argument and try to reflect on it subscribing to the properties:</p> <pre><code>function subscribeToKO(data) { $.each(data, function (property, value) { if (getType(value) == "Object") data[property] = subscribeToKO(value); else if (getType(value) == "Array") { $.each(value, function (index, item) { item = subscribeToKO(item); }); } else { if (value.subscribe) { value.subscribe(function (newValue) { // do work }); } } }); return data; } </code></pre> <p>Like I said this works, but since I am using the mapping pluging I was hoping there was a hook I could use to provide it with a function that will generically subscribe to property changes.</p> <p>Something like:</p> <pre><code>mapping = { create: function(options){ options.data.subscribe(function(newValue){ // do work ??? }); } } ko.mapping.fromJS(viewModel, mapping); </code></pre> <p>Any ideas?</p>
10,168,203
2
0
null
2012-04-13 15:23:17.757 UTC
8
2013-06-22 09:53:29.763 UTC
null
null
null
null
106,403
null
1
25
jquery|knockout.js|knockout-mapping-plugin
14,920
<p>Here's a generic approach based on <a href="http://www.knockmeout.net/2011/05/creating-smart-dirty-flag-in-knockoutjs.html" rel="nofollow noreferrer">Ryan Niemeyer's dirty flag</a>.<br> Click here for the <a href="http://jsfiddle.net/GQgpX/14/" rel="nofollow noreferrer">JsFiddle</a>.</p> <p>Html:</p> <pre><code>&lt;ol&gt; &lt;li&gt; Telephone : &lt;input data-bind="value: telephone"/&gt; &lt;/li&gt; &lt;li&gt; Address : &lt;input data-bind="value: address"/&gt; &lt;/li&gt; &lt;/ol&gt;​ </code></pre> <p>Javascript:</p> <pre><code>var model = { telephone: ko.observable('0294658963'), address: ko.observable('167 New Crest Rd') }; // knockout extension for creating a changed flag (similar to Ryan's dirty flag except it resets itself after every change) ko.changedFlag = function(root) { var result = function() {}; var initialState = ko.observable(ko.toJSON(root)); result.isChanged = ko.dependentObservable(function() { var changed = initialState() !== ko.toJSON(root); if (changed) result.reset(); return changed; }); result.reset = function() { initialState(ko.toJSON(root)); }; return result; }; // add changed flag property to the model model.changedFlag = new ko.changedFlag(model); // subscribe to changes model.changedFlag.isChanged.subscribe(function(isChanged) { if (isChanged) alert("model changed"); }); ko.applyBindings(model);​ </code></pre>
10,210,742
Run elisp program without Emacs?
<p>elisp is a good language, I find it can handle all kind of jobs, but can I use it like a shell script?</p> <p>i.e. execute some *.el files from the console, without launching Emacs. Or launch Emacs, but don't enter interactive mode.</p>
10,211,087
1
0
null
2012-04-18 13:46:24.923 UTC
13
2019-04-08 23:30:00.03 UTC
2012-05-14 09:24:36.967 UTC
null
324,105
null
531,116
null
1
25
emacs|elisp
3,155
<p>You can most definitely run elisp scripts in Emacs without starting the editor interface.</p> <p>Here are the notes I've made/copied from a few extremely useful Q&amp;As on the subject here at S.O. (and the following two in particular).</p> <ul> <li><a href="https://stackoverflow.com/questions/6238331/#6259330">Emacs shell scripts - how to put initial options into the script?</a></li> <li><a href="https://stackoverflow.com/questions/2879746/#2906967">Idiomatic batch processing of text in Emacs?</a></li> </ul> <p>Much of this information, and more besides, is also covered in the following excellent overview, which is recommended reading:</p> <ul> <li><a href="https://swsnr.de/blog/2014/08/12/emacs-script-pitfalls/" rel="nofollow noreferrer">https://swsnr.de/blog/2014/08/12/emacs-script-pitfalls/</a></li> </ul> <pre class="lang-el prettyprint-override"><code>;;;; Elisp executable scripts ;; --batch vs --script ;; M-: (info "(emacs) Initial Options") RET ;; M-: (info "(elisp) Batch Mode") RET ;; Processing command-line arguments (boiler-plate) ;; http://stackoverflow.com/questions/6238331/#6259330 (and others) ;; ;; For robustness, it's important to both pass '--' as an argument ;; (to prevent Emacs from trying to process option arguments intended ;; for the script), and also to exit explicitly with `kill-emacs' at ;; the end of the script (to prevent Emacs from carrying on with other ;; processing, and/or visiting non-option arguments as files). ;; ;; #!/bin/sh ;; ":"; exec emacs -Q --script "$0" -- "$@" # -*-emacs-lisp-*- ;; (pop argv) ; Remove the "--" argument ;; ;; (setq debug-on-error t) ; if a backtrace is wanted ;; (defun stdout (msg &amp;optional args) (princ (format msg args))) ;; (defun stderr (msg &amp;optional args) (princ (format msg args) ;; #'external-debugging-output)) ;; ;; [script body here] ;; Always exit explicitly. This returns the desired exit ;; status, and also avoids the need to (setq argv nil). ;; (kill-emacs 0) ;; Processing with STDIN and STDOUT via --script: ;; https://stackoverflow.com/questions/2879746/#2906967 ;; ;; #!/bin/sh ;; ":"; exec emacs -Q --script "$0" -- "$@" # -*-emacs-lisp-*- ;; (pop argv) ; Remove the "--" argument ;; (setq debug-on-error t) ; if a backtrace is wanted ;; (defun stdout (msg &amp;optional args) (princ (format msg args))) ;; (defun stderr (msg &amp;optional args) (princ (format msg args) ;; #'external-debugging-output)) ;; (defun process (string) ;; "Reverse STRING." ;; (concat (nreverse (string-to-list string)))) ;; ;; (condition-case nil ;; (let (line) ;; (while (setq line (read-from-minibuffer "")) ;; (stdout "%s\n" (process line)))) ;; (error nil)) ;; ;; ;; Always exit explicitly. This returns the desired exit ;; ;; status, and also avoids the need to (setq argv nil). ;; (kill-emacs 0) </code></pre> <p>Emacs aside, the only other elisp interpreter/compiler I'm aware of is Guile. If you're keen on general coding in elisp, that should be worth a look (especially if performance is a concern).</p>
9,998,691
WPF adorner with controls inside
<p>I am trying to achieve an unusual use of an Adorner. When you mouse-over a RichTextBox, an Adorner (see diagram below) will appear above it, allowing you to add a list of strings to a ListBox contained in the Adorner. This is used for adding "tags" (à la Flickr) to the passage contained in the adorned element.</p> <p><img src="https://i.stack.imgur.com/Py331.png" alt="adorner diagram"> <br /></p> <p><strong>Firstly</strong>: is this even possible?</p> <p>Most examples of Adorners show how to override the Adorner's OnRender method to do trivial things like draw shapes. I was able to use this to render a set of rectangles that creates the gray border of the Adorner, which also resizes automatically if the height of RichTextBox increases due to additional lines text being added while the Adorner is displayed.</p> <pre><code>protected override void OnRender(DrawingContext drawingContext) { SolidColorBrush grayBrush = new SolidColorBrush(); grayBrush.Color = Color.FromRgb(153, 153, 153); // left drawingContext.DrawRectangle(grayBrush, null, new System.Windows.Rect(1, 1, 5, ActualHeight)); // right drawingContext.DrawRectangle(grayBrush, null, new System.Windows.Rect(ActualWidth - 6, 1, 5, ActualHeight)); //bottom drawingContext.DrawRectangle(grayBrush, null, new System.Windows.Rect(1, ActualHeight, ActualWidth - 2, 5)); // for reasons unimportant to this example the top gray bar is rendered as part of the RichTextBox } </code></pre> <p>However, adding controls is slightly more problematic. Generally speaking, WPF's adorner requires adding child controls in code rather than XAML. Using the technique described in <a href="https://stackoverflow.com/questions/8576594/drawingcontext-adorner-possible-to-draw-stackpanel">DrawingContext adorner - possible to draw stackpanel?</a>, I have learned how to add child controls (like a TextBox) to an Adorner without any problem within the Adorner's initializer.</p> <p>The issue, however, is the placement of those controls within the Adorner.</p> <p>If I could create a grid with a gray background and position it at the bottom of the Adorner, I should be good to go. I would assume (hope) that things like automatic resizing of the Adorner based on the changing size of that Grid as tags are added would then happen automatically.</p> <p><strong>In short, assuming this is possible</strong>, can anyone recommend a way of creating this lower tagging control area <em>within</em> the Adorner and positioning it relative to the bottom of Adorner (which may possibly have to resize as the RichTextBox content resizes)?</p>
10,034,274
1
5
null
2012-04-03 17:54:13.303 UTC
21
2015-09-03 04:16:30.52 UTC
2017-05-23 11:33:13.693 UTC
null
-1
null
1,220,221
null
1
26
c#|.net|wpf
34,330
<p>Huzah! With the help of <a href="http://www.linkedin.com/pub/ghenadie-tanasiev/6/85a/532" rel="noreferrer">Ghenadie Tanasiev</a>, I've got an answer.</p> <p>Unlike most controls in WPF, adorners don't have any out-of-the-box way of assigning child elements (such as the controls I wanted to add). Without adding anything to adorners, you can only override their <code>OnRender</code> method and draw stuff within the <code>DrawingContext</code> that gets passed into it. To be honest, this fits probably 99% of use cases for adorners (stuff like creating drag handles around an object), but I needed to add some <em>proper</em> controls to my Adorner.</p> <p>The trick to doing this is to create a <a href="http://msdn.microsoft.com/en-us/library/system.windows.media.visualcollection.aspx" rel="noreferrer"><code>VisualCollection</code></a> and set your adorner as its owner by passing it into the constructor for the collection.</p> <p>This is all described pretty comprehensively in <a href="http://www.switchonthecode.com/tutorials/wpf-tutorial-using-a-visual-collection" rel="noreferrer">this blog article</a>. Unfortunately, my repeated Google searches weren't turning this article up until I knew to search for <code>VisualCollection</code>, thanks to Ghenadie's guidance.</p> <p>This isn't mentioned in the article, but note that it is possible to combine the VisualCollection technique along with drawing in the OnRender method of the adorner. I'm using OnRender to achieve the side and top borders described in my diagram above and using VisualCollection to place and create the controls.</p> <p><strong>Edit:</strong> here is the source code from the mentioned blog post since it is no longer available:</p> <pre><code>public class AdornerContentPresenter : Adorner { private VisualCollection _Visuals; private ContentPresenter _ContentPresenter; public AdornerContentPresenter(UIElement adornedElement) : base(adornedElement) { _Visuals = new VisualCollection(this); _ContentPresenter = new ContentPresenter(); _Visuals.Add(_ContentPresenter); } public AdornerContentPresenter(UIElement adornedElement, Visual content) : this(adornedElement) { Content = content; } protected override Size MeasureOverride(Size constraint) { _ContentPresenter.Measure(constraint); return _ContentPresenter.DesiredSize; } protected override Size ArrangeOverride(Size finalSize) { _ContentPresenter.Arrange(new Rect(0, 0, finalSize.Width, finalSize.Height)); return _ContentPresenter.RenderSize; } protected override Visual GetVisualChild(int index) { return _Visuals[index]; } protected override int VisualChildrenCount { get { return _Visuals.Count; } } public object Content { get { return _ContentPresenter.Content; } set { _ContentPresenter.Content = value; } } } </code></pre>
9,655,410
How to complete a milestone on GitHub?
<p>How do I close/complete milestones on GitHub projects? I've already three milestones that are "overdue" but they are completed already. I simply don't know how to mark them "completed" - can anyone help me?</p> <p>I already tried to Google this issue, and browsed the GitHub help pages, but couldn't find any information on using milestones.</p>
46,929,700
3
3
null
2012-03-11 13:39:32.257 UTC
5
2019-06-21 15:05:59.273 UTC
2019-06-21 15:05:59.273 UTC
null
2,756,409
null
1,260,906
null
1
39
github|milestone
15,119
<p>Milestones are only closed manually. You can close a milestone by clicking the "close" link in the list of milestones. Note that for some reason, there is no "close" button in the milestone's details page, only in the list page of milestones.</p> <p><a href="https://i.stack.imgur.com/wXGNs.png" rel="noreferrer"><img src="https://i.stack.imgur.com/wXGNs.png" alt="Screenshot"></a></p>
9,873,740
How do I change the XSLT debugger's input file?
<p>I'm trying to debug an XSLT file and I've gotten the Visual Studio debugger to run and prompt for an input file. Unfortunately, when I debug the file again, the same test file is loaded from before. </p> <p>How can I change the input file for the XSLT debugger? I've done some searching, but all the help materials assume this is your first run of the debugger.</p>
9,873,863
1
0
null
2012-03-26 14:11:31.44 UTC
4
2016-04-13 18:56:23.327 UTC
2016-04-13 18:56:23.327 UTC
null
247,763
null
247,763
null
1
45
visual-studio|visual-studio-2010|debugging|xslt
8,877
<p>When an XSLT file is the active document in Visual Studio, an <code>Input</code> field becomes available in the properties pane. You can put the path to your XML test file in this field:</p> <p><img src="https://i.stack.imgur.com/2305d.png" alt="enter image description here"></p>
9,823,883
Adding a right click menu to an item
<p>I have been searching for a while for a simple right-click menu for a single item. For example if I right-click on a picture I want a little menu to come up with my own labels: Add, Remove etc. If anyone could help I would be most greatful.</p> <p>Thanks for looking.</p> <p>Here is the completed code:</p> <pre><code> ContextMenu cm = new ContextMenu(); cm.MenuItems.Add("Item 1", new EventHandler(Removepicture_Click)); cm.MenuItems.Add("Item 2", new EventHandler(Addpicture_Click)); pictureBox1.ContextMenu = cm; </code></pre>
9,823,948
5
0
null
2012-03-22 14:06:00.463 UTC
8
2021-08-17 20:38:01.51 UTC
2012-03-22 14:50:15.45 UTC
null
1,007,376
null
1,007,376
null
1
50
c#|winforms|visual-studio|menu|right-click
171,729
<p>Add a contextmenu to your form and then assign it in the control's properties under ContextMenuStrip. Hope this helps :).</p> <p>Hope this helps:</p> <pre><code>ContextMenu cm = new ContextMenu(); cm.MenuItems.Add("Item 1"); cm.MenuItems.Add("Item 2"); pictureBox1.ContextMenu = cm; </code></pre>
10,007,351
Entity Framework Code First AddOrUpdate method insert Duplicate values
<p>I have simple entity:</p> <pre><code>public class Hall { [Key] public int Id {get; set;} public string Name [get; set;} } </code></pre> <p>Then in the <code>Seed</code> method I use <code>AddOrUpdate</code> to populate table:</p> <pre><code>var hall1 = new Hall { Name = "French" }; var hall2 = new Hall { Name = "German" }; var hall3 = new Hall { Name = "Japanese" }; context.Halls.AddOrUpdate( h =&gt; h.Name, hall1, hall2, hall3 ); </code></pre> <p>Then I run in the Package Management Console:</p> <pre><code>Add-Migration Current Update-Database </code></pre> <p>It's all fine: I have three rows in the table "Hall". But if I run in the Package Management Console <code>Update-Database</code> again I have already five rows:</p> <pre><code>Id Name 1 French 2 Japaneese 3 German 4 French 5 Japanese </code></pre> <p>Why? I think it is should be three rows again, not five. I tried to use <code>Id</code> property instead of <code>Name</code> but it does not make the difference.</p> <p><strong>UPDATE:</strong></p> <p>This code produces the same result:</p> <pre><code>var hall1 = new Hall { Id = 1, Name = "French" }; var hall2 = new Hall { Id = 2, Name = "German" }; var hall3 = new Hall { Id = 3, Name = "Japanese" }; context.Halls.AddOrUpdate( h =&gt; h.Id, hall1); context.Halls.AddOrUpdate( h =&gt; h.Id, hall2); context.Halls.AddOrUpdate( h =&gt; h.Id, hall3); </code></pre> <p>Also I have the latest EntityFramework installed via nuget.</p>
15,413,951
13
5
null
2012-04-04 08:19:04.323 UTC
8
2019-12-11 20:10:30.58 UTC
2012-04-05 05:37:21.723 UTC
null
381,804
null
381,804
null
1
60
c#|.net|entity-framework-4
99,154
<p>Ok I was banging my face off the keyboard for an hour with this. If your table's Id field is an Identity field then it won't work so use a different one for identifierExpression. I used the Name property and also removed the Id field from the <code>new Hall {...}</code> initializer. </p> <p>This tweak to the OPs code worked for me so I hope it helps someone: </p> <pre><code>protected override void Seed(HallContext context) { context.Halls.AddOrUpdate( h =&gt; h.Name, // Use Name (or some other unique field) instead of Id new Hall { Name = "Hall 1" }, new Hall { Name = "Hall 2" }); context.SaveChanges(); } </code></pre>
9,654,453
Fatal error: Call to undefined function imap_open() in PHP
<p>I am trying to access my gmail account through my localhost. However, I am getting the response:</p> <blockquote> <p>Fatal error: Call to undefined function imap_open()</p> </blockquote> <p>This is my code:</p> <pre><code>$hostname = '{imap.gmail.com:993/imap/ssl}INBOX'; $username = '[email protected]'; $password = 'mypassword'; /* try to connect */ $inbox = imap_open($hostname,$username,$password) or die('Cannot connect to Gmail: ' .imap_last_error()); </code></pre>
9,654,518
13
0
null
2012-03-11 11:16:47.21 UTC
7
2020-08-20 14:57:49.87 UTC
2019-10-14 17:52:06.81 UTC
null
10,607,772
null
243,796
null
1
65
php|imap
135,472
<p>Simple enough, the IMAP extension is not activated in your PHP installation. It is not <a href="http://php.net/imap.installation">enabled by default</a>. If your local installation is running XAMPP on Windows, you have to enable it as described in the <a href="http://www.apachefriends.org/en/faq-xampp-windows.html#imapphp">XAMPP FAQ</a>:</p> <blockquote> <p>Where is the IMAP support for PHP?</p> <p>As default, the IMAP support for PHP is deactivated in XAMPP, because there were some mysterious initialization errors with some home versions like Windows 98. Who works with NT systems, can open the file <code>"\xampp\php\php.ini"</code> to active the php exstension by removing the beginning semicolon at the line <code>";extension=php_imap.dll"</code>. Should be: <code>extension=php_imap.dll</code></p> <p>Now restart Apache and IMAP should work. You can use the same steps for every extension, which is not enabled in the default configuration.</p> </blockquote>
10,181,729
Should I use single or double colon notation for pseudo-elements?
<p>Since IE7 and IE8 don't support the double-colon notation for pseudo-elements (e.g. <code>::after</code> or <code>::first-letter</code>), and since modern browsers support the single-colon notation (e.g. <code>:after</code>) for backwards compatibility, should I use solely the single-colon notation and when IE8's market share drops to a negligible level go back and find/replace in my code base? Or should I include both:</p> <pre><code>.foo:after, .foo::after { /*styles*/ } </code></pre> <p>Using double alone seems silly if I care about IE8 users (the poor dears).</p>
10,181,948
6
0
null
2012-04-16 21:06:34.237 UTC
19
2018-05-23 13:58:40.093 UTC
2015-04-21 07:55:23.547 UTC
null
106,224
null
749,227
null
1
115
css|internet-explorer-8|css-selectors|internet-explorer-7|pseudo-element
32,987
<p>Do <strong>not</strong> use both combined with a comma. A CSS 2.1 compliant (not CSS3 capable) user agent will ignore the whole rule:</p> <blockquote> <p>When a user agent cannot parse the selector (i.e., it is not valid CSS 2.1), it must ignore the selector and the following declaration block (if any) as well.</p> <p>CSS 2.1 gives a special meaning to the comma (,) in selectors. However, since it is not known if the comma may acquire other meanings in future updates of CSS, the whole statement should be ignored if there is an error anywhere in the selector, even though the rest of the selector may look reasonable in CSS 2.1. </p> </blockquote> <p><a href="http://www.w3.org/TR/CSS2/syndata.html#rule-sets">http://www.w3.org/TR/CSS2/syndata.html#rule-sets</a></p> <p>You could however use</p> <pre><code>.foo:after { /*styles*/ } .foo::after { /*styles*/ } </code></pre> <p>On the other hand this is more verbose than necessary; for now, you can stick with the one-colon notation.</p>
8,221,922
Proper way to exit command line program?
<p>I'm using mac/linux and I know that ctrl-z stops the currently running command in terminal, but I frequently see the process is still running when i check the system monitor. What is the right way to stop a command in terminal? </p> <p>Typically I run into this issue when running python or ruby apps, i'm not sure if that has something to do with it, just thought I would add that.</p>
8,221,984
3
3
null
2011-11-22 04:17:15.293 UTC
5
2011-11-22 04:35:51.133 UTC
null
null
null
null
997,640
null
1
28
unix|terminal
119,605
<p>Using <kbd>control-z</kbd> suspends the process (see the output from <code>stty -a</code> which lists the key stroke under <code>susp</code>). That leaves it running, but in suspended animation (so it is not using any CPU resources). It can be resumed later.</p> <p>If you want to stop a program permanently, then any of interrupt (often <kbd>control-c</kbd>) or quit (often <kbd>control-\</kbd>) will stop the process, the latter producing a core dump (unless you've disabled them). You might also use a HUP or TERM signal (or, if really necessary, the KILL signal, but try the other signals first) sent to the process from another terminal; or you could use <kbd>control-z</kbd> to suspend the process and then send the death threat from the current terminal, and then bring the (about to die) process back into the foreground (<code>fg</code>).</p> <p>Note that all key combinations are subject to change via the <code>stty</code> command or equivalents; the defaults may vary from system to system.</p>
11,811,856
Attach debugger in C# to another process
<p>I'd like to be able to automatically attach a debugger, something like: <code>System.Diagnostics.Debugger.Launch()</code>, except rather than the current process to another named process. I've got a process name and PID to identify the other process.</p> <p>Is this possible?</p>
11,811,881
5
3
null
2012-08-04 20:39:00.953 UTC
11
2021-09-01 11:14:01.177 UTC
null
null
null
null
1,575,281
null
1
21
c#|debugging
25,666
<p><strong>Edit:</strong> <a href="https://stackoverflow.com/a/11812430/1106367"><code>GSerjo</code></a> offered the correct solution. I'd like to share a few thoughts on how to improve it (and an explanation). I hope my improved answer will be useful to to others who experience the same problem.</p> <hr> <h1>Attaching the VS Debugger to a Process</h1> <h2>Manually</h2> <ol> <li>Open the Windows Task Manager (<kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>Esc</kbd>). </li> <li>Go to the Tab <code>Processes</code>.</li> <li>Right click the process.</li> <li>Select <code>Debug</code>.</li> </ol> <p>Or, within Visual Studio, select <code>Debug &gt; Attach to Process...</code>.</p> <p>Results will vary depending on whether you have access to the source code.</p> <h2>Automatically with C#</h2> <blockquote> <p>A <strong>note of caution:</strong> The following code is brittle in the sense that certain values, such as the Visual Studio Version number, are hard-coded. Keep this in mind going forward if you are planning to distribute your program.</p> </blockquote> <p>First of all, add a reference to EnvDTE to your project (right click on the references folder in the solution explorer, add reference). In the following code, I'll only show the unusual using directives; the normal ones such as <code>using System</code> are omitted. </p> <p>Because you are <a href="http://msdn.microsoft.com/en-us/library/ms173185.aspx#sectionToggle2" rel="noreferrer">interacting with COM</a> you need to make sure to decorate your <code>Main</code> method (the entry point of your application) with the <a href="http://msdn.microsoft.com/en-us/library/system.stathreadattribute.aspx" rel="noreferrer"><code>STAThreadAttribute</code></a>.</p> <p>Then, you need to <a href="http://msdn.microsoft.com/en-us/library/ms228772(v=vs.100).aspx#exampleToggle" rel="noreferrer">define the <code>IOleMessageFilter</code> Interface</a> that will allow you to interact with the defined COM methods (note the <a href="http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.comimportattribute.aspx" rel="noreferrer"><code>ComImportAttribute</code></a>). We need to access the message filter so we can retry if the Visual Studio COM component blocks one of our calls.</p> <pre><code>using System.Runtime.InteropServices; [ComImport, Guid("00000016-0000-0000-C000-000000000046"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IOleMessageFilter { [PreserveSig] int HandleInComingCall(int dwCallType, IntPtr hTaskCaller, int dwTickCount, IntPtr lpInterfaceInfo); [PreserveSig] int RetryRejectedCall(IntPtr hTaskCallee, int dwTickCount, int dwRejectType); [PreserveSig] int MessagePending(IntPtr hTaskCallee, int dwTickCount, int dwPendingType); } </code></pre> <p>Now, we need to implement this interface in order to handle incoming messages:</p> <pre><code>public class MessageFilter : IOleMessageFilter { private const int Handled = 0, RetryAllowed = 2, Retry = 99, Cancel = -1, WaitAndDispatch = 2; int IOleMessageFilter.HandleInComingCall(int dwCallType, IntPtr hTaskCaller, int dwTickCount, IntPtr lpInterfaceInfo) { return Handled; } int IOleMessageFilter.RetryRejectedCall(IntPtr hTaskCallee, int dwTickCount, int dwRejectType) { return dwRejectType == RetryAllowed ? Retry : Cancel; } int IOleMessageFilter.MessagePending(IntPtr hTaskCallee, int dwTickCount, int dwPendingType) { return WaitAndDispatch; } public static void Register() { CoRegisterMessageFilter(new MessageFilter()); } public static void Revoke() { CoRegisterMessageFilter(null); } private static void CoRegisterMessageFilter(IOleMessageFilter newFilter) { IOleMessageFilter oldFilter; CoRegisterMessageFilter(newFilter, out oldFilter); } [DllImport("Ole32.dll")] private static extern int CoRegisterMessageFilter(IOleMessageFilter newFilter, out IOleMessageFilter oldFilter); } </code></pre> <p>I defined the return values as constants for better readability and refactored the whole thing a bit to get rid of some of the duplication from the MSDN example, so I hope you'll find it self-explanatory. <code>extern int CoRegisterMessageFilter</code> is our connection to the unmanaged message filter code - you can <a href="http://msdn.microsoft.com/en-us/library/e59b22c5(v=vs.100).aspx" rel="noreferrer">read up on the extern keyword at MSDN</a>.</p> <p>Now all that's left is some code illustrating the usage:</p> <pre><code>using System.Runtime.InteropServices; using EnvDTE; [STAThread] public static void Main() { MessageFilter.Register(); var process = GetProcess(7532); if (process != null) { process.Attach(); Console.WriteLine("Attached to {0}", process.Name); } MessageFilter.Revoke(); Console.ReadLine(); } private static Process GetProcess(int processID) { var dte = (DTE)Marshal.GetActiveObject("VisualStudio.DTE.10.0"); var processes = dte.Debugger.LocalProcesses.OfType&lt;Process&gt;(); return processes.SingleOrDefault(x =&gt; x.ProcessID == processID); } </code></pre>
11,850,970
Blob object to base64 in JavaScript
<p>I am trying to implement a paste handler to get an image from user's clipboard. I want this to run only on Google Chrome, I am not worried with other browsers.</p> <p>This is a part of a method that I found on Internet and I am trying to adapt it.</p> <pre><code>// Get the items from the clipboard var items = e.clipboardData.items; if (items) { // Loop through all items, looking for any kind of image for (var i = 0; i &lt; items.length; i++) { if (items[i].type.indexOf("image") !== -1) { // We need to represent the image as a file, var blob = items[i].getAsFile(); // and use a URL or webkitURL (whichever is available to the browser) // to create a temporary URL to the object var URLObj = window.URL || window.webkitURL; var source = URLObj.createObjectURL(blob); createImage(source); } } } </code></pre> <p>The method works and I can show the image if I use my "source" as the src of a image object. The problem is that the image source in google chrome will be something like this: <code>blob:http://localhost:8080/d1328e65-ade2-45b3-a814-107cc2842ef9</code></p> <p>I need to send this image to the server, so I want to convert it to a base64 version. For example: </p> <pre><code>data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAArgAAAAjCAIAAADwnO7RAAAKMWlDQ1BJQ0MgUHJvZmlsZQAASImdlndUU9kWh8+9N71QkhCKlNBraFICSA29SJEuKjEJEErAkAAiNkRUcERRkaYIMijggKNDkbEiioUBUbHrBBlE1HFwFBuWSWStGd+8ee/Nm98f935rn73P3Wfvfda6AJD8gwXCTFgJgAyhWBTh58WIjYtnYAcBDPAAA2wA4HCzs0IW+EYCmQJ82IxsmRP4F726DiD5+yrTP4zBAP+flLlZIjEAUJiM5/L42VwZF8k4PVecJbdPyZi2NE3OMErOIlmCMlaTc/IsW3z2mWUPOfMyhDwZy3PO4mXw5Nwn4405Er6MkWAZF+cI+LkyviZjg3RJhkDGb+SxGXxONgAoktwu5nNTZGwtY5IoMoIt43kA4EjJX/DSL1jMzxPLD8XOzFouEiSniBkmXFOGjZMTi+HPz03ni8XM...iCIBWnh+P9w9C+9eMzvhCl1iOElK09ruc2wqGhfH/uKEV30FlJkmRZJklydFuW/FdwhYFCkCBBggQJEuS/gWC4FCRIkCBBggQZlmCgECRIkCBBggQZlmCgECRIkCBBggQZFmzhwoXXWoYgQYIECRIkyHUK5vF4rrUMQYIECRIkSJDrFHLktYOCBAkSJEiQIP/NkLt3777WMgT5thLstwoSJEiQ7zxYsEUhyJWxbdu2u++++1pLESRIkCBBvl6Csx6CBAkSJEiQIMPy3dkMOsg3T7A5KkiQIEG+8wQDhSBXTjBQCBIkSJDvPMGuhyBBggQJEiTIsFwXLQr9H6bOjtYeP2mONbOj2Hut9y6/x+nlJSBCQnXkgG3Brh8Q4lqbOpAmPDqUGShex9lPDlfB4sU5I97b/8kuevygYUgYsAksAPg9fkbDQN/e1kNvVw76nfYeiTCG6sjLd5fv58rsFmxRCBIkSJDvPP8f+HtxbDVRPI8AAAAASUVORK5CYII= </code></pre> <p>In the first piece of code I have a blob object representing the file. I have tried a couple of methods but I am not getting the correct representation. How I can use it to create a base64 representation? </p>
11,870,198
1
6
null
2012-08-07 17:20:25.667 UTC
12
2019-01-25 12:59:27.007 UTC
2019-01-25 12:52:34.183 UTC
null
1,287,812
null
1,005,227
null
1
24
javascript|image|google-chrome|base64|blob
34,367
<p>Nick Retallack's answer at this page <a href="https://stackoverflow.com/questions/6333814/how-does-the-paste-image-from-clipboard-functionality-work-in-gmail-and-google-c">How does the paste image from clipboard functionality work in Gmail and Google Chrome 12+?</a> does exactly what I want.</p> <p>So the new piece of code is :</p> <pre><code>var items = e.clipboardData.items; if (items) { // Loop through all items, looking for any kind of image for (var i = 0; i &lt; items.length; i++) { if (items[i].type.indexOf("image") !== -1) { // We need to represent the image as a file, var blob = items[i].getAsFile(); var reader = new FileReader(); reader.onload = function(event){ createImage(event.target.result); //event.target.results contains the base64 code to create the image. }; reader.readAsDataURL(blob);//Convert the blob from clipboard to base64 } } } </code></pre>
11,877,554
Validate hexadecimal string using regular expression
<p>I am validating a string whether it is hexadecimal or not using regular expression. </p> <p>The expression I used is <code>^[A-Fa-f0-9]$</code>. When I using this, the string <code>AABB10</code> is recognized as a valid hexadecimal, but the string <code>10AABB</code> is recognized as invalid.</p> <p>How can I solve the problem?</p>
11,877,685
4
1
null
2012-08-09 06:01:24.747 UTC
1
2022-01-19 11:08:02.59 UTC
2012-08-09 06:08:19.947 UTC
null
1,400,768
null
1,216,216
null
1
30
regex
44,218
<p>You most likely need a <code>+</code>, so <code>regex = '^[a-fA-F0-9]+$'</code>. However, I'd be careful to (perhaps) think about such things as an optional <code>0x</code> at the beginning of the string, which would make it <code>^(0x|0X)?[a-fA-F0-9]+$'</code>.</p>
11,604,914
ContentProvider insert() always runs on UI thread?
<p>I have an app that needs to pull data from a server and insert it into an SQLite database in response to user input. I thought this would be pretty simple - the code that pulls the data from the server is a fairly straightforward subclass of AsyncTask, and it works exactly as I expect it to without hanging the UI thread. I implemented callback functionality for it with a simple interface and wrapped it in a static class, so my code looks like this:</p> <pre><code>MyServerCaller.getFolderContents(folderId, new OnFolderContentsResponseListener() { @Override public void onFolderContentsResponse(final List&lt;FilesystemEntry&gt; contents) { // do something with contents } } </code></pre> <p>All still good. Even if the server takes an hour to retrieve the data, the UI still runs smoothly, because the code in getFolderContents is running in the doInBackground method of an AsyncTask (which is in a separate thread from the UI). At the very end of the getFolderContents method, the onFolderContentsResponse is called and passed the list of FilesystemEntry's that was received from the server. I only really say all this so that it's hopefully clear that my problem is not in the getFolderContents method or in any of my networking code, because it doesn't ever occur there.</p> <p>The problem arises when I try to insert into a database via my subclass of ContentProvider within the onFolderContentsResponse method; the UI always hangs while that code is executing, leading me to believe that despite being called from the doInBackground method of an AsyncTask, the inserts are somehow still running on the UI thread. Here's what the problematic code looks like:</p> <pre><code>MyServerCaller.getFolderContents(folderId, new OnFolderContentsResponseListener() { @Override public void onFolderContentsResponse(final List&lt;FilesystemEntry&gt; contents) { insertContentsIntoDB(contents); } } </code></pre> <p>And the <code>insertContentsIntoDB</code> method:</p> <pre><code>void insertContentsIntoDB(final List&lt;FilesystemEntry&gt; contents) { for (FilesystemEntry entry : contents) { ContentValues values = new ContentValues(); values.put(COLUMN_1, entry.attr1); values.put(COLUMN_2, entry.attr2); // etc. mContentResolver.insert(MyContentProvider.CONTENT_URI, values); } } </code></pre> <p>where mContentResolver has been previously set to the result of the getContentResolver() method.</p> <p>I've tried putting insertContentsIntoDB in its own Thread, like so:</p> <pre><code>MyServerCaller.getFolderContents(folderId, new OnFolderContentsResponseListener() { @Override public void onFolderContentsResponse(final List&lt;FilesystemEntry&gt; contents) { new Thread(new Runnable() { @Override public void run() { insertContentsIntoDB(contents); } }).run(); } } </code></pre> <p>I've also tried running each individual insert in its own thread (the insert method in MyContentProvider is synchronized, so this shouldn't cause any issues there):</p> <pre><code>void insertContentsIntoDB(final List&lt;FilesystemEntry&gt; contents) { for (FilesystemEntry entry : contents) { new Thread(new Runnable() { @Override public void run() { ContentValues values = new ContentValues(); values.put(COLUMN_1, entry.attr1); values.put(COLUMN_2, entry.attr2); // etc. mContentResolver.insert(MyContentProvider.CONTENT_URI, values); } }).run(); } } </code></pre> <p>And just for good measure, I've also tried both of those solutions with the relevant code in the doInBackground method of another AsyncTask. Finally, I've explicitly defined MyContentProvider as living in a separate process in my AndroidManifest.xml:</p> <pre><code>&lt;provider android:name=".MyContentProvider" android:process=":remote"/&gt; </code></pre> <p>It runs fine, but it <strong>still seems to run in the UI thread</strong>. That's the point where I really started tearing my hair out over this, because that doesn't make any sense at all to me. No matter what I do, the UI always hangs during the inserts. Is there any way to get them not to?</p>
11,645,183
4
1
null
2012-07-22 23:44:41.613 UTC
19
2014-03-19 17:08:56.913 UTC
null
null
null
null
897,440
null
1
38
java|android|multithreading|user-interface|android-contentresolver
9,645
<p>Instead of calling <code>mContentResolver.insert()</code>, use <a href="http://developer.android.com/reference/android/content/AsyncQueryHandler.html" rel="noreferrer"><code>AsyncQueryHandler</code></a> and its <a href="http://developer.android.com/reference/android/content/AsyncQueryHandler.html#startInsert%28int,%20java.lang.Object,%20android.net.Uri,%20android.content.ContentValues%29" rel="noreferrer"><code>startInsert()</code></a> method. <code>AsyncQueryHandler</code> is designed to facilitate asynchronous <code>ContentResolver</code> queries.</p>
11,801,071
Git: How to return from 'detached HEAD' state
<p>If one would checkout a branch:</p> <p><code>git checkout 760ac7e</code> </p> <p>from e.g. <code>b9ac70b</code>, how can one go back to the last known head <code>b9ac70b</code> without knowing its SHA1?</p>
11,801,199
6
0
null
2012-08-03 18:11:08.657 UTC
22
2022-03-16 09:28:55.317 UTC
2016-12-13 16:45:18.293 UTC
null
3,257,186
null
359,862
null
1
305
git
158,359
<p>If you remember which branch was checked out before (e.g. <code>master</code>) you could simply</p> <pre><code>git checkout master </code></pre> <p>to get out of <em>detached HEAD</em> state.</p> <p>Generally speaking: <code>git checkout &lt;branchname&gt;</code> will get you out of that.</p> <p>If you don't remember the last branch name, try</p> <pre><code>git checkout - </code></pre> <p>This also tries to check out your last checked out branch.</p>
11,766,554
MVC Html.Partial or Html.Action
<p>I am new to asp.net MVC so please bear with me. I need build a menu that repeats across multiple views. What would better serve the purpose <a href="http://msdn.microsoft.com/en-us/library/ee703423.aspx"><code>Html.Action</code></a> OR <a href="http://msdn.microsoft.com/en-us/library/ee402898.aspx"><code>Html.Partial</code></a>.</p>
11,767,346
2
2
null
2012-08-01 19:52:39.267 UTC
22
2017-12-13 13:22:55.083 UTC
2014-02-24 14:43:56.807 UTC
null
578,411
null
1,110,437
null
1
63
asp.net-mvc|asp.net-mvc-partialview
63,355
<p>Here are what I consider my guidelines on using Html.Action or Html.Partial</p> <p><strong>Html.Partial</strong></p> <ol> <li>Use <code>Html.Partial</code> when you are rendering static content or, </li> <li>If you are going to pass data from the ViewModel that is being sent to the main view</li> </ol> <p><strong>Html.Action</strong></p> <ol> <li>Use <code>Html.Action</code> when you actually need to retrieve additional data from the server to populate the partial view</li> </ol> <p>Basically, if is static, use <code>Html.Partial()</code>. If dynamic, model independent data, use <code>Html.Action()</code>. There are probably more scenarios, but this will give you a good idea of where/how to go. <code>Html.RenderPartial()</code> and <code>Html.RenderAction()</code> are interchangeable for the similarly named functions above. </p>
11,638,861
UISegmentedControl change number of segments programmatically
<p>Is there a way to change the number of segments programmatically?</p>
11,638,968
7
0
null
2012-07-24 20:33:53.133 UTC
7
2020-02-19 10:13:45.92 UTC
2019-11-06 20:28:04.513 UTC
null
5,175,709
null
1,332,384
null
1
81
ios|uikit|uisegmentedcontrol
52,148
<p>Yes, you can use</p> <pre><code>removeSegmentAtIndex:(NSUInteger) animated:(BOOL) </code></pre> <p>And</p> <pre><code>insertSegmentWithTitle:(NSString *) atIndex:(NSUInteger) animated:(BOOL) </code></pre>
19,838,734
Maven -DskipTests ignored
<p>I'm building a Maven project with following <a href="http://maven.apache.org/surefire/maven-surefire-plugin/">SureFire</a> configuration:</p> <pre class="lang-xml prettyprint-override"><code>&lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-surefire-plugin&lt;/artifactId&gt; &lt;version&gt;${version.maven-surefire-plugin}&lt;/version&gt; &lt;configuration&gt; &lt;includes&gt; &lt;include&gt;**/*Test.java&lt;/include&gt; &lt;/includes&gt; &lt;/configuration&gt; &lt;/plugin&gt; </code></pre> <p>Problem is, that when I build it with <code>mvn clean install -DskipTests=true</code>, the tests are still being executed. What could be the problem? </p> <p>I tried both <code>-DskipTests</code>(which is from the <a href="http://maven.apache.org/surefire/maven-surefire-plugin/examples/skipping-test.html">Maven website</a>) and <code>-DskipTests=true</code>, which is added by IntelliJ Idea when I check "skip tests" checkbox.</p> <p>I don't use any Maven <code>settings.xml</code>.</p> <ul> <li>Maven version: 2.2.1</li> <li>Surefire plugin: 2.3</li> </ul> <p><strong>EDIT</strong> If I comment out the SureFire plugin configuration, the parameter behaves as I expect to. What could be the problem with the configuration above?</p>
19,839,375
6
15
null
2013-11-07 14:42:26.877 UTC
9
2022-09-16 01:28:08.893 UTC
2014-12-04 16:34:36.803 UTC
null
254,477
null
2,266,098
null
1
44
java|maven|junit|maven-surefire-plugin
132,516
<p>What you did should work. How to debug this further:</p> <ol> <li><p>Run <code>mvn help:effective-pom</code> to see the whole POM that Maven will execute. Search it for <code>test</code> (case insensitive) to see if there is something odd.</p></li> <li><p>Run <code>mvn test -X</code> to get debug output. This will print the options used to configure the <code>maven-surefire-plugin</code>. Make sure you redirect the output to a file!</p> <p>In the log, you will see</p> <pre><code>[DEBUG] Configuring mojo 'org.apache.maven.plugins:maven-surefire-plugin:2.15:test' with basic configurator --&gt; </code></pre> <p>and then, some lines below that:</p> <pre><code>[DEBUG] (s) runOrder = filesystem [DEBUG] (s) skip = false [DEBUG] (s) skipTests = false </code></pre> <p>These values mean that tests aren't skipped.</p></li> <li><p>Are you using a recent version of the plugin? <a href="http://maven.apache.org/surefire/maven-surefire-plugin/">Check here</a>. Maybe this option wasn't supported for your version.</p></li> </ol>
3,911,400
How to pass 2D array (matrix) in a function in C?
<p>I need to do this to persist operations on the matrix as well. Does that mean that it needs to be passed by reference? </p> <p>Will this suffice?</p> <p><code>void operate_on_matrix(char matrix[][20]);</code></p>
3,912,959
4
0
null
2010-10-12 03:04:23.86 UTC
78
2022-03-20 17:01:18.533 UTC
2015-09-13 17:41:47.29 UTC
null
1,038,379
null
459,184
null
1
86
c|multidimensional-array|parameter-passing
285,383
<p>C does not really have multi-dimensional arrays, but there are several ways to simulate them. The way to pass such arrays to a function depends on the way used to simulate the multiple dimensions:</p> <p>1) Use an array of arrays. This can only be used if your array bounds are fully determined at compile time, or if your compiler supports <a href="http://en.wikipedia.org/wiki/Variable-length_array" rel="noreferrer">VLA's</a>:</p> <pre><code>#define ROWS 4 #define COLS 5 void func(int array[ROWS][COLS]) { int i, j; for (i=0; i&lt;ROWS; i++) { for (j=0; j&lt;COLS; j++) { array[i][j] = i*j; } } } void func_vla(int rows, int cols, int array[rows][cols]) { int i, j; for (i=0; i&lt;rows; i++) { for (j=0; j&lt;cols; j++) { array[i][j] = i*j; } } } int main() { int x[ROWS][COLS]; func(x); func_vla(ROWS, COLS, x); } </code></pre> <p>2) Use a (dynamically allocated) array of pointers to (dynamically allocated) arrays. This is used mostly when the array bounds are not known until runtime.</p> <pre><code>void func(int** array, int rows, int cols) { int i, j; for (i=0; i&lt;rows; i++) { for (j=0; j&lt;cols; j++) { array[i][j] = i*j; } } } int main() { int rows, cols, i; int **x; /* obtain values for rows &amp; cols */ /* allocate the array */ x = malloc(rows * sizeof *x); for (i=0; i&lt;rows; i++) { x[i] = malloc(cols * sizeof *x[i]); } /* use the array */ func(x, rows, cols); /* deallocate the array */ for (i=0; i&lt;rows; i++) { free(x[i]); } free(x); } </code></pre> <p>3) Use a 1-dimensional array and fixup the indices. This can be used with both statically allocated (fixed-size) and dynamically allocated arrays:</p> <pre><code>void func(int* array, int rows, int cols) { int i, j; for (i=0; i&lt;rows; i++) { for (j=0; j&lt;cols; j++) { array[i*cols+j]=i*j; } } } int main() { int rows, cols; int *x; /* obtain values for rows &amp; cols */ /* allocate the array */ x = malloc(rows * cols * sizeof *x); /* use the array */ func(x, rows, cols); /* deallocate the array */ free(x); } </code></pre> <p>4) Use a dynamically allocated VLA. One advantage of this over option 2 is that there is a single memory allocation; another is that less memory is needed because the array of pointers is not required.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;time.h&gt; extern void func_vla(int rows, int cols, int array[rows][cols]); extern void get_rows_cols(int *rows, int *cols); extern void dump_array(const char *tag, int rows, int cols, int array[rows][cols]); void func_vla(int rows, int cols, int array[rows][cols]) { for (int i = 0; i &lt; rows; i++) { for (int j = 0; j &lt; cols; j++) { array[i][j] = (i + 1) * (j + 1); } } } int main(void) { int rows, cols; get_rows_cols(&amp;rows, &amp;cols); int (*array)[cols] = malloc(rows * cols * sizeof(array[0][0])); /* error check omitted */ func_vla(rows, cols, array); dump_array("After initialization", rows, cols, array); free(array); return 0; } void dump_array(const char *tag, int rows, int cols, int array[rows][cols]) { printf("%s (%dx%d):\n", tag, rows, cols); for (int i = 0; i &lt; rows; i++) { for (int j = 0; j &lt; cols; j++) printf("%4d", array[i][j]); putchar('\n'); } } void get_rows_cols(int *rows, int *cols) { srand(time(0)); // Only acceptable because it is called once *rows = 5 + rand() % 10; *cols = 3 + rand() % 12; } </code></pre> <p>(See <a href="https://stackoverflow.com/questions/7343833/srand-why-call-it-only-once/"><code>srand()</code> — why call it only once?</a>.)</p>
3,830,644
Comparing a variable to a range of values
<p>In mathematics, the notation <code>18 &lt; age &lt; 30</code> denotes that age must lie between the values 18 and 30. Is it possible to use this kind of notation in the if statement? For example, I've tried executing </p> <pre><code>if(18 &lt; age &lt; 30) </code></pre> <p>and I get weird output, so it's not quite right. Is there a way to do this or so I simply have to write</p> <pre><code>if(age &gt; 18) /*blah*/; else if(age &lt; 30) /*same blah*/; </code></pre>
3,830,661
7
1
null
2010-09-30 12:55:17.917 UTC
9
2018-02-14 16:47:36.84 UTC
2018-01-02 23:57:37.553 UTC
null
3,980,929
user360907
null
null
1
13
c++
43,163
<p>You can do:</p> <pre><code>if (18 &lt; age &amp;&amp; age &lt; 30) /*blah*/; </code></pre>
3,395,547
How to get a sub array of array in Java, without copying data?
<p>I have some library of classes, working with my data, which is being read into buffer. Is it possible somehow to avoid copying arrays again and again, passing parts of data deeper and deeper into processing methods? Well, it sounds strange, but in my particular case, there's a special writer, which divides data into blocks and writes them individually into different locations, so it just performs System.arraycopy, gets what it needs and calls underlying writer, with that new sub array. And this happens many times. What is the best approach to refactor such code?</p>
3,395,738
9
2
null
2010-08-03 10:17:13.647 UTC
7
2020-08-18 09:55:00.793 UTC
2015-02-18 00:45:35.677 UTC
null
204,665
null
255,667
null
1
51
java|arrays|containers
80,481
<p>Many classes in Java accept a subset of an arrays as parameter. E.g. Writer.write(char cbuf[], int off, int len). Maybe this already suffices for your usecase.</p>
3,568,052
Where to document functions in C or C++?
<p>I have a C program with multiple files, so I have, for example, <code>stuff.c</code> which implements a few functions, and <code>stuff.h</code> with the function prototypes.</p> <p>How should I go about documenting the functions in comments?</p> <p>Should I have all the docs in the header file, all the docs in the <code>.c</code> file, or duplicate the docs for both? I like the latter approach, but then I run into problems where I'll update the docs on one of them and not the other (usually the one where I make the first modification, i.e. if I modify the header file first, then its comments will reflect that, but if I update the implementation, only those comments will change).</p> <p>This question and its answers also apply to C++ code — see also <a href="https://stackoverflow.com/q/4355222">Where should I put documentation comments?</a></p>
3,568,099
10
0
null
2010-08-25 16:20:19.52 UTC
10
2019-11-21 12:47:09.34 UTC
2019-01-04 23:11:59.043 UTC
null
15,168
null
15,055
null
1
46
c|documentation|comments|header-files
18,305
<ul> <li><p>Put the information that people using the functions need to know in the header.</p></li> <li><p>Put the information that maintainers of the functions need to know in the source code.</p></li> </ul>
3,514,076
Special Characters in FPDF with PHP
<p>I have a web form that users can fill out and that content fills up a PDF with FPDF and PHP. When a user enters a word with an apostrophe, a slash appears before it on the PDF.</p> <p>Similarly, special characters like trademark symbols are encoded wrong.</p> <p>The FPDF FAQs say to use:</p> <pre><code>$str = utf8_decode($str); </code></pre> <p>But I'm just not sure how to apply that to the whole PDF. I'm trying to think about it as if it was an HTML page but that isn't helping.</p> <p>Any ideas?</p>
3,569,253
11
0
null
2010-08-18 16:00:37.297 UTC
13
2022-03-07 07:42:18.433 UTC
null
null
null
null
412,106
null
1
37
php|character|fpdf
88,335
<p>Figured this out by doing the following (pagesubtitle is the name of the text field in the form):</p> <pre><code>$reportSubtitle = stripslashes($_POST['pagesubtitle']); $reportSubtitle = iconv('UTF-8', 'windows-1252', $reportSubtitle); </code></pre> <p>Then print it out:</p> <pre><code>$pdf-&gt;Write (6, $reportSubtitle); </code></pre> <p>This will remove any unwanted slashes following apostrophes, as well as use the 'iconv' function to print special characters such as ™</p>
3,700,413
Is Python good enough for big applications?
<p>From the moment I have faced Python, the only thing I can say for it is "It is awesome". I am using Django framework and I am amazed by how quick things happen and how developer friendly this language is. But from many sides I hear that Python is a scripting language, and very useful for small things, experiments etc.</p> <p>So the question is can a big and heavy loaded application be built in Python (and django)? As I mainly focus on web development, examples of such applications could be Stack Overflow, Facebook, Amazon etc.</p> <hr> <p>P.S. According to many of the answers maybe I have to rephrase the question. There are several big applications working with Python (the best example is You Tube) so it can handle them but why then it is not so popular for large projects as (for example) Java, C++ and .NET?</p>
3,702,117
12
4
null
2010-09-13 12:37:02.713 UTC
10
2014-12-10 22:55:49.243 UTC
2014-12-10 22:55:49.243 UTC
null
2,118,055
null
423,283
null
1
24
python|django|web-applications
22,061
<p>Python is a pleasure to work with on big applications. Compared to other enterprise-popular languages you get:</p> <ul> <li>No compilation time, if you ever worked on a large C++ project you know how time consuming this can get</li> <li>A concise and clean syntax that makes reading code easier, also a big time saver when reading someone else's code or even yours when it was written long time ago</li> <li>Portability at the core level, if it's important for your app to run on more than one platform it certainly helps</li> <li>It's fast enough for most things, and when it's not, rewriting hot spots in C is trivial with tools such as Cython and numpy. People advocating against dynamic languages for speed reasons have forgotten the 80-20 rule (or never heard about it). The important thing to consider when choosing a language for a performance-critical application IMHO is how easily you can gain access to the C level when needed, and Python is great for that</li> </ul> <p>It's not a magic language however, you need to use the same techniques used for big projects in other languages: TDD (some may argue that it's more important than in other languages because of the lack of type checking, but that's not a win for other languages, unit tests are <strong>always</strong> important in big projects), clean OO design, etc... or maintaining your application will become a nightmare.</p> <p>The main reason for its lack of acceptance in enterprise compared to .NET, Java et al. is probably not having herds of consultants and "certified specialists" bragging about their tool being the best thing on Earth. I also heard Java was easily accepted because its syntax resembled C++... that may not be such a silly idea considering C# also chose to take this route.</p>
7,767,454
Toast.makeText(...).show() is sometimes misaligned
<p>I am using Toast.makeText to display results from dialogs and having a slightly odd problem: the text is displaying above the frame that should hold it, like this:</p> <p>The message is misaligned with the frame. Please align it better. [<strong><em>_</em>__<em>_</em>__<em>_</em>__<em>_</em>__<em>_</em>__<em>_</em>__<em>_</em>__<em>_</em>__<em>_</em>__<em>_</em>__<em>_</em>__<em>_</em>__<em>_</em>__<em>_</em>__<em>_</em>__<em>_</em>___</strong>]</p> <p>I'm generally using code looking like</p> <pre><code>Toast bread = Toast.makeText(getContext(), R.string.message, Toast.LENGTH_LONG); bread.show(); </code></pre> <p>from a dialog. I've heard bad context can sometimes cause inflation problems but <code>getOwnerActivity()</code> is returning null, so that's out. In any case, I would have thought getContext() would supply the context passed in at construction time, which is the activity anyway.</p> <p>Any suggestions?</p>
7,767,488
4
1
null
2011-10-14 12:19:11.047 UTC
2
2015-06-13 21:46:06.33 UTC
2015-06-13 21:46:06.33 UTC
null
4,370,109
null
808,808
null
1
5
android|alignment|toast|android-context
39,394
<p>you can try this:</p> <pre><code>Toast bread = Toast.makeText(getApplicationContext(), R.string.message, Toast.LENGTH_LONG); bread.show(); </code></pre>
8,079,942
Proper technique to add listeners to DOM created via an XTemplate?
<p>We use XTemplates - lots of XTemplates. They are great for displaying read-only content. But have you ever added (Ext JS) listeners to DOM created via a template? Would you care to share your preferred technique for creating these listeners?</p>
8,081,472
4
1
null
2011-11-10 13:06:17.26 UTC
9
2019-11-01 20:39:05.497 UTC
2019-11-01 20:39:05.497 UTC
null
4,370,109
null
213,113
null
1
14
javascript|templates|extjs|dom-events
10,813
<p>My preferred technique is using the analog of <code>$.live</code> function from jquery. F.i. let's assume you are going to use xtemplate for creating simple list like the following: </p> <pre><code>&lt;ul class="nav"&gt; &lt;li&gt;&lt;a href="example.com"&gt;item1&lt;/a&gt;&lt;/li&gt; &lt;!-- ... --&gt; &lt;/ul&gt; </code></pre> <p>To assign handler to the anchors you would do in jquery something like: </p> <pre><code>$('.nav a').live('click', function(){ // do something on anchor click }); </code></pre> <p>The <code>$.live</code> function is great because it would work even if handler assignation would happen before list rendering. This fact is extremely important when you use xtemplate.</p> <p>Fortunately there is analog in ExtJs - delegating events. Just look at the code:</p> <pre><code>Ext.getBody().on('click', function(event, target){ // do something on anchor click }, null, { delegate: '.nav a' }); </code></pre> <p>For more info take a look at <a href="http://docs.sencha.com/ext-js/4-0/#!/api/Ext.Element-method-addListener" rel="noreferrer">docs</a> for the <code>Ext.Element.addListener</code> method.</p>
8,240,329
SOLR Case Insensitive Search
<p>I've a problem in SOLR Search. <br>I have a data like this:<br> <img src="https://i.stack.imgur.com/gCYkl.jpg" alt="enter image description here"></p> <p>I use solr admin to find this data using query like this:</p> <pre><code>address_s:*Nadi* </code></pre> <p>and found those data. But when I use this query:</p> <pre><code>address_s:*nadi* </code></pre> <p>it doesn't found anything.<br>I've googling and I found an answer to create a field with the following script:</p> <pre><code>&lt;fieldType name="c_text" class="solr.TextField"&gt; &lt;analyzer type="index"&gt; &lt;tokenizer class="solr.WhitespaceTokenizerFactory"/&gt; &lt;filter class="solr.LowerCaseFilterFactory"/&gt; &lt;/analyzer&gt; &lt;analyzer type="query"&gt; &lt;tokenizer class="solr.WhitespaceTokenizerFactory"/&gt; &lt;filter class="solr.LowerCaseFilterFactory"/&gt; &lt;/analyzer&gt; &lt;/fieldType&gt; </code></pre> <p>I've copy paste those script into schema.xml, but it still doesn't work. What should I do? Can anyone help me?</p>
8,242,648
5
0
null
2011-11-23 10:06:37.96 UTC
5
2016-05-02 16:11:57.76 UTC
2011-11-23 10:13:15.137 UTC
null
73,652
null
1,040,934
null
1
18
solr|case-insensitive
57,137
<p>The address_s field should be defined as - </p> <pre><code>&lt;field name="address_s" type="c_text" indexed="true" stored="true"/&gt; </code></pre> <p>If you are using the default schema.xml, this defination should come before - </p> <pre><code>&lt;dynamicField name="*_s" type="string" indexed="true" stored="true"/&gt; </code></pre> <p>which defines it as a string field type with no analysis performed.</p> <p>Wildcard queries does not undergo analysis.<br> So if you apply lower case filter at index time query <code>address_s:*nadi*</code> would work.<br> However, query <code>address_s:*Nadi</code>* would not, as <code>Nadi</code> will not match <code>nadi</code> in index and you would need to lower case the queries at client side. </p>
7,736,781
How to make git log not prompt to continue?
<p>I have a couple of git repositories that belong together, and simple batch/bash file to loop over them. I often loop over them with a log command to quickly see what state they are in. This works nicely, except for one thing: if the commit message is longer than the number of characters my console is wide (or has multiple lines), git shows the line, then a newline with (END) and I have to press <em>q</em> to continue (I guess it pipes the output through <em>more</em> or something like that). Example:</p> <pre><code>&gt; gitloop . "git log --decorate=short --pretty=oneline -n1" 18629ae238e9d5832cb3535ec88274173337a501 (HEAD, origin/master, master) short log 625fb891b9b0b8648459b07ace662ae3b7773c7f (HEAD, origin/master, origin/HEAD, master) short log dc0838118266ba8570ea338c1faddfe8af0387bb (HEAD, origin/work, origin/master, work, master) oops loooooooooooooong log -(END) </code></pre> <p>This is rather inconvenient as I have to press <em>q</em> a couple of time, whereas I'd just like to see all those oneliners in one go.</p> <p>How can I disable this behaviour (preferrably while still keeping this log format)?</p>
7,737,071
6
2
null
2011-10-12 07:45:19.46 UTC
21
2022-08-30 11:26:16.007 UTC
null
null
null
null
128,384
null
1
141
git
65,631
<p>Git has an option to disable the pager:</p> <pre><code>git --no-pager log --decorate=short --pretty=oneline -n1 </code></pre> <p>If your pager cuts lines and you want to retain that behaviour, either pipe to <code>cut</code>...</p> <pre><code>git --no-pager log --decorate=short --pretty=oneline -n1 | cut -c 1-$COLUMNS </code></pre> <p>...or set the environment variable <code>GIT_PAGER</code> before the invocation:</p> <pre><code>GIT_PAGER=&quot;cut -c 1-${COLUMNS-80}&quot; git log --decorate=short --pretty=oneline -n1 </code></pre>
7,798,748
Find out whether Chrome console is open
<p>I am using this little script to find out whether Firebug is open:</p> <pre><code>if (window.console &amp;&amp; window.console.firebug) { //is open }; </code></pre> <p>And it works well. Now I was searching for half an hour to find a way to detect whether Google Chrome's built-in web developer console is open, but I couldn't find any hint.</p> <p>This:</p> <pre><code>if (window.console &amp;&amp; window.console.chrome) { //is open }; </code></pre> <p>doesn't work.</p> <p>EDIT:</p> <p>So it seems that it is not possible to detect whether the Chrome console is open. But there is a "<a href="https://stackoverflow.com/questions/7527442/how-to-detect-chrome-inspect-element-is-running-or-not">hack</a>" that works, with some drawbacks:</p> <ul> <li>will not work when console is undocked</li> <li>will not work when console is open on page load</li> </ul> <p>So, I am gonna choose Unsigned´s answer for now, but if some1 comes up with a brilliant idea, he is welcome to still answer and I change the selected answer! Thanks!</p>
7,809,413
24
7
null
2011-10-17 19:47:25.013 UTC
122
2022-09-04 23:45:58.31 UTC
2017-05-23 12:34:39.053 UTC
null
-1
null
668,190
null
1
188
javascript|google-chrome|firebug|google-chrome-devtools
139,591
<h2>requestAnimationFrame (Late 2019)</h2> <p>Leaving these previous answers here for historical context. Currently <a href="https://stackoverflow.com/a/48287643/629493">Muhammad Umer's approach</a> works on Chrome 78, with the added advantage of detecting both close and open events.</p> <h2>function toString (2019)</h2> <p>Credit to <a href="https://stackoverflow.com/users/3734569/overcl9ck">Overcl9ck</a>'s comment on this answer. Replacing the regex <code>/./</code> with an empty function object still works.</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>var devtools = function() {}; devtools.toString = function() { if (!this.opened) { alert("Opened"); } this.opened = true; } console.log('%c', devtools); // devtools.opened will become true if/when the console is opened</code></pre> </div> </div> </p> <h2>regex toString (2017-2018)</h2> <p>Since the original asker doesn't seem to be around anymore and this is still the accepted answer, adding this solution for visibility. Credit goes to <a href="https://stackoverflow.com/users/84283">Antonin Hildebrand</a>'s <a href="https://stackoverflow.com/questions/7798748/find-out-whether-chrome-console-is-open/7809413#comment62884356_30638226">comment</a> on <a href="https://stackoverflow.com/users/1068602/zswang">zswang</a>'s <a href="https://stackoverflow.com/a/30638226/629493">answer</a>. This solution takes advantage of the fact that <code>toString()</code> is not called on logged objects unless the console is open.</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>var devtools = /./; devtools.toString = function() { if (!this.opened) { alert("Opened"); } this.opened = true; } console.log('%c', devtools); // devtools.opened will become true if/when the console is opened</code></pre> </div> </div> </p> <h2>console.profiles (2013)</h2> <p><strong>Update:</strong> <code>console.profiles</code> has been removed from Chrome. This solution no longer works.</p> <p>Thanks to <a href="https://stackoverflow.com/users/89484">Paul Irish</a> for pointing out this solution from <a href="http://discover-devtools.codeschool.com/chapters/1/challenges/1" rel="noreferrer">Discover DevTools</a>, using the profiler:</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>function isInspectOpen() { console.profile(); console.profileEnd(); if (console.clear) { console.clear(); } return console.profiles.length &gt; 0; } function showIfInspectIsOpen() { alert(isInspectOpen()); }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;button onClick="showIfInspectIsOpen()"&gt;Is it open?&lt;/button&gt;</code></pre> </div> </div> </p> <h2>window.innerHeight (2011)</h2> <p>This other option can detect the docked inspector being <em>opened, after</em> the page loads, but will not be able to detect an undocked inspector, or if the inspector was already open on page load. There is also some potential for false positives.</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>window.onresize = function() { if ((window.outerHeight - window.innerHeight) &gt; 100) { alert('Docked inspector was opened'); } }</code></pre> </div> </div> </p>
4,736,622
Microsoft Charting, MVC 3 and Razor
<p>Related to <a href="https://stackoverflow.com/questions/319835/new-asp-net-charting-controls-will-they-work-with-mvc-eventually#320891">This topic</a> I wonder if anyone has made the Microsoft Charting library working with Asp MVC 3 and Razor.</p> <p>I know about the new chart helper introduced, but since that is very limited that is not really an option.</p> <p>To create an action method that returns an image is also easy enough, but since all interactivity breaks down (even just simple tooltips for the bars in a bar chart) this method has several limitations.</p> <p><a href="http://www.codecapers.com/post/Build-a-Dashboard-With-Microsoft-Chart-Controls.aspx#tb" rel="nofollow noreferrer">This example</a> is probably the most helpful article I have found, but I still cant get a single easy chart working even though it does work when rendering the image only in an action method. Also I have got the samples working fine under .net 4, but obviously those arent MVC samples.</p> <p>SO - has anyone got Microsoft charting working fully in Asp MVC 3 with Razor and could post a link to a complete solution?</p>
5,137,720
3
0
null
2011-01-19 14:50:33.69 UTC
15
2012-09-23 04:40:03.463 UTC
2017-05-23 12:00:06.737 UTC
null
-1
null
121,262
null
1
35
c#|asp.net-mvc|charts|asp.net-mvc-3|mschart
25,497
<p>If it is tool tip and drill down you are looking for then here is a sample. I tried and worked as a charm for me. You need to have ImageMap linked with your image to have interactivity.</p> <p><a href="http://geekswithblogs.net/DougLampe/archive/2011/01/23/charts-in-asp.net-mvc-2-with-drill-down.aspx" rel="noreferrer">MVC Charts with Interactivity</a></p>
14,518,300
TypeError: 'undefined' is not an object (evaluating '$.browser.msie')
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/14505301/jquery-latest-browser">jQuery latest $.browser</a> </p> </blockquote> <p>There was an error with jQuery 1.9 and $.browser; It returns 'undefined' for any $.browser; function. What i did wrong?</p> <blockquote> <p>TypeError: 'undefined' is not an object (evaluating '$.browser.msie')</p> </blockquote> <p>I use following code:</p> <pre><code>setTimeout(function(){if($.browser.msie){$('.ovy').animate({top:"0"},ct); </code></pre>
14,518,318
3
0
null
2013-01-25 08:50:24.253 UTC
2
2015-01-05 06:12:05.083 UTC
2017-05-23 12:16:41.837 UTC
null
-1
null
1,730,252
null
1
6
jquery
40,139
<p><code>$.browser</code> have been <a href="http://jquery.com/upgrade-guide/1.9/#jquery-browser-removed">removed from 1.9</a>. You can use <a href="https://github.com/jquery/jquery-migrate/">jQuery Migrate</a> to have <code>$.browser</code> support.</p>
4,182,794
In maven, what is the difference between main/resources and main/config?
<p>I want to put a configuration file in my Maven project. Looking at <a href="http://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html" rel="noreferrer">the standard directory layout</a>, there are two places that seem sensible, "<code>src/main/resources</code>" and "<code>src/main/config</code>". Could someone explain the difference between these, and explain when you would put something in <code>config</code> and when in <code>resources</code>?</p> <p>In this case, the file I'm looking at is <code>ehcache.xml</code>, but my question isn't ehcache specific, I'm curious for <code>log4j.properties</code> etc.</p> <p>A bit of googling discovered <a href="http://maven.40175.n5.nabble.com/Porpuse-of-src-main-config-td124167.html" rel="noreferrer">this person had the same question</a>, but the answers seemed contradictory, and not very authorative.</p>
4,183,095
4
2
null
2010-11-15 09:02:42.07 UTC
10
2016-04-29 00:15:11.39 UTC
2010-12-08 09:53:06.007 UTC
null
5,346
null
5,346
null
1
47
maven-2
19,658
<p>The email exchange at <a href="http://www.mail-archive.com/[email protected]/msg90985.html" rel="noreferrer">http://www.mail-archive.com/[email protected]/msg90985.html</a> says: </p> <p>"<em>This is all theory... Perhaps while writing the docs, someone involved with Maven development thought it might be useful to have a src/main/config directory and so it was included in docs, but since it was never implemented in the code, it is not being used today.</em>"</p> <p>and</p> <p>"<em>The directory</em> [src/main/config] <em>doesn't show up on the classpath so the application or test classes can't read anything in it.</em>"</p> <p>So just use <code>src/main/resources</code>.</p> <p>Note: I don't know if this is true (I'm the question asker), but that would explain why so many people on the web recommend <code>src/main/resources</code> for log4j.properties. If people agree this is the right answer could you let me know (comment or vote) I put it here to save other people the typing.</p>
4,641,962
Getting an option text/value with JavaScript
<p><strong>Answer</strong>: <code>var option_user_selection = element.options[element.selectedIndex].text</code></p> <p>I am trying to build a form that fills in a person's order.</p> <pre><code>&lt;form name="food_select"&gt; &lt;select name="maincourse" onchange="firstStep(this)"&gt; &lt;option&gt;- select -&lt;/option&gt; &lt;option text="breakfast"&gt;breakfast&lt;/option&gt; &lt;option text="lunch"&gt;lunch&lt;/option&gt; &lt;option text="dinner"&gt;dinner&lt;/option&gt; &lt;/select&gt; &lt;/form&gt; </code></pre> <p>What I'm trying to do is send in the select object, pull the name and the text/value from the option menu AND the data in the option tag. </p> <pre><code>function firstStep(element) { //Grab information from input element object /and place them in local variables var select_name = element.name; var option_value = element.value; } </code></pre> <p>I can get the name and the option value, but I can't seem to get the text="" or the value="" from the select object. I only need the text/value from the option menu the user selected. I know I can place them in an array, but that doesn't help</p> <pre><code>var option_user_selection = element.options[ whatever they select ].text </code></pre> <p>I also need to use the passed in select reference as that is how it's set up in the rest of my code. </p> <p>Later on, that text/value is going to be used to pull the XML document that will populate the next select form dynamically. </p>
4,641,968
4
5
null
2011-01-09 21:31:46.843 UTC
6
2015-12-15 19:44:51.253 UTC
2014-12-20 10:45:05.603 UTC
null
4,186,297
null
185,672
null
1
61
javascript|html|forms|html-select
129,501
<p>You can use:</p> <pre><code>var option_user_selection = element.options[ element.selectedIndex ].text </code></pre>
4,158,900
Embedding resources in executable using GCC
<p>I'm looking for a way to easily embed any external binary data in a C/C++ application compiled by GCC.</p> <p>A good example of what I'd like to do is handling shader code - I can just keep it in source files like <code>const char* shader = "source here";</code> but that's extremely impractical.</p> <p>I'd like the compiler to do it for me: upon compilation (linking stage), read file "foo.bar" and link its content to my program, so that I'd be able to access the contents as binary data from the code.</p> <p>Could be useful for small applications which I'd like to distribute as a single .exe file.</p> <p>Does GCC support something like this?</p>
4,158,997
6
1
null
2010-11-11 20:21:30.52 UTC
44
2022-09-01 13:48:05.073 UTC
2014-01-30 15:47:10.68 UTC
null
608,639
null
399,317
null
1
77
c++|c|gcc|resources|embedded-resource
41,307
<p>There are a couple possibilities:</p> <ul> <li><p>use ld's capability to turn any file into an object (<a href="https://stackoverflow.com/questions/2627004/embedding-binary-blobs-using-gcc-mingw">Embedding binary blobs using gcc mingw</a>):</p> <pre><code>ld -r -b binary -o binary.o foo.bar # then link in binary.o </code></pre></li> <li><p>use a <code>bin2c</code>/<code>bin2h</code> utility to turn any file into an array of bytes (<a href="https://stackoverflow.com/questions/225480/embed-image-in-code-without-using-resource-section-or-external-images/225658#225658">Embed image in code, without using resource section or external images</a>)</p></li> </ul> <hr> <p>Update: Here's a more complete example of how to use data bound into the executable using <code>ld -r -b binary</code>:</p> <pre><code>#include &lt;stdio.h&gt; // a file named foo.bar with some example text is 'imported' into // an object file using the following command: // // ld -r -b binary -o foo.bar.o foo.bar // // That creates an bject file named "foo.bar.o" with the following // symbols: // // _binary_foo_bar_start // _binary_foo_bar_end // _binary_foo_bar_size // // Note that the symbols are addresses (so for example, to get the // size value, you have to get the address of the _binary_foo_bar_size // symbol). // // In my example, foo.bar is a simple text file, and this program will // dump the contents of that file which has been linked in by specifying // foo.bar.o as an object file input to the linker when the progrma is built extern char _binary_foo_bar_start[]; extern char _binary_foo_bar_end[]; int main(void) { printf( "address of start: %p\n", &amp;_binary_foo_bar_start); printf( "address of end: %p\n", &amp;_binary_foo_bar_end); for (char* p = _binary_foo_bar_start; p != _binary_foo_bar_end; ++p) { putchar( *p); } return 0; } </code></pre> <hr> <p>Update 2 - Getting the resource size: I could not read the _binary_foo_bar_size correctly. At runtime, gdb shows me the right size of the text resource by using <code>display (unsigned int)&amp;_binary_foo_bar_size</code>. But assigning this to a variable gave always a wrong value. I could solve this issue the following way: </p> <pre><code>unsigned int iSize = (unsigned int)(&amp;_binary_foo_bar_end - &amp;_binary_foo_bar_start) </code></pre> <p>It is a workaround, but it works good and is not too ugly.</p>
4,670,247
Concat strings by & and + in VB.Net
<p>Is there any difference between &amp; and + operators while concatenating string? if yes, then what is difference? And if No, then why below code generating exception?</p> <p>Example:</p> <pre><code> Dim s, s1, t As String Dim i As Integer s1 = "Hello" i = 1 s = s1 &amp; i t = s1 + i //Exception here If s = t Then MessageBox.Show("Equal...") End If </code></pre>
4,670,326
8
5
null
2011-01-12 15:04:13.953 UTC
3
2021-03-29 18:14:57.813 UTC
2011-01-12 15:14:02.107 UTC
null
180,239
null
479,468
null
1
24
vb.net|concatenation
121,525
<p>&amp; and + are both concatenation operators but when you specify an integer while using +, vb.net tries to cast "Hello" into integer to do an addition. If you change "Hello" with "123", you will get the result 124.</p>
4,644,470
From command line, how to know which Firefox version is installed in windows/linux?
<p>I need to know which Firefox version is installed on my system from command line of Windows or Linux.</p>
4,644,565
8
0
null
2011-01-10 07:11:00.797 UTC
3
2021-08-25 17:30:02.853 UTC
2014-02-18 23:57:46.537 UTC
null
321,731
null
533,530
null
1
27
firefox|command-line
66,589
<p>According to <a href="https://developer.mozilla.org/en/Command_Line_Options#-v_or_-version" rel="noreferrer">this link</a>, it seems that the <code>-v</code> argument (and more) is broken on Windows. If you follow the bug link on the site, it seems there is a workaround. I quote the comment:</p> <blockquote> <p>Workaround (works with Firefox, Thunderbird, and, I suppose, other programs too):</p> <pre><code>&lt;program-name&gt; -h | more </code></pre> <p>The bug happens because, without redirection, the program releases its stdout before handling the -help parameter. With redirection, stdout is not released and you can see the output.</p> </blockquote> <p>So for example for Firefox:</p> <pre><code>C:\Program Files (x86)\Mozilla Firefox&gt;firefox -v | more Mozilla Firefox 3.6.13, Copyright (c) 1998 - 2010 mozilla.org </code></pre> <p>It works for me at least. Without <code>| more</code> I get nothing printed. On Linux it works with or without the piping.</p>
4,626,812
How do I instantiate a Queue object in java?
<p>When I try:</p> <pre><code>Queue&lt;Integer&gt; q = new Queue&lt;Integer&gt;(); </code></pre> <p>The compiler is giving me an error. Any help?</p> <p>Also, if I want to initialize a queue do I have to implement the methods of the queue?</p>
4,626,830
8
2
null
2011-01-07 15:02:18.013 UTC
43
2021-10-29 14:38:36.78 UTC
2021-10-29 14:38:36.78 UTC
null
330,776
null
330,776
null
1
160
java|data-structures|queue
364,949
<p>A <code>Queue</code> is an interface, which means you cannot construct a <code>Queue</code> directly.</p> <p>The best option is to construct off a class that already implements the <code>Queue</code> interface, like one of the following: <code>AbstractQueue</code>, <code>ArrayBlockingQueue</code>, <code>ArrayDeque</code>, <code>ConcurrentLinkedQueue</code>, <code>DelayQueue</code>, <code>LinkedBlockingQueue</code>, <code>LinkedList</code>, <code>PriorityBlockingQueue</code>, <code>PriorityQueue</code>, or <code>SynchronousQueue</code>.</p> <p>An alternative is to write your own class which implements the necessary Queue interface. It is not needed except in those rare cases where you wish to do something special while providing the rest of your program with a <code>Queue</code>.</p> <pre><code>public class MyQueue&lt;T extends Tree&gt; implements Queue&lt;T&gt; { public T element() { ... your code to return an element goes here ... } public boolean offer(T element) { ... your code to accept a submission offer goes here ... } ... etc ... } </code></pre> <p>An even less used alternative is to construct an anonymous class that implements <code>Queue</code>. You probably don't want to do this, but it's listed as an option for the sake of covering all the bases.</p> <pre><code>new Queue&lt;Tree&gt;() { public Tree element() { ... }; public boolean offer(Tree element) { ... }; ... }; </code></pre>
4,185,638
Solving the Visual Studio 2010 AlwaysCreate rebuild issue
<p>I've a C++ project that I'm currently porting from VS2008 to VS2010. When I build the project, Visual Studio 2010 reports the build as successful but if I then press F5 to start the debugger I'm told that the project is not up to date. If I ignore this warning, I can continue debugging ok, but if I press ok, the whole project (many hundreds of source files), gets rebuilt from scratch. The output contains the following;</p> <pre><code>1&gt;------ Build started: Project: SCCW-VC2010, Configuration: Debug Win32 ------ 1&gt;Build started 15/11/2010 14:47:40. 1&gt;InitializeBuildStatus: 1&gt; Creating &quot;Debug\SCCW-VC2010.unsuccessfulbuild&quot; because &quot;AlwaysCreate&quot; was specified. 1&gt;Midl: 1&gt; All outputs are up-to-date. 1&gt;ClCompile: 1&gt; tinedit.cpp 1&gt; _WIN32_WINNT not defined. Defaulting to _WIN32_WINNT_MAXVER (see WinSDKVer.h) 1&gt; Automatically linking with sfl504d.lib 1&gt; Automatically linking with ot1104d.lib 1&gt;c:\program files\rogue wave\stingray studio 10.4\include\toolkit\sectndlg.h(134): warning C4996: 'strcpy': This function or variable may be unsafe. Consider using strcpy_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details. 1&gt; c:\program files\microsoft visual studio 10.0\vc\include\string.h(105) : see declaration of 'strcpy' 1&gt; Automatically linking with og1204d.lib 1&gt; Automatically linking with RWUXThemeD10.lib 1&gt; profile.cpp 1&gt; ZOffsetDialog.cpp </code></pre> <p>Half an hour later, once the build is finished, the debugger starts. My guess is that the message</p> <p><strong>Creating &quot;Debug\SCCW-VC2010.unsuccessfulbuild&quot; because &quot;AlwaysCreate&quot; was specified.</strong></p> <p>is part of the problem, but I cant tie this to a project setting. I've found <a href="https://web.archive.org/web/20120623104219/http://connect.microsoft.com:80/VisualStudio/feedback/details/574245/alwayscreate-needs-documentation-or-vs10-fix" rel="nofollow noreferrer">some help on google</a>, but nothing that has worked thus far. Anyone else had this problem and know of a fix?</p> <p><strong>Edit:</strong> As per Jalf's suggestion in the comments below, I have created a new projected, imported all my files into that project, and the new project has the same problems. Specifically, I copied over all the following groups;</p> <pre><code>&lt;ClCompile Include=&quot;..\MyDir\MyFile.cpp&quot;/&gt; &lt;ClInclude Include=&quot;..\MyDir\MyFile.h&quot; /&gt; &lt;None Include=&quot;res\MyFile.ico&quot; /&gt; (and all similar resources) &lt;Library Include=&quot;..\MyDir\MyFile.lib&quot; /&gt; </code></pre> <p><strong>Edit2:</strong> After going through all the header includes I eventually found 3 that did not exist. Removing them and doing a rebuild all on the original project seems to have fixed the problem. Some of the blog posts that mention this problem refer to it as a bug, and two days of lost time later, I tend to agree. Thanks for the answers and comments provided.</p> <p><strong>Edit3:</strong> And one day later the problem is back! Making any edit to any file in the project once again causes a full rebuild. As per John Dibling's answer, the project does include some static libraries, including Stingray. I'm ditching VS2010 and moving back to VS2008, as I have deadlines. For related information, see the following links;</p> <p><a href="https://stackoverflow.com/questions/2762930/vs2010-always-thinks-project-is-out-of-date-but-nothing-has-changed">Visual Studio 2010 always thinks project is out of date, but nothing has changed</a></p> <p><a href="http://social.msdn.microsoft.com/Forums/en-US/vcgeneral/thread/38c08137-3bb0-4143-b97f-72d077646318" rel="nofollow noreferrer">http://social.msdn.microsoft.com/Forums/en-US/vcgeneral/thread/38c08137-3bb0-4143-b97f-72d077646318</a></p> <p><a href="https://docs.microsoft.com/en-us/archive/blogs/vsproject/enable-c-project-system-logging" rel="nofollow noreferrer">Link</a></p> <p><strong>Final Edit</strong> The release of VS2010 SP1 has solved this problem, and builds are now fast and efficient.</p>
4,185,742
11
7
null
2010-11-15 15:05:26.093 UTC
7
2022-02-20 09:02:49.783 UTC
2022-02-20 09:02:49.783 UTC
null
4,751,173
null
22,564
null
1
20
c++|visual-studio-2010|build
39,314
<p>I've had this problem many times and it was always frustrating. I'll tell you what the problem was in my case, but first I have to ask you:</p> <ul> <li>Did you do a rebuild-all before you tried running the first time, or just a rebuild?</li> <li>Once you do a rebuild all, does it ask you yet again to rebuild if you've made no changes?</li> </ul> <p>The problem in my case was somewhat complex. I had custom build rules that copies binaries for Stingray from their source directory (where they lived) to a directory in my build tree. The binaries were marked as a dependancy, so that they were copied before each build in case they changed.</p> <p>The dependancy checked looked at the timestamps of these files to see when they were changed. If the <code>blah.lib</code> had a mod date of last December in it's source directory, then when it was copied it would have the same mod date. The dependancy checked would note that "hey this file's pretty old, we have to rebuild it," and then it would ask if I wanted to do a full rebuild.</p> <p>For a while I got by by just saying "No," but eventually I fixed the problem by changing the custom build rule to write a new text file after it did the file copy. That would make the new text file the dependancy, and not the <code>blah.lib</code> file, and it made the compiler happy.</p>
14,802,807
compare file's date bash
<p>I'm working on a tiny dropbox-like bash script, how can I compare the dates of 2 files and replace the old one(s) with the new one without using <strong>rsync</strong> is there any simple way to process this? can the <strong>SHA1</strong> help me with knowing the newer?</p>
14,802,843
4
3
null
2013-02-10 21:31:27.137 UTC
5
2018-07-27 09:31:26.953 UTC
2018-07-27 09:31:26.953 UTC
null
8,344,060
null
1,484,092
null
1
49
linux|bash|centos
41,895
<p>You can compare file modification times with <code>test</code>, using <code>-nt</code> (newer than) and <code>-ot</code> (older than) operators:</p> <pre><code>if [ "$file1" -ot "$file2" ]; then cp -f "$file2" "$file1" fi </code></pre>
14,429,321
How to check if a defined constant exists in PHP?
<p>So I'm using a PHP framework called <strong>fuelphp</strong>, and I have this page that is an <strong>HTML</strong> file, so I can't use PHP in it. I have another file that has a top bar in it, which my HTML file will call through ajax. </p> <p>How do I check if a constant exists in PHP?<br> I want to check for the the fuelphp framework file locations.</p> <p>These are the constants I need to check for (actually, I only have to check one of them):</p> <pre><code>define('DOCROOT', __DIR__.DIRECTORY_SEPARATOR); define('APPPATH', realpath(__DIR__.'/fuel/app/').DIRECTORY_SEPARATOR); define('PKGPATH', realpath(__DIR__.'/fuel/packages/').DIRECTORY_SEPARATOR); define('COREPATH', realpath(__DIR__.'/fuel/core/').DIRECTORY_SEPARATOR); require APPPATH.'bootstrap.php'; </code></pre> <p><strong>edit:</strong><br /> I realized that these aren't variables they are constants...</p>
14,429,347
6
12
null
2013-01-20 21:05:19.53 UTC
6
2020-10-23 21:39:47.423 UTC
2020-10-23 07:15:04.773 UTC
null
1,718,491
null
1,823,190
null
1
81
php|if-statement|constants|fuelphp
100,538
<p>First, these are not variables, but constants.</p> <p>And you can check their existence by using the <a href="http://php.net/manual/fr/function.defined.php" rel="noreferrer"><code>defined()</code></a> function :</p> <pre><code>bool defined ( string $name ) </code></pre> <blockquote> <p>Checks whether the given constant exists and is defined.</p> </blockquote>
14,782,232
How to avoid 'cannot read property of undefined' errors?
<p>In my code, I deal with an array that has some entries with many objects nested inside one another, where as some do not. It looks something like the following:</p> <pre><code>// where this array is hundreds of entries long, with a mix // of the two examples given var test = [{'a':{'b':{'c':&quot;foo&quot;}}}, {'a': &quot;bar&quot;}]; </code></pre> <p>This is giving me problems because I need to iterate through the array at times, and the inconsistency is throwing me errors like so:</p> <pre><code>for (i=0; i&lt;test.length; i++) { // ok on i==0, but 'cannot read property of undefined' on i==1 console.log(a.b.c); } </code></pre> <p>I am aware that I can say <code>if(a.b){ console.log(a.b.c)}</code>, but this is extraordinarily tedious in cases where there are up to 5 or 6 objects nested within one another. Is there any other (easier) way that I can have it ONLY do the <code>console.log</code> if it exists, but without throwing an error?</p>
42,349,521
18
7
null
2013-02-08 22:16:00.617 UTC
41
2022-07-16 07:36:14.803 UTC
2022-07-16 07:32:11.063 UTC
null
15,288,641
null
1,459,449
null
1
164
javascript
391,234
<p><strong>Update</strong>:</p> <ul> <li>If you use JavaScript according to ECMAScript 2020 or later, see <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining" rel="noreferrer">optional chaining</a>.</li> <li>TypeScript has added support for optional chaining in version <a href="http://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html" rel="noreferrer">3.7</a>.</li> </ul> <pre class="lang-js prettyprint-override"><code>// use it like this obj?.a?.lot?.of?.properties </code></pre> <hr /> <p><strong>Solution for JavaScript before ECMASCript 2020 or TypeScript older than version 3.7</strong>:</p> <p>A quick workaround is using a try/catch helper function with ES6 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions" rel="noreferrer">arrow function</a>:</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>function getSafe(fn, defaultVal) { try { return fn(); } catch (e) { return defaultVal; } } // use it like this console.log(getSafe(() =&gt; obj.a.lot.of.properties)); // or add an optional default value console.log(getSafe(() =&gt; obj.a.lot.of.properties, 'nothing'));</code></pre> </div> </div> </p>
27,891,253
How to create a Task<> I can complete manually
<p>In unit testing a component I need to verify how a component reacts to Tasks being completed at various times.</p> <p>How do I create a <code>Task&lt;&gt;</code> that I can resolve at will?</p>
27,891,277
1
0
null
2015-01-11 19:37:54.007 UTC
2
2015-01-11 19:42:02.083 UTC
null
null
null
null
5,056
null
1
28
c#|task-parallel-library
9,200
<p>You can use a <a href="http://msdn.microsoft.com/en-us/library/dd449174%28v=vs.110%29.aspx"><code>TaskCompletionSource</code></a> to create a fully 'manual' task.</p> <blockquote> <p>Represents the producer side of a Task unbound to a delegate, providing access to the consumer side through the Task property.</p> </blockquote> <p>Hand out the the completion source's <code>Task</code> property to the consumer, and call <code>SetResult</code> on it (at will) to complete the task. Note that you also have <code>SetCanceled</code> and <code>SetException</code> to represent cancellations and failures, respectively.</p>
63,611,924
PHPExcel Error: Array and string offset access syntax with curly braces is deprecated
<p>I've just updated my <code>phpexcel</code> to <code>phpspreadsheet</code>, and I noticed this error pops up:</p> <blockquote> <p>ErrorException (E_DEPRECATED) Array and string offset access syntax with curly braces is deprecated</p> </blockquote> <blockquote> <p>require 'Classes/PHPExcel.php';</p> </blockquote> <p>here is part of my code which is triggering the above error:</p> <p><strong>File:</strong> <code>project/public/Classes/PHPExcel/Shared/ZipStreamWrapper.php</code></p> <pre><code> public function stream_open($path, $mode, $options, &amp;$opened_path) { // Check for mode if ($mode{0} != 'r') { //Error Line throw new PHPExcel_Reader_Exception('Mode ' . $mode . ' is not supported. Only read mode is supported.'); } </code></pre> <p><strong>File:</strong> <code>project/public/Classes/PHPExcel.php</code></p> <pre><code>/** PHPExcel root directory */ if (!defined('PHPEXCEL_ROOT')) { define('PHPEXCEL_ROOT', dirname(__FILE__) . '/'); require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php'); //Error Line } </code></pre> <p><strong>File:</strong> <code>app/Http/Controllers/analyticsAuth/statement.old.php</code></p> <pre><code>use PHPExcel_Reader_Excel2007; use PHPExcel; use PHPExcel_IOFactory; use ZipArchive; require 'Classes/PHPExcel.php'; //Error Line </code></pre> <p><strong>File:</strong> <code>project/public/Classes/PHPExcel/Autoloader.php</code></p> <pre><code>PHPExcel_Autoloader::Register(); PHPExcel_Shared_ZipStreamWrapper::register(); //Error Line if (ini_get('mbstring.func_overload') &amp; 2) { throw new Exception('Multibyte function overloading in PHP must be disabled for string functions (2).'); } </code></pre> <p>Thank you</p>
63,617,428
2
11
null
2020-08-27 08:20:26.8 UTC
1
2022-02-02 13:35:26.613 UTC
2020-08-27 09:04:42.563 UTC
null
14,138,027
null
14,138,027
null
1
6
php|laravel|phpexcel
46,857
<p>This can be fix by replacing the curly braces <code>{}</code> with square brackets <code>[]</code></p> <p>I would like to give credit to the <a href="https://stackoverflow.com/users/6401290/heysora">@HeySora</a> who made the comment and pointed out the exact issue in this particular case.</p>
42,677,401
Nunjucks: 'if' with multiple 'and' or 'or' condition
<p>Today my team mate was struggling on how to add multiple conditions with 'and' or 'or' in an if statement in Nunjucks template. After a lot of search he found the answer but not on Stackoverflow. I am not sure if the answer is already posted somewhere in SO but thought to post it now to narrow down future searches.</p> <p>Below is the answer:</p>
42,677,402
1
0
null
2017-03-08 17:00:56.457 UTC
7
2022-04-08 18:48:45.687 UTC
null
null
null
null
3,620,073
null
1
36
node.js|templates|npm|template-engine|nunjucks
31,444
<p>Answer:</p> <p>As we know Nunjucks is inspired by Jinja2 python's template engine, the if statement is similar to it.</p> <pre><code>// And Snippet {% if (VARIABLE &gt; 10) and (VARIABLE &lt; 20) %} // {% endif %} // Or Snippet {% if (VARIABLE == 10) or (VARIABLE == 20) %} // {% endif %} </code></pre> <p>Thats it !!!</p> <p>Couldn't find this on Nunjucks documentation either. I believe this answer will be helpful as coders working on Nunjucks tend to search with keyword Nunjucks and not with Jinja.</p>
21,184,766
How do I move the toolbar in IntelliJ?
<p>How can I move the toolbar in IntelliJ from the Top Right corner to the Top Left?</p> <p><img src="https://i.stack.imgur.com/VdEhd.jpg" alt="Screenshot"></p>
21,185,784
3
0
null
2014-01-17 11:25:02.12 UTC
5
2021-01-13 11:24:11.923 UTC
2014-01-17 14:37:53.093 UTC
null
1,366,033
null
939,497
null
1
56
intellij-idea
13,993
<p>click on Main Menu | View | Toolbar</p>
45,082,842
T-SQL DROP TYPE IF EXISTS
<p>I'm currently working on a script in T-SQL in SQL Server 2014.</p> <p>I need to drop a user-defined table type, but only if it exists, and create it again after the delete/drop type.</p> <p>I did some research on the web and found a solution, which does, unfortunately, not work at all.</p> <p>My current script looks like this:</p> <pre><code>IF OBJECT_ID('MySchema.tProjectType', 'U') IS NOT NULL DROP TYPE [MySchema].[tProjectType]; CREATE TYPE [MySchema].[tProjectType] AS TABLE ( Id INT , IsPrivate BIT , IsPublic BIT ); </code></pre> <p>My error message:</p> <blockquote> <p>The type 'MySchema.tProjectType' already exists, or you do not have permission to create it.</p> </blockquote> <p>Do you know how to successfully check if a user defined table type exists before I can delete it in SQL Server 2014?</p>
45,083,037
3
1
null
2017-07-13 13:56:52.803 UTC
2
2019-06-27 15:05:01.34 UTC
2019-06-27 15:05:01.34 UTC
null
206,730
null
1,490,878
null
1
19
sql-server|tsql
45,609
<p>Please try this, use <strong>type_id</strong> instead of <strong>object_id</strong></p> <pre><code>IF type_id('[MySchema].[tProjectType]') IS NOT NULL DROP TYPE [MySchema].[tProjectType]; CREATE TYPE [MySchema].[tProjectType] AS TABLE ( Id INT , IsPrivate BIT , IsPublic BIT ); </code></pre>
31,272,276
Pass selected value to vuejs function
<p>How can I pass selected value to a vuejs function? <code>v-model</code> won't help I guess.</p> <p>I need to set values for the filter after <code>item: items | orderBy sortKey reverse</code> where <code>reverse</code> and <code>sortKey</code> are dynamic values. </p> <p><strong>html</strong></p> <pre><code>&lt;select class="sort-filter" v-on="change: sortBy(???)"&gt; &lt;option value="title asc"&gt;Title (A-Z)&lt;/option&gt; &lt;option value="title desc"&gt;Title (Z-A)&lt;/option&gt; &lt;option value="price asc"&gt;Price (Min. - Max.)&lt;/option&gt; &lt;option value="price desc"&gt;Price (Max. - Min.)&lt;/option&gt; &lt;/select&gt; </code></pre> <p><strong>js</strong></p> <pre><code> methods: { sortBy: function (sortKey) { console.log(sortKey) } } </code></pre>
31,273,611
4
0
null
2015-07-07 14:59:32.88 UTC
11
2019-06-10 14:15:13.48 UTC
2015-07-07 15:31:01.043 UTC
null
985,241
null
985,241
null
1
20
vue.js
59,175
<p>You have several ways to do it.</p> <p><strong>Edit: Improved 2)</strong> </p> <p>It is possible to use v-model just like in <strong>2)</strong> but instead of using the value directly in your orderBy filter, you can use <a href="http://vuejs.org/guide/computed.html" rel="noreferrer">computed properties</a></p> <pre><code>computed: { sortKey: { get: function() { return this.sorting.split(' ')[0]; // return the key part } }, sortOrder: { get: function() { return this.sorting.split(' ')[1]; // return the order part } } } </code></pre> <p>This way, sortKey and sortOrder will be available like a normal property in you filter:</p> <pre><code>v-repeat="items | orderBy sortKey sortOrder" </code></pre> <p><strong>1) Use javascript event:</strong></p> <p>If you don't specify any parameter, the native event object will be passed automatically </p> <pre><code>&lt;select class="sort-filter" v-on:change="sortBy"&gt; </code></pre> <p>You can then use it like this:</p> <pre><code>methods: { sortBy: function(e) { console.log(e.target.value); }, } </code></pre> <p><strong>2) Using v-model</strong></p> <p>You can add the v-model directive</p> <pre><code>&lt;select name="test" v-model="sorting" v-on:change="sortBy"&gt; </code></pre> <p>This way the <code>sorting</code> value will be updated on every change.</p> <p>You can add this value in the data object of you ViewModel to be more clear:</p> <pre><code>data: { sorting: null // Will be updated when the select value change } </code></pre> <p>You can then access the value like in your method:</p> <pre><code>methods: { sortBy: function() { console.log(this.sorting); }, } </code></pre> <p>If you just need to update the <code>sortKey</code> value, this method is not even necessary.</p> <p><strong>3) Other weird way</strong></p> <p>You can apparently use your model value as a parameter.</p> <pre><code>&lt;select name="test" v-model="sortKey" v-on:change="sortBy(sortKey)"&gt; </code></pre> <p>This is working but I don't really see the point.</p> <pre><code>methods: { sortBy: function(sortKey) { console.log(sortKey); }, } </code></pre>
65,022,729
Use both AddDbContextFactory() and AddDbContext() extension methods in the same project
<p>I'm trying to use the new <code>DbContextFactory</code> pattern discussed in <a href="https://docs.microsoft.com/en-us/ef/core/dbcontext-configuration/#using-a-dbcontext-factory-eg-for-blazor" rel="noreferrer">the DbContext configuration section of the EF Core docs</a>.</p> <p>I've got the <code>DbContextFactory</code> up and running successfully in my Blazor app, but I want to retain the option to inject instances of <code>DbContext</code> directly in order to keep my existing code working.</p> <p>However, when I try to do that, I'm getting an error along the lines of:</p> <blockquote> <p>System.AggregateException: Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: Microsoft.EntityFrameworkCore.IDbContextFactory<code>1[MyContext] Lifetime: Singleton ImplementationType: Microsoft.EntityFrameworkCore.Internal.DbContextFactory</code>1[MyContext]': Cannot consume scoped service 'Microsoft.EntityFrameworkCore.DbContextOptions<code>1[MyContext]' from singleton 'Microsoft.EntityFrameworkCore.IDbContextFactory</code>1[MyContext]'.) ---&gt; System.InvalidOperationException: Error while validating the service descriptor 'ServiceType: Microsoft.EntityFrameworkCore.IDbContextFactory<code>1[MyContext] Lifetime: Singleton ImplementationType: Microsoft.EntityFrameworkCore.Internal.DbContextFactory</code>1[MyContext]': Cannot consume scoped service 'Microsoft.EntityFrameworkCore.DbContextOptions<code>1[MyContext]' from singleton 'Microsoft.EntityFrameworkCore.IDbContextFactory</code>1[MyContext]'. ---&gt; System.InvalidOperationException: Cannot consume scoped service 'Microsoft.EntityFrameworkCore.DbContextOptions<code>1[MyContext]' from singleton 'Microsoft.EntityFrameworkCore.IDbContextFactory</code>1[MyContext]'.</p> </blockquote> <p>I also managed to get this error at one point while experimenting:</p> <blockquote> <p>Cannot resolve scoped service 'Microsoft.EntityFrameworkCore.DbContextOptions`1[MyContext]' from root provider.</p> </blockquote> <p>Is it theoretically possible to use both <code>AddDbContext</code> and <code>AddDbContextFactory</code> together?</p>
65,022,730
2
0
null
2020-11-26 13:09:19.73 UTC
9
2021-10-01 16:08:05.147 UTC
2020-11-26 14:15:22.437 UTC
null
1,879,019
null
1,879,019
null
1
29
c#|entity-framework|dependency-injection|ef-core-3.1|ef-core-5.0
14,347
<p>It is, it's all about understanding the lifetimes of the various elements in play and getting those set correctly.</p> <p>By default the <code>DbContextFactory</code> created by the <code>AddDbContextFactory()</code> extension method has a Singleton lifespan. If you use the <code>AddDbContext()</code> extension method with it's default settings it will create a <code>DbContextOptions</code> with a <code>Scoped</code> lifespan (<a href="https://github.com/dotnet/efcore/blob/243357978bfa9b457e5e5011ea13648c46d8a1e8/src/EFCore/Extensions/EntityFrameworkServiceCollectionExtensions.cs#L534" rel="noreferrer">see the source-code here</a>), and as a <code>Singleton</code> can't use something with a shorter <code>Scoped</code> lifespan, an error is thrown.</p> <p>To get round this, we need to change the lifespan of the <code>DbContextOptions</code> to also be 'Singleton'. This can be done using by explicitly setting the scope of the <code>DbContextOptions</code> parameter of <code>AddDbContext()</code></p> <pre class="lang-cs prettyprint-override"><code>services.AddDbContext&lt;FusionContext&gt;(options =&gt; options.UseSqlServer(YourSqlConnection), contextLifetime: ServiceLifetime.Transient, optionsLifetime: ServiceLifetime.Singleton); </code></pre> <p>There's a really good discussion of this <a href="https://github.com/dotnet/efcore/pull/21246#issuecomment-668093047" rel="noreferrer">on the EF core GitHub repository starting here</a>. It's also well worth having a look at the source-code for <code>DbContextFactory</code> <a href="https://github.com/dotnet/efcore/blob/main/src/EFCore/Internal/DbContextFactory.cs" rel="noreferrer">here</a>.</p> <p>Alternatively, you can also change the lifetime of the <code>DbContextFactory</code> by <a href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.entityframeworkservicecollectionextensions.adddbcontextfactory?view=efcore-5.0" rel="noreferrer">setting the ServiceLifetime parameter in the constructor</a>:</p> <pre class="lang-cs prettyprint-override"><code>services.AddDbContextFactory&lt;FusionContext&gt;(options =&gt; options.UseSqlServer(YourSqlConnection), ServiceLifetime.Scoped); </code></pre> <p>The options should be configured exactly <a href="https://docs.microsoft.com/en-us/ef/core/dbcontext-configuration/" rel="noreferrer">as you would for a normal DbContext</a> as those are the options that will be set on the DbContext the factory creates.</p>
38,783,739
How to set a session id in Postman
<p>I need to hit a post request to an API service which requires a session id along with other parameters in its post request field in order to get the required information.</p> <p>I am using Postman to test this API.</p> <p>I would like to know how to send a 'session id' in a post request when using Postman?</p> <p>I am aware of pre-request script in Postman, but I am unaware of how to use the variable in post request.</p>
52,841,289
6
0
null
2016-08-05 07:39:39.067 UTC
4
2021-10-23 19:12:25.797 UTC
2020-02-23 12:23:32.333 UTC
null
2,648,551
null
3,808,898
null
1
24
session|post|postman
63,713
<p>In Postman native app:</p> <ul> <li>Turn on the Interceptor.</li> <li>Go to Headers</li> <li>Key: Cookie</li> <li>Value : sessionid=omuxrmt33mnetsfirxi2sdsfh4j1c2kv</li> </ul>