input_text
stringlengths 115
13.8k
| output_text
stringlengths 24
15k
| metadata
dict |
---|---|---|
Please answer the following Stack Overflow question:
Title: Connect to mysql in a docker container from the host
<p><em>(It's probably a dumb question due to my limited knowledge with Docker or mysql administration, but since I spent a whole evening on this issue, I dare to ask it.)</em></p>
<p><strong>In a nutshell</strong></p>
<p>I want to run mysql in a docker container and connect to it from my host. So far, the best I have achieved is:</p>
<pre><code>ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)
</code></pre>
<p><strong>More details</strong></p>
<p>I'm using the following <code>Dockerfile</code>:</p>
<pre><code>FROM ubuntu:14.04.3
RUN apt-get update && apt-get install -y mysql-server
# Ensure we won't bind to localhost only
RUN grep -v bind-address /etc/mysql/my.cnf > temp.txt \
&& mv temp.txt /etc/mysql/my.cnf
# It doesn't seem needed since I'll use -p, but it can't hurt
EXPOSE 3306
CMD /etc/init.d/mysql start && tail -F /var/log/mysql.log
</code></pre>
<p>In the directory where there is this file, I can succesfully build the image and run it with:</p>
<pre><code>> docker build -t my-image .
> docker run -d -p 12345:3306 my-image
</code></pre>
<p>When I attach to the image, it seems to work just fine:</p>
<pre><code># from the host
> docker exec -it <my_image_name> bash
#inside of the container now
$ mysql -u root
Welcome to the MySQL monitor. Commands end with ; or \g.
[...]
</code></pre>
<p>However I don't have that much success from the host:</p>
<pre><code>> mysql -P 12345 -uroot
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)
</code></pre>
<p><strong>Even more details</strong></p>
<ul>
<li>I've seen that there's a question which <a href="https://stackoverflow.com/q/25069860/1796345">looks like mine</a>. However, it isn't the same (and it doesn't have any answers anyway)
<ul>
<li>I've seen that there are images <a href="https://github.com/sameersbn/docker-mysql" rel="noreferrer">dedicated to mysql</a>, but I didn't have more success with them</li>
<li>My <code>grep -v</code> may feel weird. Admittedly, there may be cleaner way to do it. But when I attach my image, I can observe it actually worked as expected (ie: removed the <code>bind-address</code>). And I can see in the container <code>/var/log/mysql/error.log</code>:</li>
</ul></li>
</ul>
<blockquote>
<p>Server hostname (bind-address): '0.0.0.0'; port: 3306
- '0.0.0.0' resolves to '0.0.0.0';
Server socket created on IP: '0.0.0.0'.</p>
</blockquote> | <p>If you use "127.0.0.1" instead of localhost mysql will use tcp method and you should be able to connect container with: </p>
<pre><code>mysql -h 127.0.0.1 -P 3306 -u root
</code></pre> | {
"question_id": 33001750,
"question_date": "2015-10-07T20:21:44.170Z",
"question_score": 210,
"tags": "mysql|docker|dockerfile",
"answer_id": 40159703,
"answer_date": "2016-10-20T16:24:32.623Z",
"answer_score": 92
} |
Please answer the following Stack Overflow question:
Title: URL to load resources from the classpath in Java
<p>In Java, you can load all kinds of resources using the same API but with different URL protocols:</p>
<pre><code>file:///tmp.txt
http://127.0.0.1:8080/a.properties
jar:http://www.foo.com/bar/baz.jar!/COM/foo/Quux.class
</code></pre>
<p>This nicely decouples the actual loading of the resource from the application that needs the resource, and since a URL is just a String, resource loading is also very easily configurable.</p>
<p>Is there a protocol to load resources using the current classloader?
This is similar to the Jar protocol, except that I do not need to know which jar file or class folder the resource is coming from.</p>
<p>I can do that using <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getResourceAsStream(java.lang.String)" rel="noreferrer"><code>Class.getResourceAsStream("a.xml")</code></a>, of course, but that would require me to use a different API, and hence changes to existing code. I want to be able to use this in all places where I can specify a URL for the resource already, by just updating a property file.</p> | <h2>Intro and basic Implementation</h2>
<p>First up, you're going to need at least a URLStreamHandler. This will actually open the connection to a given URL. Notice that this is simply called <code>Handler</code>; this allows you to specify <code>java -Djava.protocol.handler.pkgs=org.my.protocols</code> and it will automatically be picked up, using the "simple" package name as the supported protocol (in this case "classpath").</p>
<h3>Usage</h3>
<pre><code>new URL("classpath:org/my/package/resource.extension").openConnection();
</code></pre>
<h3>Code</h3>
<pre><code>package org.my.protocols.classpath;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
/** A {@link URLStreamHandler} that handles resources on the classpath. */
public class Handler extends URLStreamHandler {
/** The classloader to find resources from. */
private final ClassLoader classLoader;
public Handler() {
this.classLoader = getClass().getClassLoader();
}
public Handler(ClassLoader classLoader) {
this.classLoader = classLoader;
}
@Override
protected URLConnection openConnection(URL u) throws IOException {
final URL resourceUrl = classLoader.getResource(u.getPath());
return resourceUrl.openConnection();
}
}
</code></pre>
<p><h3>Launch issues</h3>If you're anything like me, you don't want to rely on a property being set in the launch to get you somewhere (in my case, I like to keep my options open like Java WebStart - which is why <em>I</em> need all this).</p>
<h2>Workarounds/Enhancements</h2>
<h3>Manual code Handler specification</h3>
<p>If you control the code, you can do</p>
<pre><code>new URL(null, "classpath:some/package/resource.extension", new org.my.protocols.classpath.Handler(ClassLoader.getSystemClassLoader()))
</code></pre>
<p>and this will use your handler to open the connection.</p>
<p>But again, this is less than satisfactory, as you don't need a URL to do this - you want to do this because some lib you can't (or don't want to) control wants urls...</p>
<h3>JVM Handler registration</h3>
<p>The ultimate option is to register a <code>URLStreamHandlerFactory</code> that will handle all urls across the jvm:</p>
<pre><code>package my.org.url;
import java.net.URLStreamHandler;
import java.net.URLStreamHandlerFactory;
import java.util.HashMap;
import java.util.Map;
class ConfigurableStreamHandlerFactory implements URLStreamHandlerFactory {
private final Map<String, URLStreamHandler> protocolHandlers;
public ConfigurableStreamHandlerFactory(String protocol, URLStreamHandler urlHandler) {
protocolHandlers = new HashMap<String, URLStreamHandler>();
addHandler(protocol, urlHandler);
}
public void addHandler(String protocol, URLStreamHandler urlHandler) {
protocolHandlers.put(protocol, urlHandler);
}
public URLStreamHandler createURLStreamHandler(String protocol) {
return protocolHandlers.get(protocol);
}
}
</code></pre>
<p>To register the handler, call <code>URL.setURLStreamHandlerFactory()</code> with your configured factory. Then do <code>new URL("classpath:org/my/package/resource.extension")</code> like the first example and away you go.</p>
<h3>JVM Handler Registration Issue</h3>
<p>Note that this method may only be called once per JVM, and note well that Tomcat will use this method to register a JNDI handler (AFAIK). Try Jetty (I will be); at worst, you can use the method first and then it has to work around you!</p>
<h2>License</h2>
<p><em>I release this to the public domain, and ask that if you wish to modify that you start a OSS project somewhere and comment here with the details. A better implementation would be to have a <code>URLStreamHandlerFactory</code> that uses <code>ThreadLocal</code>s to store <code>URLStreamHandler</code>s for each <code>Thread.currentThread().getContextClassLoader()</code>. I'll even give you my modifications and test classes.</em></p> | {
"question_id": 861500,
"question_date": "2009-05-14T04:07:39.273Z",
"question_score": 210,
"tags": "java|url|classloader",
"answer_id": 1769454,
"answer_date": "2009-11-20T09:52:09.220Z",
"answer_score": 360
} |
Please answer the following Stack Overflow question:
Title: How to change context root of a dynamic web project in Eclipse?
<p>I developed a dynamic web project in Eclipse.
I can access the app through my browser using the following URL: </p>
<pre><code>http://localhost:8080/MyDynamicWebApp
</code></pre>
<p>I want to change the access URL to:</p>
<pre><code>http://localhost:8080/app
</code></pre>
<p>To do so, I changed the context root from the project "Properties | Web Project Settings | Context Root".
However, the web app still has the same access URL. I have re-deployed the application on Tomcat and re-started the Tomcat, but the access URL is the same as earlier.</p>
<p>I found that there was no <code>server.xml</code> file attached with the <code>WAR</code> file. Without the <code>server.xml</code> file attached, how is the Tomcat determining that the context root of my web app is <code>/MyDynamicWebApp</code> and allowing me to access the application through this context root URL?</p> | <p>I'm sure you've moved on by now, but I thought I'd answer anyway.</p>
<p>Some of these answers give workarounds. What actually must happen is that you clean and re-publish your project to "activate" the new URI. This is done by right-clicking your server (in the Servers view) and choosing Clean. Then you start (or restart it). Most of the other answers here suggest you do things that in effect accomplish this.</p>
<p>The file that's changing is <code>workspace/.metadata/.plugins/org.eclipse.wst.server.core/publish/publish.dat</code> unless, that is, you've got more than one server in your workspace in which case it will be <code>publishN.dat</code> on that same path.</p>
<p>Hope this helps somebody.</p>
<hr />
<p>Not sure if this is proper etiquette or not — I am editing this answer to give exact steps for Eclipse Indigo.</p>
<ol>
<li><p>In your project's <em><strong>Properties</strong></em>, choose <em><strong>Web Project Settings</strong></em>.</p>
</li>
<li><p>Change <em><strong>Context root</strong></em> to <em><strong>app</strong></em>.</p>
<p><img src="https://i.stack.imgur.com/gP8z8.png" alt="screen shot of Eclipse project properties Web Project Settings" /></p>
</li>
<li><p>Choose <em><strong>Window > Show View > Servers</strong></em>.</p>
</li>
<li><p>Stop the server by either clicking the red square box ("Stop the server" tooltip) or context-click on the server listing to choose "Stop".</p>
</li>
<li><p>On the server you want to use, context-click to choose "Clean…".</p>
<p><img src="https://i.stack.imgur.com/ONxFd.png" alt="enter image description here" /></p>
</li>
<li><p>Click OK in this confirmation dialog box.</p>
<p><img src="https://i.stack.imgur.com/d1Gyu.png" alt="Screenshot of dialog asking to update server configuration to match the changed context root" /></p>
</li>
</ol>
<p>Now you can run your app with the new "app" URL such as:</p>
<blockquote>
<p><code>http://localhost:8080/app/</code></p>
</blockquote>
<p>Doing this outside of Eclipse, on your production server, is even easier --> Rename the war file. Export your Vaadin app as a WAR file (<em><strong>File > Export > Web > WAR file</strong></em>). Move the WAR file to your web server's servlet container such as Tomcat. Rename your WAR file, in this case to <em><strong>app.war</strong></em>. When you start the servlet container, most such as Tomcat will auto-deploy the app, which includes expanding the war file to a folder. In this case, we should see a folder named <em><strong>app</strong></em>. You should be good to go. Test your URL. For a domain such as *example.com" this would be:</p>
<blockquote>
<p><code>http://www.example.com/app/</code></p>
</blockquote>
<p>Vaadin toolkit programmers may need to rebuild their widget set if using visual add ons.</p> | {
"question_id": 2437465,
"question_date": "2010-03-13T06:07:46.573Z",
"question_score": 210,
"tags": "eclipse|jakarta-ee|applicationcontext|contextroot",
"answer_id": 8334309,
"answer_date": "2011-11-30T23:06:51.507Z",
"answer_score": 344
} |
Please answer the following Stack Overflow question:
Title: Setting an image for a UIButton in code
<p>How do you set the image for a UIButton in code?</p>
<p>I have this:</p>
<pre><code>UIButton *btnTwo = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btnTwo.frame = CGRectMake(40, 140, 240, 30);
[btnTwo setTitle:@"vc2:v1" forState:UIControlStateNormal];
[btnTwo addTarget:self action:@selector(goToOne) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btnTwo];
</code></pre>
<p>but don't see what will set the image for it.</p> | <p>Objective-C</p>
<pre><code>UIImage *btnImage = [UIImage imageNamed:@"image.png"];
[btnTwo setImage:btnImage forState:UIControlStateNormal];
</code></pre>
<p>Swift 5.1</p>
<pre><code>let btnImage = UIImage(named: "image")
btnTwo.setImage(btnImage , for: .normal)
</code></pre> | {
"question_id": 1469474,
"question_date": "2009-09-24T02:06:31.210Z",
"question_score": 210,
"tags": "ios|objective-c|iphone|ipad|uibutton",
"answer_id": 1469487,
"answer_date": "2009-09-24T02:16:33.233Z",
"answer_score": 422
} |
Please answer the following Stack Overflow question:
Title: try/catch blocks with async/await
<p>I'm digging into the node 7 <code>async</code>/<code>await</code> feature and keep stumbling across code like this</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 getQuote() {
let quote = "Lorem ipsum dolor sit amet, consectetur adipiscing elit laborum.";
return quote;
}
async function main() {
try {
var quote = await getQuote();
console.log(quote);
} catch (error) {
console.error(error);
}
}
main();</code></pre>
</div>
</div>
</p>
<p>This seems to be the only possibility <code>resolve</code>/<code>reject</code> or <code>return</code>/<code>throw</code> with <code>async</code>/<code>await</code>, however, v8 doesn't optimise code within <code>try</code>/<code>catch</code> blocks?!</p>
<p>Are there alternatives?</p> | <h2>Alternatives</h2>
<p>An alternative to this:</p>
<pre><code>async function main() {
try {
var quote = await getQuote();
console.log(quote);
} catch (error) {
console.error(error);
}
}
</code></pre>
<p>would be something like this, using promises explicitly:</p>
<pre><code>function main() {
getQuote().then((quote) => {
console.log(quote);
}).catch((error) => {
console.error(error);
});
}
</code></pre>
<p>or something like this, using continuation passing style:</p>
<pre><code>function main() {
getQuote((error, quote) => {
if (error) {
console.error(error);
} else {
console.log(quote);
}
});
}
</code></pre>
<h2>Original example</h2>
<p>What your original code does is suspend the execution and wait for the promise returned by <code>getQuote()</code> to settle. It then continues the execution and writes the returned value to <code>var quote</code> and then prints it if the promise was resolved, or throws an exception and runs the catch block that prints the error if the promise was rejected.</p>
<p>You can do the same thing using the Promise API directly like in the second example.</p>
<h2>Performance</h2>
<p>Now, for the performance. Let's test it!</p>
<p>I just wrote this code - <code>f1()</code> gives <code>1</code> as a return value, <code>f2()</code> throws <code>1</code> as an exception:</p>
<pre><code>function f1() {
return 1;
}
function f2() {
throw 1;
}
</code></pre>
<p>Now let's call the same code million times, first with <code>f1()</code>:</p>
<pre><code>var sum = 0;
for (var i = 0; i < 1e6; i++) {
try {
sum += f1();
} catch (e) {
sum += e;
}
}
console.log(sum);
</code></pre>
<p>And then let's change <code>f1()</code> to <code>f2()</code>:</p>
<pre><code>var sum = 0;
for (var i = 0; i < 1e6; i++) {
try {
sum += f2();
} catch (e) {
sum += e;
}
}
console.log(sum);
</code></pre>
<p>This is the result I got for <code>f1</code>:</p>
<pre><code>$ time node throw-test.js
1000000
real 0m0.073s
user 0m0.070s
sys 0m0.004s
</code></pre>
<p>This is what I got for <code>f2</code>:</p>
<pre><code>$ time node throw-test.js
1000000
real 0m0.632s
user 0m0.629s
sys 0m0.004s
</code></pre>
<p>It seems that you can do something like 2 million throws a second in one single-threaded process. If you're doing more than that then you may need to worry about it.</p>
<h2>Summary</h2>
<p>I wouldn't worry about things like that in Node. If things like that get used a lot then it will get optimized eventually by the V8 or SpiderMonkey or Chakra teams and everyone will follow - it's not like it's not optimized as a principle, it's just not a problem.</p>
<p>Even if it isn't optimized then I'd still argue that if you're maxing out your CPU in Node then you should probably write your number crunching in C - that's what the native addons are for, among other things. Or maybe things like <a href="https://github.com/d5/node.native" rel="noreferrer">node.native</a> would be better suited for the job than Node.js.</p>
<p>I'm wondering what would be a use case that needs throwing so many exceptions. Usually throwing an exception instead of returning a value is, well, an exception.</p> | {
"question_id": 40884153,
"question_date": "2016-11-30T09:06:19.680Z",
"question_score": 210,
"tags": "node.js|async-await|ecmascript-2017",
"answer_id": 40886720,
"answer_date": "2016-11-30T11:04:48.063Z",
"answer_score": 235
} |
Please answer the following Stack Overflow question:
Title: Can we make unsigned byte in Java
<p>I am trying to convert a signed byte in unsigned. The problem is the data I am receiving is unsigned and Java does not support unsigned byte, so when it reads the data it treats it as signed.</p>
<p>I tried it to convert it by the following solution I got from Stack Overflow.</p>
<pre><code>public static int unsignedToBytes(byte a)
{
int b = a & 0xFF;
return b;
}
</code></pre>
<p>But when again it's converted in byte, I get the same signed data. I am trying to use this data as a parameter to a function of Java that accepts only a byte as parameter, so I can't use any other data type. How can I fix this problem?</p> | <p>I'm not sure I understand your question.</p>
<p>I just tried this and for byte -12 (signed value) it returned integer 244 (equivalent to unsigned byte value but typed as an <code>int</code>):</p>
<pre><code> public static int unsignedToBytes(byte b) {
return b & 0xFF;
}
public static void main(String[] args) {
System.out.println(unsignedToBytes((byte) -12));
}
</code></pre>
<p>Is it what you want to do?</p>
<p>Java does not allow to express 244 as a <code>byte</code> value, as would C. To express positive integers above <code>Byte.MAX_VALUE</code> (127) you have to use a different integral type, like <code>short</code>, <code>int</code> or <code>long</code>.</p> | {
"question_id": 4266756,
"question_date": "2010-11-24T12:29:32.023Z",
"question_score": 210,
"tags": "java|unsigned",
"answer_id": 4266881,
"answer_date": "2010-11-24T12:40:21.997Z",
"answer_score": 112
} |
Please answer the following Stack Overflow question:
Title: Running Windows batch file commands asynchronously
<p>Say, if I have</p>
<ul>
<li>foo.exe</li>
<li>bar.exe</li>
<li>baz.exe</li>
</ul>
<p>How do I run all of them from a batch file asynchronously, i.e. without waiting for the previous program to stop?</p> | <p>Using the <a href="http://ss64.com/nt/start.html" rel="noreferrer"><code>START</code></a> command to run each program should get you what you need:</p>
<pre><code>START "title" [/D path] [options] "command" [parameters]
</code></pre>
<p>Every <code>START</code> invocation runs the command given in its parameter and returns immediately, unless executed with a <code>/WAIT</code> switch.</p>
<p>That applies to command-line apps. Apps without command line return immediately anyway, so to be sure, if you want to run all asynchronously, use <code>START</code>.</p> | {
"question_id": 1449188,
"question_date": "2009-09-19T18:34:54.900Z",
"question_score": 210,
"tags": "batch-file|cmd",
"answer_id": 1449192,
"answer_date": "2009-09-19T18:37:18.723Z",
"answer_score": 279
} |
Please answer the following Stack Overflow question:
Title: jQuery posting valid json in request body
<p>So according to the <a href="http://api.jquery.com/jQuery.ajax/" rel="noreferrer">jQuery Ajax docs</a>, it serializes data in the form of a query string when sending requests, but setting <code>processData:false</code> should allow me to send actual JSON in the body. Unfortunately I'm having a hard time determining first, if this is happening and 2nd what the object looks like that is being sent to the server. All I know is that the server is not parsing what I'm sending.</p>
<p>When using <a href="http://ditchnet.org/httpclient/" rel="noreferrer">http client</a> to post an object literal <code>{someKey:'someData'}</code>, it works. But when using jQuery with <code>data: {someKey:'someData'}</code>, it fails. Unfortunately when I analyze the request in Safari, it says the message payload is <code>[object Object]</code> ... great... and in Firefox the post is blank...</p>
<p>When logging the body content on the Java side it literally gets <code>[object Object]</code> so how does one send REAL JSON data??</p>
<p>Has anyone had experience with a Java service serializing JSON data in the request body, with the request sent from jQuery? </p>
<p>BTW here is the full $.ajax request:</p>
<pre><code>$.ajax({
contentType: 'application/json',
data: {
"command": "on"
},
dataType: 'json',
success: function(data){
app.log("device control succeeded");
},
error: function(){
app.log("Device control failed");
},
processData: false,
type: 'POST',
url: '/devices/{device_id}/control'
});
</code></pre> | <p>An actual JSON request would look like this:</p>
<pre><code>data: '{"command":"on"}',
</code></pre>
<p>Where you're sending an actual JSON string. For a more general solution, use <a href="https://developer.mozilla.org/En/Using_native_JSON#Converting_objects_into_JSON" rel="noreferrer"><code>JSON.stringify()</code></a> to serialize an object to JSON, like this:</p>
<pre><code>data: JSON.stringify({ "command": "on" }),
</code></pre>
<p>To support older browsers that don't have the <code>JSON</code> object, use <a href="http://www.json.org/js.html" rel="noreferrer">json2.js</a> which will add it in.</p>
<hr>
<p>What's currently happening is since you have <code>processData: false</code>, it's basically sending this: <code>({"command":"on"}).toString()</code> which is <code>[object Object]</code>...what you see in your request.</p> | {
"question_id": 4159701,
"question_date": "2010-11-11T22:02:04.710Z",
"question_score": 210,
"tags": "jquery|ajax|json|xmlhttprequest",
"answer_id": 4159726,
"answer_date": "2010-11-11T22:06:00.937Z",
"answer_score": 337
} |
Please answer the following Stack Overflow question:
Title: Android selector & text color
<p>I want a simple <code>TextView</code> to behave the way <code>simple_list_item_1</code> in a <code>ListView</code> does. Here's the XML:</p>
<pre><code><TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content" android:layout_width="fill_parent"
android:gravity="center" android:focusable="true"
android:minHeight="?android:attr/listPreferredItemHeight"
android:textAppearance="?android:attr/textAppearanceLarge"
android:background="@android:drawable/list_selector_background" />
</code></pre>
<p>Everything works except for the text color that (expectedly) doesn't change in focused state. How do I make it change to <code>textAppearanceLargeInverse</code>?</p> | <p>And selector is the answer here as well.</p>
<p>Search for bright_text_dark_focused.xml in the sources, add to your project under res/color directory and then refer from the TextView as</p>
<pre><code>android:textColor="@color/bright_text_dark_focused"
</code></pre> | {
"question_id": 1219312,
"question_date": "2009-08-02T17:18:34.887Z",
"question_score": 210,
"tags": "android|textview|android-selector",
"answer_id": 1280213,
"answer_date": "2009-08-14T21:02:18.293Z",
"answer_score": 83
} |
Please answer the following Stack Overflow question:
Title: How do I move files in node.js?
<p>How can I move files (like mv command shell) on node.js? Is there any method for that or should I read a file, write to a new file and remove older file?</p> | <p>According to seppo0010 comment, I used the rename function to do that.</p>
<p><a href="http://nodejs.org/docs/latest/api/fs.html#fs_fs_rename_oldpath_newpath_callback" rel="noreferrer">http://nodejs.org/docs/latest/api/fs.html#fs_fs_rename_oldpath_newpath_callback</a></p>
<blockquote>
<p>fs.rename(oldPath, newPath, callback)</p>
<h1>Added in: v0.0.2</h1>
<pre><code>oldPath <String> | <Buffer>
newPath <String> | <Buffer>
callback <Function>
</code></pre>
<p>Asynchronous rename(2). No arguments other than a possible exception
are given to the completion callback.</p>
</blockquote> | {
"question_id": 8579055,
"question_date": "2011-12-20T16:59:20.687Z",
"question_score": 210,
"tags": "file|node.js|express",
"answer_id": 8579946,
"answer_date": "2011-12-20T18:09:10.403Z",
"answer_score": 212
} |
Please answer the following Stack Overflow question:
Title: How to disable a ts rule for a specific line?
<p>Summernote is a jQuery plugin, and I don't need type definitions for it. I just want to modify the object, but TS keeps throwing errors. The line bellow still gives me: <strong>"Property 'summernote' does not exist on type 'jQueryStatic'."</strong> error.</p>
<pre><code>(function ($) {
/* tslint:disable */
delete $.summernote.options.keyMap.pc.TAB;
delete $.summernote.options.keyMap.mac.TAB;
/* tslint:enable */
})(jQuery)
</code></pre>
<p><strong>Edit:</strong></p>
<p>Here is my tsconfig.json</p>
<pre><code>{
"compilerOptions": {
"outDir": "./dist/",
"sourceMap": true,
"noImplicitAny": true,
"module": "commonjs",
"target": "es5",
"allowJs": true,
"noUnusedParameters": true
},
"include": [
"js/**/*"
],
"exclude": [
"node_modules",
"**/*.spec.ts"
]
}
</code></pre> | <p>As of Typescript 2.6, you can now bypass a compiler error/warning for a specific line:</p>
<pre><code>if (false) {
// @ts-ignore: Unreachable code error
console.log("hello");
}
</code></pre>
<p>Note that <a href="https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-6.html#suppress-errors-in-ts-files-using--ts-ignore-comments" rel="noreferrer">the official docs "recommend you use [this] very sparingly"</a>. It is almost <em>always</em> preferable to cast to <code>any</code> instead as that better expresses intent.</p>
<hr />
<p>Older answer:</p>
<p>You can use <code>/* tslint:disable-next-line */</code> to locally disable tslint. However, as this is a compiler error disabling tslint might not help.</p>
<p>You can always temporarily cast <code>$</code> to <code>any</code>:</p>
<pre><code>delete ($ as any).summernote.options.keyMap.pc.TAB
</code></pre>
<p>which will allow you to access whatever properties you want.</p> | {
"question_id": 43618878,
"question_date": "2017-04-25T19:00:25.503Z",
"question_score": 210,
"tags": "javascript|jquery|typescript|summernote",
"answer_id": 43620820,
"answer_date": "2017-04-25T20:57:22.340Z",
"answer_score": 272
} |
Please answer the following Stack Overflow question:
Title: How to assign colors to categorical variables in ggplot2 that have stable mapping?
<p>I've been getting up to speed with R in the last month.</p>
<p>Here is my question:</p>
<p>What is a good way to assign colors to categorical variables in ggplot2 that have stable mapping? I need consistent colors across a set of graphs that have different subsets and different number of categorical variables. </p>
<p>For example,</p>
<pre><code>plot1 <- ggplot(data, aes(xData, yData,color=categoricaldData)) + geom_line()
</code></pre>
<p>where <code>categoricalData</code> has 5 levels.</p>
<p>And then</p>
<pre><code>plot2 <- ggplot(data.subset, aes(xData.subset, yData.subset,
color=categoricaldData.subset)) + geom_line()
</code></pre>
<p>where <code>categoricalData.subset</code> has 3 levels.</p>
<p>However, a particular level that is in both sets will end up with a different color, which makes it harder to read the graphs together.</p>
<p>Do I need to create a vector of colors in the data frame? Or is there another way to assigns specific colors to categories?</p> | <p>For simple situations like the exact example in the OP, I agree that Thierry's answer is the best. However, I think it's useful to point out another approach that becomes easier when you're trying to maintain consistent color schemes across multiple data frames that are <em>not</em> all obtained by subsetting a single large data frame. Managing the factors levels in multiple data frames can become tedious if they are being pulled from separate files and not all factor levels appear in each file.</p>
<p>One way to address this is to create a custom manual colour scale as follows:</p>
<pre><code>#Some test data
dat <- data.frame(x=runif(10),y=runif(10),
grp = rep(LETTERS[1:5],each = 2),stringsAsFactors = TRUE)
#Create a custom color scale
library(RColorBrewer)
myColors <- brewer.pal(5,"Set1")
names(myColors) <- levels(dat$grp)
colScale <- scale_colour_manual(name = "grp",values = myColors)
</code></pre>
<p>and then add the color scale onto the plot as needed:</p>
<pre><code>#One plot with all the data
p <- ggplot(dat,aes(x,y,colour = grp)) + geom_point()
p1 <- p + colScale
#A second plot with only four of the levels
p2 <- p %+% droplevels(subset(dat[4:10,])) + colScale
</code></pre>
<p>The first plot looks like this:</p>
<p><img src="https://i.stack.imgur.com/IHtqM.png" alt="enter image description here"></p>
<p>and the second plot looks like this:</p>
<p><img src="https://i.stack.imgur.com/f9flP.png" alt="enter image description here"></p>
<p>This way you don't need to remember or check each data frame to see that they have the appropriate levels.</p> | {
"question_id": 6919025,
"question_date": "2011-08-02T21:41:58.707Z",
"question_score": 210,
"tags": "r|ggplot2",
"answer_id": 6920045,
"answer_date": "2011-08-02T23:40:45.460Z",
"answer_score": 230
} |
Please answer the following Stack Overflow question:
Title: Java 8 stream reverse order
<p>General question: What's the proper way to reverse a stream? Assuming that we don't know what type of elements that stream consists of, what's the generic way to reverse any stream?</p>
<p>Specific question: </p>
<p><code>IntStream</code> provides range method to generate Integers in specific range <code>IntStream.range(-range, 0)</code>, now that I want to reverse it switching range from 0 to negative won't work, also I can't use <code>Integer::compare</code></p>
<pre><code>List<Integer> list = Arrays.asList(1,2,3,4);
list.stream().sorted(Integer::compare).forEach(System.out::println);
</code></pre>
<p>with <code>IntStream</code> I'll get this compiler error</p>
<blockquote>
<p>Error:(191, 0) ajc: The method <code>sorted()</code> in the type <code>IntStream</code> is not applicable for the arguments (<code>Integer::compare</code>)</p>
</blockquote>
<p>what am I missing here?</p> | <p>For the specific question of generating a reverse <code>IntStream</code>, try something like this:</p>
<pre><code>static IntStream revRange(int from, int to) {
return IntStream.range(from, to)
.map(i -> to - i + from - 1);
}
</code></pre>
<p>This avoids boxing and sorting.</p>
<p>For the general question of how to reverse a stream of any type, I don't know of there's a "proper" way. There are a couple ways I can think of. Both end up storing the stream elements. I don't know of a way to reverse a stream without storing the elements.</p>
<p>This first way stores the elements into an array and reads them out to a stream in reverse order. Note that since we don't know the runtime type of the stream elements, we can't type the array properly, requiring an unchecked cast.</p>
<pre><code>@SuppressWarnings("unchecked")
static <T> Stream<T> reverse(Stream<T> input) {
Object[] temp = input.toArray();
return (Stream<T>) IntStream.range(0, temp.length)
.mapToObj(i -> temp[temp.length - i - 1]);
}
</code></pre>
<p>Another technique uses collectors to accumulate the items into a reversed list. This does lots of insertions at the front of <code>ArrayList</code> objects, so there's lots of copying going on.</p>
<pre><code>Stream<T> input = ... ;
List<T> output =
input.collect(ArrayList::new,
(list, e) -> list.add(0, e),
(list1, list2) -> list1.addAll(0, list2));
</code></pre>
<p>It's probably possible to write a much more efficient reversing collector using some kind of customized data structure.</p>
<p><strong>UPDATE 2016-01-29</strong></p>
<p>Since this question has gotten a bit of attention recently, I figure I should update my answer to solve the problem with inserting at the front of <code>ArrayList</code>. This will be horribly inefficient with a large number of elements, requiring O(N^2) copying.</p>
<p>It's preferable to use an <code>ArrayDeque</code> instead, which efficiently supports insertion at the front. A small wrinkle is that we can't use the three-arg form of <code>Stream.collect()</code>; it requires the contents of the second arg be merged into the first arg, and there's no "add-all-at-front" bulk operation on <code>Deque</code>. Instead, we use <code>addAll()</code> to append the contents of the first arg to the end of the second, and then we return the second. This requires using the <code>Collector.of()</code> factory method.</p>
<p>The complete code is this:</p>
<pre><code>Deque<String> output =
input.collect(Collector.of(
ArrayDeque::new,
(deq, t) -> deq.addFirst(t),
(d1, d2) -> { d2.addAll(d1); return d2; }));
</code></pre>
<p>The result is a <code>Deque</code> instead of a <code>List</code>, but that shouldn't be much of an issue, as it can easily be iterated or streamed in the now-reversed order.</p> | {
"question_id": 24010109,
"question_date": "2014-06-03T08:09:45.880Z",
"question_score": 210,
"tags": "java|list|sorting|java-8|java-stream",
"answer_id": 24011264,
"answer_date": "2014-06-03T09:13:02.227Z",
"answer_score": 107
} |
Please answer the following Stack Overflow question:
Title: Get real path from URI, Android KitKat new storage access framework
<p>Before the new gallery access in <a href="https://en.wikipedia.org/wiki/Android_version_history#Android_4.4_KitKat_.28API_level_19.29">Android 4.4</a> (KitKat) I got my real path on the SD card with this method:</p>
<pre><code>public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
startManagingCursor(cursor);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
</code></pre>
<p>Now, the Intent.ACTION_GET_CONTENT return different data:</p>
<p>Before:</p>
<pre><code>content://media/external/images/media/62
</code></pre>
<p>Now:</p>
<pre><code>content://com.android.providers.media.documents/document/image:62
</code></pre>
<p>How could I manage to obtain the real path on the SD card?</p> | <p><strong>Note: This answer addresses part of the problem. For a complete solution (in the form of a library), look at <a href="https://stackoverflow.com/questions/20067508/get-real-path-from-uri-android-kitkat-new-storage-access-framework/20559175#20559175">Paul Burke's answer</a>.</strong></p>
<p>You could use the URI to obtain <code>document id</code>, and then query either <code>MediaStore.Images.Media.EXTERNAL_CONTENT_URI</code> or <code>MediaStore.Images.Media.INTERNAL_CONTENT_URI</code> (depending on the SD card situation).</p>
<p>To get document id:</p>
<pre><code>// Will return "image:x*"
String wholeID = DocumentsContract.getDocumentId(uriThatYouCurrentlyHave);
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
String[] column = { MediaStore.Images.Media.DATA };
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = getContentResolver().
query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[]{ id }, null);
String filePath = "";
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
}
cursor.close();
</code></pre>
<p>Reference: I'm not able to find the post that this solution is taken from. I wanted to ask the original poster to contribute here. Will look some more tonight.</p> | {
"question_id": 20067508,
"question_date": "2013-11-19T09:18:50.127Z",
"question_score": 210,
"tags": "android|path|uri|android-4.4-kitkat",
"answer_id": 20413475,
"answer_date": "2013-12-06T00:11:48.167Z",
"answer_score": 124
} |
Please answer the following Stack Overflow question:
Title: Why does this UnboundLocalError occur (closure)?
<p>What am I doing wrong here?</p>
<pre><code>counter = 0
def increment():
counter += 1
increment()
</code></pre>
<p>The above code throws an <code>UnboundLocalError</code>.</p> | <p>Python doesn't have variable declarations, so it has to figure out the <a href="http://docs.python.org/3.3/tutorial/classes.html#python-scopes-and-namespaces">scope</a> of variables itself. It does so by a simple rule: If there is an assignment to a variable inside a function, that variable is considered local.<sup><a href="http://docs.python.org/3.3/faq/programming.html#what-are-the-rules-for-local-and-global-variables-in-python">[1]</a></sup> Thus, the line</p>
<pre><code>counter += 1
</code></pre>
<p>implicitly makes <code>counter</code> local to <code>increment()</code>. Trying to execute this line, though, will try to read the value of the local variable <code>counter</code> before it is assigned, resulting in an <a href="http://docs.python.org/3.3/library/exceptions.html#UnboundLocalError"><code>UnboundLocalError</code></a>.<sup><a href="http://docs.python.org/3.3/faq/programming.html#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value">[2]</a></sup></p>
<p>If <code>counter</code> is a global variable, the <a href="http://docs.python.org/3.3/reference/simple_stmts.html#the-global-statement"><code>global</code></a> keyword will help. If <code>increment()</code> is a local function and <code>counter</code> a local variable, you can use <a href="http://docs.python.org/3.3/reference/simple_stmts.html#the-nonlocal-statement"><code>nonlocal</code></a> in Python 3.x.</p> | {
"question_id": 9264763,
"question_date": "2012-02-13T17:11:38.683Z",
"question_score": 210,
"tags": "python|scope|closures|global-variables",
"answer_id": 9264845,
"answer_date": "2012-02-13T17:15:54.227Z",
"answer_score": 206
} |
Please answer the following Stack Overflow question:
Title: JavaScript - get the first day of the week from current date
<p>I need the fastest way to get the first day of the week. For example: today is the 11th of November, and a Thursday; and I want the first day of this week, which is the 8th of November, and a Monday. I need the fastest method for MongoDB map function, any ideas? </p> | <p>Using the <code>getDay</code> method of Date objects, you can know the number of day of the week (being 0=Sunday, 1=Monday, etc).</p>
<p>You can then subtract that number of days plus one, for example:</p>
<pre><code>function getMonday(d) {
d = new Date(d);
var day = d.getDay(),
diff = d.getDate() - day + (day == 0 ? -6:1); // adjust when day is sunday
return new Date(d.setDate(diff));
}
getMonday(new Date()); // Mon Nov 08 2010
</code></pre> | {
"question_id": 4156434,
"question_date": "2010-11-11T16:06:27.970Z",
"question_score": 210,
"tags": "javascript|algorithm",
"answer_id": 4156516,
"answer_date": "2010-11-11T16:13:13.750Z",
"answer_score": 391
} |
Please answer the following Stack Overflow question:
Title: XML parsing of a variable string in JavaScript
<p>I have a <strong>variable string</strong> that contains well-formed and valid XML. I need to use JavaScript code to parse this feed.</p>
<p>How can I accomplish this using (browser-compatible) JavaScript code?</p> | <blockquote>
<p><em>Update: For a more correct answer see <a href="https://stackoverflow.com/a/8412989/2172">Tim Down's answer</a>.</em></p>
</blockquote>
<p>Internet Explorer and, for example, Mozilla-based browsers expose different objects for XML parsing, so it's wise to use a JavaScript framework like <a href="http://jquery.com/" rel="nofollow noreferrer">jQuery</a> to handle the cross-browsers differences.</p>
<p>A really basic example is:</p>
<pre><code>var xml = "<music><album>Beethoven</album></music>";
var result = $(xml).find("album").text();
</code></pre>
<p>Note: As pointed out in comments; jQuery does not really do any XML parsing whatsoever, it relies on the DOM innerHTML method and will parse it like it would any HTML so be careful when using HTML element names in your XML. But I think it works fairly good for simple XML 'parsing', but it's probably not suggested for intensive or 'dynamic' XML parsing where you do not upfront what XML will come down and this tests if everything parses as expected.</p> | {
"question_id": 649614,
"question_date": "2009-03-16T08:17:19.737Z",
"question_score": 210,
"tags": "javascript|xml|parsing",
"answer_id": 649655,
"answer_date": "2009-03-16T08:43:45.680Z",
"answer_score": 93
} |
Please answer the following Stack Overflow question:
Title: How to check if a table exists in a given schema
<p>Postgres 8.4 and greater databases contain common tables in <code>public</code> schema and company specific tables in <code>company</code> schema.<br>
<code>company</code> schema names always start with <code>'company'</code> and end with the company number.<br>
So there may be schemas like:</p>
<pre><code>public
company1
company2
company3
...
companynn
</code></pre>
<p>An application always works with a single company.<br>
The <code>search_path</code> is specified accordingly in odbc or npgsql connection string, like:</p>
<pre><code>search_path='company3,public'
</code></pre>
<p>How would you check if a given table exists in a specified <code>companyn</code> schema?</p>
<p>eg:</p>
<pre><code>select isSpecific('company3','tablenotincompany3schema')
</code></pre>
<p>should return <code>false</code>, and</p>
<pre><code>select isSpecific('company3','tableincompany3schema')
</code></pre>
<p>should return <code>true</code>.</p>
<p>In any case, the function should check only <code>companyn</code> schema passed, not other schemas.</p>
<p>If a given table exists in both <code>public</code> and the passed schema, the function should return <code>true</code>.<br>
It should work for Postgres 8.4 or later.</p> | <p>It depends on what you want to test <em><strong>exactly</strong></em>.</p>
<h3>Information schema?</h3>
<p>To find "whether the table exists" (<em>no matter who's asking</em>), querying the information schema (<code>information_schema.tables</code>) is <strong>incorrect</strong>, strictly speaking, because (<a href="https://www.postgresql.org/docs/current/infoschema-tables.html" rel="nofollow noreferrer">per documentation</a>):</p>
<blockquote>
<p>Only those tables and views are shown that the current user has access
to (by way of being the owner or having some privilege).</p>
</blockquote>
<p>The query <a href="https://stackoverflow.com/a/20584058/939860">provided by @kong</a> can return <code>FALSE</code>, but the table can still exist. It answers the question:</p>
<p><em><strong>How to check whether a table (or view) exists, and the current user has access to it?</strong></em></p>
<pre class="lang-sql prettyprint-override"><code>SELECT EXISTS (
SELECT FROM information_schema.tables
WHERE table_schema = 'schema_name'
AND table_name = 'table_name'
);
</code></pre>
<p>The information schema is mainly useful to stay portable across major versions and across different RDBMS. But the implementation is slow, because Postgres has to use sophisticated views to comply to the standard (<code>information_schema.tables</code> is a rather simple example). And some information (like OIDs) gets lost in translation from the system catalogs - which <em>actually</em> carry all information.</p>
<h3>System catalogs</h3>
<p>Your question was:</p>
<p><em><strong>How to check whether a table exists?</strong></em></p>
<pre class="lang-sql prettyprint-override"><code>SELECT EXISTS (
SELECT FROM pg_catalog.pg_class c
JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE n.nspname = 'schema_name'
AND c.relname = 'table_name'
AND c.relkind = 'r' -- only tables
);
</code></pre>
<p>Use the system catalogs <code>pg_class</code> and <code>pg_namespace</code> directly, which is also considerably faster. However, <a href="https://www.postgresql.org/docs/current/catalog-pg-class.html" rel="nofollow noreferrer">per documentation on <code>pg_class</code></a>:</p>
<blockquote>
<p>The catalog <code>pg_class</code> catalogs tables and most everything else that has
columns or is otherwise similar to a table. This includes <strong>indexes</strong> (but
see also <code>pg_index</code>), <strong>sequences</strong>, <strong>views</strong>, <strong>materialized views</strong>, <strong>composite
types</strong>, and <strong>TOAST tables</strong>;</p>
</blockquote>
<p>For this particular question you can also use the <a href="https://www.postgresql.org/docs/current/view-pg-tables.html" rel="nofollow noreferrer">system view <strong><code>pg_tables</code></strong></a>. A bit simpler and more portable across major Postgres versions (which is hardly of concern for this basic query):</p>
<pre class="lang-sql prettyprint-override"><code>SELECT EXISTS (
SELECT FROM pg_tables
WHERE schemaname = 'schema_name'
AND tablename = 'table_name'
);
</code></pre>
<p>Identifiers have to be unique among <em>all</em> objects mentioned above. If you want to ask:</p>
<p><em><strong>How to check whether a name for a table or similar object in a given schema is taken?</strong></em></p>
<pre class="lang-sql prettyprint-override"><code>SELECT EXISTS (
SELECT FROM pg_catalog.pg_class c
JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE n.nspname = 'schema_name'
AND c.relname = 'table_name'
);
</code></pre>
<ul>
<li><a href="https://dba.stackexchange.com/a/75124/3684">Related answer on dba.SE discussing <strong>"Information schema vs. system catalogs"</strong></a></li>
</ul>
<h2>Alternative: cast to <a href="https://www.postgresql.org/docs/current/datatype-oid.html" rel="nofollow noreferrer"><strong><code>regclass</code></strong></a></h2>
<pre><code>SELECT 'schema_name.table_name'::regclass;
</code></pre>
<p>This <em>raises an exception</em> if the (optionally schema-qualified) table (or other object occupying that name) does not exist.</p>
<p>If you do not schema-qualify the table name, a cast to <code>regclass</code> defaults to the <a href="https://stackoverflow.com/a/9067777/939860"><strong><code>search_path</code></strong></a> and returns the OID for the first table found - or an exception if the table is in none of the listed schemas. Note that the system schemas <code>pg_catalog</code> and <code>pg_temp</code> (the schema for temporary objects of the current session) are automatically part of the <code>search_path</code>.</p>
<p>You can use that and catch a possible exception in a function. Example:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/11905868/Check-if-sequence-exists-in-Postgres-plpgsql/11919600#11919600">Check if sequence exists in Postgres (plpgsql)</a></li>
</ul>
<p>A query like above avoids possible exceptions and is therefore slightly faster.</p>
<p>Note that the each component of the name is treated as <strong>identifier</strong> here - as opposed to above queries where names are given as literal strings. Identifiers are cast to lower case unless double-quoted. If you have forced otherwise illegal identifiers with double-quotes, those need to be included. Like:</p>
<pre><code>SELECT '"Dumb_SchName"."FoolishTbl"'::regclass;
</code></pre>
<p>See:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/20878932/are-postgresql-column-names-case-sensitive/20880247#20880247">Are PostgreSQL column names case-sensitive?</a></li>
</ul>
<h2><a href="https://www.postgresql.org/docs/current/functions-info.html#FUNCTIONS-INFO-CATALOG-TABLE" rel="nofollow noreferrer"><code>to_regclass(rel_name)</code></a> in Postgres 9.4+</h2>
<p>Much simpler now:</p>
<pre><code>SELECT to_regclass('schema_name.table_name');
</code></pre>
<p>Same as the cast, <a href="https://www.postgresql.org/docs/current/functions-info.html#FUNCTIONS-INFO-CATALOG-TABLE" rel="nofollow noreferrer"><strong>but</strong> it returns ...</a></p>
<blockquote>
<p>... null rather than throwing an error if the name is not found</p>
</blockquote> | {
"question_id": 20582500,
"question_date": "2013-12-14T11:07:45.177Z",
"question_score": 210,
"tags": "sql|database|postgresql|information-schema|search-path",
"answer_id": 24089729,
"answer_date": "2014-06-06T19:58:11.623Z",
"answer_score": 374
} |
Please answer the following Stack Overflow question:
Title: How to suppress warnings globally in an R Script
<p>I have a long R script that throws some warnings, which I can ignore.
I could use </p>
<pre><code>suppressWarnings(expr)
</code></pre>
<p>for single statements. But how can I suppress warnings in R globally? Is there an option for this?</p> | <p>You could use</p>
<pre><code>options(warn=-1)
</code></pre>
<p>But note that turning off warning messages globally might not be a good idea.</p>
<p>To turn warnings back on, use</p>
<pre><code>options(warn=0)
</code></pre>
<p>(or whatever your default is for <code>warn</code>, see <a href="https://stackoverflow.com/a/32719422/2093469">this answer</a>)</p> | {
"question_id": 16194212,
"question_date": "2013-04-24T14:09:30.167Z",
"question_score": 210,
"tags": "r|warnings",
"answer_id": 16194365,
"answer_date": "2013-04-24T14:15:37.413Z",
"answer_score": 268
} |
Please answer the following Stack Overflow question:
Title: Spring Boot yaml configuration for a list of strings
<p>I am trying to load an array of strings from <code>application.yml</code> file. This is the config:</p>
<pre><code>ignore:
filenames:
- .DS_Store
- .hg
</code></pre>
<p>This is the class:</p>
<pre><code>@Value("${ignore.filenames}")
private List<String> igonoredFileNames = new ArrayList<>();
</code></pre>
<p>There are other configurations in the same class that loads just fine. There are no tabs in my YAML file. Still, I get the following exception:</p>
<pre><code>Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'ignore.filenames' in string value "${ignore.filenames}"
</code></pre> | <p>My <em>guess</em> is, that the <code>@Value</code> can not cope with "complex" types. You can go with a prop class like this:</p>
<pre><code>@Component
@ConfigurationProperties('ignore')
class IgnoreSettings {
List<String> filenames
}
</code></pre>
<p><strong>Please note:</strong> This code is <em>Groovy</em> - <strong>not Java</strong> - to keep the example short! See the comments for tips how to adopt.</p>
<p>See the complete example <a href="https://github.com/christoph-frick/so-springboot-yaml-string-list" rel="noreferrer">https://github.com/christoph-frick/so-springboot-yaml-string-list</a> </p> | {
"question_id": 26699385,
"question_date": "2014-11-02T12:40:07.967Z",
"question_score": 210,
"tags": "spring-boot",
"answer_id": 26700938,
"answer_date": "2014-11-02T15:26:51.817Z",
"answer_score": 97
} |
Please answer the following Stack Overflow question:
Title: Write string to text file and ensure it always overwrites the existing content.
<p>I have a string with a C# program that I want to write to a file and always overwrite the existing content. If the file isn't there, the program should create a new file instead of throwing an exception.</p> | <pre><code>System.IO.File.WriteAllText (@"D:\path.txt", contents);
</code></pre>
<ul>
<li>If the file exists, this overwrites it.</li>
<li>If the file does not exist, this creates it. </li>
<li>Please make sure you have appropriate privileges to write at the location, otherwise you will get an exception.</li>
</ul> | {
"question_id": 1225857,
"question_date": "2009-08-04T05:52:27.420Z",
"question_score": 210,
"tags": "c#|file|text",
"answer_id": 1225869,
"answer_date": "2009-08-04T05:56:44.713Z",
"answer_score": 432
} |
Please answer the following Stack Overflow question:
Title: What's the equivalent of Java's Thread.sleep() in JavaScript?
<p>What's the equivalent of Java's <code>Thread.sleep()</code> in JavaScript?</p> | <p>The simple answer is that there is no such function.</p>
<p>The closest thing you have is:</p>
<pre><code>var millisecondsToWait = 500;
setTimeout(function() {
// Whatever you want to do after the wait
}, millisecondsToWait);
</code></pre>
<p>Note that you <em>especially</em> don't want to busy-wait (e.g. in a spin loop), since your browser is almost certainly executing your JavaScript in a single-threaded environment.</p>
<p>Here are a couple of other SO questions that deal with threads in JavaScript:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/30036/javascript-and-threads">JavaScript and Threads</a></li>
<li><a href="https://stackoverflow.com/questions/39879/why-doesnt-javascript-support-multithreading">Why doesn't JavaScript support multithreading?</a></li>
</ul>
<p>And this question may also be helpful:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/797115/javascript-settimeout-without-putting-code-into-a-string">setTimeout - how to avoid using string for callback?</a></li>
</ul> | {
"question_id": 1447407,
"question_date": "2009-09-19T01:06:04.270Z",
"question_score": 210,
"tags": "java|javascript",
"answer_id": 1447421,
"answer_date": "2009-09-19T01:18:38.880Z",
"answer_score": 237
} |
Please answer the following Stack Overflow question:
Title: What use is find_package() when you need to specify CMAKE_MODULE_PATH?
<p>I'm trying to get a cross-plattform build system working using CMake. Now the software has a few dependencies. I compiled them myself and installed them on my system.</p>
<p>Some example files which got installed:</p>
<pre><code>-- Installing: /usr/local/share/SomeLib/SomeDir/somefile
-- Installing: /usr/local/share/SomeLib/SomeDir/someotherfile
-- Installing: /usr/local/lib/SomeLib/somesharedlibrary
-- Installing: /usr/local/lib/SomeLib/cmake/FindSomeLib.cmake
-- Installing: /usr/local/lib/SomeLib/cmake/HelperFile.cmake
</code></pre>
<p>Now CMake has a <code>find_package()</code> which opens a <code>Find*.cmake</code> file and searches after the library on the system and defines some variables like <code>SomeLib_FOUND</code> etc.</p>
<p>My CMakeLists.txt contains something like this:</p>
<pre><code>set(CMAKE_MODULE_PATH "/usr/local/lib/SomeLib/cmake/;${CMAKE_MODULE_PATH}")
find_package(SomeLib REQUIRED)
</code></pre>
<p>The first command defines where CMake searches after the <code>Find*.cmake</code> and I added the directory of <code>SomeLib</code> where the <code>FindSomeLib.cmake</code> can be found, so <code>find_package()</code> works
as expected.</p>
<p>But this is kind of weird because one of the reasons why <code>find_package()</code> exists is to get away from non-cross-plattform hard coded paths.</p>
<p>How is this usually done? Should I copy the <code>cmake/</code> directory of <code>SomeLib</code> into my project and set the <code>CMAKE_MODULE_PATH</code> relatively?</p> | <p>Command <code>find_package</code> has two modes: <code>Module</code> mode and <code>Config</code> mode. You are trying to
use <code>Module</code> mode when you actually need <code>Config</code> mode.</p>
<h3>Module mode</h3>
<p><code>Find<package>.cmake</code> file located <strong>within</strong> your project. Something like this:</p>
<pre><code>CMakeLists.txt
cmake/FindFoo.cmake
cmake/FindBoo.cmake
</code></pre>
<p><code>CMakeLists.txt</code> content:</p>
<pre><code>list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_LIST_DIR}/cmake")
find_package(Foo REQUIRED) # FOO_INCLUDE_DIR, FOO_LIBRARIES
find_package(Boo REQUIRED) # BOO_INCLUDE_DIR, BOO_LIBRARIES
include_directories("${FOO_INCLUDE_DIR}")
include_directories("${BOO_INCLUDE_DIR}")
add_executable(Bar Bar.hpp Bar.cpp)
target_link_libraries(Bar ${FOO_LIBRARIES} ${BOO_LIBRARIES})
</code></pre>
<p>Note that <code>CMAKE_MODULE_PATH</code> has high priority and may be usefull when you need to rewrite standard <code>Find<package>.cmake</code> file.</p>
<h3>Config mode (install)</h3>
<p><code><package>Config.cmake</code> file located <strong>outside</strong> and produced by <code>install</code>
command of other project (<code>Foo</code> for example).</p>
<p><code>foo</code> library:</p>
<pre><code>> cat CMakeLists.txt
cmake_minimum_required(VERSION 2.8)
project(Foo)
add_library(foo Foo.hpp Foo.cpp)
install(FILES Foo.hpp DESTINATION include)
install(TARGETS foo DESTINATION lib)
install(FILES FooConfig.cmake DESTINATION lib/cmake/Foo)
</code></pre>
<p>Simplified version of config file:</p>
<pre><code>> cat FooConfig.cmake
add_library(foo STATIC IMPORTED)
find_library(FOO_LIBRARY_PATH foo HINTS "${CMAKE_CURRENT_LIST_DIR}/../../")
set_target_properties(foo PROPERTIES IMPORTED_LOCATION "${FOO_LIBRARY_PATH}")
</code></pre>
<p>By default project installed in <code>CMAKE_INSTALL_PREFIX</code> directory:</p>
<pre><code>> cmake -H. -B_builds
> cmake --build _builds --target install
-- Install configuration: ""
-- Installing: /usr/local/include/Foo.hpp
-- Installing: /usr/local/lib/libfoo.a
-- Installing: /usr/local/lib/cmake/Foo/FooConfig.cmake
</code></pre>
<h3>Config mode (use)</h3>
<p>Use <code>find_package(... CONFIG)</code> to include <code>FooConfig.cmake</code> with imported target <code>foo</code>:</p>
<pre><code>> cat CMakeLists.txt
cmake_minimum_required(VERSION 2.8)
project(Boo)
# import library target `foo`
find_package(Foo CONFIG REQUIRED)
add_executable(boo Boo.cpp Boo.hpp)
target_link_libraries(boo foo)
> cmake -H. -B_builds -DCMAKE_VERBOSE_MAKEFILE=ON
> cmake --build _builds
Linking CXX executable Boo
/usr/bin/c++ ... -o Boo /usr/local/lib/libfoo.a
</code></pre>
<p>Note that imported target is <strong>highly</strong> configurable. See my <a href="https://stackoverflow.com/a/20838147/2288008">answer</a>.</p>
<p><strong>Update</strong></p>
<ul>
<li><a href="https://github.com/forexample/package-example" rel="noreferrer">Example</a></li>
</ul> | {
"question_id": 20746936,
"question_date": "2013-12-23T15:57:59.563Z",
"question_score": 210,
"tags": "cmake",
"answer_id": 20857070,
"answer_date": "2013-12-31T12:00:21.290Z",
"answer_score": 288
} |
Please answer the following Stack Overflow question:
Title: Same Navigation Drawer in different Activities
<p>I made a working navigation drawer like it's shown in the tutorial on the <a href="http://developer.android.com" rel="nofollow noreferrer">developer.android.com</a> website. But now, I want to use one Navigation Drawer, i created in the NavigationDrawer.class for multiple Activities in my Application.</p>
<p>My question is, if anyone here can make a little Tutorial, which explains, how to use one Navigation drawer for multiple Activities.</p>
<p>I read it first at this Answer
<a href="https://stackoverflow.com/q/18697966/2876645">Android Navigation Drawer on multiple Activities</a></p>
<p>but it didn't work on my Project</p>
<pre><code>public class NavigationDrawer extends Activity {
public DrawerLayout drawerLayout;
public ListView drawerList;
private ActionBarDrawerToggle drawerToggle;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerToggle = new ActionBarDrawerToggle((Activity) this, drawerLayout, R.drawable.ic_drawer, 0, 0) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(R.string.app_name);
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(R.string.menu);
}
};
drawerLayout.setDrawerListener(drawerToggle);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
listItems = getResources().getStringArray(R.array.layers_array);
drawerList = (ListView) findViewById(R.id.left_drawer);
drawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, android.R.id.text,
listItems));
drawerList.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
drawerClickEvent(pos);
}
});
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
}
</code></pre>
<p>In this Activity i want to have the Navigation Drawer so I extends 'NavigationDrawer' and in some other Activities i want to User the Same Navigation drawer</p>
<pre><code> public class SampleActivity extends NavigationDrawer {...}
</code></pre> | <p>If you want a navigation drawer, you should use fragments.
I followed this tutorial last week and it works great: </p>
<p><a href="http://developer.android.com/training/implementing-navigation/nav-drawer.html" rel="noreferrer">http://developer.android.com/training/implementing-navigation/nav-drawer.html</a></p>
<p>You can also download sample code from this tutorial, to see how you can do this.</p>
<hr>
<p>Without fragments:</p>
<p>This is your BaseActivity Code:</p>
<pre><code>public class BaseActivity extends Activity
{
public DrawerLayout drawerLayout;
public ListView drawerList;
public String[] layers;
private ActionBarDrawerToggle drawerToggle;
private Map map;
protected void onCreate(Bundle savedInstanceState)
{
// R.id.drawer_layout should be in every activity with exactly the same id.
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerToggle = new ActionBarDrawerToggle((Activity) this, drawerLayout, R.drawable.ic_drawer, 0, 0)
{
public void onDrawerClosed(View view)
{
getActionBar().setTitle(R.string.app_name);
}
public void onDrawerOpened(View drawerView)
{
getActionBar().setTitle(R.string.menu);
}
};
drawerLayout.setDrawerListener(drawerToggle);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
layers = getResources().getStringArray(R.array.layers_array);
drawerList = (ListView) findViewById(R.id.left_drawer);
View header = getLayoutInflater().inflate(R.layout.drawer_list_header, null);
drawerList.addHeaderView(header, null, false);
drawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, android.R.id.text1,
layers));
View footerView = ((LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(
R.layout.drawer_list_footer, null, false);
drawerList.addFooterView(footerView);
drawerList.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
map.drawerClickEvent(pos);
}
});
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
}
</code></pre>
<p>All the other Activities that needs to have a navigation drawer should extend this Activity instead of Activity itself, example:</p>
<pre><code>public class AnyActivity extends BaseActivity
{
//Because this activity extends BaseActivity it automatically has the navigation drawer
//You can just write your normal Activity code and you don't need to add anything for the navigation drawer
}
</code></pre>
<p><b>XML</b></p>
<pre><code><android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- The main content view -->
<FrameLayout
android:id="@+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<!-- Put what you want as your normal screen in here, you can also choose for a linear layout or any other layout, whatever you prefer -->
</FrameLayout>
<!-- The navigation drawer -->
<ListView android:id="@+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="@android:color/transparent"
android:dividerHeight="0dp"
android:background="#111"/>
</android.support.v4.widget.DrawerLayout>
</code></pre>
<hr>
<p><strong>Edit:</strong></p>
<p>I experienced some difficulties myself, so here is a solution if you get NullPointerExceptions. In BaseActivity change the onCreate function to <code>protected void onCreateDrawer()</code>. The rest can stay the same. In the Activities which extend BaseActivity put the code in this order:</p>
<pre><code> super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
super.onCreateDrawer();
</code></pre>
<p>This helped me fix my problem, hope it helps!</p>
<p>This is how you can create a navigation drawer with multiple activities, if you have any questions feel free to ask.</p>
<hr>
<p><strong>Edit 2:</strong></p>
<p>As said by @GregDan your <strong><code>BaseActivity</code></strong> can also override <code>setContentView()</code> and call onCreateDrawer there:</p>
<pre><code>@Override
public void setContentView(@LayoutRes int layoutResID)
{
super.setContentView(layoutResID);
onCreateDrawer() ;
}
</code></pre> | {
"question_id": 19451715,
"question_date": "2013-10-18T14:07:15.087Z",
"question_score": 210,
"tags": "android|android-activity|navigation|navigation-drawer|drawer",
"answer_id": 19451842,
"answer_date": "2013-10-18T14:12:39.767Z",
"answer_score": 189
} |
Please answer the following Stack Overflow question:
Title: Failed to open/create the internal network Vagrant on Windows10
<p>I upgraded my Windows 10 to the last update yesterday and now, when I launch <code>vagrant up</code> command, I get this error :</p>
<pre><code>==> default: Booting VM...
==> default: Waiting for machine to boot. This may take a few minutes...
The guest machine entered an invalid state while waiting for it
to boot. Valid states are 'starting, running'. The machine is in the
'poweroff' state. Please verify everything is configured
properly and try again.
If the provider you're using has a GUI that comes with it,
it is often helpful to open that and watch the machine, since the
GUI often has more helpful error messages than Vagrant can retrieve.
For example, if you're using VirtualBox, run `vagrant up` while the
VirtualBox GUI is open.
The primary issue for this error is that the provider you're using
is not properly configured. This is very rarely a Vagrant issue.
</code></pre>
<p>When I try with GUI I have this error :</p>
<pre><code>Failed to open/create the internal network 'HostInterfaceNetworking-VirtualBox Host-Only Ethernet Adapter' (VERR_INTNET_FLT_IF_NOT_FOUND).
Failed to attach the network LUN (VERR_INTNET_FLT_IF_NOT_FOUND).
</code></pre>
<p>I have re-installed VirtualBox 5.0.10 and the extension pack,
reconfigured Host-Only Ethernet Adapter, but always the same error...</p>
<p>Any ideas?</p> | <p>I found a solution</p>
<ol>
<li>Open Windows Network Connections</li>
<li>Right click on VirtualBox Host only adapter that created</li>
<li>Choose properties</li>
<li>Check "VirtualBox NDIS6 Bridged Networking driver"</li>
<li>disable and Enable the adapter</li>
</ol>
<p><a href="https://i.stack.imgur.com/Tkkws.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Tkkws.png" alt="Image"></a></p> | {
"question_id": 33725779,
"question_date": "2015-11-15T22:17:22.287Z",
"question_score": 210,
"tags": "vagrant|virtualbox|windows-10",
"answer_id": 33733454,
"answer_date": "2015-11-16T10:45:55.350Z",
"answer_score": 503
} |
Please answer the following Stack Overflow question:
Title: How can I download a specific Maven artifact in one command line?
<p>I can install an artifact by <code>install:install-file</code>,
but how can I download an artifact?</p>
<p>For example: </p>
<pre><code>mvn download:download-file -DgroupId=.. -DartifactId=.. -Dversion=LATEST
</code></pre> | <p>You could use the <a href="http://maven.apache.org/plugins/maven-dependency-plugin/" rel="noreferrer">maven dependency plugin</a> which has a nice <a href="http://maven.apache.org/plugins/maven-dependency-plugin/plugin-info.html" rel="noreferrer"><code>dependency:get</code></a> goal since version 2.1. No need for a pom, everything happens on the command line.</p>
<p>To make sure to find the <code>dependency:get</code> goal, you need to explicitly tell maven to use the version 2.1, i.e. you need to use the fully qualified name of the plugin, including the version: </p>
<pre><code>mvn org.apache.maven.plugins:maven-dependency-plugin:2.1:get \
-DrepoUrl=url \
-Dartifact=groupId:artifactId:version
</code></pre>
<p><strong>UPDATE:</strong> With older versions of Maven (prior to 2.1), it is possible to run <code>dependency:get</code> normally (without using the fully qualified name and version) by forcing your copy of maven to use a given version of a plugin. </p>
<p>This can be done as follows:</p>
<p><strong>1. Add the following line within the <code><settings></code> element of your <code>~/.m2/settings.xml</code> file:</strong> </p>
<pre><code><usePluginRegistry>true</usePluginRegistry>
</code></pre>
<p><strong>2. Add the file <code>~/.m2/plugin-registry.xml</code> with the following contents:</strong></p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<pluginRegistry xsi:schemaLocation="http://maven.apache.org/PLUGIN_REGISTRY/1.0.0 http://maven.apache.org/xsd/plugin-registry-1.0.0.xsd"
xmlns="http://maven.apache.org/PLUGIN_REGISTRY/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<useVersion>2.1</useVersion>
<rejectedVersions/>
</plugin>
</plugins>
</pluginRegistry>
</code></pre>
<p>But this doesn't seem to work anymore with maven 2.1/2.2. Actually, according to the <a href="http://maven.apache.org/guides/introduction/introduction-to-plugin-registry.html" rel="noreferrer">Introduction to the Plugin Registry</a>, features of the <code>plugin-registry.xml</code> have been redesigned (for portability) and the <em>plugin registry is currently in a semi-dormant state within Maven 2</em>. So I think we have to use the long name for now (when using the plugin without a pom, which is the idea behind <code>dependency:get</code>).</p> | {
"question_id": 1895492,
"question_date": "2009-12-13T03:49:53.670Z",
"question_score": 210,
"tags": "maven-2",
"answer_id": 1896110,
"answer_date": "2009-12-13T10:29:48.833Z",
"answer_score": 226
} |
Please answer the following Stack Overflow question:
Title: node.js TypeError: path must be absolute or specify root to res.sendFile [failed to parse JSON]
<p>[add]
So my next problem is that when i try adding a new dependence (npm install --save socket.io). The JSON file is also valid. I get this error:
Failed to parse json</p>
<pre><code>npm ERR! Unexpected string
npm ERR! File: /Users/John/package.json
npm ERR! Failed to parse package.json data.
npm ERR! package.json must be actual JSON, not just JavaScript.
npm ERR!
npm ERR! This is not a bug in npm.
npm ERR! Tell the package author to fix their package.json file. JSON.parse
</code></pre>
<p>So I've been trying to figure out why this error has been returning. All of the files (HTML,JSON,JS) are inside the same folder on my desktop. I'm using node.js and socket.io</p>
<p>This is my JS file:</p>
<pre><code>var app = require('express')();
var http = require('http').Server(app);
app.get('/', function(req, res){
res.sendFile('index.html');
});
http.listen(3000,function(){
console.log('listening on : 3000');
});
</code></pre>
<p>This is what is getting returned:</p>
<pre><code>MacBook-Pro:~ John$ node /Users/John/Desktop/Chatapp/index.js
listening on : 3000
TypeError: path must be absolute or specify root to res.sendFile
at ServerResponse.sendFile (/Users/John/node_modules/express/lib/response.js:389:11)
at /Users/John/Desktop/Chatapp/index.js:5:7
at Layer.handle [as handle_request] (/Users/John/node_modules/express/lib/router/layer.js:76:5)
at next (/Users/John/node_modules/express/lib/router/route.js:100:13)
at Route.dispatch (/Users/John/node_modules/express/lib/router/route.js:81:3)
at Layer.handle [as handle_request] (/Users/John/node_modules/express/lib/router/layer.js:76:5)
at /Users/John/node_modules/express/lib/router/index.js:234:24
at Function.proto.process_params (/Users/John/node_modules/express/lib/router/index.js:312:12)
at /Users/John/node_modules/express/lib/router/index.js:228:12
at Function.match_layer (/Users/John/node_modules/express/lib/router/index.js:295:3)
TypeError: path must be absolute or specify root to res.sendFile
at ServerResponse.sendFile (/Users/John/node_modules/express/lib/response.js:389:11)
at /Users/John/Desktop/Chatapp/index.js:5:7
at Layer.handle [as handle_request] (/Users/John/node_modules/express/lib/router/layer.js:76:5)
at next (/Users/John/node_modules/express/lib/router/route.js:100:13)
at Route.dispatch (/Users/John/node_modules/express/lib/router/route.js:81:3)
at Layer.handle [as handle_request] (/Users/John/node_modules/express/lib/router/layer.js:76:5)
at /Users/John/node_modules/express/lib/router/index.js:234:24
at Function.proto.process_params (/Users/John/node_modules/express/lib/router/index.js:312:12)
at /Users/John/node_modules/express/lib/router/index.js:228:12
at Function.match_layer (/Users/John/node_modules/express/lib/router/index.js:295:3)
</code></pre> | <p>The error is pretty clear, you need to specify an absolute (instead of relative) path and/or set <code>root</code> in the config object for <code>res.sendFile()</code>. Examples:</p>
<pre><code>// assuming index.html is in the same directory as this script
res.sendFile(__dirname + '/index.html');
</code></pre>
<p>or specify a root (which is used as the base path for the first argument to <code>res.sendFile()</code>:</p>
<pre><code>res.sendFile('index.html', { root: __dirname });
</code></pre>
<p>Specifying the <code>root</code> path is more useful when you're passing a user-generated file path which could potentially contain malformed/malicious parts like <code>..</code> (e.g. <code>../../../../../../etc/passwd</code>). Setting the <code>root</code> path prevents such malicious paths from being used to access files outside of that base path.</p> | {
"question_id": 26079611,
"question_date": "2014-09-27T22:02:29.933Z",
"question_score": 210,
"tags": "javascript|json|node.js|socket.io|dependencies",
"answer_id": 26079640,
"answer_date": "2014-09-27T22:06:18.650Z",
"answer_score": 432
} |
Please answer the following Stack Overflow question:
Title: Disable a particular Checkstyle rule for a particular line of code?
<p>I have a <a href="http://checkstyle.sourceforge.net" rel="noreferrer">Checkstyle</a> validation rule configured in my project, that prohibits to define class methods with more than 3 input parameters. The rule works fine for <em>my</em> classes, but sometimes I have to extend third-party classes, which do not obey this particular rule.</p>
<p>Is there a possibility to instruct Checkstyle that a certain method should be silently ignored?</p>
<p>BTW, I ended up with my own wrapper of Checkstyle: <a href="http://www.qulice.com" rel="noreferrer">qulice.com</a> (see <a href="http://www.yegor256.com/2014/08/13/strict-code-quality-control.html" rel="noreferrer">Strict Control of Java Code Quality</a>)</p> | <p>Check out the use of the supressionCommentFilter at <a href="http://checkstyle.sourceforge.net/config_filters.html#SuppressionCommentFilter" rel="noreferrer">http://checkstyle.sourceforge.net/config_filters.html#SuppressionCommentFilter</a>. You'll need to add the module to your checkstyle.xml</p>
<pre><code><module name="SuppressionCommentFilter"/>
</code></pre>
<p>and it's configurable. Thus you can add comments to your code to turn off checkstyle (at various levels) and then back on again through the use of comments in your code. E.g.</p>
<pre><code>//CHECKSTYLE:OFF
public void someMethod(String arg1, String arg2, String arg3, String arg4) {
//CHECKSTYLE:ON
</code></pre>
<p>Or even better, use this more tweaked version:</p>
<pre><code><module name="SuppressionCommentFilter">
<property name="offCommentFormat" value="CHECKSTYLE.OFF\: ([\w\|]+)"/>
<property name="onCommentFormat" value="CHECKSTYLE.ON\: ([\w\|]+)"/>
<property name="checkFormat" value="$1"/>
</module>
</code></pre>
<p>which allows you to turn off specific checks for specific lines of code:</p>
<pre><code>//CHECKSTYLE.OFF: IllegalCatch - Much more readable than catching 7 exceptions
catch (Exception e)
//CHECKSTYLE.ON: IllegalCatch
</code></pre>
<p>*Note: you'll also have to add the <code>FileContentsHolder</code>:</p>
<pre><code><module name="FileContentsHolder"/>
</code></pre>
<p>See also</p>
<pre><code><module name="SuppressionFilter">
<property name="file" value="docs/suppressions.xml"/>
</module>
</code></pre>
<p>under the <code>SuppressionFilter</code> section on that same page, which allows you to turn off individual checks for pattern matched resources.</p>
<p>So, if you have in your checkstyle.xml:</p>
<pre><code><module name="ParameterNumber">
<property name="id" value="maxParameterNumber"/>
<property name="max" value="3"/>
<property name="tokens" value="METHOD_DEF"/>
</module>
</code></pre>
<p>You can turn it off in your suppression xml file with:</p>
<pre><code><suppress id="maxParameterNumber" files="YourCode.java"/>
</code></pre>
<p>Another method, now available in Checkstyle 5.7 is to suppress violations via the <code>@SuppressWarnings</code> java annotation. To do this, you will need to add two new modules (<code>SuppressWarningsFilter</code> and <code>SuppressWarningsHolder</code>) in your configuration file:</p>
<pre><code><module name="Checker">
...
<module name="SuppressWarningsFilter" />
<module name="TreeWalker">
...
<module name="SuppressWarningsHolder" />
</module>
</module>
</code></pre>
<p>Then, within your code you can do the following:</p>
<pre><code>@SuppressWarnings("checkstyle:methodlength")
public void someLongMethod() throws Exception {
</code></pre>
<p>or, for multiple suppressions:</p>
<pre><code>@SuppressWarnings({"checkstyle:executablestatementcount", "checkstyle:methodlength"})
public void someLongMethod() throws Exception {
</code></pre>
<p><strong>NB:</strong> The "<code>checkstyle:</code>" prefix is optional (but recommended). According to the docs the parameter name have to be in all lowercase, but practice indicates any case works.</p> | {
"question_id": 4023185,
"question_date": "2010-10-26T11:32:39.670Z",
"question_score": 210,
"tags": "java|checkstyle",
"answer_id": 4023351,
"answer_date": "2010-10-26T11:52:40.553Z",
"answer_score": 326
} |
Please answer the following Stack Overflow question:
Title: Mocking HttpClient in unit tests
<p>I have some issues trying to wrap my code to be used in unit tests. The issues is this. I have the interface <code>IHttpHandler</code>:</p>
<pre><code>public interface IHttpHandler
{
HttpClient client { get; }
}
</code></pre>
<p>And the class using it, <code>HttpHandler</code>:</p>
<pre><code>public class HttpHandler : IHttpHandler
{
public HttpClient client
{
get
{
return new HttpClient();
}
}
}
</code></pre>
<p>And then the <code>Connection</code> class, which uses simpleIOC to inject the client implementation:</p>
<pre><code>public class Connection
{
private IHttpHandler _httpClient;
public Connection(IHttpHandler httpClient)
{
_httpClient = httpClient;
}
}
</code></pre>
<p>And then I have a unit test project which has this class:</p>
<pre><code>private IHttpHandler _httpClient;
[TestMethod]
public void TestMockConnection()
{
var client = new Connection(_httpClient);
client.doSomething();
// Here I want to somehow create a mock instance of the http client
// Instead of the real one. How Should I approach this?
}
</code></pre>
<p>Now obviously I will have methods in the <code>Connection</code> class that will retrieve data (JSON) from a my back end. However, I want to write unit tests for this class, and obviously I don't want to write tests against the real back end, rather a mocked one. I Have tried to google a good answer to this without great success. I can and have used Moq to mock before, but never on something like <code>HttpClient</code>. How should I approach this problem?</p> | <p>Your interface exposes the concrete <code>HttpClient</code> class, therefore any classes that use this interface are tied to it, this means that it cannot be mocked.</p>
<p><code>HttpClient</code> does not inherit from any interface so you will have to write your own. I suggest a <strong>decorator-like</strong> pattern:</p>
<pre><code>public interface IHttpHandler
{
HttpResponseMessage Get(string url);
HttpResponseMessage Post(string url, HttpContent content);
Task<HttpResponseMessage> GetAsync(string url);
Task<HttpResponseMessage> PostAsync(string url, HttpContent content);
}
</code></pre>
<p>And your class will look like this:</p>
<pre><code>public class HttpClientHandler : IHttpHandler
{
private HttpClient _client = new HttpClient();
public HttpResponseMessage Get(string url)
{
return GetAsync(url).Result;
}
public HttpResponseMessage Post(string url, HttpContent content)
{
return PostAsync(url, content).Result;
}
public async Task<HttpResponseMessage> GetAsync(string url)
{
return await _client.GetAsync(url);
}
public async Task<HttpResponseMessage> PostAsync(string url, HttpContent content)
{
return await _client.PostAsync(url, content);
}
}
</code></pre>
<p>The point in all of this is that <code>HttpClientHandler</code> creates its own <code>HttpClient</code>, you could then of course create multiple classes that implement <code>IHttpHandler</code> in different ways.</p>
<p>The main issue with this approach is that you are effectively writing a class that just calls methods in another class, however you could create a class that <strong>inherits</strong> from <code>HttpClient</code> (See <strong>Nkosi's example</strong>, it's a much better approach than mine). Life would be much easier if <code>HttpClient</code> had an interface that you could mock, unfortunately it does not.</p>
<p>This example is <strong>not</strong> the golden ticket however. <code>IHttpHandler</code> still relies on <code>HttpResponseMessage</code>, which belongs to <code>System.Net.Http</code> namespace, therefore if you do need other implementations other than <code>HttpClient</code>, you will have to perform some kind of mapping to convert their responses into <code>HttpResponseMessage</code> objects. This of course is only a problem <strong>if you need to use multiple implementations</strong> of <code>IHttpHandler</code> but it doesn't look like you do so it's not the end of the world, but it's something to think about.</p>
<p>Anyway, you can simply mock <code>IHttpHandler</code> without having to worry about the concrete <code>HttpClient</code> class as it has been abstracted away.</p>
<p>I recommend testing the <strong>non-async</strong> methods, as these still call the asynchronous methods but without the hassle of having to worry about unit testing asynchronous methods, see <a href="https://stackoverflow.com/questions/10556350/unit-testing-asynchronous-operation">here</a></p> | {
"question_id": 36425008,
"question_date": "2016-04-05T11:23:53.517Z",
"question_score": 210,
"tags": "c#|unit-testing|moq",
"answer_id": 36425948,
"answer_date": "2016-04-05T12:06:37.233Z",
"answer_score": 55
} |
Please answer the following Stack Overflow question:
Title: Xcode 4 - "Valid signing identity not found" error on provisioning profiles on a new Macintosh install
<p>I had a Macintosh I used to develop iPhone apps with using Xcode 4.
I now have a new Macintosh with a new install of... everything.</p>
<p>When opening Xcode projects built on the old Mac, I cannot run the app on the iPhone that was configured as a development iPhone.<br />
Xcode 4 organizer tells me "Valid signing identity not found" on my provisioning profiles.</p>
<p>I guess this is something to do with the .certSigningRequest file I had generated before on the old Mac (I have a backup of that file), but what do I have to do with it on the new Mac?</p>
<p>Another strange thing, I don't see my 5 existing provisioning profiles (defined on Apple provisioning portal) in the organizer, even after a refresh and after having entered my provisioning portal login and password :</p>
<p><a href="https://i.stack.imgur.com/iz9AM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iz9AM.png" alt="organizer devices screenshot" /></a></p> | <p>With Xcode 4.2 and later versions, including Xcode 4.6, there is a better way to migrate your entire developer profile to a new machine. On your existing machine, launch Xcode and do this:</p>
<ol>
<li>Open the Organizer (Shift-Command-2).</li>
<li>Select the Devices tab.</li>
<li>Choose Developer Profile in the upper-left corner under LIBRARY, which may be under the heading library or under a heading called TEAMS.</li>
<li>Choose Export near the bottom left side of
the window. Xcode asks you to choose a file name and password.</li>
</ol>
<p><strong>Edit for Xcode 4.4:</strong></p>
<p>With Xcode 4.4, at step 3 choose Provisioning Profiles under LIBRARY. Then select your provisioning profiles either with the mouse or Command-A.</p>
<p>Also, Apple is making improvements in the way they manage this aspect of Xcode, and some users have reported that the <strong><em>Refresh</em></strong> button in the lower-right corner does the trick. So try clicking Refresh first, and if that doesn't help, do the export/import sequence.</p>
<p><strong>Picture for Xcode 4.6 added by WP</strong></p>
<p><a href="https://i.stack.imgur.com/VCLcP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VCLcP.png" alt="screenshot of enter password to secure developer profile" /></a></p>
<p><strong>Edit for Xcode 5.0 or newer:</strong></p>
<ol>
<li>Open Xcode -> Preferences ('Command' + ',')</li>
<li>Select the <strong>Apple ID</strong> from the list.</li>
<li>Click on the SETTING icon near the bottom-left corner of window, and choose EXPORT ACCOUNTS... Xcode asks you to choose a file name and password.</li>
</ol>
<p>On your new machine, launch Xcode and import the profile you exported above. Works like a charm.</p>
<p><strong>Picture for Xcode 5.0 added by Ankur</strong></p>
<p><a href="https://i.stack.imgur.com/qH8IL.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qH8IL.jpg" alt="For Xcode 5 or newer versions" /></a></p> | {
"question_id": 6769345,
"question_date": "2011-07-20T22:34:24.750Z",
"question_score": 210,
"tags": "iphone|xcode|certificate|keychain|provisioning-profile",
"answer_id": 8509545,
"answer_date": "2011-12-14T18:12:26.837Z",
"answer_score": 222
} |
Please answer the following Stack Overflow question:
Title: Proper use of errors
<p>I'm using TypeScript for a reasonably large project, and am wondering what the standard is for the use of <code>Error</code>s. For example, say I hand an index out of bounds exception in Java:</p>
<pre><code>throw new IndexOutOfBoundsException();
</code></pre>
<p>Would the equivalent statement in TypeScript be:</p>
<pre><code>throw new Error("Index Out of Bounds");
</code></pre>
<p>What other ways could I accomplish this? What is the accepted standard?</p> | <p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" rel="noreferrer">Someone posted this link to the MDN in a comment, and I think it was very helpful</a>. It describes things like ErrorTypes very thoroughly.</p>
<blockquote>
<p><strong>EvalError</strong> --- Creates an instance representing an error that occurs regarding the global function eval().</p>
<p><strong>InternalError</strong> --- Creates an instance representing an error that occurs when an internal error in the JavaScript engine is thrown. E.g.
"too much recursion".</p>
<p><strong>RangeError</strong> --- Creates an instance representing an error that occurs when a numeric variable or parameter is outside of its valid
range.</p>
<p><strong>ReferenceError</strong> --- Creates an instance representing an error that occurs when de-referencing an invalid reference.</p>
<p><strong>SyntaxError</strong> --- Creates an instance representing a syntax error that occurs while parsing code in eval().</p>
<p><strong>TypeError</strong> --- Creates an instance representing an error that occurs when a variable or parameter is not of a valid type.</p>
<p><strong>URIError</strong> --- Creates an instance representing an error that occurs when encodeURI() or decodeURI() are passed invalid parameters.</p>
</blockquote> | {
"question_id": 23790509,
"question_date": "2014-05-21T17:53:58.670Z",
"question_score": 210,
"tags": "exception|typescript",
"answer_id": 33122167,
"answer_date": "2015-10-14T09:54:47.890Z",
"answer_score": 201
} |
Please answer the following Stack Overflow question:
Title: Adjust icon size of Floating action button (fab)
<p><img src="https://i.stack.imgur.com/N4Jzt.png" alt="Floating button">
The new floating action button should be <strong>56dp x 56dp</strong> and the icon inside it should be <strong>24dp x 24dp</strong>. So the space between icon and button should be <strong>16dp</strong>.</p>
<pre><code><ImageButton
android:id="@+id/fab_add"
android:layout_width="56dp"
android:layout_height="56dp"
android:layout_gravity="bottom|right"
android:layout_marginBottom="16dp"
android:layout_marginRight="16dp"
android:background="@drawable/ripple_oval"
android:elevation="8dp"
android:src="@drawable/ic_add_black_48dp" />
</code></pre>
<p>ripple_oval.xml
</p>
<pre><code><ripple xmlns:android="http://schemas.android.com/apk/res/android"
android:color="?android:colorControlHighlight">
<item>
<shape android:shape="oval">
<solid android:color="?android:colorAccent" />
</shape>
</item>
</ripple>
</code></pre>
<p>And this is the result I get: <br>
<img src="https://i.stack.imgur.com/8BVKM.png" alt="Floating button result"> <br>
I used the icon from <em>\material-design-icons-1.0.0\content\drawable-hdpi\ic_add_black_48dp.png</em> <br>
<a href="https://github.com/google/material-design-icons/releases/tag/1.0.1">https://github.com/google/material-design-icons/releases/tag/1.0.1</a></p>
<p>How to make the <strong>size of the icon</strong> inside the button be <strong>exactly</strong> as described in guidelines ?</p>
<p><a href="http://www.google.com/design/spec/components/buttons.html#buttons-floating-action-button">http://www.google.com/design/spec/components/buttons.html#buttons-floating-action-button</a></p> | <p>As your content is 24dp x 24dp you should use <a href="https://github.com/google/material-design-icons/blob/master/content/drawable-hdpi/ic_add_black_24dp.png">24dp icon</a>. And then set <code>android:scaleType="center"</code> in your ImageButton to avoid auto resize.</p> | {
"question_id": 27484126,
"question_date": "2014-12-15T12:28:27.427Z",
"question_score": 210,
"tags": "android|material-design|floating-action-button|material-components-android|android-icons",
"answer_id": 27484368,
"answer_date": "2014-12-15T12:41:53.323Z",
"answer_score": 193
} |
Please answer the following Stack Overflow question:
Title: Most concise way to convert a Set<T> to a List<T>
<p>For example, I am currently doing this:</p>
<pre><code>Set<String> setOfTopicAuthors = ....
List<String> list = Arrays.asList(
setOfTopicAuthors.toArray( new String[0] ) );
</code></pre>
<p>Can you beat this ?</p> | <pre><code>List<String> list = new ArrayList<String>(listOfTopicAuthors);
</code></pre> | {
"question_id": 2319538,
"question_date": "2010-02-23T15:54:13.403Z",
"question_score": 210,
"tags": "java|list|collections|set|java-6",
"answer_id": 2319555,
"answer_date": "2010-02-23T15:56:06.867Z",
"answer_score": 448
} |
Please answer the following Stack Overflow question:
Title: How to refer to relative paths of resources when working with a code repository
<p>We are working with a code repository which is deployed to both Windows and Linux - sometimes in different directories. How should one of the modules inside the project refer to one of the non-Python resources in the project (CSV files, etc.)?</p>
<p>If we do something like:</p>
<pre><code>thefile = open('test.csv')
</code></pre>
<p>or:</p>
<pre><code>thefile = open('../somedirectory/test.csv')
</code></pre>
<p>It will work only when the script is run from one specific directory, or a subset of the directories.</p>
<p>What I would like to do is something like:</p>
<pre><code>path = getBasePathOfProject() + '/somedirectory/test.csv'
thefile = open(path)
</code></pre>
<p>Is it possible?</p> | <p>Try to use a filename relative to the current files path. Example for './my_file':</p>
<pre><code>fn = os.path.join(os.path.dirname(__file__), 'my_file')
</code></pre>
<p>In Python 3.4+ you can also use <a href="https://docs.python.org/3/library/pathlib.html" rel="noreferrer">pathlib</a>:</p>
<pre><code>fn = pathlib.Path(__file__).parent / 'my_file'
</code></pre> | {
"question_id": 1270951,
"question_date": "2009-08-13T09:22:30.130Z",
"question_score": 210,
"tags": "python|path|relative-path",
"answer_id": 1270970,
"answer_date": "2009-08-13T09:27:28.263Z",
"answer_score": 285
} |
Please answer the following Stack Overflow question:
Title: Remove duplicate entries in a Bash script
<p>I want to remove duplicate entries from a text file, e.g:</p>
<pre><code>kavitha= Tue Feb 20 14:00 19 IST 2012 (duplicate entry)
sree=Tue Jan 20 14:05 19 IST 2012
divya = Tue Jan 20 14:20 19 IST 2012
anusha=Tue Jan 20 14:45 19 IST 2012
kavitha= Tue Feb 20 14:00 19 IST 2012 (duplicate entry)
</code></pre>
<p>Is there any possible way to remove the duplicate entries using a Bash script?</p>
<p><strong>Desired output</strong></p>
<pre><code>kavitha= Tue Feb 20 14:00 19 IST 2012
sree=Tue Jan 20 14:05 19 IST 2012
divya = Tue Jan 20 14:20 19 IST 2012
anusha=Tue Jan 20 14:45 19 IST 2012
</code></pre> | <p>You can <code>sort</code> then <code>uniq</code>:</p>
<pre><code>$ sort -u input.txt
</code></pre>
<p>Or use <code>awk</code>:</p>
<pre><code>$ awk '!a[$0]++' input.txt
</code></pre> | {
"question_id": 9377040,
"question_date": "2012-02-21T11:46:43.560Z",
"question_score": 210,
"tags": "bash|shell",
"answer_id": 9377125,
"answer_date": "2012-02-21T11:52:57.850Z",
"answer_score": 472
} |
Please answer the following Stack Overflow question:
Title: ng-repeat finish event
<p>I want to call some jQuery function targeting div with table. That table is populated with <code>ng-repeat</code>. </p>
<p>When I call it on </p>
<pre><code>$(document).ready()
</code></pre>
<p>I have no result. </p>
<p>Also </p>
<pre><code>$scope.$on('$viewContentLoaded', myFunc);
</code></pre>
<p>doesn't help.</p>
<p>Is there any way to execute function right after ng-repeat population completes? I've read an advice about using custom <code>directive</code>, but I have no clue how to use it with ng-repeat and my div...</p> | <p>Indeed, you should use directives, and there is no event tied to the end of a ng-Repeat loop (as each element is constructed individually, and has it's own event). But a) using directives might be all you need and b) there are a few ng-Repeat specific properties you can use to make your "on ngRepeat finished" event.</p>
<p>Specifically, if all you want is to style/add events to the whole of the table, you can do so using in a directive that encompasses all the ngRepeat elements. On the other hand, if you want to address each element specifically, you can use a directive within the ngRepeat, and it will act on each element, after it is created.</p>
<p>Then, there are the <code>$index</code>, <code>$first</code>, <code>$middle</code> and <code>$last</code> properties you can use to trigger events. So for this HTML:</p>
<pre><code><div ng-controller="Ctrl" my-main-directive>
<div ng-repeat="thing in things" my-repeat-directive>
thing {{thing}}
</div>
</div>
</code></pre>
<p>You can use directives like so:</p>
<pre><code>angular.module('myApp', [])
.directive('myRepeatDirective', function() {
return function(scope, element, attrs) {
angular.element(element).css('color','blue');
if (scope.$last){
window.alert("im the last!");
}
};
})
.directive('myMainDirective', function() {
return function(scope, element, attrs) {
angular.element(element).css('border','5px solid red');
};
});
</code></pre>
<p>See it in action in this <a href="http://plnkr.co/edit/or5mys?p=preview">Plunker</a>. Hope it helps!</p> | {
"question_id": 13471129,
"question_date": "2012-11-20T10:23:01.553Z",
"question_score": 210,
"tags": "javascript|jquery|angularjs|angularjs-ng-repeat|document-ready",
"answer_id": 13472605,
"answer_date": "2012-11-20T11:51:09.967Z",
"answer_score": 244
} |
Please answer the following Stack Overflow question:
Title: Why is it said that "HTTP is a stateless protocol"?
<p>HTTP has HTTP Cookies. Cookies allow the server to track the user state, the number of connections, last connection, etc.</p>
<p>HTTP has persistent connections (Keep-Alive) where several requests can be sent from the same TCP Connection.</p> | <p>Even though multiple requests can be sent over the same HTTP connection, the server does not attach any special meaning to their arriving over the same socket. That is solely a performance thing, intended to minimize the time/bandwidth that'd otherwise be spent reestablishing a connection for each request.</p>
<p>As far as HTTP is concerned, they are all still separate requests and must contain enough information on their own to fulfill the request. That is the essence of "statelessness". Requests will not be associated with each other absent some shared info the server knows about, which in most cases is a session ID in a cookie.</p> | {
"question_id": 13200152,
"question_date": "2012-11-02T17:21:13.690Z",
"question_score": 210,
"tags": "http|stateless",
"answer_id": 13200206,
"answer_date": "2012-11-02T17:24:44.130Z",
"answer_score": 153
} |
Please answer the following Stack Overflow question:
Title: How to format a duration in java? (e.g format H:MM:SS)
<p>I'd like to format a duration in seconds using a pattern like H:MM:SS. The current utilities in java are designed to format a time but not a duration.</p> | <p>If you're using a version of Java prior to 8... you can use <a href="http://joda-time.sourceforge.net/" rel="noreferrer">Joda Time</a> and <a href="http://joda-time.sourceforge.net/api-release/org/joda/time/format/PeriodFormatter.html" rel="noreferrer"><code>PeriodFormatter</code></a>. If you've really got a duration (i.e. an elapsed amount of time, with no reference to a calendar system) then you should probably be using <code>Duration</code> for the most part - you can then call <code>toPeriod</code> (specifying whatever <code>PeriodType</code> you want to reflect whether 25 hours becomes 1 day and 1 hour or not, etc) to get a <code>Period</code> which you can format.</p>
<p>If you're using Java 8 or later: I'd normally suggest using <code>java.time.Duration</code> to represent the duration. You can then call <code>getSeconds()</code> or the like to obtain an integer for standard string formatting as per bobince's answer if you need to - although you should be careful of the situation where the duration is negative, as you probably want a <em>single</em> negative sign in the output string. So something like:</p>
<pre><code>public static String formatDuration(Duration duration) {
long seconds = duration.getSeconds();
long absSeconds = Math.abs(seconds);
String positive = String.format(
"%d:%02d:%02d",
absSeconds / 3600,
(absSeconds % 3600) / 60,
absSeconds % 60);
return seconds < 0 ? "-" + positive : positive;
}
</code></pre>
<p>Formatting this way is <em>reasonably</em> simple, if annoyingly manual. For <em>parsing</em> it becomes a harder matter in general... You could still use Joda Time even with Java 8 if you want to, of course.</p> | {
"question_id": 266825,
"question_date": "2008-11-05T21:43:54.163Z",
"question_score": 210,
"tags": "java|date-formatting|duration",
"answer_id": 266846,
"answer_date": "2008-11-05T21:49:32.030Z",
"answer_score": 93
} |
Please answer the following Stack Overflow question:
Title: Java 8 Stream and operation on arrays
<p>I have just discovered the new Java 8 stream capabilities. Coming from Python, I was wondering if there was now a neat way to do operations on arrays like summing, multiplying two arrays in a "one line pythonic" way ? </p>
<p>Thanks</p> | <p>There are new methods added to <code>java.util.Arrays</code> to convert an array into a Java 8 stream which can then be used for summing etc.</p>
<pre><code>int sum = Arrays.stream(myIntArray).sum();
</code></pre>
<p>Multiplying two arrays is a little more difficult because I can't think of a way to get the value AND the index at the same time as a Stream operation. This means you probably have to stream over the indexes of the array.</p>
<pre><code>//in this example a[] and b[] are same length
int[] a = ...
int[] b = ...
int[] result = new int[a.length];
IntStream.range(0, a.length).forEach(i -> result[i] = a[i] * b[i]);
</code></pre>
<hr />
<p>Commenter <a href="https://stackoverflow.com/users/2711488/holger">@Holger</a> points out you can use the <code>map</code> method instead of <code>forEach</code> like this:</p>
<pre><code>int[] result = IntStream.range(0, a.length).map(i -> a[i] * b[i]).toArray();
</code></pre> | {
"question_id": 24390463,
"question_date": "2014-06-24T15:21:12.933Z",
"question_score": 210,
"tags": "java|arrays|java-8|java-stream",
"answer_id": 24391227,
"answer_date": "2014-06-24T15:57:20.007Z",
"answer_score": 310
} |
Please answer the following Stack Overflow question:
Title: How to access component methods from “outside” in ReactJS?
<p>Why can’t I access the component methods from “outside” in ReactJS? Why is it not possible and is there any way to solve it?</p>
<p>Consider the code:</p>
<pre><code>var Parent = React.createClass({
render: function() {
var child = <Child />;
return (
<div>
{child.someMethod()} // expect "bar", got a "not a function" error.
</div>
);
}
});
var Child = React.createClass({
render: function() {
return (
<div>
foo
</div>
);
},
someMethod: function() {
return 'bar';
}
});
React.renderComponent(<Parent />, document.body);
</code></pre> | <p>React provides an interface for what you are trying to do via the <a href="https://facebook.github.io/react/docs/refs-and-the-dom.html" rel="noreferrer"><code>ref</code> attribute</a>. Assign a component a <code>ref</code>, and its <code>current</code> attribute will be your custom component:</p>
<pre class="lang-js prettyprint-override"><code>class Parent extends React.Class {
constructor(props) {
this._child = React.createRef();
}
componentDidMount() {
console.log(this._child.current.someMethod()); // Prints 'bar'
}
render() {
return (
<div>
<Child ref={this._child} />
</div>
);
}
}
</code></pre>
<p><strong>Note</strong>: This will only work if the child component is declared as a class, as per documentation found here: <a href="https://facebook.github.io/react/docs/refs-and-the-dom.html#adding-a-ref-to-a-class-component" rel="noreferrer">https://facebook.github.io/react/docs/refs-and-the-dom.html#adding-a-ref-to-a-class-component</a></p>
<p><strong>Update 2019-04-01:</strong> <em>Changed example to use a class and <a href="https://reactjs.org/docs/refs-and-the-dom.html#creating-refs" rel="noreferrer"><code>createRef</code></a> per latest React docs.</em></p>
<p><strong>Update 2016-09-19:</strong> <em>Changed example to use ref callback per guidance from <a href="https://facebook.github.io/react/docs/more-about-refs.html#the-ref-string-attribute" rel="noreferrer">the <code>ref</code> String attribute</a> docs.</em></p> | {
"question_id": 24841855,
"question_date": "2014-07-19T15:18:38.577Z",
"question_score": 210,
"tags": "javascript|reactjs|dom",
"answer_id": 24848228,
"answer_date": "2014-07-20T07:10:25.597Z",
"answer_score": 222
} |
Please answer the following Stack Overflow question:
Title: Django CSRF check failing with an Ajax POST request
<p>I could use some help complying with Django's CSRF protection mechanism via my AJAX post. I've followed the directions here:</p>
<p><a href="http://docs.djangoproject.com/en/dev/ref/contrib/csrf/" rel="noreferrer">http://docs.djangoproject.com/en/dev/ref/contrib/csrf/</a></p>
<p>I've copied the AJAX sample code they have on that page exactly:</p>
<p><a href="http://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax" rel="noreferrer">http://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax</a></p>
<p>I put an alert printing the contents of <code>getCookie('csrftoken')</code> before the <code>xhr.setRequestHeader</code> call and it is indeed populated with some data. I'm not sure how to verify that the token is correct, but I'm encouraged that it's finding and sending something.</p>
<p>But Django is still rejecting my AJAX post.</p>
<p>Here's my JavaScript:</p>
<pre><code>$.post("/memorize/", data, function (result) {
if (result != "failure") {
get_random_card();
}
else {
alert("Failed to save card data.");
}
});
</code></pre>
<p>Here's the error I'm seeing from Django:</p>
<blockquote>
<p>[23/Feb/2011 22:08:29] "POST /memorize/ HTTP/1.1" 403 2332</p>
</blockquote>
<p>I'm sure I'm missing something, and maybe it's simple, but I don't know what it is. I've searched around SO and saw some information about turning off the CSRF check for my view via the <code>csrf_exempt</code> decorator, but I find that unappealing. I've tried that out and it works, but I'd rather get my POST to work the way Django was designed to expect it, if possible.</p>
<p>Just in case it's helpful, here's the gist of what my view is doing:</p>
<pre><code>def myview(request):
profile = request.user.profile
if request.method == 'POST':
"""
Process the post...
"""
return HttpResponseRedirect('/memorize/')
else: # request.method == 'GET'
ajax = request.GET.has_key('ajax')
"""
Some irrelevent code...
"""
if ajax:
response = HttpResponse()
profile.get_stack_json(response)
return response
else:
"""
Get data to send along with the content of the page.
"""
return render_to_response('memorize/memorize.html',
""" My data """
context_instance=RequestContext(request))
</code></pre>
<p>Thanks for your replies!</p> | <p><strong>Real solution</strong></p>
<p>Ok, I managed to trace the problem down. It lies in the Javascript (as I suggested below) code.</p>
<p>What you need is this:</p>
<pre><code>$.ajaxSetup({
beforeSend: function(xhr, settings) {
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
// Only send the token to relative URLs i.e. locally.
xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
}
}
});
</code></pre>
<p>instead of the code posted in the official docs:
<a href="https://docs.djangoproject.com/en/2.2/ref/csrf/" rel="noreferrer">https://docs.djangoproject.com/en/2.2/ref/csrf/</a></p>
<p>The working code, comes from this Django entry: <a href="http://www.djangoproject.com/weblog/2011/feb/08/security/" rel="noreferrer">http://www.djangoproject.com/weblog/2011/feb/08/security/</a></p>
<p>So the general solution is: "use ajaxSetup handler instead of ajaxSend handler". I don't know why it works. But it works for me :)</p>
<p><strong>Previous post (without answer)</strong></p>
<p>I'm experiencing the same problem actually.</p>
<p>It occurs after updating to Django 1.2.5 - there were no errors with AJAX POST requests in Django 1.2.4 (AJAX wasn't protected in any way, but it worked just fine).</p>
<p>Just like OP, I have tried the JavaScript snippet posted in Django documentation. I'm using jQuery 1.5. I'm also using the "django.middleware.csrf.CsrfViewMiddleware" middleware.</p>
<p>I tried to follow the the middleware code and I know that it fails on this:</p>
<pre><code>request_csrf_token = request.META.get('HTTP_X_CSRFTOKEN', '')
</code></pre>
<p>and then</p>
<pre><code>if request_csrf_token != csrf_token:
return self._reject(request, REASON_BAD_TOKEN)
</code></pre>
<p>this "if" is true, because "request_csrf_token" is empty.</p>
<p>Basically it means that the header is NOT set. So is there anything wrong with this JS line:</p>
<pre><code>xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
</code></pre>
<p>?</p>
<p>I hope that provided details will help us in resolving the issue :)</p> | {
"question_id": 5100539,
"question_date": "2011-02-24T04:58:11.940Z",
"question_score": 210,
"tags": "python|ajax|django|csrf",
"answer_id": 5107878,
"answer_date": "2011-02-24T16:59:02.097Z",
"answer_score": 192
} |
Please answer the following Stack Overflow question:
Title: Best way in asp.net to force https for an entire site?
<p>About 6 months ago I rolled out a site where every request needed to be over https. The only way at the time I could find to ensure that every request to a page was over https was to check it in the page load event. If the request was not over http I would response.redirect("<a href="https://example.com" rel="noreferrer">https://example.com</a>")</p>
<p>Is there a better way -- ideally some setting in the web.config?</p> | <p>Please use <a href="https://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security" rel="noreferrer">HSTS</a> (HTTP Strict Transport Security)</p>
<p>from <a href="http://www.hanselman.com/blog/HowToEnableHTTPStrictTransportSecurityHSTSInIIS7.aspx" rel="noreferrer">http://www.hanselman.com/blog/HowToEnableHTTPStrictTransportSecurityHSTSInIIS7.aspx</a></p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="HTTP to HTTPS redirect" stopProcessing="true">
<match url="(.*)" />
<conditions>
<add input="{HTTPS}" pattern="off" ignoreCase="true" />
</conditions>
<action type="Redirect" url="https://{HTTP_HOST}/{R:1}"
redirectType="Permanent" />
</rule>
</rules>
<outboundRules>
<rule name="Add Strict-Transport-Security when HTTPS" enabled="true">
<match serverVariable="RESPONSE_Strict_Transport_Security"
pattern=".*" />
<conditions>
<add input="{HTTPS}" pattern="on" ignoreCase="true" />
</conditions>
<action type="Rewrite" value="max-age=31536000" />
</rule>
</outboundRules>
</rewrite>
</system.webServer>
</configuration>
</code></pre>
<p><strong>Original Answer</strong> (replaced with the above on 4 December 2015)</p>
<p>basically</p>
<pre><code>protected void Application_BeginRequest(Object sender, EventArgs e)
{
if (HttpContext.Current.Request.IsSecureConnection.Equals(false) && HttpContext.Current.Request.IsLocal.Equals(false))
{
Response.Redirect("https://" + Request.ServerVariables["HTTP_HOST"]
+ HttpContext.Current.Request.RawUrl);
}
}
</code></pre>
<p>that would go in the global.asax.cs (or global.asax.vb)</p>
<p>i dont know of a way to specify it in the web.config</p> | {
"question_id": 47089,
"question_date": "2008-09-05T23:34:53.583Z",
"question_score": 210,
"tags": "c#|asp.net|vb.net|webforms|https",
"answer_id": 47095,
"answer_date": "2008-09-05T23:42:16.480Z",
"answer_score": 273
} |
Please answer the following Stack Overflow question:
Title: Why can't a text column have a default value in MySQL?
<p>If you try to create a TEXT column on a table, and give it a default value in MySQL, you get an error (on Windows at least). I cannot see any reason why a text column should not have a default value. No explanation is given by the MySQL documentation. It seems illogical to me (and somewhat frustrating, as I want a default value!). Anybody know why this is not allowed?</p> | <p>Windows MySQL v5 throws an error but Linux and other versions only raise a warning. This needs to be fixed. <a href="http://dev.mysql.com/doc/refman/5.0/en/blob.html#idm140312903326336" rel="noreferrer">WTF?</a></p>
<p>Also see an attempt to fix this as bug #19498 in the MySQL Bugtracker:</p>
<blockquote>
<p>Bryce Nesbitt on April 4 2008 4:36pm:<br>
On MS Windows the "no DEFAULT" rule is an error, while on other platforms it is often a warning. While not a bug, it's possible to get trapped by this if you write code on a lenient platform, and later run it on a strict platform:</p>
</blockquote>
<p>Personally, I do view this as a bug. Searching for "BLOB/TEXT column can't have a default value" returns about 2,940 results on Google. Most of them are reports of incompatibilities when trying to install DB scripts that worked on one system but not others.</p>
<p>I am running into the same problem now on a webapp I'm modifying for one of my clients, originally deployed on Linux MySQL v5.0.83-log. I'm running Windows MySQL v5.1.41. Even trying to use the latest version of phpMyAdmin to extract the database, it doesn't report a default for the text column in question. Yet, when I try running an insert on Windows (that works fine on the Linux deployment) I receive an error of no default on ABC column. I try to recreate the table locally with the obvious default (based on a select of unique values for that column) and end up receiving the oh-so-useful <em>BLOB/TEXT column can't have a default value</em>.</p>
<p>Again, not maintaining basic compatability across platforms is unacceptable and is a bug.</p>
<hr>
<p><strong>How to disable strict mode in MySQL 5 (Windows):</strong></p>
<ul>
<li><p>Edit /my.ini and look for line</p>
<pre><code>sql-mode="STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"
</code></pre></li>
<li><p>Replace it with</p>
<pre><code>sql_mode='MYSQL40'
</code></pre></li>
<li><p>Restart the MySQL service (assuming that it is mysql5)</p>
<pre><code>net stop mysql5
net start mysql5
</code></pre></li>
</ul>
<p>If you have root/admin access you might be able to execute</p>
<pre><code>mysql_query("SET @@global.sql_mode='MYSQL40'");
</code></pre> | {
"question_id": 3466872,
"question_date": "2010-08-12T10:56:30.527Z",
"question_score": 210,
"tags": "mysql|default-value",
"answer_id": 4553664,
"answer_date": "2010-12-29T11:27:52.270Z",
"answer_score": 100
} |
Please answer the following Stack Overflow question:
Title: Convert a python 'type' object to a string
<p>I'm wondering how to convert a python 'type' object into a string using python's reflective capabilities.</p>
<p>For example, I'd like to print the type of an object</p>
<pre><code>print("My type is " + type(some_object)) # (which obviously doesn't work like this)
</code></pre> | <pre><code>print(type(some_object).__name__)
</code></pre>
<p>If that doesn't suit you, use this:</p>
<pre><code>print(some_instance.__class__.__name__)
</code></pre>
<p>Example:</p>
<pre><code>class A:
pass
print(type(A()))
# prints <type 'instance'>
print(A().__class__.__name__)
# prints A
</code></pre>
<p>Also, it seems there are differences with <code>type()</code> when using new-style classes vs old-style (that is, inheritance from <code>object</code>). For a new-style class, <code>type(someObject).__name__</code> returns the name, and for old-style classes it returns <code>instance</code>.</p> | {
"question_id": 5008828,
"question_date": "2011-02-15T19:58:04.593Z",
"question_score": 210,
"tags": "python|reflection",
"answer_id": 5008854,
"answer_date": "2011-02-15T20:01:11.693Z",
"answer_score": 318
} |
Please answer the following Stack Overflow question:
Title: Maven compile with multiple src directories
<p>Is there a way to compile multiple java source directories in a single maven project? </p> | <p>You can add a new source directory with build-helper:</p>
<pre class="lang-xml prettyprint-override"><code><build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>3.2.0</version>
<executions>
<execution>
<phase>generate-sources</phase>
<goals>
<goal>add-source</goal>
</goals>
<configuration>
<sources>
<source>src/main/generated</source>
</sources>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</code></pre> | {
"question_id": 270445,
"question_date": "2008-11-06T21:50:12.637Z",
"question_score": 210,
"tags": "java|maven-2",
"answer_id": 270490,
"answer_date": "2008-11-06T22:01:36.780Z",
"answer_score": 294
} |
Please answer the following Stack Overflow question:
Title: Meaning of delta or epsilon argument of assertEquals for double values
<p>I have a question about JUnit <code>assertEquals</code> to test <code>double</code> values. Reading the <a href="https://junit.org/junit4/javadoc/latest/org/junit/Assert.html#assertEquals(double,%20double)" rel="noreferrer">API doc</a> I can see:</p>
<blockquote>
<pre><code>@Deprecated
public static void assertEquals(double expected, double actual)
</code></pre>
<p><strong>Deprecated.</strong> Use <code>assertEquals(double expected, double actual, double delta)</code> instead.</p>
</blockquote>
<p><em>(Note: in older documentation versions, the delta parameter is called epsilon)</em></p>
<p>What does the <code>delta</code> (or <code>epsilon</code>) parameter mean?</p> | <p>Epsilon is the value that the 2 numbers can be off by. So it will assert to true as long as <code>Math.abs(expected - actual) <= epsilon</code></p> | {
"question_id": 5686755,
"question_date": "2011-04-16T13:18:22.590Z",
"question_score": 210,
"tags": "java|junit|floating-point",
"answer_id": 5686764,
"answer_date": "2011-04-16T13:20:08.227Z",
"answer_score": 223
} |
Please answer the following Stack Overflow question:
Title: How to change color of the back arrow in the new material theme?
<p>I've updated my SDK to API 21 and now the back/up icon is a black arrow pointing to the left.</p>
<p><img src="https://i.stack.imgur.com/FUEND.jpg" alt="Black back arrow" /></p>
<p>I would like it to be grey. How can I do that?</p>
<p>In the Play Store, for example, the arrow is white.</p>
<p>I've done this to set some styles. I have used <code>@drawable/abc_ic_ab_back_mtrl_am_alpha</code> for <code>homeAsUpIndicator</code>. That drawable is transparent (only alpha) but the arrow is displayed in black. I wonder if I can set the color like I do in the <code>DrawerArrowStyle</code>. Or if the only solution is to create my <code>@drawable/grey_arrow</code> and use it for <code>homeAsUpIndicator</code>.</p>
<pre class="lang-xml prettyprint-override"><code><!-- Base application theme -->
<style name="AppTheme" parent="Theme.AppCompat.Light">
<item name="android:actionBarStyle" tools:ignore="NewApi">@style/MyActionBar</item>
<item name="actionBarStyle">@style/MyActionBar</item>
<item name="drawerArrowStyle">@style/DrawerArrowStyle</item>
<item name="homeAsUpIndicator">@drawable/abc_ic_ab_back_mtrl_am_alpha</item>
<item name="android:homeAsUpIndicator" tools:ignore="NewApi">@drawable/abc_ic_ab_back_mtrl_am_alpha</item>
</style>
<!-- ActionBar style -->
<style name="MyActionBar" parent="@style/Widget.AppCompat.Light.ActionBar.Solid">
<item name="android:background">@color/actionbar_background</item>
<!-- Support library compatibility -->
<item name="background">@color/actionbar_background</item>
</style>
<!-- Style for the navigation drawer icon -->
<style name="DrawerArrowStyle" parent="Widget.AppCompat.DrawerArrowToggle">
<item name="spinBars">true</item>
<item name="color">@color/actionbar_text</item>
</style>
</code></pre>
<p>My solution so far has been to take the <code>@drawable/abc_ic_ab_back_mtrl_am_alpha</code>, which seems to be white, and paint it in the color I desire using a photo editor. It works, although I would prefer to use <code>@color/actionbar_text</code> like in <code>DrawerArrowStyle</code>.</p> | <p>You can achieve it through code. Obtain the back arrow drawable, modify its color with a filter, and set it as back button.</p>
<pre><code>final Drawable upArrow = getResources().getDrawable(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
upArrow.setColorFilter(getResources().getColor(R.color.grey), PorterDuff.Mode.SRC_ATOP);
getSupportActionBar().setHomeAsUpIndicator(upArrow);
</code></pre>
<p><strong>Revision 1:</strong></p>
<p>Starting from API 23 (Marshmallow) the drawable resource <code>abc_ic_ab_back_mtrl_am_alpha</code> is changed to <code>abc_ic_ab_back_material</code>.</p>
<p>EDIT:</p>
<p>You can use this code to achieve the results you want:</p>
<pre><code>toolbar.getNavigationIcon().setColorFilter(getResources().getColor(R.color.blue_gray_15), PorterDuff.Mode.SRC_ATOP);
</code></pre> | {
"question_id": 26788464,
"question_date": "2014-11-06T20:06:12.907Z",
"question_score": 210,
"tags": "java|android|user-interface|colors|android-styles",
"answer_id": 26837072,
"answer_date": "2014-11-10T05:02:30.870Z",
"answer_score": 373
} |
Please answer the following Stack Overflow question:
Title: Convert a char to upper case using regular expressions (EditPad Pro)
<p>I wrote a regular expression in hope that I will be able to replace every match (that is just one char) to upper case char. I am using EditPad Pro (however I am willing to use any other tool that would allow me to do this, as long as it is free to try, since I only need to do this once).</p>
<p><strong>Background:</strong> I have a very long text file used by a case sensitive application, and some words start with lower case instead of upper case char, thus crashing the application. This would take very long to do by hand, and it would be quite complicated to do without regular expressions because the occurrence of the (evil) lower case char is very specific.</p>
<p>I have written the select regular expression and now I can use it with a backreference ($1 works just fine) however I can't make it replace with upper case char. I thought something like \u$1 would work, however it doesn't in EditPad Pro.</p>
<p>If no free tool allows me to do this, I guess the alternative would be to just do it in C# however I am in a bit of a hurry and not near a compiler, so I'd have to download the express edition first, so ... It would be preferable to find a tool that supports such a feature!</p>
<p>Thank you!</p> | <p>TextPad will allow you to perform this operation.</p>
<p>example:</p>
<pre><code>test this sentence
</code></pre>
<p>Find what: <code>\([^ ]*\) \(.*\)</code>
Replace with: <code>\U\1\E \2</code></p>
<p>the <code>\U</code> will cause all following chars to be upper</p>
<p>the <code>\E</code> will turn off the <code>\U</code></p>
<p>the result will be:</p>
<pre><code>TEST this sentence
</code></pre> | {
"question_id": 1159343,
"question_date": "2009-07-21T13:53:15.447Z",
"question_score": 210,
"tags": "regex",
"answer_id": 1159389,
"answer_date": "2009-07-21T14:01:36.887Z",
"answer_score": 358
} |
Please answer the following Stack Overflow question:
Title: How can I pull from remote Git repository and override the changes in my local repository?
<p>I need to throw away all the changes in my local repository and pull all the code from the remote repository. What is the Git command to do this?</p> | <p>Provided that the remote repository is origin, and that you're interested in master:</p>
<pre><code>git fetch origin
git reset --hard origin/master
</code></pre>
<p>This tells it to fetch the commits from the remote repository, and position your working copy to the tip of its master branch. </p>
<p>All your local commits not common to the remote will be gone.</p> | {
"question_id": 6284809,
"question_date": "2011-06-08T20:24:56.833Z",
"question_score": 210,
"tags": "git",
"answer_id": 6284819,
"answer_date": "2011-06-08T20:26:10.297Z",
"answer_score": 432
} |
Please answer the following Stack Overflow question:
Title: When should we use Observer and Observable?
<p>An interviewer asked me:</p>
<p><em>What is <code>Observer</code> and <code>Observable</code> and when should we use them?</em></p>
<p>I wasn't aware of these terms, so when I got back home and started Googling about <code>Observer</code> and <code>Observable</code>, I found some points from different resources:</p>
<blockquote>
<p>1) <a href="https://docs.oracle.com/javase/8/docs/api/java/util/Observable.html" rel="noreferrer"><code>Observable</code></a> is a class and <a href="https://docs.oracle.com/javase/8/docs/api/java/util/Observer.html" rel="noreferrer"><code>Observer</code></a> is an interface.</p>
<p>2) The <code>Observable</code> class maintains a list of <code>Observer</code>s.</p>
<p>3) When an <code>Observable</code> object is updated, it invokes the <code>update()</code> method of each of its <code>Observer</code>s to notify that, it is changed.</p>
</blockquote>
<p>I found this example:</p>
<pre><code>import java.util.Observable;
import java.util.Observer;
class MessageBoard extends Observable
{
public void changeMessage(String message)
{
setChanged();
notifyObservers(message);
}
}
class Student implements Observer
{
@Override
public void update(Observable o, Object arg)
{
System.out.println("Message board changed: " + arg);
}
}
public class MessageBoardTest
{
public static void main(String[] args)
{
MessageBoard board = new MessageBoard();
Student bob = new Student();
Student joe = new Student();
board.addObserver(bob);
board.addObserver(joe);
board.changeMessage("More Homework!");
}
}
</code></pre>
<p>But I don't understand why we need <code>Observer</code> and <code>Observable</code>? What are the <code>setChanged()</code> and <code>notifyObservers(message)</code> methods for?</p> | <p>You have a concrete example of a Student and a MessageBoard. The Student registers by adding itself to the list of Observers that want to be notified when a new Message is posted to the MessageBoard. When a Message is added to the MessageBoard, it iterates over its list of Observers and notifies them that the event occurred.</p>
<p>Think Twitter. When you say you want to follow someone, Twitter adds you to their follower list. When they sent a new tweet in, you see it in your input. In that case, your Twitter account is the Observer and the person you're following is the Observable.</p>
<p>The analogy might not be perfect, because Twitter is more likely to be a Mediator. But it illustrates the point.</p> | {
"question_id": 13744450,
"question_date": "2012-12-06T13:17:55.333Z",
"question_score": 210,
"tags": "java|design-patterns|observable|observer-pattern|observers",
"answer_id": 13744537,
"answer_date": "2012-12-06T13:22:24.717Z",
"answer_score": 275
} |
Please answer the following Stack Overflow question:
Title: Can someone give an example of cosine similarity, in a very simple, graphical way?
<p><a href="http://en.wikipedia.org/wiki/Cosine_similarity" rel="nofollow noreferrer">Cosine Similarity article on Wikipedia</a></p>
<p>Can you show the vectors here (in a list or something)
and then do the math, and let us see how it works?</p> | <p>Here are two very short texts to compare:</p>
<ol>
<li><p><code>Julie loves me more than Linda loves me</code></p></li>
<li><p><code>Jane likes me more than Julie loves me</code></p></li>
</ol>
<p>We want to know how similar these texts are, purely in terms of word counts (and ignoring word order). We begin by making a list of the words from both texts:</p>
<pre><code>me Julie loves Linda than more likes Jane
</code></pre>
<p>Now we count the number of times each of these words appears in each text:</p>
<pre><code> me 2 2
Jane 0 1
Julie 1 1
Linda 1 0
likes 0 1
loves 2 1
more 1 1
than 1 1
</code></pre>
<p>We are not interested in the words themselves though. We are interested only in
those two vertical vectors of counts. For instance, there are two instances of
'me' in each text. We are going to decide how close these two texts are to each
other by calculating one function of those two vectors, namely the cosine of
the angle between them. </p>
<p>The two vectors are, again:</p>
<pre><code>a: [2, 0, 1, 1, 0, 2, 1, 1]
b: [2, 1, 1, 0, 1, 1, 1, 1]
</code></pre>
<p>The cosine of the angle between them is about 0.822.</p>
<p>These vectors are 8-dimensional. A virtue of using cosine similarity is clearly
that it converts a question that is beyond human ability to visualise to one
that can be. In this case you can think of this as the angle of about 35
degrees which is some 'distance' from zero or perfect agreement.</p> | {
"question_id": 1746501,
"question_date": "2009-11-17T04:03:34.570Z",
"question_score": 210,
"tags": "text|data-mining|cosine-similarity",
"answer_id": 1750187,
"answer_date": "2009-11-17T16:47:06.737Z",
"answer_score": 483
} |
Please answer the following Stack Overflow question:
Title: What is let-* in Angular 2 templates?
<p>I came across a strange assignment syntax inside an Angular 2 template.</p>
<pre class="lang-ts prettyprint-override"><code><template let-col let-car="rowData" pTemplate="body">
<span [style.color]="car[col.field]">{{car[col.field]}}</span>
</template>
</code></pre>
<p>It appears that <code>let-col</code> and <code>let-car="rowData"</code> create two new variables <code>col</code> and <code>car</code> that can then be bound to inside the template.</p>
<p>Source: <a href="https://www.primefaces.org/primeng/#/datatable/templating" rel="noreferrer">https://www.primefaces.org/primeng/#/datatable/templating</a></p>
<p>What is this magical <code>let-*</code> syntax called? </p>
<p>How does it work? </p>
<p>What is the difference between <code>let-something</code> and <code>let-something="something else"</code>?</p> | <p><strong>update Angular 5</strong></p>
<p><code>ngOutletContext</code> was renamed to <code>ngTemplateOutletContext</code></p>
<p>See also <a href="https://github.com/angular/angular/blob/master/CHANGELOG.md#500-pentagonal-donut-2017-11-01" rel="noreferrer">CHANGELOG.md @ angular/angular</a></p>
<p><strong>original</strong></p>
<p>Templates (<code><template></code>, or <code><ng-template></code> since 4.x) are added as embedded views and get passed a context.</p>
<p>With <code>let-col</code> the context property <code>$implicit</code> is made available as <code>col</code> within the template for bindings.
With <code>let-foo="bar"</code> the context property <code>bar</code> is made available as <code>foo</code>.</p>
<p>For example if you add a template</p>
<pre class="lang-ts prettyprint-override"><code><ng-template #myTemplate let-col let-foo="bar">
<div>{{col}}</div>
<div>{{foo}}</div>
</ng-template>
<!-- render above template with a custom context -->
<ng-template [ngTemplateOutlet]="myTemplate"
[ngTemplateOutletContext]="{
$implicit: 'some col value',
bar: 'some bar value'
}"
></ng-template>
</code></pre>
<p>See also <a href="https://stackoverflow.com/questions/39929931/angular-2-ngtemplateoutlet-with-string-variable/41241329#41241329">this answer</a> and <a href="https://angular.io/api/core/ViewContainerRef#createEmbeddedView" rel="noreferrer">ViewContainerRef#createEmbeddedView</a>.</p>
<p><code>*ngFor</code> also works this way. The canonical syntax makes this more obvious</p>
<pre class="lang-ts prettyprint-override"><code><ng-template ngFor let-item [ngForOf]="items" let-i="index" let-odd="odd">
<div>{{item}}</div>
</ng-template>
</code></pre>
<p>where <code>NgFor</code> adds the template as an embedded view to the DOM for each <code>item</code> of <code>items</code> and adds a few values (<code>item</code>, <code>index</code>, <code>odd</code>) to the context.</p>
<p>See also <a href="https://stackoverflow.com/questions/48523288/using-implict-to-pass-multiple-parameters/48524305#48524305">Using $implict to pass multiple parameters</a></p> | {
"question_id": 42978082,
"question_date": "2017-03-23T13:53:22.020Z",
"question_score": 210,
"tags": "angular|angular2-template|primeng",
"answer_id": 42978464,
"answer_date": "2017-03-23T14:07:27.147Z",
"answer_score": 216
} |
Please answer the following Stack Overflow question:
Title: Has an event handler already been added?
<p>Is there a way to tell if an event handler has been added to an object? I'm serializing a list of objects into/out of session state so we can use SQL based session state... When an object in the list has a property changed it needs to be flagged, which the event handler took care of properly before. However now when the objects are deserialized it isn't getting the event handler.</p>
<p>In an fit of mild annoyance, I just added the event handler to the Get property that accesses the object. It's getting called now which is great, except that it's getting called like 5 times so I think the handler just keeps getting added every time the object is accessed.</p>
<p>It's really safe enough to just ignore, but I'd rather make it that much cleaner by checking to see if the handler has already been added so I only do so once.</p>
<p>Is that possible?</p>
<p>EDIT: I don't necessarily have full control of what event handlers are added, so just checking for null isn't good enough. </p> | <p>From outside the defining class, as @Telos mentions, you can only use EventHandler on the left-hand side of a <code>+=</code> or a <code>-=</code>. So, if you have the ability to modify the defining class, you could provide a method to perform the check by checking if the event handler is <code>null</code> - if so, then no event handler has been added. If not, then maybe and you can loop through the values in
<a href="http://msdn.microsoft.com/en-us/library/system.delegate.getinvocationlist.aspx" rel="noreferrer">Delegate.GetInvocationList</a>. If one is equal to the delegate that you want to add as event handler, then you know it's there.</p>
<pre><code>public bool IsEventHandlerRegistered(Delegate prospectiveHandler)
{
if ( this.EventHandler != null )
{
foreach ( Delegate existingHandler in this.EventHandler.GetInvocationList() )
{
if ( existingHandler == prospectiveHandler )
{
return true;
}
}
}
return false;
}
</code></pre>
<p>And this could easily be modified to become "add the handler if it's not there". If you don't have access to the innards of the class that's exposing the event, you may need to explore <code>-=</code> and <code>+=</code>, as suggested by @Lou Franco. </p>
<p>However, you may be better off reexamining the way you're commissioning and decommissioning these objects, to see if you can't find a way to track this information yourself.</p> | {
"question_id": 136975,
"question_date": "2008-09-25T23:53:29.430Z",
"question_score": 210,
"tags": "c#|.net|asp.net",
"answer_id": 136998,
"answer_date": "2008-09-25T23:58:55.593Z",
"answer_score": 138
} |
Please answer the following Stack Overflow question:
Title: C++ Double Address Operator? (&&)
<p>I'm reading STL source code and I have no idea what <code>&&</code> address operator is supposed to do. Here is a code example from <code>stl_vector.h</code>:</p>
<pre><code>vector&
operator=(vector&& __x) // <-- Note double ampersands here
{
// NB: DR 675.
this->clear();
this->swap(__x);
return *this;
}
</code></pre>
<p>Does "Address of Address" make any sense? Why does it have two address operators instead of just one?</p> | <p>This is <a href="https://stackoverflow.com/tags/c%2b%2b11/info">C++11</a> code. In C++11, the <code>&&</code> token can be used to mean an "rvalue reference".</p> | {
"question_id": 4549151,
"question_date": "2010-12-28T20:14:10.910Z",
"question_score": 210,
"tags": "c++|stl|operator-keyword|memory-address",
"answer_id": 4549167,
"answer_date": "2010-12-28T20:16:20.353Z",
"answer_score": 132
} |
Please answer the following Stack Overflow question:
Title: Spring Boot application as a Service
<p>How to configure nicely Spring Boot application packaged as executable jar as a Service in the Linux system? Is this recommended approach, or should I convert this app to war and install it into Tomcat?</p>
<p>Currently, I can run Spring boot application from the <code>screen</code> session, which is nice but requires manual start after a server reboot.</p>
<p>What I'm looking for is general advice/direction or sample <code>init.d</code> the script, if my approach with executable <em>jar</em> is proper.</p> | <p>The following works for springboot 1.3 and above:</p>
<p><strong>As init.d service</strong></p>
<p>The executable jar has the usual start, stop, restart, and status commands. It will also set up a PID file in the usual /var/run directory and logging in the usual /var/log directory by default.</p>
<p>You just need to symlink your jar into /etc/init.d like so</p>
<pre><code>sudo link -s /var/myapp/myapp.jar /etc/init.d/myapp
</code></pre>
<p>OR</p>
<pre><code>sudo ln -s ~/myproject/build/libs/myapp-1.0.jar /etc/init.d/myapp_servicename
</code></pre>
<p>After that you can do the usual</p>
<pre><code>/etc/init.d/myapp start
</code></pre>
<p>Then setup a link in whichever runlevel you want the app to start/stop in on boot if so desired. </p>
<hr/>
<p><strong>As a systemd service</strong></p>
<p>To run a Spring Boot application installed in var/myapp you can add the following script in /etc/systemd/system/myapp.service:</p>
<pre><code>[Unit]
Description=myapp
After=syslog.target
[Service]
ExecStart=/var/myapp/myapp.jar
[Install]
WantedBy=multi-user.target
</code></pre>
<hr>
<p>NB: in case you are using this method, do not forget to make the jar file itself executable (with chmod +x) otherwise it will fail with error "Permission denied".</p>
<p><strong>Reference</strong> </p>
<p><a href="http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/html/deployment-install.html#deployment-service" rel="noreferrer">http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/html/deployment-install.html#deployment-service</a></p> | {
"question_id": 21503883,
"question_date": "2014-02-01T21:27:09.003Z",
"question_score": 210,
"tags": "linux|spring-boot|service|startup|init.d",
"answer_id": 30497095,
"answer_date": "2015-05-28T04:11:07.767Z",
"answer_score": 150
} |
Please answer the following Stack Overflow question:
Title: Ruby class instance variable vs. class variable
<p>I read <a href="http://archive.today/dCYNj" rel="noreferrer">https://stackoverflow.com/questions/826734/when-do-ruby-instance-variables-get-set</a> but I'm of two minds when to use class instance variables.</p>
<p>Class variables are shared by all objects of a class, Instance variables belong to one object. There's not much room left to use class instance variables if we have class variables.</p>
<p>Could someone explain the difference between these two and when to use them?</p>
<p>Here's a code example:</p>
<pre><code>class S
@@k = 23
@s = 15
def self.s
@s
end
def self.k
@@k
end
end
p S.s #15
p S.k #23
</code></pre>
<p><strong>Update:</strong> I understand now! Class Instance Variables are not passed along the inheritance chain.</p> | <p>Instance variable on a class:</p>
<pre><code>class Parent
@things = []
def self.things
@things
end
def things
self.class.things
end
end
class Child < Parent
@things = []
end
Parent.things << :car
Child.things << :doll
mom = Parent.new
dad = Parent.new
p Parent.things #=> [:car]
p Child.things #=> [:doll]
p mom.things #=> [:car]
p dad.things #=> [:car]
</code></pre>
<p>Class variable:</p>
<pre><code>class Parent
@@things = []
def self.things
@@things
end
def things
@@things
end
end
class Child < Parent
end
Parent.things << :car
Child.things << :doll
p Parent.things #=> [:car,:doll]
p Child.things #=> [:car,:doll]
mom = Parent.new
dad = Parent.new
son1 = Child.new
son2 = Child.new
daughter = Child.new
[ mom, dad, son1, son2, daughter ].each{ |person| p person.things }
#=> [:car, :doll]
#=> [:car, :doll]
#=> [:car, :doll]
#=> [:car, :doll]
#=> [:car, :doll]
</code></pre>
<p>With an instance variable on a class (not on an instance of that class) you can store something common to that class without having sub-classes automatically also get them (and vice-versa). With class variables, you have the convenience of not having to write <code>self.class</code> from an instance object, and (when desirable) you also get automatic sharing throughout the class hierarchy.</p>
<hr>
<p>Merging these together into a single example that also covers instance variables on instances:</p>
<pre><code>class Parent
@@family_things = [] # Shared between class and subclasses
@shared_things = [] # Specific to this class
def self.family_things
@@family_things
end
def self.shared_things
@shared_things
end
attr_accessor :my_things
def initialize
@my_things = [] # Just for me
end
def family_things
self.class.family_things
end
def shared_things
self.class.shared_things
end
end
class Child < Parent
@shared_things = []
end
</code></pre>
<p>And then in action:</p>
<pre><code>mama = Parent.new
papa = Parent.new
joey = Child.new
suzy = Child.new
Parent.family_things << :house
papa.family_things << :vacuum
mama.shared_things << :car
papa.shared_things << :blender
papa.my_things << :quadcopter
joey.my_things << :bike
suzy.my_things << :doll
joey.shared_things << :puzzle
suzy.shared_things << :blocks
p Parent.family_things #=> [:house, :vacuum]
p Child.family_things #=> [:house, :vacuum]
p papa.family_things #=> [:house, :vacuum]
p mama.family_things #=> [:house, :vacuum]
p joey.family_things #=> [:house, :vacuum]
p suzy.family_things #=> [:house, :vacuum]
p Parent.shared_things #=> [:car, :blender]
p papa.shared_things #=> [:car, :blender]
p mama.shared_things #=> [:car, :blender]
p Child.shared_things #=> [:puzzle, :blocks]
p joey.shared_things #=> [:puzzle, :blocks]
p suzy.shared_things #=> [:puzzle, :blocks]
p papa.my_things #=> [:quadcopter]
p mama.my_things #=> []
p joey.my_things #=> [:bike]
p suzy.my_things #=> [:doll]
</code></pre> | {
"question_id": 15773552,
"question_date": "2013-04-02T20:17:00.707Z",
"question_score": 210,
"tags": "ruby|instance-variables|class-variables|class-instance-variables",
"answer_id": 15773671,
"answer_date": "2013-04-02T20:24:29.753Z",
"answer_score": 318
} |
Please answer the following Stack Overflow question:
Title: Python memory usage of numpy arrays
<p>I'm using python to analyse some large files and I'm running into memory issues, so I've been using sys.getsizeof() to try and keep track of the usage, but it's behaviour with numpy arrays is bizarre. Here's an example involving a map of albedos that I'm having to open:</p>
<pre><code>>>> import numpy as np
>>> import struct
>>> from sys import getsizeof
>>> f = open('Albedo_map.assoc', 'rb')
>>> getsizeof(f)
144
>>> albedo = struct.unpack('%df' % (7200*3600), f.read(7200*3600*4))
>>> getsizeof(albedo)
207360056
>>> albedo = np.array(albedo).reshape(3600,7200)
>>> getsizeof(albedo)
80
</code></pre>
<p>Well the data's still there, but the size of the object, a 3600x7200 pixel map, has gone from ~200 Mb to 80 bytes. I'd like to hope that my memory issues are over and just convert everything to numpy arrays, but I feel that this behaviour, if true, would in some way violate some law of information theory or thermodynamics, or something, so I'm inclined to believe that getsizeof() doesn't work with numpy arrays. Any ideas?</p> | <p>You can use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.nbytes.html" rel="noreferrer"><code>array.nbytes</code></a> for numpy arrays, for example:</p>
<pre><code>>>> import numpy as np
>>> from sys import getsizeof
>>> a = [0] * 1024
>>> b = np.array(a)
>>> getsizeof(a)
8264
>>> b.nbytes
8192
</code></pre> | {
"question_id": 11784329,
"question_date": "2012-08-02T19:19:22.970Z",
"question_score": 210,
"tags": "python|numpy|sys",
"answer_id": 11784399,
"answer_date": "2012-08-02T19:24:14.747Z",
"answer_score": 314
} |
Please answer the following Stack Overflow question:
Title: diff current working copy of a file with another branch's committed copy
<p>I have a repo with file <code>foo</code> in the master branch. I switched to bar branch and made some changes to <code>foo</code>. How can I now run a <code>git diff</code> between this copy (which isn't committed yet) and the copy of the master branch?</p> | <p>The following works for me:</p>
<p><code>git diff master:foo foo</code></p>
<p>In the past, it may have been:</p>
<p><code>git diff foo master:foo</code></p> | {
"question_id": 9113280,
"question_date": "2012-02-02T13:36:30.333Z",
"question_score": 210,
"tags": "git",
"answer_id": 9113407,
"answer_date": "2012-02-02T13:46:17.390Z",
"answer_score": 203
} |
Please answer the following Stack Overflow question:
Title: What is the shortest way to simply sort an array of structs by (arbitrary) field names?
<p>I just had a problem where I had an array of structs, e.g.</p>
<pre><code>package main
import "log"
type Planet struct {
Name string `json:"name"`
Aphelion float64 `json:"aphelion"` // in million km
Perihelion float64 `json:"perihelion"` // in million km
Axis int64 `json:"Axis"` // in km
Radius float64 `json:"radius"`
}
func main() {
var mars = new(Planet)
mars.Name = "Mars"
mars.Aphelion = 249.2
mars.Perihelion = 206.7
mars.Axis = 227939100
mars.Radius = 3389.5
var earth = new(Planet)
earth.Name = "Earth"
earth.Aphelion = 151.930
earth.Perihelion = 147.095
earth.Axis = 149598261
earth.Radius = 6371.0
var venus = new(Planet)
venus.Name = "Venus"
venus.Aphelion = 108.939
venus.Perihelion = 107.477
venus.Axis = 108208000
venus.Radius = 6051.8
planets := [...]Planet{*mars, *venus, *earth}
log.Println(planets)
}
</code></pre>
<p>Lets say you want to sort it by <code>Axis</code>. How do you do that?</p>
<p>(Note: I have seen <a href="http://golang.org/pkg/sort/" rel="noreferrer">http://golang.org/pkg/sort/</a> and it seems to work, but I have to add about 20 lines just for simple sorting by a very simple key. I have a python background where it is as simple as <code>sorted(planets, key=lambda n: n.Axis)</code> - is there something similar simple in Go?)</p> | <p><strong>UPDATE:</strong> This answer relates to older versions of <code>go</code>. For Go 1.8 and newer, see the <a href="https://stackoverflow.com/a/42872183/293064">AndreKR's answer above</a>.</p>
<hr />
<p>If you want something a bit less verbose than the standard library <code>sort</code> package, you could use the third party <a href="http://godoc.org/github.com/bradfitz/slice" rel="noreferrer"><code>github.com/bradfitz/slice</code></a> package. It uses some tricks to generate the <code>Len</code> and <code>Swap</code> methods needed to sort your slice, so you only need to provide a <code>Less</code> method.</p>
<p>With this package, you can perform the sort with:</p>
<pre><code>slice.Sort(planets[:], func(i, j int) bool {
return planets[i].Axis < planets[j].Axis
})
</code></pre>
<p>The <code>planets[:]</code> part is necessary to produce a slice covering your array. If you make <code>planets</code> a slice instead of an array you could skip that part.</p> | {
"question_id": 28999735,
"question_date": "2015-03-12T00:07:48.283Z",
"question_score": 210,
"tags": "sorting|go",
"answer_id": 29000001,
"answer_date": "2015-03-12T00:37:40.893Z",
"answer_score": 94
} |
Please answer the following Stack Overflow question:
Title: Multiple font-weights, one @font-face query
<p>I have to import the Klavika font and I've received it in multiple shapes and sizes:</p>
<pre><code>Klavika-Bold-Italic.otf
Klavika-Bold.otf
Klavika-Light-Italic.otf
Klavika-Light.otf
Klavika-Medium-Italic.otf
Klavika-Medium.otf
Klavika-Regular-Italic.otf
Klavika-Regular.otf
</code></pre>
<p>Now I would like to know if it's possible to import those into CSS with just one <code>@font-face</code>-query, where I'm defining the <code>weight</code> in the query. I want to avoid copy/pasting the query 8 times.</p>
<p>So something like:</p>
<pre><code>@font-face {
font-family: 'Klavika';
src: url(../fonts/Klavika-Regular.otf), weight:normal;
src: url(../fonts/Klavika-Bold.otf), weight:bold;
}
</code></pre> | <p>Actually there is a special flavor of @font-face that will permit just what you're asking.</p>
<p>Here's an example using the same font-family name with different styles and weights associated with different fonts:</p>
<pre><code>@font-face {
font-family: "DroidSerif";
src: url("DroidSerif-Regular-webfont.ttf") format("truetype");
font-weight: normal;
font-style: normal;
}
@font-face {
font-family: "DroidSerif";
src: url("DroidSerif-Italic-webfont.ttf") format("truetype");
font-weight: normal;
font-style: italic;
}
@font-face {
font-family: "DroidSerif";
src: url("DroidSerif-Bold-webfont.ttf") format("truetype");
font-weight: bold;
font-style: normal;
}
@font-face {
font-family: "DroidSerif";
src: url("DroidSerif-BoldItalic-webfont.ttf") format("truetype");
font-weight: bold;
font-style: italic;
}
</code></pre>
<hr>
<p>You can now specify <code>font-weight:bold</code> or <code>font-style:italic</code> to any element you like without having to specify the font-family or overriding <code>font-weight</code> and <code>font-style</code>.</p>
<pre><code>body { font-family:"DroidSerif", Georgia, serif; }
h1 { font-weight:bold; }
em { font-style:italic; }
strong em {
font-weight:bold;
font-style:italic;
}
</code></pre>
<hr>
<p>For a full overview of this feature and the standard use take a look at <a href="http://www.456bereastreet.com/archive/201012/font-face_tip_define_font-weight_and_font-style_to_keep_your_css_simple/" rel="noreferrer">this article.</a></p>
<hr>
<h2><a href="http://codepen.io/maio/pen/rrKKjA" rel="noreferrer">EXAMPLE PEN</a></h2> | {
"question_id": 28279989,
"question_date": "2015-02-02T14:30:38.933Z",
"question_score": 210,
"tags": "css|fonts|font-face",
"answer_id": 28339483,
"answer_date": "2015-02-05T08:38:39.140Z",
"answer_score": 469
} |
Please answer the following Stack Overflow question:
Title: How do I find the stack trace in Visual Studio?
<p>I ask because I couldn't find the stack trace in Visual Studio, while debugging an exception that occurred.</p> | <p><strong>While debugging</strong>, Go to <strong>Debug -> Windows -> Call Stack</strong></p> | {
"question_id": 945193,
"question_date": "2009-06-03T14:43:37.677Z",
"question_score": 210,
"tags": ".net|visual-studio|debugging|exception-handling|stack-trace",
"answer_id": 945203,
"answer_date": "2009-06-03T14:45:33.727Z",
"answer_score": 296
} |
Please answer the following Stack Overflow question:
Title: Rebase array keys after unsetting elements
<p>I have an array:</p>
<pre><code>$array = array(1,2,3,4,5);
</code></pre>
<p>If I were to dump the contents of the array they would look like this:</p>
<pre><code>array(5) {
[0] => int(1)
[1] => int(2)
[2] => int(3)
[3] => int(4)
[4] => int(5)
}
</code></pre>
<p>When I loop through and unset certain keys, the index gets all jacked up. </p>
<pre><code>foreach($array as $i => $info)
{
if($info == 1 || $info == 2)
{
unset($array[$i]);
}
}
</code></pre>
<p>Subsequently, if I did another dump now it would look like: </p>
<pre><code>array(3) {
[2] => int(3)
[3] => int(4)
[4] => int(5)
}
</code></pre>
<p>Is there a proper way to reset the array so it's elements are Zero based again ?? </p>
<pre><code>array(3) {
[0] => int(3)
[1] => int(4)
[2] => int(5)
}
</code></pre> | <p>Try this:</p>
<pre><code>$array = array_values($array);
</code></pre>
<p>Using <a href="http://php.net/manual/en/function.array-values.php">array_values()</a></p> | {
"question_id": 5943149,
"question_date": "2011-05-09T22:16:37.850Z",
"question_score": 210,
"tags": "php",
"answer_id": 5943165,
"answer_date": "2011-05-09T22:18:52.493Z",
"answer_score": 469
} |
Please answer the following Stack Overflow question:
Title: How to deal with cyclic dependencies in Node.js
<p>I've been working with nodejs lately and still getting to grips with the module system so apologies if this is an obvious question. I want code roughly like the following below:</p>
<p><strong>a.js</strong> (the main file run with node)</p>
<pre><code>var ClassB = require("./b");
var ClassA = function() {
this.thing = new ClassB();
this.property = 5;
}
var a = new ClassA();
module.exports = a;
</code></pre>
<p><strong>b.js</strong></p>
<pre><code>var a = require("./a");
var ClassB = function() {
}
ClassB.prototype.doSomethingLater() {
util.log(a.property);
}
module.exports = ClassB;
</code></pre>
<p>My problem seems to be that I can't access the instance of ClassA from within an instance of ClassB.</p>
<p>Is there a correct / better way to structure modules to achieve what I want?
Is there a better way to share variables between modules?</p> | <p>While node.js does allow circular <code>require</code> dependencies, as you've found it can be <a href="http://nodejs.org/api/modules.html#modules_cycles">pretty messy</a> and you're probably better off restructuring your code to not need it. Maybe create a third class that uses the other two to accomplish what you need.</p> | {
"question_id": 10869276,
"question_date": "2012-06-03T09:42:20.503Z",
"question_score": 210,
"tags": "node.js|module|require|circular-dependency|cyclic-dependency",
"answer_id": 10872944,
"answer_date": "2012-06-03T18:49:14.413Z",
"answer_score": 114
} |
Please answer the following Stack Overflow question:
Title: Why are empty catch blocks a bad idea?
<p>I've just seen a <a href="https://stackoverflow.com/questions/1234278/good-ratio-of-catch-statements-to-lines-of-code">question on try-catch</a>, which people (including Jon Skeet) say empty catch blocks are a really bad idea? Why this? Is there no situation where an empty catch is not a wrong design decision?</p>
<p>I mean, for instance, sometimes you want to get some additional info from somewhere (webservice, database) and you really don't care if you'll get this info or not. So you try to get it, and if anything happens, that's ok, I'll just add a "catch (Exception ignored) {}" and that's all</p> | <p>Usually empty try-catch is a bad idea because you are silently swallowing an error condition and then continuing execution. Occasionally this may be the right thing to do, but often it's a sign that a developer saw an exception, didn't know what to do about it, and so used an empty catch to silence the problem. </p>
<p>It's the programming equivalent of putting black tape over an engine warning light.</p>
<p>I believe that how you deal with exceptions depends on what layer of the software you are working in: <a href="http://nedbatchelder.com/text/exceptions-in-the-rainforest.html" rel="noreferrer">Exceptions in the Rainforest</a>.</p> | {
"question_id": 1234343,
"question_date": "2009-08-05T16:31:56.347Z",
"question_score": 210,
"tags": "exception-handling|try-catch",
"answer_id": 1234364,
"answer_date": "2009-08-05T16:34:31.320Z",
"answer_score": 311
} |
Please answer the following Stack Overflow question:
Title: Execute a terminal command from a Cocoa app
<p>How can I execute a terminal command (like <code>grep</code>) from my Objective-C Cocoa application?</p> | <p>You can use <code><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSTask_Class/Reference/Reference.html" rel="noreferrer">NSTask</a></code>. Here's an example that would run '<code>/usr/bin/grep foo bar.txt</code>'. </p>
<pre><code>int pid = [[NSProcessInfo processInfo] processIdentifier];
NSPipe *pipe = [NSPipe pipe];
NSFileHandle *file = pipe.fileHandleForReading;
NSTask *task = [[NSTask alloc] init];
task.launchPath = @"/usr/bin/grep";
task.arguments = @[@"foo", @"bar.txt"];
task.standardOutput = pipe;
[task launch];
NSData *data = [file readDataToEndOfFile];
[file closeFile];
NSString *grepOutput = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog (@"grep returned:\n%@", grepOutput);
</code></pre>
<p><code>NSPipe</code> and <code>NSFileHandle</code> are used to redirect the standard output of the task. </p>
<p>For more detailed information on interacting with the operating system from within your Objective-C application, you can see this document on Apple's Development Center: <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/OperatingSystem/OperatingSystem.html#//apple_ref/doc/uid/10000058" rel="noreferrer">Interacting with the Operating System</a>. </p>
<p>Edit: Included fix for NSLog problem</p>
<p>If you are using NSTask to run a command-line utility via bash, then you need to include this magic line to keep NSLog working:</p>
<pre><code>//The magic line that keeps your log where it belongs
task.standardOutput = pipe;
</code></pre>
<p>An explanation is here: <a href="https://web.archive.org/web/20141121094204/https://cocoadev.com/HowToPipeCommandsWithNSTask" rel="noreferrer">https://web.archive.org/web/20141121094204/https://cocoadev.com/HowToPipeCommandsWithNSTask</a></p> | {
"question_id": 412562,
"question_date": "2009-01-05T08:21:32.097Z",
"question_score": 210,
"tags": "objective-c|cocoa|macos",
"answer_id": 412573,
"answer_date": "2009-01-05T08:28:22.473Z",
"answer_score": 289
} |
Please answer the following Stack Overflow question:
Title: Null-safe property access (and conditional assignment) in ES6/2015
<p>Is there a <code>null</code>-safe property access (null propagation / existence) operator in ES6 (ES2015/JavaScript.next/Harmony) like <strong><code>?.</code></strong> in <strong>CoffeeScript</strong> for example? Or is it planned for ES7?</p>
<pre><code>var aThing = getSomething()
...
aThing = possiblyNull?.thing
</code></pre>
<p>This will be roughly like:</p>
<pre><code>if (possiblyNull != null) aThing = possiblyNull.thing
</code></pre>
<p>Ideally the solution should not assign (even <code>undefined</code>) to <code>aThing</code> if <code>possiblyNull</code> is <code>null</code></p> | <p><strong>Update</strong> (2022-01-13): Seems people are still finding this, here's the current story:</p>
<ul>
<li>Optional Chaining is in the specification now (ES2020) and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining#browser_compatibility" rel="noreferrer">supported by all modern browsers</a>, more in the archived proposal: <a href="https://github.com/tc39/proposal-optional-chaining" rel="noreferrer">https://github.com/tc39/proposal-optional-chaining</a></li>
<li>babel-preset-env: If you need to support older environments that don't have it, <strong>this is probably what you want</strong> <a href="https://babeljs.io/docs/en/babel-preset-env" rel="noreferrer">https://babeljs.io/docs/en/babel-preset-env</a></li>
<li>Babel v7 Plugin: <a href="https://babeljs.io/docs/en/babel-plugin-proposal-optional-chaining" rel="noreferrer">https://babeljs.io/docs/en/babel-plugin-proposal-optional-chaining</a></li>
</ul>
<p><strong>Update</strong> (2017-08-01): If you want to use an official plugin, you can try the alpha build of Babel 7 with the new transform. <em>Your mileage may vary</em></p>
<p><a href="https://www.npmjs.com/package/babel-plugin-transform-optional-chaining" rel="noreferrer">https://www.npmjs.com/package/babel-plugin-transform-optional-chaining</a></p>
<p><strong>Original</strong>:</p>
<p>A feature that accomplishes that is currently in stage 1: Optional Chaining.</p>
<p><a href="https://github.com/tc39/proposal-optional-chaining" rel="noreferrer">https://github.com/tc39/proposal-optional-chaining</a></p>
<p>If you want to use it today, there is a Babel plugin that accomplishes that.</p>
<p><a href="https://github.com/davidyaha/ecmascript-optionals-proposal" rel="noreferrer">https://github.com/davidyaha/ecmascript-optionals-proposal</a></p> | {
"question_id": 32139078,
"question_date": "2015-08-21T11:23:46.840Z",
"question_score": 210,
"tags": "javascript|coffeescript|ecmascript-6|babeljs",
"answer_id": 41897688,
"answer_date": "2017-01-27T15:40:25.153Z",
"answer_score": 130
} |
Please answer the following Stack Overflow question:
Title: How to use arrow functions (public class fields) as class methods?
<p>I'm new to using ES6 classes with React, previously I've been binding my methods to the current object (show in first example), but does ES6 allow me to permanently bind a class function to a class instance with arrows? (Useful when passing as a callback function.) I get errors when I try to use them as you can with CoffeeScript:</p>
<pre><code>class SomeClass extends React.Component {
// Instead of this
constructor(){
this.handleInputChange = this.handleInputChange.bind(this)
}
// Can I somehow do this? Am i just getting the syntax wrong?
handleInputChange (val) => {
console.log('selectionMade: ', val);
}
</code></pre>
<p>So that if I were to pass <code>SomeClass.handleInputChange</code> to, for instance <code>setTimeout</code>, it would be scoped to the class instance, and not the <code>window</code> object.</p> | <p>Your syntax is slightly off, just missing an equals sign after the property name.</p>
<pre><code>class SomeClass extends React.Component {
handleInputChange = (val) => {
console.log('selectionMade: ', val);
}
}
</code></pre>
<p>This is an experimental feature. You will need to enable experimental features in Babel to get this to compile. <a href="https://babeljs.io/repl/#?experimental=true&evaluate=true&loose=false&spec=false&code=class%20PostInfo%20extends%20React.Component%20%7B%0A%09handleOptionsButtonClick%20%3D%20(e)%20%3D%3E%20%7B%0A%20%20%20%20this.setState(%7BshowOptionsModal%3A%20true%7D)%3B%0A%20%20%7D%0A%7D" rel="noreferrer">Here</a> is a demo with experimental enabled. </p>
<p>To use experimental features in babel you can install the relevant plugin from <a href="https://babeljs.io/docs/plugins/" rel="noreferrer">here</a>. For this specific feature, you need the <a href="http://babeljs.io/docs/plugins/transform-class-properties/" rel="noreferrer"><code>transform-class-properties</code> plugin</a>:</p>
<pre><code>{
"plugins": [
"transform-class-properties"
]
}
</code></pre>
<p>You can read more about the proposal for Class Fields and Static Properties <a href="https://github.com/tc39/proposal-class-fields" rel="noreferrer">here</a></p>
<hr> | {
"question_id": 31362292,
"question_date": "2015-07-11T22:05:21.267Z",
"question_score": 210,
"tags": "javascript|arrow-functions|ecmascript-next|class-fields",
"answer_id": 31362350,
"answer_date": "2015-07-11T22:12:39.420Z",
"answer_score": 234
} |
Please answer the following Stack Overflow question:
Title: Determine on iPhone if user has enabled push notifications
<p>I'm looking for a way to determine if the user has, via settings, enabled or disabled their push notifications for my application.</p> | <p>Call <code>enabledRemoteNotificationsTypes</code> and check the mask.</p>
<p>For example: </p>
<pre><code>UIRemoteNotificationType types = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
if (types == UIRemoteNotificationTypeNone)
// blah blah blah
</code></pre>
<p>iOS8 and above:</p>
<pre><code>[[UIApplication sharedApplication] isRegisteredForRemoteNotifications]
</code></pre> | {
"question_id": 1535403,
"question_date": "2009-10-08T03:05:08.630Z",
"question_score": 210,
"tags": "ios|iphone|notifications|apple-push-notifications|push",
"answer_id": 1535427,
"answer_date": "2009-10-08T03:13:40.577Z",
"answer_score": 301
} |
Please answer the following Stack Overflow question:
Title: InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Http.IHttpContextAccessor'
<p>I started to convert my asp.net core RC1 project to RC2 and faced with problem that now <code>IHttpContextAccessor</code>does not resolved.</p>
<p>For sake of simplicity I created new ASP.NET RC2 project using Visual Studio Template <code>ASP.NET Core Web Application (.Net Framework)</code>. Than I added constructor for HomeController which template created for me.</p>
<pre><code>public HomeController(IHttpContextAccessor accessor)
{
}
</code></pre>
<p>And after I start application I receive next error:</p>
<blockquote>
<p>InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Http.IHttpContextAccessor' while attempting to activate 'TestNewCore.Controllers.HomeController'.
в Microsoft.Extensions.Internal.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired)</p>
</blockquote>
<p>In my real application I need to resolve <code>IHttpContextAccessor</code> in my own service class for getting access to <code>_contextAccessor.HttpContext.Authentication</code> and to <code>_contextAccessor.HttpContext.User</code>. Everething works fine in RC1. So how can it suppose to be in RC2?</p> | <p>IHttpContextAccessor is no longer wired up by default, you have to register it yourself</p>
<pre><code>services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
</code></pre> | {
"question_id": 37371264,
"question_date": "2016-05-22T06:30:29.820Z",
"question_score": 210,
"tags": ".net|dependency-injection|asp.net-core",
"answer_id": 37373557,
"answer_date": "2016-05-22T11:08:57.533Z",
"answer_score": 323
} |
Please answer the following Stack Overflow question:
Title: What are the differences between the different saving methods in Hibernate?
<p>Hibernate has a handful of methods that, one way or another, takes your object and puts it into the database. What are the differences between them, when to use which, and why isn't there just one intelligent method that knows when to use what?</p>
<p>The methods that I have identified thus far are:</p>
<ul>
<li><code>save()</code></li>
<li><code>update()</code></li>
<li><code>saveOrUpdate()</code></li>
<li><code>saveOrUpdateCopy()</code></li>
<li><code>merge()</code></li>
<li><code>persist()</code></li>
</ul> | <p>Here's my understanding of the methods. Mainly these are based on the <a href="http://www.hibernate.org/hib_docs/v3/api/org/hibernate/Session.html" rel="noreferrer">API</a> though as I don't use all of these in practice.</p>
<p><strong>saveOrUpdate</strong>
Calls either save or update depending on some checks. E.g. if no identifier exists, save is called. Otherwise update is called.</p>
<p><strong>save</strong>
Persists an entity. Will assign an identifier if one doesn't exist. If one does, it's essentially doing an update. Returns the generated ID of the entity.</p>
<p><strong>update</strong>
Attempts to persist the entity using an existing identifier. If no identifier exists, I believe an exception is thrown.</p>
<p><strong>saveOrUpdateCopy</strong>
This is deprecated and should no longer be used. Instead there is...</p>
<p><strong>merge</strong>
Now this is where my knowledge starts to falter. The important thing here is the difference between transient, detached and persistent entities. For more info on the object states, <a href="http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/objectstate.html" rel="noreferrer">take a look here</a>. With save & update, you are dealing with persistent objects. They are linked to a Session so Hibernate knows what has changed. But when you have a transient object, there is no session involved. In these cases you need to use merge for updates and persist for saving.</p>
<p><strong>persist</strong>
As mentioned above, this is used on transient objects. It does not return the generated ID.</p> | {
"question_id": 161224,
"question_date": "2008-10-02T07:38:12.590Z",
"question_score": 210,
"tags": "java|hibernate|persistence",
"answer_id": 161358,
"answer_date": "2008-10-02T08:32:45.923Z",
"answer_score": 123
} |
Please answer the following Stack Overflow question:
Title: When should Flask.g be used?
<p>I <a href="https://github.com/mitsuhiko/flask/blob/master/CHANGES" rel="noreferrer">saw</a> that <code>g</code> will move from the request context to the app context in Flask 0.10, which made me confused about the intended use of <code>g</code>.</p>
<p>My understanding (for Flask 0.9) is that:</p>
<ul>
<li><code>g</code> lives in the request context, i.e., created afresh when the requests starts, and available until it ends</li>
<li><code>g</code> is intended to be used as a "request blackboard", where I can put stuff relevant for the duration of the request (i.e., set a flag at the beginning of the request and handle it at the end, possibly from a <code>before_request</code>/<code>after_request</code> pair)</li>
<li>in addition to holding request-level-state, <code>g</code> can and should be used for resource management, i.e., holding database connections, etc.</li>
</ul>
<p>Which of these sentences are no longer true in Flask 0.10? Can someone point me to a resource discussing the <em>reasons</em> for the change? What should I use as a "request blackboard" in Flask 0.10 - should I create my own app/extension specific thread-local proxy and push it to the context stack <code>before_request</code>? What's the point of resource management at the application context, if my application lives for a long while (not like a request) and thus the resources are never freed?</p> | <p><a href="https://speakerdeck.com/mitsuhiko/advanced-flask-patterns-1" rel="noreferrer">Advanced Flask Patterns</a>, as <a href="https://stackoverflow.com/questions/15083967/when-should-flask-g-be-used/15101229#comment21244306_15083967">linked by Markus</a>, explains some of the changes to <code>g</code> in 0.10:</p>
<ul>
<li><code>g</code> now lives in the application context.</li>
<li><a href="https://github.com/mitsuhiko/flask/blob/1949c4a9abc174bf29620f6dd8ceab9ed3ace2eb/flask/ctx.py#L230" rel="noreferrer">Every request pushes a new application context</a>, wiping the old one, so <code>g</code> can still be used to set flags per-request without change to code.</li>
<li>The application context is popped <em>after</em> <code>teardown_request</code> is called. (Armin's presentation explains this is because things like creating DB connections are tasks which <em>setup</em> the environment for the request, and should not be handled inside <code>before_request</code> and <code>after_request</code>)</li>
</ul> | {
"question_id": 15083967,
"question_date": "2013-02-26T07:49:46.390Z",
"question_score": 210,
"tags": "python|flask",
"answer_id": 15101229,
"answer_date": "2013-02-26T23:06:46.323Z",
"answer_score": 141
} |
Please answer the following Stack Overflow question:
Title: Which letter of the English alphabet takes up most pixels?
<p>I am trying to do some dynamic programming based on the number of characters in a sentence. Which letter of the English alphabet takes up the most pixels on the screen?</p> | <p>Hmm, let's see:</p>
<p>aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa </p>
<p>bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb </p>
<p>cccccccccccccccccccccccccccccccccccccccc </p>
<p>dddddddddddddddddddddddddddddddddddddddd </p>
<p>eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee </p>
<p>ffffffffffffffffffffffffffffffffffffffff </p>
<p>gggggggggggggggggggggggggggggggggggggggg </p>
<p>hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh </p>
<p>iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii </p>
<p>jjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj </p>
<p>kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk </p>
<p>llllllllllllllllllllllllllllllllllllllll </p>
<p>mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm </p>
<p>nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn </p>
<p>oooooooooooooooooooooooooooooooooooooooo </p>
<p>pppppppppppppppppppppppppppppppppppppppp </p>
<p>qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq </p>
<p>rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr </p>
<p>ssssssssssssssssssssssssssssssssssssssss </p>
<p>tttttttttttttttttttttttttttttttttttttttt </p>
<p>uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu </p>
<p>vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv </p>
<p>wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww </p>
<p>xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx </p>
<p>yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy </p>
<p>zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz </p>
<p>AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA </p>
<p>BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB </p>
<p>CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC </p>
<p>DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD </p>
<p>EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE </p>
<p>FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF </p>
<p>GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG </p>
<p>HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH </p>
<p>IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII </p>
<p>JJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJ </p>
<p>KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK </p>
<p>LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL </p>
<p>MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM </p>
<p>NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN </p>
<p>OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO </p>
<p>PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP </p>
<p>QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ </p>
<p>RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR </p>
<p>SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS </p>
<p>TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT </p>
<p>UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU </p>
<p>VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV </p>
<p>WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW </p>
<p>XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX </p>
<p>YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY </p>
<p>ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ </p>
<p><strong>W wins.</strong></p>
<p>Of course, this is a silly empirical experiment. There is no single answer to which letter is widest. It depends on the font. So you'll have to do a similar empirical experiment to figure out the answer for your environment. But the fact is, most fonts follow the same conventions, and capital W will be the widest.</p>
<p>Gist with these character widths in a ratio form (W = 100) captured here using this particular example font:</p>
<p><a href="https://gist.github.com/imaurer/d330e68e70180c985b380f25e195b90c" rel="noreferrer">https://gist.github.com/imaurer/d330e68e70180c985b380f25e195b90c</a></p> | {
"question_id": 3949422,
"question_date": "2010-10-16T15:09:30.353Z",
"question_score": 210,
"tags": "css|char",
"answer_id": 3949453,
"answer_date": "2010-10-16T15:15:57.693Z",
"answer_score": 815
} |
Please answer the following Stack Overflow question:
Title: is it possible to `git status` only modified files?
<p>Is it possible to have <code>git status</code> only show the modified files due, in my case, to having too many staged files?</p> | <p>You can't do this with <code>git status</code>, but you could use <code>git ls-files -m</code> to show all modified files.</p> | {
"question_id": 10018533,
"question_date": "2012-04-04T20:10:59.170Z",
"question_score": 210,
"tags": "git|ubuntu|git-status",
"answer_id": 10018728,
"answer_date": "2012-04-04T20:26:40.603Z",
"answer_score": 320
} |
Please answer the following Stack Overflow question:
Title: What are the implications of using "!important" in CSS?
<p>I've been working on a website for a few months, and a lot of times when I've been trying to edit something, I have to use <code>!important</code>, <em>for example</em>:</p>
<pre><code>div.myDiv {
width: 400px !important;
}
</code></pre>
<p>in order to make it display as expected. Is this bad practice? Or is the <code>!important</code> command okay to use? Can this cause anything undesired further down the line? </p> | <p>Yes, I'd say your example of using <code>!important</code> is bad practice, and it's very likely it would cause undesired effects further down the line. That doesn't mean it's never okay to use though.</p>
<h3>What's wrong with <code>!important</code>:</h3>
<p><a href="http://www.smashingmagazine.com/2010/04/css-specificity-and-inheritance/" rel="noreferrer">Specificity</a> is one of the main forces at work when the browser decides how CSS affects the page. The more specific a selector is, the more importance is added to it. This usually coincides with how often the selected element occurs. For example:</p>
<pre class="lang-css prettyprint-override"><code>button {
color: black;
}
button.highlight {
color: blue;
font-size: 1.5em;
}
button#buyNow {
color: green;
font-size: 2em;
}
</code></pre>
<p>On this page, all buttons are black. Except the buttons with the class "highlight", which are blue. Except that one unique button with the ID "buyNow", which is green. The importance of the entire rule (both the color and font-size in this case) is managed by the specificity of the selector.</p>
<p><strong><code>!important</code></strong>, however, is added at a property level, not a selector level. If, for instance, we used this rule:</p>
<pre class="lang-css prettyprint-override"><code>button.highlight {
color: blue !important;
font-size: 1.5em;
}
</code></pre>
<p>then the color property would have a higher importance than the font-size. In fact, the color is more important than the color in the <code>button#buyNow</code> selector, as opposed to the font-size (which is still governed by the regular ID vs class specificity).</p>
<p>An element <code><button class="highlight" id="buyNow"></code> would have a font-size of <code>2em</code>, but a color <code>blue</code>.</p>
<p>This means two things:</p>
<ol>
<li>The selector does not accurately convey the importance of all the rules inside it</li>
<li>The <em>only</em> way to override the color blue is to use <em>another</em> <code>!important</code> declaration, for example in the <code>button#buyNow</code> selector.</li>
</ol>
<p>This not only makes your stylesheets a lot harder to maintain and debug, it starts a snowball effect. One <code>!important</code> leads to another to override it, to yet another to override that, et cetera. It almost never stays with just one. Even though one <code>!important</code> can be a useful short-term solution, it will come back to bite you in the ass in the long run.</p>
<h3>When is it okay to use:</h3>
<ul>
<li>Overriding styles in a user stylesheet.</li>
</ul>
<p>This is what <code>!important</code> was invented for in the first place: to give the user a means to override website styles. It's used a lot by accessibility tools like screen readers, ad blockers, and more.</p>
<ul>
<li>Overriding 3rd party code & inline styles.</li>
</ul>
<p>Generally I'd say this is a case of code smell, but sometimes you just have no option. As a developer, you should aim to have as much control over your code as possible, but there are cases when your hands are tied and you just have to work with whatever is present. Use <code>!important</code> sparingly.</p>
<ul>
<li>Utility classes</li>
</ul>
<p>Many libraries and frameworks come with utility classes like <code>.hidden</code>, <code>.error</code>, or <code>.clearfix</code>. They serve a single purpose, and often apply very few, but very important, rules. (<code>display: none</code> for a <code>.hidden</code> class, for example). These should override whatever other styles are currently on the element, and definitely warrant an <code>!important</code> if you ask me.</p>
<h3>Conclusion</h3>
<p>Using the <code>!important</code> declaration is often considered bad practice because it has side effects that mess with one of CSS's core mechanisms: specificity. In many cases, using it could indicate poor CSS architecture.</p>
<p>There are cases in which it's tolerable or even preferred, but make sure you double check that one of those cases actually applies to your situation before using it.</p> | {
"question_id": 3706819,
"question_date": "2010-09-14T07:23:12.427Z",
"question_score": 210,
"tags": "html|css|css-specificity",
"answer_id": 3706876,
"answer_date": "2010-09-14T07:31:55.307Z",
"answer_score": 277
} |
Please answer the following Stack Overflow question:
Title: registerForRemoteNotificationTypes: is not supported in iOS 8.0 and later
<p>When trying to register for push notifications under iOS 8.x:</p>
<pre><code>application.registerForRemoteNotificationTypes(UIRemoteNotificationType.Alert | UIRemoteNotificationType.Badge | UIRemoteNotificationType.Sound)
</code></pre>
<p>I get the following error:</p>
<pre><code>registerForRemoteNotificationTypes: is not supported in iOS 8.0 and later.
</code></pre>
<p>Any ideas what is the new way of doing it? It does work when I run this Swift app on iOS 7.x.</p>
<p><strong>EDIT</strong></p>
<p>On iOS 7.x when I include the conditional code I get (either SystemVersion conditional or #if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000)</p>
<pre><code>dyld: Symbol not found: _OBJC_CLASS_$_UIUserNotificationSettings
</code></pre> | <p>As you described, you will need to use a different method based on different versions of iOS. If your team is using both Xcode 5 (which doesn't know about any iOS 8 selectors) and Xcode 6, then you will need to use conditional compiling as follows:</p>
<pre><code>#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
if ([application respondsToSelector:@selector(registerUserNotificationSettings:)]) {
// use registerUserNotificationSettings
} else {
// use registerForRemoteNotificationTypes:
}
#else
// use registerForRemoteNotificationTypes:
#endif
</code></pre>
<p>If you are only using Xcode 6, you can stick with just this:</p>
<pre><code>if ([application respondsToSelector:@selector(registerUserNotificationSettings:)]) {
// use registerUserNotificationSettings
} else {
// use registerForRemoteNotificationTypes:
}
</code></pre>
<p>The reason is here is that the way you get notification permissions has changed in iOS 8. A <code>UserNotification</code> is a message shown to the user, whether from remote or from local. You need to get permission to show one. This is described in the WWDC 2014 video <a href="https://developer.apple.com/videos/play/wwdc2014/713/" rel="nofollow noreferrer">"What's New in iOS Notifications"</a></p> | {
"question_id": 24454033,
"question_date": "2014-06-27T14:15:52.833Z",
"question_score": 210,
"tags": "objective-c|ios8|apple-push-notifications|dyld",
"answer_id": 24688545,
"answer_date": "2014-07-11T00:48:49.983Z",
"answer_score": 145
} |
Please answer the following Stack Overflow question:
Title: Pass An Instantiated System.Type as a Type Parameter for a Generic Class
<p>The title is kind of obscure. What I want to know is if this is possible:</p>
<pre><code>string typeName = <read type name from somwhere>;
Type myType = Type.GetType(typeName);
MyGenericClass<myType> myGenericClass = new MyGenericClass<myType>();
</code></pre>
<p>Obviously, MyGenericClass is described as:</p>
<pre><code>public class MyGenericClass<T>
</code></pre>
<p>Right now, the compiler complains that 'The type or namespace 'myType' could not be found." There has got to be a way to do this.</p> | <p>You can't do this without reflection. However, you <em>can</em> do it with reflection. Here's a complete example:</p>
<pre><code>using System;
using System.Reflection;
public class Generic<T>
{
public Generic()
{
Console.WriteLine("T={0}", typeof(T));
}
}
class Test
{
static void Main()
{
string typeName = "System.String";
Type typeArgument = Type.GetType(typeName);
Type genericClass = typeof(Generic<>);
// MakeGenericType is badly named
Type constructedClass = genericClass.MakeGenericType(typeArgument);
object created = Activator.CreateInstance(constructedClass);
}
}
</code></pre>
<p>Note: if your generic class accepts multiple types, you must include the commas when you omit the type names, for example:</p>
<pre><code>Type genericClass = typeof(IReadOnlyDictionary<,>);
Type constructedClass = genericClass.MakeGenericType(typeArgument1, typeArgument2);
</code></pre> | {
"question_id": 266115,
"question_date": "2008-11-05T18:19:51.687Z",
"question_score": 210,
"tags": "c#|.net|generics",
"answer_id": 266282,
"answer_date": "2008-11-05T19:30:52.807Z",
"answer_score": 248
} |
Please answer the following Stack Overflow question:
Title: How to force LINQ Sum() to return 0 while source collection is empty
<p>Basically when I do the following query, if no leads were matched the following query throws an exception. In that case I'd prefer to have the sum equalize 0 rather than an exception being thrown.
Would this be possible in the query itself - I mean rather than storing the query and checking <code>query.Any()</code> ?</p>
<pre><code>double earnings = db.Leads.Where(l => l.Date.Day == date.Day
&& l.Date.Month == date.Month
&& l.Date.Year == date.Year
&& l.Property.Type == ProtectedPropertyType.Password
&& l.Property.PropertyId == PropertyId).Sum(l => l.Amount);
</code></pre> | <p>Try changing your query to this:</p>
<pre><code>db.Leads.Where(l => l.Date.Day == date.Day
&& l.Date.Month == date.Month
&& l.Date.Year == date.Year
&& l.Property.Type == ProtectedPropertyType.Password
&& l.Property.PropertyId == PropertyId)
.Select(l => l.Amount)
.DefaultIfEmpty(0)
.Sum();
</code></pre>
<p>This way, your query will only select the <code>Amount</code> field. If the collection is empty, it will return one element with the value of <code>0</code> and then the sum will be applied.</p> | {
"question_id": 17593371,
"question_date": "2013-07-11T12:26:57.227Z",
"question_score": 210,
"tags": "c#|.net|entity-framework",
"answer_id": 17593594,
"answer_date": "2013-07-11T12:36:51.473Z",
"answer_score": 433
} |
Please answer the following Stack Overflow question:
Title: Register Application class in Manifest?
<p>I have one Application class to keep the global state of my application. But I'm unable to register it in Manifest file? Any idea how to do this?</p> | <p>If it derives from Application, add the fully qualified (namespace + class name) as the <code>android:name</code> parameter of the application element in your manifest.</p>
<pre><code><application
android:name="com.you.yourapp.ApplicationEx"
</code></pre>
<p>Or if the class' package can be described as relative to the <code>package</code> in the <code>manifest</code> tag, then just start with a <code>.</code>:</p>
<pre><code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.you.yourapp">
<application
android:name=".ApplicationEx"
</code></pre> | {
"question_id": 2929562,
"question_date": "2010-05-28T13:53:48.410Z",
"question_score": 210,
"tags": "android|android-manifest",
"answer_id": 2929927,
"answer_date": "2010-05-28T14:37:13.920Z",
"answer_score": 388
} |
Please answer the following Stack Overflow question:
Title: How do you validate the PropTypes of a nested object in ReactJS?
<p>I'm using a data object as my props for a component in ReactJS.</p>
<pre><code><Field data={data} />
</code></pre>
<p>I know its easy to validate the PropTypes object itself:</p>
<pre><code>propTypes: {
data: React.PropTypes.object
}
</code></pre>
<p>But what if I want to validate the values inside? ie. data.id, data.title?</p>
<pre><code>props[propName]: React.PropTypes.number.required // etc...
</code></pre> | <p>You can use <code>React.PropTypes.shape</code> to validate properties:</p>
<pre><code>propTypes: {
data: React.PropTypes.shape({
id: React.PropTypes.number.isRequired,
title: React.PropTypes.string
})
}
</code></pre>
<p><strong>Update</strong></p>
<p>As @Chris pointed out in comments, as of React version 15.5.0 <code>React.PropTypes</code> has moved to package <code>prop-types</code>.</p>
<pre><code>import PropTypes from 'prop-types';
propTypes: {
data: PropTypes.shape({
id: PropTypes.number.isRequired,
title: PropTypes.string
})
}
</code></pre>
<p><a href="https://facebook.github.io/react/blog/2017/04/07/react-v15.5.0.html#migrating-from-react.proptypes" rel="noreferrer">More info</a></p> | {
"question_id": 26923042,
"question_date": "2014-11-14T04:44:00.173Z",
"question_score": 210,
"tags": "reactjs",
"answer_id": 26924696,
"answer_date": "2014-11-14T07:05:48.310Z",
"answer_score": 400
} |
Please answer the following Stack Overflow question:
Title: Why does Pycharm's inspector complain about "d = {}"?
<p>When initializing a dictionary with <code>d = {}</code> Pycharm's code inspector generates a warning, saying</p>
<blockquote>
<p>This dictionary creation could be rewritten as a dictionary literal.</p>
</blockquote>
<p>If I rewrite it <code>d = dict()</code> the warning goes away. Since <code>{}</code> already <em>is</em> a dictionary literal, I'm pretty sure the message is erroneous. Furthermore, it seems like both <code>d = {}</code> and <code>d = dict()</code> are valid and Pythonic. </p>
<p>This related question seems to conclude that the choice is just a matter of style/preference:
<a href="https://stackoverflow.com/questions/2745008/differences-between-d-dict-and-d">differences between "d = dict()" and "d = {}"</a></p>
<p>Why would Pycharm complain about <code>d = {}</code>?</p>
<p><em>UPDATE:</em></p>
<p>Mac nailed it. The warning actually applied to multiple lines, not just the one that was flagged.</p>
<p>Pycharm seems to look for a sequence of consecutive statements where you initialize a dictionary and then set values in the dictionary. For example, this will trigger the warning:</p>
<pre><code>d = {}
d['a'] = 1
</code></pre>
<p>But this code will not:</p>
<pre><code>d = {}
pass
d['a'] = 1
</code></pre> | <p><strong>What is the code following your dictionary declaration?</strong></p>
<p>I think PyCharm will trigger the error if you have something like:</p>
<pre class="lang-py prettyprint-override"><code>dic = {}
dic['aaa'] = 5
</code></pre>
<p>as you could have written</p>
<pre class="lang-py prettyprint-override"><code>dic = {'aaa': 5}
</code></pre>
<p>Note: The fact that the error goes away if you use the function <code>dict()</code>. This doesn't necessarily mean that pycharm believes <code>dict()</code> is a literal. It could just mean that it doesn't complain about it:</p>
<pre class="lang-py prettyprint-override"><code>dic = dict()
dic['aaa'] = 5
</code></pre> | {
"question_id": 8406242,
"question_date": "2011-12-06T20:16:50.270Z",
"question_score": 210,
"tags": "python|pycharm",
"answer_id": 8406391,
"answer_date": "2011-12-06T20:29:00.833Z",
"answer_score": 262
} |
Please answer the following Stack Overflow question:
Title: Constructors vs Factory Methods
<p>When modelling classes, what is the preferred way of initializing:</p>
<ol>
<li>Constructors, or</li>
<li>Factory Methods</li>
</ol>
<p>And what would be the considerations for using either of them?</p>
<p>In certain situations, I prefer having a factory method which returns null if the object cannot be constructed. This makes the code neat. I can simply check if the returned value is not null before taking alternative action, in contrast with throwing an exception from the constructor. (I personally don't like exceptions)</p>
<p>Say, I have a constructor on a class which expects an id value. The constructor uses this value to populate the class from the database. In the case where a record with the specified id does not exist, the constructor throws a RecordNotFoundException. In this case I will have to enclose the construction of all such classes within a try..catch block.</p>
<p>In contrast to this I can have a static factory method on those classes which will return null if the record is not found.</p>
<p>Which approach is better in this case, constructor or factory method?</p> | <p>From page 108 of <a href="https://rads.stackoverflow.com/amzn/click/com/0201633612" rel="noreferrer" rel="nofollow noreferrer">Design Patterns: Elements of Reusable Object-Oriented Software by Gamma, Helm, Johnson, and Vlissides.</a></p>
<p>Use the Factory Method pattern when</p>
<ul>
<li>a class can't anticipate the class of objects it must create</li>
<li>a class wants its subclasses to specify the objects it creates</li>
<li>classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate</li>
</ul> | {
"question_id": 628950,
"question_date": "2009-03-10T04:38:29.020Z",
"question_score": 210,
"tags": "oop|ooad",
"answer_id": 628959,
"answer_date": "2009-03-10T04:43:27.213Z",
"answer_score": 64
} |
Please answer the following Stack Overflow question:
Title: .toArray(new MyClass[0]) or .toArray(new MyClass[myList.size()])?
<p>Assuming I have an ArrayList</p>
<pre><code>ArrayList<MyClass> myList;
</code></pre>
<p>And I want to call toArray, is there a performance reason to use</p>
<pre><code>MyClass[] arr = myList.toArray(new MyClass[myList.size()]);
</code></pre>
<p>over</p>
<pre><code>MyClass[] arr = myList.toArray(new MyClass[0]);
</code></pre>
<p>?</p>
<p>I prefer the second style, since it's less verbose, and I assumed that the compiler will make sure the empty array doesn't really get created, but I've been wondering if that's true.</p>
<p>Of course, in 99% of the cases it doesn't make a difference one way or the other, but I'd like to keep a consistent style between my normal code and my optimized inner loops...</p> | <p>Counterintuitively, the fastest version, on Hotspot 8, is:</p>
<pre><code>MyClass[] arr = myList.toArray(new MyClass[0]);
</code></pre>
<p>I have run a micro benchmark using jmh the results and code are below, showing that the version with an empty array consistently outperforms the version with a presized array. Note that if you can reuse an existing array of the correct size, the result may be different.</p>
<p>Benchmark results (score in microseconds, smaller = better):</p>
<pre><code>Benchmark (n) Mode Samples Score Error Units
c.a.p.SO29378922.preSize 1 avgt 30 0.025 ▒ 0.001 us/op
c.a.p.SO29378922.preSize 100 avgt 30 0.155 ▒ 0.004 us/op
c.a.p.SO29378922.preSize 1000 avgt 30 1.512 ▒ 0.031 us/op
c.a.p.SO29378922.preSize 5000 avgt 30 6.884 ▒ 0.130 us/op
c.a.p.SO29378922.preSize 10000 avgt 30 13.147 ▒ 0.199 us/op
c.a.p.SO29378922.preSize 100000 avgt 30 159.977 ▒ 5.292 us/op
c.a.p.SO29378922.resize 1 avgt 30 0.019 ▒ 0.000 us/op
c.a.p.SO29378922.resize 100 avgt 30 0.133 ▒ 0.003 us/op
c.a.p.SO29378922.resize 1000 avgt 30 1.075 ▒ 0.022 us/op
c.a.p.SO29378922.resize 5000 avgt 30 5.318 ▒ 0.121 us/op
c.a.p.SO29378922.resize 10000 avgt 30 10.652 ▒ 0.227 us/op
c.a.p.SO29378922.resize 100000 avgt 30 139.692 ▒ 8.957 us/op
</code></pre>
<hr>
<p>For reference, the code:</p>
<pre><code>@State(Scope.Thread)
@BenchmarkMode(Mode.AverageTime)
public class SO29378922 {
@Param({"1", "100", "1000", "5000", "10000", "100000"}) int n;
private final List<Integer> list = new ArrayList<>();
@Setup public void populateList() {
for (int i = 0; i < n; i++) list.add(0);
}
@Benchmark public Integer[] preSize() {
return list.toArray(new Integer[n]);
}
@Benchmark public Integer[] resize() {
return list.toArray(new Integer[0]);
}
}
</code></pre>
<hr>
<p>You can find similar results, full analysis, and discussion in the blog post <a href="https://shipilev.net/blog/2016/arrays-wisdom-ancients/" rel="noreferrer"><em>Arrays of Wisdom of the Ancients</em></a>. To summarize: the JVM and JIT compiler contains several optimizations that enable it to cheaply create and initialize a new correctly sized array, and those optimizations can not be used if you create the array yourself.</p> | {
"question_id": 174093,
"question_date": "2008-10-06T12:38:00.417Z",
"question_score": 210,
"tags": "java|performance|coding-style",
"answer_id": 29444594,
"answer_date": "2015-04-04T09:05:26.537Z",
"answer_score": 146
} |
Please answer the following Stack Overflow question:
Title: What is the difference between Action Bar and newly introduced Toolbar?
<p>After Google introduced Material Design, I have heard about a new widget class called Toolbar.</p>
<p>What is the Toolbar, and what is the exact difference between ActionBar and ToolBar? </p> | <p>I found a good explanation from <a href="http://android-developers.blogspot.kr/2014/10/appcompat-v21-material-design-for-pre.html" rel="noreferrer">Android Developers Blog post</a>.</p>
<blockquote>
<p>In this release, Android introduces a new Toolbar widget. <strong><em>This is a generalization of the Action Bar pattern that gives you much more control and flexibility.</em></strong> <strong><em>Toolbar is a view in your hierarchy just like any other, making it easier to interleave with the rest of your views</em></strong>, animate it, and react to scroll events. You can also set it as your Activity’s action bar, meaning that your standard options menu actions will be display within it.</p>
</blockquote>
<p>Yes, we, Android developers, needed more control over <code>ActionBar</code>, right? And <code>Toolbar</code> is just for it. </p>
<p>In other words, the <code>ActionBar</code> now became a special kind of <code>Toolbar</code>. This is an excerpt from <a href="http://www.google.com/design/spec/layout/structure.html#structure-app-bar" rel="noreferrer">Google's official Material Design spec document</a>.</p>
<blockquote>
<p>The app bar, formerly known as the action bar in Android, is a special kind of toolbar that’s used for branding, navigation, search, and actions.</p>
</blockquote>
<p>More details like how to use <code>Toolbar</code> as an <code>ActionBar</code> are included in above blog post.</p> | {
"question_id": 27665018,
"question_date": "2014-12-27T06:37:07.913Z",
"question_score": 210,
"tags": "android|android-actionbar|material-design|android-toolbar",
"answer_id": 27665019,
"answer_date": "2014-12-27T06:37:07.913Z",
"answer_score": 207
} |
Please answer the following Stack Overflow question:
Title: What is "pkg-resources==0.0.0" in output of pip freeze command
<p>When I run <code>pip freeze</code> I see (among other expected packages) <code>pkg-resources==0.0.0</code>. I have seen a few posts mentioning this package (including <a href="https://stackoverflow.com/questions/38992194/why-does-pip-freeze-list-pkg-resources-0-0-0">this one</a>), but none explaining what it is, or why it is included in the output of <code>pip freeze</code>. The main reason I am wondering is out of curiosity, but also, it seems to break things in some cases when trying to install packages with a <code>requirements.txt</code> file generated with <code>pip freeze</code> that includes the <code>pkg-resources==0.0.0</code> line (for example when <a href="https://travis-ci.org/" rel="noreferrer">Travis CI</a> tries to install dependencies through <code>pip</code> and finds this line).</p>
<p><strong>What is <code>pkg-resources</code>, and is it OK to remove this line from <code>requirements.txt</code>?</strong></p>
<h1>Update:</h1>
<p>I have found that this line only seems to exist in the output of <code>pip freeze</code> when I am in a <code>virtualenv</code>. I am still not sure what it is or what it does, but I will investigate further knowing that it is likely related to <code>virtualenv</code>.</p> | <p>According to <a href="https://github.com/pypa/pip/issues/4022" rel="nofollow noreferrer">https://github.com/pypa/pip/issues/4022</a>, this is a bug resulting from Ubuntu providing incorrect metadata to pip. So, no there does not seem to be a good reason for this behaviour. I filed a follow-up bug with Ubuntu. <a href="https://bugs.launchpad.net/ubuntu/+source/python-pip/+bug/1635463" rel="nofollow noreferrer">https://bugs.launchpad.net/ubuntu/+source/python-pip/+bug/1635463</a></p>
<p>To backup the previous answer, it should be safe to remove that line from your requirements.txt. Here is an example Make file stanza that safely freezes your package list (drop in your Makefile and run with <code>make freeze</code>):</p>
<pre><code>freeze:
pip freeze | grep -v "pkg-resources" > requirements.txt
</code></pre>
<p><em>edit 2022 July 06:</em></p>
<p>I have been informed that the package name differs depending on the system in use (<code>pkg-resources</code> vs <code>pkg_resources</code>). Please see the comments attached to this answer for differences in usage between different versions of Debian/Ubuntu. As <code>pkg-resources</code> is the historically correct package name at the time this was posted (almost 6 years ago) for the system in question, it will remain unchanged in this answer.</p> | {
"question_id": 39577984,
"question_date": "2016-09-19T16:36:39.120Z",
"question_score": 210,
"tags": "python|python-3.x|pip|ubuntu-16.04",
"answer_id": 40167445,
"answer_date": "2016-10-21T02:30:45.570Z",
"answer_score": 243
} |
Please answer the following Stack Overflow question:
Title: How to determine function name from inside a function
<p>If I have a Bash script like:</p>
<pre><code>#!/bin/bash
f() {
# echo function name, "f" in this case
}
</code></pre>
<p>Is there any way to do this? This could be used in help messages such as</p>
<pre><code>printf "Usage: %s: blah blah blah \n" $(basename $0) >&2;
</code></pre>
<p>Only in this case what I wanted is not <code>$0</code>, which is the file name of the script.</p> | <p>You can use <code>${FUNCNAME[0]}</code> in <code>bash</code> to get the function name.</p> | {
"question_id": 1835943,
"question_date": "2009-12-02T21:29:29.690Z",
"question_score": 210,
"tags": "bash|function",
"answer_id": 1835958,
"answer_date": "2009-12-02T21:31:35.350Z",
"answer_score": 300
} |
Please answer the following Stack Overflow question:
Title: Looking for ALT+LeftArrowKey solution in zsh
<p>I just recently switched from bash to zsh, however I miss my <kbd>Alt</kbd>+<kbd>LeftArrowKey</kbd> and <kbd>Alt</kbd>+<kbd>RightArrowKey</kbd> to go back and forth a word at a time.</p>
<p>Right now, if I press <kbd>Alt</kbd>+<kbd>LeftArrowKey</kbd> I go back a couple of letters and then I'm stuck. I won't go any further backwards and it won't back to the end of the line with <kbd>Alt</kbd>+<kbd>RightArrowKey</kbd> as I would expect. I can't even use the arrow keys to go to the end of the line, only to the second to last. Can't input new chars on the line either or indeed delete.</p>
<p>How do I get my beloved shortcut back?</p>
<p>I'm on Mac OS X using Terminal if that's important.</p> | <p>Run <code>cat</code> then press keys to see the codes your shortcut send.<br>
(Press <kbd>Ctrl</kbd>+<kbd>C</kbd> to kill the <code>cat</code> when you're done.)<br>
For me, (ubuntu, konsole, xterm) pressing <kbd>Alt</kbd>+<kbd>←</kbd> sends <code>^[[1;3D</code>, so i would put in my <em>.zshrc</em></p>
<pre><code>bindkey "^[[1;3C" forward-word
bindkey "^[[1;3D" backward-word
</code></pre>
<p>(Actually I prefer to use <kbd>Ctrl</kbd> + arrow to move word by word, like in a normal textbox under windows or linux gui.)</p>
<p>Related question: <a href="https://stackoverflow.com/questions/8638012">Fix key settings (Home/End/Insert/Delete) in .zshrc when running Zsh in Terminator Terminal Emulator</a></p> | {
"question_id": 12382499,
"question_date": "2012-09-12T06:41:08.020Z",
"question_score": 210,
"tags": "shell|key|zsh",
"answer_id": 12403798,
"answer_date": "2012-09-13T10:01:26.807Z",
"answer_score": 389
} |
Please answer the following Stack Overflow question:
Title: Eclipse debugger always blocks on ThreadPoolExecutor without any obvious exception, why?
<p>I'm working on my usual projects on Eclipse, it's a J2EE application, made with Spring, Hibernate and so on. I'm using Tomcat 7 for this (no particular reason, I don't exploit any new feature, I just wanted to try that). Every time I debug my application, it happens that Eclipse debugger pops out like it has reached a breakpoint, but it is not the case, in fact it stops on a Java source file that is <code>ThreadPoolExecutor</code>. There is no stack trace on the console, it just stops. Then if I click on resume it goes on and the app works perfectly. This is what shows in the debugger window:</p>
<pre><code>Daemon Thread ["http-bio-8080"-exec-2] (Suspended (exception RuntimeException))
ThreadPoolExecutor$Worker.run() line: 912
TaskThread(Thread).run() line: 619
</code></pre>
<p>I really can't explain this, because I'm not using <code>ThreadPoolExecutor</code> at all. Must be something from Tomcat, Hibernate or Spring. It's very annoying because I always have to resume during debugging.</p>
<p>Any clues?</p> | <p>The posted stack trace indicates that a RuntimeException was encountered in a Daemon thread. This is typically uncaught at runtime, unless the original developer caught and handled the exception.</p>
<p>Typically, the debugger in Eclipse is configured to suspend execution at the location where the exception was thrown, on <em>all uncaught exceptions</em>. Note that the exception might be handled later, lower down in the stack frame and might not lead to the thread being terminated. This would be cause of the behavior observed.</p>
<p><strong>Configuring the behavior of Eclipse</strong> is straightforward:<br>
Go to <strong>Window</strong> > <strong>Preferences</strong> > <strong>Java</strong> > <strong>Debug</strong> and uncheck <strong>Suspend execution on uncaught exceptions</strong>.</p> | {
"question_id": 6290470,
"question_date": "2011-06-09T09:07:52.653Z",
"question_score": 210,
"tags": "java|eclipse|debugging|tomcat",
"answer_id": 6291091,
"answer_date": "2011-06-09T10:01:13.680Z",
"answer_score": 296
} |
Please answer the following Stack Overflow question:
Title: Git clone / pull continually freezing at "Store key in cache?"
<p>I'm attempting to clone a repo from my BitBucket account to my Windows 10 laptop (running GitBash). I've completed all of the steps necessary to connect (set up my SSH key, verified by successfully SSHing [email protected], etc). However, whenever I attempt to clone a repo, the prompt continually hangs up after confirming that I want to cache Bitbucket's key. </p>
<pre><code>User@Laptop MINGW64 /C/Repos
$ git clone [email protected]:mygbid/test.git
Cloning into 'test'...
The server's host key is not cached in the registry. You
have no guarantee that the server is the computer you
think it is.
The server's rsa2 key fingerprint is:
ssh-rsa 2048 97:8c:1b:f2:6f:14:6b:5c:3b:ec:aa:46:46:74:7c:40
If you trust this host, enter "y" to add the key to
PuTTY's cache and carry on connecting.
If you want to carry on connecting just once, without
adding the key to the cache, enter "n".
If you do not trust this host, press Return to abandon the
connection.
Store key in cache? (y/n) y
</code></pre>
<p>No files are cloned, and the result is an empty repo. Trying to initiate a git pull origin master from this repo also asks to cache the key, then hangs with no feedback. Despite not asking for the key to be cached when I do a test SSH, git operations always ask for the key every time before failing.</p>
<p>With no error messages to work with, I'm really at a loss as to what is wrong. I've tried multiple repos, including very small ones, with no success at all.</p> | <p>I had this problem when cloning a repo on Windows 10 too. </p>
<p>I got around it by using the Putty GUI to SSH to the server in question (in your case: bitbucket.org) then clicked 'Yes' when the prompt asks if you want to save the server key to the cache. Running the clone command again then worked for me!</p> | {
"question_id": 33240137,
"question_date": "2015-10-20T15:02:17.957Z",
"question_score": 210,
"tags": "windows|git|ssh|version-control|bitbucket",
"answer_id": 33285412,
"answer_date": "2015-10-22T15:59:38.350Z",
"answer_score": 243
} |
Please answer the following Stack Overflow question:
Title: Git Blame Commit Statistics
<p>How can I "abuse" blame (or some better suited function, and/or in conjunction with shell commands) to give me a statistic of how much lines (of code) are currently in the repository originating from each committer?</p>
<p>Example Output:</p>
<pre><code>Committer 1: 8046 Lines
Committer 2: 4378 Lines
</code></pre> | <h3>Update</h3>
<pre><code>git ls-tree -r -z --name-only HEAD -- */*.c | sed 's/^/.\//' | xargs -0 -n1 git blame \
--line-porcelain HEAD |grep -ae "^author "|sort|uniq -c|sort -nr
</code></pre>
<p>I updated some things on the way.</p>
<p>For convenience, you can also put this into its own command:</p>
<pre><code>#!/bin/bash
# save as i.e.: git-authors and set the executable flag
git ls-tree -r -z --name-only HEAD -- $1 | sed 's/^/.\//' | xargs -0 -n1 git blame \
--line-porcelain HEAD |grep -ae "^author "|sort|uniq -c|sort -nr
</code></pre>
<p>store this somewhere in your path or modify your path and use it like</p>
<ul>
<li><code>git authors '*/*.c' # look for all files recursively ending in .c</code></li>
<li><code>git authors '*/*.[ch]' # look for all files recursively ending in .c or .h</code></li>
<li><code>git authors 'Makefile' # just count lines of authors in the Makefile</code></li>
</ul>
<h2>Original Answer</h2>
<p>While the accepted answer does the job it's very slow.</p>
<pre><code>$ git ls-tree --name-only -z -r HEAD|egrep -z -Z -E '\.(cc|h|cpp|hpp|c|txt)$' \
|xargs -0 -n1 git blame --line-porcelain|grep "^author "|sort|uniq -c|sort -nr
</code></pre>
<p>is almost instantaneous.</p>
<p>To get a list of files currently tracked you can use</p>
<pre><code>git ls-tree --name-only -r HEAD
</code></pre>
<p>This solution avoids calling <code>file</code> to determine the filetype and uses grep to match the wanted extension for performance reasons. If all files should be included, just remove this from the line.</p>
<pre><code>grep -E '\.(cc|h|cpp|hpp|c)$' # for C/C++ files
grep -E '\.py$' # for Python files
</code></pre>
<p>if the files can contain spaces, which are bad for shells you can use:</p>
<pre><code>git ls-tree -z --name-only -r HEAD | egrep -Z -z '\.py'|xargs -0 ... # passes newlines as '\0'
</code></pre>
<p>Give a list of files (through a pipe) one can use xargs to call a command and distribute the arguments. Commands that allow multiple files to be processed obmit the <code>-n1</code>. In this case we call <code>git blame --line-porcelain</code> and for every call we use exactly 1 argument.</p>
<pre><code>xargs -n1 git blame --line-porcelain
</code></pre>
<p>We then filter the output for occurences of "author " sort the list and count duplicate lines by:</p>
<pre><code>grep "^author "|sort|uniq -c|sort -nr
</code></pre>
<h3>Note</h3>
<p>Other answers actually filter out lines that contain only whitespaces.</p>
<pre><code>grep -Pzo "author [^\n]*\n([^\n]*\n){10}[\w]*[^\w]"|grep "author "
</code></pre>
<p>The command above will print authors of lines containing at least one non-whitespace character. You can also use match <code>\w*[^\w#]</code> which will also exclude lines where the first non-whitespace character isn't a <code>#</code> (comment in many scripting languages).</p> | {
"question_id": 4589731,
"question_date": "2011-01-04T00:46:41.113Z",
"question_score": 210,
"tags": "git",
"answer_id": 13687302,
"answer_date": "2012-12-03T16:14:27.800Z",
"answer_score": 178
} |
Please answer the following Stack Overflow question:
Title: Uppercase or lowercase doctype?
<p>When writing the HTML5 doctype what is the correct method?</p>
<pre><code><!DOCTYPE html>
</code></pre>
<p>or</p>
<pre><code><!doctype html>
</code></pre> | <p>In HTML, the DOCTYPE is case insensitive. The following DOCTYPEs are all valid:</p>
<pre><code><!doctype html>
<!DOCTYPE html>
<!DOCTYPE HTML>
<!DoCtYpE hTmL>
</code></pre>
<p>In XML serializations (i.e. XHTML) the DOCTYPE is not required, but if you use it, <code>DOCTYPE</code> should be uppercase:</p>
<pre><code><!DOCTYPE html>
</code></pre>
<p>See <strong><em><a href="http://mathiasbynens.be/notes/xhtml5#doctype">The XML serialization of HTML5, aka ‘XHTML5’</a></em></strong>:</p>
<blockquote>
<p>Note that if you don’t uppercase <code>DOCTYPE</code> in an XHTML document, the XML parser will return a syntax error.</p>
<p>The second part can be written in lowercase (<code>html</code>), uppercase (<code>HTML</code>) or even mixed case (<code>hTmL</code>) — it will still work. However, to conform to the <a href="http://www.w3.org/TR/html-polyglot/#doctype">Polyglot Markup Guidelines for HTML-Compatible XHTML Documents</a>, it should be written in lowercase.</p>
</blockquote> | {
"question_id": 7020961,
"question_date": "2011-08-11T04:49:39.370Z",
"question_score": 210,
"tags": "html|doctype",
"answer_id": 9109157,
"answer_date": "2012-02-02T08:26:50.870Z",
"answer_score": 203
} |
Please answer the following Stack Overflow question:
Title: Code equivalent to the 'let' keyword in chained LINQ extension method calls
<p>Using the C# compilers query comprehension features, you can write code like:</p>
<pre><code>var names = new string[] { "Dog", "Cat", "Giraffe", "Monkey", "Tortoise" };
var result =
from animalName in names
let nameLength = animalName.Length
where nameLength > 3
orderby nameLength
select animalName;
</code></pre>
<p>In the query expression above, the <code>let</code> keyword allows a value to be passed forward to the where and orderby operations without duplicate calls to <code>animalName.Length</code>.</p>
<p>What is the equivalent set of LINQ extension method calls that achieves what the "let" keyword does here?</p> | <p>Let doesn't have its own operation; it piggy-backs off of <code>Select</code>. You can see this if you use "reflector" to pull apart an existing dll.</p>
<p>it will be <em>something</em> like:</p>
<pre><code>var result = names
.Select(animalName => new { nameLength = animalName.Length, animalName})
.Where(x=>x.nameLength > 3)
.OrderBy(x=>x.nameLength)
.Select(x=>x.animalName);
</code></pre> | {
"question_id": 1092687,
"question_date": "2009-07-07T14:31:56.617Z",
"question_score": 210,
"tags": "c#|linq|extension-methods|linq-to-objects",
"answer_id": 1092770,
"answer_date": "2009-07-07T14:46:00.273Z",
"answer_score": 276
} |
Please answer the following Stack Overflow question:
Title: How to go to an error using only the keyboard in Eclipse?
<p>Let's say I have a file with 10 lines and I have a problem with the name of the package (or something) and the cursor is on the last line of the text. </p>
<p>How can I go directly to that line to see what the problem is and what suggestions there are to remove the problem, using a shortcut?</p>
<p>Question: Is there a keyboard-shortcut for this? </p>
<p>Or something like this: </p>
<p><em>Go to the next error</em> and <em>Go to the previous error</em>.</p> | <p>Windows and Linux</p>
<ul>
<li>Go to the next error: <kbd>Ctrl</kbd> + <kbd><strong>.</strong></kbd></li>
<li>Go to the previous error: <kbd>Ctrl</kbd> + <kbd><strong>,</strong></kbd></li>
<li>Show quick fixes: <kbd>Ctrl</kbd> + <kbd>1</kbd></li>
</ul>
<p>Mac</p>
<ul>
<li>Go to the next error: <kbd>Cmd</kbd> + <kbd><strong>.</strong></kbd></li>
<li>Go to the previous error: <kbd>Cmd</kbd> + <kbd><strong>,</strong></kbd></li>
<li>Show quick fixes: <kbd>Cmd</kbd> + <kbd>1</kbd></li>
</ul> | {
"question_id": 1832183,
"question_date": "2009-12-02T10:57:20.653Z",
"question_score": 210,
"tags": "eclipse|keyboard-shortcuts",
"answer_id": 1832328,
"answer_date": "2009-12-02T11:24:49.863Z",
"answer_score": 332
} |
Please answer the following Stack Overflow question:
Title: Does a lambda expression create an object on the heap every time it's executed?
<p>When I iterate over a collection using the new syntactic sugar of Java 8, such as</p>
<pre><code>myStream.forEach(item -> {
// do something useful
});
</code></pre>
<p>Isn't this equivalent to the 'old syntax' snippet below?</p>
<pre><code>myStream.forEach(new Consumer<Item>() {
@Override
public void accept(Item item) {
// do something useful
}
});
</code></pre>
<p>Does this mean a new anonymous <code>Consumer</code> object is created on the heap every time I iterate over a collection? How much heap space does this take? What performance implications does it have? Does it mean I should rather use the old style for loops when iterating over large multi-level data structures?</p> | <p>It is equivalent but not identical. Simply said, if a lambda expression does not capture values, it will be a singleton that is re-used on every invocation.</p>
<p>The behavior is not exactly specified. The JVM is given big freedom on how to implement it. Currently, Oracle’s JVM creates (at least) one instance per lambda expression (i.e. doesn’t share instance between different identical expressions) but creates singletons for all expressions which don’t capture values.</p>
<p>You may read <a href="https://stackoverflow.com/a/23991339/2711488">this answer</a> for more details. There, I not only gave a more detailed description but also testing code to observe the current behavior.</p>
<hr />
<p>This is covered by The Java® Language Specification, chapter “<a href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.27.4" rel="noreferrer">15.27.4. Run-time Evaluation of Lambda Expressions</a>”</p>
<p>Summarized:</p>
<blockquote>
<p>These rules are meant to offer flexibility to implementations of the Java programming language, in that:</p>
<ul>
<li><p>A new object need not be allocated on every evaluation.</p>
</li>
<li><p>Objects produced by different lambda expressions need not belong to different classes (if the bodies are identical, for example).</p>
</li>
<li><p>Every object produced by evaluation need not belong to the same class (captured local variables might be inlined, for example).</p>
</li>
<li><p>If an "existing instance" is available, it need not have been created at a previous lambda evaluation (it might have been allocated during the enclosing class's initialization, for example).</p>
</li>
</ul>
</blockquote> | {
"question_id": 27524445,
"question_date": "2014-12-17T11:20:59.313Z",
"question_score": 210,
"tags": "java|lambda|java-8",
"answer_id": 27524543,
"answer_date": "2014-12-17T11:27:20.100Z",
"answer_score": 186
} |
Please answer the following Stack Overflow question:
Title: How does this CSS produce a circle?
<p>This is the CSS:</p>
<pre><code>div {
width: 0;
height: 0;
border: 180px solid red;
border-radius: 180px;
}
</code></pre>
<p>How does it produce the circle below?</p>
<p><img src="https://i.stack.imgur.com/yTmLN.jpg" alt="Enter image description here"></p>
<p>Suppose, if a rectangle width is 180 pixels and height is 180 pixels then it would appear like this: </p>
<p><img src="https://i.stack.imgur.com/nvK6a.jpg" alt="Enter image description here"></p>
<p>After applying border-radius 30 pixels it would appear like this:</p>
<p><img src="https://i.stack.imgur.com/xEutT.jpg" alt="Enter image description here"></p>
<p>The rectangle is becoming smaller, that is, almost going to disappear if the radius size increases.</p>
<p>So, how does a border of 180 pixels with <code>height/width-> 0px</code> become a circle with a radius of 180 pixels?</p> | <blockquote>
<p>How does a border of 180 pixels with height/width-> 0px become a circle with a radius of 180 pixels?</p>
</blockquote>
<p>Let's reformulate that into two questions:</p>
<h2>Where do <code>width</code> and <code>height</code> actually apply?</h2>
<p>Let's have a look at the areas of a typical box (<a href="http://www.w3.org/TR/2012/CR-css3-background-20120724/#corners" rel="noreferrer">source</a>):</p>
<p><img src="https://i.stack.imgur.com/9knOE.png" alt="W3C: Areas of a typical box"></p>
<p>The <code>height</code> and <code>width</code> apply only on content, if the correct box model is being used (no quirks mode, no old Internet Explorer).</p>
<h2>Where does <code>border-radius</code> apply?</h2>
<p>The <code>border-radius</code> applies on the border-edge. If there is neither padding nor border it will directly affect your content edge, which results in your third example.</p>
<h2>What does this mean for our border-radius/circle?</h2>
<p>This means that your CSS rules result in a box that only consists of a border. Your rules state that this border should have a maximum width of 180 pixels on every side, while on the other hand it should have a maximum radius of the same size:</p>
<p><img src="https://i.stack.imgur.com/CnjBH.png" alt="Example image"></p>
<p>In the picture, the <em>actual content</em> of your element (the little black dot) is really non-existent. If you didn't apply any <code>border-radius</code> you would end up with the green box. The <code>border-radius</code> gives you the blue circle.</p>
<p>It gets easier to understand if you apply the <code>border-radius</code> <a href="http://jsfiddle.net/9qvgG/" rel="noreferrer">only to two corners</a>:</p>
<pre><code>#silly-circle{
width:0; height:0;
border: 180px solid red;
border-top-left-radius: 180px;
border-top-right-radius: 180px;
}
</code></pre>
<p><img src="https://i.stack.imgur.com/WU9aP.png" alt="Border only applied on two corners"></p>
<p>Since in your example the size and radius for all corners/borders are equal you get a circle.</p>
<h2>Further resources</h2>
<h3>References</h3>
<ul>
<li>W3C: <a href="http://www.w3.org/TR/2012/CR-css3-background-20120724/" rel="noreferrer">CSS Backgrounds and Borders Module Level 3</a> (esp. <a href="http://www.w3.org/TR/2012/CR-css3-background-20120724/#corners" rel="noreferrer">5. Rounded Corners</a>)</li>
</ul>
<h3>Demonstrations</h3>
<ul>
<li>Please open the demo below, which shows how the <code>border-radius</code> affects the border (think of the inner blue box as the content box, the inner black border as the padding border, the empty space as the padding and the giant red border as the, well, border). Intersections between the inner box and the red border would usually affect the content edge.</li>
</ul>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var all = $('#TopLeft, #TopRight, #BottomRight, #BottomLeft');
all.on('change keyup', function() {
$('#box').css('border' + this.id + 'Radius', (this.value || 0) + "%");
$('#' + this.id + 'Text').val(this.value + "%");
});
$('#total').on('change keyup', function() {
$('#box').css('borderRadius', (this.value || 0) + "%");
$('#' + this.id + 'Text').val(this.value + "%");
all.val(this.value);
all.each(function(){$('#' + this.id + 'Text').val(this.value + "%");})
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>#box {
margin:auto;
width: 32px;
height: 32px;
border: 100px solid red;
padding: 32px;
transition: border-radius 1s ease;
-moz-transition: border-radius 1s ease;
-webkit-transition: border-radius 1s ease;
-o-transition: border-radius 1s ease;
-ms-transition: border-radius 1s ease;
}
#chooser{margin:auto;}
#innerBox {
width: 100%;
height: 100%;
border: 1px solid blue;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="box">
<div id="innerBox"></div>
</div>
<table id="chooser">
<tr>
<td><label for="total">Total</label></td>
<td><input id="total" value="0" type="range" min="0" max="100" step="1" /></td>
<td><input readonly id="totalText" value="0" type="text" /></td>
</tr>
<tr>
<td><label for="TopLeft">Top-Left</label></td>
<td><input id="TopLeft" value="0" type="range" min="0" max="100" step="1" /></td>
<td><input readonly id="TopLeftText" value="0" type="text" /></td>
</tr>
<tr>
<td><label for="TopRight">Top right</label></td>
<td><input id="TopRight" value="0" type="range" min="0" max="100" step="1" /></td>
<td><input readonly id="TopRightText" value="0" type="text" /></td>
</tr>
<tr>
<td><label for="BottomRight">Bottom right</label></td>
<td><input id="BottomRight" value="0" type="range" min="0" max="100" step="1" /></td>
<td><input readonly id="BottomRightText" value="0" type="text" /></td>
</tr>
<tr>
<td><label for="BottomLeft">Bottom left</label></td>
<td><input id="BottomLeft" value="0" type="range" min="0" max="100" step="1" /></td>
<td><input readonly id="BottomLeftText" value="0" type="text" /></td>
</tr>
<caption><code>border-radius</code> values. All values are in percent.</caption>
</table>
<p>This demo uses a box with a <code>width/height</code> of 32px, a <code>padding</code> of 32px, and a <code>border</code> of 100px.</p></code></pre>
</div>
</div>
</p> | {
"question_id": 16189208,
"question_date": "2013-04-24T10:08:31.443Z",
"question_score": 210,
"tags": "html|css|css-shapes",
"answer_id": 16189351,
"answer_date": "2013-04-24T10:15:11.453Z",
"answer_score": 374
} |
Please answer the following Stack Overflow question:
Title: Can I make a pull request on a gist on GitHub?
<p>Can I make a pull request on some else's gist on GitHub?</p>
<p>I'm aware of the fork, clone and commit workflow for a gist I own. I'd like to know if I can request to update someone else's gist with my fork.</p> | <p>You cannot currently open a pull request on a Gist.</p>
<p>You can comment though on the Gist and ask the author to update the Gist from your fork.</p> | {
"question_id": 8758612,
"question_date": "2012-01-06T13:34:30.467Z",
"question_score": 210,
"tags": "git|github|gist|pull-request",
"answer_id": 8767309,
"answer_date": "2012-01-07T04:16:56.237Z",
"answer_score": 139
} |
Please answer the following Stack Overflow question:
Title: Valid, but worthless syntax in switch-case?
<p>Through a little typo, I accidentally found this construct:</p>
<pre><code>int main(void) {
char foo = 'c';
switch(foo)
{
printf("Cant Touch This\n"); // This line is Unreachable
case 'a': printf("A\n"); break;
case 'b': printf("B\n"); break;
case 'c': printf("C\n"); break;
case 'd': printf("D\n"); break;
}
return 0;
}
</code></pre>
<p>It seems that the <code>printf</code> at the top of the <code>switch</code> statement is valid, but also completely unreachable.</p>
<p>I got a clean compile, without even a warning about unreachable code, but this seems pointless.</p>
<p>Should a compiler flag this as unreachable code?<br>
Does this serve any purpose at all?</p> | <p>Perhaps not the most useful, but not <em>completely</em> worthless. You may use it to declare a local variable available within <code>switch</code> scope.</p>
<pre><code>switch (foo)
{
int i;
case 0:
i = 0;
//....
case 1:
i = 1;
//....
}
</code></pre>
<p>The standard (<code>N1579 6.8.4.2/7</code>) has the following sample:</p>
<blockquote>
<p>EXAMPLE In the artificial program fragment</p>
<pre><code>switch (expr)
{
int i = 4;
f(i);
case 0:
i = 17;
/* falls through into default code */
default:
printf("%d\n", i);
}
</code></pre>
<p>the object whose identifier is <code>i</code> exists with automatic storage duration (within the block) but is never
initialized, and thus if the controlling expression has a nonzero value, the call to the <code>printf</code> function will
access an indeterminate value. Similarly, the call to the function <code>f</code> cannot be reached.</p>
</blockquote>
<p><strong>P.S.</strong> BTW, the sample is not valid C++ code. In that case (<code>N4140 6.7/3</code>, emphasis mine):</p>
<blockquote>
<p>A program that jumps<sup>90</sup> from a point where a variable with automatic storage duration is not in scope to a
point where it is in scope is ill-formed <strong><em>unless the variable has scalar type</em></strong>, class type with a trivial default
constructor and a trivial destructor, a cv-qualified version of one of these types, or an array of one of the
preceding types <strong><em>and is declared without an initializer</em></strong> (8.5).</p>
<hr>
<p><sup>90) The transfer from the condition of a <code>switch</code> statement to a case label is considered a jump in this respect.</sup></p>
</blockquote>
<p>So replacing <code>int i = 4;</code> with <code>int i;</code> makes it a valid C++.</p> | {
"question_id": 41727415,
"question_date": "2017-01-18T19:02:57.783Z",
"question_score": 210,
"tags": "c|switch-statement|language-lawyer",
"answer_id": 41727535,
"answer_date": "2017-01-18T19:09:45.263Z",
"answer_score": 230
} |
Please answer the following Stack Overflow question:
Title: What is a NullPointerException, and how do I fix it?
<p>What are Null Pointer Exceptions (<code>java.lang.NullPointerException</code>) and what causes them?</p>
<p>What methods/tools can be used to determine the cause so that you stop the exception from causing the program to terminate prematurely?</p> | <p>There are two overarching types of variables in Java:</p>
<ol>
<li><p><em>Primitives</em>: variables that contain data. If you want to manipulate the data in a primitive variable you can manipulate that variable directly. By convention primitive types start with a lowercase letter. For example variables of type <code>int</code> or <code>char</code> are primitives.</p>
</li>
<li><p><em>References</em>: variables that contain the memory address of an <code>Object</code> i.e. variables that <em>refer</em> to an <code>Object</code>. If you want to manipulate the <code>Object</code> that a reference variable refers to you must <em>dereference</em> it. Dereferencing usually entails using <code>.</code> to access a method or field, or using <code>[</code> to index an array. By convention reference types are usually denoted with a type that starts in uppercase. For example variables of type <code>Object</code> are references.</p>
</li>
</ol>
<p>Consider the following code where you declare a variable of <em>primitive</em> type <code>int</code> and don't initialize it:</p>
<pre class="lang-java prettyprint-override"><code>int x;
int y = x + x;
</code></pre>
<p>These two lines will crash the program because no value is specified for <code>x</code> and we are trying to use <code>x</code>'s value to specify <code>y</code>. All primitives have to be initialized to a usable value before they are manipulated.</p>
<p>Now here is where things get interesting. <em>Reference</em> variables can be set to <code>null</code> which means "<strong>I am referencing <em>nothing</em></strong>". You can get a <code>null</code> value in a reference variable if you explicitly set it that way, or a reference variable is uninitialized and the compiler does not catch it (Java will automatically set the variable to <code>null</code>).</p>
<p>If a reference variable is set to null either explicitly by you or through Java automatically, and you attempt to <em>dereference</em> it you get a <code>NullPointerException</code>.</p>
<p>The <code>NullPointerException</code> (NPE) typically occurs when you declare a variable but did not create an object and assign it to the variable before trying to use the contents of the variable. So you have a reference to something that does not actually exist.</p>
<p>Take the following code:</p>
<pre><code>Integer num;
num = new Integer(10);
</code></pre>
<p>The first line declares a variable named <code>num</code>, but it does not actually contain a reference value yet. Since you have not yet said what to point to, Java sets it to <code>null</code>.</p>
<p>In the second line, the <code>new</code> keyword is used to instantiate (or create) an object of type <code>Integer</code>, and the reference variable <code>num</code> is assigned to that <code>Integer</code> object.</p>
<p>If you attempt to dereference <code>num</code> <em>before</em> creating the object you get a <code>NullPointerException</code>. In the most trivial cases, the compiler will catch the problem and let you know that "<code>num may not have been initialized</code>," but sometimes you may write code that does not directly create the object.</p>
<p>For instance, you may have a method as follows:</p>
<pre><code>public void doSomething(SomeObject obj) {
// Do something to obj, assumes obj is not null
obj.myMethod();
}
</code></pre>
<p>In which case, you are not creating the object <code>obj</code>, but rather assuming that it was created before the <code>doSomething()</code> method was called. Note, it is possible to call the method like this:</p>
<pre><code>doSomething(null);
</code></pre>
<p>In which case, <code>obj</code> is <code>null</code>, and the statement <code>obj.myMethod()</code> will throw a <code>NullPointerException</code>.</p>
<p>If the method is intended to do something to the passed-in object as the above method does, it is appropriate to throw the <code>NullPointerException</code> because it's a programmer error and the programmer will need that information for debugging purposes.</p>
<p>In addition to <code>NullPointerException</code>s thrown as a result of the method's logic, you can also check the method arguments for <code>null</code> values and throw NPEs explicitly by adding something like the following near the beginning of a method:</p>
<pre><code>// Throws an NPE with a custom error message if obj is null
Objects.requireNonNull(obj, "obj must not be null");
</code></pre>
<p>Note that it's helpful to say in your error message clearly <em>which</em> object cannot be <code>null</code>. The advantage of validating this is that 1) you can return your own clearer error messages and 2) for the rest of the method you know that unless <code>obj</code> is reassigned, it is not null and can be dereferenced safely.</p>
<p>Alternatively, there may be cases where the purpose of the method is not solely to operate on the passed in object, and therefore a null parameter may be acceptable. In this case, you would need to check for a <strong>null parameter</strong> and behave differently. You should also explain this in the documentation. For example, <code>doSomething()</code> could be written as:</p>
<pre><code>/**
* @param obj An optional foo for ____. May be null, in which case
* the result will be ____.
*/
public void doSomething(SomeObject obj) {
if(obj == null) {
// Do something
} else {
// Do something else
}
}
</code></pre>
<p>Finally, <a href="https://stackoverflow.com/q/3988788/2775450">How to pinpoint the exception & cause using Stack Trace</a></p>
<blockquote>
<p>What methods/tools can be used to determine the cause so that you stop
the exception from causing the program to terminate prematurely?</p>
</blockquote>
<p>Sonar with find bugs can detect NPE.
<a href="https://stackoverflow.com/questions/20899931/can-sonar-catch-null-pointer-exceptions-caused-by-jvm-dynamically">Can sonar catch null pointer exceptions caused by JVM Dynamically</a></p>
<p>Now Java 14 has added a new language feature to show the root cause of NullPointerException. This language feature has been part of SAP commercial JVM since 2006.</p>
<p>In Java 14, the following is a sample NullPointerException Exception message:</p>
<blockquote>
<p>in thread "main" java.lang.NullPointerException: Cannot invoke "java.util.List.size()" because "list" is null</p>
</blockquote>
<h3>List of situations that cause a <code>NullPointerException</code> to occur</h3>
<p>Here are all the situations in which a <code>NullPointerException</code> occurs, that are directly* mentioned by the Java Language Specification:</p>
<ul>
<li>Accessing (i.e. getting or setting) an <em>instance</em> field of a null reference. (static fields don't count!)</li>
<li>Calling an <em>instance</em> method of a null reference. (static methods don't count!)</li>
<li><code>throw null;</code></li>
<li>Accessing elements of a null array.</li>
<li>Synchronising on null - <code>synchronized (someNullReference) { ... }</code></li>
<li>Any integer/floating point operator can throw a <code>NullPointerException</code> if one of its operands is a boxed null reference</li>
<li>An unboxing conversion throws a <code>NullPointerException</code> if the boxed value is null.</li>
<li>Calling <code>super</code> on a null reference throws a <code>NullPointerException</code>. If you are confused, this is talking about qualified superclass constructor invocations:</li>
</ul>
<pre><code>class Outer {
class Inner {}
}
class ChildOfInner extends Outer.Inner {
ChildOfInner(Outer o) {
o.super(); // if o is null, NPE gets thrown
}
}
</code></pre>
<ul>
<li><p>Using a <code>for (element : iterable)</code> loop to loop through a null collection/array.</p>
</li>
<li><p><code>switch (foo) { ... }</code> (whether its an expression or statement) can throw a <code>NullPointerException</code> when <code>foo</code> is null.</p>
</li>
<li><p><code>foo.new SomeInnerClass()</code> throws a <code>NullPointerException</code> when <code>foo</code> is null.</p>
</li>
<li><p>Method references of the form <code>name1::name2</code> or <code>primaryExpression::name</code> throws a <code>NullPointerException</code> when evaluated when <code>name1</code> or <code>primaryExpression</code> evaluates to null.</p>
<p>a note from the JLS here says that, <code>someInstance.someStaticMethod()</code> doesn't throw an NPE, because <code>someStaticMethod</code> is static, but <code>someInstance::someStaticMethod</code> still throw an NPE!</p>
</li>
</ul>
<p><sub>* Note that the JLS probably also says a lot about NPEs <em>indirectly</em>.</sub></p> | {
"question_id": 218384,
"question_date": "2008-10-20T13:18:09.913Z",
"question_score": 209,
"tags": "java|nullpointerexception",
"answer_id": 218510,
"answer_date": "2008-10-20T13:54:24.253Z",
"answer_score": 4118
} |
Please answer the following Stack Overflow question:
Title: C++ IDE for Linux?
<p>I want to expand my programming horizons to Linux. A good, dependable basic toolset is important, and what is more basic than an IDE?</p>
<p>I could find these SO topics:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/2756/lightweight-ide-for-linux">Lightweight IDE for linux</a> and</li>
<li><a href="https://stackoverflow.com/questions/17228/what-tools-do-you-use-to-develop-c-applications-on-linux">What tools do you use to develop
C++ applications on Linux?</a></li>
</ul>
<p>I'm not looking for a <em>lightweight</em> IDE. If an IDE is worth the money, then I will pay for it, so it need not be free.</p>
<p>My question, then:</p>
<blockquote>
<p><em>What good, C++ programming IDE is available for Linux?</em></p>
</blockquote>
<p>The minimums are fairly standard: syntax highlighting, code completion (like <a href="http://en.wikipedia.org/wiki/IntelliSense" rel="nofollow noreferrer">intellisense</a> or its Eclipse counterpart) and integrated debugging (e.g., basic
breakpoints).</p>
<p>I have searched for it myself, but there are so many that it is almost impossible to separate the good from the bads by hand, especially for someone like me who has little C++ coding experience in Linux. I know that <a href="http://www.eclipse.org/cdt/" rel="nofollow noreferrer">Eclipse supports C++</a>, and I really like that IDE for Java, but is it any good for C++ and is there something better?</p>
<p>The second post actually has some good suggestions, but what I am missing is what exactly makes the sugested IDE so good for the user, what are its (dis)advantages?</p>
<p>Maybe my question should therefore be:</p>
<blockquote>
<p><em>What IDE do you propose (given your experiences), and why?</em></p>
</blockquote> | <h2>Initially: confusion</h2>
<p>When originally writing this answer, I had recently made the switch from Visual Studio (with years of experience) to Linux and the first thing I did was try to find a reasonable IDE. At the time this was impossible: no good IDE existed.</p>
<h2>Epiphany: UNIX is an IDE. <em>All of it.</em><sup>1</sup></h2>
<p>And then I realised that the IDE in Linux is the command line with its tools:</p>
<ul>
<li>First you set up your shell
<ul>
<li>Bash, in my case, but many people prefer</li>
<li><a href="https://fishshell.com/" rel="noreferrer">fish</a> or</li>
<li><a href="https://github.com/robbyrussell/oh-my-zsh" rel="noreferrer">(Oh My) Zsh</a>;</li>
</ul></li>
<li>and your editor; pick your poison — both are state of the art:
<ul>
<li><a href="https://neovim.io/" rel="noreferrer">Neovim</a><sup>2</sup> or</li>
<li><a href="https://www.gnu.org/software/emacs/" rel="noreferrer">Emacs</a>.</li>
</ul></li>
</ul>
<p>Depending on your needs, you will then have to install and configure several plugins to make the editor work nicely (that’s the one annoying part). For example, most programmers on Vim will benefit from the <a href="https://valloric.github.io/YouCompleteMe/" rel="noreferrer">YouCompleteMe</a> plugin for smart autocompletion.</p>
<p>Once that’s done, the shell is your command interface to interact with the various tools — Debuggers (gdb), Profilers (gprof, valgrind), etc. You set up your project/build environment using <a href="https://www.gnu.org/software/make/" rel="noreferrer">Make</a>, <a href="https://bitbucket.org/snakemake/snakemake/wiki/Home" rel="noreferrer">CMake</a>, <a href="https://bitbucket.org/snakemake/snakemake/wiki/Home" rel="noreferrer">SnakeMake</a> or any of the various alternatives. And you manage your code with a version control system (most people use <a href="https://git-scm.com/" rel="noreferrer">Git</a>). You also use <a href="https://tmux.github.io/" rel="noreferrer">tmux</a> (previously also screen) to multiplex (= think multiple windows/tabs/panels) and persist your terminal session.</p>
<p>The point is that, thanks to the shell and a few tool writing conventions, these all <em>integrate with each other</em>. And that way <strong>the Linux shell is a truly integrated development environment</strong>, completely on par with other modern IDEs. (This doesn’t mean that individual IDEs don’t have features that the command line may be lacking, but the inverse is also true.)</p>
<h2>To each their own</h2>
<p>I cannot overstate how well the above workflow functions once you’ve gotten into the habit. But some people simply prefer graphical editors, and in the years since this answer was originally written, Linux has gained a suite of excellent graphical IDEs for several different programming languages (but not, as far as I’m aware, for C++). Do give them a try even if — like me — you end up not using them. Here’s just a small and biased selection:</p>
<ul>
<li>For Python development, there’s <a href="https://www.jetbrains.com/pycharm/" rel="noreferrer">PyCharm</a></li>
<li>For R, there’s <a href="https://www.rstudio.com/" rel="noreferrer">RStudio</a></li>
<li>For JavaScript and TypeScript, there’s <a href="https://code.visualstudio.com/" rel="noreferrer">Visual Studio Code</a> (which is also a good all-round editor)</li>
<li>And finally, many people love the <a href="https://www.sublimetext.com/" rel="noreferrer">Sublime Text editor</a> for general code editing.</li>
</ul>
<p>Keep in mind that this list is far from complete.</p>
<hr>
<p><sup>1</sup> I stole that title from dsm’s comment.</p>
<p><sup>2</sup> I used to refer to Vim here. And while plain Vim is still more than capable, Neovim is a promising restart, and it’s modernised a few old warts.</p> | {
"question_id": 24109,
"question_date": "2008-08-23T09:52:59.517Z",
"question_score": 209,
"tags": "c++|linux|ide",
"answer_id": 24119,
"answer_date": "2008-08-23T10:06:09.157Z",
"answer_score": 259
} |
Please answer the following Stack Overflow question:
Title: Convert dd-mm-yyyy string to date
<p>i am trying to convert a string in the format dd-mm-yyyy into a date object in JavaScript using the following:</p>
<pre><code> var from = $("#datepicker").val();
var to = $("#datepickertwo").val();
var f = new Date(from);
var t = new Date(to);
</code></pre>
<p><code>("#datepicker").val()</code> contains a date in the format dd-mm-yyyy.
When I do the following, I get "Invalid Date":</p>
<pre><code>alert(f);
</code></pre>
<p>Is this because of the '-' symbol? How can I overcome this?</p> | <p><strong>Split on "-"</strong></p>
<p>Parse the string into the parts you need:</p>
<pre><code>var from = $("#datepicker").val().split("-")
var f = new Date(from[2], from[1] - 1, from[0])
</code></pre>
<p><strong>Use regex</strong></p>
<pre><code>var date = new Date("15-05-2018".replace( /(\d{2})-(\d{2})-(\d{4})/, "$2/$1/$3"))
</code></pre>
<p><strong>Why not use regex?</strong></p>
<p>Because you know you'll be working on a string made up of three parts, separated by hyphens.</p>
<p>However, if you were looking for that same string within another string, regex would be the way to go.</p>
<p><strong>Reuse</strong></p>
<p>Because you're doing this more than once in your sample code, and maybe elsewhere in your code base, wrap it up in a function:</p>
<pre><code>function toDate(dateStr) {
var parts = dateStr.split("-")
return new Date(parts[2], parts[1] - 1, parts[0])
}
</code></pre>
<p>Using as:</p>
<pre><code>var from = $("#datepicker").val()
var to = $("#datepickertwo").val()
var f = toDate(from)
var t = toDate(to)
</code></pre>
<p>Or if you don't mind jQuery in your function:</p>
<pre><code>function toDate(selector) {
var from = $(selector).val().split("-")
return new Date(from[2], from[1] - 1, from[0])
}
</code></pre>
<p>Using as:</p>
<pre><code>var f = toDate("#datepicker")
var t = toDate("#datepickertwo")
</code></pre>
<p><strong>Modern JavaScript</strong></p>
<p>If you're able to use more modern JS, array destructuring is a nice touch also:</p>
<pre><code>const toDate = (dateStr) => {
const [day, month, year] = dateStr.split("-")
return new Date(year, month - 1, day)
}
</code></pre> | {
"question_id": 7151543,
"question_date": "2011-08-22T18:01:27.230Z",
"question_score": 209,
"tags": "javascript|date",
"answer_id": 7151607,
"answer_date": "2011-08-22T18:06:54.717Z",
"answer_score": 352
} |
Please answer the following Stack Overflow question:
Title: Regular expression to match standard 10 digit phone number
<p>I want to write a regular expression for a standard US type phone number that supports the following formats:</p>
<pre><code>###-###-####
(###) ###-####
### ### ####
###.###.####
</code></pre>
<p>where # means any number. So far I came up with the following expressions</p>
<pre><code>^[1-9]\d{2}-\d{3}-\d{4}
^\(\d{3}\)\s\d{3}-\d{4}
^[1-9]\d{2}\s\d{3}\s\d{4}
^[1-9]\d{2}\.\d{3}\.\d{4}
</code></pre>
<p>respectively. I am not quite sure if the last one is correct for the dotted check. I also want to know if there is any way I could write a single expression instead of the 4 different ones that cater to the different formats I mentioned. If so, I am not sure how do I do that. And also how do I modify the expression/expressions so that I can also include a condition to support the area code as optional component. Something like</p>
<pre><code>+1 ### ### ####
</code></pre>
<p>where +1 is the area code and it is optional.</p> | <pre><code>^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}$
</code></pre>
<p>Matches the following</p>
<pre><code>123-456-7890
(123) 456-7890
123 456 7890
123.456.7890
+91 (123) 456-7890
</code></pre>
<p>If you do not want a match on non-US numbers use</p>
<pre><code>^(\+0?1\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}$
</code></pre>
<p><strong><em>Update :</em></strong><br>
As noticed by user Simon Weaver below, if you are also interested in matching on unformatted numbers just make the separator character class optional as <code>[\s.-]?</code></p>
<pre><code>^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$
</code></pre> | {
"question_id": 16699007,
"question_date": "2013-05-22T18:21:42.377Z",
"question_score": 209,
"tags": "regex",
"answer_id": 16699507,
"answer_date": "2013-05-22T18:52:14.500Z",
"answer_score": 335
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.