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
17,242,649
Can non-static methods modify static variables
<p>I am wondering how a non static method can modify a static variable. I know that static methods can only access other static methods and static variables. However, is the other side true? Can non-static methods access only non-static variables? For example:</p> <pre><code>public class SampleClass { private static int currentCount = 0; public SampleClass() { currentCount++; } public void increaseCount() { currentCount++; } } </code></pre> <p>This code compiles and I would like to know why in terms of static access privledges.</p>
22,182,556
9
4
null
2013-06-21 19:11:05.923 UTC
17
2019-06-25 16:32:07.16 UTC
2019-06-25 16:32:07.16 UTC
null
-1
null
2,399,935
null
1
27
java|methods|static|instance-variables|access-modifiers
104,167
<p>I have found this from <a href="http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html">The Java Tutorials</a></p> <ul> <li>Instance methods can access instance variables and instance methods directly.</li> <li><strong>Instance methods can access class variables and class methods directly.</strong></li> <li>Class methods can access class variables and class methods directly.</li> <li>Class methods cannot access instance variables or instance methods directly—they must use an object reference. Also, class methods cannot use the this keyword as there is no instance for this to refer to.</li> </ul> <p>So the answer is yes, non-static methods CAN modify static variables</p>
17,242,144
Javascript convert HSB/HSV color to RGB accurately
<p>I need to accurately convert HSB to RGB but I am not sure how to get around the problem of turning decimals into whole numbers without rounding. This is the current function I have out of a colorpicker library:</p> <pre><code>HSBToRGB = function (hsb) { var rgb = { }; var h = Math.round(hsb.h); var s = Math.round(hsb.s * 255 / 100); var v = Math.round(hsb.b * 255 / 100); if (s == 0) { rgb.r = rgb.g = rgb.b = v; } else { var t1 = v; var t2 = (255 - s) * v / 255; var t3 = (t1 - t2) * (h % 60) / 60; if (h == 360) h = 0; if (h &lt; 60) { rgb.r = t1; rgb.b = t2; rgb.g = t2 + t3 } else if (h &lt; 120) { rgb.g = t1; rgb.b = t2; rgb.r = t1 - t3 } else if (h &lt; 180) { rgb.g = t1; rgb.r = t2; rgb.b = t2 + t3 } else if (h &lt; 240) { rgb.b = t1; rgb.r = t2; rgb.g = t1 - t3 } else if (h &lt; 300) { rgb.b = t1; rgb.g = t2; rgb.r = t2 + t3 } else if (h &lt; 360) { rgb.r = t1; rgb.g = t2; rgb.b = t1 - t3 } else { rgb.r = 0; rgb.g = 0; rgb.b = 0 } } return { r: Math.round(rgb.r), g: Math.round(rgb.g), b: Math.round(rgb.b) }; </code></pre> <p>As you can see the inaccuracy in this function comes from the Math.round</p>
17,243,070
6
4
null
2013-06-21 18:36:47.897 UTC
16
2020-10-28 18:35:53.893 UTC
2016-09-15 18:52:14.337 UTC
null
6,599,590
null
1,174,574
null
1
50
javascript|converter|rgb|hsv|hsb
65,556
<p>From <a href="https://stackoverflow.com/users/1041853/parthik-gosar">Parthik Gosar</a>'s <a href="http://axonflux.com/handy-rgb-to-hsl-and-rgb-to-hsv-color-model-c" rel="noreferrer">link</a> in <a href="https://stackoverflow.com/questions/17242144/#comment24984878_17242144">this comment</a> with slight modification to let you enter each value independently or all at once as an object</p> <pre><code>/* accepts parameters * h Object = {h:x, s:y, v:z} * OR * h, s, v */ function HSVtoRGB(h, s, v) { var r, g, b, i, f, p, q, t; if (arguments.length === 1) { s = h.s, v = h.v, h = h.h; } i = Math.floor(h * 6); f = h * 6 - i; p = v * (1 - s); q = v * (1 - f * s); t = v * (1 - (1 - f) * s); switch (i % 6) { case 0: r = v, g = t, b = p; break; case 1: r = q, g = v, b = p; break; case 2: r = p, g = v, b = t; break; case 3: r = p, g = q, b = v; break; case 4: r = t, g = p, b = v; break; case 5: r = v, g = p, b = q; break; } return { r: Math.round(r * 255), g: Math.round(g * 255), b: Math.round(b * 255) }; } </code></pre> <p>This code expects <code>0 &lt;= h, s, v &lt;= 1</code>, if you're using degrees or radians, remember to divide them out.</p> <p>The returned <code>0 &lt;= r, g, b &lt;= 255</code> are rounded to the nearest <em>Integer</em>. If you don't want this behaviour remove the <code>Math.round</code>s from the returned object.</p> <hr> <p>And the reverse (with less division)</p> <pre><code>/* accepts parameters * r Object = {r:x, g:y, b:z} * OR * r, g, b */ function RGBtoHSV(r, g, b) { if (arguments.length === 1) { g = r.g, b = r.b, r = r.r; } var max = Math.max(r, g, b), min = Math.min(r, g, b), d = max - min, h, s = (max === 0 ? 0 : d / max), v = max / 255; switch (max) { case min: h = 0; break; case r: h = (g - b) + d * (g &lt; b ? 6: 0); h /= 6 * d; break; case g: h = (b - r) + d * 2; h /= 6 * d; break; case b: h = (r - g) + d * 4; h /= 6 * d; break; } return { h: h, s: s, v: v }; } </code></pre> <p>This code will output <code>0 &lt;= h, s, v &lt;= 1</code>, but this time takes any <code>0 &lt;= r, g, b &lt;= 255</code> (does not need to be an integer)</p> <hr> <p>For completeness,</p> <pre><code>function HSVtoHSL(h, s, v) { if (arguments.length === 1) { s = h.s, v = h.v, h = h.h; } var _h = h, _s = s * v, _l = (2 - s) * v; _s /= (_l &lt;= 1) ? _l : 2 - _l; _l /= 2; return { h: _h, s: _s, l: _l }; } function HSLtoHSV(h, s, l) { if (arguments.length === 1) { s = h.s, l = h.l, h = h.h; } var _h = h, _s, _v; l *= 2; s *= (l &lt;= 1) ? l : 2 - l; _v = (l + s) / 2; _s = (2 * s) / (l + s); return { h: _h, s: _s, v: _v }; } </code></pre> <p>All of these values should be in the range <code>0</code> to <code>1</code>. For <em><code>HSL&lt;-&gt;RGB</code></em> go via <em>HSV</em>.</p>
17,544,151
Why does Java's BigInteger have TEN and ONE as constants? Any Practical use?
<p>Why does BigInteger class has constant TEN and ONE? Any practical uses for having them as constants? I can understand some use cases for ZERO. </p>
17,545,059
5
9
null
2013-07-09 09:04:15.64 UTC
2
2013-07-09 18:00:59.887 UTC
2013-07-09 17:49:49.47 UTC
null
866,022
null
1,876,342
null
1
59
java
16,608
<p>Let's say you have written a function that returns <code>BigInteger</code> after some calculations and db operations. You often may need to return values like null, 0, 1. It's easy to return <code>BigInteger.ZERO</code>. This values are public since they are needed <strong>commonly</strong>.</p> <pre><code>public BigInteger findMyLovelyBigInteger(Integer secretNumber) { if (secretNumber == null) { return BigInteger.ZERO; // better than BigInteger.valueOf(0); } else { // some db operations } } </code></pre> <p>Also <code>BigInteger.TEN</code> is commonly used for power/divide/mod operations.</p> <p>Checkout <code>BigInteger</code> public methods. You will easily see their common use cases.</p>
17,604,071
Parse XML using JavaScript
<p>I need to be able to parse XML using JavaScript. The XML will be in a variable. I would prefer not to use jQuery or other frameworks.</p> <p>I have looked at this, <a href="https://stackoverflow.com/questions/14782408/xml-jquery-reading">XML > jQuery reading</a>.</p>
17,604,312
2
1
null
2013-07-11 21:45:37.577 UTC
57
2019-02-14 17:15:59.687 UTC
2016-09-21 19:35:54.82 UTC
null
1,190,388
null
2,574,350
null
1
118
javascript|xml|domparser
358,596
<p>I'm guessing from your <a href="https://stackoverflow.com/questions/17603738/convert-latitude-longitude-to-address">last question</a>, asked 20 minutes before this one, that you are trying to parse (read and convert) the XML found through using GeoNames' FindNearestAddress.</p> <p>If your XML is in a string variable called <code>txt</code> and looks like this:</p> <pre><code>&lt;address&gt; &lt;street&gt;Roble Ave&lt;/street&gt; &lt;mtfcc&gt;S1400&lt;/mtfcc&gt; &lt;streetNumber&gt;649&lt;/streetNumber&gt; &lt;lat&gt;37.45127&lt;/lat&gt; &lt;lng&gt;-122.18032&lt;/lng&gt; &lt;distance&gt;0.04&lt;/distance&gt; &lt;postalcode&gt;94025&lt;/postalcode&gt; &lt;placename&gt;Menlo Park&lt;/placename&gt; &lt;adminCode2&gt;081&lt;/adminCode2&gt; &lt;adminName2&gt;San Mateo&lt;/adminName2&gt; &lt;adminCode1&gt;CA&lt;/adminCode1&gt; &lt;adminName1&gt;California&lt;/adminName1&gt; &lt;countryCode&gt;US&lt;/countryCode&gt; &lt;/address&gt; </code></pre> <p>Then you can parse the XML with Javascript DOM like this:</p> <pre class="lang-js prettyprint-override"><code>if (window.DOMParser) { parser = new DOMParser(); xmlDoc = parser.parseFromString(txt, "text/xml"); } else // Internet Explorer { xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); xmlDoc.async = false; xmlDoc.loadXML(txt); } </code></pre> <p>And get specific values from the nodes like this:</p> <pre class="lang-js prettyprint-override"><code>//Gets house address number xmlDoc.getElementsByTagName("streetNumber")[0].childNodes[0].nodeValue; //Gets Street name xmlDoc.getElementsByTagName("street")[0].childNodes[0].nodeValue; //Gets Postal Code xmlDoc.getElementsByTagName("postalcode")[0].childNodes[0].nodeValue; </code></pre> <p><a href="http://jsfiddle.net/D2QpZ/" rel="noreferrer">JSFiddle</a></p> <hr> <h2>Feb. 2019 edit:</h2> <p>In response to @gaugeinvariante's concerns about xml with Namespace prefixes. Should you have a need to parse xml with Namespace prefixes, everything should work almost identically:</p> <p><strong><em>NOTE: this will only work in browsers that support xml namespace prefixes such as Microsoft Edge</em></strong></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>// XML with namespace prefixes 's', 'sn', and 'p' in a variable called txt txt = ` &lt;address xmlns:p='example.com/postal' xmlns:s='example.com/street' xmlns:sn='example.com/streetNum'&gt; &lt;s:street&gt;Roble Ave&lt;/s:street&gt; &lt;sn:streetNumber&gt;649&lt;/sn:streetNumber&gt; &lt;p:postalcode&gt;94025&lt;/p:postalcode&gt; &lt;/address&gt;`; //Everything else the same if (window.DOMParser) { parser = new DOMParser(); xmlDoc = parser.parseFromString(txt, "text/xml"); } else // Internet Explorer { xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); xmlDoc.async = false; xmlDoc.loadXML(txt); } //The prefix should not be included when you request the xml namespace //Gets "streetNumber" (note there is no prefix of "sn" console.log(xmlDoc.getElementsByTagName("streetNumber")[0].childNodes[0].nodeValue); //Gets Street name console.log(xmlDoc.getElementsByTagName("street")[0].childNodes[0].nodeValue); //Gets Postal Code console.log(xmlDoc.getElementsByTagName("postalcode")[0].childNodes[0].nodeValue);</code></pre> </div> </div> </p>
17,628,670
File Explorer in Android Studio
<p>Can anyone tell where the file explorer is located in Android Studio?</p> <p>I tried to search in windows menu but there isn't any option like "show view" that used to be in Eclipse.</p>
17,628,916
17
1
null
2013-07-13 09:08:13.097 UTC
16
2021-02-24 07:35:01.687 UTC
2019-07-31 15:49:47.867 UTC
null
6,214,491
null
2,507,902
null
1
145
android|android-studio
215,670
<p>You can start Android Device Monitor from the Android Studio (green robot icon on the toolbar, to the left of the help icon). From the ADM, select the device/emulator, then select the File Explorer tab.</p>
17,454,235
How to Git stash pop specific stash in 1.8.3?
<p>I just upgraded Git. I'm on Git version 1.8.3.</p> <p>This morning I tried to unstash a change 1 deep in the stack.</p> <p>I ran <code>git stash pop stash@{1}</code> and got this error.</p> <blockquote> <p>fatal: ambiguous argument 'stash@1': unknown revision or path not in the working tree. Use '--' to separate paths from revisions, like this: 'git [...] -- [...]'</p> </blockquote> <p>I've tried about 20+ variations on this as well as using <code>apply</code> instead of <code>pop</code> with no success. What's changed? Anyone else encounter this?</p>
17,454,945
10
2
null
2013-07-03 17:12:17.24 UTC
69
2022-07-05 05:39:02.647 UTC
2019-08-22 11:21:25.903 UTC
null
965,146
null
762,889
null
1
456
git|escaping|git-stash
324,239
<pre><code>git stash apply n </code></pre> <p>works as of git version 2.11</p> <p>Original answer, possibly helping to debug issues with the older syntax involving shell escapes:</p> <p>As pointed out previously, the curly braces may require escaping or quoting depending on your OS, shell, etc.</p> <p>See "<a href="https://stackoverflow.com/questions/6468893/stash1-is-ambiguous">stash@{1} is ambiguous?</a>" for some detailed hints of what may be going wrong, and how to work around it in various shells and platforms.</p> <pre><code>git stash list git stash apply stash@{n} </code></pre> <p><a href="https://stackoverflow.com/questions/1910082/git-stash-apply-version/1910142#1910142">git stash apply version</a></p>
30,670,310
What do [] brackets in a for loop in python mean?
<p>I'm parsing JSON objects and found this sample line of code which I kind of understand but would appreciate a more detailed explanation of:</p> <pre><code>for record in [x for x in records.split("\n") if x.strip() != '']: </code></pre> <p>I know it is spliting records to get individual records by the new line character however I was wondering why it looks so complicated? is it a case that we can't have something like this:</p> <pre><code>for record in records.split("\n") if x.strip() != '']: </code></pre> <p>So what do the brackets do []? and why do we have x twice in <code>x for x in records.split....</code></p> <p>Thanks</p>
30,670,389
3
4
null
2015-06-05 15:25:44.28 UTC
6
2018-09-02 01:39:54.187 UTC
null
null
null
null
218,183
null
1
19
python
45,898
<p>The "brackets" in your example constructs a new list from an old one, this is called <a href="https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions" rel="noreferrer">list comprehension</a>.</p> <p>The basic idea with <code>[f(x) for x in xs if condition]</code> is:</p> <pre><code>def list_comprehension(xs): result = [] for x in xs: if condition: result.append(f(x)) return result </code></pre> <p>The <code>f(x)</code> can be any expression, containing <code>x</code> or not.</p>
18,474,791
Decreasing the size of cPickle objects
<p>I am running code that creates large objects, containing multiple user-defined classes, which I must then serialize for later use. From what I can tell, only pickling is versatile enough for my requirements. I've been using cPickle to store them but the objects it generates are approximately 40G in size, from code that runs in 500 mb of memory. Speed of serialization isn't an issue, but size of the object is. Are there any tips or alternate processes I can use to make the pickles smaller? </p>
18,475,192
3
6
null
2013-08-27 20:27:40.637 UTC
22
2018-06-17 14:40:06.823 UTC
null
null
null
null
1,502,141
null
1
35
python|serialization|pickle
27,437
<p>If you must use pickle and no other method of serialization works for you, you can always pipe the pickle through <code>bzip2</code>. The only problem is that <code>bzip2</code> is a little bit slowish... <code>gzip</code> should be faster, but the file size is almost 2x bigger:</p> <pre><code>In [1]: class Test(object): def __init__(self): self.x = 3841984789317471348934788731984731749374 self.y = 'kdjsaflkjda;sjfkdjsf;klsdjakfjdafjdskfl;adsjfl;dasjf;ljfdlf' l = [Test() for i in range(1000000)] In [2]: import cPickle as pickle with open('test.pickle', 'wb') as f: pickle.dump(l, f) !ls -lh test.pickle -rw-r--r-- 1 viktor staff 88M Aug 27 22:45 test.pickle In [3]: import bz2 import cPickle as pickle with bz2.BZ2File('test.pbz2', 'w') as f: pickle.dump(l, f) !ls -lh test.pbz2 -rw-r--r-- 1 viktor staff 2.3M Aug 27 22:47 test.pbz2 In [4]: import gzip import cPickle as pickle with gzip.GzipFile('test.pgz', 'w') as f: pickle.dump(l, f) !ls -lh test.pgz -rw-r--r-- 1 viktor staff 4.8M Aug 27 22:51 test.pgz </code></pre> <p>So we see that the file size of the <code>bzip2</code> is almost 40x smaller, <code>gzip</code> is 20x smaller. And gzip is pretty close in performance to the raw cPickle, as you can see:</p> <pre><code>cPickle : best of 3: 18.9 s per loop bzip2 : best of 3: 54.6 s per loop gzip : best of 3: 24.4 s per loop </code></pre>
23,384,348
PDF External Signature
<p><img src="https://i.stack.imgur.com/nTMnw.png" alt="enter image description here"></p> <p><strong>Client=My application</strong>, <strong>Server=MSSP(Mobile Signature Services Provider)</strong></p> <p>Server is sign only the hash values. </p> <p>Data to be sign:</p> <p>*Base64 encoded SHA-1 digest of data to be signed. (28 characters)</p> <p>*Base64 encoded SHA-256 digest of data to be signed. (44 characters)</p> <p>*Base64 encoded SHA-384 digest of data to be signed. (64 characters)</p> <p>*Base64 encoded SHA-512 digest of data to be signed. (88 characters)</p> <p>*Base64 encoded DER encoded PKCS#1 DigestInfo to sign.</p> <p>I want to external signature for pdf. I wrote the below code. But I get an error when opened the document with adobe.</p> <p>Error:</p> <p>modified or corrupted after the document is signed </p> <p>Note: I use MSSP(Mobile Signature Service Provider) architecture. DataToBeSigned.length should be 44 for SHA256 algorithm.</p> <p>My operation code:</p> <pre><code> import com.itextpdf.text.Rectangle; import com.itextpdf.text.pdf.PdfDate; import com.itextpdf.text.pdf.PdfDictionary; import com.itextpdf.text.pdf.PdfName; import com.itextpdf.text.pdf.PdfReader; import com.itextpdf.text.pdf.PdfSignature; import com.itextpdf.text.pdf.PdfSignatureAppearance; import com.itextpdf.text.pdf.PdfStamper; import com.itextpdf.text.pdf.PdfString; import com.itextpdf.text.pdf.security.DigestAlgorithms; import com.itextpdf.text.pdf.security.ExternalDigest; import com.itextpdf.text.pdf.security.MakeSignature.CryptoStandard; import com.itextpdf.text.pdf.security.PdfPKCS7; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.security.GeneralSecurityException; import java.security.MessageDigest; import java.security.Security; import java.security.cert.X509Certificate; import java.util.Calendar; import java.util.HashMap; import org.bouncycastle.jce.provider.BouncyCastleProvider; /** * * @author murat.demir */ public class PdfSignOperation { private byte[] content = null; private X509Certificate x509Certificate; private PdfReader reader = null; private ByteArrayOutputStream baos = null; private PdfStamper stamper = null; private PdfSignatureAppearance sap = null; private PdfSignature dic = null; private HashMap&lt;PdfName, Integer&gt; exc = null; private ExternalDigest externalDigest = null; private PdfPKCS7 sgn = null; private InputStream data = null; private byte hash[] = null; private Calendar cal = null; private byte[] sh = null; private byte[] encodedSig = null; private byte[] paddedSig = null; private PdfDictionary dic2 = null; private X509Certificate[] chain = null; static { Security.addProvider(new BouncyCastleProvider()); } public PdfSignOperation(byte[] content, X509Certificate cert) { this.content = content; this.x509Certificate = cert; } public byte[] getHash() throws Exception { reader = new PdfReader(new ByteArrayInputStream(content)); baos = new ByteArrayOutputStream(); stamper = PdfStamper.createSignature(reader, baos, '\0'); sap = stamper.getSignatureAppearance(); sap.setReason("Test"); sap.setLocation("On a server!"); sap.setVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "sig"); sap.setCertificate(x509Certificate); dic = new PdfSignature(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED); dic.setReason(sap.getReason()); dic.setLocation(sap.getLocation()); dic.setContact(sap.getContact()); dic.setDate(new PdfDate(sap.getSignDate())); sap.setCryptoDictionary(dic); exc = new HashMap&lt;PdfName, Integer&gt;(); exc.put(PdfName.CONTENTS, new Integer(8192 * 2 + 2)); sap.preClose(exc); externalDigest = new ExternalDigest() { @Override public MessageDigest getMessageDigest(String hashAlgorithm) throws GeneralSecurityException { return DigestAlgorithms.getMessageDigest(hashAlgorithm, null); } }; chain = new X509Certificate[1]; chain[0] = x509Certificate; sgn = new PdfPKCS7(null, chain, "SHA256", null, externalDigest, false); data = sap.getRangeStream(); cal = Calendar.getInstance(); hash = DigestAlgorithms.digest(data, externalDigest.getMessageDigest("SHA256")); sh = sgn.getAuthenticatedAttributeBytes(hash, cal, null, null, CryptoStandard.CMS); sh = DigestAlgorithms.digest(new ByteArrayInputStream(sh), externalDigest.getMessageDigest("SHA256")); return sh; } public String complateToSignature(byte[] signedHash) throws Exception { sgn.setExternalDigest(signedHash, null, "RSA"); encodedSig = sgn.getEncodedPKCS7(hash, cal, null, null, null, CryptoStandard.CMS); paddedSig = new byte[8192]; System.arraycopy(encodedSig, 0, paddedSig, 0, encodedSig.length); dic2 = new PdfDictionary(); dic2.put(PdfName.CONTENTS, new PdfString(paddedSig).setHexWriting(true)); sap.close(dic2); return Base64.encodeBytes(baos.toByteArray()); } } </code></pre> <p>My test code :</p> <pre><code> public static void main(String[] args) throws Exception { TokenService.refreshAllTokens(); String alias = "alias"; String pin = "1234"; TokenService.setAliasPin(alias, pin); File pdf = new File("E:/sample.pdf"); FileInputStream is = new FileInputStream(pdf); byte[] content = new byte[is.available()]; is.read(content); X509Certificate certificate = null; for (CertInfo certInfo : TokenService.getCertificates().values()) { if (certInfo.cert != null) { certificate = certInfo.cert; } } PdfSignOperation operation = new PdfSignOperation(content, certificate); byte[] hash = operation.getHash(); //simule control for mobile signature. String encodeData = Base64.encodeBytes(hash); if (encodeData.length() != 44) { throw new Exception("Sign to data must be 44 characters"); } // This function is local in the test run function (Simulated MSSP mobile signature) // return a signed message digest byte[] signedData = TokenService.sign(encodeData, alias); //Combine signed hash value with pdf. System.out.println(operation.complateToSignature(signedData)); } </code></pre> <p><a href="https://www.dropbox.com/s/3grt2i9dre23zuk/remote_token6.pdf" rel="nofollow noreferrer">SignedPDF</a> </p> <p>Update:</p> <p>I tried with the old library version and successful signature operation. My new code:</p> <pre><code>InputStream data = sap.getRangeStream(); X509Certificate[] chain = new X509Certificate[1]; chain[0] = userCert; PdfPKCS7 sgn = new PdfPKCS7(null, chain, null, algorithm, null, false); MessageDigest digest = MessageDigest.getInstance("SHA256", "BC"); byte[] buf = new byte[8192]; int n; while ((n = data.read(buf, 0, buf.length)) &gt; 0) { digest.update(buf, 0, n); } byte hash[] = digest.digest(); logger.info("PDF hash created"); Calendar cal = Calendar.getInstance(); byte[] ocsp = null; byte sh[] = sgn.getAuthenticatedAttributeBytes(hash, cal, ocsp); sh = MessageDigest.getInstance("SHA256", "BC").digest(sh); final String encode = Utils.base64Encode(sh); SignatureService service = new SignatureService(); logger.info("PDF hash sended to sign for web service"); MobileSignResponse signResponse = service.mobileSign(mobilePhone, signText, encode, timeout, algorithm, username, password, "profile2#sha256", signWsdl); if (!signResponse.getStatusCode().equals("0")) { throw new Exception("Signing fails.\n" + signResponse.getStatusMessage()); } byte[] signedHashValue = Utils.base64Decode(signResponse.getSignature()); sgn.setExternalDigest(signedHashValue, null, "RSA"); byte[] paddedSig = new byte[csize]; byte[] encodedSig = sgn.getEncodedPKCS7(hash, cal, null, ocsp); System.arraycopy(encodedSig, 0, paddedSig, 0, encodedSig.length); if (csize + 2 &lt; encodedSig.length) { throw new Exception("Not enough space for signature"); } PdfDictionary dic2 = new PdfDictionary(); dic2.put(PdfName.CONTENTS, new PdfString(paddedSig).setHexWriting(true)); sap.close(dic2); logger.info("Signing successful"); </code></pre>
23,391,722
1
6
null
2014-04-30 09:25:27.607 UTC
9
2016-06-30 06:09:54.697 UTC
2014-05-05 15:49:14.39 UTC
user2496352
null
user2496352
null
null
1
2
java|pdf|itext|digital-signature
6,515
<p>In <code>getHash</code> you build the signed PDF (only the actual signature area is filled with '00' instead of signature bytes), calculate the hash of the byte range and return this hash.</p> <p>In your <code>main</code> you sign this returned hash as is.</p> <p>In <code>complateToSignature</code> you then insert this into the prepared <code>PdfPKCS7</code> structure.</p> <p>This is not correct, though: The hash which is signed in a PKCS7 / CMS signature is not the hash of the document (unless you have the most primitive form of a PKCS7 container) but the hash of the <strong>signed attributes</strong> (the hash of the document is but the value of only one of these attributes), also known as <em>authenticated attributes</em>.</p> <p>Thus, you have to generate the signed attributes using the document hash you calculated, and then (hash and) sign this structure.</p> <p>Have a look at iText's <a href="http://svn.code.sf.net/p/itext/code/trunk/itext/src/main/java/com/itextpdf/text/pdf/security/MakeSignature.java" rel="nofollow"><code>MakeSignature.signDetached</code></a> and work it out in parallel:</p> <pre><code>String hashAlgorithm = externalSignature.getHashAlgorithm(); PdfPKCS7 sgn = new PdfPKCS7(null, chain, hashAlgorithm, null, externalDigest, false); InputStream data = sap.getRangeStream(); byte hash[] = DigestAlgorithms.digest(data, externalDigest.getMessageDigest(hashAlgorithm)); Calendar cal = Calendar.getInstance(); byte[] ocsp = null; if (chain.length &gt;= 2 &amp;&amp; ocspClient != null) { ocsp = ocspClient.getEncoded((X509Certificate) chain[0], (X509Certificate) chain[1], null); } byte[] sh = sgn.getAuthenticatedAttributeBytes(hash, cal, ocsp, crlBytes, sigtype); byte[] extSignature = externalSignature.sign(sh); sgn.setExternalDigest(extSignature, null, externalSignature.getEncryptionAlgorithm()); </code></pre> <p><strong>PS:</strong> When trying to transfer that code to your use case, please be aware of a major difference between the <code>ExternalSignature</code> method <code>sign</code> used here and your <code>TokenService</code> method <code>sign</code>:</p> <p><code>ExternalSignature.sign</code> is documented as:</p> <pre><code>/** * Signs it using the encryption algorithm in combination with * the digest algorithm. * @param message the message you want to be hashed and signed * @return a signed message digest * @throws GeneralSecurityException */ public byte[] sign(byte[] message) throws GeneralSecurityException; </code></pre> <p>So this method does both hash and sign.</p> <p>In case of your method <code>TokenService.sign</code>, though, if you</p> <blockquote> <p>use the sha256 algorithm, sign to data must be 44 characters</p> </blockquote> <p>so the data you forward to that method seems to have to be already hashed (44 characters are needed for a base64 encoded SHA-256 hash value).</p> <p><strong>Thus, you have to calculate the hash of <code>sh</code> and forward this hash to <code>TokenService.sign</code> instead of the original signed attributes.</strong></p>
23,083,462
How to get an IFrame to be responsive in iOS Safari?
<p>The problem is that when you have to use IFrames to insert content into a website, then in the modern web-world it is expected that the IFrame would be responsive as well. In theory it's simple, simply aider use <code>&lt;iframe width="100%"&gt;&lt;/iframe&gt;</code> or set the CSS width to <code>iframe { width: 100%; }</code> however in practice it's not quite that simple, but it can be.</p> <p>If the <code>iframe</code> content is fully responsive and can resize itself without internal scroll bars, then iOS Safari will resize the <code>iframe</code> without any real issues.</p> <p>If you consider the following code:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;meta http-equiv="X-UA-Compatible" content="IE=9,10,11" /&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1" /&gt; &lt;title&gt;Iframe Isolation Test&lt;/title&gt; &lt;style type="text/css" rel="stylesheet"&gt; #Main { padding: 10px; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;Iframe Isolation Test 13.17&lt;/h1&gt; &lt;div id="Main"&gt; &lt;iframe height="950" width="100%" src="Content.html"&gt;&lt;/iframe&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>With the <em>Content.html</em>:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;meta http-equiv="X-UA-Compatible" content="IE=9,10,11" /&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1" /&gt; &lt;title&gt;Iframe Isolation Test - Content&lt;/title&gt; &lt;style type="text/css" rel="stylesheet"&gt; #Main { width: 100%; background: #ccc; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="Main"&gt; &lt;div id="ScrolledArea"&gt; Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc malesuada purus quis commodo convallis. Fusce consectetur mauris eget purus tristique blandit. Nam nec volutpat augue. Aliquam sit amet augue vitae orci fermentum tempor sit amet gravida augue. Pellentesque convallis velit eu malesuada malesuada. Aliquam erat volutpat. Nam sollicitudin nulla nec neque viverra, non suscipit purus tincidunt. Aenean blandit nisi felis, sit amet ornare mi vestibulum ac. Praesent ultrices varius arcu quis fringilla. In vitae dui consequat, rutrum sapien ut, aliquam metus. Proin sit amet porta velit, suscipit dignissim arcu. Cras bibendum tellus eu facilisis sodales. Vestibulum posuere, magna ut iaculis consequat, tortor erat vulputate diam, ut pharetra sapien massa ut magna. Donec massa purus, pharetra sed pellentesque nec, posuere ut velit. Nam venenatis feugiat odio quis tristique. &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Then this works without issues in iOS 7.1 Safari. You can change between landscape and portrait without any issues.</p> <p><img src="https://i.stack.imgur.com/5VA6C.png" alt="enter image description here"> <img src="https://i.stack.imgur.com/0p1Rs.png" alt="enter image description here"></p> <p>However by simply changing the <em>Content.html</em> CSS by adding this:</p> <pre><code> #ScrolledArea { width: 100%; overflow: scroll; white-space: nowrap; background: #ff0000; } </code></pre> <p>You get this:</p> <p><img src="https://i.stack.imgur.com/y1D6C.png" alt="enter image description here"> <img src="https://i.stack.imgur.com/fRIQ0.png" alt="enter image description here"></p> <p>As you can see, even though the <em>Content.html</em> content is fully responsive (<em>div#ScrolledArea</em> has <code>overflow: scroll</code> set) and the iframe width is 100% the iframe still takes the full width of the <em>div#ScrolledArea</em> as if the overflow does not even exist. <a href="http://www.idra.pri.ee/sample/IframeIsolationTest/">Demo</a></p> <p>In cases like this, were the <code>iframe</code>content has scrolling areas on it, the question becomes, how to get the <code>iframe</code> responsive, when the iframe content has horizontally scrolling areas? The problem here is not in the fact that the <em>Content.html</em> is not responsive, but in the fact that the iOS Safari simply resizes the iframe so that the <code>div#ScrolledArea</code> would be fully visible.</p>
23,083,463
10
8
null
2014-04-15 12:15:42.163 UTC
75
2022-01-30 22:12:01.083 UTC
2014-04-16 10:41:07.533 UTC
null
2,992,452
null
2,992,452
null
1
141
html|css|iframe
211,515
<p>The solution for this problem is actually quite simple and there are two ways to go about it. If you have control over the <em>Content.html</em> then simply change the <code>div#ScrolledArea</code> width CSS to:</p> <pre><code>width: 1px; min-width: 100%; *width: 100%; </code></pre> <p>Basically the idea here is simple, you set the <code>width</code> to something that is smaller than the viewport (iframe width in this case) and then overwrite it with <code>min-width: 100%</code> to allow for actual <code>width: 100%</code> which iOS Safari by default overwrites. The <code>*width: 100%;</code> is there so the code would remain IE6 compatible, but if you do not care for IE6 you can omit it. <a href="http://www.idra.pri.ee/sample/IframeIsolationTest/ContentSolution/" rel="nofollow noreferrer">Demo</a></p> <p><img src="https://i.stack.imgur.com/grCPv.png" alt="enter image description here" /> <img src="https://i.stack.imgur.com/EfPQw.png" alt="enter image description here" /></p> <p>As you can see now, the <code>div#ScrolledArea</code> width is actually 100% and the <code>overflow: scroll;</code> can do it's thing and hide the overflowing content. If you have access to the iframe content, then this is preferable.</p> <p>However if you do not have access to the iframe content (for what ever reason) then you can actually use the same technique on the iframe itself. Simply use the same CSS on the iframe:</p> <pre><code>iframe { width: 1px; min-width: 100%; *width: 100%; } </code></pre> <p>However, there is one limitation with this, you need to turn off the scrollbars with <code>scrolling=&quot;no&quot;</code> on the iframe for this to work:</p> <pre><code>&lt;iframe height=&quot;950&quot; width=&quot;100%&quot; scrolling=&quot;no&quot; src=&quot;Content.html&quot;&gt;&lt;/iframe&gt; </code></pre> <p>If the scrollbars are allowed, then this wont work on the iframe anymore. That said, if you modify the <em>Content.html</em> instead then you can retain the scrolling in the iframe. <a href="http://www.idra.pri.ee/sample/IframeIsolationTest/IframeSolution/" rel="nofollow noreferrer">Demo</a></p>
5,194,666
Disable randomization of memory addresses
<p>I'm trying to debug a binary that uses a lot of pointers. Sometimes for seeing output quickly to figure out errors, I print out the address of objects and their corresponding values, however, the object addresses are randomized and this defeats the purpose of this quick check up. Is there a way to disable this temporarily/permanently so that I get the same values every time I run the program.</p> <p>Oops. OS is <code>Linux fsttcs1 2.6.32-28-generic #55-Ubuntu SMP Mon Jan 10 23:42:43 UTC 2011 x86_64 GNU/Linux</code></p>
5,194,709
3
1
null
2011-03-04 13:58:55.713 UTC
22
2021-05-19 22:25:18.053 UTC
2015-10-28 20:45:17.893 UTC
null
895,245
null
247,077
null
1
41
linux|memory-address|aslr
36,260
<p>On Ubuntu , it can be disabled with...</p> <pre><code>echo 0 &gt; /proc/sys/kernel/randomize_va_space </code></pre> <p>On Windows, this post might be of some help...</p> <p><a href="http://blog.didierstevens.com/2007/11/20/quickpost-another-funny-vista-trick-with-aslr/" rel="noreferrer">http://blog.didierstevens.com/2007/11/20/quickpost-another-funny-vista-trick-with-aslr/</a></p>
25,550,244
What does "others=>'0'" mean in an assignment statement?
<pre><code>cmd_register: process (rst_n, clk) begin if (rst_n='0') then cmd_r&lt;= (others=&gt;'0'); elsif (clk'event and clk='1') then cmd_r&lt;=...; end if; end process cmd_register; </code></pre> <p>I know "&lt;=" specifies assignment but what is <code>others</code>? And what does <code>=&gt;</code> do?</p>
25,550,575
4
2
null
2014-08-28 13:38:43.847 UTC
3
2018-11-21 10:36:39.32 UTC
2014-08-28 19:22:07.963 UTC
user1155120
null
null
3,986,913
null
1
13
if-statement|process|vhdl|fpga
81,774
<p>cmd_r is defined as a <strong>std_logic_vector</strong>, or <strong>unsigned</strong> or <strong>signed</strong> signal. let's see how this signal type are defined:</p> <pre><code>type std_logic_vector is array (natural range &lt;&gt;) of std_logic; type unsigned is array (natural range &lt;&gt;) of std_logic; type signed is array (natural range &lt;&gt;) of std_logic; </code></pre> <p>Note that these 3 types have the same definition as an array of std_logic items.</p> <p>The statement "Others => '0'" is a feature of the VHDL when the coder want to defined several items in an array with the same value.</p> <p>In your example, all item std_logic in the array are set to '0'.</p> <p>Another application of this statement is to set some items at a specific value and all others at a default value : </p> <pre><code>cmd_r &lt;= (0 =&gt; '1', 4 =&gt; '1', others =&gt; '0'); </code></pre> <p>In this case, the bit 0 and 4 are set to '1' and all other bits are set to '0'.</p> <p>One last thing, it's <strong>NOT possible</strong> to write something like this :</p> <pre><code> cmd_r &lt;= (0 =&gt; '1', 4 downto 2 =&gt; "111", -- this line is wrong !!! others =&gt; '0'); </code></pre>
9,362,907
How can I reference the <HTML> element's corresponding DOM object?
<p>This is how you access the <code>&lt;body&gt;</code> element to set a background style:</p> <pre><code>document.body.style.background = ''; </code></pre> <p>But how can I access the <code>&lt;html&gt;</code> element in a similar manner? The following doesn't work:</p> <pre><code>document.html.style.background = ''; </code></pre>
9,362,944
3
4
null
2012-02-20 14:39:54.09 UTC
4
2012-02-20 14:52:07.283 UTC
2012-02-20 14:44:19.13 UTC
null
94,197
null
477,065
null
1
31
javascript|html
14,264
<p>The <code>&lt;html&gt;</code> element can be referred through the <a href="https://developer.mozilla.org/en/DOM/document.documentElement"><code>document.documentElement</code></a> property. In general, the root element of any document can be referred through <code>.documentElement</code>.</p> <pre><code>document.documentElement.style.background = ''; </code></pre> <p>Note: <code>.style.background</code> returns the value for <code>background</code> as an <strong>inline style</strong> property. That is, defined using <code>&lt;html style="background:.."&gt;</code>. If you want to get the calculated style property, use <a href="https://developer.mozilla.org/en/DOM/window.getComputedStyle"><code>getComputedStyle</code></a>:</p> <pre><code>var style = window.getComputedStyle(document.documentElement); var bgColor = style.backgroundColor; </code></pre>
18,376,042
Are relational databases a poor fit for Node.js?
<p>Recently I've been playing around with Node.js a little bit. In my particular case I wound up using MongoDB, partly because it made sense for that project because it was very simple, and partly because Mongoose seemed to be an extremely simple way to get started with it.</p> <p>I've noticed that there seems to be a degree of antipathy towards relational databases when using Node.js. They seem to be poorly supported compared to non-relational databases within the Node.js ecosystem, but I can't seem to find a concise reason for this.</p> <p>So, my question is, <strong>is there a solid technical reason why relational databases are a poorer fit for working with Node.js than alternatives such as MongoDB?</strong></p> <p>EDIT: Just want to clarify a few things:</p> <ul> <li>I'm specifically not looking for details relating to a specific application I'm building</li> <li>Nor am I looking for non-technical reasons (for example, I'm not after answers like "Node and MongoDB are both new so developers use them together")</li> </ul> <p>What I am looking for is entirely technical reasons, ONLY. For instance, if there were a technical reason why relational databases performed unusually poorly when used with Node.js, then that would be the kind of thing I'm looking for (note that from the answers so far it doesn't appear that is the case)</p>
18,376,854
5
1
null
2013-08-22 09:08:21.803 UTC
18
2021-08-22 07:57:36.5 UTC
2013-08-22 12:27:24.24 UTC
null
63,717
null
63,717
null
1
66
node.js|relational-database
33,105
<p>No, there isn't a technical reason. It's mostly just opinion and using NoSQL with Node.js is currently a popular choice.</p> <p>Granted, Node's ecosystem is <a href="https://npmjs.org/" rel="noreferrer">largely community-driven</a>. Everything beyond Node's <a href="http://nodejs.org/api/" rel="noreferrer">core API</a> requires community involvement. And, certainly, people will be more likely to support what aligns with their personal preferences.</p> <p>But, many still use and support relational databases with Node.js. Some notable projects include:</p> <ul> <li><a href="https://npmjs.org/package/mysql" rel="noreferrer"><code>mysql</code></a></li> <li><a href="https://npmjs.org/package/pg" rel="noreferrer"><code>pg</code></a></li> <li><a href="https://npmjs.org/package/sequelize" rel="noreferrer"><code>sequelize</code></a></li> </ul>
18,431,440
301 Moved Permanently
<p>I'm trying to get HTML by URL in Java. But <code>301 Moved Permanently</code> is all that I've got. Another URLs work. What's wrong? This is my code:</p> <pre><code> hh= new URL("http://hh.ru"); in = new BufferedReader( new InputStreamReader(hh.openStream())); while ((inputLine = in.readLine()) != null) { sb.append(inputLine).append("\n"); str=sb.toString();//returns 301 } </code></pre>
18,431,514
6
2
null
2013-08-25 16:57:32.27 UTC
4
2019-01-04 18:26:17.187 UTC
2014-09-10 10:39:35.807 UTC
null
2,713,969
null
2,713,969
null
1
8
java|html|http|http-status-code-301
39,742
<p>You're facing a redirect to other URL. It's quite normal and web site may have many reasons to redirect you. Just follow the redirect based on "Location" HTTP header like that:</p> <pre><code>URL hh= new URL("http://hh.ru"); URLConnection connection = hh.openConnection(); String redirect = connection.getHeaderField("Location"); if (redirect != null){ connection = new URL(redirect).openConnection(); } BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; System.out.println(); while ((inputLine = in.readLine()) != null) { System.out.println(inputLine); } </code></pre> <p>Your browser is following redirects automaticaly, but using URLConnection you should do it by your own. If it bothers you take a look at other <a href="https://hc.apache.org/" rel="noreferrer">Java HTTP client</a> implementations, like Apache HTTP Client. Most of them are able to follow redirect automatically.</p>
18,303,040
How to remove elements/nodes from angular.js array
<p>I am trying to remove elements from the array <code>$scope.items</code> so that items are removed in the view <code>ng-repeat="item in items"</code></p> <p>Just for demonstrative purposes here is some code:</p> <pre><code>for(i=0;i&lt;$scope.items.length;i++){ if($scope.items[i].name == 'ted'){ $scope.items.shift(); } } </code></pre> <p>I want to remove the 1st element from the view if there is the name ted right? It works fine, but the view reloads all the elements. Because all the array keys have shifted. This is creating unnecessary lag in the mobile app I am creating..</p> <p>Anyone have an solutions to this problem?</p>
18,303,310
12
6
null
2013-08-18 19:50:13.977 UTC
30
2017-03-27 09:12:36.22 UTC
2015-11-17 15:51:25.68 UTC
null
1,664,443
null
2,596,477
null
1
72
angularjs|scope|angularjs-ng-repeat
273,087
<p>There is no rocket science in deleting items from array. To delete items from any array you need to use <a href="http://www.w3schools.com/jsref/jsref_splice.asp"><code>splice</code></a>: <code>$scope.items.splice(index, 1);</code>. <a href="http://plnkr.co/edit/4JbLupVFIguVd8TWVAsB?p=preview">Here is an example</a>:</p> <p><strong>HTML</strong></p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html data-ng-app="demo"&gt; &lt;head&gt; &lt;script data-require="[email protected]" data-semver="1.1.5" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.js"&gt;&lt;/script&gt; &lt;link rel="stylesheet" href="style.css" /&gt; &lt;script src="script.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div data-ng-controller="DemoController"&gt; &lt;ul&gt; &lt;li data-ng-repeat="item in items"&gt; {{item}} &lt;button data-ng-click="removeItem($index)"&gt;Remove&lt;/button&gt; &lt;/li&gt; &lt;/ul&gt; &lt;input data-ng-model="newItem"&gt;&lt;button data-ng-click="addItem(newItem)"&gt;Add&lt;/button&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>JavaScript</strong></p> <pre><code>"use strict"; var demo = angular.module("demo", []); function DemoController($scope){ $scope.items = [ "potatoes", "tomatoes", "flour", "sugar", "salt" ]; $scope.addItem = function(item){ $scope.items.push(item); $scope.newItem = null; } $scope.removeItem = function(index){ $scope.items.splice(index, 1); } } </code></pre>
18,431,285
Check if a user is in a group
<p>I have a server running where I use php to run a bash script to verify certain information of a user. For example, I have a webhosting server set up, and in order to be able to add another domain to their account I want to verify if the user is actually a member of the 'customers' group. What would be the best way to do this?</p> <p>I have searched google, but all it comes up with is ways to check whether a user or a group exists, so google is not being a big help right now.</p>
18,431,322
13
0
null
2013-08-25 16:45:03.9 UTC
13
2021-08-05 11:47:24.883 UTC
2017-05-06 02:50:59.663 UTC
null
1,905,949
null
1,448,061
null
1
59
bash
86,610
<p>Try doing this :</p> <pre><code>username=ANY_USERNAME if getent group customers | grep -q "\b${username}\b"; then echo true else echo false fi </code></pre> <p>or</p> <pre><code>username=ANY_USERNAME if groups $username | grep -q '\bcustomers\b'; then echo true else echo false fi </code></pre>
15,317,321
Convert YYYYMMDD to DATE
<p>I have a bunch of dates in <code>varchar</code> like this:</p> <pre><code>20080107 20090101 20100405 ... </code></pre> <p>How do I convert them to a date format like this:</p> <pre><code>2008-01-07 2009-01-01 2010-04-05 </code></pre> <p>I've tried using this:</p> <pre><code>SELECT [FIRST_NAME] ,[MIDDLE_NAME] ,[LAST_NAME] ,cast([GRADUATION_DATE] as date) FROM mydb </code></pre> <p>But get this message:</p> <blockquote> <p>Msg 241, Level 16, State 1, Line 2<br>Conversion failed when converting date and/or time from character string.</p> </blockquote>
15,317,404
5
5
null
2013-03-09 23:56:22.613 UTC
1
2021-11-15 17:58:58.337 UTC
2013-03-10 00:11:57.357 UTC
null
61,305
null
914,308
null
1
17
sql|sql-server|sql-server-2008-r2
239,204
<p>The error is happening because you (or whoever designed this table) <code>have a bunch of dates in VARCHAR</code>. Why are you (or whoever designed this table) storing dates as strings? Do you (or whoever designed this table) also store salary and prices and distances as strings?</p> <p>To find the values that are causing issues (so you (or whoever designed this table) can fix them):</p> <pre><code>SELECT GRADUATION_DATE FROM mydb WHERE ISDATE(GRADUATION_DATE) = 0; </code></pre> <p>Bet you have at least one row. Fix those values, and then FIX THE TABLE. Or ask whoever designed the table to FIX THE TABLE. Really nicely.</p> <pre><code>ALTER TABLE mydb ALTER COLUMN GRADUATION_DATE DATE; </code></pre> <p>Now you don't have to worry about the formatting - you can always format as <code>YYYYMMDD</code> or <code>YYYY-MM-DD</code> on the client, or using <code>CONVERT</code> in SQL. When you have a <em>valid</em> date as a string literal, you can use:</p> <pre><code>SELECT CONVERT(CHAR(10), CONVERT(datetime, '20120101'), 120); </code></pre> <p>...but this is better done on the client (if at all).</p> <p>There's a popular term - garbage in, garbage out. You're never going to be able to convert to a date (never mind convert to a <em>string</em> in a specific format) if your data type choice (or the data type choice of whoever designed the table) inherently allows garbage into your table. Please fix it. Or ask whoever designed the table (again, really nicely) to fix it.</p>
15,285,698
Building a titleView programmatically with constraints (or generally constructing a view with constraints)
<p>I'm trying to build a titleView with constraints that looks like this:</p> <p><img src="https://i.stack.imgur.com/7RRKf.png" alt="titleView" /></p> <p>I know how I would do this with frames. I would calculate the width of the text, the width of the image, create a view with that width/height to contain both, then add both as subviews at the proper locations with frames.</p> <p>I'm trying to understand how one might do this with constraints. My thought was that intrinsic content size would help me out here, but I'm flailing around wildly trying to get this to work.</p> <pre><code>UILabel *categoryNameLabel = [[UILabel alloc] init]; categoryNameLabel.text = categoryName; // a variable from elsewhere that has a category like &quot;Popular&quot; categoryNameLabel.translatesAutoresizingMaskIntoConstraints = NO; [categoryNameLabel sizeToFit]; // hoping to set it to the instrinsic size of the text? UIView *titleView = [[UIView alloc] init]; // no frame here right? [titleView addSubview:categoryNameLabel]; NSArray *constraints; if (categoryImage) { UIImageView *categoryImageView = [[UIImageView alloc] initWithImage:categoryImage]; [titleView addSubview:categoryImageView]; categoryImageView.translatesAutoresizingMaskIntoConstraints = NO; constraints = [NSLayoutConstraint constraintsWithVisualFormat:@&quot;|[categoryImageView]-[categoryNameLabel]|&quot; options:NSLayoutFormatAlignAllTop metrics:nil views:NSDictionaryOfVariableBindings(categoryImageView, categoryNameLabel)]; } else { constraints = [NSLayoutConstraint constraintsWithVisualFormat:@&quot;|[categoryNameLabel]|&quot; options:NSLayoutFormatAlignAllTop metrics:nil views:NSDictionaryOfVariableBindings(categoryNameLabel)]; } [titleView addConstraints:constraints]; // here I set the titleView to the navigationItem.titleView </code></pre> <p>I shouldn't have to hardcode the size of the titleView. It should be able to be determined via the size of its contents, but...</p> <ol> <li>The titleView is determining it's size is 0 unless I hardcode a frame.</li> <li>If I set <code>translatesAutoresizingMaskIntoConstraints = NO</code> the app crashes with this error: <code>'Auto Layout still required after executing -layoutSubviews. UINavigationBar's implementation of -layoutSubviews needs to call super.'</code></li> </ol> <h1>Update</h1> <p>I got it to work with this code, but I'm still having to set the frame on the titleView:</p> <pre><code>UILabel *categoryNameLabel = [[UILabel alloc] init]; categoryNameLabel.translatesAutoresizingMaskIntoConstraints = NO; categoryNameLabel.text = categoryName; categoryNameLabel.opaque = NO; categoryNameLabel.backgroundColor = [UIColor clearColor]; UIView *titleView = [[UIView alloc] init]; [titleView addSubview:categoryNameLabel]; NSArray *constraints; if (categoryImage) { UIImageView *categoryImageView = [[UIImageView alloc] initWithImage:categoryImage]; [titleView addSubview:categoryImageView]; categoryImageView.translatesAutoresizingMaskIntoConstraints = NO; constraints = [NSLayoutConstraint constraintsWithVisualFormat:@&quot;|[categoryImageView]-7-[categoryNameLabel]|&quot; options:NSLayoutFormatAlignAllCenterY metrics:nil views:NSDictionaryOfVariableBindings(categoryImageView, categoryNameLabel)]; [titleView addConstraints:constraints]; constraints = [NSLayoutConstraint constraintsWithVisualFormat:@&quot;V:|[categoryImageView]|&quot; options:0 metrics:nil views:NSDictionaryOfVariableBindings(categoryImageView)]; [titleView addConstraints:constraints]; titleView.frame = CGRectMake(0, 0, categoryImageView.frame.size.width + 7 + categoryNameLabel.intrinsicContentSize.width, categoryImageView.frame.size.height); } else { constraints = [NSLayoutConstraint constraintsWithVisualFormat:@&quot;|[categoryNameLabel]|&quot; options:NSLayoutFormatAlignAllTop metrics:nil views:NSDictionaryOfVariableBindings(categoryNameLabel)]; [titleView addConstraints:constraints]; constraints = [NSLayoutConstraint constraintsWithVisualFormat:@&quot;V:|[categoryNameLabel]|&quot; options:0 metrics:nil views:NSDictionaryOfVariableBindings(categoryNameLabel)]; [titleView addConstraints:constraints]; titleView.frame = CGRectMake(0, 0, categoryNameLabel.intrinsicContentSize.width, categoryNameLabel.intrinsicContentSize.height); } return titleView; </code></pre>
16,114,622
6
3
null
2013-03-08 02:30:14.21 UTC
6
2019-10-29 10:45:49.233 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
287,403
null
1
32
ios|nslayoutconstraint
26,388
<p>You have to set the frame of <code>titleView</code> because you don't specify any constraints for its <code>position</code> in its superview. The Auto Layout system can only figure out the <code>size</code> of <code>titleView</code> for you from the constraints you specified and the <code>intrinsic content size</code> of its subviews.</p>
15,345,790
scipy.misc module has no attribute imread?
<p>I am trying to read an image with scipy. However it does not accept the <code>scipy.misc.imread</code> part. What could be the cause of this?</p> <pre><code>&gt;&gt;&gt; import scipy &gt;&gt;&gt; scipy.misc &lt;module 'scipy.misc' from 'C:\Python27\lib\site-packages\scipy\misc\__init__.pyc'&gt; &gt;&gt;&gt; scipy.misc.imread('test.tif') Traceback (most recent call last): File "&lt;pyshell#11&gt;", line 1, in &lt;module&gt; scipy.misc.imread('test.tif') AttributeError: 'module' object has no attribute 'imread' </code></pre>
15,345,969
18
11
null
2013-03-11 18:24:03.147 UTC
23
2022-03-25 20:16:05.937 UTC
2015-06-08 23:51:51.27 UTC
null
202,229
null
1,738,154
null
1
171
python|installation|scipy|dependencies|python-imaging-library
286,901
<p>You need to install <a href="https://python-pillow.org/" rel="noreferrer">Pillow</a> (formerly <a href="http://www.pythonware.com/products/pil/" rel="noreferrer">PIL</a>). From <a href="http://docs.scipy.org/doc/scipy/reference/misc.html" rel="noreferrer">the docs</a> on <code>scipy.misc</code>: </p> <blockquote> <p>Note that Pillow is not a dependency of SciPy but the image manipulation functions indicated in the list below are not available without it:</p> <p>... </p> <p><code>imread</code></p> <p>...</p> </blockquote> <p>After installing Pillow, I was able to access <code>imread</code> as follows:</p> <pre><code>In [1]: import scipy.misc In [2]: scipy.misc.imread Out[2]: &lt;function scipy.misc.pilutil.imread&gt; </code></pre>
28,163,439
AttributeError: 'DataFrame' object has no attribute 'Height'
<p>I am able to convert a csv file to pandas DataFormat and able to print out the table, as seen below. However, when I try to print out the Height column I get an error. How can I fix this?</p> <pre><code>import pandas as pd df = pd.read_csv('/path../NavieBayes.csv') print df #this prints out as seen below print df.Height #this gives me the "AttributeError: 'DataFrame' object has no attribute 'Height' Height Weight Classifer 0 70.0 180 Adult 1 58.0 109 Adult 2 59.0 111 Adult 3 60.0 113 Adult 4 61.0 115 Adult </code></pre>
28,163,504
3
3
null
2015-01-27 04:48:15.87 UTC
5
2020-05-07 00:39:12.847 UTC
null
null
null
null
3,062,459
null
1
11
python-2.7|pandas
51,845
<p>I have run into a similar issue before when reading from <code>csv</code>. Assuming it is the same:</p> <pre><code>col_name =df.columns[0] df=df.rename(columns = {col_name:'new_name'}) </code></pre> <p>The error in my case was caused by (I think) by a byte order marker in the csv or some other non-printing character being added to the first column label. <code>df.columns</code> returns an array of the column names. <code>df.columns[0]</code> gets the first one. Try printing it and seeing if something is odd with the results.</p>
48,129,942
Python restart program
<p>I made a program that asks you at the end for a restart.</p> <p>I <code>import os</code> and used <code>os.execl(sys.executable, sys.executable, * sys.argv)</code> but nothing happened, why?</p> <p>Here's the code:</p> <pre><code>restart = input("\nDo you want to restart the program? [y/n] &gt; ") if str(restart) == str("y"): os.execl(sys.executable, sys.executable, * sys.argv) # Nothing hapens else: print("\nThe program will be closed...") sys.exit(0) </code></pre>
48,130,152
5
5
null
2018-01-06 17:28:48.543 UTC
4
2022-09-19 21:40:45.863 UTC
2019-02-06 17:50:30.233 UTC
null
8,411,271
null
7,947,338
null
1
5
python|restart|python-os
51,365
<pre><code>import os import sys restart = input(&quot;\nDo you want to restart the program? [y/n] &gt; &quot;) if restart == &quot;y&quot;: os.execl(sys.executable, os.path.abspath(__file__), *sys.argv) else: print(&quot;\nThe program will be closed...&quot;) sys.exit(0) </code></pre> <blockquote> <p>os.execl(path, arg0, arg1, ...)</p> </blockquote> <p><code>sys.executable</code>: python executeable</p> <p><code>os.path.abspath(__file__)</code>: the python code file you are running.</p> <p><code>*sys.argv</code>: remaining argument</p> <p>It will execute the program again like <code>python XX.py arg1 arg2</code>.</p>
7,917,107
How to add a footnote under the x-axis of a plot
<p>I couldn't find the right function to add a footnote in my plot.</p> <p>The footnote I want to have is something like an explanation of one item in the legend, but it is too long to put in the legend box. So, I'd like to add a ref number, e.g. [1], to the legend item, and add the footnote in the bottom of the plot, under the x-axis.</p> <p>Which function should I use? Thanks!</p>
7,918,549
2
0
null
2011-10-27 14:07:24.957 UTC
3
2022-07-12 19:21:25.577 UTC
2022-07-12 19:21:25.577 UTC
null
7,758,804
null
927,877
null
1
26
python|matplotlib
45,735
<p>One way would be just use <code>plt.text(x,y,'text')</code></p>
9,221,010
How do I iterate over the options of a SelectField in a template?
<p>I have a select field in the form and now I need to iterate over options in this field.</p> <p><code>{{ form.myselect }}</code> gives me this:</p> <pre><code>&lt;select name="myselect" id="id_myselect"&gt; &lt;option value="" selected="selected"&gt;---------&lt;/option&gt; &lt;option value="2"&gt;Item 1&lt;/option&gt; &lt;option value="3"&gt;Item 2&lt;/option&gt; ... &lt;/select&gt; </code></pre> <p>Now I need to add some attributes to the options and because of that what I need is:</p> <pre><code>&lt;select name="myselect" id="id_myselect"&gt; {% for x in form.myselect %} &lt;option value="{{ x.id }}"&gt;{{ x.name }}&lt;/option&gt; {% endfor %} &lt;/select&gt; </code></pre> <p>but there is an error:</p> <pre class="lang-none prettyprint-override"><code>Caught TypeError while rendering: 'BoundField' object is not iterable </code></pre> <p>I tried <code>form.myselect.all</code>, <code>form.myselect.option_set</code> but it gives nothing</p>
10,715,412
5
6
null
2012-02-10 00:20:36.39 UTC
14
2020-05-15 15:53:04.043 UTC
2020-05-15 15:53:04.043 UTC
null
10,498,206
null
928,017
null
1
34
django|django-forms|django-templates
43,311
<p>I've been struggling with this problem today and found the solution. Yes, you can iterate over options of the select tag directly in template. Here's how to do it in template:</p> <pre><code>&lt;select id="id_customer" name="customer"&gt; {% for x, y in form.fields.customer.choices %} &lt;option value="{{ x }}"{% if form.fields.customer.value == x %} selected{% endif %}&gt;{{ y }}&lt;/option&gt; {% endfor %} &lt;/select&gt; </code></pre> <p>In this case I have a <code>customer</code> field in the form which has choices set up as follows:</p> <pre><code>class SomeForm(forms.Form): customer = forms.ChoiceField(label=u'Customer') def __init__(self, *args, **kwargs): super(SomeForm, self).__init__(*args, **kwargs) self.fields['customer'].choices = [(e.id, e.customer) for e in Customers.objects.all()] </code></pre> <p>Hope this helps</p>
31,164,749
Algorithm complexity: if/else under for loop
<p>I am wondering if in a situation like the following (an if/else statement under a for loop) the complexity would be O(n) or O(n^2):</p> <pre><code>for character in string: if character==something: do something else: do something else. </code></pre> <p>Thank you!</p>
31,164,966
3
5
null
2015-07-01 14:51:07.467 UTC
2
2015-07-01 15:05:19.473 UTC
null
null
null
null
3,263,734
null
1
7
if-statement|for-loop|complexity-theory
49,312
<p>It will be </p> <p>O(n) if 'do something' and 'do something else' are O(1)</p> <p>O(n^2) if 'do something' and 'do something else' are O(n)</p> <p>Basically the complexity of the for loop will depend on the complexity of it components and the no. of loops.</p>
4,940,033
SyntaxError: missing ; before statement
<p>I am getting this error :</p> <pre><code>SyntaxError: missing ; before statement </code></pre> <p>Why would I get that from this code? How can I get around this ?</p> <pre><code>var $this = $("input"); foob_name = $this.attr('name').replace(/\[(\d+)\]/, function($0, $1) { return '[' + (+$1 + 1) + ']'; })); </code></pre>
4,940,048
4
4
null
2011-02-09 00:10:01.38 UTC
1
2020-02-03 06:43:27.437 UTC
2011-02-09 00:42:58.31 UTC
null
524,566
null
93,311
null
1
17
javascript|jquery|html
102,778
<p>Looks like you have an extra parenthesis.</p> <p>The following portion is parsed as an assignment so the interpreter/compiler will look for a semi-colon or attempt to insert one if certain conditions are met. </p> <pre><code>foob_name = $this.attr('name').replace(/\[(\d+)\]/, function($0, $1) { return '[' + (+$1 + 1) + ']'; }) </code></pre>
5,285,414
Signal queuing in C
<p>I have a simple program under Linux which sends SIGUSR1 signal to its child process in a cycle. But when I send e.g. 10 signals, sometimes happens, that the child received only 3 of them. Last sent signal is always SIGUSR2 and that is received every time.</p> <p>Are the signals queuing, or when process didn't process the previous, it is simply overwritten? Is there a way I can send signals in a queue?</p>
5,285,647
4
0
null
2011-03-12 20:51:34.493 UTC
10
2019-12-17 23:17:44.16 UTC
2019-12-17 23:17:44.16 UTC
null
6,862,601
null
656,945
null
1
18
c|linux|queue|signals
12,436
<p>What happens is the following:</p> <ol> <li>First signal received, namely SIGUSR1, handler is called and is running</li> <li>Second signal received, since handler from nr1 is still running, the signal nr2 gets pending and blocked.</li> <li>Third signal received, since handler from nr1 is still running, the signal 3 gets discarded.</li> <li>Fourth, fifth...etc signal of the same type as the signal nr1 are discarded.</li> </ol> <p>Once signal handler is done with signal nr1, it will process signal nr2, and then signal handler will process the SIGUSR2.</p> <p>Basically, pending signals of the same type are not queued, but discarded. And no, there is no easy way to "burst" send signals that way. One always assumes that there can be several signals that are discarded, and tries to let the handler do the work of cleaning and finding out what to do (such as reaping children, if all children die at the same time).</p>
4,918,482
Rotating BufferedImage instances
<p>I am having trouble getting a rotated <code>BufferedImage</code> to display. I think the rotation is working just fine, but I can't actually draw it to the screen. My code:</p> <pre><code>Class extends JPanel { BufferedImage img; int rotation = 0; public void paintComponent(Graphics g) { g.clearRect(0, 0, getWidth(), getHeight()); img2d = img.createGraphics(); img2d.rotate(Math.toRadians(rotation), img.getWidth() / 2, img.getHeight() / 2); g.drawImage(img, imgx, imgy, null); this.repaint(); } } </code></pre> <p>This is not working for me. I could not find any way to draw the rotated <code>img2d</code> onto <code>g</code>.</p> <p>EDIT: I have multiple objects that are being drawn onto <code>g</code>, so I can't rotate that. I need to be able to rotate things individually.</p>
4,919,880
4
0
null
2011-02-07 06:04:41.197 UTC
6
2022-04-20 06:36:40.69 UTC
2012-12-31 06:02:01.677 UTC
null
418,556
user577304
null
null
1
21
java|swing|rotation|bufferedimage|graphics2d
55,791
<p>I would use <a href="https://docs.oracle.com/javase/6/docs/api/java/awt/Graphics2D.html#drawImage(java.awt.Image,%20java.awt.geom.AffineTransform,%20java.awt.image.ImageObserver)" rel="nofollow noreferrer"><code>Graphics2D.drawImage(image, affinetranform, imageobserver)</code></a>.</p> <p>The code example below rotates and translates an image to the center of the component. This is a screenshot of the result:</p> <p><img src="https://i.stack.imgur.com/WGlYu.png" alt="screenshot" /></p> <pre class="lang-java prettyprint-override"><code>public static void main(String[] args) throws IOException { JFrame frame = new JFrame(&quot;Test&quot;); frame.add(new JComponent() { BufferedImage image = ImageIO.read( new URL(&quot;http://upload.wikimedia.org/wikipedia/en/2/24/Lenna.png&quot;)); @Override protected void paintComponent(Graphics g) { super.paintComponent(g); // create the transform, note that the transformations happen // in reversed order (so check them backwards) AffineTransform at = new AffineTransform(); // 4. translate it to the center of the component at.translate(getWidth() / 2, getHeight() / 2); // 3. do the actual rotation at.rotate(Math.PI / 4); // 2. just a scale because this image is big at.scale(0.5, 0.5); // 1. translate the object so that you rotate it around the // center (easier :)) at.translate(-image.getWidth() / 2, -image.getHeight() / 2); // draw the image Graphics2D g2d = (Graphics2D) g; g2d.drawImage(image, at, null); // continue drawing other stuff (non-transformed) //... } }); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(400, 400); frame.setVisible(true); } </code></pre>
4,880,930
How to convert HTML entities like &#8211; to their character equivalents?
<p>I am creating a file that is to be saved on a local user's computer (not rendered in a web browser).</p> <p>I am currently using <code>html_entity_decode</code>, but this isn't converting characters like <code>&amp;#8211;</code> (which is the n-dash) and was wondering what other function I should be using.</p> <p>For example, when the file is imported into the software, instead of the ndash or just a - it shows up as <code>&amp;#8211;</code>. I know I could use <code>str_replace</code>, but if it's happening with this character, it could happen with many others since the data is dynamic.</p>
4,882,035
5
0
null
2011-02-02 22:58:51.523 UTC
8
2018-01-08 17:49:49.217 UTC
2011-02-03 01:59:21.36 UTC
null
476
null
475,890
null
1
15
php|character-encoding|special-characters
73,319
<p>You need to define the target character set. <code>&amp;#8211;</code> is not a valid character in the default ISO-8859-1 character set, so it's not decoded. Define UTF-8 as the output charset and it will decode:</p> <pre><code>echo html_entity_decode('&amp;#8211;', ENT_NOQUOTES, 'UTF-8'); </code></pre> <p>If at all possible, you should avoid HTML entities to begin with. I don't know where that encoded data comes from, but if you're storing it like this in the database or elsewhere, you're doing it wrong. Always store data UTF-8 encoded and only convert to HTML entities or otherwise escape for output when necessary.</p>
5,565,972
how i can execute CMD command in c# console application?
<p>It's very simple to make a mysqldump in <code>cmd</code> on windows, simply:</p> <p><em>Open <code>cmd</code> and put type mysqldump uroot ppassword database > c:/data.sql</em></p> <p>This results in an SQL dump file for the desired database.</p> <p>I'm writing a console application so I may run this command:</p> <pre><code>-uroot -ppass databse &gt; location\data.sql </code></pre> <p>I tried the following code to no avail:</p> <pre><code>System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + cmd); </code></pre> <p><em><strong>How might I start a <code>cmd</code> process and send my command successfully?</em></strong></p>
5,566,069
5
2
null
2011-04-06 11:59:55.837 UTC
4
2022-03-25 08:04:48.587 UTC
2011-04-06 12:08:12.157 UTC
null
263,681
delete my account
null
null
1
20
c#|.net|mysql|sql|database
65,316
<p>Is there a reason why you don't call mysqldump directly?</p> <pre><code>ProcessStartInfo procStartInfo = new ProcessStartInfo("mysqldump", "uroot ppassword databse &gt; c:/data.sql"); </code></pre> <p>If there <em>is</em> a reason, your code should look like this:</p> <pre><code>ProcessStartInfo procStartInfo = new ProcessStartInfo("cmd", "/c \"mysqldump uroot ppassword databse &gt; c:/data.sql\""); </code></pre> <p>Changes:</p> <ul> <li>You where missing "mysqldump" in your <code>cmd</code> variable.</li> <li>You should put the command to be executed in the command line into quotes.</li> </ul>
4,889,123
Any way to SQLBulkCopy "insert or update if exists"?
<p>I need to update a very large table periodically and SQLBulkCopy is perfect for that, only that I have a 2-columns index that prevents duplicates. Is there a way to use SQLBulkCopy as "insert or update if exists"? </p> <p>If not, what is the most efficient way of doing so? Again, I am talking about a table with millions of records. </p> <p>Thank you</p>
4,889,202
6
0
null
2011-02-03 16:58:27.513 UTC
12
2021-04-26 15:59:16.29 UTC
2020-06-01 08:42:57.143 UTC
null
4,925,121
null
593,651
null
1
31
c#|sql|sql-server|performance|sqlbulkcopy
60,682
<p>I would bulk load data into a temporary staging table, then do an upsert into the final table. See <a href="http://www.databasejournal.com/features/mssql/article.php/3739131/UPSERT-Functionality-in-SQL-Server-2008.htm" rel="nofollow noreferrer">here</a> for an example of doing an upsert.</p>
5,370,846
How do you use Mongoose without defining a schema?
<p>In previous versions of Mongoose (for node.js) there was an option to use it without defining a schema</p> <pre><code>var collection = mongoose.noSchema(db, "User"); </code></pre> <p>But in the current version the "noSchema" function has been removed. My schemas are likely to change often and really don't fit in with a defined schema so is there a new way to use schema-less models in mongoose?</p>
12,389,168
6
2
null
2011-03-20 19:22:27.077 UTC
39
2022-02-24 09:51:13.127 UTC
null
null
null
null
148,766
null
1
147
mongodb|node.js|mongoose
90,752
<p>I think this is what are you looking for <a href="http://mongoosejs.com/docs/guide.html#strict">Mongoose Strict</a></p> <p><strong>option: strict</strong></p> <p>The strict option, (enabled by default), ensures that values added to our model instance that were not specified in our schema do not get saved to the db. </p> <p><strong>Note: Do not set to false unless you have good reason.</strong></p> <pre><code> var thingSchema = new Schema({..}, { strict: false }); var Thing = mongoose.model('Thing', thingSchema); var thing = new Thing({ iAmNotInTheSchema: true }); thing.save() // iAmNotInTheSchema is now saved to the db!! </code></pre>
4,944,863
how to use node.js module system on the clientside
<p>I would like to use the CommonJS module system in a clientside javascript application. I chose nodejs as implementation but can't find any tutorial or docs on how to use nodejs clientside, ie without using <code>node application.js</code></p> <p>I included node.js like this in my html page:</p> <pre><code>&lt;script type="text/javascript" src="node.js"&gt;&lt;/script&gt; </code></pre> <p>Note that I didn't make nodejs on my local machine, I'm on Windows anyway (I'm aware of the Cygwin option). When I want to use the <code>require</code> function in my own javascript it says it's undefined.</p> <pre><code>var logger = require('./logger'); </code></pre> <p>My question is, is it possible to use nodejs like this?</p>
4,944,920
7
2
null
2011-02-09 12:32:51.203 UTC
24
2020-11-19 03:02:44.097 UTC
null
null
null
null
326,206
null
1
50
javascript|node.js
92,710
<p><code>Node.js</code> is a serverside application where you run javascript on the server. What you want to do is use the <code>require</code> function on the client.</p> <p>Your best bet is to just write the <code>require</code> method yourself or use any of the other implementations that use a different syntax like <a href="http://www.requirejs.org/">requireJS</a>.</p> <p>Having done a bit of extra research it seems that no-one has written a require module using the commonJS syntax for the client. I will end up writing my own in the near future, I recommend you do the same.</p> <p>[Edit]</p> <p>One important side effect is that the <code>require</code> function is synchronous and thus loading large blocks of javascript will block the browser completely. This is almost always an unwanted side-effect. You need to know what you're doing if you're going to do this. The requireJS syntax is set up so that it can be done asynchronously.</p>
5,192,068
C++ - char** argv vs. char* argv[]
<p>What is the difference between <code>char** argv</code> and <code>char* argv[]</code>? in <code>int main(int argc, char** argv)</code> and <code>int main(int argc, char* argv[])</code>?</p> <p>Are they the same? Especially that the first part does not have <code>[]</code>.</p>
5,192,091
8
0
null
2011-03-04 09:44:17.277 UTC
36
2021-11-16 14:13:05.647 UTC
2012-11-30 19:18:48.36 UTC
null
322,020
null
588,855
null
1
59
c++|program-entry-point|arguments
61,732
<p>They are entirely equivalent. <code>char *argv[]</code> must be read as array of pointers to <code>char</code> and an array argument is demoted to a pointer, so pointer to pointer to <code>char</code>, or <code>char **</code>.</p> <p>This is the same in <a href="https://stackoverflow.com/questions/779910/should-i-use-char-argv-or-char-argv-in-c">C</a>.</p>
5,335,197
Git's famous "ERROR: Permission to .git denied to user"
<p>I have tried googling and read through <a href="https://help.github.com/en/articles/connecting-to-github-with-ssh" rel="noreferrer">https://help.github.com/en/articles/connecting-to-github-with-ssh</a> and various, various guides. I am unable to <code>git push -u origin master</code> or <code>git push origin master</code> ( the same command ).</p> <p>I've had my git account for at least 2 or so years. I've successfully been able to create repos and <code>push -u origin master</code> fine on my laptop but on this desktop I'm having issues.</p> <p>Here's what I tried:</p> <p><strong>1.</strong> I have setup my git user name</p> <p><strong>2.</strong> I have setup my git user email</p> <p><strong>3.</strong> I have uploaded the contents of my /home/meder/.ssh/id_rsa.pub to github's account page. I have verified I did not paste any whitespace</p> <p><strong>4.</strong> I have created a ~/.ssh/config with these contents:</p> <pre><code> Host github.com User git Hostname github.com PreferredAuthentications publickey IdentityFile ~/.ssh/id_rsa </code></pre> <p>I have chmodded the .ssh to 700, id_rsa 600</p> <p><strong>5.</strong> I have added the <strong>proper</strong> remote origin <strong>without making typos</strong> : <code>git remote add origin [email protected]:medero/cho.git</code></p> <p><strong>6.</strong> To confirm #5, here is my .git/config. The directory is <em>correct</em> and not another directory:</p> <pre><code>[remote "origin"] fetch = +refs/heads/*:refs/remotes/origin/* url = [email protected]:medero/cho.git </code></pre> <p><strong>7.</strong> <code>ssh [email protected] -v</code> gives me a successful Authentication</p> <p><strong>8.</strong> One weird thing is, the username which it greets me with has <code>t</code> appended to it. My github username is <code>medero</code>, not <code>medert</code>.</p> <blockquote> <p>Hi mederot! You've successfully authenticated, but GitHub does not provide shell access.</p> </blockquote> <p><strong>9.</strong> I am <strong>not</strong> behind a proxy or firewall</p> <p><strong>10.</strong> The key is offered, heres the output from <code>-v</code>:</p> <blockquote> <pre><code>debug1: Host 'github.com' is known and matches the RSA host key. debug1: Found key in /home/meder/.ssh/known_hosts:58 debug1: ssh_rsa_verify: signature correct debug1: SSH2_MSG_NEWKEYS sent debug1: expecting SSH2_MSG_NEWKEYS debug1: SSH2_MSG_NEWKEYS received debug1: SSH2_MSG_SERVICE_REQUEST sent debug1: SSH2_MSG_SERVICE_ACCEPT received debug1: Authentications that can continue: publickey debug1: Next authentication method: publickey debug1: Offering public key: /home/meder/.ssh/id_rsa debug1: Remote: Forced command: gerve mederot debug1: Remote: Port forwarding disabled. debug1: Remote: X11 forwarding disabled. debug1: Remote: Agent forwarding disabled. debug1: Remote: Pty allocation disabled. debug1: Server accepts key: { some stuff, dont know if i should share it debug1: Remote: Forced command: gerve mederot debug1: Remote: Port forwarding disabled. debug1: Remote: X11 forwarding disabled. debug1: Remote: Agent forwarding disabled. debug1: Remote: Pty allocation disabled. debug1: Authentication succeeded (publickey). </code></pre> </blockquote> <p><strong>11.</strong> Here are the commands I used</p> <pre><code>mkdir cho git init touch README git add README git commit -m 'test' git remote add origin [email protected]:medero/cho.git git push -u origin master </code></pre> <p><strong>12.</strong> I don't want to create a new SSH key.</p> <p><strong>13.</strong> If I git clone using ssh and make an edit, commit, and git push, I get the same exact thing.</p> <p><strong>14.</strong> Here's the actual error:</p> <pre><code>$ git push ERROR: Permission to medero/cho.git denied to mederot. fatal: The remote end hung up unexpectedly </code></pre> <p><strong>15.</strong> I have setup my github username and github token:</p> <p>$ git config --global github.user medero $ git config --global github.token 0123456789yourf0123456789tokenSets the GitHub token for all git instances on the system</p> <p><strong>16.</strong> I have confirmed my github username is NOT <code>mederot</code> and my github token IS CORRECT per my account page ( validated first 2 chars and last 2 chars ).</p> <p><strong>17.</strong> To confirm #16, ~/.gitconfig contains</p> <pre><code>[github] token = mytoken... user = medero </code></pre> <p><strong>18.</strong> I did <code>ssh-key add ~/.ssh/id_rsa</code> if that's even necessary...</p> <p><br><br> <strong>THEORIES:</strong></p> <p>I suspect there's something fishy because when I get ssh authenticated, the user greeting is <code>mederot</code> and not <code>medero</code>, which is my acct. Could something in my github account possibly be incorrectly cached?</p> <p>I also suspect some local ssh caching weirdness because if i <code>mv ~/.ssh/id_rsa KAKA</code> and <code>mv ~/.ssh/id_rsa.pub POOPOO</code>, and do <code>ssh [email protected] -v</code>, it still Authenticates me and says it serves my /home/meder/.ssh/id_rsa when I renamed it?! It has to be cached?!</p>
5,335,583
16
2
null
2011-03-17 05:22:50.967 UTC
58
2022-07-22 12:45:48.017 UTC
2019-09-30 16:16:14.627 UTC
null
3,474,146
null
145,190
null
1
159
git|ssh|github
189,849
<p>In step 18, I assume you mean <code>ssh-add ~/.ssh/id_rsa</code>? If so, that explains this:</p> <blockquote> <p>I also suspect some local ssh caching weirdness because if i mv ~/.ssh/id_rsa KAKA and mv ~/.ssh/id_rsa.pub POOPOO, and do ssh [email protected] -v, it still Authenticates me and says it serves my /home/meder/.ssh/id_rsa when I renamed it?! It has to be cached?!</p> </blockquote> <p>... since the <code>ssh-agent</code> is caching your key.</p> <p>If you look on GitHub, there is a <a href="https://github.com/mederot" rel="noreferrer">mederot</a> account. Are you sure that this is nothing to do with you? GitHub shouldn't allow the same SSH public key to be added to two accounts, since when you are using the <code>[email protected]:...</code> URLs it's identifying the user based on the SSH key. (That this shouldn't be allowed is confirmed <a href="http://support.github.com/discussions/accounts/1397-same-ssh-key-two-accounts" rel="noreferrer">here</a>.)</p> <p>So, I suspect (in decreasing order of likelihood) that one of the following is the case:</p> <ol> <li>You created the mederot account previously and added your SSH key to it.</li> <li>Someone else has obtained a copy of your public key and added it to the mederot GitHub account.</li> <li>There's a horrible bug in GitHub.</li> </ol> <p>If 1 isn't the case then I would report this to GitHub, so they can check about 2 or 3.</p> <p>More :</p> <p>ssh-add -l check if there is more than one identify exists if yes, remove it by ssh-add -d "that key file"</p>
12,243,710
Xcode download for Snow Leopard
<p>Older threads mention that there is a download for Xcode for Snow Leopard listed in the Xcode downloads on <a href="https://developer.apple.com/downloads/index.action?name=Xcode" rel="nofollow noreferrer">https://developer.apple.com/downloads/index.action?name=Xcode</a> if you are logged-in as an enrolled iOS developer - but I can't see it. </p> <p>A comment on this thread has a direct link to the download, but clicking on the link redirects to an "Access Denied" error page:</p> <p><a href="https://stackoverflow.com/questions/7662246/cant-download-xcode-4-for-snow-leopard-anymore">https://stackoverflow.com/questions/7662246/cant-download-xcode-4-for-snow-leopard-anymore</a></p>
12,243,747
3
2
null
2012-09-03 07:35:21.3 UTC
2
2018-06-28 09:16:45.133 UTC
2018-06-11 09:32:42.233 UTC
null
5,638,630
null
336,977
null
1
6
xcode|download|xcode9|xcode10|xcode9.4
58,485
<p>you can refer to <a href="https://superuser.com/questions/346639/is-there-an-xcode-4-2-for-snow-leopard">here</a>. or if you have a good internet connection, try to download via torrent. here is the link. <a href="http://thepiratebay.se/torrent/6721955/" rel="nofollow noreferrer">link for xcode via torrent</a>.</p>
12,134,554
Node.js - external JS and CSS files (just using node.js not express)
<p>Im trying to learn node.js and have hit a bit of a roadblock.</p> <p>My issue is that i couldn't seem to load an external css and js file into a html file.</p> <pre><code>GET http://localhost:8080/css/style.css 404 (Not Found) GET http://localhost:8080/js/script.css 404 (Not Found) </code></pre> <p>(this was when all files were in the root of the app)</p> <p>I was told to somewhat mimic the following app structure, add a route for the public dir to allow the webserver to serve the external files.</p> <p>my app structure is like so</p> <pre><code>domain.com app/ webserver.js public/ chatclient.html js/ script.js css/ style.css </code></pre> <p>So my webserver.js script is in the root of app, and everything I want to access is in 'public'.</p> <p>I also saw <a href="http://www.thecodinghumanist.com/blog/archives/2011/5/6/serving-static-files-from-node-js" rel="noreferrer">this example</a> that uses path.extname() to get any files extentions located in a path. (see the last code block).</p> <p>So I've tried to combine the new site structure and this path.extname() example, to have the webserver allow access to any file in my public dir, so I can render the html file, which references the external js and css files.</p> <p>My webserver.js looks like this.</p> <pre><code>var http = require('http') , url = require('url') , fs = require('fs') , path = require('path') , server; server = http.createServer(function(req,res){ var myPath = url.parse(req.url).pathname; switch(myPath){ case '/public': // get the extensions of the files inside this dir (.html, .js, .css) var extname = mypath.extname(path); switch (extname) { // get the html case '.html': fs.readFile(__dirname + '/public/chatclient.html', function (err, data) { if (err) return send404(res); res.writeHead(200, {'Content-Type': 'text/html'}); res.write(data, 'utf8'); res.end(); }); break; // get the script that /public/chatclient.html references case '.js': fs.readFile(__dirname + '/public/js/script.js', function (err, data) { if (err) return send404(res); res.writeHead(200, { 'Content-Type': 'text/javascript' }); res.end(content, 'utf-8'); res.end(); }); break; // get the styles that /public/chatclient.html references case '.css': fs.readFile(__dirname + '/public/css/style.css', function (err, data) { if (err) return send404(res); res.writeHead(200, { 'Content-Type': 'text/javascript' }); res.end(content, 'utf-8'); res.end(); }); } break; default: send404(res); } }); </code></pre> <p>Inside the case of public, I'm trying to get any of the folders/files inside of this dir via var extname = mypath.extname(path); Similar to the link I provided.</p> <p>But at the moment 'extname' is empty when I console log it.</p> <p>Can anyone advise what I might need to add or tweek here? I'm aware this can be done easily in Express, but I would like to know how to achieve the same thing just relying on Node.</p> <p>I's appreciate any help on this.</p> <p>Thanks in advance.</p>
12,135,116
6
1
null
2012-08-26 22:51:07.72 UTC
17
2017-07-20 05:13:55.453 UTC
2013-08-13 05:20:00.393 UTC
null
2,119,665
null
1,292,733
null
1
21
node.js
68,673
<p>There are several problems with your code.</p> <ol> <li>Your server is not going to run as you have not specified a port to listen from.</li> <li>As Eric pointed out your case condition will fail as 'public' does not appear in the url.</li> <li>Your are referencing a non-existent variable 'content' in your js and css responses, should be 'data'.</li> <li>You css content-type header should be text/css instead of text/javascript</li> <li>Specifying 'utf8' in the body is unnecessary.</li> </ol> <p>I have re-written your code. Notice I do not use case/switch. I prefer much simpler if and else, you can put them back if that's your preference. The url and path modules are not necessary in my re-write, so I have removed them.</p> <pre><code>var http = require('http'), fs = require('fs'); http.createServer(function (req, res) { if(req.url.indexOf('.html') != -1){ //req.url has the pathname, check if it conatins '.html' fs.readFile(__dirname + '/public/chatclient.html', function (err, data) { if (err) console.log(err); res.writeHead(200, {'Content-Type': 'text/html'}); res.write(data); res.end(); }); } if(req.url.indexOf('.js') != -1){ //req.url has the pathname, check if it conatins '.js' fs.readFile(__dirname + '/public/js/script.js', function (err, data) { if (err) console.log(err); res.writeHead(200, {'Content-Type': 'text/javascript'}); res.write(data); res.end(); }); } if(req.url.indexOf('.css') != -1){ //req.url has the pathname, check if it conatins '.css' fs.readFile(__dirname + '/public/css/style.css', function (err, data) { if (err) console.log(err); res.writeHead(200, {'Content-Type': 'text/css'}); res.write(data); res.end(); }); } }).listen(1337, '127.0.0.1'); console.log('Server running at http://127.0.0.1:1337/'); </code></pre>
12,185,811
MySQL on delete cascade. Test Example
<p>I am wondering about this test question. I prepared the example myself and tested it but I still feel unsure of the answer.</p> <p>With the following:</p> <pre><code>CREATE TABLE foo ( id INT PRIMARY KEY AUTO_INCREMENT, name INT ) CREATE TABLE foo2 ( id INT PRIMARY KEY AUTO_INCREMENT, foo_id INT REFERENCES foo(id) ON DELETE CASCADE ) </code></pre> <p>As far as I can see the answer is:</p> <p><strong>a. Two tables are created</strong></p> <p>Although there are also:</p> <p><strong>b. If a row in table foo2, with a foo_id of 2 is deleted, then the row with id=2 in the table foo is automatically deleted</strong></p> <p><strong>d.If a row with id = 2 in table foo is deleted, all rows with foo_id = 2 in table foo2 are deleted</strong></p> <p>In my example I would have used the delete syntax:</p> <pre><code>DELETE FROM foo WHERE id = 2; DELETE FROM foo2 WHERE foo_id = 2; </code></pre> <p>For some reason I was unable to find any relationship between the tables although it seems like there should be one. Maybe there is some MySQL setting or perhaps is <code>ON DELETE CASCADE</code> not used properly in the table creation queries? I am left wondering...</p>
12,186,780
2
0
null
2012-08-29 20:15:36.47 UTC
6
2013-03-30 22:31:28.38 UTC
2013-03-30 22:31:28.38 UTC
null
1,193,333
null
922,360
null
1
24
mysql|cascade
48,050
<p>Answer d. is correct, if and only if the storage engine actually supports and enforces foreign key constraints.</p> <p>If the tables are created with <code>Engine=MyISAM</code>, then neither b. or d. is correct.</p> <p>If the tables are created with <code>Engine=InnoDB</code>, then <b>d.</b> is correct.</p> <p>NOTE:</p> <p>This is true for InnoDB if and only if <code>FOREIGN_KEY_CHECKS = 1</code>; if <code>FOREIGN_KEY_CHECKS = 0</code>, then a <code>DELETE</code> from the parent table (foo) will <em>not</em> remove rows from the child table (foo2) that reference a row removed from the parent table.</p> <p>Verify this with the output from <code>SHOW VARIABLES LIKE 'foreign_key_checks'</code> (1=ON, 0=OFF) (The normal default is for this to be ON.)</p> <p>The output from <code>SHOW CREATE TABLE foo</code> will show which engine the table uses.</p> <p>The output from <code>SHOW VARIABLES LIKE 'storage_engine'</code> will show the default engine used when a table is created and the engine is not specified.</p>
12,173,802
Trying to find which text field is active ios
<p>I am trying to find which textfield is active for when the I move the view when the keyboard rises. I am trying to set a property in my viewcontroller from the subview of a scrollview.</p> <p>This is the code I use to display the view in the scrollview </p> <pre><code>-(void)displayView:(UIViewController *)viewController{ [[viewFrame subviews] makeObjectsPerformSelector:@selector(removeFromSuperview)]; [viewFrame scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO]; [viewFrame addSubview: viewController.view]; _currentViewController = viewController; } </code></pre> <p>--EDIT--</p> <p>I have changed my way of thinking about this problem. Sorry for the question being ambiguous when I posted it. I was exhausted at the time and it made sense in my head.</p> <p>A different but similar question: Is there a common subclass of both UITextArea and UITextView that will give me the origin of the firstResponder? Or will I have to check also the class of the firstResponder before I can find the origin?</p>
12,174,042
7
4
null
2012-08-29 08:33:11.16 UTC
8
2018-02-09 11:18:34.137 UTC
2012-08-30 06:32:31.73 UTC
null
1,253,462
null
1,253,462
null
1
27
ios
26,990
<p>You need to search for an object that has become a first responder. First responder object is the one using the keyboard (actually, it is he one having focus for user input). To check which text field uses the keyboard, iterate over your text fields (or just over all subviews) and use the <code>isFirstResponder</code> method.</p> <p>EDIT: As requested, a sample code, assuming all text fields are a subview of the view controller's view:</p> <pre><code>for (UIView *view in self.view.subviews) { if (view.isFirstResponder) { [self doSomethingCleverWithView:view]; } } </code></pre>
12,247,807
Using LINK and UNLINK HTTP verbs in a REST API
<p>I am currently working on implementing a REST API. I have a resource model with a large number of relationships between the individual resources. </p> <p>My question is: how do you link two existing resources to each other (establishing a relationship) in a RESTful manner?</p> <p>One solution I came across was the use of the LINK and UNLINK HTTP verbs. The API consumer would be able to link two resources using LINK and following URI: /resource1/:id1/resource2/:id2. </p> <p>The problem with this solution is the lack of support for the LINK and UNLINK verbs. Neither <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html">http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html</a> or <a href="http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol">http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol</a> mention the verbs, and they seem to be largely "forgotten". However, the original RFC 2068 does state that they exist. </p> <p>I really like this solution. However, I'm afraid that many API consumers/clients will not be able to deal with the solution due to the lack of support for LINK/UNLINK. Is this an acceptable solution or are there any better and/or more elegant solutions for linking existing resources in a RESTful API?</p> <p>Thanks</p>
17,020,374
1
2
null
2012-09-03 12:23:10.45 UTC
8
2015-10-07 14:08:56.677 UTC
null
null
null
null
1,570,661
null
1
27
api|rest|http-verbs
9,359
<p>I use <code>LINK</code> and <code>UNLINK</code> in my (bespoke, company-internal) web app. I use <a href="https://datatracker.ietf.org/doc/html/draft-snell-link-method" rel="nofollow noreferrer">https://datatracker.ietf.org/doc/html/draft-snell-link-method</a> as my implementation reference.</p> <p>I found that there are three types of clients:</p> <ol> <li>Those that only support <code>GET</code> and <code>POST</code>, taking their cues from HTML's <code>&lt;form&gt;</code> element.</li> <li>Those that only support <code>GET</code>, <code>PUT</code>, <code>POST</code> and <code>DELETE</code>. These take their cues from CRUD and RPC-pretending-to-be-REST type APIs.</li> <li>Those that allow any method. The publication of <code>PATCH</code> as an official RFC has increased the amount of these, as has the growth of WebDAV, although sometimes category 2 clients support <code>PATCH</code> too.</li> </ol> <p>Since we currently develop our clients in-house we don't have this problem, but I have looked into it and did consider the pros and cons before defining my API, in case we did want to allow third-party clients. My solution (since we needed to support HTML clients without Javascript anyway) was to allow <code>POST</code> to override the method by supplying a <code>_METHOD</code> field (<code>application/x-www-form-urlencoded</code>) and then have my <code>post()</code> function on the back-end palm off to the appropriate function for the intended HTTP method. That way, any client in the future that is in, say, class 2 above, can use <code>PUT</code> and <code>DELETE</code> but wrap <code>PATCH</code>, <code>LINK</code> and <code>UNLINK</code> in a <code>POST</code> request. You get the best of both worlds: rich methods from clients that support it, and yet still support low-quality clients through POST-tunnelling.</p>
23,979,785
Can unnamed structures inherit?
<p>The following looks like a compilation error : </p> <pre><code>struct : Base { }; </code></pre> <p>Yet when <a href="http://ideone.com/u4LqG6" rel="noreferrer">used</a> <sup>[1]</sup> it seems to work :</p> <pre><code>#include &lt;iostream&gt; using namespace std; template&lt;bool B&gt; struct A { struct : std::integral_constant&lt;bool, B&gt; { } members; }; int main() { A&lt;true&gt; a; cout &lt;&lt; a.members.value &lt;&lt; endl; return 0; } </code></pre> <p>In c++ is it valid for unnamed structures to inherit? Are there any examples where this is userful?</p> <hr> <p><sup><sup>[1] </sup>Disclaimer: I'm not pretending the provided example is useful. I rarely use unnamed structs, and when I do they're usually bundling together some built-in member variables, in order to provide a cleaner interface for a class. The question came up from the observation that <a href="http://www.codeproject.com/Articles/3016/An-STL-like-bidirectional-map#from_and_to" rel="noreferrer">memberspaces</a> need not be nammed structures</sup></p>
23,979,909
2
6
null
2014-06-01 12:18:04.62 UTC
4
2020-08-23 14:28:57.197 UTC
2020-08-23 14:28:57.197 UTC
null
2,528,436
null
2,567,683
null
1
33
c++|inheritance|struct|unnamed-class
4,121
<p>Unnamed classes can inherit. This is useful, for example, in situations when you <em>must</em> inherit in order to override a virtual function, but you never need more than one instance of the class, and you do not need to reference the derived type, because a reference to the base type is sufficient.</p> <p>Here is an example:</p> <pre><code>#include &lt;iostream&gt; using namespace std; struct Base {virtual int process(int a, int b) = 0;}; static struct : Base { int process(int a, int b) { return a+b;} } add; static struct : Base { int process(int a, int b) { return a-b;} } subtract; static struct : Base { int process(int a, int b) { return a*b;} } multiply; static struct : Base { int process(int a, int b) { return a/b;} } divide; void perform(Base&amp; op, int a, int b) { cout &lt;&lt; "input: " &lt;&lt; a &lt;&lt; ", " &lt;&lt; b &lt;&lt; "; output: " &lt;&lt; op.process(a, b) &lt;&lt; endl; } int main() { perform(add, 2, 3); perform(subtract, 6, 1); perform(multiply, 6, 7); perform(divide, 72, 8); return 0; } </code></pre> <p>This code creates four anonymous derivations of <code>Base</code> - one for each operation. When the instances of these derivations are passed to the <code>perform</code> function, the proper override is called. Note that <code>perform</code> does not need to know about any of the specific types - the base type with its virtual function is enough to complete the process.</p> <p>Here is the output of running the above code:</p> <pre><code>input: 2, 3; output: 5 input: 6, 1; output: 5 input: 6, 7; output: 42 input: 72, 8; output: 9 </code></pre> <p><a href="http://ideone.com/b7XDaY" rel="noreferrer">Demo on ideone.</a></p>
3,984,487
Is there any console "graphics" library for .Net?
<p>My basic goal here is writing a .NET remake of Kingdom of Kroz. For those not familiar with the game:</p> <p><a href="http://www.indiefaqs.com/index.php/Kingdom_of_Kroz" rel="noreferrer">http://www.indiefaqs.com/index.php/Kingdom_of_Kroz</a></p> <p><a href="http://www.youtube.com/watch?v=cHwlNAFXpIw" rel="noreferrer">http://www.youtube.com/watch?v=cHwlNAFXpIw</a></p> <p>Originally it was supposed to be a quick distraction project to give me a break from all the generic enterprise WCF/WF/LINQ2SQL/etc work projects occupying most of my time lately. While the result of my effort is playable, it looks like absolute arse (even for a console-based game) because of the way I'm redrawing everything in each frame.</p> <p>I'm aware of some alternate approaches but in the brief tests I've done they still don't offer significant performance or aesthetic benefits. I don't want to resort to a library which 'emulates' a console if I can help it. I'd prefer to work with the proper Win32 console API under the hood, but not to work with it directly if I can help it. Keeping in mind that it's a distinctly niche use case, what would be the 'generally' accepted best approach for this? Are there any particularly optimal console 'drawing' techniques one should be aware of? I don't mind swimming in a sea of PInvoke and marshalling as long as it still ends up with a fast, responsive and efficient console UI.</p>
4,015,186
3
2
null
2010-10-21 05:15:58.797 UTC
11
2018-12-29 04:01:13.89 UTC
2014-12-03 05:38:44.693 UTC
null
243,557
null
243,557
null
1
25
c#|.net|vb.net|graphics|console
23,806
<p><a href="http://msdn.microsoft.com/en-us/library/ms682073(v=VS.85).aspx">http://msdn.microsoft.com/en-us/library/ms682073(v=VS.85).aspx</a></p> <p>Some/many of these functions you might need to use P/Invoke for, but they should do what you need. You can write at arbitrary locations in the buffer and get key-based, non-buffered input. Usually you start with GetStdHandle() to get handles to the console input and output "streams" and then you call one of the appropriate functions from the above list to do something, like WriteConsoleOutputCharacter(), or PeekConsoleInput().</p> <p>I once wrote a library to create an in-process windowing system using the Windows console and plain Win32 on C. Fun project, but I don't know where it is now.</p>
36,757,965
How to have multiple conditions for one if statement in python
<p>So I am writing some code in python 3.1.5 that requires there be more than one condition for something to happen. Example:</p> <pre><code>def example(arg1, arg2, arg3): if arg1 == 1: if arg2 == 2: if arg3 == 3: print("Example Text") </code></pre> <p>The problem is that when I do this it doesn't print anything if arg2 and arg3 are equal to anything but 0. Help?</p>
36,758,098
5
7
null
2016-04-21 01:24:26.433 UTC
9
2022-05-06 23:39:57.67 UTC
null
null
null
null
6,233,034
null
1
37
python|function|if-statement|arguments|conditional-statements
304,488
<p>I would use </p> <pre><code>def example(arg1, arg2, arg3): if arg1 == 1 and arg2 == 2 and arg3 == 3: print("Example Text") </code></pre> <p>The <code>and</code> operator is identical to the logic gate with the same name; it will return 1 if and only if all of the inputs are 1. You can also use <code>or</code> operator if you want that logic gate.</p> <p>EDIT: Actually, the code provided in your post works fine with me. I don't see any problems with that. I think that this might be a problem with your Python, not the actual language.</p>
20,659,389
PHP get the current month of a date
<p>Hello everybody I would like to get the current month of a date.</p> <p>This is what I tried:</p> <pre><code>&lt;?php $transdate = date('m-d-Y', time()); echo $transdate; $month = date('m', strtotime($transdate)); if ($month == &quot;12&quot;) { echo &quot;&lt;br /&gt;December is the month :)&quot;; } else { echo &quot;&lt;br /&gt; The month is probably not December&quot;; } ?&gt; </code></pre> <p>But the result is wrong, it should display December is the month :0</p> <p>Any ideas? thanks.</p>
20,659,745
5
5
null
2013-12-18 13:22:39.947 UTC
6
2022-05-21 08:33:06.43 UTC
2020-09-07 21:07:44.913 UTC
null
3,399,356
null
1,640,417
null
1
22
php|date
125,414
<p>You need to use the default date() function of PHP to get current month. Then you can easily check it by if conditions as mentioned in the code below:</p> <pre><code>&lt;?php $month = date('m'); if($month == 12){ echo &quot;&lt;br /&gt;December is the month :)&quot;; } else { echo &quot;&lt;br /&gt; The month is probably not December&quot;; } ?&gt; </code></pre>
10,934,705
unknown directive "server" in /etc/nginx/nginx.conf:4
<p>With nginx/0.7.65 I'm getting this error on line 4. Why doesn't it recognize <code>server</code>?</p> <pre><code>#### CHAT_FRONT #### server { listen 7000 default deferred; server_name example.com; root /home/deployer/apps/chat_front/current/public; location ^~ /assets/ { gzip_static on; expires max; add_header Cache-Control public; } error_page 500 502 503 504 /500.html; client_max_body_size 4G; keepalive_timeout 10; } #### CHAT_STORE #### server { listen 7002 default deferred; server_name store.example.com; root /home/deployer/apps/chat_store/current/public; error_page 500 502 503 504 /500.html; client_max_body_size 4G; keepalive_timeout 10; } #### LOGIN #### server { listen 7004 default deferred; server_name login.example.com; root /home/deployer/apps/login/current/public; location ^~ /assets/ { gzip_static on; expires max; add_header Cache-Control public; } error_page 500 502 503 504 /500.html; client_max_body_size 4G; keepalive_timeout 10; } #### PERMISSIONS #### server { listen 7006 default deferred; server_name permissions.example.com; root /home/deployer/apps/permissions/current/public; error_page 500 502 503 504 /500.html; client_max_body_size 4G; keepalive_timeout 10; } #### SEARCH #### server { listen 7008 default deferred; server_name search.example.com; root /home/deployer/apps/search/current/public; error_page 500 502 503 504 /500.html; client_max_body_size 4G; keepalive_timeout 10; } #### ANALYTICS #### server { listen 7010 default deferred; server_name analytics.example.com; root /home/deployer/apps/analytics/current/public; error_page 500 502 503 504 /500.html; client_max_body_size 4G; keepalive_timeout 10; } </code></pre>
10,934,792
5
0
null
2012-06-07 15:15:42.06 UTC
3
2020-08-04 02:57:34.31 UTC
null
null
null
null
765,357
null
1
15
nginx
49,844
<p>The <code>server</code> directive must be contained in the context of <code>http</code> module. Additionally you are missing top-level events module, which has one obligatory setting, and a bunch of stanzas which are to be in the http module of your config. While <a href="http://wiki.nginx.org/FullExample" rel="noreferrer">nginx documentation</a> is not particularly helpful on creating config from scratch, there are <a href="http://wiki.nginx.org/Configuration" rel="noreferrer">working examples</a> there.</p> <p>Source: <a href="http://wiki.nginx.org/HttpCoreModule#server" rel="noreferrer">nginx documentation on server directive</a></p>
11,248,657
How to import/include source files in JavaScript?
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/4634644/how-to-include-js-file-in-another-js-file">How to include js file in another js file?</a> </p> </blockquote> <p>Suppose I have a few JavaScript source files: <code>a.js</code>, <code>a1.js</code>, and <code>a2.js</code>. Functions of <code>a.js</code> invoke functions from <code>a1.js</code> and <code>a2.js</code>.</p> <p>Now I have to declare <em>all</em> these files in my HTML page. I would like to declare only <code>a.js</code> in the HTML and "import/include" <code>a1.js</code>, and <code>a2.js</code> in the <code>a.js</code> source file.</p> <p>Does it make sense? Can I do that in JavaScript?</p>
11,248,751
3
4
null
2012-06-28 16:09:31.043 UTC
1
2017-10-22 23:07:53.027 UTC
2017-10-22 23:07:53.027 UTC
null
3,885,376
null
650,444
null
1
19
javascript|client-side
64,351
<p>You can't specify imports in vanilla javascript.</p> <p>So your solutions (excluding heavy server side frameworks) are :</p> <ul> <li><p>simply do the imports</p></li> <li><p>concatenate your js files (and minify them in the same move, for exemple using the <a href="https://developers.google.com/closure/compiler/">closure compiler</a>)</p></li> <li><p>use a module itool like <a href="http://requirejs.org/">require.js</a></p></li> </ul> <p>As long as you're not experienced, and if your number of files is low (less than 15), I recommend to simply choose the first or second solution. Using a module loader may have side effects you don't want to debug when beginning to learn javascript.</p>
11,313,309
Spring Security - Programmatic login without a password
<p>I am trying to perform an automatic login when the user clicks a link in their email with Spring Security.</p> <p>I have seen a lot of examples to perform a programmatic login like the following:</p> <pre><code>UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password); try { Authentication auth = authenticationManager.authenticate(token); SecurityContextHolder.getContext().setAuthentication(auth); repository.saveContext(SecurityContextHolder.getContext(), request, response); rememberMeServices.loginSuccess(request, response, auth); .... </code></pre> <p>The problem I see is that I do not have the original password so I can't create a UsernamePasswordAuthenticationToken. Any other way to login the user if I do not have the plain text password (I have the one that is encoded)? </p> <p>Thanks in advance.</p>
11,314,388
1
2
null
2012-07-03 14:39:28.077 UTC
11
2015-08-26 18:56:40.36 UTC
null
null
null
null
1,049,900
null
1
28
spring-mvc|spring-security
29,861
<p>Be careful that you know what you are doing in terms of allowing login from a link within an email. SMTP is not a secure protocol and so it is typically bad to rely on someone having an email as a form of authentication.</p> <p>You do not need to use the AuthenticationManager if you already know they are authenticated. Instead you can just set the Authentication directly as shown below:</p> <pre><code>Authentication authentication = new UsernamePasswordAuthenticationToken(user, null, AuthorityUtils.createAuthorityList("ROLE_USER")); SecurityContextHolder.getContext().setAuthentication(authentication); </code></pre> <p>If you want a complete example, you can refer to the <a href="https://github.com/rwinch/spring-security-samples-securemail/blob/master/src/main/java/org/springframework/security/samples/mail/mvc/SignupController.java" rel="noreferrer">SignupController</a> in the <a href="https://github.com/rwinch/spring-security-samples-securemail" rel="noreferrer">secure mail</a> application that was the basis for Getting Started with Spring Security 3.1 <a href="http://www.infoq.com/presentations/Spring-Security-3-1" rel="noreferrer">(InfoQ video of presentation)</a>.</p>
11,266,997
How to get the version number of JavaFX?
<p>How can I find out at runtime which version of JavaFX I'm using?</p>
11,267,064
3
0
null
2012-06-29 18:21:43.683 UTC
9
2022-03-29 22:54:52.787 UTC
2012-06-29 20:45:14.86 UTC
null
3,340
null
62,349
null
1
42
java|javafx|javafx-2
36,657
<pre><code>com.sun.javafx.runtime.VersionInfo.getRuntimeVersion(); </code></pre>
11,173,685
How to detect radio button deselect event?
<p>Is there an easy way to attach a "deselect" event on a radio button? It seems that the change event only fires when the button is selected.</p> <p>HTML</p> <pre><code>&lt;input type="radio" id="one" name="a" /&gt; &lt;input type="radio" id="two" name="a" /&gt; </code></pre> <p>JavaScript</p> <pre><code>$('#one').change(function() { if(this.checked) { // do something when selected } else { // THIS WILL NEVER HAPPEN // do something when deselected } });​ </code></pre> <p><a href="http://jsfiddle.net/WZND9/" rel="noreferrer">jsFiddle</a> ​</p>
11,173,862
10
9
null
2012-06-23 23:03:21.383 UTC
5
2021-05-21 16:07:19.793 UTC
2012-06-23 23:30:25.22 UTC
null
811,001
null
811,001
null
1
62
javascript|jquery
41,226
<p>Why don't you simply create a custom event like, lets say, <code>deselect</code> and let it trigger on all the members of the clicked radio group except the element itself that was clicked? Its way easier to make use of the event handling API that jQuery provides that way.</p> <p><strong>HTML</strong></p> <pre><code>&lt;!-- First group of radio buttons --&gt; &lt;label for="btn_red"&gt;Red:&lt;/label&gt;&lt;input id="btn_red" type="radio" name="radio_btn" /&gt; &lt;label for="btn_blue"&gt;Blue:&lt;/label&gt;&lt;input id="btn_blue" type="radio" name="radio_btn" /&gt; &lt;label for="btn_yellow"&gt;Yellow:&lt;/label&gt;&lt;input id="btn_yellow" type="radio" name="radio_btn" /&gt; &lt;label for="btn_pink"&gt;Pink:&lt;/label&gt;&lt;input id="btn_pink" type="radio" name="radio_btn" /&gt; &lt;hr /&gt; &lt;!-- Second group of radio buttons --&gt; &lt;label for="btn_red_group2"&gt;Red 2:&lt;/label&gt;&lt;input id="btn_red_group2" type="radio" name="radio_btn_group2" /&gt; &lt;label for="btn_blue_group2"&gt;Blue 2:&lt;/label&gt;&lt;input id="btn_blue_group2" type="radio" name="radio_btn_group2" /&gt; &lt;label for="btn_yellow_group2"&gt;Yellow 2:&lt;/label&gt;&lt;input id="btn_yellow_group2" type="radio" name="radio_btn_group2" /&gt; &lt;label for="btn_pink_group2"&gt;Pink 2:&lt;/label&gt;&lt;input id="btn_pink_group2" type="radio" name="radio_btn_group2" /&gt; </code></pre> <p><strong>jQuery</strong></p> <pre><code>// Attaching click event handlers to all radio buttons... $('input[type="radio"]').bind('click', function(){ // Processing only those that match the name attribute of the currently clicked button... $('input[name="' + $(this).attr('name') + '"]').not($(this)).trigger('deselect'); // Every member of the current radio group except the clicked one... }); $('input[type="radio"]').bind('deselect', function(){ console.log($(this)); }) </code></pre> <p>​Deselection events will trigger only among members of the same radio group (elements that have the same <code>name</code> attribute).</p> <p><strong><a href="http://jsfiddle.net/FaRYg/" rel="noreferrer">jsFiddle solution</a></strong></p> <p><strong>EDIT:</strong> In order to account for all possible placements of the attached label tag (wrapping the radio element or being attached through an id selector) it is perhaps better to use <code>onchange</code> event to trigger the handlers. Thanks to <a href="https://stackoverflow.com/users/613004/faust">Faust</a> for pointing that out.</p> <pre><code>$('input[type="radio"]').on('change', function(){ // ... } </code></pre>
10,890,892
Use of symbol # (hash) in VBA Macro
<p>What is the meaning of the use of the <code>#</code> symbol in Excel VBA?</p> <p>It is used like this:</p> <pre><code> a = b /100# </code></pre> <p>I don't understand the significance of <code>#</code> after the <code>100</code>?</p>
10,891,051
1
0
null
2012-06-05 02:39:17.303 UTC
25
2015-09-15 04:55:33.24 UTC
2018-07-09 19:34:03.733 UTC
null
-1
null
1,322,141
null
1
62
vba|excel
82,345
<p>The type-declaration character for Double is the number sign (#). Also called <em>HASH</em></p> <p>Other type declaration characters are:</p> <ol> <li>Integer %</li> <li>Long &amp;</li> <li>Currency @</li> <li>Single !</li> <li>Double #</li> <li>String $</li> </ol> <blockquote> <p>Don't understand the significance of # here.</p> </blockquote> <p>It implies that when the expression is evaluated, the number in front of the type declaration character is treated as a specific data type instead of as a Variant.</p> <p>See this example, which are basically the same.</p> <pre><code>Sub Sample1() Dim a# a = 1.2 Debug.Print a End Sub Sub Sample2() Dim a As Double a = 1.2 Debug.Print a End Sub </code></pre> <p><strong>EDIT</strong></p> <p>Let me explain it a little more in detail.</p> <p>Consider this two procedures</p> <pre><code>Sub Sample1() Dim a As Double, b As Integer b = 32767 a = b * 100 Debug.Print a End Sub Sub Sample2() Dim a As Double, b As Integer b = 32767 a = b * 100# Debug.Print a End Sub </code></pre> <p><strong>Question</strong>: One of them will fail. Can you guess which one?</p> <p><strong>Ans</strong>: The 1st procedure <code>Sub Sample1()</code> will fail.</p> <p><strong>Reason</strong>: </p> <p>In <code>Sample2</code>, when you do <code>b * 100#</code> the result of calculation will be of type <code>Double</code>. Since it is within the limits of Double, so the calculation succeeds and the result is assigned to variable <code>a</code>.</p> <p>Now in <code>Sample1</code>, when you do <code>b * 100</code> the result of calculation will be of type <code>Integer</code>, since both the operands are of type integer. But the result of calculation exceeds the limits of Integer storage. As a result it will error out.</p> <p>Hope it helps :)</p>
12,738,889
When or why to use relative imports in Python
<p>Are there any rules or guidelines concerning when to use relative imports in Python? I see them in use all the time, such as in the Flask web framework. When searching for this topic, I only see articles on how to use relative imports, but not <em>why</em>.</p> <p>So is there some special benefit to using:</p> <pre><code>from . import x </code></pre> <p>rather than:</p> <pre><code>from package import x </code></pre> <p>Moreover, I noticed that <a href="https://stackoverflow.com/a/5811548/1918127">a related SO post</a> mentions that relative imports are discouraged. Yet people still continue to use them.</p>
12,738,912
1
1
null
2012-10-05 02:59:32.037 UTC
4
2022-03-23 21:53:44.93 UTC
2022-03-23 21:53:44.93 UTC
null
389,946
null
117,579
null
1
32
python|import|module|package
10,598
<p>Check out <a href="http://www.python.org/dev/peps/pep-0328/#rationale-for-relative-imports" rel="noreferrer">PEP 328's section on relative imports</a></p> <p>The rationale seems to be as written:</p> <blockquote> <p>Several use cases were presented, the most important of which is being able to rearrange the structure of large packages without having to edit sub-packages. In addition, a module inside a package can't easily import itself without relative imports.</p> </blockquote>
12,836,642
Analyzers in elasticsearch
<p>I'm having trouble understanding the concept of analyzers in elasticsearch with tire gem. I'm actually a newbie to these search concepts. Can someone here help me with some reference article or explain what actually the analyzers do and why they are used?</p> <p>I see different analyzers being mentioned at elasticsearch like keyword, standard, simple, snowball. Without the knowledge of analyzers I couldn't make out what actually fits my need.</p>
12,846,637
3
3
null
2012-10-11 09:41:42.57 UTC
20
2020-06-26 03:31:14.323 UTC
null
null
null
null
1,553,787
null
1
46
elasticsearch|analyzer|tire
27,410
<p>Let me give you a short answer.</p> <p>An analyzer is used at index Time and at search Time. It's used to create an index of terms.</p> <p>To index a phrase, it could be useful to break it in words. Here comes the analyzer.</p> <p>It applies tokenizers and token filters. A tokenizer could be a Whitespace tokenizer. It split a phrase in tokens at each space. A lowercase tokenizer will split a phrase at each non-letter and lowercase all letters.</p> <p>A token filter is used to filter or convert some tokens. For example, a ASCII folding filter will convert characters like ê, é, è to e.</p> <p>An analyzer is a mix of all of that.</p> <p>You should read <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis.html" rel="noreferrer">Analysis guide</a> and look at the right all different options you have.</p> <p>By default, Elasticsearch applies the standard analyzer. It will remove all common english words (and many other filters)</p> <p>You can also use the <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-analyze.html" rel="noreferrer">Analyze Api</a> to understand how it works. Very useful.</p>
22,259,714
ArrayIndexOutOfBoundsException: 4096 while reading gif file
<p>I am able to read png file. But getting ArrayIndexOutOfBoundsException: 4096 while reading gif file. </p> <pre><code>byte[] fileData = imageFile.getFileData(); ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(fileData); RenderedImage image = ImageIO.read(byteArrayInputStream) </code></pre> <p>Exception thrown looks like</p> <pre><code>java.lang.ArrayIndexOutOfBoundsException: 4096 at com.sun.imageio.plugins.gif.GIFImageReader.read(Unknown Source) at javax.imageio.ImageIO.read(Unknown Source) at javax.imageio.ImageIO.read(Unknown Source) </code></pre> <p>what could be the issue and what is the resolution?</p>
23,851,091
2
9
null
2014-03-07 20:07:16.727 UTC
7
2018-06-07 19:58:33.827 UTC
null
null
null
null
2,283,266
null
1
28
java|gif|javax.imageio
10,876
<p><strong>Update 3: Solution</strong></p> <p>I ended up developing my own GifDecoder and released it as open source under the Apache License 2.0. You can get it from here: <a href="https://github.com/DhyanB/Open-Imaging">https://github.com/DhyanB/Open-Imaging</a>. It does not suffer from the <code>ArrayIndexOutOfBoundsException</code> issue and delivers decent performance.</p> <p>Any feedback is highly appreciated. In particular, I'd like to know if it works correctly for all of your images and if you are happy with its speed.</p> <p>I hope this is helpful to you (:</p> <p><strong>Initial answer</strong></p> <p>Maybe this bug report is related to or describes the same problem: <a href="https://bugs.openjdk.java.net/browse/JDK-7132728">https://bugs.openjdk.java.net/browse/JDK-7132728</a>.</p> <p>Quote:</p> <pre>FULL PRODUCT VERSION : java version "1.7.0_02" Java(TM) SE Runtime Environment (build 1.7.0_02-b13) Java HotSpot(TM) 64-Bit Server VM (build 22.0-b10, mixed mode) ADDITIONAL OS VERSION INFORMATION : Microsoft Windows [Version 6.1.7601] A DESCRIPTION OF THE PROBLEM : according to specification http://www.w3.org/Graphics/GIF/spec-gif89a.txt > There is not a requirement to send a clear code when the string table is full. However, GIFImageReader requires the clear code when the string table is full. GIFImageReader violates the specification, clearly. In the real world, sometimes people finds such high compressed gif image. so you should fix this bug. STEPS TO FOLLOW TO REPRODUCE THE PROBLEM : javac -cp .;PATH_TO_COMMONS_CODEC GIF_OverflowStringList_Test.java java -cp .;PATH_TO_COMMONS_CODEC GIF_OverflowStringList_Test EXPECTED VERSUS ACTUAL BEHAVIOR : EXPECTED - complete normally. no output ACTUAL - ArrayIndexOutOfBounds occurs. ERROR MESSAGES/STACK TRACES THAT OCCUR : Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4096 at com.sun.imageio.plugins.gif.GIFImageReader.read(GIFImageReader.java:1 075) at javax.imageio.ImageIO.read(ImageIO.java:1400) at javax.imageio.ImageIO.read(ImageIO.java:1322) at GIF_OverflowStringList_Test.main(GIF_OverflowStringList_Test.java:8) REPRODUCIBILITY : This bug can be reproduced always.</pre> <p>The bug report also provides code to reproduce the bug.</p> <p><strong>Update 1</strong></p> <p>And here is an image that causes the bug in my own code:</p> <p><img src="https://i.stack.imgur.com/o23L9.gif" alt="enter image description here"></p> <p><strong>Update 2</strong></p> <p>I tried to read the same image using Apache Commons Imaging, which led to the following exception:</p> <pre>java.io.IOException: AddStringToTable: codes: 4096 code_size: 12 at org.apache.commons.imaging.common.mylzw.MyLzwDecompressor.addStringToTable(MyLzwDecompressor.java:112) at org.apache.commons.imaging.common.mylzw.MyLzwDecompressor.decompress(MyLzwDecompressor.java:168) at org.apache.commons.imaging.formats.gif.GifImageParser.readImageDescriptor(GifImageParser.java:388) at org.apache.commons.imaging.formats.gif.GifImageParser.readBlocks(GifImageParser.java:251) at org.apache.commons.imaging.formats.gif.GifImageParser.readFile(GifImageParser.java:455) at org.apache.commons.imaging.formats.gif.GifImageParser.readFile(GifImageParser.java:435) at org.apache.commons.imaging.formats.gif.GifImageParser.getBufferedImage(GifImageParser.java:646) at org.apache.commons.imaging.Imaging.getBufferedImage(Imaging.java:1378) at org.apache.commons.imaging.Imaging.getBufferedImage(Imaging.java:1292)</pre> <p>That looks very similar to the problem we have with ImageIO, so I reported the bug at the Apache Commons JIRA: <a href="https://issues.apache.org/jira/browse/IMAGING-130">https://issues.apache.org/jira/browse/IMAGING-130</a>.</p>
17,051,126
Why do I get OutOfMemory when 20% of the heap is still free?
<p>I've set the max heap to 8 GB. When my program starts using about 6.4 GB (as reported in VisualVM), the garbage collector starts taking up most of the CPU and the program crashes with OutOfMemory when making a ~100 MB allocation. I am using Oracle Java 1.7.0_21 on Windows.</p> <p>My question is whether there are GC options that would help with this. I'm not passing anything except -Xmx8g.</p> <p>My guess is the heap is getting fragmented, but shouldn't the GC compact it?</p>
28,231,912
5
2
null
2013-06-11 18:26:25.793 UTC
9
2015-01-30 08:25:37.01 UTC
2013-06-12 04:51:35.37 UTC
null
772,000
null
1,151,521
null
1
18
java|garbage-collection|jvm-hotspot
2,412
<p>Collecting bits and pieces of information (which is surprisingly difficult, since the <a href="http://docs.oracle.com/javase/8/docs/technotes/guides/vm/gctuning" rel="noreferrer">official documentation</a> is quite bad), I've determined...</p> <p>There are generally two reasons this may happen, both related to fragmentation of free space (ie, free space existing in small pieces such that a large object cannot be allocated). First, the garbage collector might not do compaction, which is to say it does not defragment the memory. Even a collector that does compaction may not do it perfectly well. Second, the garbage collector typically splits the memory area into regions that it reserves for different kinds of objects, and it may not think to take free memory from the region that has it to give to the region that needs it.</p> <p>The CMS garbage collector does not do compaction, while the others (the serial, parallel, parallelold, and G1) do. The default collector in Java 8 is ParallelOld.</p> <p>All garbage collectors split memory into regions, and, AFAIK, all of them are too lazy to try very hard to prevent an OOM error. The command line option <code>-XX:+PrintGCDetails</code> is very helpful for some of the collectors in showing the sizes of the regions and how much free space they have.</p> <p>It is possible to experiment with different garbage collectors and tuning options. Regarding my question, the <code>G1</code> collector (enabled with the JVM flag <code>-XX:+UseG1GC</code>) solved the issue I was having. However, this was basically down to chance (in other situations, it OOMs more quickly). Some of the collectors (the serial, cms, and G1) have extensive tuning options for selecting the sizes of the various regions, to enable you to waste time in futilely trying to solve the problem.</p> <p>Ultimately, the real solutions are rather unpleasant. First, is to install more RAM. Second, is to use smaller arrays. Third, is to use <code>ByteBuffer.allocateDirect</code>. Direct byte buffers (and their int/float/double wrappers) are array-like objects with array-like performance that are allocated on the OS's native heap. The OS heap uses the CPU's virtual memory hardware and is free from fragmentation issues and can even effectively use the disk's swap space (allowing you to allocate more memory than available RAM). A big drawback, however, is that the JVM doesn't really know when direct buffers should be deallocated, making this option more desirable for long-lived objects. The final, possibly best, and certainly most unpleasant option is to allocate <em>and deallocate</em> memory natively using JNI calls, and use it in Java by wrapping it in a <code>ByteBuffer</code>.</p>
50,823,743
Disable TSLint in VSCode
<p>So this feels like this should be such an easy task but it's starting to drive me insane. I can't seem to turn off TSLint or TS or whatever it is that gives me these errors. I just want the ESLint with my own configured rules, nothing else.</p> <p><a href="https://i.stack.imgur.com/PlKpX.png" rel="noreferrer"><img src="https://i.stack.imgur.com/PlKpX.png" alt="I only want the ESLint error"></a></p> <p>Is it built in TS? I have disabled TSLint extension (even uninstalled it). I have set the following rules:</p> <pre><code>"typescript.format.enable": false, "typescript.validate.enable": false, </code></pre> <p>Still gives me error. How do I turn this off?</p>
51,993,691
7
7
null
2018-06-12 18:38:54.45 UTC
15
2021-07-22 20:37:01.057 UTC
2018-06-12 21:06:53.96 UTC
null
441,387
null
3,267,110
null
1
78
typescript|visual-studio-code|tslint
65,399
<p>It seems that the error is coming from the <em>TypeScript extension</em>, which is <em>also</em> handling the JavaScript IntelliSense. Due to some UX ignorance, VSCode prefixes the error with <code>[ts]</code> instead of <code>[js]</code>.</p> <p>To disable these validations, set</p> <pre><code>"javascript.validate.enable": false </code></pre> <p>See <a href="https://github.com/Microsoft/vscode/issues/54691#issuecomment-406440968" rel="noreferrer">this issue</a> for more details.</p>
26,490,126
AppCompat style background propagated to the Image within the ToolBar
<p><strong>Context</strong></p> <p>I'm using the newest AppCompat v7 lib (21.0.0) and I have migrated my app from ActionBar to ToolBar</p> <p><strong>Problem</strong></p> <ol> <li>Images in the ToolBar automatically receive the same background as the ToolBar</li> </ol> <p>Currently the SearchBox is a custom view set on the action bar (From previous implementation) I plan to switch if to the SearchView and style it accordingly but I'm still very interested in the problem I'm facing right now.</p> <p><img src="https://i.stack.imgur.com/eVodp.png" alt="Img background"></p> <ol start="2"> <li>When long pressing on a menu item in the ToolBar a toast appear with the hint text and the text has the same background than the ToolBar.</li> </ol> <p><img src="https://i.stack.imgur.com/nHcdd.png" alt="Toast background"></p> <p>How can I avoid this?</p> <p>Here is my toolbar layout and the style &amp; theme</p> <p>layout v_toolbar.xml</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/my_awesome_toolbar" android:layout_width="match_parent" android:layout_height="wrap_content" app:popupTheme="@style/ThemeOverlay.AppCompat.Light" app:theme="@style/MyActionBarStyle"/&gt; </code></pre> <p>values/styles.xml</p> <pre><code>&lt;style name="MyActionBarStyle" parent="@style/ThemeOverlay.AppCompat.Dark.ActionBar"&gt; &lt;item name="android:background"&gt;@color/green&lt;/item&gt; &lt;item name="android:windowActionBarOverlay"&gt;true&lt;/item&gt; &lt;!-- Support library compatibility --&gt; &lt;item name="background"&gt;@color/green&lt;/item&gt; &lt;item name="windowActionBarOverlay"&gt;true&lt;/item&gt; &lt;/style&gt; </code></pre> <p>Theme</p> <pre><code>&lt;style name="MyTheme" parent="AppBaseTheme"&gt; &lt;!-- Here we setting appcompat’s actionBarStyle --&gt; &lt;!-- &lt;item name="actionBarStyle"&gt;@style/MyActionBarStyle&lt;/item&gt; --&gt; &lt;item name="windowActionBar"&gt;false&lt;/item&gt; &lt;!-- ...and here we setting appcompat’s color theming attrs --&gt; &lt;item name="colorPrimary"&gt;@color/green&lt;/item&gt; &lt;item name="colorPrimaryDark"&gt;@color/green_dark&lt;/item&gt; &lt;/style&gt; </code></pre> <p><strike><strong>Workaround 1 for problem 1</strong></p> <p>The workaround for the first problem is to set a transparent background on the ImageView</p> <pre><code>android:background="@color/transparent" </code></pre> <p>This does not solve the toast issue.</strike></p> <p><strong>Solution for both problems</strong></p> <p>I set a background to the ToolBar</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/my_awesome_toolbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/green" app:popupTheme="@style/ThemeOverlay.AppCompat.Light" app:theme="@style/MyActionBarStyle"/&gt; </code></pre> <p>And I'm not setting the background on the theme anymore.</p> <pre><code>&lt;style name="MyActionBarStyle" parent="@style/ThemeOverlay.AppCompat.Dark.ActionBar"&gt; &lt;item name="android:windowActionBarOverlay"&gt;true&lt;/item&gt; &lt;!-- Support library compatibility --&gt; &lt;item name="windowActionBarOverlay"&gt;true&lt;/item&gt; &lt;/style&gt; </code></pre> <p>As pointed by Chris Banes, a style could be created for the toolbar instead of declaring the android:background.</p> <p>This fixes my problem but then I seem to have another issue with the fact that the popupTheme isn't applied and my ShareActionMenuItem drop down does not have a white background with black text. See another question here: <a href="https://stackoverflow.com/q/26504532/1228221">AppCompat ToolBar popupTheme not used in the ShareAction MenuItem</a></p> <p>Maybe this is a bug in the appcompat library.</p>
26,508,436
2
6
null
2014-10-21 15:11:45.253 UTC
17
2014-12-29 08:24:11.447 UTC
2017-05-23 12:00:31.917 UTC
null
-1
null
1,228,221
null
1
26
android|android-appcompat|android-toolbar
19,800
<p>You should not be using <code>theme</code> like that:</p> <ul> <li>style = local to the Toolbar</li> <li>theme = global to everything inflated in the Toolbar</li> </ul> <p>Workaround 2, as you call it, is kind of the correct way. If you want to extract some values into a style, you can do it as so:</p> <pre><code>&lt;android.support.v7.widget.Toolbar android:id="@+id/my_awesome_toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" style="@style/MyDarkToolbar" /&gt; </code></pre> <p>Style:</p> <pre><code>&lt;style name="MyDarkToolbarStyle" parent="Widget.AppCompat.Toolbar"&gt; &lt;item name="android:background"&gt;@color/green&lt;/item&gt; &lt;item name="popupTheme"&gt;@style/ThemeOverlay.AppCompat.Light&lt;/item&gt; &lt;item name="theme"&gt;@style/ThemeOverlay.AppCompat.Dark.ActionBar&lt;/item&gt; &lt;/style&gt; </code></pre>
9,660,763
What's the right statistic for iOS Memory footprint. Live Bytes? Real Memory? Other?
<p>I'm definitely confused on this point.</p> <p>I have an iPad application that shows 'Live Bytes' usage of 6-12mb in the object allocation instrument. If I pull up the memory monitor or activity monitor, the 'Real Memory' Column consistently climbs to around 80-90mb after some serious usage.</p> <p>So do I have a normal memory footprint or a high one?</p> <p><a href="https://stackoverflow.com/a/7574959/287403">This answer</a> and <a href="https://stackoverflow.com/a/8797272/287403">this answer</a> claim you should watch 'Live Bytes' as the 'Real Memory' column shows memory blocks that have been released, but the OS hasn't yet reclaimed it.</p> <p>On the other hand, <a href="https://stackoverflow.com/a/2868881/287403">this answer</a> claims you need to pay attention to that memory monitor, as the 'Live Bytes' doesn't include things like interface elements.</p> <p><strong>What is the deal with iOS memory footprint!?</strong> :)</p>
9,661,761
3
0
null
2012-03-12 01:39:18.93 UTC
15
2012-03-12 18:20:07.62 UTC
2017-05-23 12:23:23.547 UTC
null
-1
null
287,403
null
1
26
ios|memory|memory-management|diagnostics
7,624
<p>Those are simply two different metrics for measuring memory use. Which one is the "right" one depends on what question you're trying to answer.</p> <p>In a nutshell, the difference between "live bytes" and "real memory" is the difference between the amount of memory currently used for stuff that your app has created and the total amount of physical memory currently attributed to your app. There are at least two reasons that those are different:</p> <ul> <li><p><strong>code:</strong> Your app's code has to be loaded into memory, of course, and the virtual memory system surely attributes that to your app even though it's not memory that your app allocated.</p></li> <li><p><strong>memory pools:</strong> Most allocators work by maintaining one or more pools of memory from which they can carve off pieces for individual objects or allocated memory blocks. Most implementations of <code>malloc</code> work that way, and I expect that the object allocator does too. These pools aren't automatically resized downward when an object is deallocated -- the memory is just marked 'free' in the pool, but the whole pool will still be attributed to your app.</p></li> </ul> <p>There may be other ways that memory is attributed to your app without being directly allocated by your code, too.</p> <p>So, what are you trying to learn about your application? If you're trying to figure out why your app crashed due to low memory, look at both "live bytes" (to see what your app is using now) and "real memory" (to see how much memory the VM system says your app is using). If you're trying to improve your app's memory performance, looking at "live bytes" or "live objects" is more likely to help, since that's the memory that you can do something about.</p>
10,021,603
Calling a subclass method from superclass
<p>I am in an introductory java course and we just started learning about inheritance. I am working on a task that asks that we create a "Pet" superclass with name and age; and three subclasses, each with their own unique trait (I have chosen "Dog", "Cat", and "Bird"). After we have all these built, we are to create a Main class to test everything, and this is where I am running into problems. I am attempting to call the <code>get</code> methods for these unique traits within <code>Main</code>, but it seems to only find methods that are in the superclass.</p> <p>Here is the Main class:</p> <pre><code>public class Kennel { public static void main(String[] args) { // Create the pet objects Pet cat = new Cat("Feline", 12, "Orange"); Pet dog = new Dog("Spot", 14, "Dalmation"); Pet bird = new Bird("Feathers", 56, 12); // Print out the status of the animals System.out.println("I have a cat named " + cat.getName() + ". He is " + cat.getAge() + " years old." + " He is " + cat.getColor() + "When he speaks he says " + cat.speak()); System.out.println("I also have a dog named " + dog.getName() + ". He is " + dog.getAge() + " years old." + " He is a " + dog.getBreed() + " When he speaks he says " + dog.speak()); System.out.println("And Finally I have a bird named " + bird.getName() + ". He is " + bird.getAge() + " years old." + " He has a wingspan of " + bird.getWingspan() + " inches." + " When he speaks he says " + bird.speak()); } } </code></pre> <p>Here is my superclass </p> <pre><code>abstract public class Pet { private String name; private int age; // Constructor public Pet(String petName, int petAge) { this.name = petName; this.age = petAge; } // Getters public String getName() { return(this.name); } public int getAge() { return(this.age); } // Setters public void setName(String nameSet) { this.name = nameSet; } public void setAge(int ageSet) { this.age = ageSet; } // Other Methods abstract public String speak(); // toString @Override public String toString() { String answer = "Name: " + this.name + " Age: " + this.age; return answer; } } </code></pre> <p>And here is one of the subclasses (they all look the same and are having the same error)</p> <pre><code>public class Cat extends Pet { private String color; // Constructor public Cat(String petName, int petAge, String petColor) { super(petName, petAge); this.color = petColor; } // Getters public String getColor() { return(this.color); } // Setters public void setColor(String colorSet) { this.color = colorSet; } // Other Methods @Override public String speak() { return "Meow!"; } // toString @Override public String toString() { String answer = "Name: " + super.getName() + " Age: "+super.getAge() + " Color: " + this.color; return answer; } } </code></pre> <p>So what is happening is I can't get the main method to find the <code>cat.getColor()</code> method, or any of the other ones unique to the subclasses.</p>
10,021,690
5
0
null
2012-04-05 01:43:30.257 UTC
16
2020-11-17 08:00:19.903 UTC
2016-03-03 09:45:39.36 UTC
null
2,947,812
null
1,314,164
null
1
28
java|inheritance
85,271
<p>When you declare a variable as having the type of the superclass, you can only access (public) methods and member variables of the superclass through that variable.</p> <pre><code>Pet cat = new Cat("Feline",12,"Orange"); cat.getName(); // this is OK cat.getColor(); // this is not OK, getColor() is not in Pet </code></pre> <p>To access the methods in the concrete class (<code>Cat</code> in this case), you need to either declare the variable as the derived class</p> <pre><code>Cat cat = new Cat("Feline",12,"Orange"); cat.getName(); // OK, getName() is part of Cat (and the superclass) cat.getColor(); // OK, getColor() is part of Cat </code></pre> <p>Or cast it to a type you know/suspect is the concrete type</p> <pre><code>Pet cat = new Cat("Feline",12,"Orange"); ((Cat)cat).getName(); // OK (same as above) ((Cat)cat).getColor(); // now we are looking at cat through the glass of Cat </code></pre> <p>You can even combine the two methods:</p> <pre><code>Pet pet = new Cat("Feline",12,"Orange"); Cat cat = (Cat)pet; cat.getName(); // OK cat.getColor(); // OK </code></pre>
9,999,064
Select view template by model type/object value using Ember.js
<p>I would like to store different objects in the same controller content array and render each one using an appropriate view template, but ideally the same view.</p> <p>I am outputting list objects using the code below. They are currently identical, but I would like to be able to use different ones.</p> <pre><code>&lt;script type="text/x-handlebars"&gt; {{#each App.simpleRowController}} {{view App.SimpleRowView class="simple-row" contentBinding="this"}} {{/each}} &lt;/script&gt; </code></pre> <p>A cut-down version of the view is below. The other functions I haven't included could be used an any of the objects, regardless of model. So I would ideally have one view (although I have read some articles about mixins that could help if not).</p> <pre><code>&lt;script&gt; App.SimpleRowView = Em.View.extend({ templateName: 'simple-row-preview', }); &lt;/script&gt; </code></pre> <p>My first few tests into allowing different object types ended up with loads of conditions within 'simple-row-preview' - it looked terrible!</p> <p>Is there any way of dynamically controlling the templateName or view used while iterating over my content array?</p> <p><strong>UPDATE</strong></p> <p>Thanks very much to the two respondents. The final code in use on the view is below. Some of my models are similar, and I liked the idea of being able to switch between template (or a sort of 'state') in my application.</p> <pre><code>&lt;script&gt; App.SimpleRowView = Em.View.extend({ templateName: function() { return Em.getPath(this, 'content.template'); }.property('content.template').cacheable(), _templateChanged: function() { this.rerender(); }.observes('templateName'), // etc. }); &lt;/script&gt; </code></pre>
10,000,000
2
0
null
2012-04-03 18:20:12.303 UTC
9
2015-08-21 14:08:53.7 UTC
2015-08-21 14:08:53.7 UTC
null
63,550
null
426,171
null
1
32
javascript|ember.js
8,393
<p>You can make templateName a property and then work out what template to use based on the content. </p> <p>For example, this uses instanceof to set a template based on the type of object:</p> <pre><code>App.ItemView = Ember.View.extend({ templateName: function() { if (this.get("content") instanceof App.Foo) { return "foo-item"; } else { return "bar-item"; } }.property().cacheable() }); </code></pre> <p>Here's a fiddle with a working example of the above: <a href="http://jsfiddle.net/rlivsey/QWR6V/" rel="noreferrer">http://jsfiddle.net/rlivsey/QWR6V/</a></p>
9,991,882
$stmt->execute() : How to know if db insert was successful?
<p>With the following piece of code, how do i know that anything was inserted in to the db?</p> <pre><code>if ($stmt = $connection-&gt;prepare("insert into table (blah) values (?)")) { $stmt-&gt;bind_param("s", $blah); $stmt-&gt;execute(); $stmt-&gt;close(); } </code></pre> <p>I had thought adding the following line would have worked but apparently not.</p> <pre><code>if($stmt-&gt;affected_rows==-1){$updateAdded="N"; echo "failed";} </code></pre> <p>And then use the $updatedAdded="N" to then skip other pieces of code further down the page that are dependent on the above insert being successful.</p> <p>Any ideas?</p>
9,991,935
6
1
null
2012-04-03 10:59:11.22 UTC
9
2022-07-22 16:06:49.383 UTC
2022-07-22 15:09:57.643 UTC
null
285,587
null
1,271,796
null
1
53
php|mysqli
97,669
<p>The <a href="http://php.net/manual/en/mysqli-stmt.execute.php" rel="nofollow noreferrer"><code>execute()</code></a> method returns a <code>boolean</code> ... so just do this :</p> <pre><code>if ($stmt-&gt;execute()) { // it worked } else { // it didn't } </code></pre> <p><strong>Update:</strong> since 2022 and beyond, a failed query will throw an error Exception. So you won't have to write any code to &quot;skip other pieces of code further down the page&quot; - it will be skipped automatically. Therefore you shouldn't add any conditions and just write the code right away:</p> <pre><code>$stmt = $connection-&gt;prepare(&quot;insert into table (blah) values (?)&quot;); $stmt-&gt;bind_param(&quot;s&quot;, $blah); $stmt-&gt;execute(); </code></pre> <p>If you need to do something in case of success, then just do it right away, like</p> <pre><code>echo &quot;success&quot;; </code></pre> <p>You will see it only if the query was successful. Otherwise it will be the error message.</p>
9,786,102
How do I parallelize a simple Python loop?
<p>This is probably a trivial question, but how do I parallelize the following loop in python?</p> <pre><code># setup output lists output1 = list() output2 = list() output3 = list() for j in range(0, 10): # calc individual parameter value parameter = j * offset # call the calculation out1, out2, out3 = calc_stuff(parameter = parameter) # put results into correct output list output1.append(out1) output2.append(out2) output3.append(out3) </code></pre> <p>I know how to start single threads in Python but I don't know how to "collect" the results. </p> <p>Multiple processes would be fine too - whatever is easiest for this case. I'm using currently Linux but the code should run on Windows and Mac as-well.</p> <p>What's the easiest way to parallelize this code?</p>
9,786,225
15
1
null
2012-03-20 11:42:42.807 UTC
143
2022-08-09 17:48:08.337 UTC
2017-09-01 15:09:04.05 UTC
null
541,136
null
561,766
null
1
425
python|parallel-processing
576,838
<p>Using multiple threads on CPython won't give you better performance for pure-Python code due to the global interpreter lock (GIL). I suggest using the <a href="http://docs.python.org/library/multiprocessing.html"><code>multiprocessing</code></a> module instead:</p> <pre><code>pool = multiprocessing.Pool(4) out1, out2, out3 = zip(*pool.map(calc_stuff, range(0, 10 * offset, offset))) </code></pre> <p>Note that this won't work in the interactive interpreter.</p> <p>To avoid the usual FUD around the GIL: There wouldn't be any advantage to using threads for this example anyway. You <em>want</em> to use processes here, not threads, because they avoid a whole bunch of problems.</p>
11,819,720
Converting Repeated Measures mixed model formula from SAS to R
<p>There are several questions and posts about mixed models for more complex experimental designs, so I thought this more simple model would help other beginners in this process as well as I.</p> <p>So, my question is I would like to formulate a repeated measures ancova in R from sas proc mixed procedure:</p> <pre><code>proc mixed data=df1; FitStatistics=akaike class GROUP person day; model Y = GROUP X1 / solution alpha=.1 cl; repeated / type=cs subject=person group=GROUP; lsmeans GROUP; run; </code></pre> <p>Here is the SAS output using the data created in R (below):</p> <pre><code>. Effect panel Estimate Error DF t Value Pr &gt; |t| Alpha Lower Upper Intercept -9.8693 251.04 7 -0.04 0.9697 0.1 -485.49 465.75 panel 1 -247.17 112.86 7 -2.19 0.0647 0.1 -460.99 -33.3510 panel 2 0 . . . . . . . X1 20.4125 10.0228 7 2.04 0.0811 0.1 1.4235 39.4016 </code></pre> <p>Below is how I formulated the model in R using 'nlme' package, but am not getting similar coefficient estimates:</p> <pre><code>## create reproducible example fake panel data set: set.seed(94); subject.id = abs(round(rnorm(10)*10000,0)) set.seed(99); sds = rnorm(10,15,5);means = 1:10*runif(10,7,13);trends = runif(10,0.5,2.5) this = NULL; set.seed(98) for(i in 1:10) { this = c(this,rnorm(6, mean = means[i], sd = sds[i])*trends[i]*1:6)} set.seed(97) that = sort(rep(rnorm(10,mean = 20, sd = 3),6)) df1 = data.frame(day = rep(1:6,10), GROUP = c(rep('TEST',30),rep('CONTROL',30)), Y = this, X1 = that, person = sort(rep(subject.id,6))) ## use package nlme require(nlme) ## run repeated measures mixed model using compound symmetry covariance structure: summary(lme(Y ~ GROUP + X1, random = ~ +1 | person, correlation=corCompSymm(form=~day|person), na.action = na.exclude, data = df1,method='REML')) </code></pre> <p>Now, the output from R, which I now realize is similar to the output from <code>lm()</code>:</p> <pre><code> Value Std.Error DF t-value p-value (Intercept) -626.1622 527.9890 50 -1.1859379 0.2413 GROUPTEST -101.3647 156.2940 7 -0.6485518 0.5373 X1 47.0919 22.6698 7 2.0772934 0.0764 </code></pre> <p>I believe I'm close as to the specification, but not sure what piece I'm missing to make the results match (within reason..). Any help would be appreciated!</p> <p><strong>UPDATE:</strong> Using the code in the answer below, the R output becomes:</p> <pre><code>&gt; summary(model2) </code></pre> <p>Scroll to bottom for the parameter estimates -- look! identical to SAS.</p> <pre><code>Linear mixed-effects model fit by REML Data: df1 AIC BIC logLik 776.942 793.2864 -380.471 Random effects: Formula: ~GROUP - 1 | person Structure: Diagonal GROUPCONTROL GROUPTEST Residual StdDev: 184.692 14.56864 93.28885 Correlation Structure: Compound symmetry Formula: ~day | person Parameter estimate(s): Rho -0.009929987 Variance function: Structure: Different standard deviations per stratum Formula: ~1 | GROUP Parameter estimates: TEST CONTROL 1.000000 3.068837 Fixed effects: Y ~ GROUP + X1 Value Std.Error DF t-value p-value (Intercept) -9.8706 251.04678 50 -0.0393178 0.9688 GROUPTEST -247.1712 112.85945 7 -2.1900795 0.0647 X1 20.4126 10.02292 7 2.0365914 0.0811 </code></pre>
11,821,352
2
7
null
2012-08-05 20:15:52.86 UTC
10
2012-08-08 11:12:17.05 UTC
2012-08-08 01:23:22.923 UTC
null
594,795
null
594,795
null
1
6
r|sas|mixed-models
6,605
<p>Please try below:</p> <pre><code>model1 &lt;- lme( Y ~ GROUP + X1, random = ~ GROUP | person, correlation = corCompSymm(form = ~ day | person), na.action = na.exclude, data = df1, method = "REML" ) summary(model1) </code></pre> <p>I think <code>random = ~ groupvar | subjvar</code> option with <code>R</code> <code>lme</code> provides similar result of <code>repeated / subject = subjvar group = groupvar</code> option with <code>SAS/MIXED</code> in this case.</p> <p><strong>Edit:</strong></p> <p>SAS/MIXED</p> <p><img src="https://i.stack.imgur.com/7KMOS.gif" alt="SAS/MIXED covariance matrix"></p> <p>R (a revised model2)</p> <pre><code>model2 &lt;- lme( Y ~ GROUP + X1, random = list(person = pdDiag(form = ~ GROUP - 1)), correlation = corCompSymm(form = ~ day | person), weights = varIdent(form = ~ 1 | GROUP), na.action = na.exclude, data = df1, method = "REML" ) summary(model2) </code></pre> <p><img src="https://i.stack.imgur.com/dmHxk.gif" alt="R covariance matrix"></p> <p>So, I think these covariance structures are very similar (&sigma;<sub>g1</sub> = &tau;<sub>g</sub><sup>2</sup> + &sigma;<sub>1</sub>).</p> <p><strong>Edit 2:</strong> </p> <p>Covariate estimates (SAS/MIXED):</p> <pre><code>Variance person GROUP TEST 8789.23 CS person GROUP TEST 125.79 Variance person GROUP CONTROL 82775 CS person GROUP CONTROL 33297 </code></pre> <p>So </p> <pre><code>TEST group diagonal element = 125.79 + 8789.23 = 8915.02 CONTROL group diagonal element = 33297 + 82775 = 116072 </code></pre> <p>where diagonal element = &sigma;<sub>k1</sub> + &sigma;<sub>k</sub><sup>2</sup>.</p> <p>Covariate estimates (R lme):</p> <pre><code>Random effects: Formula: ~GROUP - 1 | person Structure: Diagonal GROUP1TEST GROUP2CONTROL Residual StdDev: 14.56864 184.692 93.28885 Correlation Structure: Compound symmetry Formula: ~day | person Parameter estimate(s): Rho -0.009929987 Variance function: Structure: Different standard deviations per stratum Formula: ~1 | GROUP Parameter estimates: 1TEST 2CONTROL 1.000000 3.068837 </code></pre> <p>So </p> <pre><code>TEST group diagonal element = 14.56864^2 + (3.068837^0.5 * 93.28885 * -0.009929987) + 93.28885^2 = 8913.432 CONTROL group diagonal element = 184.692^2 + (3.068837^0.5 * 93.28885 * -0.009929987) + (3.068837 * 93.28885)^2 = 116070.5 </code></pre> <p>where diagonal element = &tau;<sub>g</sub><sup>2</sup> + &sigma;<sub>1</sub> + &sigma;<sub>g</sub><sup>2</sup>.</p>
11,834,231
How to Wrap Text in HTML Option
<p>I want to put a dropdown list on my page, As one option is too long, when I click the select menu, it will expand and cover the other part of the page. </p> <pre><code>&lt;select id="selectlist" name="SelectProgram"&gt; &lt;option value="LIR" &gt;LIR&lt;/option&gt; &lt;option value="How to word wrap text in HTML?"&gt;How to word wrap text in HTML? CSS / HTML text wrap for webkit&lt;/option&gt; </code></pre> <p>The second option is too long and will expand. Is there any way I could wrap such a long text into 2 lines? Thank you!</p>
11,834,385
3
1
null
2012-08-06 19:00:41.84 UTC
1
2012-11-08 14:37:45.573 UTC
null
null
null
null
1,451,653
null
1
7
javascript|jquery|html
43,618
<p>Seeing as the value and text of a Select can be very different. I would say if in the event a string thats in your select for the text is longer than X truncate it.</p> <p>Example with jquery</p> <pre><code>$('#myselect option').each(function() { var myStr = $(this).text(); if(myStr.length &gt; 15){$(this).text(myStr.substring(15));} }); </code></pre> <p>put that in your document ready, and it will trim your text down to a better size, wrapping your elements in a div that will hide the overflow is going to make something of a mess later, and you will be back here trying to solve a similar issue caused by that for strings that are smaller.</p>
11,628,338
Automatic python code formatting in sublime
<p>I am trying to find some package that would auto format python code when using sublime.</p> <p>There is PythonTidy, but when I use PackageController it says install completed but the package is not installed (does not appear in preferences).</p> <p>I did try following the instructions in: <a href="https://github.com/witsch/SublimePythonTidy">https://github.com/witsch/SublimePythonTidy</a></p> <p>and while i "pip installed" the package in python, sublime would not load, throwing:</p> <pre><code>terminate called after throwing an instance of 'boost::python::error_already_set' /usr/bin/subl: line 3: 12415 Aborted /usr/lib/sublime-text-2/sublime_text --class=sublime-text-2 "$@" </code></pre> <p>How would I go about installing this without PackageController, or alternatively, can anyone recommend another package?</p>
11,708,239
3
0
null
2012-07-24 09:52:38.61 UTC
5
2018-10-08 15:35:34.417 UTC
null
null
null
null
1,724,926
null
1
15
python|sublimetext
40,312
<p>Try doing the following in command line (a bit brute force): </p> <ol> <li>Navigate into the <code>Packages/PythonTidy</code> folder,<br> usually <code>~/.config/sublime-text-2/Packages/PythonTidy</code><br> or <code>~/.config/sublime-text-2/Packages/SublimePythonTidy</code> <ul> <li>If it's non-existent reinstalling using <code>Package Control</code></li> </ul></li> <li>Inside there should be another <code>PythonTidy</code> folder (which in your case will be empty).<br> <strong>Don't get into it, just check it is empty</strong>.</li> <li>Run <code>git clone https://github.com/witsch/PythonTidy.git</code></li> <li>Restart sublime and check the console for errors (<code>View</code> -> <code>Show Console</code>)</li> </ol> <p><strong>P.S.</strong> If you are unable to start <code>Sublime</code> do a:</p> <pre><code>sudo pip uninstall PythonTidy </code></pre> <p>Then retry what I wrote above.</p>
11,816,041
Android ActionBar - Push custom view to bottom of screen
<p>I've got a split ActionBar, and I'm trying to add functionality almost identical to google play's 'Now playing'..</p> <p>I can get menu items to appear at the bottom of the screen, using the onCreateOptionsMenu, but I can't seem to get a custom view to appear at the bottom of the screen when using actionBar.setCustomView. The custom view just sits underneath the top ActionBar.</p> <p>Does anyone know how to force the customview to the bottom, or to add custom views to the onCreateOptionsMenu?</p> <p>Here are the snippets of my code:</p> <pre><code>public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ActionBar actionBar = getActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); actionBar.setDisplayShowTitleEnabled(true); actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); //Custom view to add actionBar.setCustomView(R.layout.albumitem); //This view shows up just under the top actionbar at the moment, despite menu items being at the bottom </code></pre> <p>The menu options code: (These are showing down the bottom where I'd like my custom view to be)</p> <pre><code>@Override public boolean onCreateOptionsMenu(Menu menu) { new MenuInflater(this).inflate(R.menu.option_menu, menu); return (super.onCreateOptionsMenu(menu)); } </code></pre> <p>I believe that the now playing menu at the bottom of the google play music app is a custom view inside a split action bar:</p> <p><img src="https://i.stack.imgur.com/sI1a4.jpg" alt="Google Play Music"></p>
11,980,554
2
1
null
2012-08-05 11:31:33.877 UTC
16
2014-10-19 00:06:32.393 UTC
2012-08-05 11:37:45.203 UTC
null
1,473,919
null
1,473,919
null
1
16
android|android-actionbar
13,415
<p>So I managed to find a dirty solution to this.. Well, dirty in my amateurish opinion..</p> <p>In the oncreateOptionsMenu, I've inflated a menu called option_menu like so:</p> <pre><code>@Override public boolean onCreateOptionsMenu(Menu menu) { new MenuInflater(this).inflate(R.menu.option_menu, menu); </code></pre> <p>And in the xml for that option_menu item, I've implemented an actionViewClass, and in this case I've used relative layout (I'm guessing I could've just used View..?):</p> <p> </p> <pre><code>&lt;item android:id="@+id/layout_item" android:actionViewClass="android.widget.RelativeLayout" android:showAsAction="always|withText" android:title="Text 1"/&gt; &lt;/menu&gt; </code></pre> <p>So then I inflated an xml layout, and added it to the layout_item defined in my menu:</p> <pre><code> @Override public boolean onCreateOptionsMenu(Menu menu) { new MenuInflater(this).inflate(R.menu.option_menu, menu); relativeLayout = (RelativeLayout) menu.findItem(R.id.layout_item) .getActionView(); View inflatedView = getLayoutInflater().inflate(R.layout.now_playing, null); relativeLayout.addView(inflatedView); return (super.onCreateOptionsMenu(menu)); } </code></pre> <p>Please feel free to edit/enhance this answer as you see fit.</p>
11,508,744
Django models filter by foreignkey
<p>I'm having some trouble in filtering objects from a set of models. Here is the problem:</p> <p>I have 3 classes:</p> <pre><code>class Autor(models.Model): nome = models.CharField(max_length=50) slug = models.SlugField(max_length=50, blank=True, unique=True) foto = models.ImageField(upload_to='autores/', null=True, blank=True) ... class CategoriaRecolha(models.Model): categoria = models.CharField(max_length=30) descricao = models.TextField() slug = models.SlugField(max_length=30, blank=True, unique=True) ... class Recolha(models.Model): titulo = models.CharField(max_length=100) slug = models.SlugField(max_length=100, blank=True, unique=True) descricao = models.TextField() ficha_tec = models.TextField() categoria = models.ForeignKey(CategoriaRecolha) autor = models.ForeignKey(Autor) .... </code></pre> <p>What I'm trying to retrieve is the fields of the class Autor, in which the field categoria of the class Recolha is equal to a specific value.</p> <p>In a more simple way, I need to get the all the autor that have participated in a specific categoria.</p> <p>Thanks</p>
11,509,061
3
0
null
2012-07-16 16:43:36.013 UTC
5
2018-01-31 10:43:30.617 UTC
2014-12-05 21:45:18.567 UTC
null
464,923
null
1,529,502
null
1
22
django|filter|foreign-keys|models
57,331
<p>A more direct alternative:</p> <pre><code>autors = Autor.objects.filter(recolha__categoria=MyCategoria) </code></pre> <p>where <code>MyCategoria</code> is the relevant <code>CategoriaRecolha</code> instance. Or, if you want to match agains the specific category name, you can extend the query another level:</p> <pre><code>autors = Autor.objects.filter(recolha__categoria__categoria='my_category_name') </code></pre>
11,770,794
How to set permissions in broadcast sender and receiver in android
<p>How do we specify in broadcast sending application that which application can receive this broadcast, and in receiving application that which particular application has the permission to send broadcast to its broadcast receiver...</p> <p>I am new to android..I read the documentation etc on internet but couldn't find the syntax to specify these permissions.</p>
11,770,833
5
0
null
2012-08-02 03:49:18.047 UTC
25
2018-02-07 12:34:48.27 UTC
null
null
null
null
1,204,089
null
1
37
android|broadcastreceiver
63,580
<p>use an intent filter in receiver tag in manifest</p> <pre><code> &lt;receiver android:name="Your receiver" android:enabled="true" android:exported="false" &gt; &lt;intent-filter&gt; &lt;action android:name="action"/&gt; &lt;category android:name="category" /&gt; &lt;/intent-filter&gt; &lt;/receiver&gt; </code></pre> <p>To send broadcast to app</p> <pre><code> Intent intent = new Intent(); intent.setAction("use same action in receiver"); intent.addcategory("use same category in receiver"); context.sendBroadcast(intent); </code></pre>
11,558,334
Get rid of "Exported service does not require permission" warning
<p>I'm looking for a solution to get rid of the warning. I don't understand even why it appears. I took a look at a SDK example where no warning appears.</p> <p>At first here is my manifest where I get the warning <em>Exported service does not require permission</em>:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.android" android:versionCode="1" android:versionName="1.0" &gt; &lt;uses-sdk android:minSdkVersion="8" android:targetSdkVersion="15" /&gt; &lt;uses-feature android:name="android.hardware.camera" android:required="true" /&gt; &lt;uses-permission android:name="android.permission.GET_ACCOUNTS" /&gt; &lt;uses-permission android:name="android.permission.USE_CREDENTIALS" /&gt; &lt;uses-permission android:name="android.permission.MANAGE_ACCOUNTS" /&gt; &lt;uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS" /&gt; &lt;uses-permission android:name="android.permission.READ_SYNC_SETTINGS" /&gt; &lt;uses-permission android:name="android.permission.WRITE_SYNC_SETTINGS" /&gt; &lt;application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/Theme.Sherlock"&gt; &lt;service android:name=".AuthenticationService" android:exported="true"&gt; &lt;intent-filter&gt; &lt;action android:name="android.accounts.AccountAuthenticator" /&gt; &lt;/intent-filter&gt; &lt;meta-data android:name="android.accounts.AccountAuthenticator" android:resource="@xml/authenticator" /&gt; &lt;/service&gt; &lt;activity android:name=".Test" android:label="@string/app_name" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;category android:name="android.intent.category.LAUNCHER" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; ... </code></pre> <p>While the <strong>SampleSyncAdapter</strong> of the Android SDK has this manifest:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.android.samplesync" android:versionCode="1" android:versionName="1.0"&gt; &lt;uses-permission android:name="android.permission.GET_ACCOUNTS" /&gt; &lt;uses-permission android:name="android.permission.USE_CREDENTIALS" /&gt; &lt;!-- ... --&gt; &lt;uses-sdk android:minSdkVersion="8" android:targetSdkVersion="15" /&gt; &lt;application android:icon="@drawable/icon" android:label="@string/label"&gt; &lt;!-- The authenticator service --&gt; &lt;service android:name=".authenticator.AuthenticationService" android:exported="true"&gt; &lt;intent-filter&gt; &lt;action android:name="android.accounts.AccountAuthenticator" /&gt; &lt;/intent-filter&gt; &lt;meta-data android:name="android.accounts.AccountAuthenticator" android:resource="@xml/authenticator" /&gt; &lt;/service&gt; ... </code></pre> <p>But there is no warning. Why the hell do I get a warning? Well I use the Theme.Sherlock theme for the usage of the <em>ActionBarSherlock</em>. But I cannot imagine that this causes the error.</p>
11,562,025
3
8
null
2012-07-19 09:58:55.523 UTC
4
2014-09-01 17:22:18.96 UTC
2013-01-26 20:30:36.733 UTC
null
995,926
null
995,926
null
1
41
android|android-activity|warnings|android-manifest|android-service
23,005
<p>The warning is telling you that you have exported (ie: made publicly available) a service without securing it with a permission. This makes your service available to any other applications without restrictions. See <a href="https://stackoverflow.com/questions/10474134/exported-service-does-not-require-permission-what-does-it-mean">Exported service does not require permission: what does it mean?</a></p> <p>If your service doesn't need to be available to other applications, you don't need to export it. Explicitly setting <code>android:exported="false"</code> will remove the warning.</p> <p><strong>Note:</strong> The default value for <code>android:exported</code> is <code>true</code> if you have provided an Intent filter.</p>
3,410,548
Maven: add a folder or jar file into current classpath
<p>I am using maven-compile plugin to compile classes. Now I would like to add one jar file into the current classpath. That file stays in another location (let's say c:/jars/abc.jar . I prefer to leave this file here). How can I do that?</p> <p>If I use classpath in the argument:</p> <pre><code>&lt;configuration&gt; &lt;compilerArguments&gt; &lt;classpath&gt;c:/jars/abc.jar&lt;/classpath&gt; &lt;/compilerArguments&gt; &lt;/configuration&gt; </code></pre> <p>it will not work because it will override the current classpath (that includes all the dependencies)</p>
3,410,712
4
3
null
2010-08-04 23:03:10.07 UTC
5
2021-10-19 16:45:23.597 UTC
2021-09-03 06:59:28.127 UTC
null
187,141
null
405,855
null
1
25
maven-2|jar|classpath
147,488
<p>This might have been asked before. See <a href="https://stackoverflow.com/questions/364114/can-i-add-jars-to-maven-2-build-classpath-without-installing-them#364188">Can I add jars to maven 2 build classpath without installing them?</a></p> <p>In a nutshell: include your jar as dependency with system scope. This requires specifying the absolute path to the jar. </p> <p>See also <a href="http://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html" rel="nofollow noreferrer">http://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html</a></p>
3,294,553
jQuery Selector + SVG Incompatible?
<p>I've been working with an HTML5 document with inline SVG and javascript animation.</p> <p>I'd like to have a box pop up when the user clicks anywhere, and I'd like the box to go away when the user clicks somewhere that isn't the box. This means I can't use <code>$(window).click()</code>, which works.</p> <p>I've tried selecting the SVGs on top by giving them class names and using <code>$(".svgclassname").click()</code>, but this doesn't seem to work. Neither does selecting individual ones with <code>$("#svgname").click()</code>.</p> <p>What is the problem?</p> <p>(When I replace <code>$(".eyesvg")</code> with <code>$(window)</code>, a blue box appears near the cursor when the user clicks anywhere in the window.)</p>
5,759,456
4
1
null
2010-07-20 21:33:42.457 UTC
19
2022-01-15 17:00:13.857 UTC
2016-01-11 00:55:04.473 UTC
null
638,452
null
392,113
null
1
41
javascript|jquery|xhtml|jquery-selectors|svg
39,869
<p>This happens because SVG DOM spec differs a lot from HTML DOM. </p> <p>SVG DOM is a different dialect, and some properties have same names but mean different things. For example, to get the className of an svg element, you use:</p> <pre><code>svg.className.baseVal </code></pre> <p>The properites affected by this are</p> <pre><code>className is SVGAnimatedString height,width, x, y, offsetWidth, offsetHeight are SVGAnimatedLength </code></pre> <p>These Animated properties are structs, with <code>baseVal</code> holding the same value you'd find in HTML DOM and <code>animatedVal</code> holding I am not sure what.</p> <p>SVG DOM is also missing some properties libraries depend on, such as <code>innerHTML</code>.</p> <p>This breaks jQuery in many ways, anything that depends on above properties fails.</p> <p>In general, SVG DOM and HTML DOM do not mix very well. They work together just enough to lure you in, and then things break quietly, and another angel loses its wings.</p> <p>I wrote a little jQuery extension that wraps SVG elements to make them look more like HTML DOM</p> <pre><code>(function (jQuery){ function svgWrapper(el) { this._svgEl = el; this.__proto__ = el; Object.defineProperty(this, "className", { get: function(){ return this._svgEl.className.baseVal; }, set: function(value){ this._svgEl.className.baseVal = value; } }); Object.defineProperty(this, "width", { get: function(){ return this._svgEl.width.baseVal.value; }, set: function(value){ this._svgEl.width.baseVal.value = value; } }); Object.defineProperty(this, "height", { get: function(){ return this._svgEl.height.baseVal.value; }, set: function(value){ this._svgEl.height.baseVal.value = value; } }); Object.defineProperty(this, "x", { get: function(){ return this._svgEl.x.baseVal.value; }, set: function(value){ this._svgEl.x.baseVal.value = value; } }); Object.defineProperty(this, "y", { get: function(){ return this._svgEl.y.baseVal.value; }, set: function(value){ this._svgEl.y.baseVal.value = value; } }); Object.defineProperty(this, "offsetWidth", { get: function(){ return this._svgEl.width.baseVal.value; }, set: function(value){ this._svgEl.width.baseVal.value = value; } }); Object.defineProperty(this, "offsetHeight", { get: function(){ return this._svgEl.height.baseVal.value; }, set: function(value){ this._svgEl.height.baseVal.value = value; } }); }; jQuery.fn.wrapSvg = function() { return this.map(function(i, el) { if (el.namespaceURI == "http://www.w3.org/2000/svg" &amp;&amp; !('_svgEl' in el)) return new svgWrapper(el); else return el; }); }; })(window.jQuery); </code></pre> <p>It creates a wrapper around SVG objects that makes them look like HTML DOM to jQuery. I've used it with jQuery-UI to make my SVG elements droppable.</p> <p>The lack of DOM interoperability between HTML and SVG is a total disaster. All the sweet utility libraries written for HTML have to be reinvented for SVG.</p>
3,225,682
Convert char[] to LPCWSTR
<p>Can anyone help me to correct this code:</p> <pre><code> char szBuff[64]; sprintf(szBuff, "%p", m_hWnd); MessageBox(NULL, szBuff, L"Test print handler", MB_OK); </code></pre> <p>The error is, it cant convert the 2nd parameter to LPCWSTR.</p>
3,225,715
5
0
null
2010-07-12 03:29:17.693 UTC
2
2013-10-23 02:49:14.09 UTC
null
null
null
null
359,085
null
1
9
visual-c++
60,714
<p>For this <em>specific</em> case, the fix is quite simple:</p> <pre><code>wchar_t szBuff[64]; swprintf(szBuff, L"%p", m_hWnd); MessageBox(NULL, szBuff, L"Test print handler", MB_OK); </code></pre> <p>That is, use Unicode strings throughout. In general, when programming on Windows, using <code>wchar_t</code> and UTF-16 is probably the simplest. It depends on how much interaction with other systems you have to do, of course.</p> <p>For the general case, if you've got an ASCII (or <code>char *</code>) string, use either <a href="http://msdn.microsoft.com/en-us/library/dd374130%28VS.85%29.aspx" rel="noreferrer">WideCharToMultiByte</a> for the general case, or <code>mbstowcs</code> as @Matthew points out for simpler cases (<code>mbstowcs</code> works if the string is in the current C locale).</p>
3,666,030
How to avoid multiple nested IFs
<p>I am currently trying to restructure my program to be more OO and to better implement known patterns etc.</p> <p>I have quite many nested IF-statements and want to get rid of them. How can I go about this? My first approach was to get it done with exceptions, so e.g.</p> <pre><code>public static Boolean MyMethod(String param) { if (param == null) throw new NullReferenceException("param may not be null"); if (param.Equals("none") || param.Equals("0") || param.Equals("zero")) throw new ArgumentNullException("param may not be zero"); // Do some stuff with param // This is not executed if param is null, as the program stops a soon // as one of the above exceptions is thrown } </code></pre> <p>The method is used in the main class of the application, e.g.</p> <pre><code>static void Main() { try { Boolean test = MyClass.MyMethod(null); // Will throw an exception } catch (Exception ex) { MessageBox.Show(ex.Message, "Error"); } </code></pre> <p>I think this is quite nice, as it prevents the nested statements and nearly all of the methods actions are nicely arranged on one level.</p> <p>As with IF-statements, the method would look like this</p> <pre><code>public Boolean MyMethod(String param) { if (param != null) { if (!param.Equals("none") &amp;&amp; !param.Equals("0") &amp;&amp; !param.Equals("zero")) { // Do some stuff with param } else { MessageBox.Show("param may not be zero", "Error"); } else { MessageBox.Show("param may not be null", "Error"); } } </code></pre> <p>Which I find very, very ugly and hard to maintain.</p> <p>Now, the question is; is this approach <em>good</em>? I know, that might be subjective, but how do you overcome nested IFs (1 or 2 levels are not that bad, but it gets worse after that...)</p>
3,666,099
6
5
null
2010-09-08 08:49:48.94 UTC
11
2010-09-08 10:00:59.08 UTC
2010-09-08 09:17:11.73 UTC
null
204,693
null
204,693
null
1
23
c#|design-patterns|exception|if-statement
23,055
<p>It really depends on their purpose. In your first sample, the if statements serves the purpose of enforcing a contract, making sure that the input to the method meets certain requirements. In those cases, my own code tend to look pretty much like your code.</p> <p>In the case of using the if blocks to control the flow of a method (rather than enforcing a contract), it can sometimes be a bit harder. Sometimes I come across code like the following (extremely simplified) example:</p> <pre><code>private void SomeMethod() { if (someCondition == true) { DoSomething(); if (somethingElse == true) { DoSomethingMore(); } } else { DoSomethingElse(); } } </code></pre> <p>In this case, it seems as if the method has several responsibilities, so in this case I would probably choose to split it into several methods:</p> <pre><code>private void SomeMethod() { if (someCondition == true) { DoItThisWay(); } else { DoSomethingElse(); } } private void DoItThisWay() { DoSomething(); if (somethingElse == true) { DoSomethingMore(); } } </code></pre> <p>This makes each method much simpler with less nested code, and may also increase the readability, if the methods are given good names.</p>
3,983,325
Calculate distance between Zip Codes... AND users.
<p><strong>This is more of a challenge question than something I urgently need, so don't spend all day on it guys.</strong></p> <p>I built a dating site (long gone) back in 2000 or so, and one of the challenges was calculating the distance between users so we could present your "matches" within an X mile radius. To just state the problem, given the following database schema (roughly):</p> <p>USER TABLE UserId UserName ZipCode</p> <p>ZIPCODE TABLE ZipCode Latitude Longitude</p> <p>With USER and ZIPCODE being joined on USER.ZipCode = ZIPCODE.ZipCode.</p> <p>What approach would you take to answer the following question: What other users live in Zip Codes that are within X miles of a given user's Zip Code.</p> <p>We used the <a href="http://www.census.gov/geo/www/gazetteer/places2k.html" rel="nofollow noreferrer">2000 census data</a>, which has tables for zip codes and their approximate lattitude and longitude.</p> <p>We also used the <a href="http://en.wikipedia.org/wiki/Haversine_formula" rel="nofollow noreferrer">Haversine Formula</a> to calculate distances between any two points on a sphere... pretty simple math really.</p> <p>The question, at least for us, being the 19 year old college students we were, really became how to efficiently calculate and/store distances from all members to all other members. One approach (the one we used) would be to import all the data and calculate the distance FROM every zip code TO every other zip code. Then you'd store and index the results. Something like:</p> <pre><code>SELECT User.UserId FROM ZipCode AS MyZipCode INNER JOIN ZipDistance ON MyZipCode.ZipCode = ZipDistance.MyZipCode INNER JOIN ZipCode AS TheirZipCode ON ZipDistance.OtherZipCode = TheirZipCode.ZipCode INNER JOIN User AS User ON TheirZipCode.ZipCode = User.ZipCode WHERE ( MyZipCode.ZipCode = 75044 ) AND ( ZipDistance.Distance &lt; 50 ) </code></pre> <p>The problem, of course, is that the ZipDistance table is going to have a LOT of rows in it. It isn't completely unworkable, but it is really big. Also it requires complete pre-work on the whole data set, which is also not unmanageable, but not necessarily desireable.</p> <p>Anyway, I was wondering what approach some of you gurus might take on something like this. Also, I think this is a common issue programmers have to tackle from time to time, especially if you consider problems that are just algorithmically similar. I'm interested in a thorough solution that includes at least HINTS on all the pieces to do this really quickly end efficiently. Thanks!</p>
3,991,366
8
0
null
2010-10-21 00:13:03.663 UTC
26
2017-09-22 16:27:30.497 UTC
2017-09-22 16:27:30.497 UTC
null
406,732
null
406,732
null
1
34
database|gis|geocoding|distance|zipcode
49,494
<p>Ok, for starters, you don't really need to use the Haversine formula here. For large distances where a less accurate formula produces a larger error, your users don't care if the match is plus or minus a few miles, and for closer distances, the error is very small. There are easier (to calculate) formulas listed on the <a href="http://en.wikipedia.org/wiki/Geographical_distance" rel="noreferrer">Geographical Distance</a> Wikipedia article.</p> <p>Since zip codes are nothing like evenly spaced, any process that partitions them evenly is going to suffer mightily in areas where they are clustered tightly (east coast near DC being a good example). If you want a visual comparison, check out <a href="http://benfry.com/zipdecode" rel="noreferrer">http://benfry.com/zipdecode</a> and compare the zipcode prefix 89 with 07.</p> <p>A far better way to deal with indexing this space is to use a data structure like a <a href="http://en.wikipedia.org/wiki/Quadtree" rel="noreferrer">Quadtree</a> or an <a href="http://en.wikipedia.org/wiki/R-tree" rel="noreferrer">R-tree</a>. This structure allows you to do spatial and distance searches over data which is not evenly spaced.</p> <p>Here's what an Quadtree looks like:</p> <p><img src="https://i.stack.imgur.com/yChC3.png" alt="Quadtree"></p> <p>To search over it, you drill down through each larger cell using the index of smaller cells that are within it. Wikipedia explains it more thoroughly.</p> <p>Of course, since this is a fairly common thing to do, someone else has already done the hard part for you. Since you haven't specified what database you're using, the PostgreSQL extension <a href="http://en.wikipedia.org/wiki/PostGIS" rel="noreferrer">PostGIS</a> will serve as an example. PostGIS includes the ability to do R-tree spatial indexes which allow you to do efficient spatial querying.</p> <p>Once you've imported your data and built the spatial index, querying for distance is a query like:</p> <pre><code>SELECT zip FROM zipcode WHERE geom &amp;&amp; expand(transform(PointFromText('POINT(-116.768347 33.911404)', 4269),32661), 16093) AND distance( transform(PointFromText('POINT(-116.768347 33.911404)', 4269),32661), geom) &lt; 16093 </code></pre> <p>I'll let you work through the rest of the tutorial yourself.</p> <ul> <li><a href="http://unserializableone.blogspot.com/2007/02/using-postgis-to-find-points-of.html" rel="noreferrer">http://unserializableone.blogspot.com/2007/02/using-postgis-to-find-points-of.html</a></li> </ul> <p>Here are some other references to get you started.</p> <ul> <li><a href="http://www.bostongis.com/PrinterFriendly.aspx?content_name=postgis_tut02" rel="noreferrer">http://www.bostongis.com/PrinterFriendly.aspx?content_name=postgis_tut02</a></li> <li><a href="http://www.manning.com/obe/PostGIS_MEAPCH01.pdf" rel="noreferrer">http://www.manning.com/obe/PostGIS_MEAPCH01.pdf</a></li> <li><a href="http://postgis.refractions.net/docs/ch04.html" rel="noreferrer">http://postgis.refractions.net/docs/ch04.html</a></li> </ul>
3,820,996
Delphi 2010: How to save a whole record to a file?
<p>I have defined a record which has lots of fields with different types (integer, real , string, ... plus dynamic arrays in terms of "array of ..."). I want to save it as a whole to a file and then be able to load it back to my program. I don't want to go through saving each field's value individually. The file type (binary or ascii or ...) is not important as long Delphi could read it back to a record.</p> <p>Do you have any suggestions?</p>
3,821,120
9
3
null
2010-09-29 11:06:08.753 UTC
9
2019-03-24 10:36:01.447 UTC
2010-10-01 11:11:52.173 UTC
null
336,557
null
336,557
null
1
20
delphi|file-io|delphi-2010
22,346
<p>You can load and save the memory of a record directly to and from a stream, as long as you don't use dynamic arrays. So if you use strings, you need to make them fixed:</p> <pre><code>type TTestRecord = record FMyString : string[20]; end; var rTestRecord: TTestRecord; strm : TMemoryStream; strm.Write(rTestRecord, Sizeof(TTestRecord) ); </code></pre> <p>You can even load or save an array of record at once!</p> <pre><code>type TRecordArray = array of TTestRecord; var ra : TRecordArray; strm.Write(ra[0], SizeOf(TTestRecord) * Length(ra)); </code></pre> <p>In case you want to write dynamic content: </p> <pre><code>iCount := Length(aArray); strm.Write(iCount, Sizeof(iCount) ); //first write our length strm.Write(aArray[0], SizeOf * iCount); //then write content </code></pre> <p>After that, you can read it back:</p> <pre><code>strm.Read(iCount, Sizeof(iCount) ); //first read the length SetLength(aArray, iCount); //then alloc mem strm.Read(aArray[0], SizeOf * iCount); //then read content </code></pre>
3,340,802
Add line break within tooltips
<p>How can line breaks be added within a HTML tooltip?</p> <p>I tried using <code>&lt;br/&gt;</code> and <code>\n</code> within the tooltip as follows: </p> <pre><code>&lt;a href="#" title="Some long text &lt;br/&gt; Second line text \n Third line text"&gt;Hover me&lt;/a&gt; </code></pre> <p>However, this was useless and I could see the literal text <code>&lt;br/&gt;</code> and <code>\n</code> within the tooltip. Any suggestions will be helpful.</p>
9,118,551
27
4
null
2010-07-27 04:44:28.163 UTC
41
2021-04-07 15:21:47.833 UTC
2016-08-10 20:53:03.41 UTC
null
1,454,671
null
306,961
null
1
216
html|tooltip|newline
283,621
<p>Just use the entity code <code>&amp;#013;</code> for a linebreak in a title attribute.</p>
8,258,432
Days between two dates?
<p>What's the shortest way to see how many full days have passed between two dates? Here's what I'm doing now.</p> <pre><code>math.floor((b - a).total_seconds()/float(86400)) </code></pre>
8,258,465
4
3
null
2011-11-24 14:15:06.117 UTC
29
2019-03-09 20:30:00.87 UTC
2019-03-09 20:30:00.87 UTC
null
355,230
null
8,005
null
1
160
python|date
222,324
<p>Assuming you’ve literally got two date objects, you can subtract one from the other and query the resulting <a href="http://docs.python.org/library/datetime.html#timedelta-objects" rel="noreferrer"><code>timedelta</code> object</a> for the number of days:</p> <pre><code>&gt;&gt;&gt; from datetime import date &gt;&gt;&gt; a = date(2011,11,24) &gt;&gt;&gt; b = date(2011,11,17) &gt;&gt;&gt; a-b datetime.timedelta(7) &gt;&gt;&gt; (a-b).days 7 </code></pre> <p>And it works with datetimes too — I think it rounds down to the nearest day:</p> <pre><code>&gt;&gt;&gt; from datetime import datetime &gt;&gt;&gt; a = datetime(2011,11,24,0,0,0) &gt;&gt;&gt; b = datetime(2011,11,17,23,59,59) &gt;&gt;&gt; a-b datetime.timedelta(6, 1) &gt;&gt;&gt; (a-b).days 6 </code></pre>
7,836,632
How to replace different newline styles in PHP the smartest way?
<p>I have a text which might have different newline styles. I want to replace all newlines '\r\n', '\n','\r' with the same newline (in this case \r\n ).</p> <p>What's the fastest way to do this? My current solution looks like this which is way sucky:</p> <pre><code> $sNicetext = str_replace("\r\n",'%%%%somthing%%%%', $sNicetext); $sNicetext = str_replace(array("\r","\n"),array("\r\n","\r\n"), $sNicetext); $sNicetext = str_replace('%%%%somthing%%%%',"\r\n", $sNicetext); </code></pre> <p>Problem is that you can't do this with one replace because the \r\n will be duplicated to \r\n\r\n .</p> <p>Thank you for your help!</p>
7,836,692
5
3
null
2011-10-20 13:26:20.43 UTC
17
2022-02-26 02:06:10.417 UTC
null
null
null
null
974,390
null
1
40
php|replace|newline|unify
32,117
<pre><code>$string = preg_replace('~\R~u', "\r\n", $string); </code></pre> <p>If you don't want to replace all Unicode newlines but only CRLF style ones, use:</p> <pre><code>$string = preg_replace('~(*BSR_ANYCRLF)\R~', "\r\n", $string); </code></pre> <p><code>\R</code> matches these newlines, <code>u</code> is a modifier to treat the input string as UTF-8.</p> <hr> <p>From the <a href="http://www.pcre.org/pcre.txt">PCRE docs</a>:</p> <blockquote> <p><strong>What <code>\R</code> matches</strong></p> <p>By default, the sequence \R in a pattern matches any Unicode newline sequence, whatever has been selected as the line ending sequence. If you specify</p> <pre><code> --enable-bsr-anycrlf </code></pre> <p>the default is changed so that \R matches only CR, LF, or CRLF. Whatever is selected when PCRE is built can be overridden when the library functions are called.</p> </blockquote> <p>and</p> <blockquote> <p><strong>Newline sequences</strong></p> <p>Outside a character class, by default, the escape sequence \R matches any Unicode newline sequence. In non-UTF-8 mode \R is equivalent to the following:</p> <pre><code> (?&gt;\r\n|\n|\x0b|\f|\r|\x85) </code></pre> <p>This is an example of an "atomic group", details of which are given below. This particular group matches either the two-character sequence CR followed by LF, or one of the single characters LF (linefeed, U+000A), VT (vertical tab, U+000B), FF (formfeed, U+000C), CR (carriage return, U+000D), or NEL (next line, U+0085). The two-character sequence is treated as a single unit that cannot be split.</p> <p>In UTF-8 mode, two additional characters whose codepoints are greater than 255 are added: LS (line separator, U+2028) and PS (paragraph separator, U+2029). Unicode character property support is not needed for these characters to be recognized.</p> <p>It is possible to restrict \R to match only CR, LF, or CRLF (instead of the complete set of Unicode line endings) by setting the option PCRE_BSR_ANYCRLF either at compile time or when the pattern is matched. (BSR is an abbrevation for "backslash R".) This can be made the default when PCRE is built; if this is the case, the other behaviour can be requested via the PCRE_BSR_UNICODE option. It is also possible to specify these settings by starting a pattern string with one of the following sequences:</p> <pre><code> (*BSR_ANYCRLF) CR, LF, or CRLF only (*BSR_UNICODE) any Unicode newline sequence </code></pre> <p>These override the default and the options given to pcre_compile() or pcre_compile2(), but they can be overridden by options given to pcre_exec() or pcre_dfa_exec(). Note that these special settings, which are not Perl-compatible, are recognized only at the very start of a pattern, and that they must be in upper case. If more than one of them is present, the last one is used. They can be combined with a change of newline convention; for example, a pattern can start with:</p> <pre><code> (*ANY)(*BSR_ANYCRLF) </code></pre> <p>They can also be combined with the (*UTF8) or (*UCP) special sequences. Inside a character class, \R is treated as an unrecognized escape sequence, and so matches the letter "R" by default, but causes an error if PCRE_EXTRA is set.</p> </blockquote>
8,231,746
concatenate stringstream in c++
<p>How can I concatenate two stringstreams?</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;sstream&gt; #include &lt;string&gt; #include "types.h" int main () { char dest[1020] = "you"; char source[7] = "baby"; stringstream a,b; a &lt;&lt; source; b &lt;&lt; dest; a &lt;&lt; b; /*HERE NEED CONCATENATE*/ cout &lt;&lt; a &lt;&lt; endl; cout &lt;&lt; a.str() &lt;&lt; endl; return 0; } </code></pre> <p>The output is the following in both tries:</p> <pre><code>0xbf8cfd20 baby0xbf8cfddc </code></pre> <p>The desired output is <code>babyyou</code>.</p>
8,231,778
6
0
null
2011-11-22 18:22:28.753 UTC
null
2013-08-28 19:41:50.583 UTC
2011-11-22 18:23:20.303 UTC
null
298,054
null
945,511
null
1
10
c++|concatenation|stringstream
38,537
<p>Should be:</p> <pre><code>b &lt;&lt; dest; a &lt;&lt; b.str(); </code></pre> <p><a href="http://en.cppreference.com/w/cpp/io/basic_stringstream/str" rel="noreferrer"><code>stringstream::str</code></a> returns the underlying string in the <code>stringstream</code>.</p>
4,240,402
Syncing comments between Facebook and Wordpress
<p>I'm working on implementing a two-way sync for a website that started as a Facebook fan page years ago and now is going to be run primarily off site. </p> <p>Right now here's the process I'm using:</p> <ol> <li>Import Posts + Comments from the Graph API. Posts are stored as Wordpress posts, comments are stored as Wordpress comments and some additional data such as Facebook Post ID or Post Author are stored in the post meta. </li> <li>I've created a second submission form (only admin can submit posts from Wordpress site) that uses the Graph API to post directly to the fan page, then run the importer so that when the post is first entered into the database, it already has it's FB_POST_ID attached. </li> <li>Comments from Facebook are easily updated and added to Wordpress. FB-Connect allows Facebook users to login and comment on the Wordpress but those comments are not synced with Facebook as I can't attach a user comment to a Facebook post via the Graph API (I can't control other users). </li> </ol> <p>Has anyone run into anything similar or have other ideas for how I could achieve a "two-way" sync? (Quotes as my current setup is technically one-way that mimics two-way. New posts bypass Wordpress then get synced from Facebook).</p>
7,373,606
3
1
null
2010-11-21 21:15:40.913 UTC
10
2018-03-21 04:05:11.907 UTC
2012-01-07 20:01:26.837 UTC
user212218
null
null
251,158
null
1
9
facebook|wordpress|facebook-graph-api
8,869
<p>This question is a bit old, but I actually got here from the official <a href="https://developers.facebook.com/docs/reference/plugins/comments/" rel="nofollow">Facebook comments plugin page</a> so I'm answering. </p> <p>There is a plugin called <a href="http://wordpress.org/extend/plugins/wp-fb-comments/" rel="nofollow">WP-FB Comments</a></p> <p>It's working fine, you can <a href="http://giannopoulos.net/2011/07/06/the-wordpressfacebook-game-round-ii/" rel="nofollow">read my experience with it</a> on my blog (currently trying out Livefyre so you wont see it in action)</p>
4,049,644
"Redirect" page without refresh (Facebook photos style)
<p>I am trying to implement content browsing like it is done on Facebook when user is browsing the photos. I guess everyone is familiar with that photo browsing where you can click "next" and "previous" and immediately get the next or previous photo (you can also navigate using arrow keys).</p> <p>When you click "next" for example you notice that the page does not refresh - only the content. At first I thought it is done using plain ajax calls which refresh only the "content" in this case the image, description and comments. But then I noticed that also URL in the "Location" toolbar of my browser is changed! I tried to inspect this using Firebug and discovered that when you click "next" only the next photo is downloaded and I still don't know from where the comments &amp; image meta data (description, time, tags,...) are loaded. </p> <p>Can someone please explain how this technique is done - page URL changes without page refresh (or even without page "blinking" if it refreshes from cache). I know how to change page content using ajax but URL of that page stays the same all the time. If I click on "refresh" button I get the first page again. But not on Facebook since even the "window.location" is changed every time without actual redirect.</p> <p>The other thing I noticed is that the bottom toolbar (applications, chat, ...) is "always on top". Even if you change the page, this toolbar is not refreshed and always stays on top - it doesn't even "blink" like other pages that are refreshed (either from webserver or from local cache). I guess this is the same technique as above - some kind of "fake" redirects or something?</p> <p><strong>The Answer is pushState</strong></p> <pre><code>if (window.history.pushState) window.history.pushState([object or string], [title], [new link]); </code></pre> <p>You will smile :)</p>
4,049,790
3
1
null
2010-10-29 06:52:54.42 UTC
9
2011-11-02 22:02:11.167 UTC
2010-10-29 08:29:53.637 UTC
null
351,564
null
351,564
null
1
14
ajax|facebook|redirect|refresh
5,188
<p>I've tried to change through facebook images, and this is what I saw:</p> <p><strong>In Firefox:</strong></p> <p>The page URL is not changing. Only the hash is changing. <a href="http://code.google.com/web/ajaxcrawling/docs/getting-started.html" rel="noreferrer">This is a technique used to allow crawlers to index the content</a>. What happens is this:</p> <ul> <li>User clicks on "next"</li> <li>JS loads the next image with tags, comments, etc and replaces the old content with them.</li> <li>JS changes the hash to correspond the new image</li> </ul> <p>urls look like this: <code>http://www.facebook.com/home.php?#!/photo.php?fbid=1550005942528966&amp;set=a.1514725882151300.28042.100000570788121&amp;pid=3829033&amp;id=1000001570788121</code> (notice the hash)</p> <p>As for the second question, this is just a benefit of the technique above. When you are on facebook, the page rarely gets actually refreshed. Only the hash is changed so that you can send links to other people and crawlers can index the content.</p> <p><strong>In Google Chrome:</strong></p> <p><s>It seems that chrome hassome way to change urls without refreshing the page</s>. It does that by using <code>window.history.pushState</code>. Read about it <a href="http://www.spoiledmilk.dk/blog/?p=1922" rel="noreferrer">here</a>.</p> <p>urls look like this: <code>http://www.facebook.com/photo.php?fbid=1613802157224343&amp;set=a.1514725288215100.28042.1000005707388121&amp;pid=426541&amp;id=1000001570788121</code> (notice that there is no hash here, but still the url is changing along with images)</p> <p><strong>In <a href="http://projects.gnome.org/epiphany/" rel="noreferrer">Epiphany</a>:</strong></p> <p>Epiphany doesn't change the URL when the image changes.</p> <p>urls look like this: <code>http://www.facebook.com/photo.php?fbid=1441817122377521&amp;set=a.1514725882215100.28042.1000005707848121&amp;pid=3251944&amp;id=1000200570788121</code> (there is no hash, and the URL stays the same when changing the image)</p> <p>(don't have other browsers to verify right now)</p>
4,320,161
HTML5 <html> attributes xmlns, lang, xml:lang
<p>I don't understand the <a href="http://www.whatwg.org/specs/web-apps/current-work/#the-lang-and-xml:lang-attributes" rel="nofollow noreferrer">HTML5 specifications for the <code>lang</code> and <code>xml:lang</code> attributes</a> of the opening <code>&lt;html&gt;</code> tag. Scrolling up a bit, I understand that <code>xmlns</code> is a "talisman" (has no effect), but what about <code>lang</code> and <code>xml:lang</code>? Should they be used? If so, what should they be set to?</p>
4,320,189
3
4
null
2010-12-01 00:30:48.863 UTC
6
2018-02-15 10:28:22.433 UTC
2015-11-16 23:03:21.87 UTC
null
1,505,120
null
242,933
null
1
32
xml|html|xml-namespaces
40,662
<p>Everything I've seen and heard suggests that you should stick to</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset='UTF-8'&gt; </code></pre> <p>(or whatever character set you actually want). If you want a language associated with the page you can use the "lang" attribute on the <code>&lt;html&gt;</code> tag.</p> <p>Since HTML5 is <em>not</em> XML, really, I personally would find it weird to use any <code>xml:</code> namespace stuff.</p>
4,782,692
what does `using std::swap` inside the body of a class method implementation mean?
<p>I was trying to learn and adopt the copy-swap idiom following this thorough explanation on this question: <a href="https://stackoverflow.com/q/3279543/356440">the Copy-Swap Idiom</a>.</p> <p>But I found some code I had never seen: <code>using std::swap; // allow ADL</code> in this example</p> <pre><code>class dumb_array { public: // ... void swap(dumb_array&amp; pOther) // nothrow { using std::swap; // allow ADL /* &lt;===== THE LINE I DONT UNDERSTAND */ swap(mSize, pOther.mSize); // with the internal members swapped, swap(mArray, pOther.mArray); // *this and pOther are effectively swapped } }; </code></pre> <ol> <li>what does <code>using std::swap;</code> mean inside the body of a function implementation ? </li> <li>what does ADL mean ?</li> </ol>
4,782,809
3
1
null
2011-01-24 13:44:38.647 UTC
10
2021-10-30 20:27:09.993 UTC
2019-05-31 09:19:31.737 UTC
null
356,440
null
356,440
null
1
39
c++|stl|std|using|argument-dependent-lookup
7,777
<p>This mechanism is normally used in templated code, i.e. <code>template &lt;typename Value&gt; class Foo</code>.</p> <p>Now the question is which swap to use. <code>std::swap&lt;Value&gt;</code> will work, but it might not be ideal. There's a good chance that there's a better overload of <code>swap</code> for type <code>Value</code>, but in which namespace would that be? It's almost certainly not in <code>std::</code> (since that's illegal), but quite likely in the namespace of <code>Value</code>. Likely, but far from certain.</p> <p>In that case, <code>swap(myValue, anotherValue)</code> will get you the "best" swap possible. Argument Dependent Lookup will find any swap in the namespace where <code>Value</code> came from. Otherwise the <code>using</code> directive kicks in, and <code>std::swap&lt;Value&gt;</code> will be instantiated and used.</p> <p>In your code, <code>mSize</code> is likely an integral type, and <code>mArray</code> a pointer. Neither has an associated namespace, and <code>std::swap</code> is with 99.9% certainty optimal for them anyway. Therefore, the <code>using std::swap;</code> declaration seems useless here.</p>
4,224,817
Autofocus algorithm for USB microscope
<p>I'm trying to design an auto-focus system for a low cost USB microscope. I have been developing the hardware side with a precision PAP motor that is able to adjust the focus knob in the <a href="http://www.dealextreme.com/details.dx/sku.29661" rel="noreferrer">microscope</a>, and now I'm in the hard part.</p> <p>I have been thinking about how to implement the software. The hardware have two USB ports, one for the microscope camera and another for the motor. My initial idea is to write an application in C# that is able to get the image from the microscope and to move the motor forth and backwards, so far so good :)</p> <p>Now I need a bit of help with the auto-focus, how to implement it? There is any good algorithm for this? Or maybe an image processing library that will help my in my task?</p> <p>I have been googleling but with no success... I'll appreciate any help/idea/recommendation!</p> <p>Many thanks :)</p> <p><strong>EDIT:</strong> Thanks guys for your answers, i'll try all the options and get back here with the results (or maybe more questions).</p>
4,224,904
4
4
null
2010-11-19 12:10:34.663 UTC
11
2012-11-07 20:02:24.987 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
489,806
null
1
16
c#|algorithm|image|hardware|autofocus
9,792
<p>The most important piece is code which tells you how much out of focus the image is. Since an unfocused image loses high frequency data I'd try something like the following:</p> <pre><code>long CalculateFocusQuality(byte[,] pixels) { long sum = 0; for(int y = 0; y&lt;height-1; y++) for(int x=0; x&lt;width-1; x++) { sum += Square(pixels[x+1, y] - pixels[x, y]); sum += Square(pixels[x, y] - pixels[x, y+1]); } return sum; } int Square(int x) { return x*x; } </code></pre> <p>This algorithm doesn't work well if the image is noisy. In that case you could to downsample it, or use a more complex algorithm.</p> <p>Or another idea is calculating the variation of the pixel values:</p> <pre><code>long CalculateFocusQuality(byte[,] pixels) { long sum = 0; long sumOfSquares = 0; for(int y=0; y&lt;height; y++) for(int x=0; x&lt;width; x++) { byte pixel=pixels[x,y]; sum+=pixel; sumofSquares+=pixel*pixel; } return sumOfSquares*width*height - sum*sum; } </code></pre> <p>These functions work on monochromatic images, for RGB images just sum the values for the channels.</p> <p>Using this function change the focus trying to maximize <code>CalculateFocusQuality</code>. Increase the stepsize if several attempts in a row improved the quality, and decrease it and reverse the direction if the step reduced the quality.</p>
4,788,644
Select latest record in table (datetime field)
<p>I have searched the site for assistance but still struggling. Here is my table:</p> <pre> messages ======== id thread_id user_id subject body date_sent </pre> <p>Basically I want to retrieve the latest record for each thread_id. I have tried the following:</p> <pre><code>SELECT id, thread_id, user_id, subject, body, date_sent FROM messages WHERE user_id=1 AND date_sent=(select max(date_sent)) GROUP BY thread_id ORDER BY date_sent DESC </code></pre> <p>BUT it is giving me the oldest records, not the newest!</p> <p>Anyone able to advise?</p> <p>EDIT: Table dump:</p> <pre> -- -- Table structure for table `messages` -- CREATE TABLE IF NOT EXISTS `messages` ( `id` int(10) unsigned NOT NULL auto_increment, `thread_id` int(10) unsigned NOT NULL, `user_id` int(10) unsigned NOT NULL, `body` text NOT NULL, `date_sent` datetime NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=34 ; -- -- Dumping data for table `messages` -- INSERT INTO `messages` (`id`, `thread_id`, `user_id`, `body`, `date_sent`) VALUES (1, 1, 1, 'Test Message', '2011-01-20 00:13:51'), (2, 1, 6, 'Test Message', '2011-01-20 01:03:50'), (3, 1, 6, 'Test Message', '2011-01-20 01:22:52'), (4, 1, 6, 'Test Message', '2011-01-20 11:59:01'), (5, 1, 1, 'Test Message', '2011-01-20 11:59:22'), (6, 1, 6, 'Test Message', '2011-01-20 12:10:37'), (7, 1, 1, 'Test Message', '2011-01-20 12:10:51'), (8, 2, 6, 'Test Message', '2011-01-20 12:45:29'), (9, 1, 6, 'Test Message', '2011-01-20 13:08:42'), (10, 1, 1, 'Test Message', '2011-01-20 13:09:49'), (11, 2, 1, 'Test Message', '2011-01-20 13:10:17'), (12, 3, 1, 'Test Message', '2011-01-20 13:11:09'), (13, 1, 1, 'Test Message', '2011-01-21 02:31:43'), (14, 2, 1, 'Test Message', '2011-01-21 02:31:52'), (15, 4, 1, 'Test Message', '2011-01-21 02:31:57'), (16, 3, 1, 'Test Message', '2011-01-21 02:32:10'), (17, 4, 6, 'Test Message', '2011-01-20 22:36:57'), (20, 1, 6, 'Test Message', '2011-01-20 23:02:36'), (21, 4, 1, 'Test Message', '2011-01-20 23:17:22'); </pre> <p>EDIT: Apologies - I may have got things slightly confused here - basically what I want is to retrieve all messages for a given user_id, THEN find the latest message (per thread_id) from those retrieved messages.</p>
4,789,557
4
4
null
2011-01-25 00:03:02.813 UTC
7
2022-09-07 13:08:12.137 UTC
2011-01-25 02:51:06.433 UTC
null
372,630
null
372,630
null
1
23
mysql
79,563
<pre class="lang-sql prettyprint-override"><code>SELECT id, thread_id, user_id, subject, body, date_sent FROM messages WHERE date_sent IN (SELECT MAX(date_sent) FROM messages WHERE user_id = 6 GROUP BY thread_id) ORDER BY thread_id ASC, date_sent DESC; </code></pre> <p>Let me know if it works now</p>
4,226,480
Ampersand (&) character inside a value of jQuery AJAX request data option
<p>I am performing asynchronous HTTP (Ajax) requests via jQuery with the basic $.ajax(). The code looks like the following:</p> <pre><code>$("textarea").blur(function(){ var thisId = $(this).attr("id"); var thisValue = $(this).val(); $.ajax({ type: "POST", url: "some.php", data: "id=" + thisId + "&amp;value=" + thisValue, success: function(){ alert( "Saved successfully!" ); } }); }); </code></pre> <p><strong>Everything is working properly as usual, until user types inside <em>textarea</em> ampersand (&amp;) character.</strong> Than when I debug PHP function, which saves the value, it always have a value until this character.</p> <p>I believe there has to be a solution to skip ampersand (&amp;) somehow. Any ideas?</p>
4,226,487
4
0
null
2010-11-19 15:31:04.257 UTC
12
2014-02-25 10:11:29.003 UTC
2013-10-18 04:41:51.62 UTC
null
1,079,354
null
309,031
null
1
31
jquery
30,941
<p>Instead of:</p> <pre><code>data: "id=" + thisId + "&amp;value=" + thisValue </code></pre> <p>do: </p> <pre><code>data: { id: thisId, value: thisValue } </code></pre> <p>This way jquery will take care of properly URL encoding the values. String concatenations are the root of all evil :-)</p>
4,069,278
How to set up subdomains on IIS 7
<p>I have a website sitting on an IIS 7 server: <strong>WWW.example.COM</strong></p> <p>I would like to create several sub domains that looks like <strong>SUBDOMAIN1.example.COM</strong></p> <p>I created an IIS website and I set the bindings to be http, port 80, the ip address of my server, and SUBDOMAIN1.example.COM and the physical path to a folder under <strong>example.COM</strong></p> <p>I restarted my website and clicked on browse, the browser than opened with the address: <a href="http://SUBDOMAIN1.example.COM" rel="noreferrer">http://SUBDOMAIN1.example.COM</a></p> <p>But the website doesn't show up.</p> <p>Do I have to do something with the DNS?</p>
8,903,357
4
1
null
2010-11-01 13:30:10.617 UTC
29
2017-01-19 06:11:51.603 UTC
2015-06-11 21:37:11.7 UTC
null
296
null
493,618
null
1
78
asp.net|iis|iis-7|subdomain
135,500
<p>This one drove me crazy... basically you need two things:</p> <p>1) Make sure your DNS is setup to point to your subdomain. This means to make sure you have an A Record in the DNS for your subdomain and point to the same IP.</p> <p>2) You must add an additional website in IIS 7 named subdomain.example.com</p> <ul> <li>Sites > Add Website</li> <li>Site Name: subdomain.example.com</li> <li>Physical Path: select the subdomain directory</li> <li>Binding: same ip as example.com</li> <li>Host name: subdomain.example.com</li> </ul>
4,756,717
Find the number of downloads for a particular app in apple appstore
<p>I need to do a market research on specific type of apps. so is there a way for me to know the download count of the app / any app.</p> <p>Is there a way to find the number of downloads for a particular app in the iTunes App Store.</p>
4,853,467
4
4
null
2011-01-21 08:17:20.277 UTC
34
2017-05-13 18:56:11.453 UTC
2016-04-06 15:59:09.377 UTC
null
3,530,081
null
445,955
null
1
162
app-store|itunes
484,985
<p>There is no way to know unless the particular company reveals the info. The best you can do is find a few companies that are sharing and then extrapolate based on app ranking (which is available publicly). The best you'll get is a ball park estimate.</p>
4,643,990
Is $(document).ready necessary?
<p>I saw this question in stackoverflow but do not feel that it was answered at all.</p> <p>Is <code>$(document).ready</code> necessary?</p> <p>I link all my javascripts at the bottom of the page so in theory they are all running after the document is ready anyways. </p>
4,644,026
5
1
null
2011-01-10 05:41:07.053 UTC
36
2018-10-05 15:34:47.983 UTC
2017-10-12 09:50:08.203 UTC
null
3,922,099
null
554,058
null
1
121
jquery|document-ready
60,773
<blockquote> <p>Is <code>$(document).ready</code> necessary?</p> </blockquote> <h1>no</h1> <p>if you've placed all your scripts right before the <code>&lt;/body&gt;</code> closing tag, you've done the exact same thing.</p> <p>Additionally, if the script doesn't need to access the DOM, it won't matter where it's loaded beyond possible dependencies on other scripts.</p> <p>For many CMS's, you don't have much choice of where the scripts get loaded, so it's good form for modular code to use the <code>document.ready</code> event. Do you really want to go back and debug old code if you reuse it elsewhere?</p> <h3>off-topic:</h3> <p>As a side note: you should use <code>jQuery(function($){...});</code> instead of <code>$(document).ready(function(){...});</code> as it forces the alias to <code>$</code>.</p>
4,235,082
Configuring Jetty JSP support in embedded mode in Maven project
<p>I can visit .html pages with Jetty, but when I visit a .jsp page I get:</p> <blockquote> <p>0 13:21:13 / [INFO] No JSP support. Check that JSP jars are in lib/jsp and that the JSP option has been specified to start.jar</p> </blockquote> <p>I added the following as dependencies:</p> <pre><code>&lt;dependency&gt; &lt;groupId&gt;org.eclipse.jetty&lt;/groupId&gt; &lt;artifactId&gt;jetty-webapp&lt;/artifactId&gt; &lt;version&gt;8.0.0.M1&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;javax.servlet.jsp&lt;/groupId&gt; &lt;artifactId&gt;jsp-api&lt;/artifactId&gt; &lt;version&gt;2.1&lt;/version&gt; &lt;/dependency&gt; </code></pre> <p>Does that fulfill the "check that JSP jars are in lib/jsp" part of the error message?</p> <p>Also, I have no idea what "check that the JSP option has been specified to start.jar" means in this context. I have the following:</p> <pre><code> public static void main(String[] args) throws Exception { Server server = new Server(); SelectChannelConnector connector = new SelectChannelConnector(); connector.setPort(8080); server.addConnector(connector); WebAppContext webApp = new WebAppContext(); webApp.setContextPath("/"); webApp.setWar("src/main/webapp"); server.setHandler(webApp); server.start(); server.join(); } </code></pre>
4,235,384
6
0
null
2010-11-20 21:25:15.397 UTC
19
2014-03-19 22:30:35.057 UTC
2011-02-07 11:08:45.023 UTC
null
109,305
null
64,421
null
1
21
jsp|jetty|embedded-jetty
36,429
<p>I got it to work by adding the Mortbay JSP dependency (this is in Gradle notation, but you get the idea):</p> <pre><code>compile 'org.eclipse.jetty:jetty-io:8.0.0.M3' compile 'org.eclipse.jetty:jetty-server:8.0.0.M3' compile 'org.eclipse.jetty:jetty-servlet:8.0.0.M3' compile 'org.eclipse.jetty:jetty-util:8.0.0.M3' compile 'org.eclipse.jetty:jetty-webapp:8.0.0.M3' compile 'org.mortbay.jetty:jsp-2.1-glassfish:2.1.v20100127' </code></pre> <p>There's a <a href="http://www.benmccann.com/blog/embedded-jetty/" rel="noreferrer">larger writeup available on my blog</a>.</p>
4,582,912
Get _id of an inserted document in MongoDB?
<p>say I have a product listing. When I add a new product I save it using something like</p> <pre><code>var doc=products.Insert&lt;ProductPDO&gt;(p); </code></pre> <p>The problem is that I want after this is done to redirect the user to the page with the product. So I need to redirect to say <code>/products/&lt;ObjectID&gt;</code> </p> <p>However, I see no way of getting the ObjectID right afterwards without manually querying the database and look for a document with all the same fields and such. </p> <p>Is there an easier way? (also, <code>doc</code> in this instance returns null for some reason)</p>
4,582,943
7
0
null
2011-01-03 08:06:09.65 UTC
1
2021-08-20 21:46:07.953 UTC
null
null
null
null
69,742
null
1
41
c#|mongodb|mongodb-.net-driver
38,758
<p>The <code>Insert</code> method automatically sets the property that is declared as the BSON ID of the model.</p> <p>If declared as follows...</p> <pre><code>[BsonId] public ObjectId Id { get; set; } </code></pre> <p>... then the <code>Id</code> field will contain the default (new, unique) BSON ID of the object after inserting the object into a collection:</p> <pre><code>coll.Insert(obj); // obj.Id is now the BSON ID of the object </code></pre>
4,246,024
CoffeeScript editor for MacOS
<p>Does anybody know a good text editor for Mac that supports syntax highlighting in CoffeeScript? Is it possible to do this in TextWrangler or BBEdit?</p> <p>Cheers :)</p>
10,240,768
8
0
null
2010-11-22 13:45:36.983 UTC
8
2014-02-06 10:52:55.79 UTC
null
null
null
null
183,376
null
1
32
macos|coffeescript
15,155
<p><a href="http://macrabbit.com/espresso/">Espresso 2</a> has <a href="https://github.com/artisonian/CoffeeScript.sugar">CoffeeScript.sugar</a></p>
4,393,612
When Can I First Measure a View?
<p>So I have a bit of confusion with trying to set the background drawable of a view as it is displayed. The code relies upon knowing the height of the view, so I can't call it from <code>onCreate()</code> or <code>onResume()</code>, because <code>getHeight()</code> returns 0. <code>onResume()</code> seems to be the closest I can get though. Where should I put code such as the below so that the background changes upon display to the user?</p> <pre><code> TextView tv = (TextView)findViewById(R.id.image_test); LayerDrawable ld = (LayerDrawable)tv.getBackground(); int height = tv.getHeight(); //when to call this so as not to get 0? int topInset = height / 2; ld.setLayerInset(1, 0, topInset, 0, 0); tv.setBackgroundDrawable(ld); </code></pre>
4,398,578
9
3
null
2010-12-09 00:03:11.613 UTC
40
2022-02-04 12:30:55.093 UTC
2013-01-17 11:59:58.83 UTC
null
1,806,193
null
321,697
null
1
63
android|layout|height|android-lifecycle
49,469
<p>I didn't know about <code>ViewTreeObserver.addOnPreDrawListener()</code>, and I tried it in a test project.</p> <p>With your code it would look like this:</p> <pre><code>public void onCreate() { setContentView(R.layout.main); final TextView tv = (TextView)findViewById(R.id.image_test); final LayerDrawable ld = (LayerDrawable)tv.getBackground(); final ViewTreeObserver obs = tv.getViewTreeObserver(); obs.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { @Override public boolean onPreDraw () { Log.d(TAG, "onPreDraw tv height is " + tv.getHeight()); // bad for performance, remove on production int height = tv.getHeight(); int topInset = height / 2; ld.setLayerInset(1, 0, topInset, 0, 0); tv.setBackgroundDrawable(ld); return true; } }); } </code></pre> <p>In my test project <code>onPreDraw()</code> has been called twice, and I think in your case it may cause an infinite loop.</p> <p>You could try to call the <code>setBackgroundDrawable()</code> only when the height of the <code>TextView</code> changes :</p> <pre><code>private int mLastTvHeight = 0; public void onCreate() { setContentView(R.layout.main); final TextView tv = (TextView)findViewById(R.id.image_test); final LayerDrawable ld = (LayerDrawable)tv.getBackground(); final ViewTreeObserver obs = mTv.getViewTreeObserver(); obs.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { @Override public boolean onPreDraw () { Log.d(TAG, "onPreDraw tv height is " + tv.getHeight()); // bad for performance, remove on production int height = tv.getHeight(); if (height != mLastTvHeight) { mLastTvHeight = height; int topInset = height / 2; ld.setLayerInset(1, 0, topInset, 0, 0); tv.setBackgroundDrawable(ld); } return true; } }); } </code></pre> <p>But that sounds a bit complicated for what you are trying to achieve and not really good for performance.</p> <p><strong>EDIT by kcoppock</strong></p> <p>Here's what I ended up doing from this code. Gautier's answer got me to this point, so I'd rather accept this answer with modification than answer it myself. I ended up using the ViewTreeObserver's addOnGlobalLayoutListener() method instead, like so (this is in onCreate()):</p> <pre><code>final TextView tv = (TextView)findViewById(R.id.image_test); ViewTreeObserver vto = tv.getViewTreeObserver(); vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { @Override public void onGlobalLayout() { LayerDrawable ld = (LayerDrawable)tv.getBackground(); ld.setLayerInset(1, 0, tv.getHeight() / 2, 0, 0); } }); </code></pre> <p>Seems to work perfectly; I checked LogCat and didn't see any unusual activity. Hopefully this is it! Thanks!</p>
4,690,713
Could not find any resources appropriate for the specified culture or the neutral culture
<p>I have created an assembly and later renamed it.</p> <p>Then I started getting runtime errors when calling:</p> <pre><code>toolsMenuName = resourceManager.GetString(resourceName); </code></pre> <p>The <code>resourceName</code> variable is <strong>"enTools"</strong> at runtime.</p> <blockquote> <p>Could not find any resources appropriate for the specified culture or the neutral culture. Make sure "Jfc.TFSAddIn.CommandBar.resources" was correctly embedded or linked into assembly "Jfc.TFSAddIn" at compile time, or that all the satellite assemblies required are loadable and fully signed.</p> </blockquote> <p>The code:</p> <pre><code>string resourceName; ResourceManager resourceManager = new ResourceManager("Jfc.TFSAddIn.CommandBar", Assembly.GetExecutingAssembly()); CultureInfo cultureInfo = new CultureInfo(_applicationObject.LocaleID); if(cultureInfo.TwoLetterISOLanguageName == "zh") { CultureInfo parentCultureInfo = cultureInfo.Parent; resourceName = String.Concat(parentCultureInfo.Name, "Tools"); } else { resourceName = String.Concat(cultureInfo.TwoLetterISOLanguageName, "Tools"); } toolsMenuName = resourceManager.GetString(resourceName); // EXCEPTION IS HERE </code></pre> <p>I can see the file CommandBar.resx included in the project, I can open it and can see the "enTools" string there. It seems that either resources are not included into assembly or resource are included but .NET cannot resolve the name.</p>
4,690,798
10
0
null
2011-01-14 11:48:56.063 UTC
2
2018-07-03 16:39:49.8 UTC
2017-02-02 17:10:46.997 UTC
null
1,351,076
null
207,047
null
1
16
c#|.net|exception-handling|localization|resources
65,017
<p>I think simpler solution would be to create separate resources file for each language.</p> <p>As far as this case is concerned check if the assembly containing resources has the default namespace set to the same text (Project->Properties->Default namespace; in VS)</p> <p>Check as well if the resx file has a property BuildAction set to "Embedded resource"</p>
4,485,716
Java 'file.delete()' Is not Deleting Specified File
<p>This is currently what I have to delete the file but it's not working. I thought it may be permission problems or something but it wasn't. The file that I am testing with is empty and exists, so not sure why it doesn't delete it.</p> <pre><code>UserInput.prompt("Enter name of file to delete"); String name = UserInput.readString(); File file = new File("\\Files\\" + name + ".txt"); file.delete(); </code></pre> <p>Any help would be GREATLY appreciated!</p> <p>I now have:</p> <pre><code>File file = new File(catName + ".txt"); String path = file.getCanonicalPath(); File filePath = new File(path); filePath.delete(); </code></pre> <p>To try and find the correct path at run time so that if the program is transferred to a different computer it will still find the file.</p>
4,485,744
12
6
null
2010-12-19 23:21:19.527 UTC
14
2020-09-10 07:21:00.633 UTC
2015-07-11 23:48:14.453 UTC
null
4,370,109
null
548,047
null
1
52
java|file|delete-file
169,362
<p>Be sure to find out your current working directory, and write your filepath relative to it.</p> <p>This code:</p> <pre><code>File here = new File("."); System.out.println(here.getAbsolutePath()); </code></pre> <p>... will print out that directory.</p> <p>Also, unrelated to your question, try to use <code>File.separator</code> to remain OS-independent. Backslashes work only on Windows.</p>
14,494,513
How do I get back c++0x/c++11 support for Mac OS X 10.6 deployment using Xcode 4.6.2 thru 7.1.1
<p>I heavily use the c++0x/c++11 features in my project, particularly code blocks and shared pointers. When I upgraded my OS to 10.8 Mountain Lion (Edit: From 10.7), I was forced to upgrade Xcode. In upgrading Xcode, I lost the ability to compile my c++ project for deployment on 10.6 systems as I get the following error.</p> <p><code>clang: error: invalid deployment target for -stdlib=libc++ (requires Mac OS X 10.7 or later)</code></p> <p>It appears that Apple is trying to force people to upgrade by not allowing developers to support Snow Leopard. This makes me angry. Arrrggg!!!</p> <p>What can I do?</p> <p><strong>EDIT:</strong> After several comments back and forth, it should be made clear that 10.6 does not ship with system libc++ libraries. As a result, simply being able to build a libc++ project for 10.6 deployment is not enough. You would also need to include libc++ binaries with your 10.6 distribution or statically link to them. So lets continue with the premise that I am already doing that.</p> <p><strong>UPDATE 1:</strong> This question was originally intended for use with Xcode 4.5.2 (the latest version at the time the question was asked). I have since upgraded to Xcode 4.6.3 and have updated the question and answer to reflect that.</p> <p><strong>UPDATE 2:</strong> I've since upgraded to Xcode 5.0.2. The technique listed in the selected answer below still works as expected.</p> <p><strong>UPDATE 3:</strong> I've since upgraded to Xcode 5.1. The technique listed in the answer below does not yet work for this version!</p> <p><strong>UPDATE 4:</strong> I've since upgraded to Xcode 6.0.1. The technique listed in the selected answer below appears to be working again.</p> <p><strong>UPDATE 5:</strong> I've since upgraded to Xcode 7.1.1. The technique listed in the selected answer below appears to be working again, with one important caveat. You must disable <a href="https://developer.apple.com/library/tvos/documentation/IDEs/Conceptual/AppDistributionGuide/AppThinning/AppThinning.html" rel="noreferrer">Bitcoding</a> used for AppThinning since the opensource LLVM version doesn't support it (nor should it). So you will need to switch between the open source and Apple LLVM clang in order to compile for both 10.6 and tvOS/watchOS (since Bitcoding is required for those OSes).</p>
14,494,515
2
0
null
2013-01-24 05:21:01.16 UTC
9
2015-11-25 22:09:45.307 UTC
2015-11-25 22:05:51.677 UTC
null
1,190,255
null
1,190,255
null
1
12
c++|c++11|osx-snow-leopard|xcode4.6|libc++
10,045
<p>Apple has decided to only officially support libc++ on 10.7 or higher. So the version of clang/llvm that ships with Xcode checks to see if the deployment target is set for 10.6 when using libc++, and prevents you from compiling. However, this flag is <strong>not</strong> included in the open source version of clang/llvm.</p> <p>Take a look at this thread: <a href="http://permalink.gmane.org/gmane.comp.compilers.clang.devel/17557" rel="nofollow">http://permalink.gmane.org/gmane.comp.compilers.clang.devel/17557</a></p> <p><em>So, to compile a project that is using c++11 for 10.6 deployment, you need to give Xcode the open source version. Here is one way of doing it:</em></p> <ol> <li>Download the open source version of clang from here (use LLVM 3.1 for Xcode 4.5.x; use LLVM 3.2 for Xcode 4.6.x; use LLVM 3.3 for Xcode 5.0.x; use LLVM 3.5.0 for XCode 6.0.1; use LLVM 3.7.0 for XCode 7.1.1): <a href="http://llvm.org/releases/download.html" rel="nofollow">http://llvm.org/releases/download.html</a><br></li> <li>Make a backup of Xcode's default clang compiler and put it in a safe place (In case you screw up!) This is located at: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang</li> <li>Replace the default clang compiler with the one you downloaded from [1]</li> <li>chown the clang binary for root:wheel with <code>sudo chown root:wheel clang</code> from the bin directory listed in [2].</li> <li>Startup Xcode and compile!</li> </ol> <p><strong>UPDATE #1</strong>: This technique does not currently work for Xcode 5.1 or newer, which relies on LLVM 3.4. When I get some more time, I will try and find a solution to post here. But if someone comes up with a solution before me, they should post it as an answer.</p> <p><strong>UPDATE #2</strong>: Unfortunately I can't remember if I ever found a solution for Xcode 5.1, however I can confirm that the technique does still work for Xcode 6.0.1. I haven't tested on versions newer than that, but it could still work.</p> <p><strong>UPDATE #3</strong>: This technique appears to still work with XCode 7.1.1 using LLVM 3.7.0. However, the open source LLVM clang does not support Bitcoding. So you will need to switch between the open source compiler and Apple's compiler in order to develop for both 10.6 and tvOS/watchOS (which require Bitcoding).</p> <p>P.S.: The Mac OS X binaries for LLVM 3.4 and 3.5.0 are listed as "Clang for Darwin 10.9" at www.llvm.org/releases/download.html rather than as "Clang Binaries for Mac OS X" in previous versions.</p>
2,561,791
Iteration in LaTeX
<p>I would like to use some iteration control flow to simplify the following LaTeX code.</p> <pre><code> \begin{sidewaystable} \caption{A glance of images} \centering \begin{tabular}{| c ||c| c| c |c| c|| c |c| c|c|c| } \hline \backslashbox{Theme}{Class} &amp;\multicolumn{5}{|c|}{Class 0} &amp; \multicolumn{5}{|c|}{Class 1} \\ \hline \hline 1 &amp; \includegraphics[scale=2]{../../results/1/0_1.eps} &amp;\includegraphics[scale=2]{../../results/1/0_2.eps} &amp;\includegraphics[scale=2]{../../results/1/0_3.eps} &amp;\includegraphics[scale=2]{../../results/1/0_4.eps} &amp;\includegraphics[scale=2]{../../results/1/0_5.eps} &amp;\includegraphics[scale=2]{../../results/1/1_1.eps} &amp;\includegraphics[scale=2]{../../results/1/1_2.eps} &amp;\includegraphics[scale=2]{../../results/1/1_3.eps} &amp;\includegraphics[scale=2]{../../results/1/1_4.eps} &amp;\includegraphics[scale=2]{../../results/1/1_5.eps} \\ \hline ... % similarly for 2, 3, ..., 22 \hline 23 &amp; \includegraphics[scale=2]{../../results/23/0_1.eps} &amp;\includegraphics[scale=2]{../../results/23/0_2.eps} &amp;\includegraphics[scale=2]{../../results/23/0_3.eps} &amp;\includegraphics[scale=2]{../../results/23/0_4.eps} &amp;\includegraphics[scale=2]{../../results/23/0_5.eps} &amp;\includegraphics[scale=2]{../../results/23/1_1.eps} &amp;\includegraphics[scale=2]{../../results/23/1_2.eps} &amp;\includegraphics[scale=2]{../../results/23/1_3.eps} &amp;\includegraphics[scale=2]{../../results/23/1_4.eps} &amp;\includegraphics[scale=2]{../../results/23/1_5.eps} \\ \hline \end{tabular} \end{sidewaystable} </code></pre> <p>I learn that the <a href="http://www.ctan.org/tex-archive/macros/latex/contrib/forloop/" rel="noreferrer">forloop package</a> provides the <code>for</code> loop. But I am not sure how to apply it to my case? Or other methods not by forloop?</p> <hr> <p>If I also want to simply another similar case, where the only difference is that the directory does not run from 1, 2, to 23, but in some arbitrary order such as 3, 2, 6, 9,..., or even a list of strings such as dira, dirc, dird, dirb,.... How do I make the LaTeX code into loops then?</p>
2,561,949
2
1
null
2010-04-01 16:03:05.997 UTC
35
2015-02-01 17:53:59.477 UTC
2015-02-01 17:53:59.477 UTC
null
63,550
null
156,458
null
1
72
latex|for-loop|iteration
106,711
<p>Something like this will take care of the body of your tabular:</p> <pre><code>\newcounter{themenumber} \newcounter{classnumber} \newcounter{imagenumber} \forloop{themenumber}{1}{\value{themenumber} &lt; 24}{ % \hline &lt;-- Error here \arabic{themenumber} \forloop{classnumber}{0}{\value{classnumber} &lt; 2}{ \forloop{imagenumber}{1}{\value{imagenumber} &lt; 6}{ &amp; \includegraphics[scale=2]{ ../../results/\arabic{themenumber}/\arabic{classnumber}_\arabic{imagenumber}.eps } } } \\ \hline } </code></pre> <p>I had to comment out the first <code>\hline</code> because it gave me an error:</p> <pre><code>You can't use `\hrule' here except with leaders. </code></pre> <p>I'm not sure what that means; if you really cannot live without the double line, I can look into it more.</p> <p>Also note that you have to use <code>&lt;</code>; for example, <code>&lt;= 24</code> will not work.</p> <hr> <p>As to your update: I would simply declare a command that takes the argument that you're looping over. Something like this:</p> <pre><code>\newcommand\fordir[1]{do something complex involving directory named #1} \fordir{dira} \fordir{dirb} \fordir{dirc} \dots </code></pre>
1,612,957
Mysql index configuration
<p>I have a table with 450000 row full of news. The table schema is like this:</p> <pre><code>CREATE TABLE IF NOT EXISTS `news` ( `id` int(11) NOT NULL auto_increment, `cat_id` int(11) NOT NULL, `title` tinytext NOT NULL, `content` text NOT NULL, `date` int(11) NOT NULL, `readcount` int(11) NOT NULL default '0', PRIMARY KEY (`id`), KEY `cat_id` (`cat_id`), KEY `cat_id_2` (`cat_id`,`id`), KEY `cat_id_date` (`cat_id`,`date`) ) ENGINE=MyISAM DEFAULT CHARSET=latin5 AUTO_INCREMENT=462679 ; </code></pre> <p>When i run a sql command like below to take some news for a page "x" of the category page it takes more than 15 seconds if x is over 100:</p> <pre><code>select * news where cat_id='4' order by id desc limit 150000,10; </code></pre> <p>explain shows that its using "where" and the index "cat_id_2"</p> <p>While writing this question i also checked a more simple sql query like this and it also took near to a minute:</p> <pre><code>select * from haberler order by id desc limit 40000,10; </code></pre> <p>if the sql is like the following one it takes just a few milliseconds:</p> <pre><code>select * from haberler order by id desc limit 20,10; </code></pre> <p>My my.cnf configuration is like this:</p> <pre><code>skip-locking skip-innodb query_cache_limit=1M query_cache_size=256M query_cache_type=1 max_connections=30 interactive_timeout=600000 #wait_timeout=5 #connect_timeout=5 thread_cache_size=384 key_buffer=256M join_buffer=4M max_allowed_packet=16M table_cache=1024 record_buffer=1M sort_buffer_size=64M read_buffer_size=16M max_connect_errors=10 # Try number of CPU's*2 for thread_concurrency thread_concurrency=2 myisam_sort_buffer_size=128M long_query_time = 1 log_slow_queries = /var/log/mysql/mysql-slow.log max_heap_table_size=512M </code></pre> <p>The website is running on a core2duo with 2GB of RAM. I think that the problem may be caused by the sort_buffer_size but i'm not sure. thanks in advance.</p>
1,613,021
1
3
null
2009-10-23 11:54:34.197 UTC
10
2009-10-24 22:20:16.53 UTC
2009-10-23 14:55:40.75 UTC
null
135,152
null
195,259
null
1
9
sql|mysql|performance
1,667
<p><strong>Update:</strong></p> <p>See this article in my blog for the more detailed analysis of the problem:</p> <ul> <li><a href="http://explainextended.com/2009/10/23/mysql-order-by-limit-performance-late-row-lookups/" rel="noreferrer"><strong>MySQL ORDER BY / LIMIT performance: late row lookups</strong></a></li> </ul> <hr> <p>When you issue something like <code>LIMIT 150000, 10</code>, it means that <code>MySQL</code> should traverse these <code>150,000</code> records and find the next <code>10</code>.</p> <p>Traversing the index is slow in <code>MySQL</code>.</p> <p>Also, <code>MySQL</code> is not capable of doing late row lookups.</p> <p>Theoretically, if you do <code>ORDER BY id LIMIT 100000, 10</code>, it is enough to use the index to find the values from <code>100000</code> to <code>100010</code>, then look up only <code>10</code> rows that satisfy that index and return them.</p> <p>All major systems except <code>MySQL</code> are aware of it and look the rows up only if the values are really to be returned.</p> <p><code>MySQL</code>, however, looks up every row.</p> <p>Try to rewrite your query as this:</p> <pre><code>SELECT news.* FROM ( SELECT id FROM news WHERE cat_id='4' ORDER BY id DESC LIMIT 150000, 10 ) o JOIN news ON news.id = o.id </code></pre>
2,098,937
Proper way to Mock repository objects for unit tests using Moq and Unity
<p>At my job we are using Moq for mocking and Unity for an IOC container. I am fairly new to this and do not have many resources at work to help me out with determining the best practices I should use.</p> <p>Right now, I have a group of repository interfaces (Ex: IRepository1, IRepository2... IRepository4) that a particular process needs to use to do its job.</p> <p>In the actual code I can determine all of the IRepository objects by using the IOC container and using the RegisterType() method. </p> <p>I am trying to figure out the best way to be able to test the method that needs the 4 mentioned repositories. </p> <p>I was thinking I could just register a new instance of the Unity IOC container and call RegisterInstance on the container for each mock object passing in the Mock.Object value for each one. I am trying to make this registration process reusable so I do not have to keep doing the same thing over and over with each unit test unless a unit test requires some specific data to come back from the repository. This is where the problem lies... what is the best practice for setting up expected values on a mocked repository? It seems like if I just call RegisterType on the Unity container that I would lose a reference to the actual Mock object and would not be able to override behavior.</p>
2,102,104
1
0
null
2010-01-20 03:55:53.813 UTC
24
2011-10-03 05:02:32.313 UTC
null
null
null
null
171,485
null
1
36
c#|.net|moq|unity-container
45,521
<p>Unit tests should not use the container at all. Dependency Injection (DI) comes in two phases:</p> <ol> <li>Use DI patterns to inject dependencies into consumers. You don't need a container to do that.</li> <li>At the application's <a href="http://blog.ploeh.dk/2011/07/28/CompositionRoot.aspx" rel="noreferrer">Composition Root</a>, use a DI Container (or Poor Man's DI) to wire all components together.</li> </ol> <p><strong>How not to use any DI Container at all for unit testing</strong></p> <p>As an example, consider a class that uses IRepository1. By using the <strong>Constructor Injection</strong> pattern, we can make the dependency an invariant of the class.</p> <pre><code>public class SomeClass { private readonly IRepository1 repository; public SomeClass(IRepository1 repository) { if (repository == null) { throw new ArgumentNullException("repository"); } this.repository = repository; } // More members... } </code></pre> <p>Notice that the <code>readonly</code> keyword combined with the Guard Clause guarantees that the <code>repository</code> field isn't null if the instance was successfully instantiated.</p> <p>You don't need a container to create a new instance of MyClass. You can do that directly from a unit test using Moq or another Test Double:</p> <pre><code>[TestMethod] public void Test6() { var repStub = new Mock&lt;IRepository1&gt;(); var sut = new SomeClass(repStub.Object); // The rest of the test... } </code></pre> <p>See <a href="https://stackoverflow.com/questions/1465849/using-ioc-for-unittesting/1465896#1465896">here</a> for more information...</p> <p><strong>How to use Unity for unit testing</strong></p> <p>However, if you absolutely must use Unity in your tests, you can create the container and use the RegisterInstance method:</p> <pre><code>[TestMethod] public void Test7() { var repMock = new Mock&lt;IRepository1&gt;(); var container = new UnityContainer(); container.RegisterInstance&lt;IRepository1&gt;(repMock.Object); var sut = container.Resolve&lt;SomeClass&gt;(); // The rest of the test... } </code></pre>
36,105,118
Error in Fragment: "Already managing a GoogleApiClient with id 0"
<p>Everything works right the first time, if you launch a second time you see this error:</p> <pre class="lang-none prettyprint-override"><code>FATAL EXCEPTION: main Process: ro.vrt.videoplayerstreaming, PID: 23662 java.lang.IllegalStateException: Already managing a GoogleApiClient with id 0 at com.google.android.gms.common.internal.zzx.zza(Unknown Source) at com.google.android.gms.common.api.internal.zzw.zza(Unknown Source) at com.google.android.gms.common.api.GoogleApiClient$Builder.zza(Unknown Source) at com.google.android.gms.common.api.GoogleApiClient$Builder.zze(Unknown Source) at com.google.android.gms.common.api.GoogleApiClient$Builder.build(Unknown Source) at ro.vrt.videoplayerstreaming.Login.onCreateView(Login.java:75) at android.support.v4.app.Fragment.performCreateView(Fragment.java:1974) at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067) at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252) at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738) at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617) at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:517) at android.os.Handler.handleCallback(Handler.java:739) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5849) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:763) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:653) </code></pre> <p>Here's my code:</p> <pre class="lang-java prettyprint-override"><code>public class Login extends Fragment implements GoogleApiClient.OnConnectionFailedListener, View.OnClickListener { private static final String TAG = "SignInActivity"; private static final int RC_SIGN_IN = 9001; private GoogleApiClient mGoogleApiClient; private TextView mStatusTextView; private ProgressDialog mProgressDialog; private static String url; private static View view; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if (view != null) { ViewGroup parent = (ViewGroup) view.getParent(); if (parent != null) parent.removeView(view); } try { view = inflater.inflate(R.layout.activity_login, container, false); // Views mStatusTextView = (TextView) view.findViewById(R.id.status); // Button listeners view.findViewById(R.id.sign_in_button).setOnClickListener(this); view.findViewById(R.id.sign_out_button).setOnClickListener(this); view.findViewById(R.id.disconnect_button).setOnClickListener(this); // [START configure_signin] // Configure sign-in to request the user's ID, email address, and basic // profile. ID and basic profile are included in DEFAULT_SIGN_IN. GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestEmail() .build(); // [END configure_signin] // [START build_client] // Build a GoogleApiClient with access to the Google Sign-In API and the // options specified by gso. mGoogleApiClient = new GoogleApiClient.Builder(getActivity()) .enableAutoManage(getActivity()/* FragmentActivity */, this /* OnConnectionFailedListener */) .addApi(Auth.GOOGLE_SIGN_IN_API, gso) .build(); // [END build_client] // [START customize_button] // Customize sign-in button. The sign-in button can be displayed in // multiple sizes and color schemes. It can also be contextually // rendered based on the requested scopes. For example. a red button may // be displayed when Google+ scopes are requested, but a white button // may be displayed when only basic profile is requested. Try adding the // Scopes.PLUS_LOGIN scope to the GoogleSignInOptions to see the // difference. SignInButton signInButton = (SignInButton) view.findViewById(R.id.sign_in_button); signInButton.setSize(SignInButton.SIZE_STANDARD); signInButton.setScopes(gso.getScopeArray()); // [END customize_button] } catch (InflateException e) { /* map is already there, just return view as it is */ } super.onCreate(savedInstanceState); return view; } @Override public void onStart() { super.onStart(); OptionalPendingResult&lt;GoogleSignInResult&gt; opr = Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient); if (opr.isDone()) { // If the user's cached credentials are valid, the OptionalPendingResult will be "done" // and the GoogleSignInResult will be available instantly. Log.d(TAG, "Got cached sign-in"); GoogleSignInResult result = opr.get(); handleSignInResult(result); } else { // If the user has not previously signed in on this device or the sign-in has expired, // this asynchronous branch will attempt to sign in the user silently. Cross-device // single sign-on will occur in this branch. showProgressDialog(); opr.setResultCallback(new ResultCallback&lt;GoogleSignInResult&gt;() { @Override public void onResult(GoogleSignInResult googleSignInResult) { //adaugat de mine sa porneacsa singur cererea de logare signIn(); //fin hideProgressDialog(); handleSignInResult(googleSignInResult); } }); } } // [START onActivityResult] @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...); if (requestCode == RC_SIGN_IN) { GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data); handleSignInResult(result); } } // [END onActivityResult] // [START handleSignInResult] private void handleSignInResult(GoogleSignInResult result) { Log.d(TAG, "handleSignInResult:" + result.isSuccess()); if (result.isSuccess()) { // Signed in successfully, show authenticated UI. GoogleSignInAccount acct = result.getSignInAccount(); mStatusTextView.setText(getString(R.string.signed_in_fmt, acct.getDisplayName() + " Your token " + acct.getId())); url = "http://grupovrt.ddns.net:81/index.php?token="+acct.getId(); updateUI(true); } else { // Signed out, show unauthenticated UI. updateUI(false); } } // [END handleSignInResult] // [START signIn] private void signIn() { Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient); startActivityForResult(signInIntent, RC_SIGN_IN); } // [END signIn] // [START signOut] private void signOut() { Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback( new ResultCallback&lt;Status&gt;() { @Override public void onResult(Status status) { // [START_EXCLUDE] updateUI(false); // [END_EXCLUDE] } }); } // [END signOut] // [START revokeAccess] private void revokeAccess() { Auth.GoogleSignInApi.revokeAccess(mGoogleApiClient).setResultCallback( new ResultCallback&lt;Status&gt;() { @Override public void onResult(Status status) { // [START_EXCLUDE] updateUI(false); // [END_EXCLUDE] } }); } // [END revokeAccess] @Override public void onConnectionFailed(ConnectionResult connectionResult) { // An unresolvable error has occurred and Google APIs (including Sign-In) will not // be available. Log.d(TAG, "onConnectionFailed:" + connectionResult); } private void showProgressDialog() { if (mProgressDialog == null) { mProgressDialog = new ProgressDialog(getActivity()); mProgressDialog.setMessage(getString(R.string.loading)); mProgressDialog.setIndeterminate(true); } mProgressDialog.show(); } private void hideProgressDialog() { if (mProgressDialog != null &amp;&amp; mProgressDialog.isShowing()) { mProgressDialog.hide(); } } private void updateUI(boolean signedIn) { if (signedIn) { getView().findViewById(R.id.sign_in_button).setVisibility(View.GONE); getView().findViewById(R.id.sign_out_and_disconnect).setVisibility(View.VISIBLE); } else { mStatusTextView.setText(R.string.signed_out); getView().findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE); getView().findViewById(R.id.sign_out_and_disconnect).setVisibility(View.GONE); } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.sign_in_button: signIn(); break; case R.id.sign_out_button: signOut(); break; case R.id.disconnect_button: revokeAccess(); break; } } } </code></pre> <p>As I understand it, the problem is in these lines:</p> <pre><code> mGoogleApiClient = new GoogleApiClient.Builder(getActivity()) .enableAutoManage(getActivity()/* FragmentActivity */, this /* OnConnectionFailedListener */) .addApi(Auth.GOOGLE_SIGN_IN_API, gso) .build(); </code></pre> <p>I tried explicitly passing an id of <code>0</code>:</p> <pre><code>.enableAutoManage(getActivity() /* FragmentActivity */, 0, this /* OnConnectionFailedListener */) </code></pre> <p>but that still didn't work.</p> <p>What am I missing?</p>
37,025,744
10
0
null
2016-03-19 17:51:54.273 UTC
11
2020-05-28 00:53:50.003 UTC
2018-03-24 15:14:44.85 UTC
null
2,911,458
null
4,718,734
null
1
64
java|android|android-fragments
32,622
<p>You should call <code>stopAutoManage()</code> in the <code>onPause()</code> method of your <code>Fragment</code>:</p> <pre><code>@Override public void onPause() { super.onPause(); mGoogleClient.stopAutoManage(getActivity()); mGoogleClient.disconnect(); } </code></pre>
34,711,134
Laravel middleware 'except' rule not working
<p>I have a controller with the following in the constructor:</p> <pre><code>$this-&gt;middleware('guest', ['except' =&gt; [ 'logout', 'auth/facebook', 'auth/facebook/callback', 'auth/facebook/unlink' ] ]); </code></pre> <p>The 'logout' rule (which is there by default) works perfectly but the other 3 rules I have added are ignored. The routes in <code>routes.php</code> look like this:</p> <pre><code>Route::group(['middleware' =&gt; ['web']],function(){ Route::auth(); // Facebook auth Route::get('/auth/facebook', 'Auth\AuthController@redirectToFacebook')-&gt;name('facebook_auth'); Route::get('/auth/facebook/callback', 'Auth\AuthController@handleFacebookCallback')-&gt;name('facebook_callback'); Route::get('/auth/facebook/unlink', 'Auth\AuthController@handleFacebookUnlink')-&gt;name('facebook_unlink'); } </code></pre> <p>If I visit <code>auth/facebook</code>, <code>auth/facebook/callback</code> or <code>auth/facebook/unlink</code> whilst logged in I get denied by the middleware and thrown back to the homepage.</p> <p>I've tried specifying the 'except' rules with proceeding <code>/</code>'s so they match the routes in <code>routes.php</code> exactly but it makes no difference. Any ideas why these rules are being ignored, whilst the default 'logout' rule is respected?</p> <p>Cheers!</p>
34,711,397
7
0
null
2016-01-10 21:45:05.76 UTC
5
2021-04-23 03:18:52.147 UTC
null
null
null
null
1,165,064
null
1
17
laravel|laravel-5|laravel-middleware
45,848
<p>You need to pass the method's name instead of the URI.</p> <pre class="lang-php prettyprint-override"><code>&lt;?php namespace App\Http\Controllers; class MyController extends Controller { public function __construct() { $this-&gt;middleware('guest', ['except' =&gt; [ 'redirectToFacebook', 'handleFacebookCallback', 'handleFacebookUnlink' ]]); } } </code></pre> <p>Since Laravel 5.3, you can use fluent interface to define middlewares on controllers, which seems cleaner than using multidimensional arrays.</p> <pre class="lang-php prettyprint-override"><code>&lt;?php $this-&gt;middleware('guest')-&gt;except('redirectToFacebook', 'handleFacebookCallback', 'handleFacebookUnlink'); </code></pre>