id
int64 4
73.8M
| title
stringlengths 10
150
| body
stringlengths 17
50.8k
| accepted_answer_id
int64 7
73.8M
| answer_count
int64 1
182
| comment_count
int64 0
89
| community_owned_date
stringlengths 23
27
⌀ | creation_date
stringlengths 23
27
| favorite_count
int64 0
11.6k
⌀ | last_activity_date
stringlengths 23
27
| last_edit_date
stringlengths 23
27
⌀ | last_editor_display_name
stringlengths 2
29
⌀ | last_editor_user_id
int64 -1
20M
⌀ | owner_display_name
stringlengths 1
29
⌀ | owner_user_id
int64 1
20M
⌀ | parent_id
null | post_type_id
int64 1
1
| score
int64 -146
26.6k
| tags
stringlengths 1
125
| view_count
int64 122
11.6M
| answer_body
stringlengths 19
51k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
23,995,040 | Write to multiple outputs by key Spark - one Spark job | <p>How can you write to multiple outputs dependent on the key using Spark in a single Job.</p>
<p>Related: <a href="https://stackoverflow.com/questions/23994383/write-to-multiple-outputs-by-key-scalding-hadoop-one-mapreduce-job/">Write to multiple outputs by key Scalding Hadoop, one MapReduce Job</a></p>
<p>E.g.</p>
<pre><code>sc.makeRDD(Seq((1, "a"), (1, "b"), (2, "c")))
.writeAsMultiple(prefix, compressionCodecOption)
</code></pre>
<p>would ensure <code>cat prefix/1</code> is</p>
<pre><code>a
b
</code></pre>
<p>and <code>cat prefix/2</code> would be</p>
<pre><code>c
</code></pre>
<p>EDIT: I've recently added a new answer that includes full imports, pimp and compression codec, see <a href="https://stackoverflow.com/a/46118044/1586965">https://stackoverflow.com/a/46118044/1586965</a>, which may be helpful in addition to the earlier answers.</p> | 46,118,044 | 10 | 4 | null | 2014-06-02 12:54:11.997 UTC | 62 | 2018-12-15 21:03:19.97 UTC | 2018-12-15 21:03:19.97 UTC | null | 111,575 | null | 1,586,965 | null | 1 | 67 | scala|hadoop|output|hdfs|apache-spark | 82,175 | <p>This includes the codec as requested, necessary imports, and pimp as requested.</p>
<pre><code>import org.apache.spark.rdd.RDD
import org.apache.spark.sql.SQLContext
// TODO Need a macro to generate for each Tuple length, or perhaps can use shapeless
implicit class PimpedRDD[T1, T2](rdd: RDD[(T1, T2)]) {
def writeAsMultiple(prefix: String, codec: String,
keyName: String = "key")
(implicit sqlContext: SQLContext): Unit = {
import sqlContext.implicits._
rdd.toDF(keyName, "_2").write.partitionBy(keyName)
.format("text").option("codec", codec).save(prefix)
}
}
val myRdd = sc.makeRDD(Seq((1, "a"), (1, "b"), (2, "c")))
myRdd.writeAsMultiple("prefix", "org.apache.hadoop.io.compress.GzipCodec")
</code></pre>
<p>One subtle difference to the OP is that it will prefix <code><keyName>=</code> to the directory names. E.g.</p>
<pre><code>myRdd.writeAsMultiple("prefix", "org.apache.hadoop.io.compress.GzipCodec")
</code></pre>
<p>Would give:</p>
<pre><code>prefix/key=1/part-00000
prefix/key=2/part-00000
</code></pre>
<p>where <code>prefix/my_number=1/part-00000</code> would contain the lines <code>a</code> and <code>b</code>, and <code>prefix/my_number=2/part-00000</code> would contain the line <code>c</code>.</p>
<p>And</p>
<pre><code>myRdd.writeAsMultiple("prefix", "org.apache.hadoop.io.compress.GzipCodec", "foo")
</code></pre>
<p>Would give:</p>
<pre><code>prefix/foo=1/part-00000
prefix/foo=2/part-00000
</code></pre>
<p>It should be clear how to edit for <code>parquet</code>. </p>
<p>Finally below is an example for <code>Dataset</code>, which is perhaps nicer that using Tuples.</p>
<pre><code>implicit class PimpedDataset[T](dataset: Dataset[T]) {
def writeAsMultiple(prefix: String, codec: String, field: String): Unit = {
dataset.write.partitionBy(field)
.format("text").option("codec", codec).save(prefix)
}
}
</code></pre> |
3,668,648 | Using NServiceBus with Asp.Net MVC 2 | <p>Is there a way to using NServiceBus with Asp.Net MVC 2? I want to send a request message from a Asp.Net MVC2 Application to a Service, which handle the message and reply with a response message. is there a way to do this clearly?</p> | 3,673,664 | 3 | 1 | null | 2010-09-08 14:17:58.307 UTC | 10 | 2014-04-15 07:42:48.903 UTC | null | null | null | null | 429,659 | null | 1 | 7 | c#|asp.net-mvc-2|nservicebus | 2,887 | <p>If you <em>really</em> want to do this, here's how:</p>
<pre><code>var sync = Bus.Send<SomeMessage>(/*data*/)
.Register((AsyncCallback)delegate(IAsyncResult ar) {
var result = ar.AsyncState as CompletionResult;
// do something with result.Messages
},
null
);
sync.AsyncWaitHandle.WaitOne(/*timeout*/);
</code></pre> |
3,573,872 | How to find out if a sentence is a question (interrogative)? | <p>Is there an open source Java library/algorithm for finding if a particular piece of text is a question or not?
<br/>
I am working on a question answering system that needs to analyze if the text input by user is a question.
<br/>
I think the problem can probably be solved by using opensource NLP libraries but its obviously more complicated than simple part of speech tagging. So if someone can instead tell the algorithm for it by using an existing opensource NLP library, that would be good too.
<br/>
Also let me know if you know a library/toolkit that uses data mining to solve this problem. Although it will be difficult to get sufficient data for training purposes, I will be able to use stack exchange data for training.</p> | 3,736,630 | 3 | 8 | null | 2010-08-26 09:41:17.743 UTC | 11 | 2010-12-21 18:10:36.34 UTC | 2010-12-09 16:04:32.4 UTC | null | 414,282 | null | 414,282 | null | 1 | 23 | java|algorithm|nlp|data-mining|text-processing | 8,474 | <p>In a syntactic parse of a question, the correct structure will be in the form of:</p>
<pre><code>(SBARQ (WH+ (W+) ...)
(SQ ...*
(V+) ...*)
(?))
</code></pre>
<p>So, using anyone of the syntactic parsers available, a tree with an SBARQ node having an embedded SQ (optionally) will be an indicator the input is a question. The WH+ node (WHNP/WHADVP/WHADJP) contains the question stem (who/what/when/where/why/how) and the SQ holds the inverted phrase.</p>
<p>i.e.: </p>
<pre><code>(SBARQ
(WHNP
(WP What))
(SQ
(VBZ is)
(NP
(DT the)
(NN question)))
(. ?))
</code></pre>
<p>Of course, having a lot of preceeding clauses will cause errors in the parse (that can be worked around), as will really poorly-written questions. For example, the title of this post "How to find out if a sentence is a question?" will have an SBARQ, but not an SQ.</p> |
11,147,100 | error BC30456: '[Method]' is not a member of 'ASP.[CodeBehind]_aspx' | <p>Pretty simple question. I'm quite certain I have the Class, method, codebehind, etc linked properly. Lot's of posts online say that this has something to do with compiling and/or dll/bin files, but none of their help has worked for me.</p>
<pre><code>Compiler Error Message: BC30456: 'gvLegs_PageIndexChanging' is not a member of 'ASP.nestedgridview_aspx'.
Source Error:
Line 43: <asp:Label ID="lblEmpName" runat="server" Text='<%# Eval("Location")%>'></asp:Label>
Line 44: <asp:Literal runat="server" ID="lit1" Text="</td><tr id='trCollapseGrid' style='display:none' ><td colspan='5'>" />
Line 45: <asp:GridView ID="gvLegs" AutoGenerateColumns="False" runat="server" EnableViewState="False"
Line 46: DataKeyNames="EmployeeId" ForeColor="#333333" PageSize="4" AllowPaging="True"
Line 47: OnPageIndexChanging="gvLegs_PageIndexChanging">
Source File: C:\Users\tstanley\Desktop\NestedVB\NestedVB\NestedGridView.aspx Line: 45
</code></pre>
<p>NestedGridView.aspx</p>
<pre><code><%@ Page Language="vb" AutoEventWireup="false" codebehind="NestedGridView.aspx.vb" Inherits="NestedVB.NestedGridViewPaging2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
</code></pre>
<p>NetedGridView.aspx.vb [Code Behind]
...</p>
<pre><code> Private Sub gvLegs_PageIndexChanging(sender As Object, e As GridViewPageEventArgs)
</code></pre>
<p>If anyone has a fix for this, it would help me greatly so I can continue.... debugging the actual code lol.</p> | 11,147,117 | 1 | 0 | null | 2012-06-21 21:33:43.35 UTC | 2 | 2019-01-11 09:20:35.667 UTC | 2012-06-22 13:24:16.103 UTC | null | 1,473,374 | null | 1,473,374 | null | 1 | 6 | asp.net|vb.net|visual-studio-2010|web-applications | 56,825 | <p><code>gvLegs_PageIndexChanging</code> is private but needs to be protected or public.</p>
<p>Since you're using VB.NET you could also use the <a href="http://msdn.microsoft.com/en-us/library/6k46st1y%28v=vs.80%29.aspx" rel="noreferrer">handles clause</a>:</p>
<pre><code>Private Sub gvLegs_PageIndexChanging(sender As Object, e As GridViewPageEventArgs) _
Handles gvLegs.PageIndexChanging
End Sub
</code></pre>
<p><strong>Edit</strong>: Just to be clear, you have three options in ASP.NET with VB.NET to create event handlers:</p>
<ol>
<li>declaratively on aspx</li>
<li>in code with <a href="http://msdn.microsoft.com/en-us/library/6k46st1y%28v=vs.80%29.aspx" rel="noreferrer">handles clause</a></li>
<li>with <a href="http://msdn.microsoft.com/en-us/library/6yyk8z93%28v=vs.71%29.aspx" rel="noreferrer">AddHandler</a> (mostly for dynamical controls in VB.NET)</li>
</ol>
<p>If you use option 1 the event handler must at least be protected since the aspx page inherits from the codebehind class.</p>
<p>If you use option 2 the method can be private but you need to remove the declarative event handler on the aspx.</p> |
11,176,813 | Hidden fields in AngularJs | <p>How do I access hidden fields in angular? I have an app, where I want to submit a form for each of items in the list. The form is simple - it has submit button and a hidden field holding the ID value. But it does not work. The value is empty. </p>
<p>I updated the default angular example to display the situation - the todo text is in hidden field. </p>
<p><a href="http://jsfiddle.net/tomasfejfar/yFrze/" rel="noreferrer">http://jsfiddle.net/tomasfejfar/yFrze/</a></p> | 11,182,586 | 7 | 2 | null | 2012-06-24 10:50:54.677 UTC | 3 | 2019-03-17 00:37:45.303 UTC | null | null | null | null | 112,000 | null | 1 | 16 | javascript|angularjs | 52,566 | <p>In your simpler fiddle, the problem can be fixed by using ng-init or setting an initial value in the controller. The <code>value</code> attribute won't effect the ng-model.</p>
<p><a href="http://jsfiddle.net/andytjoslin/DkMyP/2/" rel="nofollow">http://jsfiddle.net/andytjoslin/DkMyP/2/</a></p>
<p>Also, your initial example (http://jsfiddle.net/tomasfejfar/yFrze/) works for me in its current state on Chrome 15/Windows 7.</p> |
11,340,765 | Default window colour Tkinter and hex colour codes | <p>I would like to know the default window colour in Tkinter when you simply create a window:</p>
<pre><code>root = Tk()
</code></pre>
<p>If there is one, it is possible to set widgets to the same colour or use a hex colour code? (using rgb)</p>
<p>The colour code I have found for the 'normal' window is:</p>
<p>R = 240, G = 240, B = 237</p>
<p>Thanks.</p> | 11,342,481 | 7 | 0 | null | 2012-07-05 08:44:47.763 UTC | 4 | 2021-01-07 18:49:28.613 UTC | null | null | null | null | 982,297 | null | 1 | 19 | python|colors|tkinter|ttk | 93,064 | <p>Not sure exactly what you're looking for, but will this work?</p>
<pre><code>import Tkinter
mycolor = '#%02x%02x%02x' % (64, 204, 208) # set your favourite rgb color
mycolor2 = '#40E0D0' # or use hex if you prefer
root = Tkinter.Tk()
root.configure(bg=mycolor)
Tkinter.Button(root, text="Press me!", bg=mycolor, fg='black',
activebackground='black', activeforeground=mycolor2).pack()
root.mainloop()
</code></pre>
<p>If you just want to find the current value of the window, and set widgets to use it, <code>cget</code> might be what you want:</p>
<pre><code>import Tkinter
root = Tkinter.Tk()
defaultbg = root.cget('bg')
Tkinter.Button(root,text="Press me!", bg=defaultbg).pack()
root.mainloop()
</code></pre>
<p>If you want to set the default background color for new widgets, you can use the <code>tk_setPalette(self, *args, **kw)</code> method:</p>
<pre><code>root.tk_setPalette(background='#40E0D0', foreground='black',
activeBackground='black', activeForeground=mycolor2)
Tkinter.Button(root, text="Press me!").pack()
</code></pre>
<p>Then your widgets would have this background color by default, without having to set it in the widget parameters. There's a lot of useful information provided with the inline help functions <code>import Tkinter; help(Tkinter.Tk)</code></p> |
11,052,125 | Convert Comma Separated Values to List<Long> | <p>Assume I have a set of numbers like <code>1,2,3,4,5,6,7</code> input as a single <code>String</code>. I would like to convert those numbers to a <code>List</code> of <code>Long</code> objects ie <code>List<Long></code>.</p>
<p>Can anyone recommend the easiest method?</p> | 11,052,279 | 7 | 0 | null | 2012-06-15 14:00:53.117 UTC | 6 | 2021-12-01 22:51:12.81 UTC | 2014-12-16 11:21:37.753 UTC | null | 3,622,940 | null | 362,302 | null | 1 | 23 | java | 45,346 | <p>I would use the excellent google's Guava library to do it. String.split can cause many troubles.</p>
<pre><code>String numbers="1,2,3,4,5,6,7";
Iterable<String> splitIterator = Splitter.on(',').split(numbers);
List<String> list= Lists.newArrayList(splitIterator );
</code></pre> |
11,238,830 | How to enable "World Wide Services (HTTP)" in the firewall using command line? | <p>I'm trying to share my site in the local network. I want to use command line tool to perform this action. </p>
<p><strong>Manually:</strong>
To enable http access through Windows Firewall on Windows 7. From the start menu begin typing "Allow a program through Windows Firewall". Scroll the bottom of the list and look for World Wide Web Services (HTTP) and enable it on your networks. It works fine.</p>
<p><strong>Command line doesn't work:</strong></p>
<pre><code>>> netsh advfirewall firewall set rule name="World Wide Web Services (HTTP)" new enable=yes
</code></pre>
<p><strong>Error: No rules match the specified criteria.</strong></p>
<p>What is wrong in the command line?</p> | 11,313,314 | 5 | 0 | null | 2012-06-28 05:59:21.593 UTC | 2 | 2015-07-22 17:34:09.73 UTC | null | null | null | null | 691,269 | null | 1 | 26 | iis|iis-7|sql-server-2008-r2|windows-server-2008|firewall | 85,432 | <p>I had same problem when i used russian version of MS Windows 7 Pro.</p>
<p>This issue was solved when i check <code>"World Wide Web Services (HTTP)"</code> in list of services. For my russian version of Windows it was named <code>"службы Интернета (HTTP)"</code></p>
<p>So this command line works fine:</p>
<pre class="lang-sql prettyprint-override"><code>>> netsh advfirewall firewall set rule name="службы Интернета (HTTP)" new enable=yes
</code></pre> |
11,069,437 | Changing font in UITabBarItem | <p>Hi I have this code and it doesn't work, what am I doing wrong?</p>
<pre><code>- (void)viewDidLoad
{
[self.tabBarItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:@"AmericanTypewriter" size:20.0f], UITextAttributeFont, nil] forState:UIControlStateDisabled];
}
</code></pre>
<p>BTW that's not the only thing in my viewDidLoad but I just wanted to show you guys thats where I put it. </p> | 11,069,509 | 6 | 2 | null | 2012-06-17 06:44:24.087 UTC | 8 | 2021-06-30 10:45:32.057 UTC | 2012-06-17 06:57:04.553 UTC | null | 852,828 | user1457381 | null | null | 1 | 38 | iphone|ios|xcode|uitabbarcontroller | 25,724 | <p>As per: <a href="https://stackoverflow.com/questions/8412010/how-to-change-the-color-of-text-in-uitabbaritem-in-ios-5">How to change the Color of text in UITabBarItem in iOS 5</a></p>
<p>It looks like the solution may be sending the message to the appearance proxy, instead of one item: </p>
<p><strong>(Deprecated in iOS 7.0+)</strong></p>
<pre><code>[[UITabBarItem appearance] setTitleTextAttributes:@{UITextAttributeFont: [UIFont fontWithName:@"AmericanTypewriter" size:20.0f]} forState:UIControlStateNormal];
</code></pre>
<p><strong>For iOS 7.0+ use:</strong></p>
<pre><code>[[UITabBarItem appearance] setTitleTextAttributes:@{NSFontAttributeName: [UIFont fontWithName:@"AmericanTypewriter" size:20.0f]} forState:UIControlStateNormal];
</code></pre> |
10,959,554 | Right place for putting mp3 files in an android project | <p>Is there any folder like res/drawable for mp3 or generally audio files? If yes, what is it and how can I get access to it from the app?</p> | 10,959,588 | 4 | 2 | null | 2012-06-09 08:35:05.24 UTC | 18 | 2020-08-17 14:33:04.147 UTC | null | null | null | null | 624,074 | null | 1 | 40 | android|mp3 | 70,383 | <p>The best place to put such <code>.mp3</code> or any other files would be in the <code>assets</code> folder.</p>
<p>These files once stored will become a part of your android app itself and can be read easily. This <a href="http://xjaphx.wordpress.com/2011/10/02/store-and-use-files-in-assets/" rel="noreferrer">tutorial</a> describes it well.</p>
<pre><code> AssetFileDescriptor afd = getAssets().openFd("AudioFile.mp3");
MediaPlayer player = new MediaPlayer();
player.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
player.prepare();
player.start();
</code></pre>
<p>Alternatively you can also store it in the <code>raw</code> folder and read it directly by specifying the path as the raw folder.
this can be played as:</p>
<pre><code>int resID=getResources().getIdentifier(fname, "raw", getPackageName());
MediaPlayer mediaPlayer=MediaPlayer.create(this,resID);
</code></pre> |
11,322,182 | Backbone model.save() not calling either error or success callbacks | <p>I'm trying to update a record in DB so I'm defining model with data and calling .save() method. The PUT request is triggered and the database entry is updated. The problem is neither success or error callbacks are called. What could be the cause?</p>
<pre><code>sessionsModel.save({
error: function() {
alert('test');
},
success: function () {
alert('test');
}
});
</code></pre>
<p>Edit: Request returns JSON object</p> | 11,322,260 | 4 | 4 | null | 2012-07-04 03:49:34.7 UTC | 8 | 2016-03-13 21:26:26.19 UTC | null | null | null | null | 333,763 | null | 1 | 52 | backbone.js | 25,257 | <p>Just found similar problem where the issue was solved. You have to put something as first parameter (I put null since my model was already populated with data explicitly) and object with callbacks as second. So something like; </p>
<pre><code>sessionsModel.save(null, {success:function() {} });
</code></pre> |
10,864,755 | Adding and reading from a Config file | <p>I have created a <code>C# console based project</code>. In that project i have some variables like <code>companyName</code>, <code>companyType</code> which are Strings. </p>
<pre><code>companyName="someCompanyName";
companyType="someCompanyType";
</code></pre>
<p>I need to create a config file and read values from it, and then initialize the variables <code>companyName</code>, <code>companyType</code> in the code. </p>
<ol>
<li>How can i create a config file (or equivalent) ?</li>
<li>How can i read from the config file ?</li>
</ol> | 10,864,790 | 3 | 1 | null | 2012-06-02 18:12:10.103 UTC | 23 | 2020-01-31 15:37:05.143 UTC | 2018-06-11 22:17:39.35 UTC | null | 2,514,526 | null | 844,872 | null | 1 | 61 | c#|configuration-files | 176,168 | <ol>
<li><p>Add an <a href="https://docs.microsoft.com/en-us/dotnet/framework/configure-apps/index?redirectedfrom=MSDN" rel="noreferrer"><code>Application Configuration File</code></a> item to your project (<kbd>Right -Click</kbd> Project > Add item). This will create a file called <code>app.config</code> in your project.</p></li>
<li><p>Edit the file by adding entries like <code><add key="keyname" value="someValue" /></code> within the <code><appSettings></code> tag.</p></li>
<li><p>Add a reference to the <code>System.Configuration</code> dll, and reference the items in the config using code like <code>ConfigurationManager.AppSettings["keyname"]</code>.</p></li>
</ol> |
10,963,775 | Cannot reference "X" before supertype constructor has been called, where x is a final variable | <p>Consider the following Java class declaration:</p>
<pre><code>public class Test {
private final int defaultValue = 10;
private int var;
public Test() {
this(defaultValue); // <-- Compiler error: cannot reference defaultValue before supertype constructor has been called.
}
public Test(int i) {
var = i;
}
}
</code></pre>
<p>The code will not compile, with the compiler complaining about the line I've highlighted above. Why is this error happening and what's the best workaround?</p> | 10,963,784 | 6 | 0 | null | 2012-06-09 19:05:16.647 UTC | 23 | 2020-05-23 16:37:03.873 UTC | null | null | null | null | 286,701 | null | 1 | 86 | java|constructor|final|supertype | 71,093 | <p>The reason why the code would not initially compile is because <code>defaultValue</code> is an <strong>instance variable</strong> of the class <code>Test</code>, meaning that when an object of type <code>Test</code> is created, a unique instance of <code>defaultValue</code> is also created and attached to that particular object. Because of this, it is not possible to reference <code>defaultValue</code> in the constructor, as neither it, nor the object have been created yet.</p>
<p>The solution is to make the final variable <code>static</code>:</p>
<pre><code>public class Test {
private static final int defaultValue = 10;
private int var;
public Test() {
this(defaultValue);
}
public Test(int i) {
var = i;
}
}
</code></pre>
<p>By making the variable <code>static</code>, it becomes associated with the class itself, rather than instances of that class and is shared amongst all instances of <code>Test</code>. Static variables are created when the JVM first loads the class. Since the class is already loaded when you use it to create an instance, the static variable is ready to use and so can be used in the class, including the constructor.</p>
<p>References:</p>
<ul>
<li><a href="http://www.coderanch.com/t/247949/java-programmer-SCJP/certification/Says-cannot-reference-before-supertype" rel="noreferrer">Forum post asking the same question</a></li>
<li><a href="http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html" rel="noreferrer">Understanding Instance and Class Members</a></li>
<li><a href="https://stackoverflow.com/questions/1133552/explanation-of-how-classloader-loads-static-variables">Explanation of how classloader loads static variables</a></li>
</ul> |
12,729,228 | Simple, efficient bilinear interpolation of images in numpy and python | <p>How do I implement bilinear interpolation for image data represented as a numpy array in python?</p> | 12,729,229 | 1 | 0 | null | 2012-10-04 14:12:15.947 UTC | 12 | 2013-11-17 12:28:56.343 UTC | 2012-10-04 16:01:01.057 UTC | null | 166,749 | null | 795,053 | null | 1 | 13 | python|numpy|interpolation | 30,519 | <p>I found many questions on this topic and many answers, though none were efficient for the common case that the data consists of samples on a grid (i.e. a rectangular image) and represented as a numpy array. This function can take lists as both x and y coordinates and will perform the lookups and summations without need for loops.</p>
<pre><code>def bilinear_interpolate(im, x, y):
x = np.asarray(x)
y = np.asarray(y)
x0 = np.floor(x).astype(int)
x1 = x0 + 1
y0 = np.floor(y).astype(int)
y1 = y0 + 1
x0 = np.clip(x0, 0, im.shape[1]-1);
x1 = np.clip(x1, 0, im.shape[1]-1);
y0 = np.clip(y0, 0, im.shape[0]-1);
y1 = np.clip(y1, 0, im.shape[0]-1);
Ia = im[ y0, x0 ]
Ib = im[ y1, x0 ]
Ic = im[ y0, x1 ]
Id = im[ y1, x1 ]
wa = (x1-x) * (y1-y)
wb = (x1-x) * (y-y0)
wc = (x-x0) * (y1-y)
wd = (x-x0) * (y-y0)
return wa*Ia + wb*Ib + wc*Ic + wd*Id
</code></pre> |
12,747,946 | How to write and read a file with a HashMap? | <p>I have a <code>HashMap</code> with two Strings <code>Map<String, String> ldapContent = new HashMap<String, String></code>.</p>
<p>Now I want to save the <code>Map</code> in an external file to use the <code>Map</code> later without initializing it again...</p>
<p>So how must I save the <code>Map</code> to use it later again?</p> | 12,747,984 | 4 | 2 | null | 2012-10-05 14:01:56.283 UTC | 14 | 2020-01-08 15:27:04.913 UTC | 2017-10-11 01:39:51.463 UTC | null | 2,619,038 | user1671245 | null | null | 1 | 19 | java|file|dictionary|hashmap | 125,395 | <p><code>HashMap</code> implements <code>Serializable</code> so you can use normal serialization to write hashmap to file</p>
<p>Here is the link for <a href="http://www.tutorialspoint.com/java/java_serialization.htm">Java - Serialization</a> example</p> |
12,921,789 | Django: import auth user to the model | <p>In Django I created a new model:</p>
<pre class="lang-py prettyprint-override"><code>from django.db import models
from django.contrib.auth import user
class Workers(models.Model):
user = models.OneToOneField(User, primary_key=True)
work_group = models.CharField(max_length=20)
card_num = models.IntegerField()
def __unicode__(self):
return self.user
</code></pre>
<p>But it doesn't work: <code>ImportError: cannot import name user</code></p>
<p>How to fix it?</p>
<p>I want to create a new table "workers" in db, which has a <code>OneToOne</code> relationship with table "auth_user".</p> | 12,921,810 | 4 | 0 | null | 2012-10-16 19:08:46.927 UTC | 11 | 2021-07-15 03:16:11.78 UTC | 2021-07-15 03:16:11.78 UTC | null | 11,573,842 | null | 1,751,039 | null | 1 | 89 | django|django-models | 95,926 | <pre><code>from django.contrib.auth.models import User
</code></pre>
<p>You missed the models - and user is capitalized.</p>
<p>If you use a custom user model you should use:</p>
<pre><code>from django.contrib.auth import get_user_model
User = get_user_model()
</code></pre>
<p>More details can be found in the <a href="https://docs.djangoproject.com/en/dev/topics/auth/customizing/#referencing-the-user-model" rel="noreferrer">docs</a>.</p>
<blockquote>
<p><strong>Changed in Django 1.11:</strong></p>
<p>The ability to call get_user_model() at import time was added.</p>
</blockquote> |
13,198,476 | Cannot use UPDATE with OUTPUT clause when a trigger is on the table | <p>I'm performing an <code>UPDATE</code> with <code>OUTPUT</code> query:</p>
<pre><code>UPDATE BatchReports
SET IsProcessed = 1
OUTPUT inserted.BatchFileXml, inserted.ResponseFileXml, deleted.ProcessedDate
WHERE BatchReports.BatchReportGUID = @someGuid
</code></pre>
<p>This statement is well and fine; until a trigger is defined on the table. Then my <code>UPDATE</code> statement will get the error <a href="http://msdn.microsoft.com/en-us/library/aa937592(v=sql.80).aspx" rel="noreferrer">334</a>:</p>
<blockquote>
<p>The target table 'BatchReports' of the DML statement cannot have any enabled triggers if the statement contains an OUTPUT clause without INTO clause</p>
</blockquote>
<p>Now this problem is explained in a blog post by the SQL Server team -- <a href="https://techcommunity.microsoft.com/t5/sql-server/update-with-output-clause-8211-triggers-8211-and-sqlmoreresults/ba-p/383457" rel="noreferrer">UPDATE with OUTPUT clause – Triggers – and SQLMoreResults</a>:</p>
<blockquote>
<p>The error message is self-explanatory</p>
</blockquote>
<p>And they also give solutions:</p>
<blockquote>
<p>The application was changed to utilize the INTO clause</p>
</blockquote>
<p>Except I cannot make head nor tail of the entirety of the blog post.</p>
<p>So let me ask my question: What should I change my <code>UPDATE</code> to so that it works?</p>
<h2>See also</h2>
<ul>
<li><a href="http://blogs.msdn.com/b/sqlprogrammability/archive/2008/07/11/update-with-output-clause-triggers-and-sqlmoreresults.aspx" rel="noreferrer">UPDATE with OUTPUT clause – Triggers – and SQLMoreResults</a></li>
<li><a href="https://stackoverflow.com/questions/6504173/why-is-the-target-table-of-a-merge-statement-not-allowed-to-have-enabled-rules">Why is the target table of a MERGE statement not allowed to have enabled rules?</a></li>
<li><a href="https://stackoverflow.com/questions/12537653/statement-contains-an-output-clause-without-into-clause-error">Statement contains an OUTPUT clause without INTO clause error</a></li>
</ul> | 13,198,916 | 3 | 0 | null | 2012-11-02 15:38:39.62 UTC | 19 | 2021-05-20 21:44:19.593 UTC | 2021-05-20 21:42:13.51 UTC | null | 1,127,428 | null | 12,597 | null | 1 | 92 | sql|sql-server|sql-server-2008-r2 | 66,013 | <p><strong>Visibility Warning</strong>: Don't the <a href="https://stackoverflow.com/questions/13198476/cannot-use-update-with-output-clause-when-a-trigger-is-on-the-table/13198551#13198551">other answer</a>. It will give incorrect values. Read on for why it's wrong.</p>
<hr />
<p>Given the kludge needed to make <code>UPDATE</code> with <code>OUTPUT</code> work in SQL Server 2008 R2, I changed my query from:</p>
<pre><code>UPDATE BatchReports
SET IsProcessed = 1
OUTPUT inserted.BatchFileXml, inserted.ResponseFileXml, deleted.ProcessedDate
WHERE BatchReports.BatchReportGUID = @someGuid
</code></pre>
<p>to:</p>
<pre><code>SELECT BatchFileXml, ResponseFileXml, ProcessedDate FROM BatchReports
WHERE BatchReports.BatchReportGUID = @someGuid
UPDATE BatchReports
SET IsProcessed = 1
WHERE BatchReports.BatchReportGUID = @someGuid
</code></pre>
<p>Basically I stopped using <code>OUTPUT</code>. This isn't so bad as <strong>Entity Framework itself</strong> uses this very same hack!</p>
<p>Hopefully <strike>2012</strike> <strike>2014</strike> <strike>2016</strike> <strike>2018</strike> <strike>2019</strike> 2020 will have a better implementation.</p>
<hr />
<h2><strong>Update: using OUTPUT is harmful</strong></h2>
<p>The problem we started with was trying to use the <code>OUTPUT</code> clause to retrieve the <em>"after"</em> values in a table:</p>
<pre><code>UPDATE BatchReports
SET IsProcessed = 1
OUTPUT inserted.LastModifiedDate, inserted.RowVersion, inserted.BatchReportID
WHERE BatchReports.BatchReportGUID = @someGuid
</code></pre>
<p>That then hits the well-know limitation (<em>"won't-fix"</em> bug) in SQL Server:</p>
<blockquote>
<p>The target table 'BatchReports' of the DML statement cannot have any enabled triggers if the statement contains an OUTPUT clause without INTO clause</p>
</blockquote>
<h2>Workaround Attempt #1</h2>
<p>So we try something where we will use an intermediate <code>TABLE</code> variable to hold the <code>OUTPUT</code> results:</p>
<pre><code>DECLARE @t TABLE (
LastModifiedDate datetime,
RowVersion timestamp,
BatchReportID int
)
UPDATE BatchReports
SET IsProcessed = 1
OUTPUT inserted.LastModifiedDate, inserted.RowVersion, inserted.BatchReportID
INTO @t
WHERE BatchReports.BatchReportGUID = @someGuid
SELECT * FROM @t
</code></pre>
<p>Except that fails because you're not allowed to insert a <code>timestamp</code> into the table (even a temporary table variable).</p>
<h2>Workaround Attempt #2</h2>
<p>We secretly know that a <code>timestamp</code> is actually a 64-bit (aka 8 byte) unsigned integer. We can change our temporary table definition to use <code>binary(8)</code> rather than <code>timestamp</code>:</p>
<pre><code>DECLARE @t TABLE (
LastModifiedDate datetime,
RowVersion binary(8),
BatchReportID int
)
UPDATE BatchReports
SET IsProcessed = 1
OUTPUT inserted.LastModifiedDate, inserted.RowVersion, inserted.BatchReportID
INTO @t
WHERE BatchReports.BatchReportGUID = @someGuid
SELECT * FROM @t
</code></pre>
<p>And that works, <em><strong>except that the value are wrong</strong></em>.</p>
<p>The timestamp <code>RowVersion</code> we return is not the value of the timestamp as it existed after the UPDATE completed:</p>
<ul>
<li><strong>returned timestamp</strong>: <code>0x0000000001B71692</code></li>
<li><strong>actual timestamp</strong>: <code>0x0000000001B71693</code></li>
</ul>
<p>That is because the values <code>OUTPUT</code> into our table are <strong>not</strong> the values as they were at the end of the UPDATE statement:</p>
<ul>
<li>UPDATE statement starting
<ul>
<li>modifies row
<ul>
<li>timestamp is updated <em>(e.g. 2 → 3)</em></li>
</ul>
</li>
<li>OUTPUT retrieves new timestamp <em>(i.e. 3)</em></li>
<li>trigger runs
<ul>
<li>modifies row again
<ul>
<li>timestamp is updated <em>(e.g. 3 → 4)</em></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li>UPDATE statement complete</li>
<li>OUTPUT returns <strong>3</strong> <em>(the wrong value)</em></li>
</ul>
<p>This means:</p>
<ul>
<li>We do not get the timestamp as it exists at the end of the UPDATE statement (<strong>4</strong>)</li>
<li>Instead we get the timestamp as it was in the indeterminate middle of the UPDATE statement (<strong>3</strong>)</li>
<li>We do not get the correct timestamp</li>
</ul>
<p>The same is true of <strong>any</strong> trigger that modifies <em>any</em> value in the row. The <code>OUTPUT</code> will not OUTPUT the value as of the end of the UPDATE.</p>
<p><em>This means you cannot trust OUTPUT to return any correct values ever.</em></p>
<p>This painful reality is documented in the BOL:</p>
<blockquote>
<p>Columns returned from OUTPUT reflect the data as it is after the INSERT, UPDATE, or DELETE statement has completed but before triggers are executed.</p>
</blockquote>
<h2>How did Entity Framework solve it?</h2>
<p>The .NET Entity Framework uses rowversion for Optimistic Concurrency. The EF depends on knowing the value of the <code>timestamp</code> as it exists after they issue an UPDATE.</p>
<p>Since you cannot use <code>OUTPUT</code> for any important data, Microsoft's Entity Framework uses the same workaround that I do:</p>
<h2>Workaround #3 - Final - Do not use OUTPUT clause</h2>
<p>In order to retrieve the <em>after</em> values, Entity Framework issues:</p>
<pre><code>UPDATE [dbo].[BatchReports]
SET [IsProcessed] = @0
WHERE (([BatchReportGUID] = @1) AND ([RowVersion] = @2))
SELECT [RowVersion], [LastModifiedDate]
FROM [dbo].[BatchReports]
WHERE @@ROWCOUNT > 0 AND [BatchReportGUID] = @1
</code></pre>
<p>Don't use <code>OUTPUT</code>.</p>
<p>Yes it suffers from a race condition, but that's the best SQL Server can do.</p>
<h1>What about INSERTs</h1>
<p>Do what Entity Framework does:</p>
<pre><code>SET NOCOUNT ON;
DECLARE @generated_keys table([CustomerID] int)
INSERT Customers (FirstName, LastName)
OUTPUT inserted.[CustomerID] INTO @generated_keys
VALUES ('Steve', 'Brown')
SELECT t.[CustomerID], t.[CustomerGuid], t.[RowVersion], t.[CreatedDate]
FROM @generated_keys AS g
INNER JOIN Customers AS t
ON g.[CustomerGUID] = t.[CustomerGUID]
WHERE @@ROWCOUNT > 0
</code></pre>
<p>Again, they use a <code>SELECT</code> statement to read the row, rather than placing any trust in the OUTPUT clause.</p> |
12,990,338 | Cannot convert []string to []interface {} | <p>I'm writing some code, and I need it to catch the arguments and pass them through <code>fmt.Println</code><br>
(I want its default behaviour, to write arguments separated by spaces and followed by a newline). However it takes <code>[]interface {}</code> but <code>flag.Args()</code> returns a <code>[]string</code>.<br>
Here's the code example:</p>
<pre><code>package main
import (
"fmt"
"flag"
)
func main() {
flag.Parse()
fmt.Println(flag.Args()...)
}
</code></pre>
<p>This returns the following error:</p>
<pre><code>./example.go:10: cannot use args (type []string) as type []interface {} in function argument
</code></pre>
<p>Is this a bug? Shouldn't <code>fmt.Println</code> take <strong>any</strong> array? By the way, I've also tried to do this:</p>
<pre><code>var args = []interface{}(flag.Args())
</code></pre>
<p>but I get the following error:</p>
<pre><code>cannot convert flag.Args() (type []string) to type []interface {}
</code></pre>
<p>Is there a "Go" way to workaround this?</p> | 12,990,540 | 7 | 1 | null | 2012-10-20 16:19:25.04 UTC | 39 | 2021-04-07 15:27:02.757 UTC | 2018-01-31 02:48:46.54 UTC | user6169399 | 1,924,666 | null | 1,502,569 | null | 1 | 112 | type-conversion|go | 62,841 | <p>This is not a bug. <code>fmt.Println()</code> requires a <code>[]interface{}</code> type. That means, it must be a slice of <code>interface{}</code> values and not "any slice". In order to convert the slice, you will need to loop over and copy each element.</p>
<pre><code>old := flag.Args()
new := make([]interface{}, len(old))
for i, v := range old {
new[i] = v
}
fmt.Println(new...)
</code></pre>
<p>The reason you can't use any slice is that conversion between a <code>[]string</code> and a <code>[]interface{}</code> requires the memory layout to be changed and happens in O(n) time. Converting a type to an <code>interface{}</code> requires O(1) time. If they made this for loop unnecessary, the compiler would still need to insert it.</p> |
11,388,014 | Using scp to copy a file to Amazon EC2 instance? | <p>I am trying to use my Mac Terminal to scp a file from Downloads (phpMyAdmin I downloaded online) to my Amazon EC2 instance. </p>
<p>The command I used was:</p>
<pre><code>scp -i myAmazonKey.pem phpMyAdmin-3.4.5-all-languages.tar.gz [email protected]:~/.
</code></pre>
<p>The error I got:
<strong>Warning: Identity file myAmazonKey.pem not accessible: No such file or directory.
Permission denied (publickey).
lost connection</strong></p>
<p>Both my myAmazonkey.pem and phpMyAdmin-3.4.5-all-languages.tar.gz are in Downloads, so then I tried </p>
<pre><code>scp -i /Users/Hello_Kitty22/Downloads/myAmazonKey.pem /Users/Hello_Kitty22/Downloads/phpMyAdmin-3.4.5-all-languages.tar.gz [email protected]:~/.
</code></pre>
<p>and the error I got:
<strong>Warning: Identity file /User/Hello_Kitty22/Downloads/myAmazonkey.pem not accessible: No such file or directory.
Permission denied (publickey).
lost connection</strong></p>
<p>Can anyone please tell me how to fix my problem?</p>
<p>p.s. there is a similar post: <a href="https://stackoverflow.com/questions/6558080/scp-secure-copy-to-ec2-instance-without-password">scp (secure copy) to ec2 instance without password</a>
but it doesn't answer my question. </p> | 13,925,773 | 18 | 1 | null | 2012-07-09 01:02:53.307 UTC | 101 | 2022-07-20 06:40:10.13 UTC | 2017-05-23 11:47:26.357 UTC | null | -1 | null | 1,472,828 | null | 1 | 253 | amazon-ec2|terminal|copy|scp|public-key | 400,458 | <p>Try specifying the user to be <code>ec2-user</code>, e.g.</p>
<pre><code>scp -i myAmazonKey.pem phpMyAdmin-3.4.5-all-languages.tar.gz [email protected]:~/.
</code></pre>
<p>See <a href="http://docs.amazonwebservices.com/AWSEC2/latest/UserGuide/AccessingInstancesLinux.html">Connecting to Linux/UNIX Instances Using SSH</a>.</p> |
17,029,384 | Rotating a SVG with Css (Animation) | <p>I want to have a css-coded animated rotating svg image. I have no idea how to do that. At the end it has to look exactly like this: <a href="http://baveltje.com/logo/logo.html" rel="noreferrer">http://baveltje.com/logo/logo.html</a>. I am completely new to css. The rotating svg's are gear1.svg and gear2.svg. I want them to rotate 360 degres for infinite time and I want to call them <.div class="gear1"> and gear2.. Is it possible to let it look exactly like the logo does in the link, but rotating?</p>
<p>I tried to use <a href="https://jsfiddle.net/gaby/9Ryvs/7/" rel="noreferrer">jsfiddle.net/gaby/9Ryvs/7/</a>, but with no results. It has to go the same speed like that fiddle does!</p>
<p>Thanks in advance!</p>
<p>Code: </p>
<pre><code>div {
margin: 20px;
width: 100px;
height: 100px;
background: #f00;
-webkit-animation-name: spin;
-webkit-animation-duration: 4000ms;
-webkit-animation-iteration-count: infinite;
-webkit-animation-timing-function: linear;
-moz-animation-name: spin;
-moz-animation-duration: 4000ms;
-moz-animation-iteration-count: infinite;
-moz-animation-timing-function: linear;
-ms-animation-name: spin;
-ms-animation-duration: 4000ms;
-ms-animation-iteration-count: infinite;
-ms-animation-timing-function: linear;
animation-name: spin;
animation-duration: 4000ms;
animation-iteration-count: infinite;
animation-timing-function: linear;
}
@-ms-keyframes spin {
from { -ms-transform: rotate(0deg); }
to { -ms-transform: rotate(360deg); }
}
@-moz-keyframes spin {
from { -moz-transform: rotate(0deg); }
to { -moz-transform: rotate(360deg); }
}
@-webkit-keyframes spin {
from { -webkit-transform: rotate(0deg); }
to { -webkit-transform: rotate(360deg); }
}
@keyframes spin {
from {
transform:rotate(0deg);
}
to {
transform:rotate(360deg);
}
}
</code></pre> | 17,031,363 | 1 | 0 | null | 2013-06-10 17:16:59.22 UTC | 4 | 2018-01-21 23:47:01.137 UTC | 2018-01-21 23:47:01.137 UTC | null | 2,012,163 | null | 2,456,614 | null | 1 | 14 | css|html|vector|svg | 43,922 | <p>Here is your original animation css (I have removed prefixes to keep it simple):</p>
<pre><code>#gear{
animation-name: ckw;
animation-duration: 15.5s;
}
@keyframes ckw {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
</code></pre>
<p>In <strong><em>#gear</em></strong> you should add:</p>
<ul>
<li><em><strong>animation-iteration-count</em></strong> to <strong><em>infinite</em></strong> to keep it rolling</li>
<li><em><strong>transform-origin</em></strong> to center of your div <strong><em>50% 50%</em></strong> to get gear rolling around itself</li>
<li><em><strong>display</em></strong> to <strong><em>inline-block</em></strong></li>
</ul>
<p>Result:</p>
<pre><code>#gear{
animation-name: ckw;
animation-duration: 15.5s;
/* Things added */
animation-iteration-count: infinite;
transform-origin: 50% 50%;
display: inline-block;
/* <--- */
}
@keyframes ckw {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
</code></pre>
<p>And of course add correct prefixes.</p> |
16,988,558 | Scala - No TypeTag Available Exception when using case class to try to get TypeTag? | <p>I'm looking at the scala reflect API and I'm getting lots of exceptions.</p>
<p>Doc reference:
<a href="http://docs.scala-lang.org/overviews/reflection/environment-universes-mirrors.html" rel="noreferrer">http://docs.scala-lang.org/overviews/reflection/environment-universes-mirrors.html</a></p>
<p>How do I get the typetag from a generic?</p>
<pre><code> def getChildSettings[T: ru.TypeTag](path: String, settingsParameterObject: T) = {
import scala.reflect.runtime.{ currentMirror => m }
val m = ru.runtimeMirror(getClass.getClassLoader)
val classC = ru.typeOf[T].typeSymbol.asClass
}
</code></pre>
<p>I get an exception: </p>
<pre><code>No TypeTag available for ParameterObject.type
</code></pre>
<p>Even a very simple example doesn't seem to work (edit yes it does in the repl)</p>
<pre><code>import scala.reflect.runtime.universe._
import scala.reflect.runtime.currentMirror
import scala.reflect.runtime.{universe => ru}
def getTypeTag[T: ru.TypeTag](obj: T) = ru.typeTag[T]
case class ParameterObject(stringType: String, optionType: Option[String])
getTypeTag(ParameterObject)
</code></pre>
<p>I'm guessing it's something about how I'm invoking the method.</p> | 16,990,806 | 5 | 2 | null | 2013-06-07 16:11:01.177 UTC | 8 | 2016-05-24 13:35:08.893 UTC | 2013-06-07 19:36:25.277 UTC | null | 1,255,825 | null | 1,255,825 | null | 1 | 24 | scala|reflection|types | 22,115 | <p>I finally found out what the issue was.
The case classes must be defined top level - they cannot be nested.
Something like this would fail.</p>
<pre><code>class Foo {
describe("getSettings") {
case class ParameterObject(foo: String)
settings.getTypeTag(path, ParameterObject)
}
}
class Clazzy {
def getTypeTag[T: TypeTag](obj: T) = ru.typeTag[T]
}
</code></pre> |
25,789,642 | Accessing Google Drive from a Firefox extension | <p>I'm trying to access (CRUD) Google Drive from a Firefox extension. Extensions are coded in Javascript, but neither of the two existing javascript SDKs seem to fit; the client-side SDK expects "window" to be available, which isn't the case in extensions, and the server-side SDK seems to rely on Node-specific facilities, as a script that works in node no longer does when I load it in chrome after running it through browserify. Am I stuck using raw REST calls? The Node script that works looks like this:</p>
<pre><code>var google = require('googleapis');
var readlineSync = require('readline-sync');
var CLIENT_ID = '....',
CLIENT_SECRET = '....',
REDIRECT_URL = 'urn:ietf:wg:oauth:2.0:oob',
SCOPE = 'https://www.googleapis.com/auth/drive.file';
var oauth2Client = new google.auth.OAuth2(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL);
var url = oauth2Client.generateAuthUrl({
access_type: 'offline', // 'online' (default) or 'offline' (gets refresh_token)
scope: SCOPE // If you only need one scope you can pass it as string
});
var code = readlineSync.question('Auth code? :');
oauth2Client.getToken(code, function(err, tokens) {
console.log('authenticated?');
// Now tokens contains an access_token and an optional refresh_token. Save them.
if(!err) {
console.log('authenticated');
oauth2Client.setCredentials(tokens);
} else {
console.log('not authenticated');
}
});
</code></pre>
<p>I wrap the node GDrive SDK using browserify on this script:</p>
<pre><code>var Google = new function(){
this.api = require('googleapis');
this.clientID = '....';
this.clientSecret = '....';
this.redirectURL = 'urn:ietf:wg:oauth:2.0:oob';
this.scope = 'https://www.googleapis.com/auth/drive.file';
this.client = new this.api.auth.OAuth2(this.clientID, this.clientSecret, this.redirectURL);
}
}
</code></pre>
<p>which is then called using after clicking a button (if the text field has no code it launches the browser to get one):</p>
<pre><code>function authorize() {
var code = document.getElementById("code").value.trim();
if (code === '') {
var url = Google.client.generateAuthUrl({access_type: 'offline', scope: Google.scope});
var win = Components.classes['@mozilla.org/appshell/window-mediator;1'].getService(Components.interfaces.nsIWindowMediator).getMostRecentWindow('navigator:browser');
win.gBrowser.selectedTab = win.gBrowser.addTab(url);
} else {
Google.client.getToken(code, function(err, tokens) {
if(!err) {
Google.client.setCredentials(tokens);
// store token
alert('Succesfully authorized');
} else {
alert('Not authorized: ' + err); // always ends here
}
});
}
}
</code></pre>
<p>But this yields the error <code>Not authorized: Invalid protocol: https:</code></p> | 27,703,724 | 2 | 11 | null | 2014-09-11 14:07:43.457 UTC | 2 | 2014-12-30 10:28:01.243 UTC | null | null | null | null | 2,541,040 | null | 1 | 36 | javascript|firefox-addon|google-drive-api|xul | 1,585 | <p>It is possible though, depending on the use case, it might also of limited interest.</p>
<p>Firefox ships with a tiny http server, just the bare bones. It is included for test purposes but this is not a reason to overlook it.</p>
<p>Lets follow the <a href="https://developers.google.com/drive/web/quickstart/quickstart-js" rel="nofollow">quickstart guide for running a Drive app in Javascript</a></p>
<p>The tricky part is to set the Redirect URIs and the Javascript Origins. Obviously the right setting is <code>http://localhost</code>, but how can you be sure that every user has port 80 available?</p>
<p>You can't and, unless you have control over your users, no port is guaranteed to work for everyone. With this in mind lets choose port 49870 and pray.</p>
<p>So now Redirect URIs and the Javascript Origins are set to <code>http://localhost:49870</code></p>
<p>Assuming you use Add-on SDK, save the <code>quickstart.html</code> (remember to add your Client ID) in the <code>data</code> directory of your extension. Now edit your <code>main.js</code></p>
<pre class="lang-js prettyprint-override"><code>const self = require("sdk/self");
const { Cc, Ci } = require("chrome");
const tabs = require("sdk/tabs");
const httpd = require("sdk/test/httpd");
var quickstart = self.data.load("quickstart.html");
var srv = new httpd.nsHttpServer();
srv.registerPathHandler("/gdrive", function handler(request, response){
response.setHeader("Content-Type", "text/html; charset=utf-8", false);
let converter = Cc["@mozilla.org/intl/scriptableunicodeconverter"].createInstance(Ci.nsIScriptableUnicodeConverter);
converter.charset = "UTF-8";
response.write(converter.ConvertFromUnicode(quickstart));
})
srv.start(49870);
tabs.open("http://localhost:49870/gdrive");
exports.onUnload = function (reason) {
srv.stop(function(){});
};
</code></pre>
<p>Notice that <code>quickstart.html</code> is not opened as a local file, with a <code>resource:</code> URI. The Drive API wouldn't like that. It is served at the url <code>http://localhost:49870/gdrive</code>. Needless to say that instead of static html we can use a template or anything else. Also the <code>http://localhost:49870/gdrive</code> can be scripted with a regular PageMod.</p>
<p>I don't consider this a real solution. It's just better than nothing.</p> |
26,791,477 | Xcode "Device Locked" When iPhone is unlocked | <p>When I tried to build and run, Xcode said my device was locked. I looked at my iPhone, and it's not locked at all. How do I fix this?</p> | 26,791,721 | 39 | 15 | null | 2014-11-06 23:37:00.02 UTC | 42 | 2022-07-28 07:30:13.54 UTC | 2019-05-27 12:40:12.863 UTC | null | 9,556,336 | null | 4,151,881 | null | 1 | 388 | ios|iphone|xcode|device | 234,355 | <p>Did you by chance not "trust" the device? This will prevent it from communicating with xcode even if the device is unlocked.</p>
<p>Update here's a support doc from Apple: <a href="http://support.apple.com/en-us/HT5868">http://support.apple.com/en-us/HT5868</a></p> |
10,008,374 | Cannot JUnit test using Spring | <p>My test is defined as follows:</p>
<pre><code>package com.mytest;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class SpringTestCase {
@Test
public void testSave_success() {
fail("Not implemented");
}
}
</code></pre>
<p>My intention is to just run this test and fail!</p>
<p>My test's spring configuration file is located in:</p>
<pre><code> /com/mytest/SpringTestCase-context.xml
</code></pre>
<p>The contents of my spring configuration file are as follows:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
</beans>
</code></pre>
<p>When i run my test i get the following exception:</p>
<pre><code>java.lang.NoClassDefFoundError: org/springframework/core/AttributeAccessorSupport
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:634)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:277)
at java.net.URLClassLoader.access$000(URLClassLoader.java:73)
at java.net.URLClassLoader$1.run(URLClassLoader.java:212)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:205)
at java.lang.ClassLoader.loadClass(ClassLoader.java:321)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
at java.lang.ClassLoader.loadClass(ClassLoader.java:266)
at org.springframework.test.context.TestContextManager.<init>(TestContextManager.java:117)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTestContextManager(SpringJUnit4ClassRunner.java:119)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.<init>(SpringJUnit4ClassRunner.java:108)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:532)
at org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:31)
at org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:24)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:57)
at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:29)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:57)
at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:24)
at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:51)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:123)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:104)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:164)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:110)
at org.apache.maven.surefire.booter.SurefireStarter.invokeProvider(SurefireStarter.java:175)
at org.apache.maven.surefire.booter.SurefireStarter.runSuitesInProcessWhenForked(SurefireStarter.java:107)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:68)
Caused by: java.lang.ClassNotFoundException: org.springframework.core.AttributeAccessorSupport
at java.net.URLClassLoader$1.run(URLClassLoader.java:217)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:205)
at java.lang.ClassLoader.loadClass(ClassLoader.java:321)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
at java.lang.ClassLoader.loadClass(ClassLoader.java:266)
... 36 more
</code></pre>
<p>I am using maven with the following spring version set:</p>
<pre><code><dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>3.1.1.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
</code></pre>
<p>I would be grateful for any help on this.</p>
<p>EDIT:</p>
<p>Someone suggested adding spring-core dependency as well. Although i doubt if it would make a difference, i did add it and here's what the exception looks like:</p>
<pre><code>java.lang.NoClassDefFoundError: org/springframework/beans/BeanUtils
at org.springframework.test.context.ContextLoaderUtils.resolveContextLoader(ContextLoaderUtils.java:87)
at org.springframework.test.context.ContextLoaderUtils.buildMergedContextConfiguration(ContextLoaderUtils.java:298)
at org.springframework.test.context.TestContext.<init>(TestContext.java:100)
at org.springframework.test.context.TestContextManager.<init>(TestContextManager.java:117)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTestContextManager(SpringJUnit4ClassRunner.java:119)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.<init>(SpringJUnit4ClassRunner.java:108)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:532)
at org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:31)
at org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:24)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:57)
at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:29)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:57)
at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:24)
at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:51)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:123)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:104)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:164)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:110)
at org.apache.maven.surefire.booter.SurefireStarter.invokeProvider(SurefireStarter.java:175)
at org.apache.maven.surefire.booter.SurefireStarter.runSuitesInProcessWhenForked(SurefireStarter.java:107)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:68)
Caused by: java.lang.ClassNotFoundException: org.springframework.beans.BeanUtils
at java.net.URLClassLoader$1.run(URLClassLoader.java:217)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:205)
at java.lang.ClassLoader.loadClass(ClassLoader.java:321)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
at java.lang.ClassLoader.loadClass(ClassLoader.java:266)
... 28 more
</code></pre> | 10,008,624 | 1 | 2 | null | 2012-04-04 09:24:41.147 UTC | 1 | 2012-04-04 09:50:15.777 UTC | 2012-04-04 09:36:35.567 UTC | null | 486,455 | null | 486,455 | null | 1 | 15 | java|spring|junit4|spring-test | 38,162 | <p>Is that your whole pom? if not you need to include spring-core, as spring-test only has it as an optional dependency</p>
<pre><code><dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${project.version}</version>
<optional>true</optional>
</dependency>
</code></pre>
<p>What optional means in the context of maven:</p>
<blockquote>
<p>Indicates the dependency is optional for use of this library. While the version of the dependency will be taken into account for dependency calculation if the library is used elsewhere, it will not be passed on transitively.</p>
</blockquote>
<p>You may need to include other spring libraries depending upon what you end up testing.</p>
<p>I was able to get your test running including the following Spring dependencies along with spring-test:</p>
<pre><code> <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.1.1.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>3.1.1.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>3.1.1.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>3.1.1.RELEASE</version>
<scope>test</scope>
</dependency>
</code></pre> |
9,712,085 | NumPy: Pretty print tabular data | <p>I would like to print NumPy tabular array data, so that it looks nice. R and database consoles seem to demonstrate good abilities to do this. However, NumPy's built-in printing of tabular arrays looks like garbage:</p>
<pre><code>import numpy as np
dat_dtype = {
'names' : ('column_one', 'col_two', 'column_3'),
'formats' : ('i', 'd', '|U12')}
dat = np.zeros(4, dat_dtype)
dat['column_one'] = range(4)
dat['col_two'] = 10**(-np.arange(4, dtype='d') - 4)
dat['column_3'] = 'ABCD'
dat['column_3'][2] = 'long string'
print(dat)
# [(0, 1.e-04, 'ABCD') (1, 1.e-05, 'ABCD') (2, 1.e-06, 'long string')
# (3, 1.e-07, 'ABCD')]
</code></pre>
<p>I would like something that looks more like what a database spits out, for example, postgres-style:</p>
<pre><code> column_one | col_two | column_3
------------+---------+-------------
0 | 0.0001 | ABCD
1 | 1e-05 | ABCD
2 | 1e-08 | long string
3 | 1e-07 | ABCD
</code></pre>
<p>Are there any good third-party Python libraries to format nice looking ASCII tables?</p> | 9,713,042 | 4 | 2 | null | 2012-03-14 23:52:05.9 UTC | 5 | 2022-04-14 13:49:10.227 UTC | 2021-06-01 21:32:17.71 UTC | null | 327,026 | null | 327,026 | null | 1 | 17 | python|numpy|pretty-print|tabular | 59,562 | <p>I seem to be having good output with <a href="https://github.com/jazzband/prettytable" rel="nofollow noreferrer">prettytable</a>:</p>
<pre><code>from prettytable import PrettyTable
x = PrettyTable(dat.dtype.names)
for row in dat:
x.add_row(row)
# Change some column alignments; default was 'c'
x.align['column_one'] = 'r'
x.align['col_two'] = 'r'
x.align['column_3'] = 'l'
</code></pre>
<p>And the output is not bad. There is even a <code>border</code> switch, among a few other options:</p>
<pre><code>>>> print(x)
+------------+---------+-------------+
| column_one | col_two | column_3 |
+------------+---------+-------------+
| 0 | 0.0001 | ABCD |
| 1 | 1e-05 | ABCD |
| 2 | 1e-06 | long string |
| 3 | 1e-07 | ABCD |
+------------+---------+-------------+
>>> print(x.get_string(border=False))
column_one col_two column_3
0 0.0001 ABCD
1 1e-05 ABCD
2 1e-06 long string
3 1e-07 ABCD
</code></pre> |
10,219,253 | MyBatis enum usage | <p>I know this has been asked before, but I wasn't able to implement a solution based on the information I found so far. so perhaps someone can explain it to me.</p>
<p>I have a table "status". It has two columns:id and name. id is a PK.</p>
<p>Instead of using a POJO Status, I would like to use an enum. I created such an enum as follows:</p>
<pre><code>public enum Status {
NEW(1), READY(2), CLOSED(3);
private int id;
public void setId(int id) {
this.id = id;
}
public int getId() {
return this.id;
}
Status(int id) {
this.id = id;
}
}
</code></pre>
<p>here is my mapper
</p>
<pre><code> <select id="getStatusByName" resultType="Status" parameterType="String">
SELECT ls.id, ls.name
FROM status AS ls
WHERE ls.name = #{name}
</select>
</code></pre>
<p></p>
<p>but for some reason, when I try to retrieve an enum, something breaks, but no exception is thrown.</p> | 10,941,840 | 2 | 1 | null | 2012-04-18 22:53:26.643 UTC | 7 | 2016-02-08 22:11:39.033 UTC | null | null | null | null | 1,110,612 | null | 1 | 18 | java|mysql|enums|mybatis | 39,880 | <p>I have worked on this question from a couple of angles and here are my findings. Caveat: I did all these investigations using MyBatis-3.1.1, so things might have behaved differently in earlier versions.</p>
<p>First, MyBatis has a built-in <code>EnumTypeHandler</code>. By default, any time you specify a Java enum as a resultType or parameterType, this is what will handle that type. For queries, when trying to convert a database record into a Java enum, the EnumTypeHandler only takes one argument and tries to look up the Java enum value that corresponds to that value.</p>
<p>An example will better illustrate. Suppose your query above returns <code>2</code> and <code>"Ready"</code> when I pass in "Ready" as the argument. In that case, I get the error message <code>No enum constant com.foo.Status.2</code>. If I reverse the order of your SELECT statement to be </p>
<pre class="lang-sql prettyprint-override"><code>SELECT ls.name, ls.id
</code></pre>
<p>then the error message is <code>No enum constant com.foo.Status.Ready</code>. I assume you can infer what MyBatis is doing. Note that the EnumTypeHandler is ignoring the second value returned from the query.</p>
<p>Changing your query to</p>
<pre class="lang-sql prettyprint-override"><code>SELECT UPPER(ls.name)
</code></pre>
<p>causes it to work: the Status.READY enum is returned.</p>
<p>So next I tried to define my own TypeHandler for the Status enum. Unfortunately, as with the default <code>EnumTypeHandler</code>, I could only get one of the values (id or name) in order to reference the right Enum, not both. So if the database id does not match the value you hardcoded above, then you will have a mismatch. If you ensure that the database id always matches the id you specify in the enum, then all you need from the database is the name (converted to upper case).</p>
<p>Then I thought I'd get clever and implement a MyBatis ObjectFactory, grab both the int id and String name and ensure those are matched up in the Java enum I pass back, but that did not work as MyBatis does not call the ObjectFactory for a Java enum type (at least I couldn't get it to work).</p>
<p>So my conclusion is that Java enums in MyBatis are easy as long as you just need to match up the name from the database to the enum constant name - either use the built-in EnumTypeHandler or define your own if doing UPPER(name) in the SQL isn't enough to match the Java enum names. In many cases, this is sufficient, as the enumerated value may just be a check constraint on a column and it has only the single value, not an id as well. If you need to also match up an int id as well as a name, then make the IDs match manually when setting up the Java enum and/or database entries.</p>
<p>Finally, if you'd like to see a working example of this, see koan 23 of my MyBatis koans here: <a href="https://github.com/midpeter444/mybatis-koans">https://github.com/midpeter444/mybatis-koans</a>. If you just want to see my solution, look in the completed-koans/koan23 directory. I also have an example there of inserting a record into the database via a Java enum.</p> |
9,760,236 | Method for downloading iCloud files? Very confusing? | <p>I have basic iCloud support in my application (syncing changes, making ubiquitous, etc.), but one crucial omission so far has been the lack of "download" support for files that exist (or have changes) in the cloud, but are not in sync with what's currently on disk.</p>
<p>I added the following methods to my application, based on some Apple-provided code, with a couple tweaks:</p>
<p>The download methods:</p>
<pre><code>- (BOOL)downloadFileIfNotAvailable:(NSURL*)file {
NSNumber* isIniCloud = nil;
if ([file getResourceValue:&isIniCloud forKey:NSURLIsUbiquitousItemKey error:nil]) {
// If the item is in iCloud, see if it is downloaded.
if ([isIniCloud boolValue]) {
NSNumber* isDownloaded = nil;
if ([file getResourceValue:&isDownloaded forKey:NSURLUbiquitousItemIsDownloadedKey error:nil]) {
if ([isDownloaded boolValue])
return YES;
// Download the file.
NSFileManager* fm = [NSFileManager defaultManager];
NSError *downloadError = nil;
[fm startDownloadingUbiquitousItemAtURL:file error:&downloadError];
if (downloadError) {
NSLog(@"Error occurred starting download: %@", downloadError);
}
return NO;
}
}
}
// Return YES as long as an explicit download was not started.
return YES;
}
- (void)waitForDownloadThenLoad:(NSURL *)file {
NSLog(@"Waiting for file to download...");
id<ApplicationDelegate> appDelegate = [DataLoader applicationDelegate];
while (true) {
NSDictionary *fileAttribs = [[NSFileManager defaultManager] attributesOfItemAtPath:[file path] error:nil];
NSNumber *size = [fileAttribs objectForKey:NSFileSize];
[NSThread sleepForTimeInterval:0.1];
NSNumber* isDownloading = nil;
if ([file getResourceValue:&isDownloading forKey:NSURLUbiquitousItemIsDownloadingKey error:nil]) {
NSLog(@"iCloud download is moving: %d, size is %@", [isDownloading boolValue], size);
}
NSNumber* isDownloaded = nil;
if ([file getResourceValue:&isDownloaded forKey:NSURLUbiquitousItemIsDownloadedKey error:nil]) {
NSLog(@"iCloud download has finished: %d", [isDownloaded boolValue]);
if ([isDownloaded boolValue]) {
[self dispatchLoadToAppDelegate:file];
return;
}
}
NSNumber *downloadPercentage = nil;
if ([file getResourceValue:&downloadPercentage forKey:NSURLUbiquitousItemPercentDownloadedKey error:nil]) {
double percentage = [downloadPercentage doubleValue];
NSLog(@"Download percentage is %f", percentage);
[appDelegate updateLoadingStatusString:[NSString stringWithFormat:@"Downloading from iCloud (%2.2f%%)", percentage]];
}
}
}
</code></pre>
<p>And the code that starts/checks the downloads:</p>
<pre><code> if ([self downloadFileIfNotAvailable:urlToUse]) {
// The file is already available. Load.
[self dispatchLoadToAppDelegate:[urlToUse autorelease]];
} else {
// The file is downloading. Wait for it.
[self performSelector:@selector(waitForDownloadThenLoad:) withObject:[urlToUse autorelease] afterDelay:0];
}
</code></pre>
<p><strong>As far as I can tell</strong> the above code seems fine, but when I make a large number of changes on Device A, save those changes, then open Device B (to prompt a download on Device B) this is what I see in the console:</p>
<pre><code>2012-03-18 12:45:55.858 MyApp[12363:707] Waiting for file to download...
2012-03-18 12:45:58.041 MyApp[12363:707] iCloud download is moving: 0, size is 101575
2012-03-18 12:45:58.041 MyApp[12363:707] iCloud download has finished: 0
2012-03-18 12:45:58.041 MyApp[12363:707] Download percentage is 0.000000
2012-03-18 12:45:58.143 MyApp[12363:707] iCloud download is moving: 0, size is 101575
2012-03-18 12:45:58.143 MyApp[12363:707] iCloud download has finished: 0
2012-03-18 12:45:58.144 MyApp[12363:707] Download percentage is 0.000000
2012-03-18 12:45:58.246 MyApp[12363:707] iCloud download is moving: 0, size is 101575
2012-03-18 12:45:58.246 MyApp[12363:707] iCloud download has finished: 0
2012-03-18 12:45:58.246 MyApp[12363:707] Download percentage is 0.000000
2012-03-18 12:45:58.347 MyApp[12363:707] iCloud download is moving: 0, size is 177127
2012-03-18 12:45:58.347 MyApp[12363:707] iCloud download has finished: 0
2012-03-18 12:45:58.347 MyApp[12363:707] Download percentage is 0.000000
2012-03-18 12:45:58.449 MyApp[12363:707] iCloud download is moving: 0, size is 177127
2012-03-18 12:45:58.449 MyApp[12363:707] iCloud download has finished: 0
2012-03-18 12:45:58.450 MyApp[12363:707] Download percentage is 0.000000
</code></pre>
<p>So for whatever reason:</p>
<ol>
<li>The download for the file starts without error</li>
<li>The file attributes for the file's download status always return that it's not downloading, has not finished downloading, and the progress is 0 percent.</li>
<li>I'm stuck in the loop forever, even though the <em>file size changes</em> in between checks.</li>
</ol>
<p>What am I doing wrong?</p> | 23,593,943 | 4 | 0 | null | 2012-03-18 16:54:16.3 UTC | 14 | 2017-02-25 18:24:57.54 UTC | null | null | null | null | 88,111 | null | 1 | 20 | objective-c|ios|macos|icloud | 11,155 | <p>Years later I am still experiencing periodic (though much more rare after some of the workarounds in other answers) issues downloading files. So, I contacted the developers at Apple asking for a technical review/discussion and here's what I found.</p>
<p>Periodically checking for the download status of the same <code>NSURL</code>, even if you're recreating it, is not the preferred method for checking the status. I don't know why it isn't - it seems like it <em>should</em> work, but it doesn't. Instead, once you begin to download the file, you should register an observer with <code>NSNotificationCenter</code> for the progress of that download, maintaining a reference to the query for that file. Here's the exact code sample that was provided to me. I've implemented it (with some app-specific tweaks) in my app, and it seems to be performing much more appropriately.</p>
<pre><code>- (void)download:(NSURL *)url
{
dispatch_queue_t q_default;
q_default = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(q_default, ^{
NSError *error = nil;
BOOL success = [[NSFileManager defaultManager] startDownloadingUbiquitousItemAtURL:url error:&error];
if (!success)
{
// failed to download
}
else
{
NSDictionary *attrs = [url resourceValuesForKeys:@[NSURLUbiquitousItemIsDownloadedKey] error:&error];
if (attrs != nil)
{
if ([[attrs objectForKey:NSURLUbiquitousItemIsDownloadedKey] boolValue])
{
// already downloaded
}
else
{
NSMetadataQuery *query = [[NSMetadataQuery alloc] init];
[query setPredicate:[NSPredicate predicateWithFormat:@"%K > 0", NSMetadataUbiquitousItemPercentDownloadedKey]];
[query setSearchScopes:@[url]]; // scope the search only on this item
[query setValueListAttributes:@[NSMetadataUbiquitousItemPercentDownloadedKey, NSMetadataUbiquitousItemIsDownloadedKey]];
_fileDownloadMonitorQuery = query;
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(liveUpdate:)
name:NSMetadataQueryDidUpdateNotification
object:query];
[self.fileDownloadMonitorQuery startQuery];
}
}
}
});
}
- (void)liveUpdate:(NSNotification *)notification
{
NSMetadataQuery *query = [notification object];
if (query != self.fileDownloadMonitorQuery)
return; // it's not our query
if ([self.fileDownloadMonitorQuery resultCount] == 0)
return; // no items found
NSMetadataItem *item = [self.fileDownloadMonitorQuery resultAtIndex:0];
double progress = [[item valueForAttribute:NSMetadataUbiquitousItemPercentDownloadedKey] doubleValue];
NSLog(@"download progress = %f", progress);
// report download progress somehow..
if ([[item valueForAttribute:NSMetadataUbiquitousItemIsDownloadedKey] boolValue])
{
// finished downloading, stop the query
[query stopQuery];
_fileDownloadMonitorQuery = nil;
}
}
</code></pre> |
9,717,588 | Checking password match while typing | <p>I have a registration form with "password" and "confirm password" input fields. I want to check if the "confirm password" matches the "password" while the user is typing it and give the appropriate message. So I tried to do this:</p>
<p>This is the HTML:</p>
<pre><code><div class="td">
<input type="password" id="txtNewPassword" />
</div>
<div class="td">
<input type="password" id="txtConfirmPassword" onChange="checkPasswordMatch();" />
</div>
<div class="registrationFormAlert" id="divCheckPasswordMatch">
</div>
</code></pre>
<p>And this is the checkPasswordMatch() function:</p>
<pre><code>function checkPasswordMatch() {
var password = $("#txtNewPassword").val();
var confirmPassword = $("#txtConfirmPassword").val();
if (password != confirmPassword)
$("#divCheckPasswordMatch").html("Passwords do not match!");
else
$("#divCheckPasswordMatch").html("Passwords match.");
}
</code></pre>
<p>That didn't validate while typing, only when user leaves the field.</p>
<p>I tried to use onKeyUp instead of onChange - also didn't work.</p>
<p>So how can it be done?</p>
<p>Thank you!</p> | 9,717,644 | 7 | 6 | null | 2012-03-15 10:08:13.947 UTC | 23 | 2018-10-03 14:07:48.15 UTC | 2012-03-15 10:20:56.473 UTC | null | 13,508 | null | 1,231,619 | null | 1 | 41 | javascript|jquery | 158,817 | <p>Probably invalid syntax in your onChange event, I avoid using like this (within the html) as I think it is messy and it is hard enough keeping JavaScript tidy at the best of times. </p>
<p>I would rather register the event on the document ready event in javascript. You will also definitely want to use keyup event too if you want the validation as the user is typing:</p>
<pre><code>$(document).ready(function () {
$("#txtConfirmPassword").keyup(checkPasswordMatch);
});
</code></pre>
<p><a href="http://jsfiddle.net/rpP4K/" rel="noreferrer">Here is a working example</a></p>
<hr>
<p>Personally I would prefer to do the check when either password field changes, that way if they re-type the original password then you still get the same validation check:</p>
<pre><code>$(document).ready(function () {
$("#txtNewPassword, #txtConfirmPassword").keyup(checkPasswordMatch);
});
</code></pre>
<p><a href="http://jsfiddle.net/rpP4K/772/" rel="noreferrer">Here is a working example</a></p> |
27,948,093 | Include search path on Mac OS X Yosemite 10.10.1 | <p><strong>I just to change the include search path order (I believe).</strong></p>
<p><hr>
I'd like to change the include search path. Especially, I need <code>/usr/local/include</code> first.</p>
<p>But it doesn't change because of duplicate. How can I change it?</p>
<p>I suppose there's default setting, because paths I don't specify appears. Like <code>/usr/include/c++/4.2.1</code>, <code>/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/clang/6.0/include</code></p>
<pre><code> "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang" -cc1 -triple x86_64-apple-macosx10.10.0 -emit-obj -mrelax-all -disable-free -disable-llvm-verifier -main-file-name test_common.cpp -mrelocation-model pic -pic-level 2 -mdisable-fp-elim -masm-verbose -munwind-tables -target-cpu core2 -target-linker-version 241.9 -v -gdwarf-2 -coverage-file /Users/machidahiroaki/RubymineProjects/caffe/.build_debug/src/caffe/test/test_common.o -resource-dir /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/clang/6.0 -D DEBUG -D CPU_ONLY -I /usr/local/include -I /usr/local/include -I /Users/machidahiroaki/anaconda/include -I /Users/machidahiroaki/anaconda/include/python2.7 -I /Users/machidahiroaki/anaconda/lib/python2.7/site-packages/numpy/core/include -I .build_debug/src -I ./src -I ./include -I /usr/local/atlas/include -stdlib=libstdc++ -O0 -Wall -Wno-sign-compare -Wno-unneeded-internal-declaration -fdeprecated-macro -fdebug-compilation-dir /Users/machidahiroaki/RubymineProjects/caffe -ferror-limit 19 -fmessage-length 0 -pthread -stack-protector 1 -mstackrealign -fblocks -fobjc-runtime=macosx-10.10.0 -fencode-extended-block-signature -fcxx-exceptions -fexceptions -fdiagnostics-show-option -vectorize-slp -o .build_debug/src/caffe/test/test_common.o -x c++ src/caffe/test/test_common.cpp
clang -cc1 version 6.0 based upon LLVM 3.5svn default target x86_64-apple-darwin14.0.0
ignoring nonexistent directory "/usr/include/c++/4.2.1/i686-apple-darwin10/x86_64"
ignoring nonexistent directory "/usr/include/c++/4.0.0"
ignoring nonexistent directory "/usr/include/c++/4.0.0/i686-apple-darwin8/"
ignoring nonexistent directory "/usr/include/c++/4.0.0/backward"
ignoring duplicate directory "/usr/local/include"
ignoring duplicate directory "/usr/local/include"
as it is a non-system directory that duplicates a system directory
#include "..." search starts here:
#include <...> search starts here:
/Users/machidahiroaki/anaconda/include
/Users/machidahiroaki/anaconda/include/python2.7
/Users/machidahiroaki/anaconda/lib/python2.7/site-packages/numpy/core/include
.build_debug/src
./src
./include
/usr/local/atlas/include
/usr/include/c++/4.2.1
/usr/include/c++/4.2.1/backward
/usr/local/include
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/clang/6.0/include
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include
/usr/include
/System/Library/Frameworks (framework directory)
/Library/Frameworks (framework directory)
End of search list.
</code></pre>
<hr/>
<h2>Library search paths</h2>
<pre><code>Machida-no-MacBook-Air:caffe machidahiroaki$ /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ld -v ...
@(#)PROGRAM:ld PROJECT:ld64-241.9
configured to support archs: armv6 armv7 armv7s arm64 i386 x86_64 x86_64h armv6m armv7m armv7em
Library search paths:
/usr/lib
/usr/local/lib
Framework search paths:
/Library/Frameworks/
/System/Library/Frameworks/
</code></pre>
<p>For sure this is the <code>ld</code> done in <code>make</code>.</p>
<pre><code> "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ld" -demangle -dynamic -dylib -arch x86_64 -macosx_version_min 10.10.0 -t -o .build_debug/lib/libcaffe.so -L/usr/local/lib -L/usr/lib -L/usr/local/atlas/lib .build_debug/src/caffe/proto/caffe.pb.o .build_debug/src/caffe/proto/caffe_pretty_print.pb.o .build_debug/src/caffe/blob.o .build_debug/src/caffe/common.o .build_debug/src/caffe/data_transformer.o .build_debug/src/caffe/internal_thread.o .build_debug/src/caffe/layer_factory.o .build_debug/src/caffe/layers/absval_layer.o .build_debug/src/caffe/layers/accuracy_layer.o .build_debug/src/caffe/layers/argmax_layer.o .build_debug/src/caffe/layers/base_data_layer.o .build_debug/src/caffe/layers/bnll_layer.o .build_debug/src/caffe/layers/concat_layer.o .build_debug/src/caffe/layers/contrastive_loss_layer.o .build_debug/src/caffe/layers/conv_layer.o .build_debug/src/caffe/layers/cudnn_conv_layer.o .build_debug/src/caffe/layers/cudnn_pooling_layer.o .build_debug/src/caffe/layers/cudnn_relu_layer.o .build_debug/src/caffe/layers/cudnn_sigmoid_layer.o .build_debug/src/caffe/layers/cudnn_softmax_layer.o .build_debug/src/caffe/layers/cudnn_tanh_layer.o .build_debug/src/caffe/layers/data_layer.o .build_debug/src/caffe/layers/dropout_layer.o .build_debug/src/caffe/layers/dummy_data_layer.o .build_debug/src/caffe/layers/eltwise_layer.o .build_debug/src/caffe/layers/euclidean_loss_layer.o .build_debug/src/caffe/layers/flatten_layer.o .build_debug/src/caffe/layers/hdf5_data_layer.o .build_debug/src/caffe/layers/hdf5_output_layer.o .build_debug/src/caffe/layers/hinge_loss_layer.o .build_debug/src/caffe/layers/im2col_layer.o .build_debug/src/caffe/layers/image_data_layer.o .build_debug/src/caffe/layers/infogain_loss_layer.o .build_debug/src/caffe/layers/inner_product_layer.o .build_debug/src/caffe/layers/loss_layer.o .build_debug/src/caffe/layers/lrn_layer.o .build_debug/src/caffe/layers/memory_data_layer.o .build_debug/src/caffe/layers/multinomial_logistic_loss_layer.o .build_debug/src/caffe/layers/mvn_layer.o .build_debug/src/caffe/layers/neuron_layer.o .build_debug/src/caffe/layers/pooling_layer.o .build_debug/src/caffe/layers/power_layer.o .build_debug/src/caffe/layers/relu_layer.o .build_debug/src/caffe/layers/sigmoid_cross_entropy_loss_layer.o .build_debug/src/caffe/layers/sigmoid_layer.o .build_debug/src/caffe/layers/silence_layer.o .build_debug/src/caffe/layers/slice_layer.o .build_debug/src/caffe/layers/softmax_layer.o .build_debug/src/caffe/layers/softmax_loss_layer.o .build_debug/src/caffe/layers/split_layer.o .build_debug/src/caffe/layers/tanh_layer.o .build_debug/src/caffe/layers/threshold_layer.o .build_debug/src/caffe/layers/window_data_layer.o .build_debug/src/caffe/net.o .build_debug/src/caffe/solver.o .build_debug/src/caffe/syncedmem.o .build_debug/src/caffe/util/benchmark.o .build_debug/src/caffe/util/im2col.o .build_debug/src/caffe/util/insert_splits.o .build_debug/src/caffe/util/io.o .build_debug/src/caffe/util/math_functions.o .build_debug/src/caffe/util/upgrade_proto.o -framework Accelerate -lglog -lgflags -lprotobuf -lleveldb -lsnappy -llmdb -lboost_system -lhdf5_hl -lhdf5 -lopencv_core -lopencv_highgui -lopencv_imgproc -lpthread -lboost_thread-mt -lcblas -lstdc++ -lSystem /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/clang/6.0/lib/darwin/libclang_rt.osx.a
</code></pre>
<p><strong>So... where does this path <code>/usr/include/c++/4.2.1</code> come from?</strong></p>
<hr/>
<p>Did I get some hints?</p>
<pre><code>Machida-no-MacBook-Air:caffe machidahiroaki$ g++ -print-search-dirs
install: /usr/local/lib/gcc/x86_64-apple-darwin14.0.0/5.0.0/
programs: =/usr/local/libexec/gcc/x86_64-apple-darwin14.0.0/5.0.0/:/usr/local/libexec/gcc/x86_64-apple-darwin14.0.0/5.0.0/:/usr/local/libexec/gcc/x86_64-apple-darwin14.0.0/:/usr/local/lib/gcc/x86_64-apple-darwin14.0.0/5.0.0/:/usr/local/lib/gcc/x86_64-apple-darwin14.0.0/:/usr/local/lib/gcc/x86_64-apple-darwin14.0.0/5.0.0/../../../../x86_64-apple-darwin14.0.0/bin/x86_64-apple-darwin14.0.0/5.0.0/:/usr/local/lib/gcc/x86_64-apple-darwin14.0.0/5.0.0/../../../../x86_64-apple-darwin14.0.0/bin/
libraries: =/usr/local/lib/gcc/x86_64-apple-darwin14.0.0/5.0.0/:/usr/local/lib/gcc/x86_64-apple-darwin14.0.0/5.0.0/../../../../x86_64-apple-darwin14.0.0/lib/x86_64-apple-darwin14.0.0/5.0.0/:/usr/local/lib/gcc/x86_64-apple-darwin14.0.0/5.0.0/../../../../x86_64-apple-darwin14.0.0/lib/:/usr/local/lib/gcc/x86_64-apple-darwin14.0.0/5.0.0/../../../x86_64-apple-darwin14.0.0/5.0.0/:/usr/local/lib/gcc/x86_64-apple-darwin14.0.0/5.0.0/../../../:/lib/x86_64-apple-darwin14.0.0/5.0.0/:/lib/:/usr/lib/x86_64-apple-darwin14.0.0/5.0.0/:/usr/lib/
Machida-no-MacBook-Air:caffe machidahiroaki$ clang++ -print-search-dirs
programs: =/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin:/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin
libraries: =/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/clang/6.0
M
</code></pre>
<p>I don't know if it has to do with the problem...</p>
<pre><code>Machida-no-MacBook-Air:caffe machidahiroaki$ gcc -print-search-dirs
install: /usr/local/lib/gcc/x86_64-apple-darwin14.0.0/5.0.0/
programs: =/usr/local/libexec/gcc/x86_64-apple-darwin14.0.0/5.0.0/:/usr/local/libexec/gcc/x86_64-apple-darwin14.0.0/5.0.0/:/usr/local/libexec/gcc/x86_64-apple-darwin14.0.0/:/usr/local/lib/gcc/x86_64-apple-darwin14.0.0/5.0.0/:/usr/local/lib/gcc/x86_64-apple-darwin14.0.0/:/usr/local/lib/gcc/x86_64-apple-darwin14.0.0/5.0.0/../../../../x86_64-apple-darwin14.0.0/bin/x86_64-apple-darwin14.0.0/5.0.0/:/usr/local/lib/gcc/x86_64-apple-darwin14.0.0/5.0.0/../../../../x86_64-apple-darwin14.0.0/bin/
libraries: =/usr/local/lib/gcc/x86_64-apple-darwin14.0.0/5.0.0/:/usr/local/lib/gcc/x86_64-apple-darwin14.0.0/5.0.0/../../../../x86_64-apple-darwin14.0.0/lib/x86_64-apple-darwin14.0.0/5.0.0/:/usr/local/lib/gcc/x86_64-apple-darwin14.0.0/5.0.0/../../../../x86_64-apple-darwin14.0.0/lib/:/usr/local/lib/gcc/x86_64-apple-darwin14.0.0/5.0.0/../../../x86_64-apple-darwin14.0.0/5.0.0/:/usr/local/lib/gcc/x86_64-apple-darwin14.0.0/5.0.0/../../../:/lib/x86_64-apple-darwin14.0.0/5.0.0/:/lib/:/usr/lib/x86_64-apple-darwin14.0.0/5.0.0/:/usr/lib/
Machida-no-MacBook-Air:caffe machidahiroaki$ gcc --version
gcc (GCC) 5.0.0 20141005 (experimental)
Copyright (C) 2014 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
</code></pre>
<hr/>
<p><b>Wait, <code>export CFLAGS="-I/path/to/preferred/HDF5/hdf5.h"</code> would not work...</b></p>
<p>Specify nothing</p>
<pre><code>Machida-no-MacBook-Air:caffe machidahiroaki$ echo | "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang" -Wp,-v -stdlib=libstdc++ -x c++ - -fsyntax-only
clang -cc1 version 6.0 based upon LLVM 3.5svn default target x86_64-apple-darwin14.0.0
#include "..." search starts here:
#include <...> search starts here:
/usr/include/c++/4.2.1
/usr/include/c++/4.2.1/backward
/usr/local/include
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/clang/6.0/include
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include
/usr/include
/System/Library/Frameworks (framework directory)
/Library/Frameworks (framework directory)
End of search list.
</code></pre>
<p><b>Can't specify a header file!!</b></p>
<pre><code>Machida-no-MacBook-Air:caffe machidahiroaki$ echo | "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang" -Wp,-v -stdlib=libstdc++ -x c++ - -fsyntax-only -I/usr/local/include/hdf5.h
clang -cc1 version 6.0 based upon LLVM 3.5svn default target x86_64-apple-darwin14.0.0
ignoring nonexistent directory "/usr/local/include/hdf5.h"
#include "..." search starts here:
#include <...> search starts here:
/usr/include/c++/4.2.1
/usr/include/c++/4.2.1/backward
/usr/local/include
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/clang/6.0/include
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include
/usr/include
/System/Library/Frameworks (framework directory)
/Library/Frameworks (framework directory)
End of search list.
</code></pre>
<p>As expected, the duplicate directory is ignored and <b>the order does not change.</b></p>
<pre><code>Machida-no-MacBook-Air:caffe machidahiroaki$ echo | "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang" -Wp,-v -stdlib=libstdc++ -x c++ - -fsyntax-only -I/usr/local/include/
clang -cc1 version 6.0 based upon LLVM 3.5svn default target x86_64-apple-darwin14.0.0
ignoring duplicate directory "/usr/local/include"
as it is a non-system directory that duplicates a system directory
#include "..." search starts here:
#include <...> search starts here:
/usr/include/c++/4.2.1
/usr/include/c++/4.2.1/backward
/usr/local/include
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/clang/6.0/include
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include
/usr/include
/System/Library/Frameworks (framework directory)
/Library/Frameworks (framework directory)
End of search list.
</code></pre>
<hr/>
<p><strong>But, I found <code>clang</code>'s <code>-include</code> option, which is able to specify a file!</strong></p> | 27,948,194 | 3 | 5 | null | 2015-01-14 16:43:10.697 UTC | 9 | 2017-11-21 22:24:17.433 UTC | 2017-11-21 22:14:01.427 UTC | null | 63,550 | null | 2,288,621 | null | 1 | 11 | c++|xcode|macos|osx-yosemite|clang++ | 51,882 | <blockquote>
<p>I'd like to change library search path...</p>
</blockquote>
<p>At compile time, you augment the library search path with <code>-L</code>. You cannot delete paths; you can only add paths that have a "higher" preference than existing paths.</p>
<p>At runtime, you use <code>DYLD_LIBRARY_PATH</code>, <code>DYLD_FALLBACK_LIBRARY_PATH</code> and friends to change the library search path. See <a href="https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man1/dyld.1.html" rel="noreferrer"><code>dyld(1)</code> OS X Man Pages</a>.</p>
<p>Usually you use <code>DYLD_LIBRARY_PATH</code> to ensure a particular library is loaded rather than the system one. Its a way to override default behavior. <code>DYLD_FALLBACK_LIBRARY_PATH</code> is used to provide a library that's not a system one. Its less intrusive because you don't displace system paths.</p>
<h2>----------</h2>
<blockquote>
<p>I need /usr/local/include first...</p>
</blockquote>
<p>Sounds a bit odd to me, but...</p>
<pre><code>$ export DYLD_LIBRARY_PATH=/usr/local/include
$ clang ...
</code></pre>
<h2>----------</h2>
<p><strong><em>IF</em></strong> you are cross-compiling from the command line, you should do something like this. The trick is to use <code>--sysroot</code> to automatically bring in the headers and libraries for the platform, rather than hacking them with <code>-I</code>, <code>-L</code> and <code>-l</code>.</p>
<pre><code># Put cross compile tools on the PATH first
export PATH="/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/:$PATH"
# C compiler
export CC=/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang
# C++ compiler
export CXX=/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang++
# SYSROOT brings in platform headers and libraries, No need for -I, -L and -l.
SYSROOT=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS7.1.sdk
# Compiler flags
export CFLAGS="-march armv7 -march armv7s --sysroot=$SYSROOT"
# Compiler flags
export CXXFLAGS="-march armv7 -march armv7s --sysroot=$SYSROOT"
# Using defualt C++ runtime
$CXX $CXXFLAGS foo.c -o foo.exe
</code></pre>
<p>You can also specify GNU's runtime with <code>-stdlib=libstdc++</code>, and LLVM's runtime with <code>-stdlib=libc++</code>.</p>
<h2>----------</h2>
<p>Based on your updates:</p>
<blockquote>
<p><code><ld command and output omitted></code> <br>
where does this path /usr/include/c++/4.2.1 come from??</p>
</blockquote>
<p><code>/usr/include/c++/4.2.1</code> is <em>not</em> in your <strong><em>Library Search Path</em></strong>. Its just not there.</p>
<p>That's a header include path, and you specify it with <code>-I</code>.</p>
<p>If you want to see your header include paths for <code>libstdc++</code> and <code>libc++</code>, do this:</p>
<pre><code># GNU C++ runtime
$ echo | /usr/local/bin/clang++ -Wp,-v -stdlib=ibstdc++ -x c++ - -fsyntax-only
</code></pre>
<p>And:</p>
<pre><code># LLVM C++ runtime
$ echo | /usr/local/bin/clang++ -Wp,-v -stdlib=libc++ -x c++ - -fsyntax-only
</code></pre>
<p>Here's what I get on OS X 10.8.5:</p>
<p><strong>libstdc++ (GNU)</strong>:</p>
<pre><code> /usr/include/c++/4.2.1
/usr/include/c++/4.2.1/backward
/usr/local/include
/usr/local/bin/../lib/clang/3.5.0/include
/usr/include
/System/Library/Frameworks (framework directory)
/Library/Frameworks (framework directory
</code></pre>
<p><strong>libc++ (LLVM)</strong>:</p>
<pre><code> /usr/local/include
/usr/local/bin/../lib/clang/3.5.0/include
/usr/include
/System/Library/Frameworks (framework directory)
/Library/Frameworks (framework directory)
</code></pre>
<p>So <code>/usr/include/c++/4.2.1</code> is a built-in compiler path when using GNU's <code>libstdc++</code> (but not LLVM's <code>libc++</code>). I'll go even further and tell you its hard coded in LLVM/Clang sources (I build LLVM/Clang from source often):</p>
<pre><code>$ cd clang-sources/llvm
$ grep -R "/usr/include/c++/4.2.1" *
tools/clang/lib/Frontend/InitHeaderSearch.cpp: AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.2.1",
tools/clang/lib/Frontend/InitHeaderSearch.cpp: AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.2.1",
tools/clang/lib/Frontend/InitHeaderSearch.cpp: AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.2.1",
tools/clang/lib/Frontend/InitHeaderSearch.cpp: AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.2.1",
tools/clang/lib/Frontend/InitHeaderSearch.cpp: AddGnuCPlusPlusIncludePaths("/usr/include/c++/4.2.1",
</code></pre>
<p>You can add additional include paths when building LLVM/Clang with <code>--with-c-include-dirs</code>.</p>
<h2>----------</h2>
<p>Based on your comment: <em>"... If I delete ~/anaconda/include/hdf5.h..."</em>. If you need a new path for the HDF5 package, then use something like:</p>
<pre><code>export CPPFLAGS="-I/path/to/preferred/HDF5/hdf5.h"
export CFLAGS="-I/path/to/preferred/HDF5/hdf5.h"
export CXXFLAGS="-I/path/to/preferred/HDF5/hdf5.h"
export LDFLAGS="-L/path/to/preferred/HDF5/lib"
./configure ...
</code></pre>
<p>You need it in <code>CPPFLAGS</code> too because the autotools might run some tests with it.</p>
<p>Then, at runtime:</p>
<pre><code>export DYLD_LIBRARY_PATH=/path/to/preferred/HDF5/lib
./run_the_executable
</code></pre>
<p>And you can side step <code>DYLD_LIBRARY_PATH</code> <strong><em>IF</em></strong> you perform static linking against HDF5. But be aware the OS X linker always uses a shared object or dynalib <em>if</em> its available. Effectively, it ignores your request for static linking. You will have to <code>mv</code> shared object or dynalib off-path while leaving an archive on-path.</p>
<h2>----------</h2>
<p>To muddy the waters a little more... If you are saying "library" when you really want to say "framework", then see this Stack Overflow question about using the <code>-framework</code> option: <a href="https://stackoverflow.com/q/16387484/608639">Clang(LLVM) compile with frameworks</a>.</p> |
10,144,210 | Java Jar file: use resource errors: URI is not hierarchical | <p>I have deployed my app to jar file. When I need to copy data from one file of resource to outside of jar file, I do this code:</p>
<pre><code>URL resourceUrl = getClass().getResource("/resource/data.sav");
File src = new File(resourceUrl.toURI()); //ERROR HERE
File dst = new File(CurrentPath()+"data.sav"); //CurrentPath: path of jar file don't include jar file name
FileInputStream in = new FileInputStream(src);
FileOutputStream out = new FileOutputStream(dst);
// some excute code here
</code></pre>
<p>The error I have met is: <code>URI is not hierarchical</code>. this error I don't meet when run in IDE.</p>
<p>If I change above code as some help on other post on StackOverFlow:</p>
<pre><code>InputStream in = Model.class.getClassLoader().getResourceAsStream("/resource/data.sav");
File dst = new File(CurrentPath() + "data.sav");
FileOutputStream out = new FileOutputStream(dst);
//....
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) { //NULL POINTER EXCEPTION
//....
}
</code></pre> | 10,144,757 | 6 | 0 | null | 2012-04-13 15:54:36 UTC | 17 | 2021-05-14 06:53:46.103 UTC | 2014-05-30 07:34:50.443 UTC | null | 2,160,152 | null | 1,192,728 | null | 1 | 77 | java|deployment|resources|executable-jar | 101,519 | <p>You cannot do this</p>
<pre><code>File src = new File(resourceUrl.toURI()); //ERROR HERE
</code></pre>
<p>it is not a file!
When you run from the ide you don't have any error, because you don't run a jar file. In the IDE classes and resources are extracted on the file system.</p>
<p>But you can open an <code>InputStream</code> in this way:</p>
<pre><code>InputStream in = Model.class.getClassLoader().getResourceAsStream("/data.sav");
</code></pre>
<p>Remove <code>"/resource"</code>. Generally the IDEs separates on file system classes and resources. But when the jar is created they are put all together. So the folder level <code>"/resource"</code> is used only for classes and resources separation.</p>
<p>When you get a resource from classloader you have to specify the path that the resource has inside the jar, that is the real package hierarchy.</p> |
9,910,966 | How to get shell to self-detect using zsh or bash | <p>I've a question on how to tell which shell the user is using. Suppose a script that if the user is using zsh, then put PATH to his <code>.zshrc</code> and if using bash should put in .bashrc. And set rvmrc accordingly.</p>
<pre><code>#!/usr/bin/env bash
export PATH='/usr/local/bin:$PATH' >> ~/.zshrc
source ~/.zshrc
</code></pre>
<p>I've tried the following but it does not work : (</p>
<pre><code>if [[ $0 == "bash" ]]; then
export PATH='/usr/local/bin:$PATH' >> ~/.bashrc
elif [[ $0 == "zsh" ]]; then
export PATH='/usr/local/bin:$PATH' >> ~/.zshrc
fi
# ... more commands ...
if [[ $0 == "bash" ]]; then
[[ -s '/Users/`whoami`/.rvm/scripts/rvm' ]] && source '/Users/`whoami`/.rvm/scripts/rvm' >> ~/.bashrc
source ~/.bashrc
elif [[ $0 == "zsh" ]]; then
[[ -s '/Users/`whoami`/.rvm/scripts/rvm' ]] && source '/Users/`whoami`/.rvm/scripts/rvm' >> ~/.zshrc
source ~/.zshrc
fi
</code></pre> | 9,915,302 | 8 | 4 | null | 2012-03-28 15:37:09.083 UTC | 17 | 2022-08-23 13:02:40.913 UTC | 2020-04-04 16:42:52.733 UTC | null | 68,587 | null | 517,868 | null | 1 | 78 | bash|zsh|sh | 60,484 | <p>A word of warning: the question you seem to have asked, the question you meant to ask, and the question you should have asked are three different things.</p>
<p>“Which shell the user is using” is ambiguous. Your attempt looks like you're trying to determine which shell is executing your script. That's always going to be whatever you put in the <code>#!</code> line of the script, unless you meant your users to edit that script, so this isn't useful to you.</p>
<p>What you meant to ask, I think, is what the user's favorite shell is. This can't be determined fully reliably, but you can cover most cases. Check the <code>SHELL</code> environment variable. If it contains <code>fish</code>, <code>zsh</code>, <code>bash</code>, <code>ksh</code> or <code>tcsh</code>, the user's favorite shell is probably that shell. However, this is the wrong question for your problem.</p>
<p>Files like <code>.bashrc</code>, <code>.zshrc</code>, <code>.cshrc</code> and so on are shell initialization files. They are not the right place to define environment variables. An environment variable defined there would only be available in a terminal where the user launched that shell and not in programs started from a GUI. The definition would also override any customization the user may have done in a subsession.</p>
<p>The right place to define an environment variable is in a session startup file. This is mostly unrelated to the user's choice of shell. Unfortunately, there's no single place to define environment variables. On a lot of systems, <code>~/.profile</code> will work, but this is not universal. See <a href="https://unix.stackexchange.com/questions/4621/correctly-setting-environment">https://unix.stackexchange.com/questions/4621/correctly-setting-environment</a> and the other posts I link to there for a longer discussion.</p> |
9,948,517 | How to stop a PowerShell script on the first error? | <p>I want my PowerShell script to stop when any of the commands I run fail (like <code>set -e</code> in bash). I'm using both Powershell commands (<code>New-Object System.Net.WebClient</code>) and programs (<code>.\setup.exe</code>).</p> | 9,949,909 | 10 | 2 | null | 2012-03-30 18:27:33.69 UTC | 36 | 2022-01-04 13:19:03.22 UTC | 2012-03-30 19:06:30.113 UTC | null | 73,070 | null | 237,285 | null | 1 | 344 | windows|powershell | 217,088 | <p><code>$ErrorActionPreference = "Stop"</code> will get you part of the way there (i.e. this works great for cmdlets).</p>
<p>However for EXEs you're going to need to check <code>$LastExitCode</code> yourself after every exe invocation and determine whether that failed or not. Unfortunately I don't think PowerShell can help here because on Windows, EXEs aren't terribly consistent on what constitutes a "success" or "failure" exit code. Most follow the UNIX standard of 0 indicating success but not all do. Check out the <a href="http://rkeithhill.wordpress.com/2009/08/03/effective-powershell-item-16-dealing-with-errors/" rel="noreferrer">CheckLastExitCode function in this blog post</a>. You might find it useful.</p> |
11,790,241 | How can I wait for a click event to complete | <p>I add a click event handler to an element</p>
<pre><code> $(".elem").click(function(){
$.post("page.php".function(){
//code1
})
})
</code></pre>
<p>And then I trigger a click event</p>
<pre><code>$(".elem").click();
//code2
</code></pre>
<p>How can i make sure that code2 executes after code1 executes</p> | 11,790,273 | 4 | 1 | null | 2012-08-03 06:13:11.327 UTC | 8 | 2019-11-19 06:56:52.767 UTC | 2018-04-09 05:07:55.763 UTC | null | 374,437 | null | 1,545,385 | null | 1 | 19 | javascript|jquery | 78,960 | <p>(Ignoring WebWorkers) JavaScript runs on a single thread, so you can be sure that code2 will always execute after code1.</p>
<p><em>Unless</em> your code1 does something asynchronous like an Ajax call or a <code>setTimeout()</code>, in which case the triggered click handler will complete, then code2 will execute, then (eventually) the callback from the Ajax call (or <code>setTimeout()</code>, or whatever) will run.</p>
<p><strong>EDIT:</strong> For your updated question, code2 will always execute before code1, because as I said above an async Ajax callback will happen later (even if the Ajax response is very fast, it won't call the callback until the current JS finishes).</p>
<blockquote>
<p><em>"How i make sure that code2 executes after code1 executes"</em></p>
</blockquote>
<p>Using <code>.click()</code> with no params is a shortcut to <code>.trigger("click")</code>, but if you actually call <code>.trigger()</code> explicitly you can provide additional parameters that will be passed to the handler, which lets you do this:</p>
<pre><code>$(".elem").click(function(e, callback) {
$.post("page.php".function(){
//code1
if (typeof callback === "function")
callback();
});
});
$(".elem").trigger("click", function() {
// code 2 here
});
</code></pre>
<p>That is, within the click handler test whether a function has been passed in the <code>callback</code> parameter and if so call it. This means when the event occurs "naturally" there will be no callback, but when you trigger it programmatically and pass a function then that function will be executed. (Note that the parameter you pass with <code>.trigger()</code> doesn't have to be a function, it can be any type of data and you can pass more than one parameter, but for this purpose we want a function. See the <a href="http://api.jquery.com/trigger" rel="noreferrer"><code>.trigger()</code> doco</a> for more info.)</p>
<p>Demo: <a href="http://jsfiddle.net/nnnnnn/ZbRJ7/1/" rel="noreferrer">http://jsfiddle.net/nnnnnn/ZbRJ7/1/</a></p> |
11,783,407 | What's the difference between the dual and the complement of a boolean expression? | <p>Its the same thing right? Or is there a slight difference? I just wanna make sure I'm not misunderstanding anything.</p> | 11,783,677 | 7 | 2 | null | 2012-08-02 18:16:01.307 UTC | 5 | 2018-02-03 19:28:33.35 UTC | null | null | null | null | 1,285,943 | null | 1 | 24 | boolean|boolean-logic|boolean-expression|boolean-operations | 96,862 | <p>Boolean duals are generated by simply replacing ANDs with ORs and ORs with ANDs. The complements themselves are unaffected, where as the complement of an expression is the negation of the variables WITH the replacement of ANDs with ORs and vice versa.</p>
<p>Consider:</p>
<pre><code>A+B
</code></pre>
<p>Complement: <code>A'B'</code></p>
<p>Dual: <code>AB</code></p> |
11,699,206 | Cannot get searchview in actionbar to work | <p>I am pretty new to java and android development; and I have been working on an app in which I want an action bar with a <code>SearchView</code>. I have looked at the google examples but I can not get it to work. I must be doing something wrong and I'm about to give up on app-development :D I have searched but I have not found anything helpful. Maybe you guys can help me :)</p>
<p><strong>The problem</strong>: I get the search view to open as it should, but after that nothing happens at all, I've noticed that my <em>searchManager.getSearchableInfo(getComponentName())</em> returns null. Also my hint that I've given is not displayed in my search box which leads me to believing that maybe the app can't find my searchable.xml? Enough talk :)</p>
<p><strong>MainActivity.java</strong></p>
<pre><code>public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
// Get the SearchView and set the searchable configuration
SearchManager searchManager =
(SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView =
(SearchView) menu.findItem(R.id.menu_search).getActionView();
searchView.setSearchableInfo(
searchManager.getSearchableInfo(getComponentName()));
return true;
}
}
</code></pre>
<p><strong>searchable.xml</strong></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:hint="@string/search_hint"
android:label="@string/app_label">
</searchable>
</code></pre>
<p><strong>Androidmanifest</strong></p>
<pre><code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.searchapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="15" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity android:name=".SearchableActivity" >
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
</activity>
<activity
android:name=".MainActivity"
android:label="@string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data android:name="android.app.searchable"
android:resource="@xml/searchable"/>
</application>
</manifest>
</code></pre>
<p><strong>SearchableActivity.java</strong></p>
<pre><code>package com.example.searchapp;
import android.app.ListActivity;
import android.app.SearchManager;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
public class SearchableActivity extends ListActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search);
// Get the intent, verify the action and get the query
Intent intent = getIntent();
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
doMySearch(query);
}
}
private void doMySearch(String query) {
Log.d("Event",query);
}
}
</code></pre>
<p>And here is a link to the referred project, I would be eternally grateful if someone was to help me with this!</p>
<p><a href="https://www.dropbox.com/sh/z0amwhu16y1essw/Tjko051u9x/SearchApp.rar" rel="nofollow noreferrer">Source code</a></p> | 11,704,661 | 9 | 3 | null | 2012-07-28 07:35:23.173 UTC | 40 | 2019-11-03 03:14:33.737 UTC | 2018-07-03 11:55:17.627 UTC | null | 8,789,857 | null | 907,119 | null | 1 | 67 | android|android-actionbar|searchview | 35,851 | <p>Your problem is in your AndroidManifest. I had it almost exactly as you do, because that is what I get following the documentation. But it is unclear or mistaken.</p>
<p>Watching at the API Demos source I found that the "android.app.searchable" metadata must go in your "results" activity, and in the main activity (or the activity where you place the SearchView) you point to the other one with "android.app.default_searchable".</p>
<p>You can see it in the following file, which is the Manifest from my test project:</p>
<pre><code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.test"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data
android:name="android.app.default_searchable"
android:value=".SearchActivity" />
</activity>
<activity
android:name=".SearchActivity"
android:label="@string/app_name" >
<!-- This intent-filter identifies this activity as "searchable" -->
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<!-- This metadata entry provides further configuration details for searches -->
<!-- that are handled by this activity. -->
<meta-data
android:name="android.app.searchable"
android:resource="@xml/searchable" />
</activity>
</application>
</code></pre>
<p></p>
<p>It is also important that the hint and label in the searchable.xml are references, and not hardcoded strings.</p>
<p>I hope it solves your problem. It took me all day to figure it out :(</p> |
11,821,801 | Why use a ReentrantLock if one can use synchronized(this)? | <p>I'm trying to understand what makes the lock in concurrency so important if one can use <code>synchronized (this)</code>. In the dummy code below, I can do either:</p>
<ol>
<li>synchronized the entire method or synchronize the vulnerable area (<code>synchronized(this){...}</code>)</li>
<li>OR lock the vulnerable code area with a ReentrantLock.</li>
</ol>
<p>Code:</p>
<pre><code> private final ReentrantLock lock = new ReentrantLock();
private static List<Integer> ints;
public Integer getResult(String name) {
.
.
.
lock.lock();
try {
if (ints.size()==3) {
ints=null;
return -9;
}
for (int x=0; x<ints.size(); x++) {
System.out.println("["+name+"] "+x+"/"+ints.size()+". values >>>>"+ints.get(x));
}
} finally {
lock.unlock();
}
return random;
}
</code></pre> | 11,821,900 | 8 | 3 | null | 2012-08-06 02:08:39.677 UTC | 185 | 2020-06-27 20:43:33.66 UTC | 2019-03-30 06:03:00.86 UTC | null | 2,361,308 | null | 992,600 | null | 1 | 362 | java|multithreading|concurrency|synchronize|reentrantlock | 178,923 | <p>A <a href="http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/locks/ReentrantLock.html" rel="noreferrer">ReentrantLock</a> is <em>unstructured</em>, unlike <code>synchronized</code> constructs -- i.e. you don't need to use a block structure for locking and can even hold a lock across methods. An example:</p>
<pre><code>private ReentrantLock lock;
public void foo() {
...
lock.lock();
...
}
public void bar() {
...
lock.unlock();
...
}
</code></pre>
<p>Such flow is impossible to represent via a single monitor in a <code>synchronized</code> construct.</p>
<hr />
<p>Aside from that, <code>ReentrantLock</code> supports <a href="http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/ReentrantLock.html#tryLock()" rel="noreferrer">lock polling</a> and <a href="http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/ReentrantLock.html#tryLock(long,%20java.util.concurrent.TimeUnit)" rel="noreferrer">interruptible lock waits that support time-out</a>. <code>ReentrantLock</code> also has support for <a href="http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/ReentrantLock.html#ReentrantLock(boolean)" rel="noreferrer">configurable <em>fairness</em> policy</a>, allowing more flexible thread scheduling.</p>
<blockquote>
<p>The constructor for this class accepts an optional <em>fairness</em> parameter. When set <code>true</code>, under contention, locks favor granting access to the longest-waiting thread. Otherwise this lock does not guarantee any particular access order. Programs using fair locks accessed by many threads may display lower overall throughput (i.e., are slower; often much slower) than those using the default setting, but have smaller variances in times to obtain locks and guarantee lack of starvation. Note however, that fairness of locks does not guarantee fairness of thread scheduling. Thus, one of many threads using a fair lock may obtain it multiple times in succession while other active threads are not progressing and not currently holding the lock. Also note that the untimed <code>tryLock</code> method does not honor the fairness setting. It will succeed if the lock is available even if other threads are waiting.</p>
</blockquote>
<hr />
<p><code>ReentrantLock</code> <strong>may</strong> also be <a href="http://lycog.com/concurency/performance-reentrantlock-synchronized/" rel="noreferrer"><strong>more scalable</strong></a>, performing much better under higher contention. You can read more about this <a href="http://www.ibm.com/developerworks/java/library/j-jtp10264/" rel="noreferrer">here</a>.</p>
<p>This claim has been contested, however; see the following comment:</p>
<blockquote>
<p>In the reentrant lock test, a new lock is created each time, thus there is no exclusive locking and the resulting data is invalid. Also, the IBM link offers no source code for the underlying benchmark so its impossible to characterize whether the test was even conducted correctly.</p>
</blockquote>
<hr />
<p>When should you use <code>ReentrantLock</code>s? According to that developerWorks article...</p>
<blockquote>
<p>The answer is pretty simple -- use it when you actually need something it provides that <code>synchronized</code> doesn't, like timed lock waits, interruptible lock waits, non-block-structured locks, multiple condition variables, or lock polling. <code>ReentrantLock</code> also has scalability benefits, and you should use it if you actually have a situation that exhibits high contention, but remember that the vast majority of <code>synchronized</code> blocks hardly ever exhibit any contention, let alone high contention. I would advise developing with synchronization until synchronization has proven to be inadequate, rather than simply assuming "the performance will be better" if you use <code>ReentrantLock</code>. Remember, these are advanced tools for advanced users. (And truly advanced users tend to prefer the simplest tools they can find until they're convinced the simple tools are inadequate.) As always, make it right first, and then worry about whether or not you have to make it faster.</p>
</blockquote>
<hr />
<p>One final aspect that's gonna become more relevant in the near future has to do with <a href="http://cr.openjdk.java.net/%7Erpressler/loom/loom/sol1_part1.html#pinning" rel="noreferrer">Java 15 and Project Loom</a>. In the (new) world of virtual threads, the underlying scheduler would be able to work much better with <code>ReentrantLock</code> than it's able to do with <code>synchronized</code>, that's true at least in the initial Java 15 release but may be optimized later.</p>
<blockquote>
<p>In the current Loom implementation, a virtual thread can be pinned in two situations: when there is a native frame on the stack — when Java code calls into native code (JNI) that then calls back into Java — and when inside a <code>synchronized</code> block or method. In those cases, blocking the virtual thread will block the physical thread that carries it. Once the native call completes or the monitor released (the <code>synchronized</code> block/method is exited) the thread is unpinned.</p>
</blockquote>
<blockquote>
<p>If you have a common I/O operation guarded by a <code>synchronized</code>, replace the monitor with a <code>ReentrantLock</code> to let your application benefit fully from Loom’s scalability boost even before we fix pinning by monitors (or, better yet, use the higher-performance <code>StampedLock</code> if you can).</p>
</blockquote> |
11,874,234 | Difference between \w and \b regular expression meta characters | <p>Can anyone explain the difference between <code>\b</code> and <code>\w</code> regular expression metacharacters? It is my understanding that both these metacharacters are used for word boundaries. Apart from this, which meta character is efficient for multilingual content?</p> | 11,874,899 | 5 | 1 | null | 2012-08-08 22:38:56.033 UTC | 46 | 2021-11-13 13:00:25.763 UTC | 2021-11-13 13:00:25.763 UTC | null | 3,689,450 | null | 377,407 | null | 1 | 159 | regex | 240,277 | <p>The metacharacter <code>\b</code> is an anchor like the caret and the dollar sign. It matches at a position that is called a <strong>"word boundary"</strong>. This match is zero-length.</p>
<p>There are three different positions that qualify as word boundaries:</p>
<ul>
<li>Before the first character in the string, if the first character is
a word character.</li>
<li>After the last character in the string, if the
last character is a word character.</li>
<li>Between two characters in the
string, where one is a word character and the other is not a word character. </li>
</ul>
<p>Simply put: <code>\b</code> allows you to perform a <strong>"whole words only"</strong> search using a regular expression in the form of <code>\bword\b</code>. A <strong>"word character"</strong> is a character that can be used to form words. All characters that are not <strong>"word characters"</strong> are <strong>"non-word characters"</strong>.</p>
<p>In all flavors, the characters <code>[a-zA-Z0-9_]</code> are word characters. These are also matched by the short-hand character class <code>\w</code>. Flavors showing <strong>"ascii"</strong> for word boundaries in the flavor comparison recognize only these as word characters.</p>
<p><code>\w</code> stands for <strong>"word character"</strong>, usually <code>[A-Za-z0-9_]</code>. Notice the inclusion of the underscore and digits.</p>
<p><code>\B</code> is the negated version of <code>\b</code>. <code>\B</code> matches at every position where <code>\b</code> does not. Effectively, <code>\B</code> matches at any position between two word characters as well as at any position between two non-word characters.</p>
<p><code>\W</code> is short for <code>[^\w]</code>, the negated version of <code>\w</code>.</p> |
20,285,970 | Form resetting is not working | <p>I'm using the following code to reset the form fields.</p>
<pre><code>document.getElementById("form1").reset();//form1 is the form id.
</code></pre>
<p>It is not working. I also tried with <code>JQuery</code>. Even JQuery also not working.</p>
<pre><code>$("#reset").click(function(){
$('form1')[0].reset();
});
</code></pre>
<p>My html code is</p>
<pre><code><form name="form1" id="form1" method="post">
<h3>Personal Information</h3>
<h4>Name</h4>
<input type="text" id="fname" name="fname" maxlength=50 size=11/>
<input type="text" id="mname" name="mname" maxlength=15 size=8/>
<input type="text" id="lname" name="lname" maxlength=50 size=11/>
<input type="button" id="reset" value="Reset" onclick="Reset()"/>
</form>
</code></pre>
<p>I'm following <a href="http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_form_reset" rel="noreferrer">W3Schools</a>. Here is my <a href="http://jsfiddle.net/ty9rU/" rel="noreferrer">Fiddle</a>. Can you please explain the mistake?</p> | 20,286,240 | 8 | 10 | null | 2013-11-29 12:35:19.483 UTC | 1 | 2020-01-22 15:58:27.89 UTC | 2013-11-29 13:04:16.133 UTC | null | 2,223,788 | null | 2,223,788 | null | 1 | 11 | javascript|jquery|html|forms|reset | 54,763 | <p>I finally solved my issue. the problem is <code>"id=reset"</code>. Because it overrides the <code>reset</code> method . I changed it to <code>id="reset1"</code>. Now it is working</p> |
3,873,636 | No response from MediaWiki API using jQuery | <p>I've tried to get some content from Wikipedia as JSON:</p>
<pre><code>$.getJSON("http://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&titles="+title+"&format=json", function(data) {
doSomethingWith(data);
});
</code></pre>
<p>But I got nothing in response. If I paste to the browser's adress bar, something like</p>
<pre><code>http://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&titles=jQuery&format=json
</code></pre>
<p>I get the expected content. What's wrong?</p> | 3,873,658 | 4 | 0 | null | 2010-10-06 14:36:26.1 UTC | 10 | 2017-12-09 15:02:26.47 UTC | 2015-08-24 13:58:06.027 UTC | null | 3,576,214 | null | 468,079 | null | 1 | 14 | jquery|json|cross-domain|response|wikipedia-api | 15,518 | <p>You need to trigger JSONP behavior with <a href="http://api.jquery.com/jQuery.getJSON/" rel="noreferrer"><code>$.getJSON()</code></a> by adding <code>&callback=?</code> on the querystring, like this:</p>
<pre><code>$.getJSON("http://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&titles="+title+"&format=json&callback=?", function(data) {
doSomethingWith(data);
});
</code></pre>
<p><a href="http://jsfiddle.net/nick_craver/FPhcr/" rel="noreferrer">You can test it here</a>.</p>
<p>Without using JSONP you're hitting the <a href="http://en.wikipedia.org/wiki/Same_origin_policy" rel="noreferrer">same-origin policy</a> which is blocking the XmlHttpRequest from getting any data back.</p> |
3,604,681 | jQuery, find li class name (inside ul) | <p>I have ul with a number of li inside. All li have an id "#category" but different classes (like ".tools", ".milk", ".apple").</p>
<p>Using jQuery. I do : </p>
<pre><code>$("li#category").click(function(){ some_other_thing ( .... )});
</code></pre>
<p>now i have to put a li's class "name" — (a string indeed) inside the some_other_thing() function instead of ....</p>
<p>How it can be done?</p> | 3,604,705 | 5 | 0 | null | 2010-08-30 22:24:10.567 UTC | null | 2015-09-09 05:42:42.827 UTC | 2010-08-30 22:29:50.06 UTC | null | 1,843,422 | null | 1,843,422 | null | 1 | 6 | javascript|jquery | 41,860 | <pre><code>$(this).attr('class')
</code></pre> |
3,233,379 | Why is "out of range" not thrown for 'substring(startIndex, endIndex)' | <p>In Java I am using the <code>substring()</code> method and I'm not sure why it is not throwing an "out of index" error.</p>
<p>The string <code>abcde</code> has index start from 0 to 4, but the <code>substring()</code> method takes startIndex and endIndex as arguments based on the fact that I can call foo.substring(0) and get "abcde".</p>
<p>Then why does substring(5) work? That index should be out of range. What is the explanation?</p>
<pre><code>/*
1234
abcde
*/
String foo = "abcde";
System.out.println(foo.substring(0));
System.out.println(foo.substring(1));
System.out.println(foo.substring(2));
System.out.println(foo.substring(3));
System.out.println(foo.substring(4));
System.out.println(foo.substring(5));
</code></pre>
<p>This code outputs:</p>
<pre><code>abcde
bcde
cde
de
e
//foo.substring(5) output nothing here, isn't this out of range?
</code></pre>
<p>When I replace 5 with 6:</p>
<pre><code>foo.substring(6)
</code></pre>
<p>Then I get error:</p>
<pre><code>Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: -1
</code></pre> | 3,233,398 | 6 | 0 | null | 2010-07-13 00:36:34.44 UTC | 2 | 2018-02-08 20:16:29.093 UTC | 2018-02-08 20:16:29.093 UTC | null | 63,550 | null | 355,044 | null | 1 | 18 | java|substring | 72,211 | <p>According to the <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#substring-int-int-" rel="noreferrer">Java API doc</a>, substring throws an error when the start index is greater than the <em>Length</em> of the String.</p>
<blockquote>
<p>IndexOutOfBoundsException - if
beginIndex is negative or larger than
the length of this String object.</p>
</blockquote>
<p>In fact, they give an example much like yours:</p>
<pre><code>"emptiness".substring(9) returns "" (an empty string)
</code></pre>
<p>I guess this means it is best to think of a Java String as the following, where an index is wrapped in <code>|</code>:</p>
<pre><code>|0| A |1| B |2| C |3| D |4| E |5|
</code></pre>
<p>Which is to say a string has both a start and end index.</p> |
3,683,302 | How to find out what algorithm [ encryption ] are supported by my JVM? | <p>I am using Jasypt for encryption. This is my code:</p>
<pre><code>public class Encryptor {
private final static StandardPBEStringEncryptor pbeEncryptor = new StandardPBEStringEncryptor();
private final static String PASSWORD = "FBL";
private final static String ALGORITHM = "PBEWithMD5AndTripleDES";
static{
pbeEncryptor.setPassword( PASSWORD );
//pbeEncryptor.setAlgorithm( ALGORITHM );
}
public static String getEncryptedValue( String text ){
return pbeEncryptor.encrypt( text );
}
public static String getDecryptedValue( String text ){
return pbeEncryptor.decrypt( text );
}
}
</code></pre>
<p>Uncomment the <code>setAlgorithm</code> line and it will throw an exception</p>
<blockquote>
<p><strong>org.jasypt.exceptions.EncryptionOperationNotPossibleException</strong>:
Encryption raised an excep tion. A
possible cause is you are using strong
encryption algorithms and you have not
installed the Java Cryptography Ex
tension (JCE) Unlimited Strength
Jurisdiction Policy Files in this Java
Virtual Machine</p>
</blockquote>
<p>api says:</p>
<blockquote>
<p>Sets the algorithm to be used for
encryption Sets the algorithm to be
used for encryption, like
PBEWithMD5AndDES.</p>
<p>This algorithm has to be supported by
your JCE provider (if you specify one,
or the default JVM provider if you
don't) and, if it is supported, you
can also specify mode and padding for
it, like ALGORITHM/MODE/PADDING.</p>
</blockquote>
<p>refer: <a href="http://www.jasypt.org/api/jasypt/apidocs/org/jasypt/encryption/pbe/StandardPBEStringEncryptor.html#setAlgorithm%28java.lang.String%29" rel="noreferrer">http://www.jasypt.org/api/jasypt/apidocs/org/jasypt/encryption/pbe/StandardPBEStringEncryptor.html#setAlgorithm%28java.lang.String%29</a></p>
<p>Now, when you comment 'setAlgorithm' it will use the default Algorithm [ i guess it is md5 ], and it will work fine. That means md5 is supported by my JVM. Now, how to find out what other encryption algorithms are supported by my JVM.</p>
<p>Thanks,</p> | 3,683,915 | 6 | 0 | null | 2010-09-10 08:53:16.04 UTC | 13 | 2021-06-11 08:53:16.753 UTC | null | null | null | null | 94,813 | null | 1 | 32 | java|encryption|jvm|jasypt | 39,603 | <p>The following will list all the providers and the algorithms supporter. What version of Java are you using? Unless you're on an old version JCE should be included as standard.</p>
<pre><code>import java.security.Provider;
import java.security.Security;
public class SecurityListings {
public static void main(String[] args) {
for (Provider provider : Security.getProviders()) {
System.out.println("Provider: " + provider.getName());
for (Provider.Service service : provider.getServices()) {
System.out.println(" Algorithm: " + service.getAlgorithm());
}
}
}
}
</code></pre>
<p>Edit:
Any reason why you don't use the standard stuff from the javax.crypto package?</p>
<p>1) Generate a <code>Key</code> using</p>
<pre><code>Key key = SecretKeyFactory.getInstance(algorithm).generateSecret(new PBEKeySpec(password.toCharArray()));
</code></pre>
<p>2) Create a <code>Cipher</code> using</p>
<pre><code>cipher = Cipher.getInstance(algorithm);
</code></pre>
<p>3) Init your cipher with the key</p>
<pre><code>cipher.init(Cipher.ENCRYPT_MODE, key);
</code></pre>
<p>4) Do the encrypting with</p>
<pre><code>byte[] encrypted = cipher.doFinal(data)
</code></pre> |
3,885,095 | Multiply vector elements by a scalar value using STL | <p>Hi I want to (multiply,add,etc) vector by scalar value for example <code>myv1 * 3</code> , I know I can do a function with a forloop , but is there a way of doing this using STL function? Something like the {Algorithm.h :: transform function }?</p> | 3,885,136 | 6 | 0 | null | 2010-10-07 19:18:19.503 UTC | 18 | 2022-06-30 12:18:54.177 UTC | 2014-05-10 18:55:07.683 UTC | null | 3,234,422 | null | 263,215 | null | 1 | 50 | c++|stl|vector|element|operation | 80,954 | <p>Yes, using <code>std::transform</code>:</p>
<pre><code>std::transform(myv1.begin(), myv1.end(), myv1.begin(),
std::bind(std::multiplies<T>(), std::placeholders::_1, 3));
</code></pre>
<p>Before C++17 you could use <code>std::bind1st()</code>, which was deprecated in C++11.</p>
<pre><code>std::transform(myv1.begin(), myv1.end(), myv1.begin(),
std::bind1st(std::multiplies<T>(), 3));
</code></pre>
<p>For the placeholders;</p>
<pre><code>#include <functional>
</code></pre> |
3,221,314 | asynchronous programming in python | <p>Is there a generic notion of asynchronous programming in python? Could I assign a callback to a function, execute it and return to the main program flow immediately, no matter how long the execution of that function would take?</p> | 3,221,320 | 6 | 2 | null | 2010-07-11 00:03:35.31 UTC | 25 | 2018-03-14 23:13:01.703 UTC | 2010-07-11 00:11:02.74 UTC | null | 23,199 | null | 282,307 | null | 1 | 58 | python|asynchronous | 65,100 | <p>Take a look here:</p>
<p><a href="http://xph.us/2009/12/10/asynchronous-programming-in-python.html" rel="noreferrer">Asynchronous Programming in Python</a></p>
<p><a href="http://krondo.com/blog/?p=1247" rel="noreferrer">An Introduction to Asynchronous Programming and Twisted</a></p>
<p>Worth checking out:</p>
<p><a href="https://plus.google.com/103282573189025907018/posts/6gLX8Nhk5WM" rel="noreferrer">asyncio (previously Tulip) has been checked into the Python default branch</a></p>
<h3>Edited on 14-Mar-2018</h3>
<p>Today Python has <a href="https://docs.python.org/3/library/asyncio.html" rel="noreferrer">asyncIO — Asynchronous I/O, event loop, coroutines and tasks</a> built in.</p>
<p>Description taken from the link above:</p>
<blockquote>
<p>The <strong>asyncIO</strong> module provides infrastructure for writing single-threaded
concurrent code using coroutines, multiplexing I/O access over sockets
and other resources, running network clients and servers, and other
related primitives. Here is a more detailed list of the package
contents:</p>
<ol>
<li>a pluggable event loop with various system-specific implementations;</li>
<li>transport and protocol abstractions (similar to those in Twisted);</li>
<li>concrete support for TCP, UDP, SSL, subprocess pipes, delayed calls,
and others (some may be system-dependent);</li>
<li>a Future class that mimics the one in the concurrent.futures module, but adapted for use with the event loop;</li>
<li>coroutines and tasks based on yield from (PEP 380), to
help write concurrent code in a sequential fashion;</li>
<li>cancellation support for Futures and coroutines;</li>
<li>synchronization primitives for use
between coroutines in a single thread, mimicking those in the
threading module;</li>
<li>an interface for passing work off to a threadpool,
for times when you absolutely, positively have to use a library that
makes blocking I/O calls.</li>
</ol>
<p>Asynchronous programming is more complex
than classical “sequential” programming: see the <a href="https://docs.python.org/3/library/asyncio-dev.html#asyncio-dev" rel="noreferrer">Develop with asyncio
page</a> which lists common traps and explains how to avoid them. Enable
the debug mode during development to detect common issues.</p>
</blockquote>
<p>Also worth checking out:</p>
<p><a href="https://medium.freecodecamp.org/a-guide-to-asynchronous-programming-in-python-with-asyncio-232e2afa44f6" rel="noreferrer">A guide to asynchronous programming in Python with asyncIO</a></p> |
3,407,857 | Only inserting a row if it's not already there | <p>I had always used something similar to the following to achieve it:</p>
<pre><code>INSERT INTO TheTable
SELECT
@primaryKey,
@value1,
@value2
WHERE
NOT EXISTS
(SELECT
NULL
FROM
TheTable
WHERE
PrimaryKey = @primaryKey)
</code></pre>
<p>...but once under load, a primary key violation occurred. This is the only statement which inserts into this table at all. So does this mean that the above statement is not atomic?</p>
<p>The problem is that this is almost impossible to recreate at will.</p>
<p>Perhaps I could change it to the something like the following:</p>
<pre><code>INSERT INTO TheTable
WITH
(HOLDLOCK,
UPDLOCK,
ROWLOCK)
SELECT
@primaryKey,
@value1,
@value2
WHERE
NOT EXISTS
(SELECT
NULL
FROM
TheTable
WITH
(HOLDLOCK,
UPDLOCK,
ROWLOCK)
WHERE
PrimaryKey = @primaryKey)
</code></pre>
<p>Although, maybe I'm using the wrong locks or using too much locking or something.</p>
<p>I have seen other questions on stackoverflow.com where answers are suggesting a "IF (SELECT COUNT(*) ... INSERT" etc., but I was always under the (perhaps incorrect) assumption that a single SQL statement would be atomic.</p>
<p>Does anyone have any ideas?</p> | 3,408,196 | 7 | 6 | null | 2010-08-04 16:56:10.703 UTC | 28 | 2022-05-26 13:57:59.97 UTC | 2016-02-10 14:26:08.723 UTC | null | 2,404,470 | null | 411,051 | null | 1 | 77 | sql|sql-server|tsql|concurrency|locking | 41,676 | <p>What about the <a href="http://acronymfinder.com/JFDI.html" rel="noreferrer">"JFDI"</a> pattern?</p>
<pre><code>BEGIN TRY
INSERT etc
END TRY
BEGIN CATCH
IF ERROR_NUMBER() <> 2627
RAISERROR etc
END CATCH
</code></pre>
<p>Seriously, this is quickest and the most concurrent without locks, especially at high volumes.
What if the UPDLOCK is escalated and the whole table is locked?</p>
<p><a href="https://web.archive.org/web/20170514175218/http://sqlblog.com/blogs/paul_nielsen/archive/2007/12/12/10-lessons-from-35k-tps.aspx" rel="noreferrer">Read lesson 4</a>:</p>
<blockquote>
<p><strong>Lesson 4:</strong> When developing the upsert proc prior to tuning the indexes, I first trusted that the <code>If Exists(Select…)</code> line would fire for any item and would prohibit duplicates. Nada. In a short time there were thousands of duplicates because the same item would hit the upsert at the same millisecond and both transactions would see a not exists and perform the insert. After much testing the solution was to use the unique index, catch the error, and retry allowing the transaction to see the row and perform an update instead an insert.</p>
</blockquote> |
3,475,601 | Accessing a protected member variable outside a class | <p>I'm querying for the ID of a field by accessing a class function which someone has already put in place. The result is a object returned with protected member variables. I'm struggling to see how I can access the member variable values outside the class.</p> | 3,476,290 | 8 | 2 | null | 2010-08-13 09:33:32.873 UTC | 2 | 2020-05-01 18:25:22.967 UTC | 2010-08-13 09:38:05.013 UTC | null | 12,405 | user275074 | null | null | 1 | 17 | php|class|variables|member|protected | 46,720 | <p>Just add a "get" method to the class.</p>
<pre><code>class Foo
{
protected $bar = 'Hello World!';
public function getBar()
{
return $this->bar;
}
}
$baz = new Foo();
echo $baz->getBar();
</code></pre> |
8,222,809 | Recognize the backspace and spacebar with jQuery | <p>when a user clicks the spacebar or backspace I need to create a variable that stores the action so I can use it to manipulate an array. I want the backspace to delete a value in an array and the spacebar to create a space. How can I do this?</p> | 8,222,835 | 4 | 0 | null | 2011-11-22 06:22:31.373 UTC | 4 | 2017-09-27 08:01:11.24 UTC | null | null | null | null | 1,029,365 | null | 1 | 34 | javascript|jquery | 52,039 | <p>Maybe this can help you:</p>
<pre><code>$('body').keyup(function(e){
if(e.keyCode == 8){
// user has pressed backspace
array.pop();
}
if(e.keyCode == 32){
// user has pressed space
array.push('');
}
});
</code></pre> |
8,047,454 | jQuery animate scroll | <p>I'm not sure how to call the effect, but can someone point me into a library that would help me do the same effect as this website?</p>
<p><a href="http://www.makr.com">http://www.makr.com</a></p>
<p>Basically, it moves up the row to the top of the page on mouse click. A code snippet, preferably jQuery, can help to, if there is no such specialized effect library for it.</p>
<p>Im not sure if i need to start another topic, but can anyone help me with a small jQuery snippet to achieve the whole effect of the Makr UI?</p> | 8,047,537 | 5 | 4 | null | 2011-11-08 08:00:58.027 UTC | 18 | 2020-04-08 22:10:12.32 UTC | 2011-11-10 04:05:14.84 UTC | null | 264,309 | null | 264,309 | null | 1 | 76 | jquery|user-interface|scroll|effects | 129,706 | <p>You can animate the scrolltop of the page with jQuery.</p>
<pre><code>$('html, body').animate({
scrollTop: $(".middle").offset().top
}, 2000);
</code></pre>
<p>See this site:
<a href="http://papermashup.com/jquery-page-scrolling/" rel="noreferrer">http://papermashup.com/jquery-page-scrolling/</a></p> |
4,378,795 | SQL performance: Is there any performance hit using NVarchar(MAX) instead of NVarChar(200) | <p>I am wondering if there is any disadvantage on defining a column of type nvarchar(max) instead of giving it a (smaller) maximum size.</p>
<p>I read somewhere that if the column value has more than 4?KB the remaining data will be added to an "overflow" area, which is ok.</p>
<p>I'm creating a table where most of the time the text will be of a few lines, but I was wondering if there's any advantage in setting a lower limit and then adding a validation to avoid breaking that limit.</p>
<p>Is there any restriction on the creation of indexes with nvarchar(max) column, or anything that pays for having to add the restriction on the size limit?</p>
<p>Thanks!</p> | 4,380,625 | 3 | 0 | null | 2010-12-07 16:10:07.88 UTC | 6 | 2013-10-09 07:21:30.917 UTC | null | null | null | null | 84,167 | null | 1 | 43 | sql-server|performance|indexing|nvarchar | 28,594 | <p>Strictly speaking the <code>MAX</code> types will always be a bit slower than the non-MAX types, see <a href="http://rusanu.com/2010/03/22/performance-comparison-of-varcharmax-vs-varcharn/" rel="noreferrer">Performance comparison of varchar(max) vs. varchar(N)</a>. But this difference is never visible in practice, where it just becomes noise in the overall performance driven by IO.</p>
<p>Your main concern should not be performance of MAX vs. non-MAX. You should be concerned with the question <em>it will be possible that this column will have to store more than 8000 bytes?</em> If the answer is yes, even by if is a very very unlikely yes, then the answer is obvious: use a MAX type, the pain to convert this column later to a MAX type is not worth the minor performance benefit of non-MAX types.</p>
<p>Other concerns (possibility to index that column, unavailability of ONLINE index operations for tables with MAX columns) were already addressed by Denis' answer.</p>
<p>BTW, the information about the columns over 4KB having remaining data in an overflow area is wrong. The correct information is in <a href="http://msdn.microsoft.com/en-us/library/ms189051.aspx" rel="noreferrer">Table and Index Organization</a>:</p>
<blockquote>
<p><strong>ROW_OVERFLOW_DATA Allocation Unit</strong></p>
<p>For every partition used by a table
(heap or clustered table), index, or
indexed view, there is one
ROW_OVERFLOW_DATA allocation unit.
This allocation unit contains zero (0)
pages until a data row with variable
length columns (varchar, nvarchar,
varbinary, or sql_variant) in the
IN_ROW_DATA allocation unit exceeds
the 8 KB row size limit. When the size
limitation is reached, SQL Server
moves the column with the largest
width from that row to a page in the
ROW_OVERFLOW_DATA allocation unit. A
24-byte pointer to this off-row data
is maintained on the original page.</p>
</blockquote>
<p>So is not columns over 4KB, is rows that don't fit in the free space on the page, and is not the 'remaining', is the entire column.</p> |
14,917,829 | retrieving data from SQL in VB (part 2) | <p>I am trying to populate a listbox by retrieving data from a database through sql. I have asked this question earlier but i was using a different configuration and the one i'm using now isn't giving any results.</p>
<p><a href="https://stackoverflow.com/questions/14529534/retrieving-data-in-vb-from-sql">retrieving data in VB from SQL</a></p>
<p>That is my old post. I will now provide the code to the newer version of my attempt.</p>
<pre><code>Imports System.Data.Sql
Imports System.Data.SqlClient
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim conn As New SqlConnection
conn.Open()
Dim comm As New SqlCommand("SELECT name FROM Table_1", conn)
Dim reader As SqlDataReader = comm.ExecuteReader
Dim dt As New DataTable
dt.Load(reader)
ListBox1.Items.Add(dt)
End Sub
End Class
</code></pre>
<p>If anyone would be willing to help me out i'd greatly appreciate it. If possible, use a practical approach when trying to enlighten me, as that works best.</p>
<p>edit 1</p>
<pre><code>Imports System.Data.Sql
Imports System.Data.SqlClient
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim connString As String = "Data Source=THE_SHOGUNATE\SQLEXPRESS;Initial Catalog=le_database;Integrated Security=True"
Dim conn As New SqlConnection(connString)
conn.Open()
Dim comm As New SqlCommand("SELECT name FROM Table_1", conn)
Dim reader As SqlDataReader = comm.ExecuteReader
Dim dt As New DataTable
dt.Load(reader)
ListBox1.DataSource = dt
End Sub
End Class
</code></pre>
<p>With this code the listbox populates with 6 instances of "System.Data.DataRowView" strings, 6 being the number of items in my table. How do i get the actual values?</p> | 14,917,856 | 3 | 0 | null | 2013-02-17 03:56:46.157 UTC | 1 | 2019-01-07 11:02:22.907 UTC | 2017-05-23 11:53:46.777 UTC | null | -1 | null | 1,889,231 | null | 1 | 3 | vb.net|visual-studio-2012|sql-server-2012 | 49,164 | <p>You missed the <code>connectionString</code>
<br>
If you want to populate list from DB there are many ways</p>
<p><strong>With DataReader</strong></p>
<pre><code>Imports System.Data.Sql
Imports System.Data.SqlClient
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim connectionString As String = "Data Sourec=localhost;........."
Dim conn As New SqlConnection(connectionString)
conn.Open()
Dim comm As New SqlCommand("SELECT name FROM Table_1", conn)
Dim reader As SqlDataReader = comm.ExecuteReader
/* As it is not working i commented this
listBox1.ItemsSource = dt; // use this instead of ListBox1.Items.Add(dt)
//because Add event add only one item in the list.
*/
Dim i As Integer
i=0
while reader.read()
listbox1.Items.Add(dr(i).ToString);
i++
End While
End Sub
End Class
</code></pre>
<p><strong>With DataTable</strong> </p>
<pre><code>Imports System.Data.Sql
Imports System.Data.SqlClient
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim connectionString As String = "Data Sourec=localhost;........."
Dim conn As New SqlConnection(connectionString)
conn.Open()
// Create new DataAdapter
SqlDataAdapter a = new SqlDataAdapter("SELECT * FROM EmployeeIDs", c)
// Use DataAdapter to fill DataTable
DataTable dt = new DataTable();
a.Fill(dt);
ListBox1.DataSource = dt;
ListBox1.DataTextField = "name";
End Sub
End Class
</code></pre>
<p><br>
<strong>EDIT:</strong> <br>
Other parameters of connection string depends on your security and all that. You must see this link <a href="http://www.connectionstrings.com/sql-server-2008" rel="nofollow">Connection strings for SQL Server 2008</a></p> |
4,444,758 | Huge Django Session table, normal behaviour or bug? | <p>Perhaps this is completely normal behaviour, but I feel like the <code>django_session</code> table is much larger than it should have to be.</p>
<p>First of all, I run the following cleanup command daily so the size <strong>is not</strong> caused by <strong>expired sessions</strong>:</p>
<pre><code>DELETE FROM %s WHERE expire_date < NOW()
</code></pre>
<p>The numbers:</p>
<ul>
<li>We've got about 5000 unique visitors (bots excluded) every day.</li>
<li>The <code>SESSION_COOKIE_AGE</code> is set to the default, 2 weeks</li>
<li>The table has a little over <strong>1,000,000 rows</strong></li>
</ul>
<p>So, I'm guessing that Django also generates session keys for all bots that visits the site and that the bots don't store the cookies so it continuously generates new cookies.</p>
<p>But... is this normal behaviour? Is there a setting so Django won't generate sessions for anonymous users, or atleast... no sessions for users that aren't using sessions?</p> | 4,456,686 | 4 | 0 | null | 2010-12-14 22:04:58.8 UTC | 14 | 2015-03-25 07:29:11.92 UTC | 2010-12-15 08:07:09.477 UTC | null | 54,017 | null | 54,017 | null | 1 | 22 | django|django-sessions | 5,927 | <p>After a bit of debugging I've managed to trace cause of the problem.
One of my middlewares (and most of my views) have a <code>request.user.is_authenticated()</code> in them.</p>
<p>The <code>django.contrib.auth</code> middleware sets <code>request.user</code> to <code>LazyUser()</code></p>
<p>Source: <a href="http://code.djangoproject.com/browser/django/trunk/django/contrib/auth/middleware.py?rev=14919#L13" rel="noreferrer">http://code.djangoproject.com/browser/django/trunk/django/contrib/auth/middleware.py?rev=14919#L13</a> (I don't see why there is a <code>return None</code> there, but ok...)</p>
<pre><code>class AuthenticationMiddleware(object):
def process_request(self, request):
assert hasattr(request, 'session'), "The Django authentication middleware requires session middleware to be installed. Edit your MIDDLEWARE_CLASSES setting to insert 'django.contrib.sessions.middleware.SessionMiddleware'."
request.__class__.user = LazyUser()
return None
</code></pre>
<p>The <code>LazyUser</code> calls <code>get_user(request)</code> to get the user:</p>
<p>Source: <a href="http://code.djangoproject.com/browser/django/trunk/django/contrib/auth/middleware.py?rev=14919#L5" rel="noreferrer">http://code.djangoproject.com/browser/django/trunk/django/contrib/auth/middleware.py?rev=14919#L5</a></p>
<pre><code>class LazyUser(object):
def __get__(self, request, obj_type=None):
if not hasattr(request, '_cached_user'):
from django.contrib.auth import get_user
request._cached_user = get_user(request)
return request._cached_user
</code></pre>
<p>The <code>get_user(request)</code> method does a <code>user_id = request.session[SESSION_KEY]</code></p>
<p>Source: <a href="http://code.djangoproject.com/browser/django/trunk/django/contrib/auth/__init__.py?rev=14919#L100" rel="noreferrer">http://code.djangoproject.com/browser/django/trunk/django/contrib/auth/<strong>init</strong>.py?rev=14919#L100</a></p>
<pre><code>def get_user(request):
from django.contrib.auth.models import AnonymousUser
try:
user_id = request.session[SESSION_KEY]
backend_path = request.session[BACKEND_SESSION_KEY]
backend = load_backend(backend_path)
user = backend.get_user(user_id) or AnonymousUser()
except KeyError:
user = AnonymousUser()
return user
</code></pre>
<p>Upon accessing the session sets <code>accessed</code> to true:</p>
<p>Source: <a href="http://code.djangoproject.com/browser/django/trunk/django/contrib/sessions/backends/base.py?rev=14919#L183" rel="noreferrer">http://code.djangoproject.com/browser/django/trunk/django/contrib/sessions/backends/base.py?rev=14919#L183</a></p>
<pre><code>def _get_session(self, no_load=False):
"""
Lazily loads session from storage (unless "no_load" is True, when only
an empty dict is stored) and stores it in the current instance.
"""
self.accessed = True
try:
return self._session_cache
except AttributeError:
if self._session_key is None or no_load:
self._session_cache = {}
else:
self._session_cache = self.load()
return self._session_cache
</code></pre>
<p>And that causes the session to initialize. The bug was caused by a faulty session backend that also generates a session when <code>accessed</code> is set to true... </p> |
4,662,452 | In Maven, Why Run 'mvn clean'? | <p>I am wondering what the major difference between running <code>mvn compile</code> and <code>mvn clean compile</code> are, in practicality.</p>
<p>I understand what the actual difference is, that <code>mvn clean compile</code> deletes all the generated files and starts again from scratch, but why would we want to do this? I can assume <code>mvn compile</code> will regenerate files if it's necessary, right?</p>
<p>One thing I noticed in my project was that if you had deleted a source file, without running <code>clean</code>, the compiled file remains, which usually wouldn't be a problem, but could be I suppose.</p> | 4,662,537 | 4 | 2 | null | 2011-01-11 20:47:28.227 UTC | 14 | 2022-08-02 05:17:07.393 UTC | 2018-04-12 15:02:53.02 UTC | null | 183,704 | null | 459,041 | null | 1 | 75 | java|maven | 58,890 | <p>As noted in Gareth's <a href="https://stackoverflow.com/a/4662536/139985">answer</a>, when you rename or remove a source class, Maven doesn't have sufficient information to know to remove the corresponding compiled file from the previous build. The presence of the stale file can cause unexpected runtime problems. A <code>clean</code> is required to get rid of the stale files so that they doesn't get accidentally included in WARs, JARs and so on.</p>
<p>In addition, certain plugins require a <code>clean</code> in order to work properly. For example (at least in Maven 2), the <code>maven-war-plugin</code> explodes each dependent WAR into an existing directory tree. A <code>clean</code> is required to get rid of stale files left over from previous versions of the dependent WARs.</p>
<blockquote>
<p>I can assume "mvn compile" will regenerate files if it's necessary, right?</p>
</blockquote>
<p>For mainstream plugins, that is a fair assumption. However, if you are using a plugin to generate source code components, I'd look carefully at the documentation, and at where you put the generated source code. For instance, there are a couple of unsupported plugins whose purpose is to drive the Eclipse EMF code generator.</p> |
4,582,649 | PHP sort array by two field values | <p>I've an array like this </p>
<pre>
Array (
[0] => Array( "destination" => "Sydney",
"airlines" => "airline_1",
"one_way_fare" => 100,
"return_fare => 300
),
[2] => Array( "destination" => "Sydney",
"airlines" => "airline_2",
"one_way_fare" => 150,
"return_fare => 350
),
[3] => Array( "destination" => "Sydney",
"airlines" => "airline_3",
"one_way_fare" => 180,
"return_fare => 380
)
)
</pre>
<p>How can i sort the value by return_fare asc , one_way_fare asc ?</p>
<p>I tried <a href="http://php.net/manual/en/function.array-multisort.php">array_multisort()</a> but i ended up getting mixed up data..</p>
<p>asort only works for one dimensional array, i need to sort by two values or more, how can i achieve this like in SQL, order by field1 asc,field2 asc ?</p> | 4,582,659 | 6 | 0 | null | 2011-01-03 07:09:39.573 UTC | 23 | 2022-02-02 13:10:10.163 UTC | 2012-12-06 07:56:22.44 UTC | null | 30,512 | null | 507,982 | null | 1 | 83 | php|arrays|sorting | 91,346 | <p><a href="http://www.php.net/array_multisort" rel="noreferrer"><code>array_multisort()</code></a> is the correct function, you must have messed up somehow:</p>
<pre><code>// Obtain a list of columns
foreach ($data as $key => $row) {
$return_fare[$key] = $row['return_fare'];
$one_way_fare[$key] = $row['one_way_fare'];
}
// Sort the data with volume descending, edition ascending
array_multisort($data, $return_fare, SORT_ASC, $one_way_fare, SORT_ASC);
</code></pre>
<p>If you take a look at the comments at PHP's manual page for <code>array_multisort()</code>, you can find a very helpful <code>array_orderby()</code> function which allows you to shorten the above to just this:</p>
<pre><code>$sorted = array_orderby($data, 'return_fare', SORT_ASC, 'one_way_fare', SORT_ASC);
</code></pre>
<p>To avoid the looping use <code>array_column()</code> (as of PHP 5.5.0):</p>
<pre><code>array_multisort(array_column($data, 'return_fare'), SORT_ASC,
array_column($data, 'one_way_fare'), SORT_ASC,
$data);
</code></pre> |
4,190,949 | Create multiple threads and wait for all of them to complete | <p>How can I create multiple threads and wait for all of them to complete?</p> | 4,190,969 | 8 | 0 | null | 2010-11-16 03:23:47.487 UTC | 18 | 2021-11-22 09:41:44.357 UTC | 2021-10-25 06:34:49.137 UTC | null | 446,477 | null | 496,949 | null | 1 | 84 | c#|.net|multithreading | 153,994 | <p>It depends which version of the .NET Framework you are using. .NET 4.0 made thread management a whole lot easier using Tasks:</p>
<pre><code>class Program
{
static void Main(string[] args)
{
Task task1 = Task.Factory.StartNew(() => doStuff());
Task task2 = Task.Factory.StartNew(() => doStuff());
Task task3 = Task.Factory.StartNew(() => doStuff());
Task.WaitAll(task1, task2, task3);
Console.WriteLine("All threads complete");
}
static void doStuff()
{
//do stuff here
}
}
</code></pre>
<p>In previous versions of .NET you could use the <code>BackgroundWorker</code> object, use <code>ThreadPool.QueueUserWorkItem()</code>, or create your threads manually and use <code>Thread.Join()</code> to wait for them to complete:</p>
<pre><code>static void Main(string[] args)
{
Thread t1 = new Thread(doStuff);
t1.Start();
Thread t2 = new Thread(doStuff);
t2.Start();
Thread t3 = new Thread(doStuff);
t3.Start();
t1.Join();
t2.Join();
t3.Join();
Console.WriteLine("All threads complete");
}
</code></pre> |
4,679,782 | Can I use CoffeeScript instead of JS for node.js? | <p>What are my restrictions if I want to code node.js and use CoffeeScript?
Can I do anything I'd be able to do in JS?</p> | 4,679,798 | 8 | 0 | null | 2011-01-13 12:01:35.947 UTC | 54 | 2015-10-12 20:59:48.523 UTC | 2012-12-06 12:09:22.203 UTC | null | 225,037 | null | 435,951 | null | 1 | 191 | javascript|node.js|coffeescript | 66,200 | <p>Yes, CoffeeScript simply compiles into pure JS, making it completely compatible with node.js. </p>
<p>To run CoffeeScripts on node, you can either:</p>
<ul>
<li>Type <code>coffee -c example.coffee</code> to compile, followed by <code>node example.js</code> to run the compiled JS.</li>
<li>Simply type <code>coffee example.coffee</code></li>
</ul> |
4,133,904 | PS1 line with Git current branch and colors | <p>Here is my current PS1:</p>
<pre><code>export PS1='[\u@\h \W$(__git_ps1 " (%s)")]\$ '
</code></pre>
<p>How can I display the current branch in a different color?</p> | 4,138,025 | 16 | 0 | null | 2010-11-09 13:01:03.45 UTC | 52 | 2021-09-29 08:55:26.63 UTC | 2018-09-13 20:38:54.433 UTC | null | 63,550 | null | 74,415 | null | 1 | 70 | git|command-prompt|bash | 101,312 | <p>You can wrap the part that you want in colour with the following:</p>
<p><code>\e[0;32m</code> - sets colour (in this case, to green)</p>
<p><code>\e[m</code> - sets colour back to the default</p>
<p>For example, this sets the prompt to the last token of the current path, in green, followed by <code>$</code> in the default colour:</p>
<pre><code>export PS1='\e[0;32m\w\e[m $'
</code></pre>
<p>Other colours are available too. Have a look at <a href="http://www.ibm.com/developerworks/linux/library/l-tip-prompt/" rel="noreferrer">this article</a> under colorization for a comprehensive list of alternatives.</p> |
14,821,715 | (JAVA) Use Command Prompt to create .jar file from multiple .class files | <p>I have written a .java file, called Main.java, and have compiled it using the javac in the Windows Command Prompt. The compiler is creating multiple .class files (called Main.class, Main$1.class, & Main$2.class--presumably because I have anonymous inner classes in my Main.java file). I am trying to create a runnable .jar file so I can double click a shortcut to run this application (it is a Java Swing application), but I am unsuccessful when I navigate to the directory of the three class files and type:</p>
<pre><code>jar cfv file.jar Main.class Main$1.class Main$2.class
</code></pre>
<p>The Command Prompt then outputs this text:</p>
<pre><code>added manifest
adding: Main.class(in 4871) (out = 2848)(deflated 41%)
adding: Main$1.class(in 1409) (out = 833)(deflated 40%)
adding: Main$2.class(in 1239) (out = 767)(deflated 38%)
</code></pre>
<p>Despite this, when I double click on the file.jar file in Windows Explorer, simply put, nothing happens. No swing application opens.</p>
<p>Hopefully someone can help me out with this. Thank you</p>
<p>Best...SL</p> | 14,821,791 | 4 | 1 | null | 2013-02-11 22:02:14.297 UTC | 1 | 2018-06-17 11:09:43.86 UTC | null | null | null | null | 1,544,197 | null | 1 | 9 | java|command-line|jar|javac | 78,003 | <p>You need to use the entry-point switch <code>-e</code> (with the name of the class containing the <code>main()</code> method) as such:</p>
<pre><code>jar cfve file.jar Main Main.class Main$1.class Main$2.class
</code></pre> |
14,830,433 | How to prepare encoded POST data on javascript? | <p>I need to send data by POST method.</p>
<p>For example, I have the string "bla&bla&bla". I tried using <code>encodeURI</code> and got "bla&bla&bla" as the result. I need to replace "&" with something correct for this example.</p>
<p>What kind of method should I call to prepare correct POST data?</p>
<p><strong>UPDATED:</strong></p>
<p>I need to convert only charachters which may broke POST request. Only them.</p> | 14,830,517 | 5 | 2 | null | 2013-02-12 10:32:33.357 UTC | 3 | 2018-11-14 19:05:13.333 UTC | 2017-05-09 17:25:42.26 UTC | null | 626,528 | null | 865,475 | null | 1 | 14 | javascript|encoding | 59,476 | <pre><code>>>> encodeURI("bla&bla&bla")
"bla&bla&bla"
>>> encodeURIComponent("bla&bla&bla")
"bla%26bla%26bla"
</code></pre> |
14,463,921 | Select from multiple tables with laravel fluent query builder | <p>I'm re-writing some PHP/MySQL to work with Laravel. One thing I would like to do is make the DB queries more succinct <a href="http://laravel.com/docs/database/fluent" rel="noreferrer">with the Fluent Query Builder</a> but I'm a bit lost:</p>
<pre><code>SELECT p.post_text, p.bbcode_uid, u.username, t.forum_id, t.topic_title, t.topic_time, t.topic_id, t.topic_poster
FROM phpbb_topics t, phpbb_posts p, phpbb_users u
WHERE t.forum_id = 9
AND p.post_id = t.topic_first_post_id
AND u.user_id = t.topic_poster
ORDER BY t.topic_time
DESC LIMIT 10
</code></pre>
<p>This queries a phpbb forum and gets posts:
<img src="https://i.stack.imgur.com/o0GdF.png" alt="enter image description here"></p>
<p>How could I re-write this to make use of the Fluent Query Builder syntax?</p> | 14,465,123 | 2 | 0 | null | 2013-01-22 16:58:17.98 UTC | 3 | 2019-09-29 06:01:07.083 UTC | null | null | null | null | 617,615 | null | 1 | 14 | php|mysql|laravel | 55,962 | <p><strong>Not tested but here is a start</strong></p>
<pre><code>return DB::table('phpbb_topics')
->join('phpbb_posts', 'phpbb_topics.topic_first_post_id', '=', 'phpbb_posts.post_id')
->join('phpbb_users', 'phpbb_topics.topic_poster', '=', 'phpbb_users.user_id')
->order_by('topic_time', 'desc')
->take(10)
->get(array(
'post_text',
'bbcode_uid',
'username',
'forum_id',
'topic_title',
'topic_time',
'topic_id',
'topic_poster'
));
</code></pre> |
14,765,891 | Image smoothing in Python | <p>I wanted to try to write a simple function to smooth an inputted image. I was trying to do this using the Image and numpy libraries. I was thinking that using a convolution mask would be an approach to this problem and I know numpy has a convolve function build in.</p>
<p>How can I use the <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.convolve.html">numpy.convolve</a> to smooth an image?</p> | 14,766,356 | 3 | 1 | null | 2013-02-08 04:50:00.143 UTC | 8 | 2018-07-12 22:49:50.637 UTC | 2018-07-12 22:49:50.637 UTC | null | 674,039 | null | 779,920 | null | 1 | 15 | python|numpy|image-processing|smoothing | 23,146 | <p>Nice question! <strong>tcaswell</strong> post here is a great suggestion, but you will not learn much this way because scipy is doing all the work for you! Since your question said you wanted to <em>try and write the function</em>, I will show you a bit more crude and basic kind of way to do it all manually in the hope that you will better understand the maths behind convolution etc, and then you can improve it with your own ideas and efforts! </p>
<p>Note: You will get different results with different shapes/sizes of kernels, a Gaussian is the usual way but you can try out some other ones for fun (cosine, triangle, etc!). I just made up this one on the spot, I think it's a kind of pyramid shaped one. </p>
<pre><code>import scipy.signal
import numpy as np
import matplotlib.pyplot as plt
im = plt.imread('example.jpg')
im /= 255. # normalise to 0-1, it's easier to work in float space
# make some kind of kernel, there are many ways to do this...
t = 1 - np.abs(np.linspace(-1, 1, 21))
kernel = t.reshape(21, 1) * t.reshape(1, 21)
kernel /= kernel.sum() # kernel should sum to 1! :)
# convolve 2d the kernel with each channel
r = scipy.signal.convolve2d(im[:,:,0], kernel, mode='same')
g = scipy.signal.convolve2d(im[:,:,1], kernel, mode='same')
b = scipy.signal.convolve2d(im[:,:,2], kernel, mode='same')
# stack the channels back into a 8-bit colour depth image and plot it
im_out = np.dstack([r, g, b])
im_out = (im_out * 255).astype(np.uint8)
plt.subplot(2,1,1)
plt.imshow(im)
plt.subplot(2,1,2)
plt.imshow(im_out)
plt.show()
</code></pre>
<p><img src="https://i.stack.imgur.com/NBZpl.jpg" alt="enter image description here"></p> |
14,415,357 | Ruby/Rails using || to determine value, using an empty string instead of a nil value | <p>I usually do</p>
<pre><code> value = input || "default"
</code></pre>
<p>so if input = nil</p>
<pre><code> value = "default"
</code></pre>
<p>But how can I do this so instead of <code>nil</code> It also counts an empty string <code>''</code> as <code>nil</code></p>
<p>I want so that if I do</p>
<pre><code>input = ''
value = input || "default"
=> "default"
</code></pre>
<p>Is there a simple elegant way to do this without <code>if</code>?</p> | 14,415,417 | 3 | 2 | null | 2013-01-19 14:27:58.09 UTC | 7 | 2020-10-21 09:44:25.52 UTC | 2013-01-20 06:47:20.48 UTC | null | 950,147 | null | 950,147 | null | 1 | 29 | ruby-on-rails|ruby | 13,894 | <p>Rails adds <a href="http://api.rubyonrails.org/classes/Object.html#method-i-presence" rel="noreferrer">presence</a> method to all object that does exactly what you want</p>
<pre><code>input = ''
value = input.presence || "default"
=> "default"
input = 'value'
value = input.presence || "default"
=> "value"
input = nil
value = input.presence || "default"
=> "default"
</code></pre> |
14,465,279 | Delete all objects in a list | <p>I create many object then I store in a list. But I want to delete them after some time because I create news one and don't want my memory goes high (in my case, it jumps to 20 gigs of ram if I don't delete it).</p>
<p>Here is a little code to illustrate what I trying to do:</p>
<pre><code>class test:
def __init__(self):
self.a = "Hello World"
def kill(self):
del self
a = test()
b = test()
c = [a,b]
print("1)Before:",a,b)
for i in c:
del i
for i in c:
i.kill()
print("2)After:",a,b)
</code></pre>
<p>A and B are my objects. C is a list of these two objects. I'm trying to delete it definitely with a for-loop in C: one time with DEL and other time with a function. It's not seem to work because the print continue to show the objects.</p>
<p>I need this because I create 100 000 objects many times. The first time I create 100k object, the second time another 100k but I don't need to keep the previous 100k. If I don't delete them, the memory usage goes really high, very quickly.</p> | 14,465,359 | 4 | 2 | null | 2013-01-22 18:13:14.467 UTC | 5 | 2020-07-13 23:25:49.53 UTC | 2013-01-22 18:23:35.13 UTC | null | 179,910 | null | 967,334 | null | 1 | 42 | python|object|memory|del | 128,879 | <p>tl;dr;</p>
<pre><code>mylist.clear() # Added in Python 3.3
del mylist[:]
</code></pre>
<p>are probably the best ways to do this. The rest of this answer tries to explain why some of your other efforts didn't work.</p>
<hr />
<p>cpython at least works on reference counting to determine when objects will be deleted. Here you have multiple references to the same objects. <code>a</code> refers to the same object that <code>c[0]</code> references. When you loop over <code>c</code> (<code>for i in c:</code>), at some point <code>i</code> also refers to that same object. the <code>del</code> keyword removes a single reference, so:</p>
<pre><code>for i in c:
del i
</code></pre>
<p>creates a reference to an object in <code>c</code> and then deletes that reference -- but the object still has other references (one stored in <code>c</code> for example) so it will persist.</p>
<p>In the same way:</p>
<pre><code>def kill(self):
del self
</code></pre>
<p>only deletes a reference to the object in that method. One way to remove all the references from a list is to use slice assignment:</p>
<pre><code>mylist = list(range(10000))
mylist[:] = []
print(mylist)
</code></pre>
<p>Apparently you can also delete the slice to remove objects in place:</p>
<pre><code>del mylist[:] #This will implicitly call the `__delslice__` or `__delitem__` method.
</code></pre>
<p>This will remove all the references from <code>mylist</code> and also remove the references from anything that refers to <code>mylist</code>. Compared that to simply deleting the list -- e.g.</p>
<pre><code>mylist = list(range(10000))
b = mylist
del mylist
#here we didn't get all the references to the objects we created ...
print(b) #[0, 1, 2, 3, 4, ...]
</code></pre>
<p>Finally, more recent python revisions have added a <a href="https://docs.python.org/3.5/tutorial/datastructures.html#data-structures" rel="noreferrer"><code>clear</code></a> method which does the same thing that <code>del mylist[:]</code> does.</p>
<pre><code>mylist = [1, 2, 3]
mylist.clear()
print(mylist)
</code></pre> |
14,509,950 | My diff contains trailing whitespace - how to get rid of it? | <p>I've tried editing a php file in TextWrangler with line endings set to Unix, in NetBeans, and in vim. When I save the diff to a patch and then try to apply it, it gives whitespace errors. When I type <code>git diff</code> I can see <code>^M</code> at the ends of my lines, but if I manually remove these in vim, it says my patch file is corrupted, and then the patch doesn't apply at all.</p>
<p>I create a patch with the following command:</p>
<p><code>git diff > patchname.patch</code> </p>
<p>And I apply it by checking out a clean version of the file to be patched and typing</p>
<p><code>git apply patchname.patch</code></p>
<p>How can I create this patch without whitespace errors? I've created patches before and never run into this issue.</p> | 14,513,670 | 7 | 4 | null | 2013-01-24 20:16:38.07 UTC | 6 | 2022-01-03 21:46:26.673 UTC | 2013-01-25 16:06:20.91 UTC | null | 1,370,106 | null | 1,370,106 | null | 1 | 55 | git|netbeans|whitespace|removing-whitespace|textwrangler | 95,086 | <p>Are you sure those are hard errors? By default, git will warn about whitespace errors, but will still accept them. If they are hard errors then you must have changed some settings. You can use the <code>--whitespace=</code> flag to <code>git apply</code> to control this on a per-invocation basis. Try</p>
<pre><code>git apply --whitespace=warn patchname.patch
</code></pre>
<p>That will force the default behavior, which is to warn but accept. You can also use <code>--whitespace=nowarn</code> to remove the warnings entirely.</p>
<p>The config variable that controls this is <code>apply.whitespace</code>.</p>
<hr>
<p>For reference, the whitespace errors here aren't errors with your patch. It's a code style thing that git will, by default, complain about when applying patches. Notably, it dislikes trailing whitespace. Similarly <code>git diff</code> will highlight whitespace errors (if you're outputting to a terminal and color is on). The default behavior is to warn, but accept the patch anyway, because not every project is fanatical about whitespace.</p> |
14,775,981 | AngularJS - Using ng-repeat to create sets of radio inputs | <p>I'm evaluating angularjs for a future project. One of the things I will need to do is display different pages of "channel" information by selecting an appropriate "page" radio input. Furthermore, ranges of page buttons may also be selected from a group of "page set" radio inputs.</p>
<p>The working example below has a set of 32 channels with the visible group of channels being selected via a combination of "set" and "page" radio inputs, giving a total of 2 * 4 pages of 4 channels each.</p>
<pre><code><!doctype html>
<html ng-app>
<head>
<script type="text/javascript" src="angular.js"></script>
<script type="text/javascript">
function Channels($scope) {
$scope.groupSize = 4;
$scope.pageSet = 0;
$scope.pageNumber = 0;
$scope.channels = [
{"id": "Ch-001"}, {"id": "Ch-002"}, {"id": "Ch-003"}, {"id": "Ch-004"},
{"id": "Ch-005"}, {"id": "Ch-006"}, {"id": "Ch-007"}, {"id": "Ch-008"},
{"id": "Ch-009"}, {"id": "Ch-010"}, {"id": "Ch-011"}, {"id": "Ch-012"},
{"id": "Ch-013"}, {"id": "Ch-014"}, {"id": "Ch-015"}, {"id": "Ch-016"},
{"id": "Ch-017"}, {"id": "Ch-018"}, {"id": "Ch-019"}, {"id": "Ch-020"},
{"id": "Ch-021"}, {"id": "Ch-022"}, {"id": "Ch-023"}, {"id": "Ch-024"},
{"id": "Ch-025"}, {"id": "Ch-026"}, {"id": "Ch-027"}, {"id": "Ch-028"},
{"id": "Ch-029"}, {"id": "Ch-030"}, {"id": "Ch-031"}, {"id": "Ch-032"}
];
}
</script>
</head>
<body ng-controller="Channels">
<p>Set:
<input type="radio" name="pageSet" ng-model="pageSet" ng-value="0">1-4</input>
<input type="radio" name="pageSet" ng-model="pageSet" ng-value="1">5-8</input>
</p>
<p>Page:
<input type="radio" name="pageNumber" ng-model="pageNumber" ng-value="0">{{pageSet * groupSize + 1}}</input>
<input type="radio" name="pageNumber" ng-model="pageNumber" ng-value="1">{{pageSet * groupSize + 2}}</input>
<input type="radio" name="pageNumber" ng-model="pageNumber" ng-value="2">{{pageSet * groupSize + 3}}</input>
<input type="radio" name="pageNumber" ng-model="pageNumber" ng-value="3">{{pageSet * groupSize + 4}}</input>
</p>
<ul>
<li ng-repeat="channel in channels | limitTo: groupSize * ((groupSize * pageSet) + pageNumber + 1) | limitTo: -groupSize">
<p>{{channel.id}}</p>
</li>
</ul>
</body>
</html>
</code></pre>
<p>My question is how to create the page/page set radio inputs using <code>ng-repeat</code>. I've tried approaches such as:</p>
<pre><code><p>Set: <input ng-repeat="n in [0,1]" type="radio" name="pageSet" ng-model="pageSet" ng-value="{{n}}"></p>
<p>Page: <input ng-repeat="n in [0,1,2,3]" type="radio" name="pageNumber" ng-model="pageNumber" ng-value="{{n}}"></p>
</code></pre>
<p>which looks right, but the values don't bind to the corresponding pageSet/pageNumber variables. Can anyone tell what I'm missing here?</p> | 14,776,259 | 3 | 0 | null | 2013-02-08 15:33:53.863 UTC | 17 | 2016-11-09 15:36:37.603 UTC | null | null | null | null | 2,054,713 | null | 1 | 63 | angularjs | 97,966 | <p>ng-repeat create a child scope, so you have to bind to the $parent: </p>
<p>Here's a fiddle: <a href="http://jsfiddle.net/g/r9MLe/2/">http://jsfiddle.net/g/r9MLe/2/</a></p>
<p>Sample:</p>
<pre><code> <p>Set:
<label ng-repeat="n in [0,1]">
<input type="radio" name="pageSet" ng-model="$parent.pageSet" ng-value="n" />{{n}}
</label>
</p>
<p>Page:
<label ng-repeat="n in [0,1,2,3]">
<input type="radio" name="pageNumber" ng-model="$parent.pageNumber" ng-value="n" /> {{n}}
</label>
</p>
</code></pre> |
14,842,195 | How to get file creation date/time in Bash/Debian? | <p>I'm using Bash on Debian GNU/Linux 6.0. Is it possible to get the file creation date/time? Not the modification date/time.
<code>ls -lh a.txt</code> and <code>stat -c %y a.txt</code> both only give the modification time.</p> | 14,842,384 | 13 | 2 | null | 2013-02-12 21:30:26.657 UTC | 23 | 2021-08-13 02:50:05.453 UTC | null | null | null | null | 1,745,732 | null | 1 | 91 | linux|bash|shell|debian|ls | 330,579 | <p>Unfortunately your quest won't be possible in general, as there are only 3 distinct time values stored for each of your files as defined by the POSIX standard (see <a href="http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_08">Base Definitions section 4.8 File Times Update</a>)</p>
<blockquote>
<p>Each file has three distinct associated timestamps: the time of last
data access, the time of last data modification, and the time the file
status last changed. These values are returned in the file
characteristics structure <strong>struct stat</strong>, as described in <a href="http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/sys_stat.h.html"><sys/stat.h></a>.</p>
</blockquote>
<p>EDIT: As mentioned in the comments below, depending on the filesystem used metadata may contain file creation date. Note however storage of information like that is non standard. Depending on it may lead to portability problems moving to another filesystem, in case the one actually used somehow stores it anyways. </p> |
14,381,694 | Why is the Android test runner reporting "Empty test suite"? | <p>I am banging my head against the wall here trying to figure out why IntelliJ/Android is reporting "Empty test suite". I have a small project with two IntelliJ Modules ("Projects" in Eclipse). The Unit test module has its own AndroidManifest.xml, which I have pasted at the bottom. I am trying to run an <code>ActivityUnitTestCase</code>, since the tests will be dependent upon the <code>Context</code>-object.</p>
<p>The package name of the main module is <code>nilzor.myapp</code>. The pacakge name of the test module is <code>nilzor.myapp.tests</code></p>
<p>Why is not the test runner detecting the <code>testBlah()</code>-method as a test?</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<!-- package name must be unique so suffix with "tests" so package loader doesn't ignore us -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="nilzor.myapp.tests"
android:versionCode="1"
android:versionName="1.0">
<!-- We add an application tag here just so that we can indicate that
this package needs to link against the android.test library,
which is needed when building test cases. -->
<application>
<uses-library android:name="android.test.runner"/>
</application>
<!--
This declares that this application uses the instrumentation test runner targeting
the package of nilzor.myapp. To run the tests use the command:
"adb shell am instrument -w nilzor.myapp.tests/android.test.InstrumentationTestRunner"
-->
<instrumentation android:name="android.test.InstrumentationTestRunner"
android:targetPackage="nilzor.myapp"
android:label="Tests for nilzor.myapp"/>
</manifest>
</code></pre>
<p>And here is my test class:;</p>
<pre><code>package nilzor.myapp.tests;
public class NilzorSomeTest<T extends Activity> extends ActivityUnitTestCase<T>{
public NilzorSomeTest(Class<T> activityClass){
super(activityClass);
}
@SmallTest
public void testBlah(){
assertEquals(1,1);
}
}
</code></pre>
<p>I have read the <a href="http://developer.android.com/tools/testing/testing_android.html" rel="noreferrer">testing fundamentals</a>, the <a href="http://developer.android.com/tools/testing/activity_testing.html" rel="noreferrer">activity testing document</a>, and tried following this <a href="http://wptrafficanalyzer.in/blog/android-testing-example-helloworld-with-activityunittestcase/" rel="noreferrer">Hello world test blog</a>, even though it is for Eclipse. I cannot get the test runner to find and run my test. What am I doing wrong?</p>
<p>Some of the questions I still feel unsure about are:</p>
<ol>
<li>Do I need an Annotation above the Unit test method?</li>
<li>Do I need to prefix the method with "test", or is that just for JUnit tests?</li>
<li>Can I have tests in sub-packages of <code>nilzor.myapp.tests</code>?</li>
</ol>
<p>But the main question of this post is <em>why does not the test runner detect my test</em>?</p> | 14,424,650 | 31 | 2 | null | 2013-01-17 14:50:19.073 UTC | 12 | 2019-04-11 09:59:13.017 UTC | null | null | null | null | 507,339 | null | 1 | 98 | android|intellij-idea | 68,836 | <p>You need to provide default constructor for your test class, for example:</p>
<pre><code>package nilzor.myapp.tests;
public class NilzorSomeTest extends ActivityUnitTestCase<ActivityYouWantToTest>{
public NilzorSomeTest(){
super(ActivityYouWantToTest.class);
}
@SmallTest
public void testBlah(){
assertEquals(1,1);
}
}
</code></pre>
<p>about your other questions:</p>
<ol>
<li><p>No. My tests still run without any annotations, but I guess it's a good practice to have them. It allows you to specify size of tests to run. See <a href="https://stackoverflow.com/questions/4671923/what-is-the-purpose-of-smalltest-mediumtest-and-largetest-annotations-in-an">What is the purpose of @SmallTest, @MediumTest, and @LargeTest annotations in Android?</a> for more detail.</p></li>
<li><p>Yes, you need "test" prefix. InteliJ gives "method never used" warning when there's no "test" prefix, and skips that method during test run.</p></li>
<li><p>Yes. I have my tests organized into subpackages and it seems to be working well. </p></li>
</ol> |
62,825,358 | Javascript .replaceAll() is not a function type error | <p>The documentation page: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll" rel="noreferrer">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll</a></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let string = ":insertx: :insertx: :inserty: :inserty: :insertz: :insertz:";
let newstring = string.replaceAll(":insertx:", 'hello!');</code></pre>
</div>
</div>
</p>
<p>When I run this, I receive <code>Uncaught TypeError: string.replaceAll is not a function</code>. Maybe I'm misunderstanding what a prototype is, but the function appears to be a string method that is available for use.</p>
<p>I'm using Chrome.</p> | 62,825,401 | 7 | 9 | null | 2020-07-09 23:51:15.897 UTC | 6 | 2022-06-07 06:46:49.347 UTC | 2020-09-02 12:22:22.447 UTC | null | 12,637,568 | null | 12,637,568 | null | 1 | 84 | javascript|typeerror | 95,092 | <p><code>.replaceAll</code> will be available starting on Chrome 85. The current version is 83.</p>
<p>If you download Google Chrome Canary (which is on version 86), you'll be able to see that your code runs fine. Firefox is on version 78, and since <code>.replaceAll</code> has been available starting version 77, it works there too. It will work on current Safari as well. Microsoft Edge has it as unsupported.</p>
<p>You'll find supported browser versions at the bottom of the article in your question.</p> |
26,353,917 | Update to Android SDK Tools 23.0.5 and avd doesn't start | <p>I am running on Windows 8.1 x64, developing Android apps using ADT Bundle. Previously (before updating the Android SDK Tools) the AVD was working very correctly and after the update, it says the following error while starting the AVD</p>
<pre><code>emulator: ERROR: x86 emulation currently requires hardware acceleration!
Please ensure Intel HAXM is properly installed and usable.
CPU acceleration status: HAX kernel module is not installed!
</code></pre>
<p>I tried to delete the avd, avd-folder from the windows user-specific folder and re-created the similar avd but no progress.</p>
<p>How can I run the avd again? (after the SDK update)</p> | 26,459,135 | 6 | 0 | null | 2014-10-14 06:20:28.78 UTC | 6 | 2015-12-17 21:22:56.853 UTC | null | null | null | null | 4,136,107 | null | 1 | 12 | adt|android-sdk-tools | 46,812 | <p>Create emulator in CPU/ABI in ARM, this error only exist for Intel processor.</p>
<p>If you want to create AVD CPU/ABI in Intel gor for this process,
Make sure you have instaled HAXM installer on your SDK Manager.</p>
<p>After you download it make sure you run the setup located in: {SDK_FOLDER}\extras\intel\Hardware_Accelerated_Execution_Manager\intelhaxm.exe</p>
<p>If you get the error "VT not supported" during the installation disable Hyper-V on windows features. You can execute this command dism.exe /Online /Disable-Feature:Microsoft-Hyper-V. You will also need "Virtualization Technology" to be enabled on your BIOS</p> |
2,702,720 | Seeking Functional Programming Lexicon | <p>Knowing the argot of a field helps me a lot, especially since it allows me to converse intelligently with those who know a lot more than I, so I would like to find a good lexicon of Functional Programming terms.</p>
<p>E.g., I repeatedly encounter these: Functor, Arrow, Category, Kleisli, Monad, Monoid, a veritable zoo of Morphisms, etc. I also notice many of these appear with prefixes such as "covariant", "co-", "endo-" etc.</p>
<p>Of these, I can say I actually understand Monoid and Covariant and sort of get Monad, but the rest are still gibberish to me. (Note that I don't mean this list as exhaustive and I'm not looking to have these defined or described for me here, I'm looking for learning resources.)</p>
<p>Can someone point me towards an FP lexicon? It need not be on-line, as long as it's possible to find it (and it's not a rare volume for which I'd have to pay many tens of dollars).</p> | 2,707,293 | 3 | 3 | null | 2010-04-24 00:35:16.983 UTC | 11 | 2012-09-22 02:52:09.427 UTC | null | null | null | null | 200,166 | null | 1 | 15 | functional-programming | 659 | <p>As other answers have pointed out, to really understand those terms you have to study Category Theory. However, Category Theory is very abstract and may not help you build up intuition immediately. To see the abstract concepts in action, I highly recommend the Typeclassopedia (<a href="http://www.haskell.org/wikiupload/8/85/TMR-Issue13.pdf" rel="nofollow noreferrer">PDF</a>) (<a href="http://byorgey.wordpress.com/2009/02/16/the-typeclassopedia-request-for-feedback/" rel="nofollow noreferrer">blog announcement</a>).</p> |
2,939,393 | Why use nginx with Catalyst/Plack/Starman? | <p>I am trying to deploy my little Catalyst web app using Plack/Starman. All the documentation seems to suggest I want to use this in combination with nginx. What are the benefits of this? Why not use Starman straight up on port 80?</p> | 2,939,522 | 3 | 0 | null | 2010-05-30 16:13:23.757 UTC | 11 | 2014-10-20 21:39:46.027 UTC | null | null | null | null | 58,089 | null | 1 | 24 | perl|nginx|catalyst|plack|starman | 6,800 | <p>It doesn't have to be nginx in particular, but you want some kind of frontend server proxying to your application server for a few reasons:</p>
<ol>
<li><p>So that you can run the Catalyst server on a high port, as an ordinary user, while running the frontend server on port 80.</p></li>
<li><p>To serve static files (ordinary resources like images, JS, and CSS, as well as any sort of downloads you might want to use X-Sendfile or X-Accel-Redirect with) without tying up a perl process for the duration of the download.</p></li>
<li><p>It makes things easier if you want to move on to a more complicated config involving e.g. Edge Side Includes, or having the webserver serve directly from memcached or mogilefs (both things that nginx can do), or a load-balancing / HA config.</p></li>
</ol> |
2,454,473 | Junit Parameterized tests together with Powermock - how? | <p>I've been trying to figure out how to run parameterized tests in Junit4 together with PowerMock. The problem is that to use PowerMock you need to decorate your test class with </p>
<pre><code>@RunWith(PowerMockRunner.class)
</code></pre>
<p>and to use parameterized tests you have to decorate with </p>
<pre><code>@RunWith(Parameterized.class)
</code></pre>
<p>From what I can see they seem mutually excluded!? Is this true? Is there any way around this? I've tried to create a parameterized class within a class running with PowerMock; something like this:</p>
<pre><code>@RunWith(PowerMockRunner.class)
class MyTestClass {
@RunWith(Parameterized.class)
class ParamTestClass {
// Yadayada
}
}
</code></pre>
<p>But unfortunately this doesn't do much good... The <code>ParamTestClass</code> still doesn't run with PowerMock support (not that surprisingly maybe)... And I've kind of run out of ideas so any help is greatly appreciated!</p>
<p><strong>Update:</strong>
For future googlers also see: <a href="http://groups.google.com/group/powermock/browse_thread/thread/f7df24bddf1cc73/dd4ca873a36381a18?lnk=gst&q=parameterized#dd4ca873a3638118" rel="noreferrer">Using PowerMock without the RunWith?</a></p> | 30,175,305 | 4 | 0 | null | 2010-03-16 13:03:14.993 UTC | 6 | 2020-05-12 14:30:50.49 UTC | 2017-06-09 10:59:26.06 UTC | null | 5,091,346 | null | 20,364 | null | 1 | 50 | java|junit|powermock|parameterized | 17,557 | <p>I had the same issue. Unfortunately it would not let me use a PowerMock Rule due to the JVM I had. Instead of the rule I used RunnerDelegate.</p>
<pre><code>@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(Parameterized.class)
</code></pre> |
2,706,129 | Can a c++ class include itself as an member? | <p>I'm trying to speed up a python routine by writing it in C++, then using it using ctypes or cython.</p>
<p>I'm brand new to c++. I'm using Microsoft Visual C++ Express as it's free.</p>
<p>I plan to implement an expression tree, and a method to evaluate it in postfix order.</p>
<p>The problem I run into right away is:</p>
<pre><code>class Node {
char *cargo;
Node left;
Node right;
};
</code></pre>
<p>I can't declare <code>left</code> or <code>right</code> as <code>Node</code> types.</p> | 2,706,136 | 4 | 1 | null | 2010-04-24 21:02:43.837 UTC | 21 | 2021-10-23 05:47:46.907 UTC | 2017-12-12 20:47:23.933 UTC | null | 787,480 | null | 169,415 | null | 1 | 51 | c++ | 42,211 | <p>No, because the object would be infinitely large (because every <code>Node</code> has as members two other <code>Node</code> objects, which each have as members two other <code>Node</code> objects, which each... well, you get the point).</p>
<p>You can, however, have a pointer to the class type as a member variable:</p>
<pre><code>class Node {
char *cargo;
Node* left; // I'm not a Node; I'm just a pointer to a Node
Node* right; // Same here
};
</code></pre> |
3,214,035 | Mercurial: How do you undo changes? | <p>When using Mercurial, how do you undo all changes in the working directory since the last commit? It seems like this would be a simple thing, but it's escaping me.</p>
<p>For example, let's say I have 4 commits. Then, I make some changes to my code. Then I decide that my changes are bad and I just want to go back to the state of the code at my last commit. So, I think I should do:</p>
<pre><code>hg update 4
</code></pre>
<p>with 4 being the revision # of my latest commit. But, Mercurial doesn't change any of the files in my working directory. Why not?</p> | 3,214,065 | 4 | 1 | null | 2010-07-09 15:22:21.15 UTC | 15 | 2013-01-30 02:49:03.25 UTC | 2010-07-10 13:38:14.423 UTC | null | 110,204 | null | 387,875 | null | 1 | 66 | version-control|mercurial | 70,658 | <p><a href="http://www.selenic.com/mercurial/hg.1.html#revert" rel="noreferrer"><code>hg revert</code></a> will do the trick.</p>
<p>It will revert you to the last commit. </p>
<p><code>--all</code> will revert all files.</p>
<p>See the link for the Man Page description of it.</p>
<p><code>hg update</code> is usually used to refresh your working directory after you pull from a different repo or swap branches. <code>hg up myawesomebranch</code>. It also can be used to revert to a specific version. <code>hg up -r 12</code>. </p> |
40,416,056 | How to download previous version of tensorflow? | <p>For some reason, I want to use some previous version of tensorflow('tensorflow-**-.whl', not source code on github) and where can I download the previous version and how can I know the corresponding <code>cuda version</code> that is compatible.</p> | 40,418,913 | 8 | 0 | null | 2016-11-04 05:46:26.64 UTC | 12 | 2020-10-21 12:47:49.68 UTC | null | null | null | null | 4,696,856 | null | 1 | 24 | tensorflow | 81,903 | <p>You can always download the previous version of tensorflow version</p>
<p>from <a href="https://www.tensorflow.org/versions/r0.11/get_started/os_setup.html#download-and-setup" rel="nofollow noreferrer">here</a></p>
<p>Here on the top left you can change the version</p>
<p><a href="https://i.stack.imgur.com/WafWs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WafWs.png" alt="enter image description here"></a></p> |
40,567,451 | Dockerfile vs. docker-compose VOLUME | <p>This experiment tries to build a container using this Docker file:</p>
<pre><code>FROM lambdalinux/baseimage-amzn:2016.09-000
COPY ./bundle /opt/bundle/
VOLUME /bundle
</code></pre>
<p>Then inside the container, create a <code>/opt/bundle/file.txt</code> and put some text in it. But that file did not show up in the bundle directory on the host as I expected after reading <a href="https://docs.docker.com/compose/faq/" rel="noreferrer">Should I include my code with COPY/ADD or a volume</a> last paragraph:</p>
<blockquote>
<p>There may be cases where you’ll want to use both. You can have the image include the code using a COPY, and use a volume in your Compose file to include the code from the host during development. The volume overrides the directory contents of the image.</p>
</blockquote>
<p>Doesn't Dockerfile VOLUME do the same as <code>docker-compose.yml</code> VOLUME? If so, how can this be done so that changes in the host directory is reflected inside the container directory in this case?</p>
<p>I also created a file on the host <code>bundle/play.txt</code> but that did not show up inside the container <code>/opt/bundle/...</code></p> | 40,568,482 | 1 | 0 | null | 2016-11-12 20:43:15.027 UTC | 10 | 2017-04-20 16:12:41.797 UTC | 2016-12-24 21:37:20.353 UTC | null | 875,915 | null | 5,047,454 | null | 1 | 62 | docker|docker-compose | 23,537 | <p>A <a href="https://docs.docker.com/engine/reference/builder/#/volume" rel="noreferrer"><code>VOLUME</code> instruction</a> in the dockerfile creates a mount point but initially only maps it to Docker's internal data directory.</p>
<p>In order to map the volume to the host filesystem, you need to specify which path on the host should be mapped to the volume. You can do this in the docker-compose file using the <a href="https://docs.docker.com/compose/compose-file/#/volumes-volumedriver" rel="noreferrer"><code>volumes</code> parameter</a>. (Note: you can create volumes using docker-compose without declaring them in the Dockerfile.)</p>
<p>Note that when mapping a directory from the host to a container, the directory contents on the host will replace the contents in the container, not vice versa.</p> |
48,692,741 | How can I make all line endings (EOLs) in all files in Visual Studio Code, Unix-like? | <p>I use <a href="https://en.wikipedia.org/wiki/Windows_10_editions#Baseline_editions" rel="noreferrer">Windows 10 Home</a> and I usually use Visual Studio Code (VS Code) to edit Linux Bash scripts as well as PHP and JavaScript.</p>
<p>I don't develop anything dedicated for Windows and I wouldn't mind that the default EOLs for all files I edit whatsoever would be Unix like (nix).</p>
<p>How could I ensure that all EOLs, in all files whatsoever (from whatever file extension), are nix, in Visual Studio Code?</p>
<hr />
<p>I ask this question after I've written a few Bash scripts in Windows with Visual Studio Code, uploaded them to GitHub as part of a project, and a senior programmer that reviewed the project told me I have <strong>Windows EOLs</strong> there and also a <strong><a href="https://en.wikipedia.org/wiki/Byte_order_mark" rel="noreferrer">BOM</a></strong> problem that I could solve if I'll change the EOLs there to be nix (or that's what I understood, at least).</p>
<hr />
<p>Because all my development is Linux-oriented, I would prefer that by default, <strong>any</strong> file I edit would have nix EOLs, even if it's Windows unique.</p> | 48,693,007 | 9 | 0 | null | 2018-02-08 18:49:05.25 UTC | 23 | 2022-03-01 16:18:46.253 UTC | 2021-05-17 18:12:37.767 UTC | null | 63,550 | null | 9,303,970 | null | 1 | 105 | windows|bash|visual-studio-code|editor|line-endings | 111,209 | <p>In your project preferences, add/edit the following configuration option:</p>
<pre><code>"files.eol": "\n"
</code></pre>
<p>This was added as of commit <a href="https://github.com/Microsoft/vscode/commit/639a3cbcb3ac118dfaba7443e2ee3b502ff34d21" rel="noreferrer">639a3cb</a>, so you would obviously need to be using a version after that commit.</p>
<p>Note: Even if you have a single <code>CRLF</code> in the file, the above setting will be ignored and the whole file will be converted to <code>CRLF</code>. You first need to convert all <code>CRLF</code> into <code>LF</code> before you can open it in Visual Studio Code.</p>
<p>See also: <a href="https://github.com/Microsoft/vscode/issues/2957" rel="noreferrer">https://github.com/Microsoft/vscode/issues/2957</a></p> |
54,137,790 | Convert from '_io.BytesIO' to a bytes-like object in python3.6? | <p>I am using this function to uncompress the body or a HTTP response if it is compressed with gzip, compress or deflate.</p>
<pre><code>def uncompress_body(self, compression_type, body):
if compression_type == 'gzip' or compression_type == 'compress':
return zlib.decompress(body)
elif compression_type == 'deflate':
compressor = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS)
compressed = compressor.compress(body)
compressed += compressor.flush()
return base64.b64encode(compressed)
return body
</code></pre>
<p>However python throws this error message.</p>
<pre><code>TypeError: a bytes-like object is required, not '_io.BytesIO'
</code></pre>
<p>on this line:</p>
<pre><code>return zlib.decompress(body)
</code></pre>
<p>Essentially, how do I convert from '_io.BytesIO' to a bytes-like object?</p> | 54,137,810 | 3 | 0 | null | 2019-01-10 22:26:47.937 UTC | 12 | 2022-03-28 13:09:53.38 UTC | 2020-09-01 23:41:44.697 UTC | null | 1,127,428 | null | 964,491 | null | 1 | 61 | python|python-3.x|typeerror|zlib|bytesio | 64,456 | <p>It's a file-like object. Read them:</p>
<pre><code>>>> b = io.BytesIO(b'hello')
>>> b.read()
b'hello'
</code></pre>
<p>If the data coming in from <code>body</code> is too large to read into memory, you'll want to refactor your code and use <a href="https://docs.python.org/3/library/zlib.html#zlib.decompressobj" rel="noreferrer"><code>zlib.decompressobj</code></a> instead of <code>zlib.decompress</code>.</p> |
49,775,261 | Check null in ternary operation | <p>I wanna put a default value on a textfield if _contact is not null. To do this </p>
<pre><code>new TextField(
decoration: new InputDecoration(labelText: "Email"),
maxLines: 1,
controller: new TextEditingController(text: (_contact != null) ? _contact.email: ""))
</code></pre>
<p>Is there a better way to do that? E.g: Javascript would be something like: <code>text: _contact ? _contact.email : ""</code></p> | 49,775,293 | 1 | 0 | null | 2018-04-11 12:32:02.97 UTC | 6 | 2018-06-14 14:44:09.98 UTC | null | null | null | null | 6,066,044 | null | 1 | 25 | dart|flutter | 41,033 | <p>Dart comes with <code>?.</code> and <code>??</code> operator for null check.</p>
<p>You can do the following :</p>
<pre><code>var result = _contact?.email ?? ""
</code></pre>
<hr>
<p>You can also do </p>
<pre><code>if (t?.creationDate?.millisecond != null) {
...
}
</code></pre>
<p>Which in JS is equal to : </p>
<pre><code>if (t && t.creationDate && t.creationDate.millisecond) {
...
}
</code></pre> |
15,487,900 | How to store multiple records in JSON | <p>I wan't to know how store multiple entities in json file (Structure) I will want to find by id functions (JQuery/javascript) and easy sorting (0,1,2...200).</p>
<p>Here my code:</p>
<pre><code>{
"id" : 5,
"name" : "Jemmy overy",
"data" : {...},
"link" : "http:...",
}
</code></pre> | 15,487,923 | 2 | 1 | null | 2013-03-18 22:09:45.367 UTC | 0 | 2016-05-02 13:15:30.39 UTC | 2013-03-18 22:21:37.08 UTC | null | 558,021 | null | 965,921 | null | 1 | 0 | javascript|jquery|json | 44,134 | <p>Btw, The answer by Lix below is best if you're looking to pull them out via their index number.</p>
<p>Wrap them in square brackets!</p>
<pre><code>[{
"id" : 5,
"name" : "Jemmy overy",
"data" : {...},
"link" : "http:...",
},
{
"id" : 6,
"name" : "John Smith",
"data" : {...},
"link" : "http:...",
}]
</code></pre> |
43,018,777 | angular-cli different versions in the same computer | <p>I'm working with Angular2 in several projects. Each of this projects uses a different version of <code>angular-cli</code>, so, I need to be able to run and compile for production each separately with the correct version of <code>angular-cli</code>. When I installed <code>angular-cli</code> locally using <code>save-dev</code>, ng commands not found so I cannot create a build distribution for the project.</p>
<p>So the question are, how can I have multiples <code>angular-cli</code> version in the same machine, without installed globally (with -g option)?, it is possible run ng commands without installing <code>angular-cli</code> globally?</p> | 51,126,312 | 7 | 0 | null | 2017-03-25 16:15:35.837 UTC | 19 | 2022-05-05 22:43:20.193 UTC | 2019-10-16 01:32:27.543 UTC | null | 1,127,428 | null | 4,447,391 | null | 1 | 33 | angular|angular-cli | 38,524 | <p>You could use <a href="https://github.com/creationix/nvm" rel="noreferrer">NVM</a> which is a Node Version Manager and allows you to work with different global modules in each Node version. </p>
<p>In my case, I'm working with Node 6.9.5 and Angular2 in one project, and Node 10 and Angular6 in other. </p>
<p>You only have to pay attention which version is seated and work as normally as you do. </p> |
44,980,247 | How to finish all fetch before executing next function in React? | <p>Using ReactJS, I have two different API points that I am trying to get and restructure: <code>students</code> and <code>scores</code>. They are both an array of objects.</p>
<p><strong>My goal is</strong> : first, get students and scores, and second, with students and scores saved in state, I will modify them and create a new state based on students and scores state. In short, I have 3 functions: <code>getStudents</code>, <code>getScores</code>, and <code>rearrangeStudentsAndScores</code>. <code>getStudents</code> and <code>getScores</code> need to finish before <code>rearrangeStudentsAndScores</code> can run.</p>
<p><strong>My problem is</strong>: sometimes <code>rearrangeStudentsAndScores</code> will run before <code>getScores</code> would complete. That messed <code>rearrangeStudentsAndScores</code> up. But sometimes it would complete. Not sure why it works 50% of the time, but I need to make it work 100% of the time. </p>
<p>This is what I have to <code>fetch</code> <code>students and scores</code> in my <code>Client</code> file:</p>
<pre><code>function getStudents(cb){
return fetch(`api/students`, {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
}).then((response) => response.json())
.then(cb)
};
function getScores(cb){
return fetch(`api/scores`, {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
}).then((response) => response.json())
.then(cb)
};
</code></pre>
<p>I then combined them together:</p>
<pre><code>function getStudentsAndScores(cbStudent, cbScores, cbStudentsScores){
getStudents(cbStudent).then(getScores(cbScores)).then(cbStudentsScores);
}
</code></pre>
<p>In my react app, I have the following:</p>
<pre><code>getStudentsAndScores(){
Client.getStudentsAndScores(
(students) => {this.setState({students})},
(scores) => {this.setState({scores})},
this.rearrangeStudentsWithScores
)
}
rearrangeStudentsWithScores(){
console.log('hello rearrange!')
console.log('students:')
console.log(this.state.students);
console.log('scores:');
console.log(this.state.scores); //this returns [] half of the time
if (this.state.students.length > 0){
const studentsScores = {};
const students = this.state.students;
const scores = this.state.scores;
...
}
}
</code></pre>
<p>Somehow, by the time I get to <code>rearrangeStudentsWithScores</code>, <code>this.state.scores</code> will still be <code>[]</code>. </p>
<p>How can I ensure that <code>this.state.students</code> and <code>this.state.scores</code> are both loaded before I run <code>rearrangeStudentsWithScores</code>?</p> | 44,980,331 | 3 | 0 | null | 2017-07-07 22:00:26.89 UTC | 11 | 2022-03-16 09:40:22.063 UTC | 2022-03-16 09:40:22.063 UTC | null | 3,689,450 | null | 5,739,288 | null | 1 | 30 | javascript|reactjs|asynchronous|fetch-api | 55,851 | <p>Your code mixes <a href="https://en.wikipedia.org/wiki/Continuation-passing_style" rel="noreferrer">continuation callbacks</a> and Promises. You'll find it easier to reason about it you use one approach for async flow control. Let's use Promises, because <code>fetch</code> uses them.</p>
<pre><code>// Refactor getStudents and getScores to return Promise for their response bodies
function getStudents(){
return fetch(`api/students`, {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
}).then((response) => response.json())
};
function getScores(){
return fetch(`api/scores`, {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
}).then((response) => response.json())
};
// Request both students and scores in parallel and return a Promise for both values.
// `Promise.all` returns a new Promise that resolves when all of its arguments resolve.
function getStudentsAndScores(){
return Promise.all([getStudents(), getScores()])
}
// When this Promise resolves, both values will be available.
getStudentsAndScores()
.then(([students, scores]) => {
// both have loaded!
console.log(students, scores);
})
</code></pre>
<p>As well as being simpler, this approach is more efficient because it makes both requests at the same time; your approach waited until the students were fetched before fetching the scores.</p>
<p>See <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise/all" rel="noreferrer"><code>Promise.all</code> on MDN</a></p> |
36,340,639 | Async Progress Bar Update | <p>I am trying to use an <code>async await</code> to update a progress bar on my WinForm based on a copy operation, but the progress bar will only update when the <code>Copy</code> function has finished, and then throws an exception that it can't update as it's not on the same thread?</p>
<p>The Copy function doesn't need to interact with the UI but the Progress function does.</p>
<p>The UI isn't blocked though, so it would appear the async part is working as expected, it's just interacting with the UI thread that isn't.</p>
<pre><code>long fileProgress = 0;
long totalProgress = 0;
bool complete = false;
CopyFileEx.CopyFileCallbackAction callback(FileInfo source, FileInfo destination, object state, long totalFileSize, long totalBytesTransferred)
{
fileProgress = totalBytesTransferred;
totalProgress = totalFileSize;
return CopyFileEx.CopyFileCallbackAction.Continue;
}
async Task Progress()
{
await Task.Run(() =>
{
while (!complete)
{
if (fileProgress != 0 && totalProgress != 0)
{
fileProgressBar.Value = (int)(fileProgress / totalProgress) * 100;
}
}
});
}
private async void startButton_Click(object sender, EventArgs e)
{
Copy();
await Progress();
MessageBox.Show("Done");
}
void Copy()
{
Task.Run(() =>
{
CopyFileEx.FileRoutines.CopyFile(new FileInfo(@"C:\_USB\Fear.rar"), new FileInfo(@"H:\Fear.rar"), CopyFileEx.CopyFileOptions.All, callback, null);
complete = true;
});
}
</code></pre> | 36,341,034 | 3 | 0 | null | 2016-03-31 18:09:00.09 UTC | 4 | 2019-01-15 10:58:41.277 UTC | null | null | null | null | 799,586 | null | 1 | 10 | c#|async-await | 40,513 | <ol>
<li><code>async / await</code> is all about not blocking a thread - any thread - when dealing with I/O. Putting a <strong>blocking</strong> I/O call inside <code>Task.Run()</code> (like you did in <code>Copy()</code>) doesn't avoid blocking - it just create a Task which some other thread will later pick up, just to find it itself gets blocked when it hits the blocking <code>CopyFileEx.FileRoutines.CopyFile()</code> method. </li>
<li>You are getting that error because you are not using <code>async / await</code> properly (regardless the above). Think about which thread is trying to modify the UI object <code>fileProgressBar</code>: the random threadpool thread that picks up the Task you create on <code>Task.Run()</code> gets to execute <code>fileProgressBar.Value = ...</code>, which will obviously throw. </li>
</ol>
<p>This is one way to avoid this situation:</p>
<pre><code>async Task Progress()
{
await Task.Run(() =>
{
//A random threadpool thread executes the following:
while (!complete)
{
if (fileProgress != 0 && totalProgress != 0)
{
//Here you signal the UI thread to execute the action:
fileProgressBar.Invoke(new Action(() =>
{
//This is done by the UI thread:
fileProgressBar.Value = (int)(fileProgress / totalProgress) * 100
}));
}
}
});
}
private async void startButton_Click(object sender, EventArgs e)
{
await Copy();
await Progress();
MessageBox.Show("Done"); //here we're on the UI thread.
}
async Task Copy()
{
//You need find an async API for file copy, and System.IO has a lot to offer.
//Also, there is no reason to create a Task for MyAsyncFileCopyMethod - the UI
// will not wait (blocked) for the operation to complete if you use await:
await MyAsyncFileCopyMethod();
complete = true;
}
</code></pre> |
26,309,081 | How do Rust's ownership semantics relate to uniqueness typing as found in Clean and Mercury? | <p>I noticed that in Rust moving is applied to lvalues, and it's statically enforced that moved-from objects are not used.</p>
<p>How do these semantics relate to uniqueness typing as found in Clean and Mercury? Are they the same concept? If not, how do they differ?</p> | 26,411,895 | 1 | 0 | null | 2014-10-10 22:43:08.877 UTC | 9 | 2015-02-11 22:44:31.967 UTC | 2015-02-11 22:44:31.967 UTC | user1804599 | null | user1804599 | null | null | 1 | 19 | rust|move-semantics|mercury|clean-language | 1,042 | <p>The concept of ownership in Rust is not the same as uniqueness in Mercury and Clean, although they are related in that they both aim to provide safety via static checking, and they are both defined in terms of the number of references within a scope. The key differences are:</p>
<ul>
<li><p>Uniqueness is a more abstract concept. While it can be interpreted as saying that a reference to a memory location is unique, like Rust's <a href="http://doc.rust-lang.org/reference.html#lvalues,-rvalues-and-temporaries" rel="noreferrer">lvalues</a>, it can also apply to abstract values such as the state of every object in the universe, to give an extreme but typical example. There is no pointer corresponding to such a value - it cannot be opened up and inspected within a debugger or anything like that - but it can be used through an interface just like any other abstract type. The aim is to give a <em>value-oriented</em> semantics that remains consistent in the presence of statefulness.</p></li>
<li><p>In Mercury, at least (I can't speak for Clean), uniqueness is a more limited concept than ownership, in that there must be exactly one reference. You can't share several copies of a reference on the proviso that they will not be written to, as can be done in Rust. You also can't lend a reference for writing but get it back later after the borrower has finished with it.</p></li>
<li><p>Declaring something unique in Mercury does not guarantee that writing to references will occur, just that the compiler will check that it would be safe to do so; it is still valid for an implementation to copy the contents of a unique reference rather than update in place. The compiler will arrange for the update in place if it deems it appropriate at its given optimization level. Alternatively, authors of abstract types may perform similar (or sometimes drastically better) optimizations manually, safe in the knowledge that users will be forced to use the abstract type in a way that is consistent with them. Ownership in Rust, on the other hand, is more directly connected to the memory model and gives stronger guarantees about behaviour.</p></li>
</ul> |
22,873,419 | org.mockito.exceptions.misusing.MissingMethodInvocationException | <p>I am getting following exceptions when I run Junit test.</p>
<blockquote>
<p>org.mockito.exceptions.misusing.MissingMethodInvocationException:</p>
<p>when() requires an argument which has to be 'a method call on a mock'.
For example:</p>
<pre><code> when(mock.getArticles()).thenReturn(articles);
</code></pre>
<p>Also, this error might show up because:</p>
<ol>
<li>you stub either of: final/private/equals()/hashCode() methods. Those methods <em>cannot</em> be stubbed/verified.</li>
<li>inside when() you don't call method on mock but on some other object.</li>
<li>the parent of the mocked class is not public. It is a limitation of the mock engine.</li>
</ol>
</blockquote>
<p>Following is my code and the exception was thrown at the second when statement. I don't think that my test code didn't violate what the exception claims. I spent for a while, but couldn't figure out. Could someone help? What I need to test is getPermProducts method. In the getPermProducts method, I want to ignore isTempProduct method. So, when p1 came, I want it returns false, and when p2 came, I want it returns true etc..</p>
<pre><code>@Named(ProductManager.NAME)
public class ProductManager {
@Resource(name = ProductService.NAME)
private ProductService productService;
public List<Product> getPermProducts(Set<Product> products) {
Iterator<Product> it = products.iterator();
List<Product> cProducts = new ArrayList<Product>();
Product p;
while (it.hasNext()) {
p = it.next();
if (!isTempProduct(p)) {
cProducts.add(p);
}
}
return cProducts;
}
public Boolean isTempProduct(Product product) {
if (product instanceof PermProduct) {
return false;
}
Set<ProductItems> pItems = product.getProductItems();
if (pItems.isEmpty()) {
return false;
}
Iterator<ProductItem> itr = pItems.iterator();
while (itr.hasNext()) {
if (itr.next() instanceof TempItem) {
return true;
}
}
return false;
}
public Product getProduct(Integer productId) {
Product p = productService.getProduct(productId);
return p;
}
}
@RunWith(MockitoJUnitRunner.class)
public class ProductManagerTest {
@InjectMocks
private ProductManager mockProductManager;
@Mock
private ProductService mockProductService;//not being used here
private static final Integer PRODUCT_ID_1 = 1;
private static final Integer PRODUCT_ID_2 = 2;
@Test
public void getProduct(){
Product p1 = mock(PermProduct.class);
p1.setProductId(PRODUCT_ID_1);
when(mockProductManager.getProductId()).thenReturn(PRODUCT_ID_1);
when(mockProductManager.isTempProduct(p1)).thenReturn(false);
Product p2 = mock(TempProduct.class);
p2.setProductId(PRODUCT_ID_2);
when(mockProductManager.isTempProduct(p2)).thenReturn(true);
List<Product> products = Mock(List.class);
products.add(p1);
products.add(p2);
Iterator<Product> pIterator = mock(Iterator.class);
when(prodcuts.iterator()).thenReturn(pIterator);
when(pIterator.hasNext()).thenReturn(true, true, false);
when(pIterator.next()).thenReturn(p1, p2);
asserEquals(1, mockProductManager.getPermProducts(products).size());
}
}
</code></pre>
<p>SOLUTION: I updated my test based on enterbios's answer. I used partial mocking, but as enterbios suggested, we should avoid it, but sometimes we need it. I found that we can have both non-mocked and partial mocked class same time.</p>
<pre><code>@RunWith(MockitoJUnitRunner.class)
public class ProductManagerTest {
@InjectMocks
private ProductManager productManager;//not being used here
@Mock
private ProductService mockProductService;//not being used here
@Spy
private OtherService other = new OtherService();//not being used here
@InjectMocks
final ProductManager partiallyMockedProductManager = spy(new ProductManager());
private static final Integer PRODUCT_ID_1 = 1;
private static final Integer PRODUCT_ID_2 = 2;
@Test
public void getProduct() {
Product p1 = new PermProduct();
p1.setProductId(PRODUCT_ID_1);
Product p2 = new Product();
p2.setProductId(PRODUCT_ID_2);
List<Product> products = new ArrayList<Product>();
products.add(p1);
products.add(p2);
doReturn(false).when(partiallyMockedProductManager).isTempProduct(p1);
doReturn(true).when(partiallyMockedProductManager).isTempProduct(p2);
assertEquals(1, partiallyMockedProductManager.getPermProducts(products).size());
verify(partiallyMockedProductManager).isTempProduct(p1);
verify(partiallyMockedProductManager).isTempProduct(p2);
}
}
</code></pre> | 22,873,465 | 1 | 0 | null | 2014-04-04 21:34:43.857 UTC | null | 2014-07-29 16:34:32.573 UTC | 2014-07-29 16:34:32.573 UTC | null | 196,921 | null | 3,123,690 | null | 1 | 4 | java|mockito|junit4 | 39,949 | <p>Your mockProductManager is actually not a mock but an instance of ProductManager class. You shouldn't mock a tested object. The way to mock some methods from tested object is using a spy but I recommend you to not use them, or even to not think about them unless you're fighting with some ugly legacy code.
I think your second 'when' should be replaced with assertion, like:</p>
<pre><code>assertFalse(mockProductManager.isTempProduct(p1));
</code></pre>
<p>because what you really want to check in this test is if productManager.isTempProduct(p1) returns false for all instances of PermProduct. To verify results of some method calls/objects states you should use assertions. To make your life with assertions easier you can take a look on some helpful libraries like Hamcrest or FEST (<a href="http://docs.codehaus.org/display/FEST/Fluent+Assertions+Module" rel="nofollow">http://docs.codehaus.org/display/FEST/Fluent+Assertions+Module</a>). FEST is simpler for beginners I think.</p> |
39,409,328 | Storing injector instance for use in components | <p>Before RC5 I was using appref injector as a service locator like this:</p>
<p>Startup.ts</p>
<pre><code>bootstrap(...)
.then((appRef: any) => {
ServiceLocator.injector = appRef.injector;
});
</code></pre>
<p>ServiceLocator.ts</p>
<pre><code>export class ServiceLocator {
static injector: Injector;
}
</code></pre>
<p>components:</p>
<pre><code>let myServiceInstance = <MyService>ServiceLocator.injector.get(MyService)
</code></pre>
<p>Now doing the same in bootstrapModule().then() doesn't work because components seems to start to execute before the promise. </p>
<p>Is there a way to store the injector instance before components load?</p>
<p>I don't want to use constructor injection because I'm using the injector in a base component which derived by many components and I rather not inject the injector to all of them.</p> | 39,435,457 | 4 | 0 | null | 2016-09-09 10:21:06.787 UTC | 16 | 2020-08-27 01:37:15.9 UTC | null | null | null | null | 55,818 | null | 1 | 47 | angular | 19,306 | <p>I've managed to do it using manual boostrapping. Don't use "<code>bootstrap: [AppComponent]</code>" declaration in <code>@NgModule</code>, use <code>ngDoBootstrap</code> method instead:</p>
<pre><code>export class AppModule {
constructor(private injector: Injector) {
}
ngDoBootstrap(applicationRef: ApplicationRef) {
ServiceLocator.injector = this.injector;
applicationRef.bootstrap(AppComponent);
}
}
</code></pre> |
2,347,936 | Can't get rid of "this decimal constant is unsigned only in ISO C90" warning | <p>I'm using the FNV hash as a hashing algorithm on my Hash Table implementation but I'm getting the warning in the question title on this line:</p>
<pre><code>unsigned hash = 2166136261;
</code></pre>
<p>I don't understand why this is happening because when I do this:</p>
<pre><code>printf("%u\n", UINT_MAX);
printf("2166136261\n");
</code></pre>
<p>I get this:</p>
<pre><code>4294967295
2166136261
</code></pre>
<p>Which seems to be under the limits of my machine...</p>
<p>Why do I get the warning and what are my options to get rid of it?</p> | 2,347,946 | 1 | 0 | null | 2010-02-27 15:53:49.477 UTC | 11 | 2011-03-14 15:42:03.587 UTC | 2011-03-14 15:42:03.587 UTC | null | 259 | null | 40,480 | null | 1 | 29 | c|warnings|constants|unsigned|c89 | 22,742 | <pre><code>unsigned hash = 2166136261u; // note the u.
</code></pre>
<p>You need a suffix <code>u</code> to signify this is an unsigned number. Without the <code>u</code> suffix it will be a signed number. Since</p>
<pre><code>2166136261 > 2³¹ - 1 = INT_MAX,
</code></pre>
<p>this integer literal will be problematic. </p> |
21,268,383 | Put entire column (each value in column) in an array? | <p>So i'm making a macro to do a bunch of things. one thing is find duplicates of cells in sheet1 from sheet2. given columnA in sheet 1, do any values in columnB on sheet2 match any of the values in columna sheet1.</p>
<p>I know theres a remove duplicates, but I just want to mark them, not remove. </p>
<p>I was thinking something with the filtering. I know when you filter you can select multiple criteria, so if u have a column with 20 different values in it, you can select 5 values in the filter and it will show rows with those 5 values for the particular column. So i recorded a macro of that, and checked out the code, and I see for that it uses a string array, where each value to search for is in a string array. Is there any way to just specify an entire column and add every value to the string array?</p>
<p>thanks in advance</p> | 21,269,273 | 2 | 0 | null | 2014-01-21 20:25:44.507 UTC | 6 | 2020-09-09 07:40:19.98 UTC | 2018-07-09 19:34:03.733 UTC | null | -1 | null | 1,759,942 | null | 1 | 9 | vba|excel|duplicates|excel-2010 | 78,435 | <p>Here are three different ways to load items into an array. The first method is much faster but simply stores everything in the column. You have to be careful with this though because it creates a multidimensional array which isn't something that can be passed to AutoFilter.</p>
<p>Method 1:</p>
<pre><code>Sub LoadArray()
Dim strArray As Variant
Dim TotalRows As Long
TotalRows = Rows(Rows.Count).End(xlUp).Row
strArray = Range(Cells(1, 1), Cells(TotalRows, 1)).Value
MsgBox "Loaded " & UBound(strArray) & " items!"
End Sub
</code></pre>
<p>Method 2:</p>
<pre><code>Sub LoadArray2()
Dim strArray() As String
Dim TotalRows As Long
Dim i As Long
TotalRows = Rows(Rows.Count).End(xlUp).Row
ReDim strArray(1 To TotalRows)
For i = 1 To TotalRows
strArray(i) = Cells(i, 1).Value
Next
MsgBox "Loaded " & UBound(strArray) & " items!"
End Sub
</code></pre>
<p>if you know the values ahead of time and just want to list them in a variable you can assign a variant using Array()</p>
<pre><code>Sub LoadArray3()
Dim strArray As Variant
strArray = Array("Value1", "Value2", "Value3", "Value4")
MsgBox "Loaded " & UBound(strArray) + 1 & " items!"
End Sub
</code></pre> |
37,153,903 | How to get First and Last Day of Previous Month with Carbon - Laravel | <p>I need <strong>First</strong> and <strong>Last Day</strong> of <strong>Previous Month</strong> using Carbon Library, what I have tried is as follows:</p>
<pre><code>$firstDayofPreviousMonth = Carbon::now()->startOfMonth()->subMonth()->toDateString();
$lastDayofPreviousMonth = Carbon::now()->endOfMonth()->subMonth()->toDateString();
</code></pre>
<p>Result I'm getting is for<code>$firstDayofPreviousMonth = '2016-04-01'</code>(as current month is 5th(May)) and for <code>$lastDayofPreviousMonth = '2016-05-01'</code>.</p>
<p>I'm getting correct result for <code>$firstDayofPreviousMonth</code>, but it's giving me 30 days previous result, and giving me wrong result for <code>$lastDayofPreviousMonth</code>.</p>
<p>Can anyone help me out with this?</p> | 37,153,998 | 7 | 0 | null | 2016-05-11 05:40:00.297 UTC | 11 | 2021-09-10 09:32:56.423 UTC | 2017-06-26 03:18:17.95 UTC | null | 2,370,483 | null | 3,892,606 | null | 1 | 64 | php|laravel|date|php-carbon | 92,996 | <p>Try this:</p>
<pre><code>$start = new Carbon('first day of last month');
$end = new Carbon('last day of last month');
</code></pre> |
38,587,898 | In Influxdb, How to delete all measurements? | <p>I know <code>DROP MEASUREMENT measurement_name</code> used to drop single measurement. How to delete all measurements at once ?</p> | 38,647,418 | 4 | 1 | null | 2016-07-26 10:52:37.563 UTC | 2 | 2022-01-04 09:48:11.813 UTC | null | null | null | null | 2,929,040 | null | 1 | 41 | influxdb | 77,468 | <p>Theres no way to drop all of the measurements directly, but the query below will achieve the same result.</p>
<pre><code>DROP SERIES FROM /.*/
</code></pre> |
6,022,074 | API design Python | <p>I have found a very nice talk by Joshua Bloch:</p>
<p><a href="http://www.youtube.com/watch?v=aAb7hSCtvGw" rel="noreferrer">http://www.youtube.com/watch?v=aAb7hSCtvGw</a></p>
<p><a href="http://lcsd05.cs.tamu.edu/slides/keynote.pdf" rel="noreferrer">http://lcsd05.cs.tamu.edu/slides/keynote.pdf</a></p>
<p>While it is fairly general, some comments are only valid to statically typed languages. I am looking for something equivalent for Python.
(<a href="http://ep2011.europython.eu/conference/talks/good-api-design" rel="noreferrer">This</a> talk looks promising but has not been given yet)</p> | 6,022,243 | 1 | 0 | null | 2011-05-16 19:04:32.643 UTC | 19 | 2014-09-15 05:12:37.713 UTC | null | null | null | null | 482,819 | null | 1 | 13 | python|api | 6,575 | <p>Perhaps one of these (or both).</p>
<ul>
<li><a href="http://pyvideo.org/video/366/pycon-2011--api-design--lessons-learned">PyCon 2011: API Design: Lessons Learned by Hettinger</a></li>
<li><a href="http://pyvideo.org/video/445/pycon-2011--api-design-anti-patterns">PyCon 2011: API Design anti-patterns by Alex Martelli</a></li>
</ul> |
6,218,789 | Google +1 Button not working in IE7? | <p>Works fine in IE8, IE9, and latest Chrome and Firefox, but can't seem to get it to show up in IE7. This is even with the most basic example of using the script.</p>
<p>Anyone had similar issues? Thanks!</p> | 6,220,286 | 1 | 0 | null | 2011-06-02 18:35:02.397 UTC | 6 | 2011-07-28 13:18:11.96 UTC | null | null | null | null | 781,654 | null | 1 | 60 | internet-explorer-7|google-plus-one | 23,352 | <p><a href="http://www.google.com/support/accounts/bin/answer.py?hl=en&answer=1151309" rel="noreferrer">http://www.google.com/support/accounts/bin/answer.py?hl=en&answer=1151309</a></p>
<p>Looks like it's not supported.</p> |
5,767,129 | lenses, fclabels, data-accessor - which library for structure access and mutation is better | <p>There are at least three popular libraries for accessing and manipulating fields of records. The ones I know of are: data-accessor, fclabels and lenses. </p>
<p>Personally I started with data-accessor and I'm using them now. However recently on haskell-cafe there was an opinion of fclabels being superior.</p>
<p>Therefore I'm interested in comparison of those three (and maybe more) libraries.</p> | 5,769,285 | 1 | 1 | null | 2011-04-23 21:42:26.093 UTC | 101 | 2017-04-01 20:31:51.87 UTC | 2011-04-24 12:13:42.347 UTC | null | 34,707 | null | 263,407 | null | 1 | 178 | data-structures|haskell|record|lenses | 17,464 | <p>There are at least 4 libraries that I am aware of providing lenses.</p>
<p>The notion of a lens is that it provides something isomorphic to</p>
<pre><code>data Lens a b = Lens (a -> b) (b -> a -> a)
</code></pre>
<p>providing two functions: a getter, and a setter</p>
<pre><code>get (Lens g _) = g
put (Lens _ s) = s
</code></pre>
<p>subject to three laws:</p>
<p>First, that if you put something, you can get it back out</p>
<pre><code>get l (put l b a) = b
</code></pre>
<p>Second that getting and then setting doesn't change the answer</p>
<pre><code>put l (get l a) a = a
</code></pre>
<p>And third, putting twice is the same as putting once, or rather, that the second put wins.</p>
<pre><code>put l b1 (put l b2 a) = put l b1 a
</code></pre>
<p>Note, that the type system isn't sufficient to check these laws for you, so you need to ensure them yourself no matter what lens implementation you use.</p>
<p>Many of these libraries also provide a bunch of extra combinators on top, and usually some form of template haskell machinery to automatically generate lenses for the fields of simple record types.</p>
<p>With that in mind, we can turn to the different implementations:</p>
<p><em><strong>Implementations</strong></em></p>
<p><strong>fclabels</strong></p>
<p><a href="http://hackage.haskell.org/package/fclabels" rel="nofollow noreferrer">fclabels</a> is perhaps the most easily reasoned about of the lens libraries, because its <code>a :-> b</code> can be directly translated to the above type. It provides a <a href="http://www.haskell.org/ghc/docs/6.12.2/html/libraries/base-4.2.0.1/Control-Category.html" rel="nofollow noreferrer">Category</a> instance for <code>(:->)</code> which is useful as it allows you to compose lenses. It also provides a lawless <code>Point</code> type which generalizes the notion of a lens used here, and some plumbing for dealing with isomorphisms.</p>
<p>One hindrance to the adoption of <code>fclabels</code> is that the main package includes the template-haskell plumbing, so the package is not Haskell 98, and it also requires the (fairly non-controversial) <code>TypeOperators</code> extension.</p>
<p><strong>data-accessor</strong></p>
<p>[Edit: <code>data-accessor</code> is no longer using this representation, but has moved to a form similar to that of <code>data-lens</code>. I'm keeping this commentary, though.]</p>
<p><a href="http://hackage.haskell.org/package/data-accessor" rel="nofollow noreferrer">data-accessor</a> is somewhat more popular than <code>fclabels</code>, in part because it <em>is</em> Haskell 98. However, its choice of internal representation makes me throw up in my mouth a little bit.</p>
<p>The type <code>T</code> it uses to represent a lens is internally defined as</p>
<pre><code>newtype T r a = Cons { decons :: a -> r -> (a, r) }
</code></pre>
<p>Consequently, in order to <code>get</code> the value of a lens, you must submit an undefined value for the 'a' argument! This strikes me as an incredibly ugly and ad hoc implementation.</p>
<p>That said, Henning has included the template-haskell plumbing to automatically generate the accessors for you in a separate '<a href="http://hackage.haskell.org/package/data-accessor-template" rel="nofollow noreferrer">data-accessor-template</a>' package.</p>
<p>It has the benefit of a decently large set of packages that already employ it, being Haskell 98, and providing the all-important <code>Category</code> instance, so if you don't pay attention to how the sausage is made, this package is actually pretty reasonable choice.</p>
<p><strong>lenses</strong></p>
<p>Next, there is the <a href="http://hackage.haskell.org/packages/archive/lenses/0.1.4/doc/html/Data-Lenses.html" rel="nofollow noreferrer">lenses</a> package, which observes that a lens can provide a state monad homomorphism between two state monads, by definining lenses directly <em>as</em> such monad homomorphisms.</p>
<p>If it actually bothered to provide a type for its lenses, they would have a rank-2 type like:</p>
<pre><code>newtype Lens s t = Lens (forall a. State t a -> State s a)
</code></pre>
<p>As a result, I rather don't like this approach, as it needlessly yanks you out of Haskell 98 (if you want a type to provide to your lenses in the abstract) and deprives you of the <code>Category</code> instance for lenses, which would let you compose them with <code>.</code>. The implementation also requires multi-parameter type classes.</p>
<p>Note, all of the other lens libraries mentioned here provide some combinator or can be used to provide this same state focalization effect, so nothing is gained by encoding your lens directly in this fashion.</p>
<p>Furthermore, the side-conditions stated at the start don't really have a nice expression in this form. As with 'fclabels' this does provide template-haskell method for automatically generating lenses for a record type directly in the main package.</p>
<p>Because of the lack of <code>Category</code> instance, the baroque encoding, and the requirement of template-haskell in the main package, this is my least favorite implementation.</p>
<p><strong>data-lens</strong></p>
<p>[Edit: As of 1.8.0, these have moved from the comonad-transformers package to data-lens]</p>
<p>My <a href="http://hackage.haskell.org/package/data-lens" rel="nofollow noreferrer"><code>data-lens</code></a> package provides lenses in terms of the <a href="http://hackage.haskell.org/packages/archive/comonad-transformers/1.5.2.6/doc/html/Control-Comonad-Trans-Store-Lazy.html" rel="nofollow noreferrer">Store</a> comonad.</p>
<pre><code>newtype Lens a b = Lens (a -> Store b a)
</code></pre>
<p>where</p>
<pre><code>data Store b a = Store (b -> a) b
</code></pre>
<p>Expanded this is equivalent to</p>
<pre><code>newtype Lens a b = Lens (a -> (b, b -> a))
</code></pre>
<p>You can view this as factoring out the common argument from the getter and the setter to return a pair consisting of the result of retrieving the element, and a setter to put a new value back in. This offers the computational benefit that the 'setter' here can recycle some of the work used to get the value out, making for a more efficient 'modify' operation than in the <code>fclabels</code> definition, especially when accessors are chained.</p>
<p>There is also a nice theoretical justification for this representation, because the subset of 'Lens' values that satisfy the 3 laws stated in the beginning of this response are precisely those lenses for which the wrapped function is a 'comonad coalgebra' for the store comonad. This transforms 3 hairy laws for a lens <code>l</code> down to 2 nicely pointfree equivalents:</p>
<pre><code>extract . l = id
duplicate . l = fmap l . l
</code></pre>
<p>This approach was first noted and described in Russell O'Connor's <a href="https://arxiv.org/abs/1103.2841" rel="nofollow noreferrer"><code>Functor</code> is to <code>Lens</code> as <code>Applicative</code> is to <code>Biplate</code>: Introducing Multiplate</a> and was <a href="http://patternsinfp.wordpress.com/2011/01/31/lenses-are-the-coalgebras-for-the-costate-comonad/" rel="nofollow noreferrer">blogged about based on a preprint</a> by Jeremy Gibbons.</p>
<p>It also includes a number of combinators for working with lenses strictly and some stock lenses for containers, such as <code>Data.Map</code>.</p>
<p>So the lenses in <code>data-lens</code> form a <code>Category</code> (unlike the <code>lenses</code> package), are Haskell 98 (unlike <code>fclabels</code>/<code>lenses</code>), are sane (unlike the back end of <code>data-accessor</code>) and provide a slightly more efficient implementation, <a href="http://hackage.haskell.org/package/data-lens-fd" rel="nofollow noreferrer"><code>data-lens-fd</code></a> provides the functionality for working with MonadState for those willing to step outside of Haskell 98, and the template-haskell machinery is now available via <a href="http://hackage.haskell.org/package/data-lens-template" rel="nofollow noreferrer"><code>data-lens-template</code></a>.</p>
<p><em><strong>Update 6/28/2012: Other Lens Implementation Strategies</strong></em></p>
<p><strong>Isomorphism Lenses</strong></p>
<p>There are two other lens encodings worth considering. The first gives a nice theoretical way to view a lens as a way to break a structure into the value of the field, and 'everything else'.</p>
<p>Given a type for isomorphisms</p>
<pre><code>data Iso a b = Iso { hither :: a -> b, yon :: b -> a }
</code></pre>
<p>such that valid members satisfy <code>hither . yon = id</code>, and <code>yon . hither = id</code></p>
<p>We can represent a lens with:</p>
<pre><code>data Lens a b = forall c. Lens (Iso a (b,c))
</code></pre>
<p>These are primarily useful as a way to think about the meaning of lenses, and we can use them as a reasoning tool to explain other lenses.</p>
<p><strong>van Laarhoven Lenses</strong></p>
<p>We can model lenses such that they can be composed with <code>(.)</code> and <code>id</code>, even without a <code>Category</code> instance by using</p>
<pre><code>type Lens a b = forall f. Functor f => (b -> f b) -> a -> f a
</code></pre>
<p>as the type for our lenses.</p>
<p>Then defining a lens is as easy as:</p>
<pre><code>_2 f (a,b) = (,) a <$> f b
</code></pre>
<p>and you can validate for yourself that function composition is lens composition.</p>
<p>I've recently written on how you can further <a href="http://comonad.com/reader/2012/mirrored-lenses/" rel="nofollow noreferrer">generalize van Laarhoven lenses</a> to get lens families that can change the types of fields, just by generalizing this signature to</p>
<pre><code>type LensFamily a b c d = forall f. Functor f => (c -> f d) -> a -> f b
</code></pre>
<p>This does have the unfortunate consequence that the best way to talk about lenses is to use rank 2 polymorphism, but you don't need to use that signature directly when defining lenses.</p>
<p>The <code>Lens</code> I defined above for <code>_2</code> is actually a <code>LensFamily</code>.</p>
<pre><code>_2 :: Functor f => (a -> f b) -> (c,a) -> f (c, b)
</code></pre>
<p>I've written a library that includes lenses, lens families, and other generalizations including getters, setters, folds and traversals. It is available on hackage as the <a href="http://hackage.haskell.org/package/lens" rel="nofollow noreferrer"><code>lens</code></a> package.</p>
<p>Again, a big advantage of this approach is that library maintainers can actually create lenses in this style in your libraries without incurring any lens library dependency whatsoever, by just supplying functions with type <code>Functor f => (b -> f b) -> a -> f a</code>, for their particular types 'a' and 'b'. This greatly lowers the cost of adoption.</p>
<p>Since you don't need to actually use the package to define new lenses, it takes a lot of pressure off my earlier concerns about keeping the library Haskell 98.</p> |
36,489,579 | "This" within es6 class method | <p>For some reason I'm getting weird values for "this" in my es6 class...</p>
<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>'use strict';
class Clicker {
constructor(element) {
this.count = 0;
this.elem = element;
this.elem.addEventListener('click', this.click);
// logs Clicker { count:0, elem: button#thing} as expected
console.log(this);
}
click() {
// logs <button id="thing">...</button> as unexpected...
console.log(this);
this.count++;
}
}
var thing = document.getElementById('thing');
var instance = new Clicker(thing);</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><button id="thing">Click me</button></code></pre>
</div>
</div>
</p>
<h2>Question:</h2>
<p>Why is the "this" inside of of the Clickers' click method referring to the dom node rather than ... itself? </p>
<p>More importantly, how do I refer to Clickers' count property from within its' click method if I can't use "this" to do it?</p> | 36,489,599 | 1 | 0 | null | 2016-04-08 00:34:59.17 UTC | 17 | 2016-04-08 02:08:55.81 UTC | null | null | null | null | 1,529,909 | null | 1 | 39 | javascript|class|ecmascript-6|this | 32,938 | <blockquote>
<p>Why is the "this" inside of of the Clickers' click method referring to
the dom node rather than ... itself?</p>
</blockquote>
<p>Because the specification for <code>.addEventListener()</code> is to set the <code>this</code> pointer to the DOM element that caught the event. That's how it is designed to work.</p>
<hr>
<p>When passing a method as a callback where you want to override the value of <code>this</code>, you can use <code>.bind()</code> to force the desired value of <code>this</code> with it:</p>
<pre><code>this.elem.addEventListener('click', this.click.bind(this));
</code></pre>
<p><strong>Explanation:</strong></p>
<p>All function calls in Javascript set a new value of <code>this</code> according to how the function is called. See <a href="https://stackoverflow.com/questions/28016664/when-you-pass-this-as-an-argument/28016676#28016676">this explanation</a> for further info on that basic set of rules.</p>
<p>On top of that, when you do this:</p>
<pre><code>this.elem.addEventListener('click', this.click);
</code></pre>
<p>You are just getting the <code>this.click</code> method and passing that method alone to <code>addEventListener()</code>. The value of <code>this</code> will be completely lost. It's as if you are doing this:</p>
<pre><code>var m = this.click; // m here is just a reference to Clicker.prototype.click
this.elem.addEventListener('click', m);
</code></pre>
<p>On top of this, <code>.addEventListener()</code> is specifically built to set it's own value of <code>this</code> when it calls the callback (to point <code>this</code> at the element creating the event).</p>
<p>So, you can use <code>.bind()</code> as shown above to force the proper value of <code>this</code> to be in place when your method is called.</p>
<hr>
<p>For reference, you may find <a href="https://stackoverflow.com/questions/28016664/when-you-pass-this-as-an-argument/28016676#28016676">this description of the six ways that <code>this</code> is set</a> for a function call in Javascript to be useful.</p>
<hr>
<p><strong>Other Options</strong></p>
<p>I find <code>.bind()</code> to be the clearest way of defining this, but you could also use either a local anonymous function:</p>
<pre><code>var self = this;
this.elem.addEventListener('click', function() {
self.click();
});
</code></pre>
<p>or in ES6, an arrow function:</p>
<pre><code>this.elem.addEventListener('click', () => this.click());
</code></pre>
<p>The arrow function will preserve the value of <code>this</code> for you automatically to avoid needing the <code>self</code> reference used in the prior example.</p> |
36,667,548 | How to create a series of numbers using Pandas in Python | <p>I am new to python and have recently learnt to create a series in python using Pandas. I can define a series eg: <code>x = pd.Series([1, 2, 3, 4, 5])</code> but how to define the series for a range, say 1 to 100 rather than typing all elements from 1 to 100? </p> | 36,667,605 | 5 | 0 | null | 2016-04-16 17:45:15.22 UTC | 4 | 2022-07-29 08:00:15.743 UTC | 2016-04-16 19:53:32.327 UTC | null | 2,411,802 | null | 6,213,726 | null | 1 | 29 | python|python-3.x|pandas|range|series | 74,954 | <p>As seen in <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.html" rel="noreferrer">the docs for pandas.Series</a>, all that is required for your <code>data</code> parameter is an <em>array-like, dict, or scalar value</em>. Hence to create a series for a range, you can do exactly the same as you would to create a list for a range. </p>
<pre><code>one_to_hundred = pd.Series(range(1,101))
</code></pre> |
40,489,292 | CSS positioning issues: invalid property value | <p>I have some very simple HTML/CSS code, and no matter what I do, I always get an "invalid property value" exception by chrome, and the logo won't position properly.</p>
<p>Fixed the first problem, but now the image does not move related to the border.</p>
<pre><code><html lang="de" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>my website</title>
<style type="text/css">
*{ padding: 0; margin: 0; }
.header {
width: 100%;
height: 100px;
border: none;
border-bottom-style: solid;
border-bottom-width: 5px;
position: relative;
border-bottom-color: rgb(220,30,60);
}
.logo {
position: absolute;
padding-bottom:50px;
height: 150%;
width: auto;
}
</style>
</head>
<body>
<div class="header" id="header">
<img id="logo" class="logo" src="image.png"/>
</div>
</body>
</html>
</code></pre> | 40,489,435 | 4 | 6 | null | 2016-11-08 14:20:57.29 UTC | null | 2020-12-20 11:09:52.023 UTC | 2020-12-20 11:09:52.023 UTC | null | 6,296,561 | null | 7,130,966 | null | 1 | 15 | html|css|position|padding | 70,891 | <p>I just don't understand why you used <strong>padding-bottom</strong> instead of <strong>bottom</strong> in this case. Anyway:</p>
<pre><code> <html lang="de" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>my website</title>
<style type="text/css">
*{ padding: 0; margin: 0; }
.header {
position: relative;
height: 100px;
border-bottom: 5px solid rgb(220,30,60);
}
.logo {
position: absolute;
bottom:50px;
height: 150%;
width: auto;
}
</style>
</head>
<body>
<div class="header" id="header">
<img id="logo" class="logo" src="image.png"/>
</div>
</body>
</html>
</code></pre>
<p>CSS <strong>bottom</strong> property: <a href="http://www.w3schools.com/cssref/pr_pos_bottom.asp" rel="nofollow noreferrer">http://www.w3schools.com/cssref/pr_pos_bottom.asp</a></p>
<p>CSS <strong>padding-bottom</strong> property: <a href="http://www.w3schools.com/cssref/pr_padding-bottom.asp" rel="nofollow noreferrer">http://www.w3schools.com/cssref/pr_padding-bottom.asp</a></p> |
37,528,652 | How to check the timezone of oracle pl/sql developer | <p>Where do I check the timezone of oracle <strong>pl/sql developer</strong>.Can someone help please</p> | 37,531,359 | 2 | 0 | null | 2016-05-30 14:56:51.247 UTC | null | 2016-05-30 17:57:19.12 UTC | null | null | null | null | 4,795,471 | null | 1 | 7 | sql|oracle|plsql|plsqldeveloper | 52,935 | <p>I just ran <code>select systimestamp from dual;</code> in SQL developer on my machine, it replied with <code>30-MAY-16 12.49.28.279000000 PM -05:00</code>. The -05:00 shows the timezone offset (5 hours behind UTC, essentially 5 hours behind GMT with no daylight savings time adjustments made to GMT). This shows the database server time zone.</p>
<p>Then I ran <code>select current_timestamp from dual;</code> and I got: <code>30-MAY-16 12.54.17.762000000 PM AMERICA/CHICAGO</code> which in fact is the same timezone (but in different format - it depends on the settings I have). I get the same result because my "server" is on my personal laptop, which is also the "client". In the general case, the timezone component from this query will be the "local" or "client" or "session" timezone, while the first query (with systimestamp) gives the "server" or "database" timezone.</p> |
51,172,076 | Python error: the following arguments are required | <p>I have the Python script that works well when executing it via command line.
What I'm trying to do is to import this script to another python file and run it from there. </p>
<p>The problem is that the initial script requires arguments. They are defined as follows:</p>
<pre><code>#file one.py
def main(*args):
import argparse
parser = argparse.ArgumentParser(description='MyApp')
parser.add_argument('-o','--output',dest='output', help='Output file image', default='output.png')
parser.add_argument('files', metavar='IMAGE', nargs='+', help='Input image file(s)')
a = parser.parse_args()
</code></pre>
<p>I imported this script to another file and passed arguments:</p>
<pre><code>#file two.py
import one
one.main('-o file.png', 'image1.png', 'image2.png')
</code></pre>
<p>But although I defined input images as arguments, I still got the following error:</p>
<pre><code>usage: two.py [-h] [-o OUTPUT]
IMAGE [IMAGE ...]
two.py: error: the following arguments are required: IMAGE
</code></pre> | 51,172,247 | 2 | 0 | null | 2018-07-04 11:00:02.3 UTC | 1 | 2022-08-23 18:46:58.097 UTC | 2018-07-04 11:39:00.157 UTC | null | 8,701,393 | null | 8,701,393 | null | 1 | 7 | python|python-import|argparse|args | 72,958 | <p>When calling <code>argparse</code> with arguments not from <code>sys.argv</code> you've got to call it with</p>
<pre><code>parser.parse_args(args)
</code></pre>
<p>instead of just</p>
<pre><code>parser.parse_args()
</code></pre> |
38,058,950 | get value out of dataframe | <p>In Scala I can do <code>get(#)</code> or <code>getAs[Type](#)</code> to get values out of a dataframe. How should I do it in <code>pyspark</code>?</p>
<p>I have a two columns DataFrame: <code>item(string)</code> and <code>salesNum(integers)</code>. I do a <code>groupby</code> and <code>mean</code> to get a mean of those numbers like this: </p>
<p><code>saleDF.groupBy("salesNum").mean()).collect()</code></p>
<p>and it works. Now I have the mean in a dataframe with one value.</p>
<p>How can I get that value out of the dataframe to get the mean as a float number?</p> | 38,059,262 | 3 | 0 | null | 2016-06-27 16:30:21.707 UTC | 5 | 2020-06-07 15:22:00.04 UTC | 2019-01-09 09:47:13.753 UTC | null | 1,714,692 | null | 2,525,128 | null | 1 | 23 | python|pyspark|type-conversion|apache-spark-sql | 110,779 | <p><code>collect()</code> returns your results as a python list. To get the value out of the list you just need to take the first element like this: </p>
<pre><code>saleDF.groupBy("salesNum").mean()).collect()[0]
</code></pre> |
1,276,909 | PHP syntax question: What does the question mark and colon mean? | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/889373/quick-php-syntax-question">quick php syntax question</a> </p>
</blockquote>
<pre><code>return $add_review ? FALSE : $arg;
</code></pre>
<p>What do question mark and colon mean?</p>
<p>Thanks</p> | 1,276,912 | 2 | 7 | null | 2009-08-14 09:27:00 UTC | 26 | 2022-01-15 16:20:04.673 UTC | 2017-05-23 12:34:48.327 UTC | null | -1 | Petkun | null | null | 1 | 83 | php|syntax|ternary-operator | 153,914 | <p>This is the PHP <a href="https://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary" rel="noreferrer">ternary operator</a> (also known as a conditional operator) - if first operand evaluates true, evaluate as second operand, else evaluate as third operand.</p>
<p>Think of it as an "if" statement you can use in expressions. Can be very useful in making concise assignments that depend on some condition, e.g.</p>
<pre><code>$param = isset($_GET['param']) ? $_GET['param'] : 'default';
</code></pre>
<p>There's also a shorthand version of this (in PHP 5.3 onwards). You can leave out the middle operand. The operator will evaluate as the first operand if it true, and the third operand otherwise. For example:</p>
<pre><code>$result = $x ?: 'default';
</code></pre>
<p>It is worth mentioning that the above code when using i.e. $_GET or $_POST variable will throw undefined index notice and to prevent that we need to use a longer version, with <code>isset</code> or <a href="http://php.net/manual/en/migration70.new-features.php#migration70.new-features.null-coalesce-op" rel="noreferrer">a null coalescing operator</a> which is introduced in PHP7:</p>
<pre><code>$param = $_GET['param'] ?? 'default';
</code></pre> |
2,579,883 | Using external javascript files in a .js file | <p>I would like to use an external javascript file in another javascript file. For example, I could store all my global variables in a globals.js file and then call then from the website logic logic.js. Then in the index.html, i would insert the tag. How do I use the globals.js inside the logic.js?</p> | 2,579,902 | 5 | 0 | null | 2010-04-05 17:32:59.743 UTC | 10 | 2022-05-16 12:14:37 UTC | null | null | null | null | 138,943 | null | 1 | 32 | javascript | 81,627 | <p>Javascript doesn't have any implicit "include this other file" mechanisms, like css's @include. You just have to list your globals file before the logic file in the tags:</p>
<pre><code> <script type="text/javascript" src="globals.js" />
<script type="text/javascript" src="logic.js" />
</code></pre>
<p>If guaranteeing that the globals are available before anything in the logic file fires up, you can do a slow polling loop to see if some particular variable is available before calling an init() or whatever function.</p> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.