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
9,376,384
Sort a list of tuples depending on two elements
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/3979872/python-how-to-sort-a-complex-list-on-two-different-keys">python: how to sort a complex list on two different keys</a> </p> </blockquote> <p>I've got a list of tuples. I want to sort them depending two elements. Here is following example</p> <pre><code>unsorted = [('a', 4, 2), ('a', 4, 3), ('a', 7, 2), ('a', 7, 3), ('b', 4, 2), ('b', 4, 3), ('b', 7, 2), ('b', 7, 3)] sorted = [('a', 4, 2), ('b', 4, 2), ('a', 4, 3), ('b', 4, 3), ('a', 7, 2), ('b', 7, 2), ('a', 7, 3), ('b', 7, 3)] </code></pre> <p>I know how to sort them on the second element:</p> <pre><code>sorted(unsorted, key = lambda element : element[1]) </code></pre> <p>But how to do that with two keys?</p>
9,376,419
1
2
null
2012-02-21 11:01:21.263 UTC
13
2012-02-21 11:04:07.923 UTC
2017-05-23 12:02:24.833 UTC
null
-1
null
967,164
null
1
56
python|sorting|python-3.x|tuples
62,146
<pre><code>sorted(unsorted, key=lambda element: (element[1], element[2])) </code></pre> <p>I've assumed an order for the keys from the sample output.</p>
16,120,697
Kotlin: how to pass a function as parameter to another?
<p>Given function foo :</p> <pre><code>fun foo(m: String, bar: (m: String) -&gt; Unit) { bar(m) } </code></pre> <p>We can do:</p> <pre><code>foo("a message", { println("this is a message: $it") } ) //or foo("a message") { println("this is a message: $it") } </code></pre> <p>Now, lets say we have the following function:</p> <pre><code>fun buz(m: String) { println("another message: $m") } </code></pre> <p>Is there a way I can pass "buz" as a parameter to "foo" ? Something like:</p> <pre><code>foo("a message", buz) </code></pre>
33,402,863
11
0
null
2013-04-20 13:04:06.723 UTC
29
2022-03-12 05:07:04.833 UTC
2017-06-15 17:08:41.263 UTC
null
1,530,549
null
393,786
null
1
274
kotlin
163,595
<p>Use <code>::</code> to signify a function reference, and then:</p> <pre><code>fun foo(msg: String, bar: (input: String) -&gt; Unit) { bar(msg) } // my function to pass into the other fun buz(input: String) { println(&quot;another message: $input&quot;) } // someone passing buz into foo fun something() { foo(&quot;hi&quot;, ::buz) } </code></pre> <p><a href="https://kotlinlang.org/docs/reference/whatsnew11.html#bound-callable-references" rel="noreferrer">Since Kotlin 1.1</a> you can now use functions that are class members (&quot;<em>Bound Callable References</em>&quot;), by prefixing the function reference operator with the instance:</p> <pre><code>foo(&quot;hi&quot;, OtherClass()::buz) foo(&quot;hi&quot;, thatOtherThing::buz) foo(&quot;hi&quot;, this::buz) </code></pre>
16,396,297
Camera preview freezes after screen lock
<p>The custom camera app I've written stops giving the preview after the screen locks (by pushing lock butten or waiting for a couple of minutes). I don't get an exception, which makes it quite difficult to find the problem. </p> <p>Does the android screen lock (if that's the correct term) pauses/halts/... my App (activity)? </p> <p>If this were the case, could the cause be my onPause/onResume methods? Or is another cause mor likely? </p> <p>Thanks in advance</p>
16,532,667
4
1
null
2013-05-06 10:01:27.407 UTC
10
2017-03-01 08:05:36.567 UTC
null
null
null
null
2,320,084
null
1
20
java|android|android-activity|camera
7,111
<p>I faced same problem and fixed it using following steps:</p> <ol> <li><p>I created my camera preview and added it to the container FrameLayout in onResume() of the parent activity. Something like:</p> <pre><code>public void onResume{ super.onResume(); mCamera = Camera.open(); if(null != mCamera){ mCamera.setDisplayOrientation(90); mPreview = new CameraOverlay(getActivity(), mCamera); frLyParent.addView(mPreview); } } </code></pre></li> <li><p>I removed the view in onPause(). This fixes the freeze.</p> <pre><code>public void onPause(){ super.onPause(); if(null != mCamera){ mCamera.release(); mCamera = null; } frLyParent.removeView(mPreview); mPreview = null; } </code></pre></li> </ol> <p>where CameraOverlay() is the class which extends SurfaceView and implements SurfaceHolder.Callback. Do let me know if you need that implementation. </p>
16,105,485
unsupported operand type(s) for *: 'float' and 'Decimal'
<p>I'm just playing around learning classes functions etc, So I decided to create a simple function what should give me tax amount.</p> <p>this is my code so far.</p> <pre><code>class VAT_calculator: """ A set of methods for VAT calculations. """ def __init__(self, amount=None): self.amount = amount self.VAT = decimal.Decimal('0.095') def initialize(self): self.amount = 0 def total_with_VAT(self): """ Returns amount with VAT added. """ if not self.amount: msg = u"Cannot add VAT if no amount is passed!'" raise ValidationError(msg) return (self.amount * self.VAT).quantize(self.amount, rounding=decimal.ROUND_UP) </code></pre> <p>My issue is I'm getting the following error:</p> <blockquote> <p>unsupported operand type(s) for *: 'float' and 'Decimal'**</p> </blockquote> <p>I don't see why this should not work!</p>
16,105,582
2
1
null
2013-04-19 13:13:25.863 UTC
7
2018-03-20 05:18:01.86 UTC
2018-03-20 05:18:01.86 UTC
null
3,962,914
null
578,822
null
1
76
python|django
140,147
<p>It seems like <code>self.VAT</code> is of <code>decimal.Decimal</code> type and <code>self.amount</code> is a <code>float</code>, thing that you can't do.</p> <p>Try <code>decimal.Decimal(self.amount) * self.VAT</code> instead.</p>
28,947,607
ascii codec cant decode byte 0xe9
<p>I have done some research and seen solutions but none have worked for me.</p> <p><a href="https://stackoverflow.com/questions/9644099/python-ascii-codec-cant-decode-byte">Python - &#39;ascii&#39; codec can&#39;t decode byte</a> </p> <p>This didn't work for me. And I know the 0xe9 is the é character. But I still can't figure out how to get this working, here is my code</p> <pre><code>output_lines = ['&lt;menu&gt;', '&lt;day name="monday"&gt;', '&lt;meal name="BREAKFAST"&gt;', '&lt;counter name="Entreé"&gt;', '&lt;dish&gt;', '&lt;name icon1="Vegan" icon2="Mindful Item"&gt;', 'Cream of Wheat (Farina)','&lt;/name&gt;', '&lt;/dish&gt;', '&lt;/counter &gt;', '&lt;/meal &gt;', '&lt;/day &gt;', '&lt;/menu &gt;'] output_string = '\n'.join([line.encode("utf-8") for line in output_lines]) </code></pre> <p>And this give me the error <code>ascii codec cant decode byte 0xe9</code></p> <p>And I have tried decoding, I have tried to replace the "é" but can't seem to get that to work either.</p>
28,947,833
4
8
null
2015-03-09 16:55:36.733 UTC
null
2015-03-09 17:23:27.21 UTC
2017-05-23 10:31:00.813 UTC
null
-1
null
3,961,428
null
1
7
python|unicode|encoding|utf-8|decode
40,231
<p>You are trying to encode bytestrings:</p> <pre><code>&gt;&gt;&gt; '&lt;counter name="Entreé"&gt;'.encode('utf8') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 20: ordinal not in range(128) </code></pre> <p>Python is trying to be helpful, you can only encode a <em>Unicode</em> string to bytes, so to encode Python first implictly <em>decodes</em>, using the default encoding.</p> <p>The solution is to <em>not encode</em> data that is already encoded, or first decode using a suitable codec before trying to encode again, if the data was encoded to a different codec than what you needed.</p> <p>If you have a mix of unicode and bytestring values, decode just the bytestrings or encode just the unicode values; try to avoid mixing the types. The following decodes byte strings to unicode first:</p> <pre><code>def ensure_unicode(v): if isinstance(v, str): v = v.decode('utf8') return unicode(v) # convert anything not a string to unicode too output_string = u'\n'.join([ensure_unicode(line) for line in output_lines]) </code></pre>
17,403,795
Populate state and city dropdowns based on country and state using jQuery
<p>I am trying to accomplish dropdowns using JSON. I want 3 dropdowns. First populate the country dropdown (eg: usa, uk etc.,). Now, when the user select USA then states dropdown needs to be populated by using jQuery .change(). Again when user select the state they need to be presented with cities dropdowns.</p> <p>How can I achieve this? As my JSON file is slightly big I have added it here and tried to populate countries dropdown but unable to generate states and cities drop down...</p> <p><a href="http://jsfiddle.net/vCFv6/" rel="nofollow">http://jsfiddle.net/vCFv6/</a></p> <pre><code>$.each(myJson.country, function (index, value) { $("#country").append('&lt;option value="'+value.id+'"&gt;'+value.name+'&lt;/option&gt;');}); </code></pre> <p>The above code helps me populate just the countries but not others like states and cities. Any help is much appreciated.</p> <p>Thanks in advance.</p>
17,404,238
4
1
null
2013-07-01 11:48:32.357 UTC
3
2019-02-06 12:14:10.553 UTC
2018-10-17 09:41:38.917 UTC
null
87,015
null
1,395,787
null
1
6
javascript|jquery|json|ajax|html-select
66,816
<p>Exactly like others said, you have to handle the <code>onchange</code> event of country &amp; state select inputs &amp; apply your logic. I have fiddled here for getting states dynamically on selecting a country, you might be able to code the rest yourself - <a href="http://jsfiddle.net/YqLh8/" rel="nofollow noreferrer">Fiddle</a></p> <p><strike>You may also see this Populating Dropdown Based On Other Dropdown Value</strike></p>
17,312,949
Delphi Error Dataset not in Insert or Edit Mode
<p>Objective:</p> <ol> <li>Click on the button on the TRxDBCombo to call a search box</li> <li>On Selecting the record from search box, the result is set as Field Value for the TComboEditBox and is posted in the TRxMemoryData Dataset</li> </ol> <p>The Error:</p> <p>Dataset not in Insert or Edit Mode appears the second time of calling this function</p> <pre><code>TDBEditBox1.SetFocus; Form_Search:= TForm_Search.Create(Application); with Form_Search do Begin showmodal; //Get Result from Database if trim(TempResult) &lt;&gt; '' then Begin TDBEditBox1.Field.Value := MResult; End; End; </code></pre> <p>The setup includes:</p> <ol> <li>A TJvDBGrid with the Data Source connected to a TDataSource</li> <li>The TDataSource is Connected to a TRxMemoryData</li> <li>A TRxDBComboEdit with its Data Source set to the TDataSource in step 2 above</li> </ol> <p>Please assist</p>
17,334,907
1
2
null
2013-06-26 06:25:34.33 UTC
null
2013-06-27 05:05:33.263 UTC
2013-06-26 13:12:24.76 UTC
null
1,744,164
null
964,576
null
1
6
delphi|delphi-7
42,870
<p>The error is coming because of the following line: <strong>TDBEditBox1.Field.Value := MResult;</strong> at this line your dataset is not in Insert or Edit mode. You can add following check to avoid this error:</p> <pre><code>if not (TDBEditBox1.DataSource.DataSet.State in [dsEdit, dsInsert]) then begin TDBEditBox1.DataSource.DataSet.Edit; // Or TDBEditBox1. DataSource.DataSet.Insert; depending on the operation you are doing (Edit or Insert) end; TDBEditBox1.Field.Value := MResult; </code></pre>
17,329,924
How to get Java File absolute path from InputStream?
<p>I'm on Java 6 and I have a method that scans the runtime classpath for a file called <code>config.xml</code>. If found, I would like to read the contents of the file into a string:</p> <pre><code>InputStream istream = this.getClass().getClassLoader().getResourceAsStream("config.xml"); if(istream != null) { System.out.println("Found config.xml!"); StringBuffer fileData = new StringBuffer(1000); BufferedReader reader; try { reader = new BufferedReader(new FileReader(fileName)); char[] buf = new char[1024]; int numRead = 0; while((numRead=reader.read(buf)) != -1) { String readData = String.valueOf(buf, 0, numRead); fileData.append(readData); buf = new char[1024]; reader.close(); } } catch (FileNotFoundException fnfExc) { throw new RuntimeException("FileNotFoundException: " + fnfExc.getMessage()); } catch (IOException ioExc) { throw new RuntimeException("IOException: " + ioExc.getMessage()); } } </code></pre> <p>When I run this code, I get the following console output:</p> <pre><code>Found config.xml! Exception in thread "main" java.lang.RuntimeException: FileNotFoundException: config.xml (No such file or directory) at com.me.myapp.Configurator.readConfigFileFromClasspath(Configurator.java:556) at com.me.myapp.Configurator.&lt;init&gt;(Configurator.java:34) ...rest of stack trace omitted for brevity </code></pre> <p>So the classpath scan for <code>config.xml</code> is successful, but then the reader can't seem to find the file. <strong>Why???</strong> My only theory is that when <code>config.xml</code> is found on the classpath, it doesn't contain an absolute path to the location of the file on the file system, and perhaps that's what the reader code is looking for.</p>
17,330,561
2
2
null
2013-06-26 20:32:39.277 UTC
2
2013-06-26 21:14:04.607 UTC
null
null
null
user1768830
null
null
1
18
java|file-io|classpath|classloader|absolute-path
78,926
<p>From your given example, it is not clear what <code>fileName</code> refers to. You should just use the stream you got from <code>getResourceAsStream()</code>to read you file, something along</p> <pre><code>reader = new BufferedReader(new InputStreamReader(istream)); </code></pre> <p>And you should avoid to repeatedly allocating <code>buf</code> new for every read cycle, once is enough.</p>
17,660,469
Get field class in annotations processor
<p>I am writing my first Annotations processor and having trouble with something that seems trivial but I cannot find any information about it.</p> <p>I have a element annotated with my annotation</p> <pre><code>@MyAnnotation String property; </code></pre> <p>When I get this property as a element in my processor I can not seem to get the type of the element in any way. In this case a would want to get a Class or TypeElement instance representing String. </p> <p>I tried instantiating a class object of the container type with <code>Class.forName()</code> but it threw a ClassNotFoundException. I think this is because I do not have access to the class loader containing the class?</p>
17,660,882
1
2
null
2013-07-15 17:43:31.077 UTC
14
2015-10-26 18:18:33.463 UTC
2013-07-15 17:49:07.617 UTC
null
771,578
null
662,994
null
1
19
java|annotations
13,325
<p>When running your annotation processor, you don't have access to the compiled classes. The point of annotation processing is that it happens pre-compile.</p> <p>Instead, you need to create an annotation processor that specifically handles your annotation type, then use the mirror API to access the field. For example:</p> <pre><code>@SupportedAnnotationTypes("com.example.MyAnnotation") public class CompileTimeAnnotationProcessor extends AbstractProcessor { @Override public boolean process(Set&lt;? extends TypeElement&gt; annotations, RoundEnvironment roundEnv) { // Only one annotation, so just use annotations.iterator().next(); Set&lt;? extends Element&gt; elements = roundEnv.getElementsAnnotatedWith( annotations.iterator().next()); Set&lt;VariableElement&gt; fields = ElementFilter.fieldsIn(elements); for (VariableElement field : fields) { TypeMirror fieldType = field.asType(); String fullTypeClassName = fieldType.toString(); // Validate fullTypeClassName } return true; } } </code></pre> <p>For the validation, you <strong>cannot</strong> use any classes which have yet to be compiled (including those that are about to be compiled with the annotation) using something like <code>MyType.class</code>. For these, you must use <strong>strings only</strong>. That is because annotation processing occurs during a pre-compiling phase known as "source generation", which is what allows you to generate source code before the compiler runs using annotations.</p> <p>An example validation verifying that the field type is <code>java.lang.String</code> (which is already compiled):</p> <pre><code>for (VariableElement field : fields) { TypeMirror fieldType = field.asType(); String fullTypeClassName = fieldType.toString(); if (!String.class.getName().equals(fullTypeClassName)) { processingEnv.getMessager().printMessage( Kind.ERROR, "Field type must be java.lang.String", field); } } </code></pre> <p><strong>Resources</strong></p> <ul> <li><a href="http://docs.oracle.com/javase/7/docs/technotes/guides/apt/" rel="noreferrer">Main APT Page</a></li> <li><a href="http://docs.oracle.com/javase/7/docs/jdk/api/apt/mirror/overview-summary.html" rel="noreferrer">Mirror API Javadocs (Java 7 and older)</a></li> <li><strong>Edit:</strong> <a href="https://docs.oracle.com/javase/8/docs/api/javax/lang/model/package-summary.html" rel="noreferrer">Mirror API Javadocs (Java 8)</a> <ul> <li>Note that the mirror API is now standardized in Java 8 under <code>javax.lang.model</code> and the old API is deprecated. See <a href="https://blogs.oracle.com/darcy/entry/an_apt_replacement" rel="noreferrer">this blog post</a> for more information. If you've been using the <code>javax</code> classes, then you don't need to worry.</li> </ul></li> </ul> <p><strong>Edit:</strong></p> <blockquote> <p>I want to get the field type to get annotations on that type. But this does not seem like it will be possible?</p> </blockquote> <p>Indeed it is possible! This can be done using more methods on the <code>TypeMirror</code>:</p> <pre><code>if (fieldType.getKind() != TypeKind.DECLARED) { processingEnv.getMessager().printMessage( Kind.ERROR, "Field cannot be a generic type.", field); } DeclaredType declaredFieldType = (DeclaredType) fieldType; TypeElement fieldTypeElement = (TypeElement) declaredFieldType.asElement(); </code></pre> <p>From here, you have two choices:</p> <ol> <li>If the annotation you're trying to find is already compiled (i.e. it's from another library) then you can reference the class directly to get the annotation.</li> <li>If the annotation you're trying to find is not compiled (i.e. it's being compiled in the current call to <code>javac</code> that's running the APT) then you can reference it via <code>AnnotationMirror</code> instances.</li> </ol> <p><strong>Already Compiled</strong></p> <pre><code>DifferentAnnotation diffAnn = fieldTypeElement.getAnnotation( DifferentAnnotation.class); // Process diffAnn </code></pre> <p>Very straight-forward, this gives you direct access to the annotation itself.</p> <p><strong>Not Compiled</strong></p> <p>Note that this solution will work regardless of whether or not the annotation is compiled, it's just not as clean as the code above.</p> <p>Here are a couple methods I wrote once to extract a certain value from an annotation mirror by its class name:</p> <pre><code>private static &lt;T&gt; T findAnnotationValue(Element element, String annotationClass, String valueName, Class&lt;T&gt; expectedType) { T ret = null; for (AnnotationMirror annotationMirror : element.getAnnotationMirrors()) { DeclaredType annotationType = annotationMirror.getAnnotationType(); TypeElement annotationElement = (TypeElement) annotationType .asElement(); if (annotationElement.getQualifiedName().contentEquals( annotationClass)) { ret = extractValue(annotationMirror, valueName, expectedType); break; } } return ret; } private static &lt;T&gt; T extractValue(AnnotationMirror annotationMirror, String valueName, Class&lt;T&gt; expectedType) { Map&lt;ExecutableElement, AnnotationValue&gt; elementValues = new HashMap&lt;ExecutableElement, AnnotationValue&gt;( annotationMirror.getElementValues()); for (Entry&lt;ExecutableElement, AnnotationValue&gt; entry : elementValues .entrySet()) { if (entry.getKey().getSimpleName().contentEquals(valueName)) { Object value = entry.getValue().getValue(); return expectedType.cast(value); } } return null; } </code></pre> <p>Let's say that you're looking for the <code>DifferentAnnotation</code> annotation and your source code looks like this:</p> <pre><code>@DifferentAnnotation(name = "My Class") public class MyClass { @MyAnnotation private String field; // ... } </code></pre> <p>This code will print <code>My Class</code>:</p> <pre><code>String diffAnnotationName = findAnnotationValue(fieldTypeElement, "com.example.DifferentAnnotation", "name", String.class); System.out.println(diffAnnotationName); </code></pre>
12,042,303
Accessing variables in other Windows Form class
<p>I will appreciate if anyone can help me on this.</p> <p>I have a windows form app that has three forms: form1, form2, form3. form1 starts when the app is activated. on form1, there is a button that brings up form2, and hide form1. there is also one button that brings up form3 and hides form2 on form2.</p> <pre><code>public partial class Form1 : Form { Form2 f2= new Form2(); public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { this.Hide(); f2.Show(); } } public partial class Form2 : Form { Form3 f3 = new Form3(); private void button1_Click(object sender, EventArgs e) { this.Hide(); f3.Show(); } } </code></pre> <p>The question is on form3, i tried to access some of the variables that are assigned with values on runtime in form2. I think since i make f2 as modaless form, i should be able to access by simply using f2.myvariables, but the intellisense does not give me f2 object. Why is that? I found a way to declare those variables public static, so i could access by using form2.myvariables..Here is another thing that confuses me. Since all the values are assigned during runtime, how could static variable do this? I am a newbie on C#, and i already did a lot of searches on this, but seems no place answers my question exactly. Thanks for help in advance!!</p>
12,042,398
4
6
null
2012-08-20 17:35:47.347 UTC
2
2017-07-16 16:35:40.63 UTC
2017-07-16 16:35:40.63 UTC
null
107,625
null
1,401,920
null
1
3
c#|windows|forms
60,472
<p>So you have information in the parent form (form2) that you want to access in a method of the child form (form3).</p> <ol> <li>Create properties in <code>form3</code> for the information that it will need.</li> <li>When <code>form2</code> creates an instance of <code>form3</code> it should set those properties.</li> </ol> <p>You should think of this not as having the child form ask for information from it's parent, but rather that the parent is giving information to its child. If you shift your mindset accordingly the code becomes not only easier to write, but also will be more in line with good coding practices (lower coupling, not exposing more information externally than needed, etc.)</p> <p>To create a property you can do something like this in <code>form3</code>:</p> <pre><code>//TODO: give real name; adjust type as needed public string SomePropertyName { get; set; } </code></pre> <p>then in <code>form2</code> you can do:</p> <pre><code>f3.SomePropertyName = "hello from form2"; </code></pre> <p>or </p> <pre><code>f3.SomePropertyName = someVariableInForm2; </code></pre>
22,321,769
Function.prototype.apply.bind usages?
<p>I perfectly know the <a href="https://stackoverflow.com/a/8843181/859154">usages</a> for : </p> <p><code>Function.prototype.bind.apply(f,arguments)</code></p> <blockquote> <blockquote> <p>Explanation - Use the original (if exists) <code>bind</code> method over <code>f</code> with <code>arguments</code> (which its first item will be used as context to <code>this</code>)</p> </blockquote> </blockquote> <p><em>This code can be used ( for example) for creating new functions via constructor function with arguments</em> </p> <p>Example : </p> <pre><code>function newCall(Cls) { return new (Function.prototype.bind.apply(Cls, arguments)); } </code></pre> <p>Execution:</p> <pre><code>var s = newCall(Something, a, b, c); </code></pre> <p><strong>But</strong> I came across this one : <code>Function.prototype.apply.bind(f,arguments)</code> //word swap</p> <p><strong>Question :</strong> </p> <p><em>As it is hard to understand its meaning</em> - in what usages/scenario would I use this code ? </p>
22,322,147
1
2
null
2014-03-11 09:40:37.557 UTC
19
2014-03-11 09:55:04.413 UTC
2017-05-23 12:18:25.473 UTC
null
-1
null
859,154
null
1
15
javascript
2,772
<p>This is used to fix the first parameter of <code>.apply</code>.</p> <p>For example, when you get the max value from an array, you do:</p> <pre><code>var max_value = Math.max.apply(null, [1,2,3]); </code></pre> <p>But you want to get the first parameter fixed to <code>null</code>, so you could create an new function by:</p> <pre><code>var max = Function.prototype.apply.bind(Math.max, null); </code></pre> <p>then you could just do:</p> <pre><code>var max_value = max([1,2,3]); </code></pre>
21,632,243
How do I get asynchronous / event-driven LISTEN/NOTIFY support in Java using a Postgres database?
<p>From what I can tell, the JDBC drivers for LISTEN/NOTIFY in Java do NOT support true event-driven notifications. You have to poll the database every so often to see if there's a new notification.</p> <p>What options do I have in Java (possibly something other than JDBC?), if any, to get notifications asynchronously in a true event-driven manner without polling? </p>
23,352,527
3
6
null
2014-02-07 15:57:11.243 UTC
14
2022-04-06 04:15:13.113 UTC
null
null
null
null
3,241,719
null
1
44
java|postgresql
29,407
<p>Use the pgjdbc-ng driver.</p> <p><a href="http://impossibl.github.io/pgjdbc-ng/" rel="nofollow noreferrer">http://impossibl.github.io/pgjdbc-ng/</a></p> <p>It supports async notifications, without polling. I have used it successfully.</p> <p>See <a href="https://database-patterns.blogspot.com/2014/04/postgresql-nofify-websocket-spring-mvc.html" rel="nofollow noreferrer">https://database-patterns.blogspot.com/2014/04/postgresql-nofify-websocket-spring-mvc.html</a></p> <p>Source code: <a href="https://bitbucket.org/neilmcg/postgresql-websocket-example" rel="nofollow noreferrer">https://bitbucket.org/neilmcg/postgresql-websocket-example</a></p> <p>Oleg has a nice example answer as well</p>
26,833,517
Error inflating class android.support.v7.widget.CardView
<p>I unexpectedly encountered the following error while trying to run my application:</p> <pre><code>Binary XML file line #8: Error inflating class android.support.v7.widget.CardView </code></pre> <p>Below is the log cat:</p> <pre><code>11-09 13:11:58.558: E/AndroidRuntime(12542): FATAL EXCEPTION: main 11-09 13:11:58.558: E/AndroidRuntime(12542): android.view.InflateException: Binary XML file line #8: Error inflating class android.support.v7.widget.CardView 11-09 13:11:58.558: E/AndroidRuntime(12542): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:698) 11-09 13:11:58.558: E/AndroidRuntime(12542): at android.view.LayoutInflater.rInflate(LayoutInflater.java:746) 11-09 13:11:58.558: E/AndroidRuntime(12542): at android.view.LayoutInflater.inflate(LayoutInflater.java:489) 11-09 13:11:58.558: E/AndroidRuntime(12542): at android.view.LayoutInflater.inflate(LayoutInflater.java:396) 11-09 13:11:58.558: E/AndroidRuntime(12542): at com.dooba.beta.ThirdFragment.onCreateView(ThirdFragment.java:15) 11-09 13:11:58.558: E/AndroidRuntime(12542): at android.support.v4.app.Fragment.performCreateView(Fragment.java:1786) 11-09 13:11:58.558: E/AndroidRuntime(12542): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:947) 11-09 13:11:58.558: E/AndroidRuntime(12542): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1126) 11-09 13:11:58.558: E/AndroidRuntime(12542): at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:739) 11-09 13:11:58.558: E/AndroidRuntime(12542): at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1489) 11-09 13:11:58.558: E/AndroidRuntime(12542): at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:454) 11-09 13:11:58.558: E/AndroidRuntime(12542): at android.os.Handler.handleCallback(Handler.java:615) 11-09 13:11:58.558: E/AndroidRuntime(12542): at android.os.Handler.dispatchMessage(Handler.java:92) 11-09 13:11:58.558: E/AndroidRuntime(12542): at android.os.Looper.loop(Looper.java:137) 11-09 13:11:58.558: E/AndroidRuntime(12542): at android.app.ActivityThread.main(ActivityThread.java:4745) 11-09 13:11:58.558: E/AndroidRuntime(12542): at java.lang.reflect.Method.invokeNative(Native Method) 11-09 13:11:58.558: E/AndroidRuntime(12542): at java.lang.reflect.Method.invoke(Method.java:511) 11-09 13:11:58.558: E/AndroidRuntime(12542): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) 11-09 13:11:58.558: E/AndroidRuntime(12542): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 11-09 13:11:58.558: E/AndroidRuntime(12542): at dalvik.system.NativeStart.main(Native Method) 11-09 13:11:58.558: E/AndroidRuntime(12542): Caused by: java.lang.ClassNotFoundException: android.support.v7.widget.CardView 11-09 13:11:58.558: E/AndroidRuntime(12542): at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:61) 11-09 13:11:58.558: E/AndroidRuntime(12542): at java.lang.ClassLoader.loadClass(ClassLoader.java:501) 11-09 13:11:58.558: E/AndroidRuntime(12542): at java.lang.ClassLoader.loadClass(ClassLoader.java:461) 11-09 13:11:58.558: E/AndroidRuntime(12542): at android.view.LayoutInflater.createView(LayoutInflater.java:552) 11-09 13:11:58.558: E/AndroidRuntime(12542): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:687) 11-09 13:11:58.558: E/AndroidRuntime(12542): ... 19 more </code></pre> <p>Below is the java code:</p> <pre><code>public class ThirdFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.activity_city, container, false); return rootView; } } </code></pre> <p>Below is the layout code:</p> <pre><code>&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:card_view="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" &gt; &lt;!-- A CardView that contains a TextView --&gt; &lt;android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto" android:id="@+id/card_view" android:layout_gravity="center" android:layout_width="200dp" android:layout_height="200dp" &gt; &lt;TextView android:id="@+id/info_text" android:layout_width="match_parent" android:layout_height="match_parent" /&gt; &lt;/android.support.v7.widget.CardView&gt; &lt;/LinearLayout&gt; </code></pre> <p>Thanks in advance</p>
37,704,732
11
2
null
2014-11-09 21:26:35.123 UTC
6
2020-05-29 23:59:44.573 UTC
null
null
null
null
3,907,211
null
1
27
java|android|android-layout|android-activity
38,037
<p>I solved this by adding updated cardview and appcompat on the app/build.gradle</p> <pre><code>dependencies { ... compile 'com.android.support:appcompat-v7:23.4.0' compile 'com.android.support:cardview-v7:23.4.0' compile 'com.android.support:recyclerview-v7:23.4.0' } </code></pre> <p>Then rebuild the project</p>
26,532,081
What is wrong with my Java solution to Codility MissingInteger?
<p>I am trying to solve the codility MissingInteger problem <a href="https://codility.com/c/intro/demoZKF8W2-4TC" rel="nofollow noreferrer">link</a>:</p> <blockquote> <p>Write a function:</p> <pre><code>class Solution { public int solution(int[] A); } </code></pre> <p>that, given a non-empty zero-indexed array A of N integers, returns the minimal positive integer that does not occur in A. For example, given:</p> <pre><code> A[0] = 1 A[1] = 3 A[2] = 6 A[3] = 4 A[4] = 1 A[5] = 2 </code></pre> <p>the function should return 5.</p> <p>Assume that:</p> <p>N is an integer within the range [1..100,000]; each element of array A is an integer within the range [−2,147,483,648..2,147,483,647].</p> <p>Complexity:</p> <p>expected worst-case time complexity is O(N); expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments). Elements of input arrays can be modified.</p> </blockquote> <p>My solution is:</p> <pre><code>class Solution { TreeMap&lt;Integer,Object&gt; all = new TreeMap&lt;Integer,Object&gt;(); public int solution(int[] A) { for(int i=0; i&lt;A.length; i++) all.put(i+1,new Object()); for(int i=0; i&lt;A.length; i++) if(all.containsKey(A[i])) all.remove(A[i]); Iterator notOccur = all.keySet().iterator(); if(notOccur.hasNext()) return (int)notOccur.next(); return 1; } } </code></pre> <p>The test result is:</p> <p><img src="https://i.stack.imgur.com/zIbzR.png" alt="enter image description here"></p> <p><strong>Can anyone explain me why I got this two wrong answers?</strong> Especially the first one, if there is only one element in the array, shouldn't the only right answer be 1? </p>
26,532,194
5
4
null
2014-10-23 15:48:46.193 UTC
7
2019-11-12 13:20:53.613 UTC
2018-07-02 22:08:42.78 UTC
null
2,891,664
null
3,878,104
null
1
11
java
71,688
<blockquote> <p>returns the minimal positive integer that does not occur in A.</p> </blockquote> <p>So in an array with only one element, if that number is 1, you should return 2. If not, you should return 1.</p> <p>I think you're probably misunderstanding the requirements a little. Your code is creating keys in a map based on the <em>indexes</em> of the given array, and then removing keys based on the <em>values</em> it finds there. This problem shouldn't have anything to do with the array's indexes: it should simply return the lowest possible positive integer that isn't a value in the given array.</p> <p>So, for example, if you iterate from <code>1</code> to <code>Integer.MAX_VALUE</code>, inclusive, and return the first value that isn't in the given array, that would produce the correct answers. You'll need to figure out what data structures to use, to ensure that your solution scales at <code>O(n)</code>.</p>
21,417,954
Espresso: Thread.sleep( )
<p>Espresso claims that there is no need for <code>Thread.sleep()</code> but my code doesn't work unless I include it. I am connecting to an IP and, while connecting, a progress dialog is shown. I need a <code>Thread.sleep()</code> call to wait for the dialog to dismiss. This is my test code where I use it:</p> <pre><code> IP.enterIP(); // fills out an IP dialog (this is done with espresso) //progress dialog is now shown Thread.sleep(1500); onView(withId(R.id.button).perform(click()); </code></pre> <p>I have tried this code without the <code>Thread.sleep()</code> call but it says <code>R.id.Button</code> doesn't exist. The only way I can get it to work is with the <code>Thread.sleep()</code> call.</p> <p>Also, I have tried replacing <code>Thread.sleep()</code> with things like <code>getInstrumentation().waitForIdleSync()</code> and still no luck.</p> <p>Is this the only way to do this? Or am I missing something?</p> <p>Thanks in advance.</p>
22,563,297
14
11
null
2014-01-28 22:06:54.69 UTC
40
2021-09-17 06:33:34.903 UTC
2020-10-23 08:46:46.23 UTC
null
1,071,320
null
1,642,079
null
1
124
android|testing|android-espresso
80,543
<p>On my mind correct approach will be:</p> <pre><code>/** Perform action of waiting for a specific view id. */ public static ViewAction waitId(final int viewId, final long millis) { return new ViewAction() { @Override public Matcher&lt;View&gt; getConstraints() { return isRoot(); } @Override public String getDescription() { return "wait for a specific view with id &lt;" + viewId + "&gt; during " + millis + " millis."; } @Override public void perform(final UiController uiController, final View view) { uiController.loopMainThreadUntilIdle(); final long startTime = System.currentTimeMillis(); final long endTime = startTime + millis; final Matcher&lt;View&gt; viewMatcher = withId(viewId); do { for (View child : TreeIterables.breadthFirstViewTraversal(view)) { // found view with required ID if (viewMatcher.matches(child)) { return; } } uiController.loopMainThreadForAtLeast(50); } while (System.currentTimeMillis() &lt; endTime); // timeout happens throw new PerformException.Builder() .withActionDescription(this.getDescription()) .withViewDescription(HumanReadables.describe(view)) .withCause(new TimeoutException()) .build(); } }; } </code></pre> <p>And then pattern of usage will be:</p> <pre><code>// wait during 15 seconds for a view onView(isRoot()).perform(waitId(R.id.dialogEditor, TimeUnit.SECONDS.toMillis(15))); </code></pre>
17,583,126
How to tell Gradle to use a different AndroidManifest from the command line?
<p>I have a multi-module project. From the root of my project (which contains multiple modules), I want to be able to call 'gradle build' and have it use a different AndroidManifest in one of my modules depending on some parameter I pass in. What's the best way to accomplish this? Should I use a gradle.properties file or can I specify a different build.gradle somehow in my settings.gradle file? Any help appreciated!</p> <p>settings.gradle:</p> <pre><code>include 'ActionBarSherlock' include '&lt;main_app&gt;' </code></pre> <p> build.gradle:</p> <pre><code>buildscript { repositories { mavenCentral() } dependencies { classpath 'com.android.tools.build:gradle:0.4.2' } } apply plugin: 'android' dependencies { compile project(':ActionBarSherlock') } android { buildToolsVersion "17.0" compileSdkVersion 17 sourceSets { main { manifest.srcFile 'AndroidManifest.xml' java.srcDirs = ['src'] resources.srcDirs = ['src'] aidl.srcDirs = ['src'] renderscript.srcDirs = ['src'] res.srcDirs = ['res'] assets.srcDirs = ['assets'] } } } </code></pre> <p>I'm looking for the best way to use a different AndroidManifest.xml, say one I have in //test/AndroidManifest.xml. And I need to be able to specify this change from the command-line. Any ideas?</p>
17,604,654
2
0
null
2013-07-11 00:24:41.193 UTC
10
2021-12-06 13:28:54.553 UTC
null
null
null
null
760,105
null
1
20
android|command-line|android-manifest|gradle|command-line-arguments
21,589
<p>I solved this by using different build types.</p> <p>Here's my build.gradle:</p> <pre><code>buildscript { repositories { mavenCentral() } dependencies { classpath 'com.android.tools.build:gradle:0.4.2' } } apply plugin: 'android' dependencies { compile project(':facebook-android-sdk-3.0.1:facebook') compile project(':google-play-services_lib') compile project(':nineoldandroids') compile project(':SlidingMenu-master:library') compile project(':ViewPagerIndicator') compile project(':volley') compile project(':windowed-seek-bar') compile files('compile-libs/androidannotations-2.7.1.jar', 'libs/Flurry_3.2.1.jar', 'libs/google-play-services.jar', 'libs/gson-2.2.4.jar', 'libs/picasso-1.1.1.jar', 'libs/crittercism_v3_0_11_sdkonly.jar', 'libs/gcm.jar', 'libs/apphance-library.jar') } android { buildToolsVersion "17.0" compileSdkVersion 17 signingConfigs { debug { storeFile file('keystores/debug.keystore') } } buildTypes { debug { sourceSets { main { manifest.srcFile 'AndroidManifest.xml' java.srcDirs = ['src'] resources.srcDirs = ['src'] aidl.srcDirs = ['src'] renderscript.srcDirs = ['src'] res.srcDirs = ['res'] assets.srcDirs = ['assets'] } } } release { zipAlign true sourceSets { main { manifest.srcFile 'AndroidManifest.xml' java.srcDirs = ['src'] resources.srcDirs = ['src'] aidl.srcDirs = ['src'] renderscript.srcDirs = ['src'] res.srcDirs = ['res'] assets.srcDirs = ['assets'] } } } utest { debuggable true signingConfig signingConfigs.debug sourceSets { main { manifest.srcFile 'utest/AndroidManifest.xml' java.srcDirs = ['src'] resources.srcDirs = ['src'] aidl.srcDirs = ['src'] renderscript.srcDirs = ['src'] res.srcDirs = ['res'] assets.srcDirs = ['assets'] } } } } } </code></pre> <p>You can see that for my utest build, I'm specifying a manifest in a different directory. works.</p>
17,654,266
SOLR autoCommit vs autoSoftCommit
<p>I'm very confused about and . Here is what I understand</p> <ul> <li><p><strong>autoSoftCommit</strong> - after a autoSoftCommit, if the the SOLR server goes down, the autoSoftCommit documents will be lost. </p></li> <li><p><strong>autoCommit</strong> - does a hard commit to the disk and make sure all the autoSoftCommit commits are written to disk and commits any other document.</p></li> </ul> <p>My following configuration seems to be only with with autoSoftCommit. autoCommit on its own does not seems to be doing any commits. Is there something I am missing ? </p> <pre><code>&lt;updateHandler class="solr.DirectUpdateHandler2"&gt; &lt;updateLog&gt; &lt;str name="dir"&gt;${solr.ulog.dir:}&lt;/str&gt; &lt;/updateLog&gt; &lt;autoSoftCommit&gt; &lt;maxDocs&gt;1000&lt;/maxDocs&gt; &lt;maxTime&gt;1200000&lt;/maxTime&gt; &lt;/autoSoftCommit&gt; &lt;autoCommit&gt; &lt;maxDocs&gt;10000&lt;/maxDocs&gt; &lt;maxTime&gt;120000&lt;/maxTime&gt; &lt;openSearcher&gt;false&lt;/openSearcher&gt; &lt;/autoCommit&gt; &lt;/updateHandler&gt; </code></pre> <p>why is autoCommit working on it's own ?</p>
17,666,569
3
0
null
2013-07-15 12:28:37.263 UTC
18
2019-09-22 22:48:22.743 UTC
2013-07-15 13:39:01.07 UTC
null
1,378,771
null
1,378,771
null
1
30
solr|solr4
28,914
<p>You have openSearcher=false for hard commits. Which means that even though the commit happened, the searcher has not been restarted and cannot see the changes. Try changing that setting and you will not need soft commit.</p> <p>SoftCommit does reopen the searcher. So if you have both sections, soft commit shows new changes (even if they are not hard-committed) and - as configured - hard commit saves them to disk, but does not change visibility.</p> <p>This allows to put soft commit to 1 second and have documents show up quickly and have hard commit happen less frequently.</p>
18,656,808
How to optimize vlookup for high search count ? (alternatives to VLOOKUP)
<p>I am looking for alternatives to vlookup, with improved performance within the context of interest.</p> <p>The context is the following:</p> <ul> <li>I have a data set of {key;data} which is big (~ 100'000 records)</li> <li>I want to perform a lot of VLOOKUP operations on the dataset (typical use is to reorder the whole dataset)</li> <li>My data set has no duplicate keys</li> <li>I am looking only for exact matches (last argument to <code>VLOOKUP</code> is <code>FALSE</code>)</li> </ul> <p>A schema to explain :</p> <p>Reference sheet : (<code>"sheet1"</code>)</p> <pre><code> A B 1 2 key1 data1 3 key2 data2 4 key3 data3 ... ... ... 99999 key99998 data99998 100000 key99999 data99999 100001 key100000 data100000 100002 </code></pre> <p>Lookup sheet:</p> <pre><code> A B 1 2 key51359 =VLOOKUP(A2;sheet1!$A$2:$B$100001;2;FALSE) 3 key41232 =VLOOKUP(A3;sheet1!$A$2:$B$100001;2;FALSE) 4 key10102 =VLOOKUP(A3;sheet1!$A$2:$B$100001;2;FALSE) ... ... ... 99999 key4153 =VLOOKUP(A99999;sheet1!$A$2:$B$100001;2;FALSE) 100000 key12818 =VLOOKUP(A100000;sheet1!$A$2:$B$100001;2;FALSE) 100001 key35032 =VLOOKUP(A100001;sheet1!$A$2:$B$100001;2;FALSE) 100002 </code></pre> <p>On my Core i7 M 620 @2.67 GHz, this computes in ~10 minutes</p> <p>Are there alternatives to VLOOKUP with better performance in this context ?</p>
18,656,809
4
1
null
2013-09-06 11:31:30.057 UTC
16
2018-01-31 16:06:10.113 UTC
2018-07-09 18:41:45.953 UTC
null
-1
null
2,496,333
null
1
23
performance|excel|dictionary|vlookup|vba
44,893
<p>I considered the following alternatives:</p> <ul> <li>VLOOKUP array-formula</li> <li>MATCH / INDEX </li> <li>VBA (using a dictionary)</li> </ul> <p>The compared performance is:</p> <ul> <li>VLOOKUP simple formula : ~10 minutes</li> <li>VLOOKUP array-formula : ~10 minutes (1:1 performance index)</li> <li>MATCH / INDEX : ~2 minutes (5:1 performance index) </li> <li>VBA (using a dictionary) : ~6 seconds (100:1 performance index)</li> </ul> <p>Using the same reference sheet</p> <p>1) Lookup sheet: (vlookup array formula version)</p> <pre><code> A B 1 2 key51359 {=VLOOKUP(A2:A10001;sheet1!$A$2:$B$100001;2;FALSE)} 3 key41232 formula in B2 4 key10102 ... extends to ... ... ... 99999 key4153 ... cell B100001 100000 key12818 ... (select whole range, and press 100001 key35032 ... CTRL+SHIFT+ENTER to make it an array formula) 100002 </code></pre> <p>2) Lookup sheet: (match+index version)</p> <pre><code> A B C 1 2 key51359 =MATCH(A2;sheet1!$A$2:$A$100001;) =INDEX(sheet1!$B$2:$B$100001;B2) 3 key41232 =MATCH(A3;sheet1!$A$2:$A$100001;) =INDEX(sheet1!$B$2:$B$100001;B3) 4 key10102 =MATCH(A4;sheet1!$A$2:$A$100001;) =INDEX(sheet1!$B$2:$B$100001;B4) ... ... ... ... 99999 key4153 =MATCH(A99999;sheet1!$A$2:$A$100001;) =INDEX(sheet1!$B$2:$B$100001;B99999) 100000 key12818 =MATCH(A100000;sheet1!$A$2:$A$100001;) =INDEX(sheet1!$B$2:$B$100001;B100000) 100001 key35032 =MATCH(A100001;sheet1!$A$2:$A$100001;) =INDEX(sheet1!$B$2:$B$100001;B100001) 100002 </code></pre> <p>3) Lookup sheet: (vbalookup version)</p> <pre><code> A B 1 2 key51359 {=vbalookup(A2:A50001;sheet1!$A$2:$B$100001;2)} 3 key41232 formula in B2 4 key10102 ... extends to ... ... ... 50000 key91021 ... 50001 key42 ... cell B50001 50002 key21873 {=vbalookup(A50002:A100001;sheet1!$A$2:$B$100001;2)} 50003 key31415 formula in B50001 extends to ... ... ... 99999 key4153 ... cell B100001 100000 key12818 ... (select whole range, and press 100001 key35032 ... CTRL+SHIFT+ENTER to make it an array formula) 100002 </code></pre> <p><strong>NB</strong> : For some (external internal) reason, the vbalookup fails to return more than 65536 data at a time. So I had to split the array formula in two.</p> <p>and the associated VBA code : </p> <pre><code>Function vbalookup(lookupRange As Range, refRange As Range, dataCol As Long) As Variant Dim dict As New Scripting.Dictionary Dim myRow As Range Dim I As Long, J As Long Dim vResults() As Variant ' 1. Build a dictionnary For Each myRow In refRange.Columns(1).Cells ' Append A : B to dictionnary dict.Add myRow.Value, myRow.Offset(0, dataCol - 1).Value Next myRow ' 2. Use it over all lookup data ReDim vResults(1 To lookupRange.Rows.Count, 1 To lookupRange.Columns.Count) As Variant For I = 1 To lookupRange.Rows.Count For J = 1 To lookupRange.Columns.Count If dict.Exists(lookupRange.Cells(I, J).Value) Then vResults(I, J) = dict(lookupRange.Cells(I, J).Value) End If Next J Next I vbalookup = vResults End Function </code></pre> <p>NB: <code>Scripting.Dictionary</code> requires a referenc to <code>Microsoft Scripting Runtime</code> which must be added manually (Tools->References menu in the Excel VBA window)</p> <p>Conclusion :</p> <p>In this context, VBA using a dictionary is 100x faster than using VLOOKUP and 20x faster than MATCH/INDEX</p>
51,860,043
Javascript ES6 TypeError: Class constructor Client cannot be invoked without 'new'
<p>I have a class written in Javascript ES6. When I try to execute <code>nodemon</code> command I always see this error <code>TypeError: Class constructor Client cannot be invoked without 'new'</code></p> <p>The full error is mentioned below:</p> <pre><code>/Users/akshaysood/Blockchain/fabricSDK/dist/application/Transaction.js:45 return (0, _possibleConstructorReturn3.default)(this, (FBClient.__proto__ || (0, _getPrototypeOf2.default)(FBClient)).call(this, props)); ^ TypeError: Class constructor Client cannot be invoked without 'new' at new FBClient (/Users/akshaysood/Blockchain/fabricSDK/dist/application/Transaction.js:45:127) at Object.&lt;anonymous&gt; (/Users/akshaysood/Blockchain/fabricSDK/dist/application/Transaction.js:195:14) at Module._compile (module.js:641:30) at Object.Module._extensions..js (module.js:652:10) at Module.load (module.js:560:32) at tryModuleLoad (module.js:503:12) at Function.Module._load (module.js:495:3) at Module.require (module.js:585:17) at require (internal/module.js:11:18) at Object.&lt;anonymous&gt; (/Users/akshaysood/Blockchain/fabricSDK/dist/routes/users.js:11:20) </code></pre> <p>What I am trying to do is, I have created a class and then created an instance of that class. Then I am trying to export that variable.</p> <p>The class structure is defined below:</p> <pre><code>class FBClient extends FabricClient{ constructor(props){ super(props); } &lt;&lt;&lt; FUNCTIONS &gt;&gt;&gt; } </code></pre> <p>How I am trying to export the variable -></p> <pre><code>var client = new FBClient(); client.loadFromConfig(config); export default client = client; </code></pre> <p>You can find the full code here > <a href="https://hastebin.com/kecacenita.js" rel="noreferrer">https://hastebin.com/kecacenita.js</a> Code generated by Babel > <a href="https://hastebin.com/fabewecumo.js" rel="noreferrer">https://hastebin.com/fabewecumo.js</a></p>
51,860,850
8
7
null
2018-08-15 13:51:13.893 UTC
16
2022-08-01 14:11:08.863 UTC
2018-08-15 14:08:29.397 UTC
null
5,431,173
null
5,431,173
null
1
69
javascript|node.js|ecmascript-6
156,273
<p>The problem is that the class extends native ES6 class and is transpiled to ES5 with Babel. Transpiled classes cannot extend native classes, at least without additional measures.</p> <pre><code>class TranspiledFoo extends NativeBar { constructor() { super(); } } </code></pre> <p>results in something like</p> <pre><code>function TranspiledFoo() { var _this = NativeBar.call(this) || this; return _this; } // prototypically inherit from NativeBar </code></pre> <p>Since ES6 classes should be only called with <code>new</code>, <code>NativeBar.call</code> results in error.</p> <p>ES6 classes are supported in any recent Node version, they shouldn't be transpiled. <code>es2015</code> should be excluded from Babel configuration, it's preferable to use <a href="https://babeljs.io/docs/en/babel-preset-env/" rel="noreferrer"><code>env</code> preset set to <code>node</code> target</a>.</p> <p>The same problem <a href="https://stackoverflow.com/a/50203532/3731501">applies to TypeScript</a>. The compiler should be properly configured to not transpile classes in order for them to inherit from native or Babel classes.</p>
5,021,995
JsonResult parsing special chars as \u0027 (apostrophe)
<p>I am in the process of converting some of our web "services" to MVC3 from WCF Rest.</p> <p>Our old web services returned JSON from POCO's just fine using: <code>[WebGet(.... ResponseFormat=WebMessageFormat.Json]</code></p> <p>In my controller to return back a simple poco I'm using a JsonResult as the return type, and creating the json with <code>Json(someObject, ...)</code>.</p> <p>In the WCF Rest service, the apostrophes and special chars are formatted cleanly when presented to the client.</p> <p>In the MVC3 controller, the apostrophes appear as \u0027.</p> <p>Any thoughts? I'm new to serializing JSON so any pointers would be a huge help.</p> <p>Example response: WCF Rest: <code>{"CategoryId":8,"SomeId":6,"Name":"Richie's House"}</code></p> <p>MVC3: <code>{"CategoryId":8,"SomeId":6,"Name":"Richie\u0027s House"}</code></p>
5,022,386
3
0
null
2011-02-16 20:56:33.487 UTC
4
2020-06-12 11:30:49.91 UTC
2011-02-16 21:30:41.023 UTC
null
179,482
null
338,140
null
1
7
asp.net-mvc|asp.net-mvc-3|json
43,149
<p>That shouldn't be any problem, as both representations are equivalent:</p> <pre><code>var a = {"CategoryId":8,"SomeId":6,"Name":"Richie\u0027s House"}; alert(a.Name); </code></pre> <p>alerts <code>Richie's House</code>.</p>
5,021,120
ffmpeg mp3 conversion failed
<p>using ffmpeg to convert from flv to mp3 gives the following result<pre><br> ] ffmpeg-0.6.1 >> ffmpeg -i name.flv name.mp3 FFmpeg version 0.6.1, Copyright (c) 2000-2010 the FFmpeg developers built on Feb 14 2011 12:33:38 with gcc 4.1.2 20080704 (Red Hat 4.1.2-48) configuration: libavutil 50.15. 1 / 50.15. 1 libavcodec 52.72. 2 / 52.72. 2 libavformat 52.64. 2 / 52.64. 2 libavdevice 52. 2. 0 / 52. 2. 0 libswscale 0.11. 0 / 0.11. 0 [flv @ 0x10869420]Could not find codec parameters (Video: 0x0000) [flv @ 0x10869420]Estimating duration from bitrate, this may be inaccurate Input #0, flv, from 'name.flv': Metadata: audiocodecid : 5 duration : 10 videocodecid : -1 canSeekToEnd : true Duration: 00:00:10.17, start: 0.000000, bitrate: N/A Stream #0.0: Video: 0x0000, 1k tbr, 1k tbn, 1k tbc Stream #0.1: Audio: nellymoser, 8000 Hz, mono, s16 Output #0, mp3, to 'name.mp3': Stream #0.0: Audio: 0x0000, 8000 Hz, mono, s16, 64 kb/s Stream mapping: Stream #0.1 -> #0.0 Encoder (codec id 86017) not found for output stream #0.0</pre></p> <p>you can see in last line it says codec id 86017 not found. when i run following command:<br/> <pre>ffmpeg -formats > ffmpeg-format.txt</pre><br/> mp3 is listed in available formats as <br/>DE mp3 MPEG audio layer 3<br/>.What can be the error.is it that mp3 codec is not properly installed?Help will be appreciated</p>
5,023,195
3
0
null
2011-02-16 19:25:26.27 UTC
10
2012-11-14 02:18:19.153 UTC
2011-02-16 19:40:34.103 UTC
null
444,757
null
444,757
null
1
32
ffmpeg|mp3|flv
43,852
<p>It looks like your FFMPEG wasn't compiled with libmp3lame. See this post:</p> <p><a href="https://superuser.com/questions/196857/how-to-install-libmp3lame-for-ffmpeg">https://superuser.com/questions/196857/how-to-install-libmp3lame-for-ffmpeg</a></p> <p>If you can't compile it on your own you'll have to search for a binary that does support it.</p>
9,280,716
How to Ignore Line Length PHP_CodeSniffer
<p>I have been using PHP_CodeSniffer with jenkins, my build.xml was configured for phpcs as below </p> <pre><code>&lt;target name="phpcs"&gt; &lt;exec executable="phpcs"&gt; &lt;arg line="--report=checkstyle --report-file=${basedir}/build/logs/checkstyle.xml --standard=Zend ${source}"/&gt; &lt;/exec&gt; &lt;/target&gt; </code></pre> <p>And I would like to ignore the following warning</p> <pre><code>FOUND 0 ERROR(S) AND 1 WARNING(S) AFFECTING 1 LINE(S) -------------------------------------------------------------------------------- 117 | WARNING | Line exceeds 80 characters; contains 85 characters -------------------------------------------------------------------------------- </code></pre> <p>How could I ignore the line length warning?</p>
9,281,546
4
3
null
2012-02-14 16:45:06.91 UTC
7
2022-01-17 22:33:09.023 UTC
2013-01-04 22:40:55.15 UTC
null
367,456
null
531,466
null
1
46
php|jenkins|continuous-integration|pear|codesniffer
36,418
<p>You could create your own standard. The Zend one is quite simple (this is at <code>/usr/share/php/PHP/CodeSniffer/Standards/Zend/ruleset.xml</code> in my Debian install after installing it with PEAR). Create another one based on it, but ignore the line-length bit:</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;ruleset name="Custom"&gt; &lt;description&gt;Zend, but without linelength check.&lt;/description&gt; &lt;rule ref="Zend"&gt; &lt;exclude name="Generic.Files.LineLength"/&gt; &lt;/rule&gt; &lt;/ruleset&gt; </code></pre> <p>And set <code>--standard=/path/to/your/ruleset.xml</code>.</p> <p>Optionally, if you just want to up the char count before this is triggered, redefine the rule:</p> <pre><code> &lt;!-- Lines can be N chars long (warnings), errors at M chars --&gt; &lt;rule ref="Generic.Files.LineLength"&gt; &lt;properties&gt; &lt;property name="lineLimit" value="N"/&gt; &lt;property name="absoluteLineLimit" value="M"/&gt; &lt;/properties&gt; &lt;/rule&gt; </code></pre>
9,642,055
CSV Parsing Options with .NET
<p>I'm looking at my delimited-file (e.g. CSV, tab seperated, etc.) parsing options based on MS stack in general, and .net specifically. The only technology I'm excluding is SSIS, because I already know it will not meet my needs.</p> <p>So my options appear to be:</p> <ol> <li>Regex.Split</li> <li><a href="http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.fileio.textfieldparser.aspx" rel="noreferrer">TextFieldParser</a> </li> <li><a href="http://www.switchonthecode.com/tutorials/csharp-tutorial-using-the-built-in-oledb-csv-parser" rel="noreferrer">OLEDB CSV Parser</a> </li> </ol> <p>I have two criteria I must meet. First, given the following file which contains two logical rows of data (and five physical rows altogether):</p> <p><code>101, Bob, "Keeps his house ""clean"".<br> Needs to work on laundry."<br> 102, Amy, "Brilliant.<br> Driven.<br> Diligent."</code></p> <p>The parsed results must yield two logical "rows," consisting of three strings (or columns) each. The third row/column string must preserve the newlines! Said differently, the parser must recognize when lines are "continuing" onto the next physical row, due to the "unclosed" text qualifier.</p> <p>The second criteria is that the delimiter and text qualifier must be configurable, per file. Here are two strings, taken from different files, that I must be able to parse:</p> <pre><code>var first = @"""This"",""Is,A,Record"",""That """"Cannot"""", they say,"","""",,""be"",rightly,""parsed"",at all"; var second = @"~This~|~Is|A|Record~|~ThatCannot~|~be~|~parsed~|at all"; </code></pre> <p>A proper parsing of string "first" would be:</p> <ul> <li>This</li> <li>Is,A,Record</li> <li>That "Cannot", they say,</li> <li>_ </li> <li>_ </li> <li>be</li> <li>rightly</li> <li>parsed</li> <li>at all</li> </ul> <p>The '_' simply means that a blank was captured - I don't want a literal underbar to appear. </p> <p>One important assumption can be made about the flat-files to be parsed: there will be a fixed number of columns per file.</p> <p>Now for a dive into the technical options.</p> <p><em>REGEX</em></p> <p>First, many responders comment that regex "is not the best way" to achieve the goal. I did, however, find a <a href="http://www.programmersheaven.com/user/Jonathan/blog/73-Splitting-CSV-with-regex/" rel="noreferrer">commenter who offered an excellent CSV regex</a>:</p> <pre><code>var regex = @",(?=(?:[^""]*""[^""]*"")*(?![^""]*""))"; var Regex.Split(first, regex).Dump(); </code></pre> <p>The results, applied to string "first," are quite wonderful:</p> <ul> <li>"This"</li> <li>"Is,A,Record"</li> <li>"That ""Cannot"", they say,"</li> <li>""</li> <li>_</li> <li>"be"</li> <li>rightly</li> <li>"parsed"</li> <li>at all</li> </ul> <p>It would be nice if the quotes were cleaned up, but I can easily deal with that as a post-process step. Otherwise, this approach can be used to parse both sample strings "first" and "second," provided the regex is modified for tilde and pipe symbols accordingly. Excellent!</p> <p>But the real problem pertains to the multi-line criteria. Before a regex can be applied to a string, I must read the full logical "row" from the file. Unfortunately, I don't know how many physical rows to read to complete the logical row, unless I've got a regex / state machine. </p> <p>So this becomes a "chicken and the egg" problem. My best option would be to read the entire file into memory as one giant string, and let the regex sort-out the multiple lines (I didn't check if the above regex could handle that). If I've got a 10 gig file, this could be a bit precarious. </p> <p>On to the next option.</p> <p><em>TextFieldParser</em></p> <p>Three lines of code will make the problem with this option apparent:</p> <pre><code>var reader = new Microsoft.VisualBasic.FileIO.TextFieldParser(stream); reader.Delimiters = new string[] { @"|" }; reader.HasFieldsEnclosedInQuotes = true; </code></pre> <p>The Delimiters configuration looks good. However, the "HasFieldsEnclosedInQuotes" is "game over." I'm stunned that the delimiters are arbitrarily configurable, but in contrast I have no other qualifier option other than quotations. Remember, I need configurability over the text qualifier. So again, unless someone knows a TextFieldParser configuration trick, this is game over.</p> <p><em>OLEDB</em></p> <p>A colleague tells me this option has two major failings. First, it has terrible performance for large (e.g. 10 gig) files. Second, so I'm told, it guesses data types of input data rather than letting you specify. Not good.</p> <p><strong>HELP</strong></p> <p>So I'd like to know the facts I got wrong (if any), and the other options that I missed. Perhaps someone knows a way to jury-rig TextFieldParser to use an arbitrary delimiter. And maybe OLEDB has resolved the stated issues (or perhaps never had them?).</p> <p>What say ye?</p>
9,642,224
3
4
null
2012-03-09 22:51:47.927 UTC
4
2018-07-27 10:38:24.577 UTC
2012-03-09 23:10:42.02 UTC
null
284,758
null
284,758
null
1
14
c#|.net|parsing
38,056
<p>Did you try searching for an already-existing .NET <a href="http://www.codeproject.com/search.aspx?q=.net+CSV+parser" rel="noreferrer">CSV parser</a>? <a href="http://www.codeproject.com/Articles/9258/A-Fast-CSV-Reader" rel="noreferrer">This one</a> claims to handle multi-line records significantly faster than OLEDB.</p>
18,429,121
Inline Form nested within Horizontal Form in Bootstrap 3
<p>I want to build a form in Bootstrap 3 like this:</p> <p><img src="https://i.stack.imgur.com/gsVKH.png" alt=""></p> <p>My site (not the above link) just updates from Bootstrap 2.3.2 and the format is not correct anymore.</p> <p>I cannot find any doc about this type of form on <a href="http://getbootstrap.com" rel="noreferrer">getbootstrap.com</a>.</p> <p>Could anyone tell me how to do this? Only 'Username' would be OK.</p> <p>Thanks.</p> <p><strong>PS</strong> There is a <a href="https://stackoverflow.com/questions/12201835/form-inline-inside-a-form-horizontal-in-twitter-bootstrap">similar question</a> but it's using Bootstrap 2.3.2.</p>
18,429,555
6
0
null
2013-08-25 12:46:17.18 UTC
23
2020-05-04 14:31:39.587 UTC
2017-05-23 11:47:26.613 UTC
null
-1
null
1,421,239
null
1
74
html|css|forms|twitter-bootstrap|twitter-bootstrap-3
149,696
<p>I have created a <a href="http://jsfiddle.net/r7hgjjzv/"><strong>demo</strong></a> for you.</p> <p>Here is how your nested structure should be in Bootstrap 3:</p> <pre><code>&lt;div class="form-group"&gt; &lt;label for="birthday" class="col-xs-2 control-label"&gt;Birthday&lt;/label&gt; &lt;div class="col-xs-10"&gt; &lt;div class="form-inline"&gt; &lt;div class="form-group"&gt; &lt;input type="text" class="form-control" placeholder="year"/&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;input type="text" class="form-control" placeholder="month"/&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;input type="text" class="form-control" placeholder="day"/&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Notice how the whole <code>form-inline</code> is nested within the <code>col-xs-10</code> div containing the control of the horizontal form. In other terms, the whole <code>form-inline</code> is the "control" of the birthday label in the main horizontal form.</p> <p><strong>Note</strong> that you will encounter a left and right margin problem by nesting the inline form within the horizontal form. To fix this, add this to your css:</p> <pre><code>.form-inline .form-group{ margin-left: 0; margin-right: 0; } </code></pre>
18,300,536
Get value of attribute in CSS
<p>I have this HTML code:</p> <pre><code>&lt;div data-width="70"&gt;&lt;/div&gt; </code></pre> <p>I want to set it's width in CSS equal to the value of data-width attribute, e.g. something like this:</p> <pre><code>div { width: [data-width]; } </code></pre> <p>I saw this was done somewhere, but I can't remember it. Thanks.</p>
18,301,660
8
2
null
2013-08-18 15:15:00.353 UTC
5
2021-10-31 15:47:21.087 UTC
null
null
null
null
1,616,512
null
1
51
html|css
95,911
<p>You need <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/attr()" rel="noreferrer">the <code>attr</code> CSS function</a>:</p> <pre><code>div { width: attr(data-width); } </code></pre> <p>The problem is that (as of 2021) it's not supported even by some of the major browsers (in my case Chrome):</p> <p><a href="https://i.stack.imgur.com/gKLKN.png" rel="noreferrer"><img src="https://i.stack.imgur.com/gKLKN.png" alt="enter image description here" /></a></p>
20,357,223
easy way to unzip file with golang
<p>is there a easy way to unzip file with golang ?</p> <p>right now my code is:</p> <pre><code>func Unzip(src, dest string) error { r, err := zip.OpenReader(src) if err != nil { return err } defer r.Close() for _, f := range r.File { rc, err := f.Open() if err != nil { return err } defer rc.Close() path := filepath.Join(dest, f.Name) if f.FileInfo().IsDir() { os.MkdirAll(path, f.Mode()) } else { f, err := os.OpenFile( path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode()) if err != nil { return err } defer f.Close() _, err = io.Copy(f, rc) if err != nil { return err } } } return nil } </code></pre>
24,792,688
8
2
null
2013-12-03 17:00:54.663 UTC
11
2021-05-21 20:53:00.957 UTC
2013-12-07 12:06:52.583 UTC
null
740,182
null
740,182
null
1
37
go|zip|unzip
40,528
<p>Slight rework of the OP's solution to create the containing directory <code>dest</code> if it doesn't exist, and to wrap the file extraction/writing in a closure to eliminate stacking of <code>defer .Close()</code> calls per <a href="https://stackoverflow.com/users/164234/nick-craig-wood">@Nick Craig-Wood</a>'s comment:</p> <pre><code>func Unzip(src, dest string) error { r, err := zip.OpenReader(src) if err != nil { return err } defer func() { if err := r.Close(); err != nil { panic(err) } }() os.MkdirAll(dest, 0755) // Closure to address file descriptors issue with all the deferred .Close() methods extractAndWriteFile := func(f *zip.File) error { rc, err := f.Open() if err != nil { return err } defer func() { if err := rc.Close(); err != nil { panic(err) } }() path := filepath.Join(dest, f.Name) // Check for ZipSlip (Directory traversal) if !strings.HasPrefix(path, filepath.Clean(dest) + string(os.PathSeparator)) { return fmt.Errorf(&quot;illegal file path: %s&quot;, path) } if f.FileInfo().IsDir() { os.MkdirAll(path, f.Mode()) } else { os.MkdirAll(filepath.Dir(path), f.Mode()) f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode()) if err != nil { return err } defer func() { if err := f.Close(); err != nil { panic(err) } }() _, err = io.Copy(f, rc) if err != nil { return err } } return nil } for _, f := range r.File { err := extractAndWriteFile(f) if err != nil { return err } } return nil } </code></pre> <p><strong>Note:</strong> Updated to include Close() error handling as well (if we're looking for best practices, may as well follow ALL of them).</p>
15,095,868
jquery.click() not working in iOS
<p>HTML:</p> <pre><code>&lt;div id="footer"&gt; &lt;a class="button1 selected" id="button1" href="#"&gt;&lt;div class="icon"&gt;&lt;/div&gt;&lt;div class="text"&gt;Option 1&lt;/div&gt;&lt;/a&gt; &lt;a class="button2" id="button2" href="#"&gt;&lt;div class="icon"&gt;&lt;/div&gt;&lt;div class="text"&gt;Option 2&lt;/div&gt;&lt;/a&gt; &lt;a class="button3" id="button3" href="#"&gt;&lt;div class="icon"&gt;&lt;/div&gt;&lt;div class="text"&gt;Option 3&lt;/div&gt;&lt;/a&gt; &lt;a class="button4" id="button4" href="#"&gt;&lt;div class="icon"&gt;&lt;/div&gt;&lt;div class="text"&gt;Option 4&lt;/div&gt;&lt;/a&gt; &lt;/div&gt; </code></pre> <p>JS:</p> <pre><code>$('#button1').click(function() { alert('button1'); }); $('#button2').click(function() { alert('button2'); }); </code></pre> <p>Now, this script works perfectly on my PC Browser but it doesn't work on iOS. I've tried this solution too: <a href="https://stackoverflow.com/questions/3705937/document-click-not-working-correctly-on-iphone-jquery">$(document).click() not working correctly on iPhone. jquery</a> but it doesen't work.</p> <p>I am using on jQuery 1.8.3, no jQuery Mobile (I prefer not to).</p> <p>Somebody can help me with this?</p>
15,096,054
6
3
null
2013-02-26 17:50:19.783 UTC
5
2021-12-23 07:08:07.72 UTC
2017-05-23 12:32:35.72 UTC
null
-1
null
718,645
null
1
24
jquery|ios
48,030
<p>Try to add a pointer cursor to the button and use .on to bind the click event.</p> <pre><code>$('#button1').css('cursor','pointer'); $(document).on('click', '#button1', function(event) { event.preventDefault(); alert('button1'); }); </code></pre>
15,449,034
Batch program to to check if process exists
<p>I want a batch program, which will check if the process <code>notepad.exe</code> exists.</p> <p><strong>if</strong> <code>notepad.exe</code> exists, it will end the process, </p> <p><strong>else</strong> the batch program will close itself.</p> <p>Here is what I've done:</p> <pre><code>@echo off tasklist /fi "imagename eq notepad.exe" &gt; nul if errorlevel 1 taskkill /f /im "notepad.exe" exit </code></pre> <p>But it doesn't work. What is the wrong in my code?</p>
15,449,358
5
5
null
2013-03-16 12:04:48.457 UTC
13
2021-11-05 17:39:24.88 UTC
2016-07-15 10:20:59.073 UTC
null
2,306,173
null
2,176,930
null
1
34
windows|batch-file|command|cmd
149,056
<p><code>TASKLIST</code> does not set errorlevel.</p> <pre><code>echo off tasklist /fi "imagename eq notepad.exe" |find ":" &gt; nul if errorlevel 1 taskkill /f /im "notepad.exe" exit </code></pre> <p>should do the job, since ":" should appear in <code>TASKLIST</code> output only if the task is NOT found, hence <code>FIND</code> will set the errorlevel to <code>0</code> for <code>not found</code> and <code>1</code> for <code>found</code></p> <p>Nevertheless,</p> <p>taskkill /f /im "notepad.exe"</p> <p>will kill a notepad task if it exists - it can do nothing if no notepad task exists, so you don't really need to test - unless there's something else you want to do...like perhaps</p> <pre><code>echo off tasklist /fi "imagename eq notepad.exe" |find ":" &gt; nul if errorlevel 1 taskkill /f /im "notepad.exe"&amp;exit </code></pre> <p>which would appear to do as you ask - kill the notepad process if it exists, then exit - otherwise continue with the batch</p>
15,120,745
Understanding Oracle's Java on Mac
<p>I've been using Java on OS X for many, many years and recently when Apple stopped including Java by default I let the OS go and install it for me (Apple's variety, of course).</p> <p>So now I'm using OS X 10.8 and I need to install Java 7 so I just got Oracle's Update 15 in DMG form and ran the installer. It updated my /usr/bin/java (and related files) to point here:</p> <pre><code>/System/Library/Frameworks/JavaVM.framework/Versions/Current/Commands/java </code></pre> <p>Tracing this back to '/System/Library/Frameworks/JavaVM.framework/Versions' everything either points to 'Current' or 'CurrentJDK', the former being a link to 'A' (which is Oracle's Java 7, from what I can tell, not sure why it is 'A') and the latter being a link to Apple's Java 6 in '/System/Library/Java/JavaVirtualMachines/1.6.0.jdk'.</p> <p>Now this is all really confusing but this isn't even my question yet. It appears there is a Java 7 installed here:</p> <pre><code>/System/Library/Frameworks/JavaVM.framework/Versions/A </code></pre> <p>But there is also a Java 7 installed here:</p> <pre><code>/Library/Java/JavaVirtualMachines/jdk1.7.0_15.jdk </code></pre> <p>Finding 'java' in both and printing out the version yields the same version and build (java version "1.7.0_15"), however, when hashing the files they are different.</p> <p>So does this mean Oracle installed Java 7 in two different places? If so, why? Which am I supposed to use? And why do some things still point to Java 6 (CurrentJDK). </p> <p>I've looked on Oracle's website but nothing there clears anything up. </p>
15,133,344
3
1
null
2013-02-27 19:32:16.057 UTC
32
2017-08-15 09:12:13.27 UTC
2017-08-15 09:12:13.27 UTC
null
1,033,581
null
499,689
null
1
49
java|macos|oracle
18,054
<p>Oracle's JVM is only installed in one location. You've been misled!</p> <p>As you've noted, the Java commands in <code>/usr/bin</code> are symlinks to binaries in <code>/System/Library/Frameworks/JavaVM.framework/Versions/Current/Commands</code>. The binaries within that directory are stub applications that determine which Java VM to use*, and then exec the corresponding real binary within that VM version. This is why all of the binaries within <code>/System/Library/Frameworks/JavaVM.framework/Versions/Current/Commands</code> are almost identical in size, despite the fact that you'd expect them to be implementing quite different functionality.</p> <p>You can see this in action by using <code>dtrace</code>:</p> <pre><code>mrowe@angara:~$ sudo dtrace -n 'syscall::posix_spawn:entry { trace(copyinstr(arg1)); }' -c "/usr/bin/java -version" dtrace: description 'syscall::posix_spawn:entry ' matched 1 probe dtrace: pid 44727 has exited CPU ID FUNCTION:NAME 8 619 posix_spawn:entry /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home/bin/java </code></pre> <p>The given <code>dtrace</code> invocation prints out the path argument to <code>posix_spawn</code> when it is called by <code>java -version</code>. In my case the stub application has found Apple's Java 1.6 runtime in <code>/System/Library/Java/JavaVirtualMachines/1.6.0.jdk</code> and is invoking that version of the <code>java</code> command.</p> <p>The stub binaries also have another benefit: when they detect that no Java VM is installed they will prompt the user to install one.</p> <p>As for the <code>CurrentJDK</code> symlink, as best as I can tell this for sake of backwards-compatibility with the past when Apple was the only source of the JVM on OS X.</p> <hr> <p>* A combination of factors are considered when determining which Java VM should be used. <code>JAVA_HOME</code> is used if set (try <code>JAVA_HOME=/tmp java</code>). If <code>JAVA_HOME</code> is not set then the list of all virtual machines on the system is discovered. The <code>JAVA_VERSION</code> and <code>JAVA_ARCH</code> environment variables are used, if set, to filter the list of virtual machines to a particular version and supported architecture. The resulting list is then sorted by architecture (preferring 64-bit over 32-bit) and version (newer is better), and the best match is returned.</p>
38,382,043
How to use CSS position sticky to keep a sidebar visible with Bootstrap 4
<p>I have a two columns layout like this:</p> <pre><code> &lt;div class="row"&gt; &lt;div class="col-xs-8 content"&gt; &lt;/div&gt; &lt;div class="col-xs-4"&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>If I set the <code>position:sticky</code> to the sidebar column, I get the sticky behaviour of the sidebar: <a href="https://codepen.io/marcanuy/pen/YWYZEp" rel="noreferrer">https://codepen.io/marcanuy/pen/YWYZEp</a></p> <p>CSS:</p> <pre><code>.sticky { position: sticky; top: 10px; } </code></pre> <p>HTML:</p> <pre><code> &lt;div class="row"&gt; &lt;div class="col-xs-8 content"&gt; &lt;/div&gt; &lt;div class="col-xs-4 sticky"&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>But when I set the <code>sticky</code> property <strong>only</strong> to the <strong>menu</strong> that is located in the sidebar, so the <em>related articles</em> section scrolls normally and gets the <em>sticky</em> behaviour with the <em>menu div</em>, it doesn't work:</p> <pre><code> &lt;div class="row"&gt; &lt;div class="col-xs-8 content"&gt; &lt;/div&gt; &lt;div class="col-xs-4"&gt; &lt;div class="menu sticky"&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>This is the screencast of the first example scrolling the whole sidebar with a sticky behaviour, and then changing the sticky property to the menu that doesn't work:</p> <p><a href="https://i.stack.imgur.com/wYJDo.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/wYJDo.gif" alt="enter image description here"></a></p> <p>Bootstrap 4 <a href="http://v4-alpha.getbootstrap.com/migration/#components" rel="noreferrer">recommends</a> the <strong>sticky</strong> property as the dropped support for the Affix jQuery plugin:</p> <blockquote> <p>Dropped the Affix jQuery plugin. We recommend using a position: sticky polyfill instead.</p> </blockquote> <p>I have tested it in:</p> <ul> <li><p>Firefox 47.0 with <code>css.sticky.enabled=“true”</code> under <code>about:config</code> </p></li> <li><p>Chrome 50.0.2661.94 (64-bit) with <code>experimental Web Platform features</code> enabled in <code>chrome://flags</code> </p></li> </ul> <p>(This is not a duplicate of <a href="https://stackoverflow.com/q/37645566/1165509">How to make a sticky sidebar in Bootstrap?</a> because that one is using BS affix)</p>
38,413,663
4
4
null
2016-07-14 18:50:22.077 UTC
5
2021-08-10 11:36:33.767 UTC
2018-03-05 13:50:48.84 UTC
null
171,456
null
1,165,509
null
1
18
css|twitter-bootstrap|css-position|bootstrap-4|twitter-bootstrap-4
42,773
<p>I solved enabling <code>flexbox</code>. After raising an issue in Bootstrap's <a href="https://github.com/twbs/bootstrap/issues/20307#issuecomment-233069019" rel="noreferrer">Github</a> repository I got an answer by a Bootstrap <a href="https://github.com/cvrebert" rel="noreferrer">member</a>:</p> <blockquote> <p>The .col-xs-4 isn't as tall as the .col-xs-8, so there's basically no space for the Menu to "float" within when the stickiness kicks in. Make the .col-xs-4 taller and things work fine: <a href="https://codepen.io/anon/pen/OXzoNJ" rel="noreferrer">https://codepen.io/anon/pen/OXzoNJ</a> If you enable the Flexbox version of our grid system (via $enable-flex: true;), you get automatic equal-height columns for free, which comes in handy in your case.</p> </blockquote>
28,285,813
Style jQuery autocomplete in a Bootstrap input field
<p>I have implemented a jQuery autocomplete function to a Bootstrap input. The jQuery autocomplete is working fine but I want to see the results as a combo and I guess it's now happening because I'm using BootStrap.</p> <p>This is the field that I'm assigning autocomplete:</p> <pre class="lang-html prettyprint-override"><code>&lt;div class="form-group"&gt; &lt;label&gt;Employee&lt;/label&gt; &lt;input class="form-control" name="txtEmployee" placeholder="Trabajador"&gt; &lt;/div&gt; </code></pre> <pre class="lang-js prettyprint-override"><code>$(this).autocomplete({ source: function(request, response) { $.ajax({ url: '@Url.Content("~/Employee/SearchEmployee")/', type: 'POST', contentType: 'application/json', dataType: "json", data: JSON.stringify({ employerId: 1, searchStr: me.val() }), success: function(data) { if (data.success) { response($.map(data.data, function(item) { return { label: "(" + item.EmployeeNumber + ") " + item.FirstName + " " + item.MothersLast + ", " + item.FathersLast, employeeId: item.EmployeeId } })); } } }); }, minLength: 3 }); </code></pre> <p>The results are displayed but like this:</p> <p><img src="https://i.stack.imgur.com/RHzhD.png" alt="enter image description here"></p> <p>How can I style the results with Bootstrap so I can see them like dropdownlist?</p>
28,286,277
5
3
null
2015-02-02 20:05:46.213 UTC
27
2022-03-15 10:18:57.74 UTC
2015-08-06 03:48:26.927 UTC
null
1,366,033
null
1,253,667
null
1
41
jquery|twitter-bootstrap|jquery-autocomplete
146,859
<p>If you're using jQuery-UI, you <em>must</em> include the jQuery UI CSS package, otherwise the UI components don't know how to be styled. </p> <p>If you don't like the jQuery UI styles, then you'll have to recreate all the styles it would have otherwise applied.</p> <p>Here's an example and some possible fixes.</p> <h2><a href="https://stackoverflow.com/help/mcve">Minimal, Complete, and Verifiable example</a> (i.e. broken)</h2> <p>Here's a demo in Stack Snippets <strong>without</strong> jquery-ui.css (doesn't work)</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$(function() { var availableTags = [ "ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++", "Clojure", "COBOL", "ColdFusion", "Erlang", "Fortran", "Groovy", "Haskell", "Java", "JavaScript", "Lisp", "Perl", "PHP", "Python", "Ruby", "Scala", "Scheme" ]; $(".autocomplete").autocomplete({ source: availableTags }); });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/&gt; &lt;script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"&gt;&lt;/script&gt; &lt;script src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.2/jquery-ui.js"&gt;&lt;/script&gt; &lt;script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.js"&gt;&lt;/script&gt; &lt;div class="container"&gt; &lt;div class="form-group"&gt; &lt;label&gt;Languages&lt;/label&gt; &lt;input class="form-control autocomplete" placeholder="Enter A" /&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label &gt;Another Field&lt;/label&gt; &lt;input class="form-control"&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <h2>Fix #1 - jQuery-UI Style</h2> <p>Just include jquery-ui.css and everything should work just fine with the latest supported versions of jquery.</p> <p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$(function() { var availableTags = [ "ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++", "Clojure", "COBOL", "ColdFusion", "Erlang", "Fortran", "Groovy", "Haskell", "Java", "JavaScript", "Lisp", "Perl", "PHP", "Python", "Ruby", "Scala", "Scheme" ]; $(".autocomplete").autocomplete({ source: availableTags }); });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;link href="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.2/jquery-ui.css" rel="stylesheet"/&gt; &lt;link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/&gt; &lt;script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"&gt;&lt;/script&gt; &lt;script src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.2/jquery-ui.js"&gt;&lt;/script&gt; &lt;script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.js"&gt;&lt;/script&gt; &lt;div class="container"&gt; &lt;div class="form-group"&gt; &lt;label&gt;Languages&lt;/label&gt; &lt;input class="form-control autocomplete" placeholder="Enter A" /&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label &gt;Another Field&lt;/label&gt; &lt;input class="form-control"&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <h2>Fix #2 - Bootstrap Theme</h2> <p>There is a project that created a Bootstrap-esque theme for jQuery-UI components called <a href="https://github.com/jquery-ui-bootstrap/jquery-ui-bootstrap" rel="noreferrer">jquery‑ui‑bootstrap</a>. Just grab the stylesheet from there and you should be all set.</p> <p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$(function() { var availableTags = [ "ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++", "Clojure", "COBOL", "ColdFusion", "Erlang", "Fortran", "Groovy", "Haskell", "Java", "JavaScript", "Lisp", "Perl", "PHP", "Python", "Ruby", "Scala", "Scheme" ]; $(".autocomplete").autocomplete({ source: availableTags }); });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;link href="https://cdnjs.cloudflare.com/ajax/libs/jquery-ui-bootstrap/0.5pre/css/custom-theme/jquery-ui-1.10.0.custom.css" rel="stylesheet"/&gt; &lt;link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/&gt; &lt;script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"&gt;&lt;/script&gt; &lt;script src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.2/jquery-ui.js"&gt;&lt;/script&gt; &lt;script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.js"&gt;&lt;/script&gt; &lt;div class="container"&gt; &lt;div class="form-group"&gt; &lt;label&gt;Languages&lt;/label&gt; &lt;input class="form-control autocomplete" placeholder="Enter A" /&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label &gt;Another Field&lt;/label&gt; &lt;input class="form-control"&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <h2>Fix #3 - Manual CSS</h2> <p>If you only need the AutoComplete widget from jQuery-UI's library, you should start by doing a custom build so you don't pull in resources you're not using. </p> <p>After that, you'll need to style it yourself. Just look at some of the other styles that are applied to jquery's <a href="https://github.com/jquery/jquery-ui/blob/master/themes/base/autocomplete.css" rel="noreferrer">autocomplete.css</a> and <a href="https://github.com/jquery/jquery-ui/blob/master/themes/base/theme.css" rel="noreferrer">theme.css</a> to figure out what styles you'll need to manually replace.</p> <p>You can use bootstrap's <a href="https://github.com/twbs/bootstrap/blob/master/less/dropdowns.less" rel="noreferrer">dropdowns.less</a> for inspiration. </p> <p>Here's a sample CSS that fits pretty well with Bootstrap's default theme:</p> <pre class="lang-css prettyprint-override"><code>.ui-autocomplete { position: absolute; z-index: 1000; cursor: default; padding: 0; margin-top: 2px; list-style: none; background-color: #ffffff; border: 1px solid #ccc; -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; -webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); -moz-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); } .ui-autocomplete &gt; li { padding: 3px 20px; } .ui-autocomplete &gt; li.ui-state-focus { background-color: #DDD; } .ui-helper-hidden-accessible { display: none; } </code></pre> <p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$(function() { var availableTags = [ "ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++", "Clojure", "COBOL", "ColdFusion", "Erlang", "Fortran", "Groovy", "Haskell", "Java", "JavaScript", "Lisp", "Perl", "PHP", "Python", "Ruby", "Scala", "Scheme" ]; $(".autocomplete").autocomplete({ source: availableTags }); });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.ui-autocomplete { position: absolute; z-index: 1000; cursor: default; padding: 0; margin-top: 2px; list-style: none; background-color: #ffffff; border: 1px solid #ccc -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; -webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); -moz-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); } .ui-autocomplete &gt; li { padding: 3px 20px; } .ui-autocomplete &gt; li.ui-state-focus { background-color: #DDD; } .ui-helper-hidden-accessible { display: none; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/&gt; &lt;script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"&gt;&lt;/script&gt; &lt;script src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.2/jquery-ui.js"&gt;&lt;/script&gt; &lt;script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.js"&gt;&lt;/script&gt; &lt;div class="container"&gt; &lt;div class="form-group ui-widget"&gt; &lt;label&gt;Languages&lt;/label&gt; &lt;input class="form-control autocomplete" placeholder="Enter A" /&gt; &lt;/div&gt; &lt;div class="form-group ui-widget"&gt; &lt;label &gt;Another Field&lt;/label&gt; &lt;input class="form-control" /&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <blockquote> <p><strong>Tip</strong>: Since the dropdown menu hides every time you go to inspect the element (i.e. whenever the input loses focus), for easier debugging of the style, find the control with <code>.ui-autocomplete</code> and remove <code>display: none;</code>.</p> </blockquote>
8,122,431
How to create custom view controller container using storyboard in iOS 5
<p>In iOS5 using storyboard feature I want to create a custom container which will have 2 <code>ViewControllers</code> embedded in it. For Example, embed Table view controller as well as a view controller both in one <code>ViewController</code>.</p> <p>That is, one view controller will have 2 relationship:</p> <ol> <li>to table view controller</li> <li>to view controller which in turn will have 4 <code>UIImage</code> view Or <code>UIButton</code> in it</li> </ol> <p>Is creating this type of relationship possible using storyboard's drag drop feature only &amp; not programmatically?</p>
8,123,625
2
1
null
2011-11-14 13:40:06.963 UTC
11
2014-08-27 07:31:50.9 UTC
2014-08-27 07:31:50.9 UTC
null
3,623,301
null
977,868
null
1
23
ios5|storyboard
22,685
<p>,You should only have one view controller to control the scene. However, this viewController might have two other view controllers that control particular subviews on your scene. To do this you create properties in your scene viewController, in your case one for your tableViewController and one for your view. I like to keep things together so I make both these viewControllers outlets and create them in interface builder. To create them in interface builder pull in an Object from the Object library and set its type to the relevant viewController. Hook it up to the appropriate outlet you just created in your scene's viewController - Note: this is important otherwise the viewController will be released if you are using ARC and crash your app. Then hook these viewControllers up to the view you want them to control and you are done.</p> <p>Alternatively you can instantiate and hop up your viewControllers in your scenes viewController should you prefer to do this.</p> <p>Hope this helps.</p> <p>Edit: On reflection this is not a good idea and actually goes against the HIG you should maintain only one ViewController for each screen of content and instead try to create a suitable view class and have the single view controller deal with the interactions between the various views.</p>
8,117,822
In bash, can you use a function call as a condition in an if statement?
<p>here's what i'm trying to achive:</p> <pre><code>function f1() { return 0 } function f2() { return 0 } if [[ f1 &amp;&amp; f2 ]]; then echo "success" else echo "fail" fi </code></pre>
8,117,867
2
0
null
2011-11-14 05:51:49.23 UTC
11
2011-11-14 06:05:05.983 UTC
null
null
null
null
3,966
null
1
47
bash
44,019
<p>You don't use <code>[[</code> (or <code>[</code>) when running a command and checking the result code.</p> <pre><code>if f1 &amp;&amp; f2 ; then echo "success" else echo "fail" fi </code></pre>
9,633,840
Spring autowired bean for @Aspect aspect is null
<p>I have the following spring configuration:</p> <pre><code>&lt;context:component-scan base-package="uk.co.mysite.googlecontactsync.aop"/&gt; &lt;bean name="simpleEmailSender" class="uk.co.mysite.util.email.simple.SimpleEmailSenderImplementation"/&gt; &lt;aop:aspectj-autoproxy/&gt; </code></pre> <p>Then I have an aspect:</p> <pre><code>@Aspect public class SyncLoggingAspect { @Autowired private SimpleEmailSender simpleEmailSender @AfterReturning(value="execution(* uk.co.mysite.datasync.polling.Poller+.doPoll())", returning="pusher") public void afterPoll(Pusher pusher) { simpleEmailSender.send(new PusherEmail(pusher)); } } </code></pre> <p>This aspect works (I can hit a breakpoint on afterPoll) but simpleEmailSender is null. Unfortunately I cannot find clear documentation on why this is. (For the record, my simpleEmailSender bean exists and is correctly wired into other classes) The following things confuse me:</p> <ol> <li>Is context:component-scan supposed to be picking up @Aspect? If it is then surely it would be a spring managed bean, thus autowired should work?</li> <li>If context:component-scan isn't for creating aspects, how is my aspect being created? I thought aop:aspectj-autoproxy just creates a beanPostProcessor to proxy my @Aspect class? How would it do this if it isn't a spring managed bean?</li> </ol> <p>Obviously you can tell I don't have an understanding of how things should be working from the ground up.</p>
9,658,819
10
7
null
2012-03-09 12:10:32.73 UTC
12
2021-03-08 09:29:20.197 UTC
2012-03-12 09:12:11.953 UTC
null
835,058
null
835,058
null
1
37
java|spring|aop|aspectj|spring-aop
34,390
<p>The aspect is a singleton object and is created outside the Spring container. A solution with XML configuration is to use Spring's factory method to retrieve the aspect.</p> <pre><code>&lt;bean id="syncLoggingAspect" class="uk.co.demo.SyncLoggingAspect" factory-method="aspectOf" /&gt; </code></pre> <p>With this configuration the aspect will be treated as any other Spring bean and the autowiring will work as normal.</p> <p>You have to use the factory-method also on Enum objects and other objects without a constructor or objects that are created outside the Spring container.</p>
9,549,866
PHP Regex to Remove http:// from string
<p>I have full URLs as strings, but I want to remove the http:// at the beginning of the string to display the URL nicely (ex: www.google.com instead of <a href="http://www.google.com">http://www.google.com</a>)</p> <p>Can someone help?</p>
9,549,893
8
7
null
2012-03-03 21:06:22.38 UTC
16
2019-06-05 10:02:19.31 UTC
null
null
null
null
538,143
null
1
50
php|regex
59,331
<pre><code>$str = 'http://www.google.com'; $str = preg_replace('#^https?://#', '', $str); echo $str; // www.google.com </code></pre> <p>That will work for both <code>http://</code> and <code>https://</code></p>
9,419,175
Are closures a violation of the functional programming paradigm?
<p>Functional programming "avoids state and mutable data". </p> <p>Closures hide state by binding their lexical environment and are thus closed over their free <strong>variables</strong>. </p> <p>How is Haskell purely-functional if it supports closures? Don't they break referential transparency?</p>
9,419,915
4
14
null
2012-02-23 18:43:24.36 UTC
10
2013-07-07 20:56:16.497 UTC
2012-04-28 12:40:41.027 UTC
user257111
null
null
255,528
null
1
27
haskell|functional-programming|closures
3,293
<p>In Haskell, closures have free variables in the same way that in math you can write <code>f x = x^2</code> - it doesn't mutate state.</p> <p>I would say that Haskell avoids <em>mutable</em> state.</p>
59,867,434
Every vue component returning Cannot read property 'parseComponent' of undefined
<p>So i've tried researching this but none of the solutions are working. I think it's specifically an issue with some of my vue dependencies, potentially <code>vue-loader</code>, but I'm not sure what specifically to do to fix it. I have tried: </p> <ul> <li>deleting <code>node_modules</code> and re-running <code>npm install</code> </li> <li><code>npm update</code></li> <li>i've tried removing <code>vue-loader</code> completely</li> <li>tried adding, removing, and updating <code>@vue/component-compiler-utils</code></li> <li>tried changing the version of the above to three different things</li> <li>tried running <code>composer install</code> and <code>composer update</code></li> <li>creating a new temp staging branch from master just in case it was some weird git error and building from that</li> </ul> <p>What am I missing here? Every vue component on my staging site returns this same error. The weirdest thing is that the staging server is a direct clone of our production server, where all of this works completely smoothly and i get zero errors.</p> <p><strong>The Errors:</strong></p> <pre><code>ERROR in ./resources/assets/js/components/component.vue Module build failed (from ./node_modules/vue-loader/lib/index.js): TypeError: Cannot read property 'parseComponent' of undefined at parse (/var/www/site/node_modules/@vue/component-compiler-utils/dist/parse.js:14:23) at Object.module.exports (/var/www/site/node_modules/vue-loader/lib/index.js:67:22) @ ./resources/assets/js/app.js 60:29-81 @ multi ./resources/assets/js/app.js ./resources/assets/sass/app.scss </code></pre> <p>I've tried installing these warnings' dependencies as well but still get the same error above, I'm including these because it's what pops up when i run my bash script and run npm install from my staging branch:</p> <pre><code>npm WARN [email protected] requires a peer of eslint@^5.0.0 but none is installed. You must install peer dependencies yourself. npm WARN [email protected] requires a peer of eslint@^5.0.0 but none is installed. You must install peer dependencies yourself. npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules/webpack-dev-server/node_modules/fsevents): npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"}) </code></pre> <p><strong>package.json dependencies</strong></p> <pre><code>"devDependencies": { "axios": "^0.19.0", "babel-preset-stage-2": "^6.24.1", "browser-sync": "^2.26.7", "browser-sync-webpack-plugin": "^2.2.2", "cross-env": "^5.2.0", "eslint": "^6.1.0", "eslint-config-standard": "^13.0.1", "eslint-loader": "^2.2.1", "eslint-plugin-import": "^2.18.2", "eslint-plugin-node": "^9.1.0", "eslint-plugin-promise": "^4.2.1", "eslint-plugin-standard": "^4.0.0", "eslint-plugin-vue": "^5.2.3", "exports-loader": "^0.6.4", "imports-loader": "^0.7.1", "jquery": "^3.3.1", "laravel-mix": "^4.1.2", "lodash": "^4.17.11", "resolve-url-loader": "^3.1.0", "sass": "^1.22.10", "vue": "^2.6.10" }, "dependencies": { "@vue/component-compiler-utils": "^3.1.1", "ajv": "^6.10.0", "babel-polyfill": "^6.26.0", "bootstrap": "^4.3.1", "braces": "^2.3.1", "es6-promise": "^4.2.6", "font-awesome": "^4.7.0", "luxon": "^1.12.1", "moment": "^2.24.0", "popper": "^1.0.1", "popper.js": "^1.14.7", "sass-loader": "^7.1.0", "vue-datetime": "^1.0.0-beta.10", "vue-datetime-picker": "^0.2.1", "vue-full-calendar": "^2.7.0", "vue-loader": "^15.8.3", "vue-router": "^3.0.2", "vue-template-compiler": "2.6.10", "vue-wysiwyg": "^1.7.2", "vuex": "^3.1.0", "weekstart": "^1.0.0", "whatwg-fetch": "^2.0.4", "wkhtmltopdf": "^0.3.4" } } </code></pre> <p>I'm thinking it might have something to do with a specific version of a dependency? But nothing i've been trying from other stack overflow threads or google searches has been helping</p> <p>Let me know if there's any code missing that may help</p>
62,102,017
7
9
null
2020-01-22 20:02:03.94 UTC
5
2022-09-07 04:07:39.41 UTC
2020-01-22 21:08:15.437 UTC
null
3,812,918
null
3,812,918
null
1
29
laravel|vue.js|npm
37,675
<p>I had exacly the same problem and just figured it out, I hope this helps someone. First I changed the vue template compiler to:</p> <blockquote> <p>"vue-template-compiler": "2.6.11"</p> </blockquote> <p>and the I also had to change the vue version to the latest realese, in my case:</p> <blockquote> <p>"vue": "2.6.11"</p> </blockquote>
8,382,536
Allow a custom Attribute only on specific type
<p>Is there a way to force the compiler to restrict the usage of a custom attribute to be used only on specific <strong>property</strong> types like int, short, string (all the primitive types)?<br> similar to the <a href="http://msdn.microsoft.com/en-us/library/system.attributeusageattribute%28v=vs.95%29.aspx">AttributeUsageAttribute</a>'s ValidOn-<a href="http://msdn.microsoft.com/en-us/library/system.attributetargets%28v=vs.95%29.aspx">AttributeTargets</a> enumeration.</p>
8,382,559
5
4
null
2011-12-05 08:13:57.52 UTC
1
2022-03-17 09:34:41.96 UTC
2013-05-29 15:25:15.097 UTC
null
773,113
null
601,179
null
1
47
c#|.net|compiler-construction|attributes
30,507
<p>No, you can't, basically. You can limit it to <code>struct</code> vs <code>class</code> vs <code>interface</code>, that is about it. Plus: you can't add attributes to types outside your code anyway (except for via <code>TypeDescriptor</code>, which isn't the same).</p>
5,031,675
Where does paging, sorting, etc go in repository pattern?
<p>Where do we put the logic for paging and sorting data in an asp.net repository pattern project?</p> <p>Should it go in the service layer or put it in the controller and have the controller directly call the repository? Controller -> Repository is shown <a href="http://highoncoding.com/Articles/566_JQuery_jqGrid_Export_to_Excel_Using_ASP_NET_MVC_Framework.aspx">here</a> for a jquery grid.</p> <p>But unlike that article, my repository returns <code>IQueryable&lt;datatype&gt;</code></p>
5,036,023
5
1
null
2011-02-17 16:28:08.73 UTC
12
2011-02-17 23:28:41.63 UTC
2011-02-17 16:34:00.877 UTC
null
400,861
null
400,861
null
1
19
asp.net-mvc|asp.net-mvc-3|repository-pattern
16,391
<p>It should go in the Repository if your Repository returns materialized sequences (<code>ICollection&lt;T&gt;</code>, <code>List&lt;T&gt;</code>), etc.</p> <p>But if your returning <code>IQueryable&lt;T&gt;</code> (like i am), i hope you have a service layer mediating between your Controllers and Repository, which executes queries on the IQueryable and materialises them into concrete collections.</p> <p>So, i would put the paging in the service layer.</p> <p>Something like this:</p> <pre><code>public PagedList&lt;T&gt; Find(Expression&lt;Func&lt;T,bool&gt;&gt; predicate, int pageNumber, pageSize) { return repository .Find() .Where(predicate) .ToPagedList(pageNumber, pageSize); } </code></pre> <p><code>.ToPagedList</code> can be an extension method that applies the paging you require and projects to a <code>PagedList&lt;T&gt;</code>.</p> <p>There are many <code>PagedList&lt;T&gt;</code> implementations out there. I like <a href="http://www.squaredroot.com/2008/04/08/updated-pagedlist-class/" rel="noreferrer">Rob Conery's one</a>. Has properties that your View requires, so you can bind to a <code>PagedList&lt;T&gt;</code> and create a HTML Helper to render out the page numbers very easily. The only problem with any paged list LINQ implementation is the <code>Count()</code> operation (for the number of records) needs to be done on the server and hence results in 2 round trips.</p> <p>You don't want to be returning non-materialized queries to your View's, as IMO this breaks the MVC pattern.</p> <p>Each time you go to a new page, call your service to retrieve the required result.</p>
5,285,857
When is using MySQL BLOB recommended?
<p>I'm coding an application that will be uploading and deleting many files, i usually just move the files to a folder in the server naming them with the row unique <code>id</code>. But as i understand MySQL also lets me store binary data (files) when would this be a better choice?.</p> <blockquote> <p>Please use solid arguments, like When does using BLOB will mean performance improvement?.</p> </blockquote> <p>P.S: I'm using MyISAM if that matters.</p> <p>Thanks.</p> <hr> <p><strong>UPDATE:</strong></p> <blockquote> <p><strong>Related questions</strong>:<br> - <a href="https://stackoverflow.com/questions/3748/storing-images-in-db-yea-or-nay">Storing Images in DB - Yea or Nay?</a><br> - <a href="https://stackoverflow.com/questions/815626/to-do-or-not-to-do-store-images-in-a-database">To Do or Not to Do: Store Images in a Database</a> (thanks to Sebastian) </p> </blockquote> <p><strong>UPDATE 2</strong></p> <p>Storing the files in the database <strong>is not a need</strong> i'm trying to know when is this a better idea than storing them in folders.</p>
5,285,903
5
1
null
2011-03-12 22:14:29.39 UTC
6
2014-03-06 17:04:48.433 UTC
2017-05-23 12:16:51.87 UTC
null
-1
null
459,688
null
1
19
mysql|filesystems|blob
43,539
<p>Read:</p> <ul> <li><a href="https://stackoverflow.com/questions/4654004/mysql-binary-storage-using-blob-vs-os-file-system-large-files-large-quantities">MySQL Binary Storage using BLOB VS OS File System: large files, large quantities, large problems</a></li> <li><a href="https://stackoverflow.com/questions/815626/to-do-or-not-to-do-store-images-in-a-database">To Do or Not to Do: Store Images in a Database</a></li> </ul> <p>which <em>concludes</em></p> <blockquote> <p>If you on occasion need to retrieve an image and it has to be available on several different web servers. But I think that's pretty much it.</p> <ul> <li>If it doesn't have to be available on several servers, it's always better to put them in the file system. </li> <li>If it has to be available on several servers and there's actually some kind of load in the system, you'll need some kind of distributed storage.</li> </ul> </blockquote>
5,512,023
Ruby on Rails 3 : "superclass mismatch for class ..."
<p>Platform: Mac OSX 10.6</p> <p>In my terminal, i start the Ruby console with "rails c"</p> <p>While following the Ruby on Rails 3 tutorial to build a class:</p> <pre><code>class Word &lt; String def palindrome? #check if a string is a palindrome self == self.reverse end end </code></pre> <p>i get the error message:</p> <pre><code>TypeError: superclass mismatch for class Word from (irb):33 from /Users/matthew/.rvm/gems/ruby-1.9.2-p180@rails3tutorial/gems/railties-3.0.5/lib/rails/commands/console.rb:44:in `start' from /Users/matthew/.rvm/gems/ruby-1.9.2-p180@rails3tutorial/gems/railties-3.0.5/lib/rails/commands/console.rb:8:in `start' from /Users/matthew/.rvm/gems/ruby-1.9.2-p180@rails3tutorial/gems/railties-3.0.5/lib/rails/commands.rb:23:in `&lt;top (required)&gt;' from script/rails:6:in `require' from script/rails:6:in `&lt;main&gt;' </code></pre> <p>The tutorial shows that it has no problem and i know the code is fine; I've searched other related questions, but they all involved migrating from Ruby 2 to 3 or erb vs eruby.</p>
5,512,173
5
0
null
2011-04-01 10:20:21.767 UTC
11
2020-05-09 19:31:24.883 UTC
2018-05-20 23:07:43.383 UTC
null
479,863
null
605,948
null
1
69
ruby-on-rails|ruby|ruby-on-rails-3
78,013
<p>You already have a <code>Word</code> class defined elsewhere. I tried within a Rails 3 app but was not able to replicate.</p> <p>If you have not created a second <code>Word</code> class yourself, it is likely one of your Gems or plugins already defines it.</p>
4,954,741
How to ping IP addresses using JavaScript
<p>I want to run a JavaScript code to ping 4 different IP addresses and then retrieve the packet loss and latency of these ping requests and display them on the page.</p> <p>How do I do this?</p>
4,954,789
8
2
null
2011-02-10 08:14:33.513 UTC
9
2021-08-04 02:29:24.657 UTC
2011-02-10 08:16:17.79 UTC
null
313,758
null
434,885
null
1
9
javascript|ping|latency
81,817
<p>You can't do this from JS. What you could do is this:</p> <pre><code> client --AJAX-- yourserver --ICMP ping-- targetservers </code></pre> <p>Make an AJAX request to your server, which will then ping the target servers for you, and return the result in the AJAX result. </p> <p>Possible caveats:</p> <ul> <li>this tells you whether the target servers are pingable from your server, not from the user's client <ul> <li>so the client won't be able to test hosts its LAN</li> <li>but you shouldn't let the host check hosts on the server's internal network, if any exist</li> <li>some hosts may block traffic from certain hosts and not others</li> </ul></li> <li>you need to limit the ping count per machine: <ul> <li>to avoid the AJAX request from timing out</li> <li>some site operators can get very upset when you keep pinging their sites all the time</li> </ul></li> <li>resources <ul> <li>long-running HTTP requests could run into maximum connection limit of your server, check how high it is</li> <li>many users trying to ping at once might generate suspicious-looking traffic (all ICMP and nothing else)</li> </ul></li> <li>concurrency - you may wish to pool/cache the up/down status for a few seconds at least, so that multiple clients wishing to ping the same target won't launch a flood of pings</li> </ul>
5,383,074
How is an "int" assigned to an object?
<p>How are we able to assign an integer to an object in .NET?</p> <p>Reference types are derived from System.Object and value types are from System.ValueType.</p> <p>So, how is it possible?</p>
5,383,104
9
0
null
2011-03-21 20:13:21.14 UTC
4
2016-05-20 12:37:18.133 UTC
2016-05-20 12:37:18.133 UTC
null
1,465,171
null
670,110
null
1
13
c#|.net|types
41,528
<p>If you look at <a href="http://msdn.microsoft.com/en-us/library/system.valuetype.aspx" rel="nofollow noreferrer"><code>System.ValueType</code></a>, it too derives from <code>System.Object</code></p> <p>Also see <a href="https://stackoverflow.com/questions/1682231/how-do-valuetypes-derive-from-object-referencetype-and-still-be-valuetypes">How do ValueTypes derive from Object (ReferenceType) and still be ValueTypes</a></p>
5,166,842
sort dates in python array
<p>How to sort the below array of dates on python 2.4</p> <pre><code> timestamps = ['2011-06-2', '2011-08-05', '2011-02-04', '2010-1-14', '2010-12-13', '2010-1-12', '2010-2-11', '2010-2-07', '2010-12-02', '2011-11-30', '2010-11-26', '2010-11-23', '2010-11-22', '2010-11-16'] </code></pre>
5,166,911
9
1
null
2011-03-02 11:29:41.57 UTC
9
2020-02-26 17:43:35.997 UTC
null
null
null
null
277,603
null
1
27
python
104,374
<pre><code>sorted(timestamps, key=lambda d: map(int, d.split('-'))) </code></pre>
4,852,251
Is there a software-engineering methodology for functional programming?
<p>Software Engineering as it is taught today is entirely focused on object-oriented programming and the 'natural' object-oriented view of the world. There is a detailed methodology that describes how to transform a domain model into a class model with several steps and a lot of (UML) artifacts like use-case-diagrams or class-diagrams. Many programmers have internalized this approach and have a good idea about how to design an object-oriented application from scratch. </p> <p>The new hype is functional programming, which is taught in many books and tutorials. But what about functional software engineering? While reading about Lisp and Clojure, I came about two interesting statements: </p> <ol> <li><p>Functional programs are often developed bottom up instead of top down ('On Lisp', Paul Graham)</p></li> <li><p>Functional Programmers use Maps where OO-Programmers use objects/classes ('Clojure for Java Programmers', talk by Rich Hickley). </p></li> </ol> <p>So what is the methodology for a systematic (model-based ?) design of a functional application, i.e. in Lisp or Clojure? What are the common steps, what artifacts do I use, how do I map them from the problem space to the solution space? </p>
4,905,458
13
9
null
2011-01-31 14:50:30.083 UTC
152
2018-01-19 10:36:30.7 UTC
null
null
null
null
783,306
null
1
204
functional-programming|clojure|lisp|model-driven-development
23,116
<p>Thank God that the software-engineering people have not yet discovered functional programming. Here are some parallels:</p> <ul> <li><p>Many OO "design patterns" are captured as higher-order functions. For example, the Visitor pattern is known in the functional world as a "fold" (or if you are a pointy-headed theorist, a "catamorphism"). In functional languages, data types are mostly trees or tuples, and every tree type has a natural catamorphism associated with it. </p> <p>These higher-order functions often come with certain laws of programming, aka "free theorems".</p></li> <li><p>Functional programmers use diagrams much less heavily than OO programmers. Much of what is expressed in OO diagrams is instead expressed in <em>types</em>, or in "signatures", which you should think of as "module types". Haskell also has "type classes", which is a bit like an interface type.</p> <p>Those functional programmers who use types generally think that "once you get the types right; the code practically writes itself."</p> <p>Not all functional languages use explicit types, but the <a href="http://htdp.org" rel="noreferrer">How To Design Programs</a> book, an excellent book for learning Scheme/Lisp/Clojure, relies heavily on "data descriptions", which are closely related to types.</p></li> </ul> <blockquote> <p>So what is the methodology for a systematic (model-based ?) design of a functional application, i.e. in Lisp or Clojure? </p> </blockquote> <p>Any design method based on data abstraction works well. I happen to think that this is easier when the language has explicit types, but it works even without. A good book about design methods for abstract data types, which is easily adapted to functional programming, is <em>Abstraction and Specification in Program Development</em> by Barbara Liskov and John Guttag, the <em>first</em> edition. Liskov won the Turing award in part for that work.</p> <p>Another design methodology that is unique to Lisp is to decide what language extensions would be useful in the problem domain in which you are working, and then use hygienic macros to add these constructs to your language. A good place to read about this kind of design is Matthew Flatt's article <a href="http://queue.acm.org/detail.cfm?id=2068896" rel="noreferrer"><em>Creating Languages in Racket</em></a>. The article may be behind a paywall. You can also find more general material on this kind of design by searching for the term "domain-specific embedded language"; for particular advice and examples beyond what Matthew Flatt covers, I would probably start with Graham's <a href="http://www.paulgraham.com/onlisp.html" rel="noreferrer"><em>On Lisp</em></a> or perhaps <a href="http://www.paulgraham.com/acl.html" rel="noreferrer"><em>ANSI Common Lisp</em></a>.</p> <blockquote> <p>What are the common steps, what artifacts do I use?</p> </blockquote> <p>Common steps:</p> <ol> <li><p>Identify the data in your program and the operations on it, and define an abstract data type representing this data.</p></li> <li><p>Identify common actions or patterns of computation, and express them as higher-order functions or macros. Expect to take this step as part of refactoring.</p></li> <li><p>If you're using a typed functional language, use the type checker early and often. If you're using Lisp or Clojure, the best practice is to write function contracts first including unit tests—it's test-driven development to the max. And you will want to use whatever version of QuickCheck has been ported to your platform, which in your case looks like it's called <a href="https://bitbucket.org/kotarak/clojurecheck" rel="noreferrer">ClojureCheck</a>. It's an extremely powerful library for constructing random tests of code that uses higher-order functions.</p></li> </ol>
29,542,356
Xcode 6.3 Crashes when navigating from storyboard to other Swift 1.2 file
<p>I installed Xcode 6.3 which includes support for Swift 1.2. It turned up a ton of error messages, which are mostly casting issues. </p> <p>I navigated to the storyboard, and cannot go back to any other <code>.swift</code> without the whole thing crashing. I have force quit, restarted, and even re-installed, and I still can't navigate away from the <code>Main.storyboard</code> file. </p> <p>I have tried <a href="https://stackoverflow.com/a/26474823/106611">the suggestion described here</a> to open storyboard as code, make some changes, revert those changes, save and try again, and still no luck. </p> <p>Is something in my code breaking Xcode? Is anyone else experiencing this? I had used Xcode 6.3 beta successfully with the same codebase. </p> <p><strong>Update:</strong> This has now been fixed in <a href="https://itunes.apple.com/app/xcode/id497799835" rel="nofollow noreferrer">Xcode 6.3.1</a> released on the 21st of April 2015.</p>
29,543,801
8
12
null
2015-04-09 15:11:43.043 UTC
15
2017-02-06 14:41:50.767 UTC
2017-05-23 11:45:24.007 UTC
null
-1
null
106,611
null
1
80
ios|swift|xcode
5,768
<p>I gather from the apple developer forums that this is an <strong>@IBDesignable</strong> issue. Especially in projects that use custom fonts, additional xibs, etc. </p> <p>I have somehow fixed my issue by removing all <strong>@IBDesignable</strong> from swift UIView class definitions. You can open your project directory with TextMate or other, search and remove all "@IBDesignable"</p> <p>However I still think this is a MAJOR bug, that needs to be worked on.. so keep filing bug reports to Apple.</p>
12,162,860
How can I render line faster than CGContextStrokePath?
<p>I'm plotting ~768 points for a graph using CGContextStrokePath. The problem is that every second I get a new data point, and thus redraw the graph. This is currently taking 50% CPU in what's already a busy App. </p> <p><img src="https://i.stack.imgur.com/YmrCr.png" alt="graph"></p> <p><img src="https://i.stack.imgur.com/3xYch.png" alt="instruments"></p> <p>Graph drawing is done in drawRect in a UIView. The graph is time based, so new data points always arrive on the right hand side. </p> <p>I'm thinking a few alternative approaches:</p> <ol> <li>Draw with GLKit (at cost of not supporting older devices) and seems like a lot of work.</li> <li>Do some kind of screen grab (renderInContext?), shift left by 1 px, blit, and only draw a line for the last two data points.</li> <li>Have a very wide CALayer and pan along it?</li> <li>Smooth the data set, but this feels like cheating :)</li> </ol> <p>It's also possible I'm missing something obvious here that I'm seeing such poor performance?</p> <pre><code> CGContextBeginPath(context); CGContextSetLineWidth(context, 2.0); UIColor *color = [UIColor whiteColor]; CGContextSetStrokeColorWithColor(context, [color CGColor]); … CGContextAddLines(context, points, index); CGContextMoveToPoint(context, startPoint.x, startPoint.y); CGContextClosePath(context); CGContextStrokePath(context); </code></pre>
12,168,863
3
2
null
2012-08-28 15:43:49.15 UTC
9
2012-08-28 23:14:43.533 UTC
null
null
null
null
345,165
null
1
8
ios|performance|cgcontext
2,768
<p>Let's implement a graphing view that uses a bunch of tall, skinny layers to reduce the amount of redrawing needed. We'll slide the layers to the left as we add samples, so at any time, we probably have one layer hanging off the left edge of the view and one hanging off the right edge of the view:</p> <p><img src="https://i.stack.imgur.com/zHUCW.png" alt="layers over view"></p> <p>You can find a complete working example of the code below on <a href="https://github.com/mayoff/stackoverflow-12162860-GraphView" rel="noreferrer">my github account</a>.</p> <h2>Constants</h2> <p>Let's make each layer 32 points wide:</p> <pre><code>#define kLayerWidth 32 </code></pre> <p>And let's say we're going to space the samples along the X axis at one sample per point:</p> <pre><code>#define kPointsPerSample 1 </code></pre> <p>So we can deduce the number of samples per layer. Let's call one layer's worth of samples a <em>tile</em>:</p> <pre><code>#define kSamplesPerTile (kLayerWidth / kPointsPerSample) </code></pre> <p>When we're drawing a layer, we can't just draw the samples strictly inside the layer. We have to draw a sample or two past each edge, because the lines to those samples cross the edge of the layer. We'll call these the <em>padding samples</em>:</p> <pre><code>#define kPaddingSamples 2 </code></pre> <p>The maximum dimension of an iPhone screen is 320 points, so we can compute the maximum number of samples we need to retain:</p> <pre><code>#define kMaxVisibleSamples ((320 / kPointsPerSample) + 2 * kPaddingSamples) </code></pre> <p>(You should change the 320 if you want to run on an iPad.)</p> <p>We'll need to be able to compute which tile contains a given sample. And as you'll see, we'll want to do this even if the sample number is negative, because it will make later computations easier:</p> <pre><code>static inline NSInteger tileForSampleIndex(NSInteger sampleIndex) { // I need this to round toward -∞ even if sampleIndex is negative. return (NSInteger)floorf((float)sampleIndex / kSamplesPerTile); } </code></pre> <h2>Instance Variables</h2> <p>Now, to implement <code>GraphView</code>, we'll need some instance variables. We'll need to store the layers that we're using to draw the graph. And we want to be able to look up each layer according to which tile it's graphing:</p> <pre><code>@implementation GraphView { // Each key in _tileLayers is an NSNumber whose value is a tile number. // The corresponding value is the CALayer that displays the tile's samples. // There will be tiles that don't have a corresponding layer. NSMutableDictionary *_tileLayers; </code></pre> <p>In a real project, you'd want to store the samples in a model object and give the view a reference to the model. But for this example, we'll just store the samples in the view:</p> <pre><code> // Samples are stored in _samples as instances of NSNumber. NSMutableArray *_samples; </code></pre> <p>Since we don't want to store an arbitrarily large number of samples, we'll discard old samples when <code>_samples</code> gets big. But it will simplify the implementation if we can mostly pretend that we never discard samples. To do that, we keep track of the total number of samples ever received.</p> <pre><code> // I discard old samples from _samples when I have more than // kMaxTiles' worth of samples. This is the total number of samples // ever collected, including discarded samples. NSInteger _totalSampleCount; </code></pre> <p>We should avoid blocking the main thread, so we'll do our drawing on a separate GCD queue. We need to keep track of which tiles need to be drawn on that queue. To avoid drawing a pending tile more than once, we use a set (which eliminates duplicates) instead of an array:</p> <pre><code> // Each member of _tilesToRedraw is an NSNumber whose value // is a tile number to be redrawn. NSMutableSet *_tilesToRedraw; </code></pre> <p>And here's the GCD queue on which we'll do the drawing.</p> <pre><code> // Methods prefixed with rq_ run on redrawQueue. // All other methods run on the main queue. dispatch_queue_t _redrawQueue; } </code></pre> <h2>Initialization / Destruction</h2> <p>To make this view work whether you create it in code or in a nib, we need two initialization methods:</p> <pre><code>- (id)initWithFrame:(CGRect)frame { if ((self = [super initWithFrame:frame])) { [self commonInit]; } return self; } - (void)awakeFromNib { [self commonInit]; } </code></pre> <p>Both methods call <code>commonInit</code> to do the real initialization:</p> <pre><code>- (void)commonInit { _tileLayers = [[NSMutableDictionary alloc] init]; _samples = [[NSMutableArray alloc] init]; _tilesToRedraw = [[NSMutableSet alloc] init]; _redrawQueue = dispatch_queue_create("MyView tile redraw", 0); } </code></pre> <p>ARC won't clean up the GCD queue for us:</p> <pre><code>- (void)dealloc { if (_redrawQueue != NULL) { dispatch_release(_redrawQueue); } } </code></pre> <h2>Adding a sample</h2> <p>To add a new sample, we pick a random number and append it to <code>_samples</code>. We also increment <code>_totalSampleCount</code>. We discard the oldest samples if <code>_samples</code> has gotten big.</p> <pre><code>- (void)addRandomSample { [_samples addObject:[NSNumber numberWithFloat:120.f * ((double)arc4random() / UINT32_MAX)]]; ++_totalSampleCount; [self discardSamplesIfNeeded]; </code></pre> <p>Then, we check if we've started a new tile. If so, we find the layer that was drawing the oldest tile, and reuse it to draw the newly-created tile.</p> <pre><code> if (_totalSampleCount % kSamplesPerTile == 1) { [self reuseOldestTileLayerForNewestTile]; } </code></pre> <p>Now we recompute the layout of all the layers, which will to the left a bit so the new sample will be visible in the graph.</p> <pre><code> [self layoutTileLayers]; </code></pre> <p>Finally, we add tiles to the redraw queue.</p> <pre><code> [self queueTilesForRedrawIfAffectedByLastSample]; } </code></pre> <p>We don't want to discard samples one at a time. That would be inefficient. Instead, we let the garbage build up for a while, then throw it away all at once:</p> <pre><code>- (void)discardSamplesIfNeeded { if (_samples.count &gt;= 2 * kMaxVisibleSamples) { [_samples removeObjectsInRange:NSMakeRange(0, _samples.count - kMaxVisibleSamples)]; } } </code></pre> <p>To reuse a layer for the new tile, we need to find the layer of the oldest tile:</p> <pre><code>- (void)reuseOldestTileLayerForNewestTile { // The oldest tile's layer should no longer be visible, so I can reuse it as the new tile's layer. NSInteger newestTile = tileForSampleIndex(_totalSampleCount - 1); NSInteger reusableTile = newestTile - _tileLayers.count; NSNumber *reusableTileObject = [NSNumber numberWithInteger:reusableTile]; CALayer *layer = [_tileLayers objectForKey:reusableTileObject]; </code></pre> <p>Now we can remove it from the <code>_tileLayers</code> dictionary under the old key and store it under the new key:</p> <pre><code> [_tileLayers removeObjectForKey:reusableTileObject]; [_tileLayers setObject:layer forKey:[NSNumber numberWithInteger:newestTile]]; </code></pre> <p>By default, when we move the reused layer to its new position, Core Animation will animate it sliding over. We don't want that, because it will be a big empty orange rectangle sliding across our graph. We want to move it instantly:</p> <pre><code> // The reused layer needs to move instantly to its new position, // lest it be seen animating on top of the other layers. [CATransaction begin]; { [CATransaction setDisableActions:YES]; layer.frame = [self frameForTile:newestTile]; } [CATransaction commit]; } </code></pre> <p>When we add a sample, we'll always want to redraw the tile containing the sample. We also need to redraw the prior tile, if the new sample is within the padding range of the prior tile.</p> <pre><code>- (void)queueTilesForRedrawIfAffectedByLastSample { [self queueTileForRedraw:tileForSampleIndex(_totalSampleCount - 1)]; // This redraws the second-newest tile if the new sample is in its padding range. [self queueTileForRedraw:tileForSampleIndex(_totalSampleCount - 1 - kPaddingSamples)]; } </code></pre> <p>Queuing a tile for redraw is just a matter of adding it to the redraw set and dispatching a block to redraw it on <code>_redrawQueue</code>.</p> <pre><code>- (void)queueTileForRedraw:(NSInteger)tile { [_tilesToRedraw addObject:[NSNumber numberWithInteger:tile]]; dispatch_async(_redrawQueue, ^{ [self rq_redrawOneTile]; }); } </code></pre> <h2>Layout</h2> <p>The system will send <code>layoutSubviews</code> to the <code>GraphView</code> when it first appears, and any time its size changes (such as if a device rotation resizes it). And we only get the <code>layoutSubviews</code> message when we're really about to appear on the screen, with our final bounds set. So <code>layoutSubviews</code> is a good place to set up the tile layers.</p> <p>First, we need to create or remove layers as necessary so we have the right layers for our size. Then we need to lay out the layers by setting their frames appropriately. Finally, for each layer, we need to queue its tile for redraw.</p> <pre><code>- (void)layoutSubviews { [self adjustTileDictionary]; [CATransaction begin]; { // layoutSubviews only gets called on a resize, when I will be // shuffling layers all over the place. I don't want to animate // the layers to their new positions. [CATransaction setDisableActions:YES]; [self layoutTileLayers]; } [CATransaction commit]; for (NSNumber *key in _tileLayers) { [self queueTileForRedraw:key.integerValue]; } } </code></pre> <p>Adjusting the tile dictionary means setting up a layer for each visible tile and removing layers for non-visible tiles. We'll just reset the dictionary from scratch each time, but we'll try to reuse the layer's we've already created. The tiles that need layers are the newest tile, and preceding tiles so we have enough layers to cover the view.</p> <pre><code>- (void)adjustTileDictionary { NSInteger newestTile = tileForSampleIndex(_totalSampleCount - 1); // Add 1 to account for layers hanging off the left and right edges. NSInteger tileLayersNeeded = 1 + ceilf(self.bounds.size.width / kLayerWidth); NSInteger oldestTile = newestTile - tileLayersNeeded + 1; NSMutableArray *spareLayers = [[_tileLayers allValues] mutableCopy]; [_tileLayers removeAllObjects]; for (NSInteger tile = oldestTile; tile &lt;= newestTile; ++tile) { CALayer *layer = [spareLayers lastObject]; if (layer) { [spareLayers removeLastObject]; } else { layer = [self newTileLayer]; } [_tileLayers setObject:layer forKey:[NSNumber numberWithInteger:tile]]; } for (CALayer *layer in spareLayers) { [layer removeFromSuperlayer]; } } </code></pre> <p>The first time through, and any time the view gets sufficiently wider, we need to create new layers. While we're creating the view, we'll tell it to avoid animating its contents or position. Otherwise it will animate them by default.</p> <pre><code>- (CALayer *)newTileLayer { CALayer *layer = [CALayer layer]; layer.backgroundColor = [UIColor greenColor].CGColor; layer.actions = [NSDictionary dictionaryWithObjectsAndKeys: [NSNull null], @"contents", [NSNull null], @"position", nil]; [self.layer addSublayer:layer]; return layer; } </code></pre> <p>Actually laying out the tile layers is just a matter of setting each layer's frame:</p> <pre><code>- (void)layoutTileLayers { [_tileLayers enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { CALayer *layer = obj; layer.frame = [self frameForTile:[key integerValue]]; }]; } </code></pre> <p>Of course the trick is computing the frame for each layer. And the y, width, and height parts are easy enough:</p> <pre><code>- (CGRect)frameForTile:(NSInteger)tile { CGRect myBounds = self.bounds; CGFloat x = [self xForTile:tile myBounds:myBounds]; return CGRectMake(x, myBounds.origin.y, kLayerWidth, myBounds.size.height); } </code></pre> <p>To compute the x coordinate of the tile's frame, we compute the x coordinate of the first sample in the tile:</p> <pre><code>- (CGFloat)xForTile:(NSInteger)tile myBounds:(CGRect)myBounds { return [self xForSampleAtIndex:tile * kSamplesPerTile myBounds:myBounds]; } </code></pre> <p>Computing the x coordinate for a sample requires a little thought. We want the newest sample to be at the right edge of the view, and the second-newest to be <code>kPointsPerSample</code> points to the left of that, and so on:</p> <pre><code>- (CGFloat)xForSampleAtIndex:(NSInteger)index myBounds:(CGRect)myBounds { return myBounds.origin.x + myBounds.size.width - kPointsPerSample * (_totalSampleCount - index); } </code></pre> <h2>Redrawing</h2> <p>Now we can talk about how to actually draw tiles. We're going to do the drawing on a separate GCD queue. We can't safely access most Cocoa Touch objects from two threads simultaneously, so we need to be careful here. We'll use a prefix of <code>rq_</code> on all the methods that run on <code>_redrawQueue</code> to remind ourselves that we're not on the main thread.</p> <p>To redraw one tile, we need to get the tile number, the graphical bounds of the tile, and the points to draw. All of those things come from data structures that we might be modifying on the main thread, so we need to access them only on the main thread. So we dispatch back to the main queue:</p> <pre><code>- (void)rq_redrawOneTile { __block NSInteger tile; __block CGRect bounds; CGPoint pointStorage[kSamplesPerTile + kPaddingSamples * 2]; CGPoint *points = pointStorage; // A block cannot reference a local variable of array type, so I need a pointer. __block NSUInteger pointCount; dispatch_sync(dispatch_get_main_queue(), ^{ tile = [self dequeueTileToRedrawReturningBounds:&amp;bounds points:points pointCount:&amp;pointCount]; }); </code></pre> <p>It so happens that we might not have any tiles to redraw. If you look back at <code>queueTilesForRedrawIfAffectedByLastSample</code>, you'll see that it usually tries to queue the same tile twice. Since <code>_tilesToRedraw</code> is a set (not an array), the duplicate was discarded, but <code>rq_redrawOneTile</code> was dispatched twice anyway. So we need to check that we actually have a tile to redraw:</p> <pre><code> if (tile == NSNotFound) return; </code></pre> <p>Now we need to actually draw the tile's samples:</p> <pre><code> UIImage *image = [self rq_imageWithBounds:bounds points:points pointCount:pointCount]; </code></pre> <p>Finally we need to update the tile's layer to show the new image. We can only touch a layer on the main thread:</p> <pre><code> dispatch_async(dispatch_get_main_queue(), ^{ [self setImage:image forTile:tile]; }); } </code></pre> <p>Here's how we actually draw the image for the layer. I will assume you know enough Core Graphics to follow this:</p> <pre><code>- (UIImage *)rq_imageWithBounds:(CGRect)bounds points:(CGPoint *)points pointCount:(NSUInteger)pointCount { UIGraphicsBeginImageContextWithOptions(bounds.size, YES, 0); { CGContextRef gc = UIGraphicsGetCurrentContext(); CGContextTranslateCTM(gc, -bounds.origin.x, -bounds.origin.y); [[UIColor orangeColor] setFill]; CGContextFillRect(gc, bounds); [[UIColor whiteColor] setStroke]; CGContextSetLineWidth(gc, 1.0); CGContextSetLineJoin(gc, kCGLineCapRound); CGContextBeginPath(gc); CGContextAddLines(gc, points, pointCount); CGContextStrokePath(gc); } UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image; } </code></pre> <p>But we still have to get the tile, the graphics bounds, and the points to draw. We dispatched back to the main thread to do it:</p> <pre><code>// I return NSNotFound if I couldn't dequeue a tile. // The `pointsOut` array must have room for at least // kSamplesPerTile + 2*kPaddingSamples elements. - (NSInteger)dequeueTileToRedrawReturningBounds:(CGRect *)boundsOut points:(CGPoint *)pointsOut pointCount:(NSUInteger *)pointCountOut { NSInteger tile = [self dequeueTileToRedraw]; if (tile == NSNotFound) return NSNotFound; </code></pre> <p>The graphics bounds are just the bounds of the tile, just like we computed earlier to set the frame of the layer:</p> <pre><code> *boundsOut = [self frameForTile:tile]; </code></pre> <p>I need to start graphing from the padding samples before the first sample of the tile. But, prior to having enough samples to fill the view, my tile number may actually be negative! So I need to be sure not to try to access a sample at a negative index:</p> <pre><code> NSInteger sampleIndex = MAX(0, tile * kSamplesPerTile - kPaddingSamples); </code></pre> <p>We also need to make sure we don't try to run past the end of the samples when we compute the sample at which we stop graphing:</p> <pre><code> NSInteger endSampleIndex = MIN(_totalSampleCount, tile * kSamplesPerTile + kSamplesPerTile + kPaddingSamples); </code></pre> <p>And when I actually access the sample values, I need to account for the samples I've discarded:</p> <pre><code> NSInteger discardedSampleCount = _totalSampleCount - _samples.count; </code></pre> <p>Now we can compute the actual points to graph:</p> <pre><code> CGFloat x = [self xForSampleAtIndex:sampleIndex myBounds:self.bounds]; NSUInteger count = 0; for ( ; sampleIndex &lt; endSampleIndex; ++sampleIndex, ++count, x += kPointsPerSample) { pointsOut[count] = CGPointMake(x, [[_samples objectAtIndex:sampleIndex - discardedSampleCount] floatValue]); } </code></pre> <p>And I can return the number of points and the tile:</p> <pre><code> *pointCountOut = count; return tile; } </code></pre> <p>Here's how we actually pull a tile off the redraw queue. Remember that the queue might be empty:</p> <pre><code>- (NSInteger)dequeueTileToRedraw { NSNumber *number = [_tilesToRedraw anyObject]; if (number) { [_tilesToRedraw removeObject:number]; return number.integerValue; } else { return NSNotFound; } } </code></pre> <p>And finally, here's how we actually set the tile layer's contents to the new image. Remember that we dispatched back to the main queue to do this:</p> <pre><code>- (void)setImage:(UIImage *)image forTile:(NSInteger)tile { CALayer *layer = [_tileLayers objectForKey:[NSNumber numberWithInteger:tile]]; if (layer) { layer.contents = (__bridge id)image.CGImage; } } </code></pre> <h2>Making it sexier</h2> <p>If you do all of that, it will work fine. But you can actually make it slightly nicer-looking by animating the repositioning of the layers when a new sample comes in. This is very easy. We just modify <code>newTileLayer</code> so that it adds an animation for the <code>position</code> property:</p> <pre><code>- (CALayer *)newTileLayer { CALayer *layer = [CALayer layer]; layer.backgroundColor = [UIColor greenColor].CGColor; layer.actions = [NSDictionary dictionaryWithObjectsAndKeys: [NSNull null], @"contents", [self newTileLayerPositionAnimation], @"position", nil]; [self.layer addSublayer:layer]; return layer; } </code></pre> <p>and we create the animation like this:</p> <pre><code>- (CAAnimation *)newTileLayerPositionAnimation { CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"]; animation.duration = 0.1; animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]; return animation; } </code></pre> <p>You will want to set the duration to match the speed at which new samples arrive.</p>
12,609,527
Why isn't Try/Catch used more often in JavaScript?
<p>It seems like with other languages that support Try/Catch, developers make use of that feature more than they do in JavaScript. Is there a reason for this? Is the JS implementation of Try/Catch flawed?</p>
12,609,630
5
5
null
2012-09-26 20:05:21.883 UTC
7
2017-06-17 16:39:55.687 UTC
null
null
null
null
55,589
null
1
38
javascript
16,691
<p>Try taking a look at this article: <a href="http://dev.opera.com/articles/view/efficient-javascript/?page=2#trycatch" rel="noreferrer">http://dev.opera.com/articles/view/efficient-javascript/?page=2#trycatch</a></p> <p><em>From the above link:</em></p> <p>The try-catch-finally construct is fairly unique. Unlike other constructs, it <strong>creates a new variable in the current scope at runtime</strong>. This happens <strong>each time</strong> the catch clause is executed, where the caught exception object is assigned to a variable. This variable does not exist inside other parts of the script even inside the same scope. It is created at the start of the catch clause, then destroyed at the end of it.</p> <p>Because this variable is created and destroyed at runtime, and represents a special case in the language, <strong>some browsers do not handle it very efficiently</strong>, and <strong>placing a catch handler inside a performance critical loop may cause performance problems when exceptions are caught</strong>.</p> <p>You can also view a similar question <a href="https://stackoverflow.com/questions/5260526/use-of-try-catch-in-javascript"><strong>here</strong></a></p> <p><strong>UPDATE</strong></p> <p>Adding a link to: <a href="https://github.com/petkaantonov/bluebird/wiki/Optimization-killers" rel="noreferrer">https://github.com/petkaantonov/bluebird/wiki/Optimization-killers</a> as it contains useful information regarding V8 and how it handles these (and similar) constructs. </p> <p>In particular: </p> <p>Currently not optimizable:</p> <ul> <li>Generator functions </li> <li>Functions that contain a for-of statement</li> <li>Functions that contain a try-catch statement </li> <li>Functions that contain a try-finally statement </li> <li>Functions that contain a compound let assignment </li> <li>Functions that contain a compound const assignment</li> <li>Functions that contain object literals that contain <strong>proto</strong>, or get or set declarations.</li> </ul> <p>Likely never optimizable:</p> <ul> <li>Functions that contain a debugger statement</li> <li>Functions that call literally eval()</li> <li>Functions that contain a with statement</li> </ul>
12,594,070
dyld: Library not loaded different behavior for 6.0 simulator/6.0 device
<p>My app runs fine on the iPhone 6.0 Simulator in Xcode, but when I try to run it on my 6.0 device, I get the following fatal error:</p> <p>dyld: Library not loaded: /System/Library/Frameworks/AdSupport.framework/AdSupport Referenced from: /var/mobile/Applications/26329A7C-04B0-415A-B8EB-3C59CC1EC0B1/hammerhead.app/hammerhead Reason: image not found</p> <p>I am sure that my Phone has version 6.0 and is up to date. My deployment target is set to 6.0 in my project file and in my info.plist file. What should I do?</p> <p>The problem seems to be with the AdSupport framework, which I put in my app so the new Facebook SDK (3.1) could function with iOS 6.</p>
12,812,450
3
1
null
2012-09-26 03:14:43.88 UTC
10
2014-10-06 13:59:56.517 UTC
2012-10-11 06:09:16.97 UTC
null
859,492
null
1,464,728
null
1
39
xcode|cocoa-touch|ios6|dyld|ios-frameworks
13,105
<p>If you're targeting iOS versions less than 6.0, you'll need to make AdSupport.framework, Social.framework, and Accounts.framework optionally-linked.</p> <p>Please have a look at the attached screenshot.</p> <p>Cheers!!!<img src="https://i.stack.imgur.com/VcHpb.png" alt="enter image description here"></p>
12,530,406
Is gcc 4.8 or earlier buggy about regular expressions?
<p>I am trying to use std::regex in a C++11 piece of code, but it appears that the support is a bit buggy. An example:</p> <pre><code>#include &lt;regex&gt; #include &lt;iostream&gt; int main (int argc, const char * argv[]) { std::regex r("st|mt|tr"); std::cerr &lt;&lt; "st|mt|tr" &lt;&lt; " matches st? " &lt;&lt; std::regex_match("st", r) &lt;&lt; std::endl; std::cerr &lt;&lt; "st|mt|tr" &lt;&lt; " matches mt? " &lt;&lt; std::regex_match("mt", r) &lt;&lt; std::endl; std::cerr &lt;&lt; "st|mt|tr" &lt;&lt; " matches tr? " &lt;&lt; std::regex_match("tr", r) &lt;&lt; std::endl; } </code></pre> <p>outputs:</p> <pre><code>st|mt|tr matches st? 1 st|mt|tr matches mt? 1 st|mt|tr matches tr? 0 </code></pre> <p>when compiled with gcc (MacPorts gcc47 4.7.1_2) 4.7.1, either with </p> <pre><code>g++ *.cc -o test -std=c++11 g++ *.cc -o test -std=c++0x </code></pre> <p>or</p> <pre><code>g++ *.cc -o test -std=gnu++0x </code></pre> <p>Besides, the regex works well if I only have two alternative patterns, e.g. <code>st|mt</code>, so it looks like the last one is not matched for some reasons. The code works well with the Apple LLVM compiler.</p> <p>Any ideas about how to solve the issue?</p> <p><strong>Update</strong> one possible solution is to use groups to implement multiple alternatives, e.g. <code>(st|mt)|tr</code>.</p>
12,665,408
3
15
null
2012-09-21 12:13:43.107 UTC
25
2017-07-10 18:32:30.903 UTC
2015-09-27 04:24:53.357 UTC
null
2,756,719
null
25,418
null
1
105
c++|regex|gcc|c++11|libstdc++
37,180
<p><strong><code>&lt;regex&gt;</code> was implemented and released in GCC 4.9.0.</strong></p> <p>In your (older) version of GCC, it is <a href="http://gcc.gnu.org/bugzilla/show_bug.cgi?id=53631" rel="noreferrer">not implemented</a>.</p> <p>That prototype <code>&lt;regex&gt;</code> code was added when all of GCC's C++0x support was <strong>highly</strong> experimental, tracking early C++0x drafts and being made available for people to experiment with. That allowed people to find problems and give feedback to the standard committee before the standard was finalised. At the time lots of people were grateful to have had access to bleeding edge features long before C++11 was finished and before many other compilers provided <em>any</em> support, and that feedback really helped improve C++11. This was a Good Thing<sup>TM</sup>.</p> <p>The <code>&lt;regex&gt;</code> code was never in a useful state, but was added as a work-in-progress like many other bits of code at the time. It was checked in and made available for others to collaborate on if they wanted to, with the intention that it would be finished eventually.</p> <p>That's often how open source works: <a href="http://en.wikipedia.org/wiki/Release_early,_release_often" rel="noreferrer">Release early, release often</a> -- unfortunately in the case of <code>&lt;regex&gt;</code> we only got the early part right and not the often part that would have finished the implementation. </p> <p>Most parts of the library were more complete and are now almost fully implemented, but <code>&lt;regex&gt;</code> hadn't been, so it stayed in the same unfinished state since it was added.</p> <blockquote> <p>Seriously though, who though that shipping an implementation of regex_search that only does "return false" was a good idea?</p> </blockquote> <p>It wasn't such a bad idea a few years ago, when C++0x was still a work in progress and we shipped lots of partial implementations. No-one thought it would remain unusable for so long so, with hindsight, maybe it should have been disabled and required a macro or built-time option to enable it. But that ship sailed long ago. There are exported symbols from the <em>libstdc++.so</em> library that depend on the regex code, so simply removing it (in, say, GCC 4.8) would not have been trivial.</p>
12,163,433
Inserting a multiple records in a table with while loop
<p>I want to insert couple of hundred rows into a table that points to pk in other table. I have been trying to use while loops for inserting multiple records in the table. I am actually setting up my test data.</p> <p>This is what I am doing :</p> <pre><code>declare @count int; set @count = 4018; while @count &lt;= 5040 begin INSERT INTO [MY_TABLE] ([pk_from_other_table] ,[..] ,[...] ,[..] ,[..] ,[...] ,[...] ,[..]) select (pk_from_other_table, ,[..] ,[...] ,[..] ,[..] ,[...] ,[...] ,[..]) @count = @count + 1; end </code></pre> <p>but this does not seems to work ! can anyone help please... all I want to do is insert number of records = number of records that exist in primary table.</p> <p>? any idea on how can I achieve this ?</p> <p>I either get incorrect sytax near count </p> <p>or </p> <p>Msg 102, Level 15, State 1, Line 17 Incorrect syntax near ','.</p>
12,163,553
2
6
null
2012-08-28 16:17:10.72 UTC
1
2012-08-28 16:55:56.817 UTC
2012-08-28 16:23:20.097 UTC
null
1,630,846
null
1,630,846
null
1
-5
sql|sql-server|tsql
62,576
<p>Your current syntax problem is with the <code>@count = @count + 1;</code> which needs to be <code>set @count = @count + 1</code>.</p> <p>But...</p> <p>There is no need for a loop. You can simply do one big insert directly, like:</p> <pre><code>insert into your_table (fk_col, other_col1, other_col2) select pk_col, 'something', 'something else' from your_other_table </code></pre> <p>If you need to, you can add a <code>where</code> clause to the above.</p>
18,888,220
How to check whether java is installed on the computer
<p>I am trying to install java windows application on client machine.I want to check whether requried JRE is installed on the machine or not. I want to check it by java program not by cmd command</p>
18,888,250
12
4
null
2013-09-19 07:04:52.457 UTC
6
2019-05-29 17:02:05.663 UTC
2013-12-02 06:33:39.71 UTC
null
2,791,255
null
2,791,255
null
1
34
java|runtime
242,134
<p>if you are using windows or linux operating system then type in command prompt / terminal</p> <pre><code>java -version </code></pre> <p>If java is correctly installed then you will get something like this</p> <pre><code>java version "1.7.0_25" Java(TM) SE Runtime Environment (build 1.7.0_25-b15) Java HotSpot(TM) Client VM (build 23.25-b01, mixed mode, sharing) </code></pre> <p>Side note: <em>After installation of Java on a windows operating system, the PATH variable is changed to add java.exe so you need to re-open cmd.exe to reload the PATH variable.</em></p> <p><strong>Edit:</strong></p> <p>CD to the path first...</p> <pre><code>cd C:\ProgramData\Oracle\Java\javapath java -version </code></pre>
19,025,841
How to update some data in a Listview without using notifyDataSetChanged()?
<p>I'm trying to create a <code>ListView</code> with a list of downloading tasks.</p> <p>The downloading tasks are managed in a <code>Service</code> (DownloadService). Everytime a chunk of data is received, the task sends the progress via a <code>Broadcast</code>, received by the <code>Fragment</code> containing the <code>ListView</code> (SavedShowListFragment). On receiving the <code>Broadcast</code> message, the SavedShowListFragment updates the progress of the downloading tasks in the adapter and triggers <code>notifyDataSetChanged()</code>.</p> <p>Every row in the list contains a <code>ProgressBar</code>, a <code>TextView</code> for the title of the file being downloaded and one for the numeric value of the progress, and a <code>Button</code> to pause/resume the download or play the saved show when the download is finished.</p> <p>The problem is that the pause/resume/play <code>Button</code> is often not responsive (<code>onClick()</code> is not called), and I think that's because the whole list is updated very frequently with <code>notifyDataSetChanged()</code> (every time a chunk of data, i.e. 1024 bytes is received, which can be many times per second, especially when there are several downloading tasks running).</p> <p>I guess I could increase the size of the data chunk in the downloading tasks, but I really think my method is not optimal at all!</p> <p>Could calling very frequently <code>notifyDataSetChanged()</code> make the <code>ListView</code> UI unresponsive?</p> <p>Is there any way to update only some <code>Views</code> in the <code>ListView</code> rows, i.e. in my case the <code>ProgressBar</code> and the <code>TextView</code> with the numeric value of the progress, without calling <code>notifyDataSetChanged()</code>, which updates the whole list?</p> <p>To update the progress of the downloading tasks in the <code>ListView</code>, is there any better option than "getChunk/sendBroadcast/updateData/notifyDataSetChanged"?</p> <p>Below are the relevant parts of my code.</p> <p><b>Download task in download service</b></p> <pre><code>public class DownloadService extends Service { //... private class DownloadTask extends AsyncTask&lt;SavedShow, Void, Map&lt;String, Object&gt;&gt; { //... @Override protected Map&lt;String, Object&gt; doInBackground(SavedShow... params) { //... BufferedInputStream in = new BufferedInputStream(connection.getInputStream()); byte[] data = new byte[1024]; int x = 0; while ((x = in.read(data, 0, 1024)) &gt;= 0) { if(!this.isCancelled()){ outputStream.write(data, 0, x); downloaded += x; MyApplication.dbHelper.updateSavedShowProgress(savedShow.getId(), downloaded); Intent intent_progress = new Intent(ACTION_UPDATE_PROGRESS); intent_progress.putExtra(KEY_SAVEDSHOW_ID, savedShow.getId()); intent_progress.putExtra(KEY_PROGRESS, downloaded ); LocalBroadcastManager.getInstance(DownloadService.this).sendBroadcast(intent_progress); } else{ break; } } //... } //... } } </code></pre> <p><b>SavedShowListFragment</b></p> <pre><code>public class SavedShowListFragment extends Fragment { //... @Override public void onResume() { super.onResume(); mAdapter = new SavedShowAdapter(getActivity(), MyApplication.dbHelper.getSavedShowList()); mListView.setAdapter(mAdapter); //... } private ServiceConnection mDownloadServiceConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName className, IBinder service) { // Get service instance DownloadServiceBinder binder = (DownloadServiceBinder) service; mDownloadService = binder.getService(); // Set service to adapter, to 'bind' adapter to the service mAdapter.setDownloadService(mDownloadService); //... } @Override public void onServiceDisconnected(ComponentName arg0) { // Remove service from adapter, to 'unbind' adapter to the service mAdapter.setDownloadService(null); } }; private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if(action.equals(DownloadService.ACTION_UPDATE_PROGRESS)){ mAdapter.updateItemProgress(intent.getLongExtra(DownloadService.KEY_SAVEDSHOW_ID, -1), intent.getLongExtra(DownloadService.KEY_PROGRESS, -1)); } //... } }; //... } </code></pre> <p><b>SavedShowAdapter</b></p> <pre><code>public class SavedShowAdapter extends ArrayAdapter&lt;SavedShow&gt; { private LayoutInflater mLayoutInflater; private List&lt;Long&gt; mSavedShowIdList; // list to find faster the position of the item in updateProgress private DownloadService mDownloadService; private Context mContext; static class ViewHolder { TextView title; TextView status; ProgressBar progressBar; DownloadStateButton downloadStateBtn; } public static enum CancelReason{ PAUSE, DELETE }; public SavedShowAdapter(Context context, List&lt;SavedShow&gt; savedShowList) { super(context, 0, savedShowList); mLayoutInflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE ); mContext = context; mSavedShowIdList = new ArrayList&lt;Long&gt;(); for(SavedShow savedShow : savedShowList){ mSavedShowIdList.add(savedShow.getId()); } } public void updateItemProgress(long savedShowId, long progress){ getItem(mSavedShowIdList.indexOf(savedShowId)).setProgress(progress); notifyDataSetChanged(); } public void updateItemFileSize(long savedShowId, int fileSize){ getItem(mSavedShowIdList.indexOf(savedShowId)).setFileSize(fileSize); notifyDataSetChanged(); } public void updateItemState(long savedShowId, int state_ind, String msg){ SavedShow.State state = SavedShow.State.values()[state_ind]; getItem(mSavedShowIdList.indexOf(savedShowId)).setState(state); if(state==State.ERROR){ getItem(mSavedShowIdList.indexOf(savedShowId)).setError(msg); } notifyDataSetChanged(); } public void deleteItem(long savedShowId){ remove(getItem((mSavedShowIdList.indexOf(savedShowId)))); notifyDataSetChanged(); } public void setDownloadService(DownloadService downloadService){ mDownloadService = downloadService; notifyDataSetChanged(); } @Override public View getView(final int position, View convertView, ViewGroup parent) { ViewHolder holder; View v = convertView; if (v == null) { v = mLayoutInflater.inflate(R.layout.saved_show_list_item, parent, false); holder = new ViewHolder(); holder.title = (TextView)v.findViewById(R.id.title); holder.status = (TextView)v.findViewById(R.id.status); holder.progressBar = (ProgressBar)v.findViewById(R.id.progress_bar); holder.downloadStateBtn = (DownloadStateButton)v.findViewById(R.id.btn_download_state); v.setTag(holder); } else { holder = (ViewHolder) v.getTag(); } holder.title.setText(getItem(position).getTitle()); Integer fileSize = getItem(position).getFileSize(); Long progress = getItem(position).getProgress(); if(progress != null &amp;&amp; fileSize != null){ holder.progressBar.setMax(fileSize); holder.progressBar.setProgress(progress.intValue()); holder.status.setText(Utils.humanReadableByteCount(progress) + " / " + Utils.humanReadableByteCount(fileSize)); } holder.downloadStateBtn.setTag(position); SavedShow.State state = getItem(position).getState(); /* set the button state */ //... /* set buton onclicklistener */ holder.downloadStateBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { int position = (Integer) v.getTag(); SavedShow.State state = getItem(position).getState(); if(state==SavedShow.State.DOWNLOADING){ getItem(position).setState(SavedShow.State.WAIT_PAUSE); notifyDataSetChanged(); mDownloadService.cancelDownLoad(getItem(position).getId(), CancelReason.PAUSE); } else if(state==SavedShow.State.PAUSED || state==SavedShow.State.ERROR){ getItem(position).setState(SavedShow.State.WAIT_DOWNLOAD); notifyDataSetChanged(); mDownloadService.downLoadFile(getItem(position).getId()); } if(state==SavedShow.State.DOWNLOADED){ /* play file */ } } }); return v; } } </code></pre>
19,090,832
3
5
null
2013-09-26 10:34:24.483 UTC
18
2013-10-04 18:21:55.23 UTC
2013-09-29 01:34:44.137 UTC
null
326,849
null
326,849
null
1
23
android|listview|notifydatasetchanged
19,947
<p>Of course, As <strong>pjco</strong> stated, do not update at that speed. I would recommend sending broadcasts at intervals. Better yet, have a container for the data such as progress and update every interval by polling.</p> <p>However, I think it is a good thing as well to update the listview at times without <code>notifyDataSetChanged</code>. Actually this is most useful when the application has a higher update frequency. Remember: I am not saying that your update-triggering mechanism is correct.</p> <hr> <p><strong>Solution</strong></p> <p>Basically, you will want to update a particular position without <code>notifyDataSetChanged</code>. In the following example, I have assumed the following:</p> <ol> <li>Your listview is called mListView.</li> <li>You only want to update the progress</li> <li>Your progress bar in your convertView has the id <code>R.id.progress</code></li> </ol> <hr> <pre><code>public boolean updateListView(int position, int newProgress) { int first = mListView.getFirstVisiblePosition(); int last = mListView.getLastVisiblePosition(); if(position &lt; first || position &gt; last) { //just update your DataSet //the next time getView is called //the ui is updated automatically return false; } else { View convertView = mListView.getChildAt(position - first); //this is the convertView that you previously returned in getView //just fix it (for example:) ProgressBar bar = (ProgressBar) convertView.findViewById(R.id.progress); bar.setProgress(newProgress); return true; } } </code></pre> <hr> <p><strong>Notes</strong></p> <p>This example of course is not complete. You can probably use the following sequence:</p> <ol> <li>Update your Data (when you receive new progress)</li> <li>Call <code>updateListView(int position)</code> that should use the same code but update using your dataset and without the parameter.</li> </ol> <p>In addition, I just noticed that you have some code posted. Since you are using a Holder, you can simply get the holder inside the function. I will not update the code (I think it is self-explanatory).</p> <p>Lastly, just to emphasize, change your whole code for triggering progress updates. A fast way would be to alter your Service: Wrap the code that sends the broadcast with an if statement which checks whether the last update had been more than a second or half second ago and whether the download has finished (no need to check finished but make sure to send update when finished):</p> <p>In your download service</p> <pre><code>private static final long INTERVAL_BROADCAST = 800; private long lastUpdate = 0; </code></pre> <p>Now in doInBackground, wrap the intent sending with an if statement</p> <pre><code>if(System.currentTimeMillis() - lastUpdate &gt; INTERVAL_BROADCAST) { lastUpdate = System.currentTimeMillis(); Intent intent_progress = new Intent(ACTION_UPDATE_PROGRESS); intent_progress.putExtra(KEY_SAVEDSHOW_ID, savedShow.getId()); intent_progress.putExtra(KEY_PROGRESS, downloaded ); LocalBroadcastManager.getInstance(DownloadService.this).sendBroadcast(intent_progress); } </code></pre>
18,761,404
How to scale images on a html5 canvas with better interpolation?
<p>First of all: what am I trying to do?</p> <p>I have an application to view images. It uses the canvas element to render the image. You can zoom in, you can zoom out, and you can drag it around. This part works perfectly right now.</p> <p>But let's say I have an image with a lot of text. It has a resolution of 1200x1700, and my canvas has 1200x900. Initially, when zoomed out, this leads to a rendered resolution of ~560x800.</p> <p>My actual drawing looks like this:</p> <pre><code>drawImage(src, srcOffsetX, srcOffsetY, sourceViewWidth, sourceViewHeight, destOffsetX, destOffsetY, destWidth, destHeight); </code></pre> <p>Small text on this image looks really, really bad, especially when compared to other image viewers (e.g. IrfanView), or even the html &lt; img > element.</p> <p>I figured out that the browsers interpolation algorithm is the cause of this problem. Comparing different browsers showed that Chrome renders scaled images the best, but still not good enough.</p> <p>Well I searched in every corner of the Interwebs for 4-5 hours straight and did not find what I need. I found the "imageSmoothingEnabled" option, "image-rendering" CSS styles which you can not use on canvas, rendering at float positions and many JavaScript implementations of interpolation algorithms (those are <strong>far</strong> to slow for my purpose).</p> <p>You may ask why I am telling you all of this: to save you the time to give me answers I already know</p> <p>So: is there <strong>any</strong> good and fast way to have better interpolation? My current idea is to create an image object, resize this (because img has good interpolation when scaled!) and render it then. Unfortunately, applying img.width seems only to affect the displayed width...</p> <p><strong>Update</strong>: Thanks to Simon, I could solve my problem. Here is the dynamic scaling algorithm I used. Notice that it keeps the aspect ratio, the height parameter is only for avoiding more float computing. It only scales down right now.</p> <pre><code>scale(destWidth, destHeight){ var start = new Date().getTime(); var scalingSteps = 0; var ctx = this._sourceImageCanvasContext; var curWidth = this._sourceImageWidth; var curHeight = this._sourceImageHeight; var lastWidth = this._sourceImageWidth; var lastHeight = this._sourceImageHeight; var end = false; var scale=0.75; while(end==false){ scalingSteps +=1; curWidth *= scale; curHeight *= scale; if(curWidth &lt; destWidth){ curWidth = destWidth; curHeight = destHeight; end=true; } ctx.drawImage(this._sourceImageCanvas, 0, 0, Math.round(lastWidth), Math.round(lastHeight), 0, 0, Math.round(curWidth), Math.round(curHeight)); lastWidth = curWidth; lastHeight = curHeight; } var endTime =new Date().getTime(); console.log("execution time: "+ ( endTime - start) + "ms. scale per frame: "+scale+ " scaling step count: "+scalingSteps); } </code></pre>
18,765,964
1
6
null
2013-09-12 10:11:31.557 UTC
19
2019-02-03 02:24:02.797 UTC
2019-02-03 02:24:02.797 UTC
null
4,298,200
null
2,772,067
null
1
43
javascript|html|canvas|scaling|interpolation
52,140
<p>You need to "step down" several times. Instead of scaling from a very large image to a very small, you need to re-scale it to intermediary sizes.</p> <p>Consider an image you want to draw at 1/6 scale. You could do this:</p> <pre><code>var w = 1280; var h = 853; ctx.drawImage(img, 0, 0, w/6, h/6); </code></pre> <p>Or you could draw it to an in-memory canvas at 1/2 scale, then 1/2 scale again, then 1/2 scale again. The result is a 1/6 scale image, but we use three steps:</p> <pre><code>var can2 = document.createElement('canvas'); can2.width = w/2; can2.height = w/2; var ctx2 = can2.getContext('2d'); ctx2.drawImage(img, 0, 0, w/2, h/2); ctx2.drawImage(can2, 0, 0, w/2, h/2, 0, 0, w/4, h/4); ctx2.drawImage(can2, 0, 0, w/4, h/4, 0, 0, w/6, h/6); </code></pre> <p>Then you can draw that back to your original context:</p> <pre><code>ctx.drawImage(can2, 0, 0, w/6, h/6, 0, 200, w/6, h/6); </code></pre> <p>You can see the difference live, here:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var can = document.getElementById('canvas1'); var ctx = can.getContext('2d'); var img = new Image(); var w = 1280; var h = 853; img.onload = function() { // step it down only once to 1/6 size: ctx.drawImage(img, 0, 0, w/6, h/6); // Step it down several times var can2 = document.createElement('canvas'); can2.width = w/2; can2.height = w/2; var ctx2 = can2.getContext('2d'); // Draw it at 1/2 size 3 times (step down three times) ctx2.drawImage(img, 0, 0, w/2, h/2); ctx2.drawImage(can2, 0, 0, w/2, h/2, 0, 0, w/4, h/4); ctx2.drawImage(can2, 0, 0, w/4, h/4, 0, 0, w/6, h/6); ctx.drawImage(can2, 0, 0, w/6, h/6, 0, 200, w/6, h/6); } img.src = 'http://upload.wikimedia.org/wikipedia/commons/thumb/a/a4/Equus_quagga_%28Namutoni%2C_2012%29.jpg/1280px-Equus_quagga_%28Namutoni%2C_2012%29.jpg'</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>canvas { border: 1px solid gray; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;canvas id="canvas1" width="400" height="400"&gt;&lt;/canvas&gt;</code></pre> </div> </div> </p> <p><a href="http://jsfiddle.net/qwDDP/" rel="noreferrer">View same snippet on jsfiddle.</a></p>
19,246,103
socket.error:[errno 99] cannot assign requested address and namespace in python
<p>My server software says <code>errno99: cannot assign requested address</code> while using an ip address other than <code>127.0.0.1</code> for binding.</p> <p>But if the IP address is <code>127.0.0.1</code> it works. Is it related to namespaces?</p> <p>I am executing my server and client codes in another python program by calling <code>execfile()</code>. I am actually editing the mininet source code.I edited net.py and inside that I used execfile('server.py') execfile('client1.py') and execfile('client2.py').So as soon as "sudo mn --topo single,3" is called along with the creation of 3 hosts my server and client codes will get executed.I have given my server and client codes below.</p> <pre><code>#server code import select import socket import sys backlog = 5 size = 1024 server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind(("10.0.0.1",9999)) server.listen(backlog) input = [server] running = 1 while running: inputready,outputready,exceptready = select.select(input,[],[]) for s in inputready: if s == server: client, address = server.accept() input.append(client) else: l = s.recv(1024) sys.stdout.write(l) server.close() </code></pre> <p><br></p> <pre><code>#client code import socket import select import sys import time while(1) : s,addr=server1.accept() data=int(s.recv(4)) s = socket.socket() s.connect(("10.0.0.1",9999)) while (1): f=open ("hello1.txt", "rb") l = f.read(1024) s.send(l) l = f.read(1024) time.sleep(5) s.close() </code></pre>
19,267,994
5
7
null
2013-10-08 11:07:45.34 UTC
26
2022-02-07 15:03:32.307 UTC
2013-10-09 09:03:50.177 UTC
null
929,999
null
2,833,462
null
1
68
python|sockets|namespaces|ip
349,309
<p>Stripping things down to basics this is what you would want to test with:</p> <pre><code>import socket server = socket.socket() server.bind((&quot;10.0.0.1&quot;, 6677)) server.listen(4) client_socket, client_address = server.accept() print(client_address, &quot;has connected&quot;) while True: recvieved_data = client_socket.recv(1024) print(recvieved_data) </code></pre> <p>This works assuming a few things:</p> <ol> <li>Your local IP address (on the server) is 10.0.0.1 (<a href="http://www.youtube.com/watch?v=1H82rLX1MM4#t=0m40s" rel="noreferrer">This video shows you how</a>)</li> <li>No other software is listening on port 6677</li> </ol> <h2>Also note the basic concept of IP addresses:</h2> <p>Try the following, open the start menu, in the &quot;search&quot; field type <code>cmd</code> and press enter. Once the black console opens up type <code>ping www.google.com</code> and this should give you and IP address for google. This address is googles local IP and they bind to that and obviously you can <strong>not</strong> bind to an IP address owned by google.</p> <p>With that in mind, you own your own set of IP addresses. First you have the local IP of the server, but then you have the local IP of your house. In the below picture <code>192.168.1.50</code> is the local IP of the server which you can bind to. You still own <code>83.55.102.40</code> but the problem is that it's owned by the Router and not your server. So even if you visit <a href="http://whatsmyip.com" rel="noreferrer">http://whatsmyip.com</a> and that tells you that your IP is <code>83.55.102.40</code> that is not the case because it can only see where you're coming from.. and you're accessing your internet from a router.</p> <p><img src="https://i.stack.imgur.com/kKDbC.png" alt="enter image description here" /></p> <p>In order for your friends to access your server (which is bound to <code>192.168.1.50</code>) you need to forward port <code>6677</code> to <code>192.168.1.50</code> and this is done in your router. Assuming you are behind one.</p> <p>If you're in school there's other dilemmas and routers in the way most likely.</p>
24,060,498
org.hibernate.exception.SQLGrammarException: could not prepare statement
<p>I have created two entities and am trying to fill one with data after loading it, to show it as a drop down list.</p> <p>I got the error</p> <blockquote> <p>org.hibernate.exception.SQLGrammarException: could not prepare statement</p> </blockquote> <p>The <code>Group</code> entity that must be in the drop down list is:</p> <pre><code>@Entity @Table(name="GROUP") public class Group implements Serializable,Lifecycle{ /** * */ private static final long serialVersionUID = 5551707547269388327L; @Id @Column(name="ID") @GeneratedValue private int id; @Column(name="E_NAME") private String eName; @Column(name="A_NAME") private String aName; public int getId() { return id; } public void setId(int id) { this.id = id; } public String geteName() { return eName; } public void seteName(String eName) { this.eName = eName; } public String getaName() { return aName; } public void setaName(String aName) { this.aName = aName; } @Override public boolean onDelete(Session arg0) throws CallbackException { // TODO Auto-generated method stub return false; } @Override public void onLoad(Session session, Serializable arg1) { // TODO Auto-generated method stub Group adminGroup =new Group(); Group sectionAdminGroup =new Group(); Group userGroup =new Group(); adminGroup.seteName("Admin"); sectionAdminGroup.seteName("Section Admin"); userGroup.seteName("User"); adminGroup.setaName("مسشرف عام"); sectionAdminGroup.setaName("مشرف قطاع"); userGroup.setaName("مستخدم"); session.save(adminGroup); session.save(sectionAdminGroup); session.save(userGroup); } @Override public boolean onSave(Session arg0) throws CallbackException { // TODO Auto-generated method stub return false; } @Override public boolean onUpdate(Session arg0) throws CallbackException { // TODO Auto-generated method stub return false; } } </code></pre> <p>The stack trace is:</p> <blockquote> <p>Caused by:</p> <p>org.hibernate.exception.SQLGrammarException: could not prepare statement at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:123) at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49) at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126) at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:196) at org.hibernate.engine.jdbc.internal.StatementPreparerImpl.prepareQueryStatement(StatementPreparerImpl.java:160) at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1884) at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1861) at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1838) at org.hibernate.loader.Loader.doQuery(Loader.java:909) at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:354) at org.hibernate.loader.Loader.doList(Loader.java:2551) at org.hibernate.loader.Loader.doList(Loader.java:2537) at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2367) at org.hibernate.loader.Loader.list(Loader.java:2362) at org.hibernate.loader.criteria.CriteriaLoader.list(CriteriaLoader.java:126) at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1678) at org.hibernate.internal.CriteriaImpl.list(CriteriaImpl.java:380) at org.gaca.gms.dao.GenericDAOImpl.getAll(GenericDAOImpl.java:56) at org.gaca.gms.services.GenericServiceImpl.getAllObjects(GenericServiceImpl.java:61) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:483) at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317) at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98) at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207) at com.sun.proxy.$Proxy39.getAllObjects(Unknown Source) at org.gaca.gms.controllers.UsersController.listUsers(UsersController.java:43) at org.gaca.gms.controllers.UsersController$$FastClassBySpringCGLIB$$29260f80.invoke() at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:708) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98) at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:644) at org.gaca.gms.controllers.UsersController$$EnhancerBySpringCGLIB$$de07b585.listUsers() at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:483) at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852) at javax.servlet.http.HttpServlet.service(HttpServlet.java:707) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837) at javax.servlet.http.HttpServlet.service(HttpServlet.java:820) at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:487) at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:362) at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216) at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:181) at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:726) at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:405) at org.mortbay.jetty.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:206) at org.mortbay.jetty.handler.HandlerCollection.handle(HandlerCollection.java:114) at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152) at org.mortbay.jetty.Server.handle(Server.java:324) at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:505) at org.mortbay.jetty.HttpConnection$RequestHandler.headerComplete(HttpConnection.java:829) at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:514) at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:211) at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:380) at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:395) at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:488) Caused by: org.h2.jdbc.JdbcSQLException: Syntax error in SQL statement "SELECT THIS_.ID AS ID1_0_0_, THIS_.A_NAME AS A_NAME2_0_0_, THIS_.E_NAME AS E_NAME3_0_0_ FROM GROUP[*] THIS_ "; expected "identifier"; SQL statement: select this_.ID as ID1_0_0_, this_.A_NAME as A_NAME2_0_0_, this_.E_NAME as E_NAME3_0_0_ from GROUP this_ [42001-178] at org.h2.message.DbException.getJdbcSQLException(DbException.java:344) at org.h2.message.DbException.getSyntaxError(DbException.java:204) at org.h2.command.Parser.readIdentifierWithSchema(Parser.java:3024) at org.h2.command.Parser.readTableFilter(Parser.java:1185) at org.h2.command.Parser.parseSelectSimpleFromPart(Parser.java:1859) at org.h2.command.Parser.parseSelectSimple(Parser.java:1968) at org.h2.command.Parser.parseSelectSub(Parser.java:1853) at org.h2.command.Parser.parseSelectUnion(Parser.java:1674) at org.h2.command.Parser.parseSelect(Parser.java:1662) at org.h2.command.Parser.parsePrepared(Parser.java:434) at org.h2.command.Parser.parse(Parser.java:306) at org.h2.command.Parser.parse(Parser.java:278) at org.h2.command.Parser.prepareCommand(Parser.java:243) at org.h2.engine.Session.prepareLocal(Session.java:442) at org.h2.engine.Session.prepareCommand(Session.java:384) at org.h2.jdbc.JdbcConnection.prepareCommand(JdbcConnection.java:1188) at org.h2.jdbc.JdbcPreparedStatement.(JdbcPreparedStatement.java:73) at org.h2.jdbc.JdbcConnection.prepareStatement(JdbcConnection.java:276) at org.apache.commons.dbcp.DelegatingConnection.prepareStatement(DelegatingConnection.java:281) at org.apache.commons.dbcp.PoolingDataSource$PoolGuardConnectionWrapper.prepareStatement(PoolingDataSource.java:313) at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$5.doPrepare(StatementPreparerImpl.java:162) at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:186) ... 73 more</p> <p>Caused by:</p> <p>org.h2.jdbc.JdbcSQLException: Syntax error in SQL statement "SELECT THIS_.ID AS ID1_0_0_, THIS_.A_NAME AS A_NAME2_0_0_, THIS_.E_NAME AS E_NAME3_0_0_ FROM GROUP[*] THIS_ "; expected "identifier"; SQL statement: select this_.ID as ID1_0_0_, this_.A_NAME as A_NAME2_0_0_, this_.E_NAME as E_NAME3_0_0_ from GROUP this_ [42001-178] at org.h2.message.DbException.getJdbcSQLException(DbException.java:344) at org.h2.message.DbException.getSyntaxError(DbException.java:204) at org.h2.command.Parser.readIdentifierWithSchema(Parser.java:3024) at org.h2.command.Parser.readTableFilter(Parser.java:1185) at org.h2.command.Parser.parseSelectSimpleFromPart(Parser.java:1859) at org.h2.command.Parser.parseSelectSimple(Parser.java:1968) at org.h2.command.Parser.parseSelectSub(Parser.java:1853) at org.h2.command.Parser.parseSelectUnion(Parser.java:1674) at org.h2.command.Parser.parseSelect(Parser.java:1662) at org.h2.command.Parser.parsePrepared(Parser.java:434) at org.h2.command.Parser.parse(Parser.java:306) at org.h2.command.Parser.parse(Parser.java:278) at org.h2.command.Parser.prepareCommand(Parser.java:243) at org.h2.engine.Session.prepareLocal(Session.java:442) at org.h2.engine.Session.prepareCommand(Session.java:384) at org.h2.jdbc.JdbcConnection.prepareCommand(JdbcConnection.java:1188) at org.h2.jdbc.JdbcPreparedStatement.(JdbcPreparedStatement.java:73) at org.h2.jdbc.JdbcConnection.prepareStatement(JdbcConnection.java:276) at org.apache.commons.dbcp.DelegatingConnection.prepareStatement(DelegatingConnection.java:281) at org.apache.commons.dbcp.PoolingDataSource$PoolGuardConnectionWrapper.prepareStatement(PoolingDataSource.java:313) at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$5.doPrepare(StatementPreparerImpl.java:162) at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:186) at org.hibernate.engine.jdbc.internal.StatementPreparerImpl.prepareQueryStatement(StatementPreparerImpl.java:160) at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1884) at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1861) at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1838) at org.hibernate.loader.Loader.doQuery(Loader.java:909) at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:354) at org.hibernate.loader.Loader.doList(Loader.java:2551) at org.hibernate.loader.Loader.doList(Loader.java:2537) at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2367) at org.hibernate.loader.Loader.list(Loader.java:2362) at org.hibernate.loader.criteria.CriteriaLoader.list(CriteriaLoader.java:126) at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1678) at org.hibernate.internal.CriteriaImpl.list(CriteriaImpl.java:380) at org.gaca.gms.dao.GenericDAOImpl.getAll(GenericDAOImpl.java:56) at org.gaca.gms.services.GenericServiceImpl.getAllObjects(GenericServiceImpl.java:61) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:483) at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317) at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98) at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207) at com.sun.proxy.$Proxy39.getAllObjects(Unknown Source) at org.gaca.gms.controllers.UsersController.listUsers(UsersController.java:43) at org.gaca.gms.controllers.UsersController$$FastClassBySpringCGLIB$$29260f80.invoke() at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:708) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98) at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:644) at org.gaca.gms.controllers.UsersController$$EnhancerBySpringCGLIB$$de07b585.listUsers() at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:483) at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852) at javax.servlet.http.HttpServlet.service(HttpServlet.java:707) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837) at javax.servlet.http.HttpServlet.service(HttpServlet.java:820) at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:487) at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:362) at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216) at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:181) at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:726) at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:405) at org.mortbay.jetty.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:206) at org.mortbay.jetty.handler.HandlerCollection.handle(HandlerCollection.java:114) at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152) at org.mortbay.jetty.Server.handle(Server.java:324) at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:505) at org.mortbay.jetty.HttpConnection$RequestHandler.headerComplete(HttpConnection.java:829) at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:514) at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:211) at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:380) at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:395) at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:488)</p> </blockquote> <p>This is my Spring controller:</p> <pre><code>@SuppressWarnings("unchecked") @RequestMapping(method=RequestMethod.GET) public String listUsers(Map&lt;String, Object&gt; map) { map.put("user", new User()); map.put("usersList", usersService.getAllObjects(User.class)); map.put("groupsList", usersService.getAllObjects(Group.class)); return "index"; } </code></pre> <p>This is my JSP page:</p> <pre><code>&lt;tr&gt; &lt;td&gt;groups&lt;/td&gt; &lt;td&gt;&lt;form:select path="selectedGroup"&gt; &lt;form:options items="${groupsList}"/&gt; &lt;/form:select&gt;&lt;/td&gt; &lt;/tr&gt; </code></pre> <p>I am new to this. Can anybody help?</p>
24,060,905
9
4
null
2014-06-05 12:40:26 UTC
null
2022-04-14 13:56:04.937 UTC
2018-08-29 23:11:54.773 UTC
null
9,238,547
null
3,706,420
null
1
11
java|hibernate|jpa
107,979
<p>The table name you used, <code>GROUP</code>, is a reserved keyword for h2 databases. Rename your table with a name like <code>ADMIN_GROUP</code>.</p> <p>Here's an extract from <a href="http://www.h2database.com/html/advanced.html#compatibility" rel="noreferrer">the h2 documentation</a>:</p> <blockquote> <p>Keywords / Reserved Words</p> <p>There is a list of keywords that can't be used as identifiers (table names, column names and so on), unless they are quoted (surrounded with double quotes). The list is currently:</p> <p><code>CROSS, CURRENT_DATE, CURRENT_TIME, CURRENT_TIMESTAMP, DISTINCT, EXCEPT, EXISTS, FALSE, FOR, FROM, FULL, GROUP, HAVING, INNER, INTERSECT, IS, JOIN, LIKE, LIMIT, MINUS, NATURAL, NOT, NULL, ON, ORDER, PRIMARY, ROWNUM, SELECT, SYSDATE, SYSTIME, SYSTIMESTAMP, TODAY, TRUE, UNION, UNIQUE, WHERE</code></p> <p>Certain words of this list are keywords because they are functions that can be used without '()' for compatibility, for example <code>CURRENT_TIMESTAMP</code>.</p> </blockquote>
19,121,367
UITextViews in a UITableView link detection bug in iOS 7
<p>I have custom UITableViewCells that contain a UITextView. I have link detection in the UITextView turned on in Interface Builder. When I first load the table view, everything seems to be working, but as I scroll up and down the table view, the link detection gets messed up. Specifically, cells that just have regular text (which are presented normally initially) are being shown as links (all the text in the text view is coloured blue and is an active link), and the links point to objects that are in some of the other table view cells. For example a link might point to a website that was in a different table view cell, or launch an email to an address that was in a different table view cell.</p> <p>It seems like when the table view cells are being reused, even though the text view text is being updated, the links are somehow getting saved.</p> <p>This only happens in iOS 7, not iOS 6. It happens in the simulator and on my device.</p> <p>Here is the code:</p> <pre><code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { NSString *sectionKey = [self.orderedSectionKeys objectAtIndex:indexPath.section]; NSDictionary *infoDictionary = [[self.tableViewData objectForKey:sectionKey] objectAtIndex:indexPath.row]; static NSString *cellIdentifier = @"InfoDefaultTableViewCell"; InfoDefaultTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; if (cell == nil) { NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"InfoTableViewCells" owner:self options:nil]; cell = [topLevelObjects objectAtIndex:0]; } cell.bodyTextView.text = [infoDictionary objectForKey:@"description"]; return cell; } </code></pre> <p>Does anyone know what is happening here, and how to solve it?</p> <hr> <p>I tried adding this code after setting the text view text, to try to reset the links:</p> <pre><code>cell.bodyTextView.dataDetectorTypes = UIDataDetectorTypeNone; cell.bodyTextView.dataDetectorTypes = UIDataDetectorTypeAddress | UIDataDetectorTypeLink | UIDataDetectorTypePhoneNumber; </code></pre> <p>but it didn't change the behaviour that I'm seeing.</p>
19,128,056
13
10
null
2013-10-01 16:28:25.927 UTC
9
2015-12-12 14:58:43.217 UTC
2013-10-02 00:08:11.063 UTC
null
472,344
null
472,344
null
1
46
ios|uitableview|uitextview|ios7
14,682
<p>This appears to be a bug in iOS 7.0's <code>UITextView</code>s. A <a href="https://stackoverflow.com/a/18968687/774">similar question</a> has a workaround which seems to help: set the text view's text to <code>nil</code> before setting it to the new text string.</p>
8,973,529
Retrieve an object from entityframework without ONE field
<p>I'm using entity framework to connect with the database. I've one little problem:</p> <p>I've one table which have one varbinary(MAX) column(with filestream).</p> <p>I'm using SQL request to manage the "Data" part, but EF for the rest(metadata of the file).</p> <p>I've one code which has to get all files id, filename, guid, modification date, ... of a file. This doesn't need at all the "Data" field.</p> <p>Is there a way to retrieve a List but without this column filled?</p> <p>Something like</p> <pre><code>context.Files.Where(f=&gt;f.xyz).Exclude(f=&gt;f.Data).ToList(); </code></pre> <p>??</p> <p>I know I can create anonymous objects, but I need to transmit the result to a method, so no anonymous methods. And I don't want to put this in a list of anonymous type, and then create a list of my non-anonymous type(File).</p> <p>The goal is to avoid this:</p> <pre><code>using(RsSolutionsEntities context = new RsSolutionsEntities()) { var file = context.Files .Where(f =&gt; f.Id == idFile) .Select(f =&gt; new { f.Id, f.MimeType, f.Size, f.FileName, f.DataType, f.DateModification, f.FileId }).FirstOrDefault(); return new File() { DataType = file.DataType, DateModification = file.DateModification, FileId = file.FileId, FileName = file.FileName, Id = file.Id, MimeType = file.MimeType, Size = file.Size }; } </code></pre> <p>(I'm using here the anonymous type because otherwise you will get a NotSupportedException: The entity or complex type 'ProjectName.File' cannot be constructed in a LINQ to Entities query.)</p> <p>(e.g. this code throw the previous exception:</p> <pre><code>File file2 = context.Files.Where(f =&gt; f.Id == idFile) .Select(f =&gt; new File() {Id = f.Id, DataType = f.DataType}).FirstOrDefault(); </code></pre> <p>and "File" is the type I get with a <code>context.Files.ToList()</code>. This is the good class: </p> <pre><code>using File = MyProjectNamespace.Common.Data.DataModel.File; </code></pre> <p>File is a known class of my EF datacontext:</p> <pre><code>public ObjectSet&lt;File&gt; Files { get { return _files ?? (_files = CreateObjectSet&lt;File&gt;("Files")); } } private ObjectSet&lt;File&gt; _files; </code></pre>
8,975,420
9
9
null
2012-01-23 14:52:57.907 UTC
11
2021-07-13 01:31:25.84 UTC
2012-01-23 18:51:27.353 UTC
null
100,283
null
397,830
null
1
67
c#|.net|sql|entity-framework
59,350
<blockquote> <p>Is there a way to retrieve a List but without this column filled?</p> </blockquote> <p>Not without projection which you want to avoid. If the column is mapped it is natural part of your entity. Entity without this column is not complete - it is different data set = projection. </p> <blockquote> <p>I'm using here the anonymous type because otherwise you will get a NotSupportedException: The entity or complex type 'ProjectName.File' cannot be constructed in a LINQ to Entities query.</p> </blockquote> <p>As exception says you cannot project to mapped entity. I mentioned reason above - projection make different data set and EF don't like "partial entities". </p> <blockquote> <p>Error 16 Error 3023: Problem in mapping fragments starting at line 2717:Column Files.Data in table Files must be mapped: It has no default value and is not nullable.</p> </blockquote> <p>It is not enough to delete property from designer. You must open EDMX as XML and delete column from SSDL as well which will make your model very fragile (each update from database will put your column back). If you don't want to map the column you should use database view without the column and map the view instead of the table but you will not be able to insert data.</p> <p>As a workaround to all your problems use <a href="https://docs.microsoft.com/en-us/ef/core/modeling/table-splitting" rel="nofollow noreferrer">table splitting</a> and separate the problematic binary column to another entity with 1 : 1 relation to your main <code>File</code> entity.</p>
8,798,707
Securing communication [Authenticity, Privacy & Integrity] with mobile app?
<p>An Android/Iphone app will be accessing application data from the server. [Django-Python]</p> <p>How can I secure the communication with the mobile app ?</p> <p><strong>Expectation</strong> : Secure enough for sensitive information like passwords, there shall be no direct way of decryption except brute-forcing.</p> <p><strong>My requirements</strong> :</p> <ul> <li>Authentication [Only the app is authorized]</li> <li>Integrity [Messages should not be modified in between]</li> <li>Privacy [Communication should not be readable if sniffed]</li> </ul> <p><strong>My effort</strong>:</p> <ul> <li>SSL authenticates only the Server, not the client.</li> <li>I can-not use a symmetric encryption [Provides only Privacy]</li> <li>Digital signature is not possible [Lacks Privacy]</li> <li>PGP full-fills all 3 requirements.</li> </ul> <p><strong>Problem</strong> :</p> <ul> <li>PGP requires to store keys on client app.</li> <li>There seems to be no assuring way of securing keys on client app.</li> <li><strong>If the key is out, then PGP or Symmetric encryption are equally vulnerable.</strong></li> <li>Reverse-Engineering PGP keys or symmetic keys is equally hard.</li> <li><strong>In that case PGP is a non-sense burden on the mobile processor.</strong></li> <li><strong>OAuth is again useless, since it also have a client key.</strong></li> </ul> <p>So, how can/should I move forward on this ? <strong>How does the industry deals with this ?</strong></p> <p>Should I implement casual approach :</p> <ul> <li><strong>Use simple SSL and cross my fingers ?</strong>, since authentication is not possible if the keys are stolen? (Only server authentication is possible with this)</li> </ul> <p><strong>Update:</strong></p> <p>Conclusion was to use AES, since if I can keep the key secure then I am as good as SSL. Plus I can keep changing the key over-time for better security. Contribute if you think there is a better way, do read the entire post before posting.</p>
8,803,983
3
15
null
2012-01-10 04:51:26.983 UTC
16
2014-01-17 03:09:32.557 UTC
2012-02-10 06:05:26.397 UTC
null
731,963
null
731,963
null
1
34
android|iphone|python|django|security
6,980
<p>You're working on bad information. SSL can absolutely authenticate the client, it's just not something that is done for the bulk of SSL as the protocol is (or, atleast was) typically used to protect e-commerce sites where authentication of the server was important but doing so with the client was not important and/or not feasible. What you want to do is employ mutually-authenticated SSL, so that your server will only accept incoming connections from your app and your app will only communicate with your server.</p> <p>Here's the high-level approach. Create a self-signed server SSL certificate and deploy on your web server. If you're using Android, you can use the keytool included with the Android SDK for this purpose; if you're using another app platform like iOS, similar tools exist for them as well. Then create a self-signed client and deploy that within your application in a custom keystore included in your application as a resource (keytool will generate this as well). Configure the server to require client-side SSL authentication and to only accept the client certificate you generated. Configure the client to use that client-side certificate to identify itself and only accept the one server-side certificate you installed on your server for that part of it.</p> <p>If someone/something other than your app attempts to connect to your server, the SSL connection will not be created, as the server will reject incoming SSL connections that do not present the client certificate that you have included in your app.</p> <p>A step-by-step for this is a much longer answer than is warranted here. I would suggest doing this in stages as there are resources on the web about how to deal with self-signed SSL certificate in both Android and iOS, both server and client side. There is also a complete walk-through in my book, <a href="http://shop.oreilly.com/product/0636920022596.do" rel="noreferrer">Application Security for the Android Platform</a>, published by O'Reilly.</p>
22,450,036
Refreshing OAuth token using Retrofit without modifying all calls
<p>We are using Retrofit in our Android app, to communicate with an OAuth2 secured server. Everything works great, we use the RequestInterceptor to include the access token with each call. However there will be times, when the access token will expire, and the token needs to be refreshed. When the token expires, the next call will return with an Unauthorized HTTP code, so that's easy to monitor. We could modify each Retrofit call the following way: In the failure callback, check for the error code, if it equals Unauthorized, refresh the OAuth token, then repeat the Retrofit call. However, for this, all calls should be modified, which is not an easily maintainable, and good solution. Is there a way to do this without modifying all Retrofit calls?</p>
31,624,433
10
14
null
2014-03-17 08:52:00.873 UTC
138
2021-09-08 18:17:54.773 UTC
2014-03-17 10:19:18.17 UTC
null
1,395,437
null
1,395,437
null
1
203
android|oauth-2.0|retrofit
100,140
<p>Please do not use <code>Interceptors</code> to deal with authentication.</p> <p>Currently, the best approach to handle authentication is to use the new <a href="https://square.github.io/okhttp/3.x/okhttp/okhttp3/Authenticator.html" rel="noreferrer"><code>Authenticator</code></a> API, designed specifically for <a href="https://github.com/square/okhttp/wiki/Recipes#handling-authentication" rel="noreferrer">this purpose</a>.</p> <p>OkHttp will <strong>automatically ask</strong> the <code>Authenticator</code> for credentials when a response is <code>401 Not Authorised</code> <strong>retrying last failed request</strong> with them.</p> <pre><code>public class TokenAuthenticator implements Authenticator { @Override public Request authenticate(Proxy proxy, Response response) throws IOException { // Refresh your access_token using a synchronous api request newAccessToken = service.refreshToken(); // Add new header to rejected request and retry it return response.request().newBuilder() .header(AUTHORIZATION, newAccessToken) .build(); } @Override public Request authenticateProxy(Proxy proxy, Response response) throws IOException { // Null indicates no attempt to authenticate. return null; } </code></pre> <p>Attach an <code>Authenticator</code> to an <code>OkHttpClient</code> the same way you do with <code>Interceptors</code></p> <pre><code>OkHttpClient okHttpClient = new OkHttpClient(); okHttpClient.setAuthenticator(authAuthenticator); </code></pre> <p>Use this client when creating your <code>Retrofit</code> <code>RestAdapter</code></p> <pre><code>RestAdapter restAdapter = new RestAdapter.Builder() .setEndpoint(ENDPOINT) .setClient(new OkClient(okHttpClient)) .build(); return restAdapter.create(API.class); </code></pre>
11,352,301
How to use DoEvents() without being "evil"?
<p>A simple <a href="http://www.google.com/search?q=doevents">search for <code>DoEvents</code></a> brings up lots of results that lead, basically, to:</p> <blockquote> <p><code>DoEvents</code> is evil. Don't use it. Use threading instead.</p> </blockquote> <p>The reasons generally cited are:</p> <ul> <li>Re-entrancy issues </li> <li>Poor performance</li> <li>Usability issues (e.g. drag/drop over a disabled window)</li> </ul> <p>But some notable Win32 functions such as <code>TrackPopupMenu</code> and <code>DoDragDrop</code> <em>perform their own message processing</em> to keep the UI responsive, just like <code>DoEvents</code> does.<br> And yet, none of these seem to come across these issues (performance, re-entrancy, etc.).</p> <p>How do they do it? How do they avoid the problems cited with <code>DoEvents</code>? (Or <em>do</em> they?)</p>
11,352,575
3
1
null
2012-07-05 20:45:29.643 UTC
17
2019-09-17 21:21:11.353 UTC
null
null
null
null
541,686
null
1
25
windows|winforms|winapi|visual-c++|doevents
9,659
<p>DoEvents() is <em>dangerous</em>. But I bet you do lots of dangerous things every day. Just yesterday I set off a few explosive devices (future readers: note the original post date relative to a certain American holiday). With care, we can sometimes account for the dangers. Of course, that means knowing and understanding what the dangers are:</p> <ul> <li><p><strong>Re-entry issues.</strong> There are actually two dangers here:</p> <ol> <li>Part of the problem here has to do with the call stack. If you call .DoEvents() in a loop that itself handles messages that use DoEvents(), and so on, you're getting a pretty deep call stack. <em>It's easy to over-use DoEvents() and accidentally fill up your call stack</em>, resulting in a StackOverflow exception. If you're only using .DoEvents() in one or two places, you're probably okay. If it's the first tool you reach for whenever you have a long-running process, you can easily find yourself in trouble here. Even one use in the wrong place can make it possible for a user to <em>force</em> a stackoverflow exception (sometimes just by holding down the enter key), and that can be a security issue.</li> <li>It is sometimes possible to find your same method on the call stack twice. If you didn't build the method with this in mind (hint: you probably didn't) then bad things can happen. If everything passed in to the method is a value type, and there is no dependance on things outside of the method, you might be fine. But otherwise, you need to think carefully about what happens if your entire method were to run again before control is returned to you at the point where .DoEvents() is called. What parameters or resources outside of your method might be modified that you did not expect? Does your method change any objects, where both instances on the stack might be acting on the same object?</li> </ol></li> <li><p><strong>Performance Issues.</strong> DoEvents() can give the <em>illusion</em> of multi-threading, but it's not real mutlithreading. This has at least three real dangers:</p> <ol> <li>When you call DoEvents(), you are giving control on your existing thread back to the message pump. The message pump might in turn give control to something else, and that something else might take a while. The result is that your original operation could take much longer to finish than if it were in a thread by itself that never yields control, definitely longer than it needs. </li> <li>Duplication of work. Since it's possible to find yourself running the same method twice, and we already know this method is expensive/long-running (or you wouldn't need DoEvents() in the first place), even if you accounted for all the external dependencies mentioned above so there are no adverse side effects, you may still end up duplicating a lot of work.</li> <li>The other issue is the extreme version of the first: a potential to deadlock. If something else in your program depends on your process finishing, and will block until it does, and that thing is called by the message pump from DoEvents(), your app will get stuck and become unresponsive. This may sound far-fetched, but in practice it's surprisingly easy to do accidentally, and the crashes are very hard to find and debug later. This is at the root of some of the hung app situations you may have experienced on your own computer.</li> </ol></li> <li><p><strong>Usability Issues.</strong> These are side-effects that result from not properly accounting for the other dangers. There's nothing new here, as long as you looked in other places appropriately.</p></li> </ul> <p><strong><em>If</em></strong> you can be <em>sure</em> you accounted for all these things, then go ahead. But really, if DoEvents() is the first place you look to solve UI responsiveness/updating issues, you're probably not accounting for all of those issues correctly. If it's not the first place you look, there are enough other options that I would question how you made it to considering DoEvents() at all. Today, DoEvents() exists mainly for compatibility with older code that came into being before other credible options where available, and as a crutch for newer programmers who haven't yet gained enough experience for exposure to the other options.</p> <p>The reality is that most of the time, at least in the .Net world, a <strong><a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx" rel="nofollow noreferrer">BackgroundWorker</a></strong> component is nearly as easy, at least once you've done it once or twice, and it will do the job in a safe way. More recently, the <strong>async/await pattern</strong> or the use of a <strong><code>Task</code></strong> can be much more effective and safe, without needing to delve into full-blown multi-threaded code on your own.</p>
10,898,035
How to get node value / innerHTML with XPath?
<p>I have a XPath to select to a class I want: <code>//div[@class='myclass']</code>. But it returns me the whole div (with the <code>&lt;div class='myclass'&gt;</code> also, but I would like to return only the contents of this tag without the tag itself. How can I do it?</p>
10,899,531
4
0
null
2012-06-05 13:16:41.853 UTC
9
2020-06-05 01:38:42.413 UTC
2017-10-06 19:46:47.24 UTC
null
290,085
null
38,940
null
1
40
xml|parsing|xpath|html-parsing
89,301
<p>With xpath, the thing you will get returned is the last thing in the path that is not a condition. What that means? Well, conditions are the stuff between <code>[]</code>'s (but you already knew that) and yours reads like <em>pathElement[<strong>that has a 'class' attribute with value 'my class'</strong>]</em>. The pathElement comes directly before the <code>[</code>.</p> <p>All the stuff outside of <code>[]</code>'s then is the path, so in <code>//a/b/c[@blah='bleh']/d</code> <em>a</em>, <em>b</em>, <em>c</em> and <em>d</em> are all path elements, <em>blah</em> is an attribute and <em>bleh</em> a literal value. If this path matches it will return you a <em>d</em>, the last non-condition thing. </p> <p>Your particular path returns a (series of) <em>div</em>, being the last thing in your xpath's path. This return value thus includes the top-level node(s), <em>div</em> in your case, and underneath it (them) all its (their) children. Nodes can be elements or text (or comments, processing instructions, ...). </p> <p>Underneath a node there can be multiple text nodes, hence the array pOcHa talks about. <code>x/text()</code> returns all text that is a direct child of x, <code>x/node()</code> returns all child nodes, <em>including</em> text.</p>
11,196,367
Processing single file from multiple processes
<p>I have a single big text file in which I want to process each line ( do some operations ) and store them in a database. Since a single simple program is taking too long, I want it to be done via multiple processes or threads. Each thread/process should read the DIFFERENT data(different lines) from that single file and do some operations on their piece of data(lines) and put them in the database so that in the end, I have whole of the data processed and my database is dumped with the data I need.</p> <p>But I am not able to figure it out that how to approach this. </p>
11,196,615
3
1
null
2012-06-25 19:54:19.44 UTC
62
2018-11-27 02:31:35.897 UTC
2018-11-27 02:31:35.897 UTC
null
355,230
null
1,174,984
null
1
86
python|multithreading|multiprocessing
62,725
<p>What you are looking for is a Producer/Consumer pattern</p> <p><strong>Basic threading example</strong></p> <p>Here is a basic example using the <a href="http://docs.python.org/library/threading.html" rel="noreferrer">threading module</a> (instead of multiprocessing)</p> <pre><code>import threading import Queue import sys def do_work(in_queue, out_queue): while True: item = in_queue.get() # process result = item out_queue.put(result) in_queue.task_done() if __name__ == "__main__": work = Queue.Queue() results = Queue.Queue() total = 20 # start for workers for i in xrange(4): t = threading.Thread(target=do_work, args=(work, results)) t.daemon = True t.start() # produce data for i in xrange(total): work.put(i) work.join() # get the results for i in xrange(total): print results.get() sys.exit() </code></pre> <p>You wouldn't share the file object with the threads. You would produce work for them by supplying the <a href="http://docs.python.org/library/queue.html" rel="noreferrer">queue</a> with lines of data. Then each thread would pick up a line, process it, and then return it in the queue. </p> <p>There are some more advanced facilities built into the <a href="http://docs.python.org/library/multiprocessing.html" rel="noreferrer">multiprocessing module</a> to share data, like lists and <a href="http://docs.python.org/library/multiprocessing.html#multiprocessing.Queue" rel="noreferrer">special kind of Queue</a>. There are trade-offs to using multiprocessing vs threads and it depends on whether your work is cpu bound or IO bound. </p> <p><strong>Basic multiprocessing.Pool example</strong></p> <p>Here is a really basic example of a multiprocessing Pool</p> <pre><code>from multiprocessing import Pool def process_line(line): return "FOO: %s" % line if __name__ == "__main__": pool = Pool(4) with open('file.txt') as source_file: # chunk the work into batches of 4 lines at a time results = pool.map(process_line, source_file, 4) print results </code></pre> <p><a href="http://docs.python.org/library/multiprocessing.html#module-multiprocessing.pool" rel="noreferrer">A Pool</a> is a convenience object that manages its own processes. Since an open file can iterate over its lines, you can pass it to the <code>pool.map()</code>, which will loop over it and deliver lines to the worker function. <a href="http://docs.python.org/library/multiprocessing.html#multiprocessing.pool.multiprocessing.Pool.map" rel="noreferrer">Map</a> blocks and returns the entire result when its done. Be aware that this is an overly simplified example, and that the <code>pool.map()</code> is going to read your entire file into memory all at once before dishing out work. If you expect to have large files, keep this in mind. There are more advanced ways to design a producer/consumer setup.</p> <p><strong>Manual "pool" with limit and line re-sorting</strong></p> <p>This is a manual example of the <a href="http://docs.python.org/library/multiprocessing.html#multiprocessing.pool.multiprocessing.Pool.map" rel="noreferrer">Pool.map</a>, but instead of consuming an entire iterable in one go, you can set a queue size so that you are only feeding it piece by piece as fast as it can process. I also added the line numbers so that you can track them and refer to them if you want, later on.</p> <pre><code>from multiprocessing import Process, Manager import time import itertools def do_work(in_queue, out_list): while True: item = in_queue.get() line_no, line = item # exit signal if line == None: return # fake work time.sleep(.5) result = (line_no, line) out_list.append(result) if __name__ == "__main__": num_workers = 4 manager = Manager() results = manager.list() work = manager.Queue(num_workers) # start for workers pool = [] for i in xrange(num_workers): p = Process(target=do_work, args=(work, results)) p.start() pool.append(p) # produce data with open("source.txt") as f: iters = itertools.chain(f, (None,)*num_workers) for num_and_line in enumerate(iters): work.put(num_and_line) for p in pool: p.join() # get the results # example: [(1, "foo"), (10, "bar"), (0, "start")] print sorted(results) </code></pre>
11,420,520
PHP variables in anonymous functions
<p>I was playing around with anonymous functions in PHP and realized that they don't seem to reach variables outside of them. Is there any way to get around this problem?</p> <p>Example:</p> <pre><code>$variable = "nothing"; functionName($someArgument, function() { $variable = "something"; }); echo $variable; //output: "nothing" </code></pre> <p>This will output "nothing". Is there any way that the anonymous function can access the <code>$variable</code>?</p>
11,420,541
2
0
null
2012-07-10 19:30:07.78 UTC
26
2021-09-15 16:43:30.347 UTC
2019-10-01 16:56:13.457 UTC
null
1,255,289
null
1,228,540
null
1
144
php|function|variables|global-variables|anonymous
55,739
<p>Yes, <a href="http://php.net/closure" rel="noreferrer">use a closure</a>:</p> <pre><code>functionName($someArgument, function() use(&amp;$variable) { $variable = "something"; }); </code></pre> <p>Note that in order for you to be able to modify <code>$variable</code> and retrieve the modified value outside of the scope of the anonymous function, it must be referenced in the closure using <code>&amp;</code>.</p>
13,053,660
mysqli_query, mysqli_fetch_array and while loop
<p>I am new to PHP and I am trying to build a website using PHP. I have localhost for testing the result and I have phpmyadmin already installed on the website.</p> <p>What i am trying to do now, is to list the contents of my table "property" from database "portal" and fill a table with the results.</p> <p>I am using <code>mysqli_query</code>, <code>mysqli_fetch_array</code> and while loop. I'm getting the following error:</p> <blockquote> <p>Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in C:\xampp\htdocs\falcon\portal\forms\edit listing.php on line 15</p> </blockquote> <pre><code>session_start(); require_once "connect_to_mysql.php"; // where i store username and password to access my db. $sqlCommand = "SELECT * property FROM portal"; // dbname: portal - table: propery $query = mysqli_query($myConnection, $sqlCommand); $Displayproperty = ''; while ($row = mysqli_fetch_array($query)) $id = $row["pid"]; $title = $row["ptitle"]; $area = $row["parea"]; $city = $row["pcity"]; $Displayproperty .= '&lt;table width="500" border="0" cellspacing="0" cellpadding="1"&gt; &lt;tr&gt; &lt;td&gt;' . $id . '&lt;/td&gt; &lt;td&gt;' . $title . '&lt;/td&gt; &lt;td&gt;' . $area . '&lt;/td&gt; &lt;td&gt;' . $city . '&lt;/td&gt; &lt;td&gt;&lt;a href="forms.php?pid=' . $id . '"&gt;Upload images&lt;/a&gt;&lt;br /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt;'; </code></pre>
13,053,716
6
0
null
2012-10-24 16:38:11.17 UTC
null
2017-04-25 20:55:03.637 UTC
2012-10-24 16:43:20.703 UTC
null
206,403
null
1,771,795
null
1
6
php|mysql
58,562
<p>Replace your query with this. Make sure you have added this line before.</p> <pre><code>$db = mysql_select_db('portal'); $sqlCommand = "SELECT * FROM property"; </code></pre>
13,068,257
Multiprocessing scikit-learn
<p>I got linearsvc working against training set and test set using <code>load_file</code> method i am trying to get It working on Multiprocessor enviorment.</p> <p>How can i get multiprocessing work on <code>LinearSVC().fit()</code> <code>LinearSVC().predict()</code>? I am not really familiar with datatypes of scikit-learn yet.</p> <p>I am also thinking about splitting samples into multiple arrays but i am not familiar with numpy arrays and scikit-learn data structures. </p> <p>Doing this it will be easier to put into multiprocessing.pool() , with that , split samples into chunks , train them and combine trained set back later , would it work ? </p> <p>EDIT: Here is my scenario:</p> <p>lets say , we have 1 million files in training sample set , when we want to distribute processing of Tfidfvectorizer on several processors we have to split those samples (for my case it will only have two categories , so lets say 500000 each samples to train) . My server have 24 cores with 48 GB , so i want to split each topics into number of chunks 1000000 / 24 and process Tfidfvectorizer on them. Like that i would do to Testing sample set , as well as SVC.fit() and decide(). Does it make sense? </p> <p>Thanks. </p> <p>PS: Please do not close this .</p>
13,082,746
2
10
null
2012-10-25 12:10:03.3 UTC
10
2013-12-13 14:55:42.94 UTC
2012-10-26 14:49:32.787 UTC
null
200,044
null
200,044
null
1
10
python|multithreading|numpy|machine-learning|scikit-learn
11,552
<p>I think using SGDClassifier instead of LinearSVC for this kind of data would be a good idea, as it is much faster. For the vectorization, I suggest you look into the <a href="https://github.com/scikit-learn/scikit-learn/pull/909" rel="noreferrer">hash transformer PR</a>.</p> <p>For the multiprocessing: You can distribute the data sets across cores, do <code>partial_fit</code>, get the weight vectors, average them, distribute them to the estimators, do partial fit again.</p> <p>Doing parallel gradient descent is an area of active research, so there is no ready-made solution there.</p> <p>How many classes does your data have btw? For each class, a separate will be trained (automatically). If you have nearly as many classes as cores, it might be better and much easier to just do one class per core, by specifying <code>n_jobs</code> in SGDClassifier.</p>
12,790,297
Hiding button using jQuery
<p>Can someone please tell me how I can hide this button after pressing it using jQuery?</p> <pre><code>&lt;input type="button" name="Comanda" value="Comanda" id="Comanda" data-clicked="unclicked" /&gt; </code></pre> <p>Or this one:</p> <pre><code>&lt;input type=submit name="Vizualizeaza" value="Vizualizeaza"&gt; </code></pre>
12,790,323
4
0
null
2012-10-08 22:21:14.287 UTC
2
2019-05-12 07:37:45.363 UTC
2019-05-12 07:37:45.363 UTC
null
6,296,561
null
1,725,664
null
1
20
javascript|jquery|button
152,395
<p>Try this:</p> <pre><code>$('input[name=Comanda]') .click( function () { $(this).hide(); } ); </code></pre> <p>For doing everything else you can use something like this one:</p> <pre><code>$('input[name=Comanda]') .click( function () { $(this).hide(); $(".ClassNameOfShouldBeHiddenElements").hide(); } ); </code></pre> <p>For hidding any other elements based on their IDs, use this one:</p> <pre><code>$('input[name=Comanda]') .click( function () { $(this).hide(); $("#FirstElement").hide(); $("#SecondElement").hide(); $("#ThirdElement").hide(); } ); </code></pre>
13,044,814
How to register multiple models with the admin?
<p>If I want to register my models with the admin I have to do this like this:</p> <pre><code>#admin.py admin.site.register(models.About) </code></pre> <p>But with multiple models you <strong>can't</strong> do something like this:</p> <pre><code>models = (models.Project, models.Client, models.About) for m in models: admin.site.register(m) </code></pre> <p>First of all: why not!? Secondly: imagine one has a lot of models which all should be accessible from the admin interface. How do you do that in a generic way? </p>
13,044,950
8
1
null
2012-10-24 07:43:24.3 UTC
8
2021-10-11 14:03:29.623 UTC
null
null
null
null
1,105,929
null
1
31
django|django-admin
28,737
<p><code>admin.site.register</code> has this definition in the library: </p> <pre><code>def register(self, model_or_iterable, admin_class=None, **options): </code></pre> <p>so models to be registered can be a single model or iterable object so just use this:</p> <pre><code>myModels = [models.Project, models.Client, models.About] # iterable list admin.site.register(myModels) </code></pre> <p>I tested this in my site and works perfectly fine. </p>
16,610,612
Create HTTPS server with node js
<p>I want to create a https server for my localhost.<br/> Node JS documentation provides out of the box solution but I have some confusion with it. <strong>Example</strong></p> <pre><code>var https = require('https'); var fs = require('fs'); var options = { key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem') }; https.createServer(options, function (req, res) { res.writeHead(200); res.end("hello world\n"); }).listen(8000); </code></pre> <p><strong>Or</strong></p> <pre><code>var options = { pfx: fs.readFileSync('server.pfx') }; </code></pre> <p>Here how would I get key, cert or pfx for my localhost?</p>
16,613,647
3
0
null
2013-05-17 13:43:26.48 UTC
14
2019-05-10 21:56:20.38 UTC
null
null
null
null
1,101,083
null
1
21
node.js|https
14,309
<p>For development purposes you can create a self-certified certificate. Here's how to do it on a linux-based system:</p> <p>First, generate a private key</p> <pre><code>openssl genrsa 1024 &gt; key.pem </code></pre> <p>This will store a 1024 bit RSA key in the file key.pem</p> <p>Then, generate an SSL certificate with that key:</p> <pre><code>openssl req -x509 -new -key key.pem &gt; key-cert.pem </code></pre> <p>Now, you can use key.pem and key-cert.pem in the options you pass to createServer.</p>
17,125,505
What makes a better constant in C, a macro or an enum?
<p>I am confused about when to use macros or enums. Both can be used as constants, but what is the difference between them and what is the advantage of either one? Is it somehow related to compiler level or not?</p>
17,125,538
7
1
null
2013-06-15 16:05:25.413 UTC
17
2022-02-04 17:05:25.463 UTC
2013-06-19 08:47:46.24 UTC
null
648,658
null
2,464,707
null
1
43
c|macros|enums
31,951
<p>In terms of readability, enumerations make better constants than macros, because related values are grouped together. In addition, <code>enum</code> defines a new type, so the readers of your program would have easier time figuring out what can be passed to the corresponding parameter.</p> <p>Compare</p> <pre><code>#define UNKNOWN 0 #define SUNDAY 1 #define MONDAY 2 #define TUESDAY 3 ... #define SATURDAY 7 </code></pre> <p>to</p> <pre><code>typedef enum { UNKNOWN, SUNDAY, MONDAY, TUESDAY, ... SATURDAY, } Weekday; </code></pre> <p>It is much easier to read code like this</p> <pre><code>void calendar_set_weekday(Weekday wd); </code></pre> <p>than this</p> <pre><code>void calendar_set_weekday(int wd); </code></pre> <p>because you know which constants it is OK to pass.</p>
16,800,255
How do we do both left and right folds in Clojure?
<p>Reduce works fine but it is more like fold-left. Is there any other form of reduce that lets me fold to right ?</p>
41,775,034
2
0
null
2013-05-28 11:20:40.177 UTC
17
2017-01-21 02:02:44.53 UTC
null
null
null
Amogh Talpallikar
961,021
null
1
48
clojure
7,112
<p>Let's look at a possible definition of each:</p> <pre><code>(defn foldl [f val coll] (if (empty? coll) val (foldl f (f val (first coll)) (rest coll)))) (defn foldr [f val coll] (if (empty? coll) val (f (foldr f val (rest coll)) (first coll)))) </code></pre> <p>Notice that only <code>foldl</code> is in tail position, and the recursive call can be replaced by <code>recur</code>. So with <code>recur</code>, <code>foldl</code> will not take up stack space, while <code>foldr</code> will. That's why <code>reduce</code> is like <code>foldl</code>. Now let's try them out:</p> <pre><code>(foldl + 0 [1 2 3]) ;6 (foldl - 0 [1 2 3]) ;-6 (foldl conj [] [1 2 3]) ;[1 2 3] (foldl conj '() [1 2 3]) ;(3 2 1) (foldr + 0 [1 2 3]) ;6 (foldr - 0 [1 2 3]) ;-6 (foldr conj [] [1 2 3]) ;[3 2 1] (foldr conj '() [1 2 3]) ;(1 2 3) </code></pre> <p>Is there some reason you want to fold right? I think the most common usage of <code>foldr</code> is to put together a list from front to back. In Clojure we don't need that because we can just use a vector instead. Another choice to avoid stack overflow is to use a lazy sequence:</p> <pre><code>(defn make-list [coll] (lazy-seq (cons (first coll) (rest coll)))) </code></pre> <p>So, if you want to fold right, some efficient alternatives are</p> <ol> <li>Use a vector instead.</li> <li>Use a lazy sequence.</li> <li>Use <code>reduced</code> to short-circuit <code>reduce</code>.</li> <li>If you really want to dive down a rabbit hole, use a transducer.</li> </ol>
16,834,245
C# declare empty string array
<p>I need to declare an empty string array and i'm using this code</p> <pre><code>string[] arr = new String[0](); </code></pre> <p>But I get "method name expected" error.</p> <p>What's wrong?</p>
16,834,388
9
9
null
2013-05-30 10:52:01.303 UTC
15
2021-07-02 14:13:10.737 UTC
2018-05-17 21:26:44.303 UTC
null
2,840,103
null
2,336,575
null
1
192
c#|arrays|string
356,353
<p>Try this</p> <pre><code>string[] arr = new string[] {}; </code></pre>
25,607,216
Why should I prefer the "explicitly typed initializer" idiom over explicitly giving the type
<p>I've recently bought the new Effective modern C++ from Scott Meyers and reading through it now. But I have encountered one thing which totally bugs me.</p> <p>In item 5, Scott says that using <code>auto</code> is a great thing. It saves typing, gives you in most cases the correct type and it might be immune to type mismatches. I totally understand this and think of <code>auto</code> as a good thing too.</p> <p>But then in item 6, Scott says that every coin has two sides. Likewise, there might be cases when <code>auto</code> deduces a totally wrong type, e.g. for proxy objects.</p> <p>You may already know this example:</p> <pre><code>class Widget; std::vector&lt;bool&gt; features(Widget w); Widget w; bool priority = features(w)[5]; // this is fine auto priority = features(w)[5]; // this result in priority being a proxy // to a temporary object, which will result // in undefined behavior on usage after that // line </code></pre> <p>So far, so good.</p> <p>But Scott's solution to this, is the so called "explicitly typed initializer idiom". The idea is, to use static_cast on the initializer like this:</p> <pre><code>auto priority = static_cast&lt;bool&gt;(features(w)[5]); </code></pre> <p>But this not only leads to more typing, but means you also explicitly state the type, which should be deduced. You basically lose both advantages of <code>auto</code> over an explicit given type.</p> <p>Can anyone tell me, why it is advantageous to use this idiom?</p> <hr> <p>First to clear things up, my questions aims to why I should write:</p> <pre><code>auto priority = static_cast&lt;bool&gt;(features(w)[5]); </code></pre> <p>instead of:</p> <pre><code>bool priority = features(w)[5]; </code></pre> <p>@Sergey brought up a link to a nice article on <a href="http://herbsutter.com/2013/08/12/gotw-94-solution-aaa-style-almost-always-auto/" rel="nofollow noreferrer">GotW</a> about this topic, which partly answers my question. </p> <blockquote> <p>Guideline: Consider declaring local variables auto x = type{ expr }; when you do want to explicitly commit to a type. It is self-documenting to show that the code is explicitly requesting a conversion, it guarantees the variable will be initialized, and it won’t allow an accidental implicit narrowing conversion. Only when you do want explicit narrowing, use ( ) instead of { }.</p> </blockquote> <p>Which basically brings me to a related question. Which of these <em>four</em> alternatives should I choose?</p> <pre><code>bool priority = features(w)[5]; auto priority = static_cast&lt;bool&gt;(features(w)[5]); auto priority = bool(features(w)[5]); auto priority = bool{features(w)[5]}; </code></pre> <p>Number one is still my favorite. It's less typing and as explicit as the three other ones. </p> <p>The point about the guaranteed initialization doesn't really hold, as I'm declaring variables anyways not before I can initialize them somehow. And the other argument about the narrowing didn't work out well in <a href="http://ideone.com/GXvIIr" rel="nofollow noreferrer">a quick test</a>.</p>
25,609,753
4
8
null
2014-09-01 13:45:21.677 UTC
6
2020-02-13 09:40:33.23 UTC
2020-02-13 09:40:33.23 UTC
null
12,409,240
null
2,489,745
null
1
44
c++|c++11|effective-c++
2,679
<p>Following the C++ Standard:</p> <blockquote> <h3><strong>§ 8.5 Initializers <code>[dcl.init]</code></strong></h3> <ol start="15"> <li><p>The initialization that occurs in the form</p> <pre><code>T x = a; </code></pre> <p>as well as in argument passing, function return, throwing an exception (15.1), handling an exception (15.3), and aggregate member initialization (8.5.1) is called <em>copy-initialization</em>.</p></li> </ol> </blockquote> <p>I can think of the example given in the book:</p> <pre><code>auto x = features(w)[5]; </code></pre> <p>as the one that represents any form of <em>copy-initialization</em> with auto / template type (<em>deduced type</em> in general), just like:</p> <pre><code>template &lt;typename A&gt; void foo(A x) {} foo(features(w)[5]); </code></pre> <p>as well as:</p> <pre><code>auto bar() { return features(w)[5]; } </code></pre> <p>as well as:</p> <pre><code>auto lambda = [] (auto x) {}; lambda(features(w)[5]); </code></pre> <p>So the point is, we cannot always just <em>"move type T from <code>static_cast&lt;T&gt;</code> to the left-hand side of assignment"</em>.</p> <p>Instead, in any of the above examples we need to explicitly specify the desired type rather than allowing compiler deduce one on its own, if the latter can lead to <em>undefined behavior</em>:</p> <p>Respectively to my examples that would be:</p> <pre><code>/*1*/ foo(static_cast&lt;bool&gt;(features(w)[5])); /*2*/ return static_cast&lt;bool&gt;(features(w)[5]); /*3*/ lambda(static_cast&lt;bool&gt;(features(w)[5])); </code></pre> <p>As such, using <code>static_cast&lt;T&gt;</code> is an elegant way of forcing a desired type, which alternatively can be expressed by explicit contructor call:</p> <pre><code>foo(bool{features(w)[5]}); </code></pre> <hr> <p>To summarize, I don't think the book says:</p> <blockquote> <p>Whenever you want to force the type of a variable, use <code>auto x = static_cast&lt;T&gt;(y);</code> instead of <code>T x{y};</code>.</p> </blockquote> <p>To me it sounds more like a word of warning:</p> <blockquote> <p>The type inference with <code>auto</code> is cool, but may end up with undefined behavior if used unwisely.</p> </blockquote> <p>And as a solution for the scenarios <em>involving type deduction</em>, the following is proposed:</p> <blockquote> <p>If the compiler's regular type-deduction mechanism is not what you want, use <code>static_cast&lt;T&gt;(y)</code>.</p> </blockquote> <hr> <p><strong>UPDATE</strong></p> <p>And answering your updated question, <em>which of the below initializations should one prefer</em>:</p> <pre><code>bool priority = features(w)[5]; auto priority = static_cast&lt;bool&gt;(features(w)[5]); auto priority = bool(features(w)[5]); auto priority = bool{features(w)[5]}; </code></pre> <p><strong>Scenario 1</strong></p> <p>First, imagine the <code>std::vector&lt;bool&gt;::reference</code> is <strong>not implicitly</strong> convertible to <code>bool</code>:</p> <pre><code>struct BoolReference { explicit operator bool() { /*...*/ } }; </code></pre> <p>Now, the <code>bool priority = features(w)[5];</code> will <strong>not compile</strong>, as it is not an explicit boolean context. The others will work fine (as long as the <code>operator bool()</code> is accessible).</p> <p><strong>Scenario 2</strong></p> <p>Secondly, let's assume the <code>std::vector&lt;bool&gt;::reference</code> is implemented in an <em>old fashion</em>, and although the <em>conversion operator</em> is not <code>explicit</code>, it returns <code>int</code> instead:</p> <pre><code>struct BoolReference { operator int() { /*...*/ } }; </code></pre> <p>The change in signature <strong>turns off</strong> the <code>auto priority = bool{features(w)[5]};</code> initialization, as using <code>{}</code> prevents the <em>narrowing</em> (which converting an <code>int</code> to <code>bool</code> is).</p> <p><strong>Scenario 3</strong></p> <p>Thirdly, what if we were talking not about <code>bool</code> at all, but about some <em>user-defined</em> type, that, to our surprise, declares <code>explicit</code> constructor:</p> <pre><code>struct MyBool { explicit MyBool(bool b) {} }; </code></pre> <p>Surprisingly, once again the <code>MyBool priority = features(w)[5];</code> initialization will <strong>not compile</strong>, as the copy-initialization syntax requires non-explicit constructor. Others will work though.</p> <p><strong>Personal attitude</strong></p> <p>If I were to choose one initialization from the listed four candidates, I would go with:</p> <pre><code>auto priority = bool{features(w)[5]}; </code></pre> <p>because it introduces an explicit boolean context (which is fine in case we want to assign this value to boolean variable) and prevents narrowing (in case of other types, not-easily-convertible-to-bool), so that when an error/warning is triggered, we can diagnose what <code>features(w)[5]</code> <strong>really is</strong>.</p> <hr> <p><strong>UPDATE 2</strong></p> <p>I have recently watched Herb Sutter's speech from <em>CppCon 2014</em> titled <a href="https://www.youtube.com/watch?v=xnqTKD8uD64" rel="noreferrer"><em>Back to the Basics! Essentials of Modern C++ Style</em></a>, where he presents some points on why should one prefer the <em>explicit type initializer</em> of <code>auto x = T{y};</code> form (though it is not the same as with <code>auto x = static_cast&lt;T&gt;(y)</code>, so not all arguments apply) over <code>T x{y};</code>, which are:</p> <ol> <li><p><code>auto</code> variables must always be initialized. That is, you can't write <code>auto a;</code>, just like you can write error-prone <code>int a;</code></p></li> <li><p>The <em>modern C++</em> style prefers the type on the right side, just like in:</p> <p>a) Literals:</p> <pre><code>auto f = 3.14f; // ^ float </code></pre> <p>b) User-defined literals:</p> <pre><code>auto s = "foo"s; // ^ std::string </code></pre> <p>c) Function declarations:</p> <pre><code>auto func(double) -&gt; int; </code></pre> <p>d) Named lambdas:</p> <pre><code>auto func = [=] (double) {}; </code></pre> <p>e) Aliases:</p> <pre><code>using dict = set&lt;string&gt;; </code></pre> <p>f) Template aliases:</p> <pre><code>template &lt;class T&gt; using myvec = vector&lt;T, myalloc&gt;; </code></pre> <p><strong>so as such</strong>, adding one more:</p> <pre><code>auto x = T{y}; </code></pre> <p>is consistent with the style where we have name on the left side, and type with initializer on the right side, what can be briefly described as:</p> <pre><code>&lt;category&gt; name = &lt;type&gt; &lt;initializer&gt;; </code></pre></li> <li><p>With copy-elision and non-explicit copy/move constructors it has <em>zero-cost</em> compared to <code>T x{y}</code> syntax.</p></li> <li><p>It is more explicit when there are subtle differences between the types:</p> <pre><code> unique_ptr&lt;Base&gt; p = make_unique&lt;Derived&gt;(); // subtle difference auto p = unique_ptr&lt;Base&gt;{make_unique&lt;Derived&gt;()}; // explicit and clear </code></pre></li> <li><p><code>{}</code> guarantees no implicit conversions and no narrowing.</p></li> </ol> <p>But he also mentions some drawbacks of the <code>auto x = T{}</code> form in general, which has already been described in this post:</p> <ol> <li><p>Even though the compiler can elide the right-hand side's temporary, it requires an accessible, non-deleted and non-explicit copy-constructor:</p> <pre><code> auto x = std::atomic&lt;int&gt;{}; // fails to compile, copy constructor deleted </code></pre></li> <li><p>If the elision is not enabled (e.g. <code>-fno-elide-constructors</code>), then moving non-movable types results in expensive copy:</p> <pre><code> auto a = std::array&lt;int,50&gt;{}; </code></pre></li> </ol>
62,601,538
Passing a function in the useEffect dependency array causes infinite loop
<p>Why is an infinite loop created when I pass a function expression into the useEffect dependency array? The function expression does not alter the component state, it only references it.</p> <pre><code>// component has one prop called =&gt; sections const markup = (count) =&gt; { const stringCountCorrection = count + 1; return ( // Some markup that references the sections prop ); }; // Creates infinite loop useEffect(() =&gt; { if (sections.length) { const sectionsWithMarkup = sections.map((section, index)=&gt; markup(index)); setSectionBlocks(blocks =&gt; [...blocks, ...sectionsWithMarkup]); } else { setSectionBlocks(blocks =&gt; []); } }, [sections, markup]); </code></pre> <p>If markup altered state I could understand why it would create an infinite loop but it does not it simply references the sections prop.</p> <p>So I'm not looking for a code related answer to this question. If possible I'm looking for a detailed explanation as to why this happens.</p> <p>I'm more interested in the why then just simply finding the answer or correct way to solve the problem.</p> <p>Why does passing a function in the useEffect dependency array that is declared outside of useEffect cause a re-render when both state and props aren't changed in said function?</p>
62,601,621
2
1
null
2020-06-26 19:21:48.923 UTC
7
2022-06-22 16:54:31.087 UTC
2022-06-22 16:54:31.087 UTC
null
1,264,804
null
8,142,680
null
1
47
reactjs|react-hooks|use-effect|usecallback
49,383
<p>The issue is that upon each render cycle, <code>markup</code> is redefined. React uses shallow object comparison to determine if a value updated or not. Each render cycle <code>markup</code> has a different reference. You can use <code>useCallback</code> to memoize the function though so the reference is stable. Do you have the <a href="https://www.npmjs.com/package/eslint-plugin-react-hooks" rel="noreferrer">react hook rules</a> enabled for your linter? If you did then it would likely flag it, tell you why, and make this suggestion to resolve the reference issue.</p> <pre><code>const markup = useCallback( (count) =&gt; { const stringCountCorrection = count + 1; return ( // Some markup that references the sections prop ); }, [count, /* and any other dependencies the react linter suggests */] ); // No infinite looping, markup reference is stable/memoized useEffect(() =&gt; { if (sections.length) { const sectionsWithMarkup = sections.map((section, index)=&gt; markup(index)); setSectionBlocks(blocks =&gt; [...blocks, ...sectionsWithMarkup]); } else { setSectionBlocks(blocks =&gt; []); } }, [sections, markup]); </code></pre>
4,741,164
Javascript: Get div inside of div
<p>I have two divs nested like so:</p> <pre><code>&lt;div id="upper"&gt; &lt;div id="lower" name="moo"&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>How would I, using jQuery or JavaScript alone, can I get the name of that lower nested div?</p>
4,741,174
2
3
null
2011-01-19 21:46:22.7 UTC
3
2018-10-24 13:22:15.517 UTC
null
null
null
null
270,483
null
1
12
javascript|jquery
64,145
<pre><code>var nameValue = $('#lower').attr('name'); </code></pre> <p>But if you really want to use the outer <code>div</code> to select the inner one:</p> <pre><code>var nameValue = $('#upper &gt; div').attr('name'); </code></pre> <p>Or</p> <pre><code>var nameValue = $('#upper #lower').attr('name'); </code></pre> <p>Or</p> <pre><code>var nameValue = $('#upper').find('#lower').attr('name'); </code></pre>
4,340,349
Running unit tests from currently opened file in IntelliJ IDEA
<p>Is there any way to have IntelliJ run the current MyTest.java file I'm looking at? </p> <p>Thanks</p>
4,341,210
2
0
null
2010-12-02 21:52:59.13 UTC
2
2020-01-21 08:24:39.377 UTC
2020-01-21 08:24:39.377 UTC
null
814,702
null
12,503
null
1
29
java|unit-testing|intellij-idea
9,980
<p>Yeah, you can either:</p> <ol> <li>Right click on the file and go to <blockquote> <p>Run 'MyTest'</p> </blockquote></li> <li>Use the key binding: if the <em>caret</em> is in a method on that method will be run <ul> <li>on a Mac: it's <kbd>Control</kbd>+<kbd>Fn</kbd>+<kbd>Shift</kbd>+<kbd>F10</kbd></li> <li>elsewhere: it's <kbd>Alt</kbd>+<kbd>Shift</kbd>+<kbd>F10</kbd></li> </ul></li> </ol>
4,218,847
HtmlAgilityPack -- Does <form> close itself for some reason?
<p>I just wrote up this test to see if I was crazy...</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using HtmlAgilityPack; namespace HtmlAgilityPackFormBug { class Program { static void Main(string[] args) { var doc = new HtmlDocument(); doc.LoadHtml(@" &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Form Test&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;form&gt; &lt;input type=""text"" /&gt; &lt;input type=""reset"" /&gt; &lt;input type=""submit"" /&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; "); var body = doc.DocumentNode.SelectSingleNode("//body"); foreach (var node in body.ChildNodes.Where(n =&gt; n.NodeType == HtmlNodeType.Element)) Console.WriteLine(node.XPath); Console.ReadLine(); } } } </code></pre> <p>And it outputs:</p> <pre><code>/html[1]/body[1]/form[1] /html[1]/body[1]/input[1] /html[1]/body[1]/input[2] /html[1]/body[1]/input[3] </code></pre> <p>But, if I change <code>&lt;form&gt;</code> to <code>&lt;xxx&gt;</code> it gives me:</p> <pre><code>/html[1]/body[1]/xxx[1] </code></pre> <p>(As it should). So... it looks like those input elements are <em>not</em> contained within the form, but directly within the body, as if the <code>&lt;form&gt;</code> just closed itself off immediately. What's up with that? Is this a bug?</p> <hr> <p>Digging through the source, I see:</p> <pre><code>ElementsFlags.Add("form", HtmlElementFlag.CanOverlap | HtmlElementFlag.Empty); </code></pre> <p>It has the "empty" flag, like META and IMG. Why?? Forms are most definitely <em>not</em> supposed to be empty.</p>
4,219,060
2
6
null
2010-11-18 19:44:19.713 UTC
5
2013-05-08 21:50:57.22 UTC
2010-11-18 20:19:52.743 UTC
null
65,387
null
65,387
null
1
34
c#|html-agility-pack
5,255
<p>This is also reported in <a href="http://htmlagilitypack.codeplex.com/workitem/23074" rel="noreferrer">this workitem</a>. It contains a suggested workaround from DarthObiwan.</p> <blockquote> <p>You can change this without recompiling. The ElementFlags list is a static property on the HtmlNode class. It can be removed with</p> <pre><code> HtmlNode.ElementsFlags.Remove("form"); </code></pre> <p>before doing the document load</p> </blockquote>
10,025,660
Override home and back button is case a boolean is true
<p>I was wondering if I can override the action of the back and home button is some cases. Normally these buttons should just react like they always do, but in a case some setting is true I want to override the buttons and let them call my own methods.</p> <p>I´m using these two methods to override these buttons:</p> <pre><code> @Override public void onBackPressed() { // call my backbutton pressed method when boolean==true } @Override public void onAttachedToWindow() { this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD); super.onAttachedToWindow(); // call my homebutton pressed method when boolean==true } </code></pre>
10,025,904
6
0
null
2012-04-05 09:02:49.883 UTC
20
2015-06-13 05:11:32.937 UTC
2012-11-24 12:49:21.67 UTC
null
739,270
null
1,062,575
null
1
10
android|button|overriding|back-button
22,565
<blockquote> <p>I was wondering if I can override the action of the back and home button is some cases.</p> </blockquote> <p>Yes you can do override <code>Home</code> button.</p> <p>I have developed an application which disable hard button, you can have a look. I have taken a <strong>toggle button</strong> which locks all hard button to work except <strong>Power</strong> button</p> <pre><code>public class DisableHardButton extends Activity { /** Called when the activity is first created. */ TextView mTextView; ToggleButton mToggleButton; boolean isLock=false; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mTextView=(TextView) findViewById(R.id.tvInfo); mToggleButton=(ToggleButton) findViewById(R.id.btnLock); mToggleButton.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // TODO Auto-generated method stub isLock=isChecked; onAttachedToWindow(); } }); } @Override public boolean dispatchKeyEvent(KeyEvent event) { if ( (event.getKeyCode() == KeyEvent.KEYCODE_HOME) &amp;&amp; isLock) { mTextView.setText("KEYCODE_HOME"); return true; } else return super.dispatchKeyEvent(event); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { // TODO Auto-generated method stub if( (keyCode==KeyEvent.KEYCODE_BACK) &amp;&amp; isLock) { mTextView.setText("KEYCODE_BACK"); return true; } else return super.onKeyDown(keyCode, event); } @Override public void onAttachedToWindow() { System.out.println("Onactivity attached :"+isLock); if(isLock) { this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD); super.onAttachedToWindow(); } else { this.getWindow().setType(WindowManager.LayoutParams.TYPE_APPLICATION); super.onAttachedToWindow(); } } } </code></pre> <p>main.xml</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" &gt; &lt;TextView android:id="@+id/tvInfo" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /&gt; &lt;ToggleButton android:id="@+id/btnLock" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textOff="UnLocked" android:textOn="Locked" /&gt; &lt;/LinearLayout&gt; </code></pre>
10,143,784
C can't compile - symbol(s) not found for architecture x86_64
<p>Having a serious problem with my C code, I just don't seem to be able to get it to compile and I really can't figure out why. </p> <p>I have tried researching online and can't find a solution to the problem, do you have any idea?</p> <p>Thanks for your time!</p> <pre><code>Undefined symbols for architecture x86_64: "_Insert", referenced from: _InsertNode in part1.o (maybe you meant: _InsertNode) "_Create", referenced from: _findShortestPaths in part1.o "_DeleteMin", referenced from: _findShortestPaths in part1.o "_decreaseKey", referenced from: _findShortestPaths in part1.o "_GetMin", referenced from: _findShortestPaths in part1.o ld: symbol(s) not found for architecture x86_64 collect2: ld returned 1 exit status make: *** [part1] Error 1 </code></pre> <p>Snippits from part1.c</p> <pre><code>#include "limits.h" #include "pegBinaryHeap.h" void InsertNode(int distance, Node* node, PriorityQueue PQ) { ... Insert(*item, PQ); } ... int* findShortestPaths(Graph *graph, int start) { ... //Priority queue ordered by distance PriorityQueue pq = Create(graph-&gt;MaxSize); for(int i = 0; i &lt; graph-&gt;MaxSize; i++) { ... } //While the queue isn't empty: while((currentPqItem=GetMin(pq)) != NULL) { ... DeleteMin(pq); //for each node accesable from currentNode List *currentNeighbour = currentNode.outlist; while(currentNeighbour!=NULL) { ... decreaseKey(currentNode.id, newDistance, pq); } // end for }// end while } int main(int argc,char *argv[]) { Graph mygraph; return 0; } </code></pre> <p>And the .h file that it appears to be complaining about</p> <pre><code>#include "graph.h" struct HeapStruct; typedef struct HeapStruct *PriorityQueue; typedef struct { int distance; Node *node; } QueueType; PriorityQueue Create( int MaxSize ); void Destroy( PriorityQueue H ); int Insert( QueueType Item, PriorityQueue H ); QueueType DeleteMin( PriorityQueue H ); QueueType* GetMin( PriorityQueue H ); void decreaseKey(int nodeId, int value, PriorityQueue H); </code></pre>
10,144,099
3
4
null
2012-04-13 15:29:11.343 UTC
8
2012-10-06 05:16:54.52 UTC
null
null
null
null
193,376
null
1
18
c|compilation
42,309
<p>You can <em>compile</em>, but you cannot <em>link</em>.</p> <p><code>part1.o</code> is using the functions you defined in your last <code>.h</code> file and the implementations cannot be found. When you link your program, you need to make sure you're linking in the object file(s) (or libraries) that contain the implementations of those functions. You've likely done something like:</p> <p><code>gcc part1.c -o myapp</code></p> <p>and so the linker doesn't have all the pieces to the puzzle.</p> <p>If you want to compile in parts, you need to:</p> <pre><code>gcc -c part1.c -o part1.o gcc -c implementations.c -o implementations.o gcc implementations.o part1.o -o myapp </code></pre> <p>Here, all the <code>.c</code> files are compiled into object (<code>.o</code>) files separately, and then linked together into an executable. Or you could do everything at once:</p> <pre><code>gcc part1.c implementations.c -o myapp </code></pre> <p>If the implementations are in a library (<code>libimplementations.a</code>):</p> <pre><code>gcc part1.c -Lpath/to/libs -limplementations -o myapp </code></pre>
10,234,053
RPM spec file - Is it possible to dynamically populate a spec file variable
<p>I have a spec file. I need to %define a spec variable that gets its value from a one line file on the system.</p> <p>For example</p> <pre><code>%define path `cat /home/user/path_file` </code></pre> <p>and in path_file is one line</p> <pre><code>/var/www/html/hosts </code></pre> <p>This partially works. I say that begins in the RPM BUILD output sometimes the value of <code>${path}</code> is literally my command <code>cat /home/user/path_file</code> and sometimes the value is the line in the path_file (/var/www/html/hosts) as it should be?</p>
10,236,104
1
0
null
2012-04-19 18:03:06.06 UTC
6
2019-04-19 17:49:15.173 UTC
2019-04-19 17:49:15.173 UTC
null
68,587
null
1,288,571
null
1
31
rpm|rpmbuild|rpm-spec
29,483
<p>You can define rpmbuild variables with <code>%(cmd)</code> at the top of the spec file. Notice the command is in parenthesis, not curly brackets. An example:</p> <pre><code>%define whoami %(whoami) </code></pre> <p>And elsewhere in the spec file, such as a script or the build/install sections, use the variable as normal in the curly brackets like this:</p> <pre><code>echo "The user that built this is %{whoami}" </code></pre> <p>The <code>cmd</code> can be anything, including your cat command. Be careful - when another user rebuilds the spec file it may not find the file. So it'll be preferable to use the %{sourcedir} macro like this:</p> <pre><code>%define path %(cat %{sourcedir}/path_file) </code></pre> <p>And make sure that <code>path_file</code> is in the source directory and included as a source in the spec file.</p>
10,246,831
How to look at Bitmap objects in Visual Studio debugger?
<p>I am building a C# app that creates many bitmaps (System.Drawing.Image). Having the bitmaps seen in the debugger as pictures, would be of enormous help. The debugger has native support for XML files. Is there a way to see the pictures?</p>
10,246,871
6
3
null
2012-04-20 13:05:21.453 UTC
2
2019-04-16 09:18:42.827 UTC
null
null
null
null
112,091
null
1
32
c#|visual-studio-2010|debugging|c#-4.0|bitmap
17,380
<p>There is no debugger visualizer by default for Bitmap, so you might want to give this one a try: <a href="http://imagedebugvisualizer.codeplex.com/" rel="noreferrer">http://imagedebugvisualizer.codeplex.com/</a></p>
9,809,180
Why is JUnit 4 on Android not working?
<p>as the documentation of Android says, "Note that the Android testing API supports JUnit 3 code style, but not JUnit 4." (<a href="http://developer.android.com/guide/topics/testing/testing_android.html">Testing Fundamentals</a>). It should be clear that JUnit 4 cannot be used out of the box with Android.</p> <p>But why is this the case? Is it because the tests are executed within the DVM (in that the Android Runtime only has support for JUnit 3)? On a JVM one on its own could choose the JUnit runtime that should be used. Isn't this possible within the DVM?</p>
11,916,340
2
3
null
2012-03-21 16:51:16.403 UTC
14
2015-10-05 07:38:11.48 UTC
null
null
null
null
1,229,451
null
1
33
java|android|junit4|dalvik|junit3
14,936
<p><strong>Update 2015/10</strong></p> <p>It is now possible via the AndroidJUnitRunner, which is part of the <a href="http://developer.android.com/tools/testing-support-library/index.html" rel="noreferrer">Android Testing Support Library</a>. In short, you need to do the following in a Gradle-based project:</p> <ol> <li><p>Add the dependencies:</p> <pre><code>dependencies { compile 'com.android.support:support-annotations:22.2.0' androidTestCompile 'com.android.support.test:runner:0.4.1' } </code></pre></li> <li><p>Specify the testInstrumentationRunner:</p> <pre><code>android { defaultConfig { testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } } </code></pre></li> <li><p>Annotate your test class with <code>@RunWith(AndroidJUnit4.class)</code>.</p></li> <li>Write your tests in normal JUnit4 style.</li> </ol> <p>Also see the <a href="https://google.github.io/android-testing-support-library/docs/espresso/setup/index.html" rel="noreferrer">Espresso setup instructions</a>. Note that you don't need Espresso itself for plain JUnit4 tests.</p> <p><strong>Why it's needed</strong></p> <p>There are very little information I could find on the internet on this topic. The best I found was the info on <a href="http://developer.android.com/tools/testing/testing_android.html#InstrumentationTestRunner" rel="noreferrer">InstrumentationTestRunner</a>.</p> <p>There are nothing preventing JUnit4 tests from running on an Android device just like any other Java code. However, the Android test framework does some additional work:</p> <ol> <li>It sends test results back to your development machine over ADB.</li> <li>It does instrumentation (I'm not sure what exactly this involves).</li> </ol> <p>The above is performed by some extensions specifically for JUnit3.</p> <p>This JUnit3-specific code seems to be part of the InstrumentationTestRunner which forms part of the core Android system. However, as is evident with AndroidJUnitRunner, it is possible to use a custom test runner that supports JUnit4 or other frameworks.</p>
28,226,229
How to loop through dates using Bash?
<p>I have such bash script:</p> <pre><code>array=( '2015-01-01', '2015-01-02' ) for i in "${array[@]}" do python /home/user/executeJobs.py {i} &amp;&gt; /home/user/${i}.log done </code></pre> <p>Now I want to loop through a range of dates, e.g. 2015-01-01 until 2015-01-31.</p> <p>How to achieve in Bash?</p> <p><strong>Update</strong>: </p> <p>Nice-to-have: No job should be started before a previous run has completed. In this case, when executeJobs.py is completed bash prompt <code>$</code> will return.</p> <p>e.g. could I incorporate <code>wait%1</code> in my loop?</p>
28,226,339
10
17
null
2015-01-29 22:55:05.467 UTC
37
2022-09-20 23:00:11.877 UTC
2019-12-25 12:09:22.857 UTC
null
608,639
null
356,759
null
1
114
bash|loops|date
120,739
<p>Using GNU date:</p> <pre><code>d=2015-01-01 while [ &quot;$d&quot; != 2015-02-20 ]; do echo $d d=$(date -I -d &quot;$d + 1 day&quot;) # mac option for d decl (the +1d is equivalent to + 1 day) # d=$(date -j -v +1d -f &quot;%Y-%m-%d&quot; $d +%Y-%m-%d) done </code></pre> <p>Note that because this uses string comparison, it requires full ISO 8601 notation of the edge dates (do not remove leading zeros). To check for valid input data and coerce it to a valid form if possible, you can use <code>date</code> as well:</p> <pre><code># slightly malformed input data input_start=2015-1-1 input_end=2015-2-23 # After this, startdate and enddate will be valid ISO 8601 dates, # or the script will have aborted when it encountered unparseable data # such as input_end=abcd startdate=$(date -I -d &quot;$input_start&quot;) || exit -1 enddate=$(date -I -d &quot;$input_end&quot;) || exit -1 d=&quot;$startdate&quot; while [ &quot;$d&quot; != &quot;$enddate&quot; ]; do echo $d d=$(date -I -d &quot;$d + 1 day&quot;) done </code></pre> <p><strong>One final addition</strong>: To check that <code>$startdate</code> is before <code>$enddate</code>, if you only expect dates between the years 1000 and 9999, you can simply use string comparison like this:</p> <pre><code>while [[ &quot;$d&quot; &lt; &quot;$enddate&quot; ]]; do </code></pre> <p>To be on the very safe side beyond the year 10000, when lexicographical comparison breaks down, use</p> <pre><code>while [ &quot;$(date -d &quot;$d&quot; +%Y%m%d)&quot; -lt &quot;$(date -d &quot;$enddate&quot; +%Y%m%d)&quot; ]; do </code></pre> <p>The expression <code>$(date -d &quot;$d&quot; +%Y%m%d)</code> converts <code>$d</code> to a numerical form, i.e., <code>2015-02-23</code> becomes <code>20150223</code>, and the idea is that dates in this form can be compared numerically.</p>
11,658,011
Cannot modify content of iframe, what is wrong?
<p>I am trying to modify content of an iframe but it does not work.</p> <p>This is my main.html</p> <pre><code>&lt;html&gt; &lt;head&gt;&lt;title&gt;Main page&lt;/title&gt; &lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;h3&gt;Main page&lt;/h3&gt; &lt;iframe src="ifr.htm" id="ifr" name="ifr"&gt;&lt;/iframe&gt; &lt;/body&gt; &lt;script&gt; $(document).ready(function(){ $('#ifr').load(function(){ $('#ifr').contents().find('body').html('Hey, i`ve changed content of &lt;body&gt;! Yay!!!'); }); }); &lt;/script&gt; &lt;/html&gt; </code></pre> <p>This is my ifr.htm</p> <pre><code>&lt;html&gt; &lt;head&gt;&lt;title&gt;Iframe page&lt;/title&gt;&lt;/head&gt; &lt;body&gt; Content to be displayed in iframe ... &lt;/body&gt; &lt;/html&gt; </code></pre>
11,658,546
3
7
null
2012-07-25 20:23:00.883 UTC
5
2019-08-26 14:42:57.687 UTC
2015-05-22 11:00:36.64 UTC
null
1,793,718
null
1,313,296
null
1
13
jquery|html
46,817
<p>Please don't forget the <code>cross-domain</code> policy, otherwise it won't work.</p> <p><strong>Live demo:</strong> <a href="http://jsfiddle.net/oscarj24/wTWjF/" rel="nofollow noreferrer">http://jsfiddle.net/oscarj24/wTWjF/</a></p> <p><em>(Just to know, I am not using a 404 page, take a look)</em></p> <p>Try this:</p> <pre><code>$(document).ready(function(){ $('#ifr').ready(function(){ $(this).contents().find('body').html('Hey, I have changed the body content yay!'); }); });​ </code></pre>
11,911,660
Redirect console.writeline from windows application to a string
<p>I have an external dll written in C# and I studied from the assemblies documentation that it writes its debug messages to the Console using <code>Console.WriteLine</code>.</p> <p>this DLL writes to console during my interaction with the UI of the Application, so i don't make DLL calls directly, but i would capture all console output , so i think i got to intialize in form load , then get that captured text later.</p> <p>I would like to redirect all the output to a string variable.</p> <p>I tried <code>Console.SetOut</code>, but its use to redirect to string is not easy.</p>
11,911,734
5
0
null
2012-08-11 03:30:16.713 UTC
13
2021-01-20 10:43:20.75 UTC
2012-08-11 04:11:45.743 UTC
null
749,063
null
749,063
null
1
18
c#|.net|console
22,945
<p>As it seems like you want to catch the Console output in realtime, I figured out that you might create your own <code>TextWriter</code> implementation that fires an event whenever a <code>Write</code> or <code>WriteLine</code> happens on the <code>Console</code>.</p> <p>The writer looks like this:</p> <pre><code> public class ConsoleWriterEventArgs : EventArgs { public string Value { get; private set; } public ConsoleWriterEventArgs(string value) { Value = value; } } public class ConsoleWriter : TextWriter { public override Encoding Encoding { get { return Encoding.UTF8; } } public override void Write(string value) { if (WriteEvent != null) WriteEvent(this, new ConsoleWriterEventArgs(value)); base.Write(value); } public override void WriteLine(string value) { if (WriteLineEvent != null) WriteLineEvent(this, new ConsoleWriterEventArgs(value)); base.WriteLine(value); } public event EventHandler&lt;ConsoleWriterEventArgs&gt; WriteEvent; public event EventHandler&lt;ConsoleWriterEventArgs&gt; WriteLineEvent; } </code></pre> <p>If it's a WinForm app, you can setup the writer and consume its events in the Program.cs like this:</p> <pre><code> /// &lt;summary&gt; /// The main entry point for the application. /// &lt;/summary&gt; [STAThread] static void Main() { using (var consoleWriter = new ConsoleWriter()) { consoleWriter.WriteEvent += consoleWriter_WriteEvent; consoleWriter.WriteLineEvent += consoleWriter_WriteLineEvent; Console.SetOut(consoleWriter); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } static void consoleWriter_WriteLineEvent(object sender, Program.ConsoleWriterEventArgs e) { MessageBox.Show(e.Value, "WriteLine"); } static void consoleWriter_WriteEvent(object sender, Program.ConsoleWriterEventArgs e) { MessageBox.Show(e.Value, "Write"); } </code></pre>
11,877,586
How to merge two arrays of object in PHP
<p>I have the following two arrays of objects:</p> <p><strong>First Array:</strong> <code>$array1</code></p> <pre><code>Array ( [0] =&gt; stdClass Object ( [id] =&gt; 100 [name] =&gt; Muhammad ) [1] =&gt; stdClass Object ( [id] =&gt; 102 [name] =&gt; Ibrahim ) [2] =&gt; stdClass Object ( [id] =&gt; 101 [name] =&gt; Sumayyah ) ) </code></pre> <p><strong>Second Array:</strong> <code>$array2</code></p> <pre><code>Array ( [0] =&gt; stdClass Object ( [id] =&gt; 100 [name] =&gt; Muhammad ) [1] =&gt; stdClass Object ( [id] =&gt; 103 [name] =&gt; Yusuf ) ) </code></pre> <p>I want to merge these two object arrays (removing all duplicates) and sorted according to <code>id</code>.</p> <p><strong>Desired output:</strong></p> <pre><code>Array ( [0] =&gt; stdClass Object ( [id] =&gt; 100 [name] =&gt; Muhammad ) [1] =&gt; stdClass Object ( [id] =&gt; 101 [name] =&gt; Sumayyah ) [2] =&gt; stdClass Object ( [id] =&gt; 102 [name] =&gt; Ibrahim ) [3] =&gt; stdClass Object ( [id] =&gt; 103 [name] =&gt; Yusuf ) ) </code></pre>
11,879,498
3
3
null
2012-08-09 06:03:52.24 UTC
6
2022-08-31 10:41:04.37 UTC
2012-08-09 06:52:55.477 UTC
null
462,732
null
462,732
null
1
22
php|arrays|sorting
43,284
<p>These 3 simple steps did the work:</p> <pre><code>//both arrays will be merged including duplicates $result = array_merge( $array1, $array2 ); //duplicate objects will be removed $result = array_map("unserialize", array_unique(array_map("serialize", $result))); //array is sorted on the bases of id sort( $result ); </code></pre> <p><strong>Note:</strong> Answer by @Kamran helped me come to this simple solution</p>
12,043,875
ArgumentNullException - how to simplify?
<p>I've noticed this code crops up a lot in my constructors:</p> <pre><code>if (someParam == null) throw new ArgumentNullException("someParam"); if (someOtherParam == null) throw new ArgumentNullException("someOtherParam"); ... </code></pre> <p>I have a few constructors where several things are injected and must all be non-null. Can anyone think of a way to streamline this? The only thing I can think of is the following:</p> <pre><code>public static class ExceptionHelpers { public static void CheckAndThrowArgNullEx(IEnumerable&lt;KeyValuePair&lt;string, object&gt;&gt; parameters) { foreach(var parameter in parameters) if(parameter.Value == null) throw new ArgumentNullException(parameter.Key); } } </code></pre> <p>However, the usage of that would be something like:</p> <pre><code>ExceptionHelper.CheckAndThrowArgNullEx(new [] { new KeyValuePair&lt;string, object&gt;("someParam", someParam), new KeyValuePair&lt;string, object&gt;("someOtherParam", someOtherParam), ... }); </code></pre> <p>... which doesn't really help streamline the code. Tuple.Create() instead of KVPs doesn't work because Tuple's GTPs aren't covariant (even though IEnumerable's GTP is). Any ideas?</p>
12,044,807
17
3
null
2012-08-20 19:28:52.35 UTC
9
2022-04-28 16:14:21.38 UTC
2012-08-20 21:05:52.61 UTC
null
436,376
null
436,376
null
1
23
c#|exception
18,848
<p>Upticks for most of you guys; your answers contributed to the solution I finally arrived at, which incorporated bits and pieces but ultimately is different from all of them.</p> <p>I created a couple of static methods that work on lambda expressions of a specific form (<strong>EDIT</strong> - small change; the methods can't be generic or they will require all expressions to return the same type. Func is fine instead, with an extra condition in the GetName method to unwrap the cast):</p> <pre><code>public static class ExpressionReader { /// &lt;summary&gt; /// Gets the name of the variable or member specified in the lambda. /// &lt;/summary&gt; /// &lt;param name="expr"&gt;The lambda expression to analyze. /// The lambda MUST be of the form ()=&gt;variableName.&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; public static string GetName(this Expression&lt;Func&lt;object&gt;&gt; expr) { if (expr.Body.NodeType == ExpressionType.MemberAccess) return ((MemberExpression) expr.Body).Member.Name; //most value type lambdas will need this because creating the //Expression from the lambda adds a conversion step. if (expr.Body.NodeType == ExpressionType.Convert &amp;&amp; ((UnaryExpression)expr.Body).Operand.NodeType == ExpressionType.MemberAccess) return ((MemberExpression)((UnaryExpression)expr.Body).Operand) .Member.Name; throw new ArgumentException( "Argument 'expr' must be of the form ()=&gt;variableName."); } } public static class ExHelper { /// &lt;summary&gt; /// Throws an ArgumentNullException if the value of any passed expression is null. /// &lt;/summary&gt; /// &lt;param name="expr"&gt;The lambda expressions to analyze. /// The lambdas MUST be of the form ()=&gt;variableName.&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; public static void CheckForNullArg(params Expression&lt;Func&lt;object&gt;&gt;[] exprs) { foreach (var expr in exprs) if(expr.Compile()() == null) throw new ArgumentNullException(expr.GetName()); } } </code></pre> <p>... which can be used thusly:</p> <pre><code>//usage: ExHelper.CheckForNullArg(()=&gt;someParam, ()=&gt;someOtherParam); </code></pre> <p>This reduces the boilerplate to one line, without third-party tools. The ExpressionReader, and thus the exception-generating method, work on any lambda of the form ()=>variableName that compiles in the caller, meaning it works for local variables, parameters, instance fields and instance properties, at least. I haven't checked to see if it works on statics.</p>
11,873,959
flask-sqlalchemy - PostgreSQL - Define specific schema for table?
<p>I want to define a specific schema for a 'model' using flask-sqlalchemy. When you create a table object in sqlalchemy itself it has a parameter to pass for schema name. </p> <p>How do I do this in flask-sqlalchemy?</p>
11,875,775
3
0
null
2012-08-08 22:11:35.543 UTC
11
2020-08-03 00:44:53.61 UTC
2013-09-05 17:46:22.02 UTC
null
2,165,163
null
786,467
null
1
28
python|flask|flask-sqlalchemy
13,699
<p>When you define your model class use:</p> <pre><code>__table_args__ = {"schema":"schema_name"} </code></pre> <p>maybe it will save someone else some hunting.</p>
11,590,792
How can I find the parent tr of a td using jQuery?
<p>I have the following:</p> <pre><code> tdToPad = tds.filter('[id^="input_Title_"]') pad = 60; tdToPad.css('margin-left', pad); </code></pre> <p>What I would like to do is to remove any class that starts with "X-" and give the row that is contained by "tdToPad" a class of "X-" + pad. </p> <p>Something like:</p> <pre><code>&lt;tr class='X-60'&gt; &lt;td&gt; &lt;/td&gt; &lt;/tr&gt; </code></pre> <p>Being that toToPad refers to the td element in a row. How can I give the parent tr the class "X-" + pad ? I think I need something like the following but if that's the correct way to do it then how can I remove elements already there with a class of "X-" somevalue and then give this element the correct class?</p> <pre><code>tdToPad.Parent('tr') </code></pre>
11,590,807
2
0
null
2012-07-21 08:48:30.477 UTC
7
2014-01-16 15:03:14.503 UTC
null
null
null
null
1,422,604
null
1
30
jquery
94,062
<p>You can use <a href="http://api.jquery.com/closest/"><code>closest()</code></a> method:</p> <blockquote> <p>Get the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.</p> </blockquote> <pre><code>tdToPad.closest('tr') .addClass('X-' + pad) </code></pre> <p><strong>update:</strong></p> <pre><code>tdToPad.closest('tr').get(0).className = tdToPad.closest('tr').get(0).className.replace(/\bX\-.*?\b/g, ''); tdToPad.closest('tr').addClass('X-' + pad) </code></pre>
11,685,305
What is the syntax of the enhanced for loop in Java?
<p>I have been asked to use the enhanced <code>for</code> loop in my coding. </p> <p>I have only been taught how to use traditional <code>for</code> loops, and as such don't know about the differences between it and the enhanced <code>for</code> loop. </p> <p><strong>How does an enhanced <code>for</code> loop differ from a traditional <code>for</code> loop in Java?</strong> </p> <p>Are there any intricacies that I should look out for which tutorials tend not to mention?</p>
11,685,345
3
5
null
2012-07-27 09:46:02.913 UTC
7
2021-01-02 00:01:56.84 UTC
2019-07-02 23:25:21.717 UTC
null
6,912,508
user1920811
null
null
1
39
java|foreach
120,289
<p>Enhanced for loop:</p> <pre><code>for (String element : array) { // rest of code handling current element } </code></pre> <p>Traditional for loop equivalent:</p> <pre><code>for (int i=0; i &lt; array.length; i++) { String element = array[i]; // rest of code handling current element } </code></pre> <p>Take a look at these forums: <a href="https://blogs.oracle.com/CoreJavaTechTips/entry/using_enhanced_for_loops_with" rel="nofollow noreferrer">https://blogs.oracle.com/CoreJavaTechTips/entry/using_enhanced_for_loops_with</a></p> <p><a href="http://www.java-tips.org/java-se-tips/java.lang/the-enhanced-for-loop.html" rel="nofollow noreferrer">http://www.java-tips.org/java-se-tips/java.lang/the-enhanced-for-loop.html</a></p>
11,773,369
Convert from Long to date format
<p>I want to convert Long value to String or Date in this format dd/mm/YYYY.</p> <p>I have this value in Long format: 1343805819061.</p> <p>It is possible to convert it to Date format?</p>
11,773,465
6
0
null
2012-08-02 08:04:44.363 UTC
7
2020-11-06 10:49:44.677 UTC
2018-04-06 08:12:48.147 UTC
null
3,681,880
null
1,112,535
null
1
43
android|date|long-integer
82,573
<p>You can use below line of code to do this. Here timeInMilliSecond is long value.</p> <pre><code> String dateString = new SimpleDateFormat("MM/dd/yyyy").format(new Date(TimeinMilliSeccond)); </code></pre> <p>Or you can use below code too also.</p> <pre><code> String longV = "1343805819061"; long millisecond = Long.parseLong(longV); // or you already have long value of date, use this instead of milliseconds variable. String dateString = DateFormat.format("MM/dd/yyyy", new Date(millisecond)).toString(); </code></pre> <p>Reference:- <a href="http://developer.android.com/reference/java/text/DateFormat.html" rel="noreferrer">DateFormat</a> and <a href="http://developer.android.com/reference/java/text/SimpleDateFormat.html" rel="noreferrer">SimpleDateFormat</a></p> <p>P.S. Change date format according to your need.</p>
3,505,674
Comparing SIFT features stored in a mysql database
<p>I'm currently extending an image library used to categorize images and i want to find duplicate images, transformed images, and images that contain or are contained in other images.<br> I have tested the SIFT implementation from OpenCV and it works very well but would be rather slow for multiple images. Too speed it up I thought I could extract the features and save them in a database as a lot of other image related meta data is already being held there. </p> <p><strong>What would be the fastest way to compare the features of a new images to the features in the database?</strong><br> Usually comparison is done calculating the euclidean distance using kd-trees, FLANN, or with the <a href="http://userweb.cs.utexas.edu/~grauman/research/projects/pmk/pmk_projectpage.htm" rel="noreferrer">Pyramid Match Kernel</a> that I found in another thread here on SO, but haven't looked much into yet.</p> <p>Since I don't know of a way to save and search a kd-tree in a database efficiently, I'm currently only seeing three options:<br> * Let MySQL calculate the euclidean distance to every feature in the database, although I'm sure that that will take an unreasonable time for more than a few images.<br> * Load the entire dataset into memory at the beginning and build the kd-tree(s). This would probably be fast, but very memory intensive. Plus all the data would need to be transferred from the database.<br> * Saving the generated trees into the database and loading all of them, would be the fastest method but also generate high amounts of traffic as with new images the kd-trees would have to be rebuilt and send to the server.</p> <p>I'm using the SIFT implementation of OpenCV, but I'm not dead set on it. If there is a feature extractor more suitable for this task (and roughly equally robust) I'm glad if someone could suggest one.</p>
3,524,693
4
1
null
2010-08-17 18:27:08.397 UTC
23
2011-12-20 19:23:14.99 UTC
null
null
null
null
423,083
null
1
18
c++|database|algorithm|computer-vision|sift
6,585
<p>So I basically did something very similar to this a few years ago. <strong>The algorithm you want to look into was proposed a few years ago by David Nister, the paper is: "Scalable Recognition with a Vocabulary Tree". They pretty much have an exact solution to your problem that can scale to millions of images.</strong></p> <p>Here is a link to the abstract, you can find a download link by googleing the title. <a href="http://ieeexplore.ieee.org/xpl/freeabs_all.jsp?arnumber=1641018" rel="noreferrer">http://ieeexplore.ieee.org/xpl/freeabs_all.jsp?arnumber=1641018</a></p> <p>The basic idea is to build a tree with a hierarchical k-means algorithm to model the features and then leverage the sparse distribution of features in that tree to quickly find your nearest neighbors... or something like that, it's been a few years since I worked on it. You can find a powerpoint presentation on the authors webpage here: <a href="http://www.vis.uky.edu/~dnister/Publications/publications.html" rel="noreferrer">http://www.vis.uky.edu/~dnister/Publications/publications.html</a></p> <p>A few other notes:</p> <ul> <li><p>I wouldn't bother with the pyramid match kernel, it's really more for improving object recognition than duplicate/transformed image detection.</p></li> <li><p>I would not store any of this feature stuff in an SQL database. Depending on your application it is <em>sometimes</em> more effective to compute your features on the fly since their size can exceed the original image size when computed densely. Histograms of features or pointers to nodes in a vocabulary tree are much more efficient.</p></li> <li><p>SQL databases are not designed for doing massive floating point vector calculations. <strong>You can store things in your database, but don't use it as a tool for computation.</strong> I tried this once with SQLite and it ended very badly.</p></li> <li><p>If you decide to implement this, read the paper in detail and keep a copy handy while implementing it, as there are many minor details that are very important to making the algorithm work efficiently.</p></li> </ul>
3,992,353
Javascript function to reload a page every X seconds?
<p>A couple of questions:</p> <ul> <li><p>I've never really used JS listeners other than <code>onclick</code> and <code>onkey</code> events, so I wondered if someone could help me with what I need in order to reload the page every X seconds?</p></li> <li><p>Secondly, the page contains bare minimum, literally just one input box. Do I still need to include the html <code>head</code> and <code>body</code>?</p></li> </ul>
3,992,382
4
2
null
2010-10-21 22:01:32.37 UTC
4
2014-12-23 05:09:04.633 UTC
2012-05-09 12:12:14.363 UTC
null
1,223,744
null
477,945
null
1
20
javascript|html|syntax
50,092
<p>You don't need Javascript for this simple function. Add in the page header:</p> <pre><code>&lt;meta http-equiv="Refresh" content="300"&gt; </code></pre> <p>300 is the number of seconds in this example.</p>
3,302,177
Android - Activity Constructor vs onCreate
<p>I understand that Android <code>Activities</code> have specific lifecycles and that <code>onCreate</code> should be overridden and used for initialization, but what exactly happens in the constructor? Are there any cases when you could/should override the <code>Activity</code> constructor as well, or should you never touch it?</p> <p>I'm assuming that the constructor should never be used because references to <code>Activities</code> aren't cleaned up entirely (thus hampering the garbage collector) and that <code>onDestroy</code> is there for that purpose. Is this correct?</p>
3,303,512
4
1
null
2010-07-21 17:44:30.253 UTC
22
2013-07-19 21:46:55.717 UTC
null
null
2,359,478
user370382
2,359,478
null
1
93
java|android|garbage-collection|android-activity|oncreate
53,895
<p>I can't think of any good reason to do anything in the constructor. You never construct an activity directly, so you can't use it to pass in parameters. Generally, just do things in onCreate.</p>
3,436,118
Is Java RegEx case-insensitive?
<p>In Java, when doing a replaceAll to look for a regex pattern like:</p> <pre><code>replaceAll("\\?i\\b(\\w+)\\b(\\s+\\1)+\\b", "$1"); </code></pre> <p>(to remove duplicate consecutive case-insensitive words, e.g. Test test), I'm not sure where I put the <code>?i</code>. I read that it is supposed to be at the beginning, but if I take it out then i catch duplicate consecutive words (e.g. test test), but not case-insensitive words (e.g. Test test). So I thought I could add the ?i in the beginning but that does not seem to get the job done. Any thoughts? Thanks!</p>
3,436,130
5
1
null
2010-08-08 21:21:09.36 UTC
19
2019-05-19 22:31:48.573 UTC
2019-05-19 22:31:48.573 UTC
null
4,928,642
null
207,524
null
1
134
java|regex|case-sensitive
175,793
<p><a href="http://www.regexbuddy.com/" rel="noreferrer">RegexBuddy</a> is telling me if you want to include it at the beginning, this is the correct syntax:</p> <pre><code>"(?i)\\b(\\w+)\\b(\\s+\\1)+\\b" </code></pre>
3,795,923
Bottom button bar in android
<p>I am wondering how it's possible to create bottom bar buttons in android, </p> <p>I read something about this U.I. solution, are there any controls that can be used?</p>
3,795,949
6
0
null
2010-09-25 23:11:31.59 UTC
7
2021-01-30 18:03:10.793 UTC
2018-03-22 22:32:02.36 UTC
null
5,108,735
null
371,301
null
1
21
android
55,562
<p>You can do something like this inside a relative layout</p> <pre><code>&lt;LinearLayout android:id=&quot;@+id/footer&quot; android:layout_width=&quot;fill_parent&quot; android:layout_height=&quot;wrap_content&quot; android:orientation=&quot;horizontal&quot; android:layout_alignParentBottom=&quot;true&quot; style=&quot;@android:style/ButtonBar&quot;&gt; &lt;Button android:id=&quot;@+id/saveButton&quot; android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; android:layout_weight=&quot;1&quot; android:text=&quot;@string/menu_done&quot; /&gt; &lt;Button android:id=&quot;@+id/cancelButton&quot; android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; android:layout_weight=&quot;1&quot; android:text=&quot;@string/menu_cancel&quot; /&gt; &lt;/LinearLayout&gt; </code></pre>
3,234,977
Using jQuery how to get click coordinates on the target element
<p>I have the following event handler for my html element</p> <pre><code>jQuery("#seek-bar").click(function(e){ var x = e.pageX - e.target.offsetLeft; alert(x); }); </code></pre> <p>I need to find the position of the mouse on the #seek-bar at the time of clicking. I would have thought the above code should work, but it gives incorrect result </p>
3,236,129
6
4
null
2010-07-13 07:26:04.317 UTC
40
2018-02-15 11:06:00.61 UTC
2010-07-13 07:32:20.027 UTC
null
294,089
null
294,089
null
1
117
javascript|jquery|html|css|jquery-ui
244,043
<p>Are you trying to get the position of mouse pointer <code>relative</code> to element ( or ) simply the mouse pointer location<br /><br /> Try this Demo : <a href="http://jsfiddle.net/AMsK9/" rel="noreferrer"><strong>http://jsfiddle.net/AMsK9/</strong></a></p> <hr> <h2>Edit :</h2> <p>1) <code>event.pageX</code>, <code>event.pageY</code> gives you the mouse position relative document !</p> <p><strong>Ref</strong> : <a href="http://api.jquery.com/event.pageX/" rel="noreferrer">http://api.jquery.com/event.pageX/</a><br> <a href="http://api.jquery.com/event.pageY/" rel="noreferrer">http://api.jquery.com/event.pageY/</a></p> <p>2) <code>offset()</code> : It gives the offset position of an element</p> <p><strong>Ref</strong> : <a href="http://api.jquery.com/offset/" rel="noreferrer">http://api.jquery.com/offset/</a></p> <p>3) <code>position()</code> : It gives you the relative Position of an element i.e.,</p> <p>consider an element is embedded inside another element </p> <p><strong>example</strong> : </p> <pre><code>&lt;div id="imParent"&gt; &lt;div id="imchild" /&gt; &lt;/div&gt; </code></pre> <p><strong>Ref</strong> : <a href="http://api.jquery.com/position/" rel="noreferrer">http://api.jquery.com/position/</a></p> <p><strong><em>HTML</em></strong></p> <pre><code>&lt;body&gt; &lt;div id="A" style="left:100px;"&gt; Default &lt;br /&gt; mouse&lt;br/&gt;position &lt;/div&gt; &lt;div id="B" style="left:300px;"&gt; offset() &lt;br /&gt; mouse&lt;br/&gt;position &lt;/div&gt; &lt;div id="C" style="left:500px;"&gt; position() &lt;br /&gt; mouse&lt;br/&gt;position &lt;/div&gt; &lt;/body&gt; </code></pre> <p><strong><em>JavaScript</em></strong></p> <pre><code>$(document).ready(function (e) { $('#A').click(function (e) { //Default mouse Position alert(e.pageX + ' , ' + e.pageY); }); $('#B').click(function (e) { //Offset mouse Position var posX = $(this).offset().left, posY = $(this).offset().top; alert((e.pageX - posX) + ' , ' + (e.pageY - posY)); }); $('#C').click(function (e) { //Relative ( to its parent) mouse position var posX = $(this).position().left, posY = $(this).position().top; alert((e.pageX - posX) + ' , ' + (e.pageY - posY)); }); }); </code></pre>
3,590,489
Visual Studio 2010 Intellisense slows down everything
<p>I have the issue with Visual Studio 2010, after a while, running exceptionally slowly and slowing everything else down with it. I'm meaning:</p> <ul> <li>Most other open windows become unresponsive</li> <li>Typing is delayed</li> <li>Build times increase 10-fold</li> <li>Saving takes forever</li> </ul> <p>I am sure this is an Intellisense issue; disabling it solves everything, and when this happens in Task Manager I find a couple of vcpkgsrv.exe (the Intellisense thing) running at about 160,000K memory (This is about the same as an older, less graphical intensive games). However, I would like to run Intellisense. The only way I have of solving this at the moment is to abort these processes when they slow stuff down.</p> <p>I have tried getting the patch and think it is installed, because I cannot install it again.</p> <p>EDIT: I'm running Windows XP, with VSC++ Express. I have 2GB RAM, and a dual core 3.2GHz Processor. Anyone help please?</p>
3,852,810
8
6
null
2010-08-28 11:00:40.83 UTC
9
2021-02-13 13:17:46.517 UTC
null
null
null
null
407,879
null
1
13
visual-studio|visual-studio-2010|intellisense|performance|lag
19,686
<p>I had the same problem with my Windows XP machine. After a long search I found a solution so I'll post it back here since it was the first result I got on google.</p> <p>Install Windows Automation API update for Windows XP (KB971513).</p> <p><a href="https://www.catalog.update.microsoft.com/Search.aspx?q=KB971513" rel="nofollow noreferrer">https://www.catalog.update.microsoft.com/Search.aspx?q=KB971513</a></p>
3,228,984
A better way to validate URL in C# than try-catch?
<p>I'm building an application to retrieve an image from internet. Even though it works fine, it is slow (on wrong given URL) when using try-catch statements in the application. </p> <p>(1) Is this the best way to verify URL and handle wrong input - or should I use Regex (or some other method) instead?</p> <p>(2) Why does the application try to find images locally if I don't specify http:// in the textBox?</p> <pre><code>private void btnGetImage_Click(object sender, EventArgs e) { String url = tbxImageURL.Text; byte[] imageData = new byte[1]; using (WebClient client = new WebClient()) { try { imageData = client.DownloadData(url); using (MemoryStream ms = new MemoryStream(imageData)) { try { Image image = Image.FromStream(ms); pbxUrlImage.Image = image; } catch (ArgumentException) { MessageBox.Show("Specified image URL had no match", "Image Not Found", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } catch (ArgumentException) { MessageBox.Show("Image URL can not be an empty string", "Empty Field", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (WebException) { MessageBox.Show("Image URL is invalid.\nStart with http:// " + "and end with\na proper image extension", "Not a valid URL", MessageBoxButtons.OK, MessageBoxIcon.Information); } } // end of outer using statement } // end of btnGetImage_Click </code></pre> <p><strong>EDIT:</strong> I tried the suggested solution by Panagiotis Kanavos (thank you for your effort!), but it only gets caught in the if-else statement if the user enters <code>http://</code> and nothing more. Changing to UriKind.Absolute catches empty strings as well! Getting closer :) The code as of now:</p> <pre><code>private void btnGetImage_Click(object sender, EventArgs e) { String url = tbxImageURL.Text; byte[] imageData = new byte[1]; Uri myUri; // changed to UriKind.Absolute to catch empty string if (Uri.TryCreate(url, UriKind.Absolute, out myUri)) { using (WebClient client = new WebClient()) { try { imageData = client.DownloadData(myUri); using (MemoryStream ms = new MemoryStream(imageData)) { imageData = client.DownloadData(myUri); Image image = Image.FromStream(ms); pbxUrlImage.Image = image; } } catch (ArgumentException) { MessageBox.Show("Specified image URL had no match", "Image Not Found", MessageBoxButtons.OK, MessageBoxIcon.Error); } catch (WebException) { MessageBox.Show("Image URL is invalid.\nStart with http:// " + "and end with\na proper image extension", "Not a valid URL", MessageBoxButtons.OK, MessageBoxIcon.Information); } } } else { MessageBox.Show("The Image Uri is invalid.\nStart with http:// " + "and end with\na proper image extension", "Uri was not created", MessageBoxButtons.OK, MessageBoxIcon.Information); } </code></pre> <p>I must be doing something wrong here. :(</p>
3,228,997
10
2
null
2010-07-12 13:29:36.383 UTC
9
2019-11-13 19:35:59.557 UTC
2017-08-19 13:35:51.217 UTC
null
1,033,581
null
286,244
null
1
64
c#|image|url|try-catch
54,620
<p>Use <a href="http://msdn.microsoft.com/en-us/library/system.uri.trycreate.aspx" rel="noreferrer">Uri.TryCreate</a> to create a new Uri object only if your url string is a valid URL. If the string is not a valid URL, TryCreate returns false. </p> <pre><code>string myString = "http://someUrl"; Uri myUri; if (Uri.TryCreate(myString, UriKind.RelativeOrAbsolute, out myUri)) { //use the uri here } </code></pre> <p><strong>UPDATE</strong></p> <p>TryCreate or the Uri constructor will happily accept strings that may appear invalid, eg "Host: www.stackoverflow.com","Host:%20www.stackoverflow.com" or "chrome:about". In fact, these are perfectly valid URIs that specify a custom scheme instead of "http". </p> <p>The documentation of the <a href="http://msdn.microsoft.com/en-us/library/system.uri.scheme.aspx" rel="noreferrer">Uri.Scheme</a> property provides more examples like "gopher:" (anyone remember this?), "news", "mailto", "uuid".</p> <p>An application can register itself as a custom protocol handler as described in <a href="http://msdn.microsoft.com/en-us/library/aa767914.aspx" rel="noreferrer">MSDN</a> or other SO questions, eg <a href="https://stackoverflow.com/questions/80650/how-do-i-register-a-custom-url-protocol-in-windows">How do I register a custom URL protocol in Windows?</a></p> <p>TryCreate doesn't provide a way to restrict itself to specific schemes. The code needs to check the Uri.Scheme property to ensure it contains an acceptable value</p> <p><strong>UPDATE 2</strong></p> <p>Passing a weird string like <code>"&gt;&lt;/script&gt;&lt;script&gt;alert(9)&lt;/script&gt;</code> will return <code>true</code> and construct a relative Uri object. Calling <a href="http://msdn.microsoft.com/en-us/library/system.uri.iswellformedoriginalstring%28v=vs.110%29.aspx" rel="noreferrer">Uri.IsWellFormedOriginalString</a> will return false though. So you probably need to call <code>IsWellFormedOriginalString</code> if you want to ensure that relative Uris are well formed.</p> <p>On the other hand, calling <code>TryCreate</code> with <code>UriKind.Absolute</code> will return false in this case.</p> <p>Interestingly, Uri.IsWellFormedUriString calls TryCreate internally and then returns the value of <code>IsWellFormedOriginalString</code> if a relative Uri was created.</p>
3,835,028
Getting list of Facebook friends with latest API
<p>I'm using <a href="http://github.com/facebook/php-sdk/" rel="noreferrer">the most recent version of the Facebook SDK</a> (which lets to connect to something called the 'graph API' though I'm not sure). I've adapted Facebook's example code to let me connect to Facebook and that works... but I can't get a list of my friends.</p> <pre><code>$friends = $facebook-&gt;api('friends.get'); </code></pre> <p>This produces the error message: "Fatal error: Uncaught OAuthException: (#803) Some of the aliases you requested do not exist: friends.get thrown in /mycode/facebook.php on line 543"</p> <p>No clue why that is or what that means. Can someone tell me the right syntax (for the latest Facebook API) to get a list of friends? (I tried "$friends = $facebook->api->friends_get();" and get a different error, "Fatal error: Call to a member function friends_get() on a non-object in /mycode/example.php on line 129".)</p> <p>I can confirm that BEFORE this point in my code, things are fine: I'm connected to Facebook with a valid session and I can get my info and dump it to the screen just... i.e. this code executes perfectly before the failed friends.get call:</p> <pre><code>$session = $facebook-&gt;getSession(); if ($session) { $uid = $facebook-&gt;getUser(); $me = $facebook-&gt;api('/me'); } print_r($me); </code></pre>
3,835,568
11
0
null
2010-09-30 21:38:36.157 UTC
17
2021-06-26 17:21:29.98 UTC
2014-04-12 09:57:24.12 UTC
null
1,045,444
null
284,698
null
1
25
php|facebook|facebook-php-sdk|facebook-apps|facebook-friends
112,233
<p>I think this is what you want:</p> <pre><code>$friends = $facebook-&gt;api('/me/friends'); </code></pre>