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
8,502,146
Convert .Net object to JSON object in the view
<p>I want to convert a .Net object in to JSON in the view. My view model is like this,</p> <pre><code>public class ViewModel{ public SearchResult SearchResult { get; set;} } public class SearchResult { public int Id { get; set; } public string Text{ get; set; } } </code></pre> <p>I want to convert <code>Model.SearchResult</code> in to a JSON object. Currenty I'm doing it like this:</p> <pre><code>System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); //.... var s = @serializer.Serialize(Model.Institution); </code></pre> <p>but the result is like this,</p> <pre><code>var s = { &amp;quot;Name&amp;quot;:&amp;quot;a&amp;quot;,&amp;quot;Id&amp;quot;:1}; Create:228Uncaught SyntaxError: Unexpected token &amp; </code></pre> <p>How can I convert this correctly in to a JSON object?</p>
8,513,701
3
1
null
2011-12-14 09:30:49.153 UTC
10
2016-09-30 20:58:24.89 UTC
2011-12-14 09:34:17.603 UTC
null
519,413
null
590,278
null
1
33
javascript|jquery|json|asp.net-mvc-3
35,041
<p>Try using this method:</p> <p><code>@Html.Raw(Json.Encode(Model.Content))</code></p>
8,535,731
How can a variable be used when its definition is bypassed?
<p>In my mind, always, definition means storage allocation. </p> <p>In the following code, <code>int i</code> allocates a 4-byte (typically) storage on program stack and bind it to <code>i</code>, and <code>i = 3</code> assigns 3 to that storage. But because of <code>goto</code>, definition is bypassed which means there is no storage allocated for <code>i</code>.</p> <p>I heard that local variables are allocated either at the entry of the function (<code>f()</code> in this case) where they reside, or at the point of definition.</p> <p><em>But either way, how can <code>i</code> be used while it hasn't been defined yet (no storage at all)? Where does the value three assigned to when executing <code>i = 3</code>?</em></p> <pre><code>void f() { goto label; int i; label: i = 3; cout &lt;&lt; i &lt;&lt; endl; //prints 3 successfully } </code></pre>
8,535,765
8
1
null
2011-12-16 14:41:49.633 UTC
6
2012-06-15 15:06:32.357 UTC
2011-12-16 14:49:01.65 UTC
null
110,204
null
419,391
null
1
36
c++|scope|variable-declaration
1,094
<p>Long story short; <code>goto</code> will result is a runtime jump, variable definition/declaration will result in storage allocation, compile time.</p> <p>The compiler will see and decide on how much storage to allocate for an <code>int</code>, it will also make so that this allocated storage will be set to <code>3</code> when "hitting" <code>i = 3;</code>.</p> <p>That memory location will be there even if there is a <code>goto</code> at the start of your function, before the declaration/definition, just as in your example.</p> <hr> <h2>Very silly simile</h2> <p>If I place a log on the ground and my friend runs (with his eyes closed) and jumps over it, the log will still be there - even if he hasn't seen or felt it.</p> <p>It's realistic to say that he could turn around (at a later time) and set it on fire, if he wanted to. His jump doesn't make the log magically disappear.</p>
8,587,177
String to timestamp in MySQL
<p>Is there any way to convert string to UNIX timestamp in MySQL?</p> <p>For example, I have the string <code>2011-12-21 02:20pm</code> which needs to be in Unix timestamp format.</p>
8,587,425
2
1
null
2011-12-21 08:54:52.48 UTC
5
2021-02-22 10:19:35.74 UTC
2021-02-22 10:19:35.74 UTC
null
4,217,744
null
592,635
null
1
43
mysql|sql|timestamp
111,887
<p><code>UNIX_TIMESTAMP()</code> does the trick:</p> <pre><code>SELECT UNIX_TIMESTAMP('2011-12-21 14:20:00'); </code></pre> <p>However, the <code>UNIX_TIMESTAMP()</code> function only takes a standard MySQL formatted date. If you want to use the AM/PM notation, you will need to use <a href="http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_str-to-date" rel="noreferrer"><code>STR_TO_DATE</code></a> first like this:</p> <pre><code>SELECT UNIX_TIMESTAMP( STR_TO_DATE('2011-12-21 02:20pm', '%Y-%m-%d %h:%i%p') ); </code></pre>
720,113
Find Hyperlinks in Text using Python (twitter related)
<p>How can I parse text and find all instances of hyperlinks with a string? The hyperlink will not be in the html format of <code>&lt;a href="http://test.com"&gt;test&lt;/a&gt;</code> but just <code>http://test.com</code></p> <p>Secondly, I would like to then convert the original string and replace all instances of hyperlinks into clickable html hyperlinks.</p> <p>I found an example in this thread:</p> <p><a href="https://stackoverflow.com/questions/32637/easiest-way-to-convert-a-url-to-a-hyperlink-in-a-c-string">Easiest way to convert a URL to a hyperlink in a C# string?</a></p> <p>but was unable to reproduce it in python :(</p>
720,137
4
3
null
2009-04-06 02:37:48.72 UTC
11
2021-08-27 18:20:31.777 UTC
2017-05-23 12:14:53.447 UTC
null
-1
TimLeung
32,372
null
1
13
python|regex
22,371
<p>Here's a Python port of <a href="https://stackoverflow.com/questions/32637/easiest-way-to-convert-a-url-to-a-hyperlink-in-a-c-string/32648#32648">Easiest way to convert a URL to a hyperlink in a C# string?</a>:</p> <pre><code>import re myString = "This is my tweet check it out http://tinyurl.com/blah" r = re.compile(r"(http://[^ ]+)") print r.sub(r'&lt;a href="\1"&gt;\1&lt;/a&gt;', myString) </code></pre> <p>Output:</p> <pre><code>This is my tweet check it out &lt;a href="http://tinyurl.com/blah"&gt;http://tinyurl.com/blah&lt;/a&gt; </code></pre>
285,579
C# String.Replace double quotes and Literals
<p>I'm fairly new to c# so that's why I'm asking this here.</p> <p>I am consuming a web service that returns a long string of XML values. Because this is a string all the attributes have escaped double quotes</p> <pre><code>string xmlSample = "&lt;root&gt;&lt;item att1=\"value\" att2=\"value2\" /&gt;&lt;/root&gt;" </code></pre> <p>Here is my problem. I want to do a simple string.replace. If I was working in PHP I'd just run strip_slashes().</p> <p>However, I'm in C# and I can't for the life of me figure it out. I can't write out my expression to replace the double quotes (") because it terminates the string. If I escape it then it has incorrect results. What am I doing wrong?</p> <pre><code> string search = "\\\""; string replace = "\""; Regex rgx = new Regex(search); string strip = rgx.Replace(xmlSample, replace); //Actual Result &lt;root&gt;&lt;item att1=value att2=value2 /&gt;&lt;/root&gt; //Desired Result &lt;root&gt;&lt;item att1="value" att2="value2" /&gt;&lt;/root&gt; </code></pre> <blockquote> <p>MizardX: To include a quote in a raw string you need to double it. </p> </blockquote> <p>That's important information, trying that approach now...No luck there either There is something going on here with the double quotes. The concepts you all are suggesting are solid, BUT the issue here is dealing with the double quotes and it looks like I'll need to do some additional research to solve this problem. If anyone comes up with something please post an answer.</p> <pre><code>string newC = xmlSample.Replace("\\\"", "\""); //Result &lt;root&gt;&lt;item att=\"value\" att2=\"value2\" /&gt;&lt;/root&gt; string newC = xmlSample.Replace("\"", "'"); //Result newC "&lt;root&gt;&lt;item att='value' att2='value2' /&gt;&lt;/root&gt;" </code></pre>
286,056
4
4
null
2008-11-12 22:17:21.207 UTC
7
2008-11-13 19:55:59.35 UTC
2008-11-13 19:55:59.363 UTC
discorax
30,408
discorax
30,408
null
1
16
c#|xml
67,495
<p>the following statement in C# </p> <pre><code>string xmlSample = "&lt;root&gt;&lt;item att1=\"value\" att2=\"value2\" /&gt;&lt;/root&gt;" </code></pre> <p>will actually store the value </p> <pre><code>&lt;root&gt;&lt;item att1="value" att2="value2" /&gt;&lt;/root&gt; </code></pre> <p>whereas </p> <pre><code>string xmlSample = @"&lt;root&gt;&lt;item att1=\""value\"" att2=\""value2\"" /&gt;&lt;/root&gt;"; </code></pre> <p>have the value of </p> <pre><code>&lt;root&gt;&lt;item att1=\"value\" att2=\"value2\" /&gt;&lt;/root&gt; </code></pre> <p>for the second case, you need to replace the slash () by empty string as follow</p> <pre><code>string test = xmlSample.Replace(@"\", string.Empty); </code></pre> <p>the result will be </p> <pre><code>&lt;root&gt;&lt;item att1="value" att2="value2" /&gt;&lt;/root&gt; </code></pre> <p>P.S. </p> <ol> <li>slash (<code>\</code>) is default escape character in C#</li> <li>to ignore slashes, use @ at the beginning of string </li> <li>if @ is used, the escape character is double quote (")</li> </ol>
3,060,512
How to distinguish Multiple Keyboards in Delphi?
<p>I have two keyboards attached to a PC. One is used to type in TMemo1 and the other in TMemo2. Both are allowed to type at the same time. The problem is I cannot distinguish what keyboard-one has typed and what keyboard-two has typed.</p> <p>Is there any way to distinguish, which device certain input came from?</p>
3,060,668
2
0
null
2010-06-17 09:44:10.52 UTC
9
2017-01-09 16:16:47.773 UTC
2017-01-09 16:16:47.773 UTC
null
1,889,329
null
369,240
null
1
11
delphi|keyboard
4,981
<p>@Dian, you can use the <a href="http://msdn.microsoft.com/en-us/library/ms645600%28VS.85%29.aspx" rel="noreferrer">RegisterRawInputDevices</a> function to register the keyboards and monitor the <a href="http://msdn.microsoft.com/en-us/library/ms645590%28VS.85%29.aspx" rel="noreferrer">WM_INPUT</a> message to determine the device (keyboard) where the input came from.</p> <p>check theses links for more info</p> <ul> <li><a href="http://www.codeproject.com/KB/system/rawinput.aspx" rel="noreferrer">Using Raw Input from C# to handle multiple keyboards</a></li> <li><a href="http://msdn.microsoft.com/en-us/library/ms645590%28VS.85%29.aspx" rel="noreferrer">WM_INPUT Message</a></li> </ul>
38,253,185
Re-authenticating User Credentials Swift
<p>I wish to re-authenticate a user prior to allowing them to change their login information. However, due to the recent Firebase update, I found the documentation rather unhelpful. Using <a href="https://firebase.google.com/docs/auth/ios/manage-users#re-authenticate_a_user" rel="noreferrer">this link</a> I produced the following authenticateUser() function.</p> <pre><code>func authenticateUser() { let user = FIRAuth.auth()?.currentUser var credential: FIRAuthCredential //prompt user to re-enter info user?.reauthenticateWithCredential(credential, completion: { (error) in if error != nil { self.displayAlertMessage("Error reauthenticating user") } else { //user reauthenticated successfully } }) } </code></pre> <p>However, I am unsure what to do with the credential variable of type FIRAuthCredential, in order to re-authenticate the user. The documentation for this class can be found <a href="https://firebase.google.com/docs/reference/ios/firebaseauth/interface_f_i_r_auth_credential#properties" rel="noreferrer">here</a>.</p>
38,253,448
3
0
null
2016-07-07 18:49:51.167 UTC
11
2021-08-24 16:42:22.35 UTC
2016-07-07 18:56:31.553 UTC
null
3,915,603
null
3,915,603
null
1
18
ios|swift|authentication|firebase|firebase-authentication
11,342
<p>Getting the <code>FIRAuthCredential</code> object depends on what provider you want to use to reauthenticate.</p> <h3>Email:</h3> <pre><code>let credential = EmailAuthProvider.credential(withEmail: email, password: password) </code></pre> <h3>Facebook:</h3> <pre><code>let credential = FacebookAuthProvider.credential(withAccessToken: FBSDKAccessToken.currentAccessToken().tokenString) </code></pre> <h3>Twitter:</h3> <pre><code>let credential = TwitterAuthProvider.credential(withToken: session.authToken, secret: session.authTokenSecret) </code></pre> <h3>Google:</h3> <pre><code>let authentication = user.authentication let credential = GoogleAuthProvider.credential(withIDToken: authentication.idToken, accessToken: authentication.accessToken) </code></pre>
33,626,443
Comparing floats in a pandas column
<p>I have the following dataframe:</p> <pre><code> actual_credit min_required_credit 0 0.3 0.4 1 0.5 0.2 2 0.4 0.4 3 0.2 0.3 </code></pre> <p>I need to add a column indicating where actual_credit >= min_required_credit. The result would be:</p> <pre><code> actual_credit min_required_credit result 0 0.3 0.4 False 1 0.5 0.2 True 2 0.4 0.4 True 3 0.1 0.3 False </code></pre> <p>I am doing the following:</p> <pre><code>df['result'] = abs(df['actual_credit']) &gt;= abs(df['min_required_credit']) </code></pre> <p>However the 3rd row (0.4 and 0.4) is constantly resulting in False. After researching this issue at various places including: <a href="https://stackoverflow.com/questions/5595425/what-is-the-best-way-to-compare-floats-for-almost-equality-in-python">What is the best way to compare floats for almost-equality in Python?</a> I still can't get this to work. Whenever the two columns have an identical value, the result is False which is not correct.</p> <p>I am using python 3.3</p>
33,627,436
4
0
null
2015-11-10 09:15:54.783 UTC
10
2021-04-30 15:47:39.653 UTC
2019-12-17 02:18:11.713 UTC
null
202,229
null
4,169,229
null
1
33
python|pandas|floating-point|floating-point-comparison|inexact-arithmetic
41,468
<p>Due to imprecise float comparison you can <code>or</code> your comparison with <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.isclose.html" rel="noreferrer"><code>np.isclose</code></a>, <code>isclose</code> takes a relative and absolute tolerance param so the following should work:</p> <pre><code>df['result'] = df['actual_credit'].ge(df['min_required_credit']) | np.isclose(df['actual_credit'], df['min_required_credit']) </code></pre>
30,939,867
How to properly write cross-references to external documentation with intersphinx?
<p>I'm trying to add cross-references to external API into my documentation but I'm facing three different behaviors.</p> <p>I am using sphinx(1.3.1) with Python(2.7.3) and my intersphinx mapping is configured as:</p> <pre><code>{ 'python': ('https://docs.python.org/2.7', None), 'numpy': ('http://docs.scipy.org/doc/numpy/', None), 'cv2' : ('http://docs.opencv.org/2.4/', None), 'h5py' : ('http://docs.h5py.org/en/latest/', None) } </code></pre> <p>I have no trouble writing a cross-reference to numpy API with <code>:class:`numpy.ndarray`</code> or <code>:func:`numpy.array`</code> which gives me, as expected, something like <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.html#numpy.ndarray" rel="noreferrer">numpy.ndarray</a>.</p> <p>However, with h5py, the only way I can have a link generated is if I omit the module name. For example, <code>:class:`Group`</code> (or <code>:class:`h5py:Group`</code>) gives me <a href="http://docs.h5py.org/en/latest/high/group.html#Group" rel="noreferrer">Group</a> but <code>:class:`h5py.Group`</code> fails to generate a link.</p> <p>Finally, I cannot find a way to write a working cross-reference to OpenCV API, none of these seems to work:</p> <pre><code>:func:`cv2.convertScaleAbs` :func:`cv2:cv2.convertScaleAbs` :func:`cv2:convertScaleAbs` :func:`convertScaleAbs` </code></pre> <p>How to properly write cross-references to external API, or configure intersphinx, to have a generated link as in the numpy case?</p>
30,981,554
7
0
null
2015-06-19 13:50:26.53 UTC
12
2021-06-03 21:08:04.023 UTC
2016-10-21 09:55:28.007 UTC
null
3,819,284
null
3,819,284
null
1
29
python|opencv|documentation|python-sphinx|autodoc
10,240
<p>I gave another try on trying to understand the content of an <code>objects.inv</code> file and hopefully this time I inspected numpy and h5py instead of only OpenCV's one.</p> <h2>How to read an intersphinx inventory file</h2> <p>Despite the fact that I couldn't find anything useful about reading the content of an <code>object.inv</code> file, it is actually very simple with the intersphinx module.</p> <pre><code>from sphinx.ext import intersphinx import warnings def fetch_inventory(uri): """Read a Sphinx inventory file into a dictionary.""" class MockConfig(object): intersphinx_timeout = None # type: int tls_verify = False class MockApp(object): srcdir = '' config = MockConfig() def warn(self, msg): warnings.warn(msg) return intersphinx.fetch_inventory(MockApp(), '', uri) uri = 'http://docs.python.org/2.7/objects.inv' # Read inventory into a dictionary inv = fetch_inventory(uri) # Or just print it intersphinx.debug(['', uri]) </code></pre> <h2>File structure (numpy)</h2> <p>After inspecting numpy's one, you can see that keys are domains:</p> <pre><code>[u'np-c:function', u'std:label', u'c:member', u'np:classmethod', u'np:data', u'py:class', u'np-c:member', u'c:var', u'np:class', u'np:function', u'py:module', u'np-c:macro', u'np:exception', u'py:method', u'np:method', u'np-c:var', u'py:exception', u'np:staticmethod', u'py:staticmethod', u'c:type', u'np-c:type', u'c:macro', u'c:function', u'np:module', u'py:data', u'np:attribute', u'std:term', u'py:function', u'py:classmethod', u'py:attribute'] </code></pre> <p>You can see how you can write your cross-reference when you look at the content of a specific domain. For example, <code>py:class</code>:</p> <pre><code>{u'numpy.DataSource': (u'NumPy', u'1.9', u'http://docs.scipy.org/doc/numpy/reference/generated/numpy.DataSource.html#numpy.DataSource', u'-'), u'numpy.MachAr': (u'NumPy', u'1.9', u'http://docs.scipy.org/doc/numpy/reference/generated/numpy.MachAr.html#numpy.MachAr', u'-'), u'numpy.broadcast': (u'NumPy', u'1.9', u'http://docs.scipy.org/doc/numpy/reference/generated/numpy.broadcast.html#numpy.broadcast', u'-'), ...} </code></pre> <p>So here, <code>:class:`numpy.DataSource`</code> will work as expected.</p> <h2>h5py</h2> <p>In the case of h5py, the domains are:</p> <pre><code>[u'py:attribute', u'std:label', u'py:method', u'py:function', u'py:class'] </code></pre> <p>and if you look at the <code>py:class</code> domain:</p> <pre><code>{u'AttributeManager': (u'h5py', u'2.5', u'http://docs.h5py.org/en/latest/high/attr.html#AttributeManager', u'-'), u'Dataset': (u'h5py', u'2.5', u'http://docs.h5py.org/en/latest/high/dataset.html#Dataset', u'-'), u'ExternalLink': (u'h5py', u'2.5', u'http://docs.h5py.org/en/latest/high/group.html#ExternalLink', u'-'), ...} </code></pre> <p>That's why I couldn't make it work as numpy references. So a good way to format them would be <code>:class:`h5py:Dataset`</code>.</p> <h2>OpenCV</h2> <p>OpenCV's inventory object seems malformed. Where I would expect to find domains there is actually 902 function signatures:</p> <pre><code>[u':', u'AdjusterAdapter::create(const', u'AdjusterAdapter::good()', u'AdjusterAdapter::tooFew(int', u'AdjusterAdapter::tooMany(int', u'Algorithm::create(const', u'Algorithm::getList(vector&lt;string&gt;&amp;', u'Algorithm::name()', u'Algorithm::read(const', u'Algorithm::set(const' ...] </code></pre> <p>and if we take the first one's value:</p> <pre><code>{u'Ptr&lt;AdjusterAdapter&gt;': (u'OpenCV', u'2.4', u'http://docs.opencv.org/2.4/detectorType)', u'ocv:function 1 modules/features2d/doc/common_interfaces_of_feature_detectors.html#$ -')} </code></pre> <p>I'm pretty sure it is then impossible to write OpenCV cross-references with this file...</p> <h2>Conclusion</h2> <p>I thought intersphinx generated the <code>objects.inv</code> based on the content of the documentation project in an <em>standard</em> way, which seems not to be the case. As a result, it seems that the proper way to write cross-references is API dependent and one should inspect a specific inventory object to actually see what's available.</p>
1,690,201
Best Android 2.0 development book?
<p>I'm looking for a single book source for Android 2.0 development. While I may be ok with a general Android development book, a book which covers 2.0 features is ideal.</p> <p>What is the best Android 2.0 book out there, or upcoming?</p>
1,690,403
1
2
null
2009-11-06 20:31:52.357 UTC
16
2012-11-11 00:59:28.163 UTC
null
null
null
null
24,126
null
1
21
android|android-2.0-eclair
14,589
<p>At the time of this writing, the Android 2.0 SDK has been available for about 2.5 weeks. Hence, it will be months before you will be able to compare a wide range of print books specifically for their Android 2.0 coverage. I will be impressed if there are more than three authors with Android 2.0-ready books by the end of February 2010.</p> <p>I can tell you that:</p> <ul> <li><a href="http://commonsware.com/Android/" rel="nofollow noreferrer">One of my books</a> will be updated to be compatible with Android 2.0 within the next few days. However, there is little new in Android 2.0 that affects that specific title, and that book is available primarily in <a href="http://commonsware.com/warescription" rel="nofollow noreferrer">digital form</a>.</li> <li>My <a href="http://commonsware.com/AdvAndroid" rel="nofollow noreferrer">other two</a> <a href="http://commonsware.com/AndTutorials" rel="nofollow noreferrer">main books</a> will be updated with some Android 2.0 content shortly -- digital editions by the end of the year, printed editions in early 2010.</li> <li>I am under the distinct impression that <a href="http://www.wrox.com/WileyCDA/WroxTitle/Professional-Android-Application-Development.productCd-0470344717.html" rel="nofollow noreferrer">Reto Meier</a> and <a href="http://www.pragprog.com/titles/eband/hello-android" rel="nofollow noreferrer">Ed Burnette</a> are planning on updating their books.</li> <li>I do not know anyone else's plans in this area.</li> </ul>
1,585,449
Insert the carriage return character in vim
<p>I'm editing a network protocol frame stored a file in Unix (<code>\n</code> newlines). I need to insert the carriage return character (<code>U+000D</code> aka <code>\r</code>). When I try to paste it from the clipboard (<code>"+p</code>) or type it using <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>u</kbd>-<code>000d</code>, the linefeed is inserted (<code>U+000A</code>).</p> <p>What is the right way to do it?</p>
1,585,463
1
0
null
2009-10-18 17:10:20.26 UTC
25
2013-07-21 08:36:18.897 UTC
null
null
null
null
187,103
null
1
112
unix|vim|special-characters
101,438
<p>Type: <kbd>ctrl</kbd>-<kbd>v</kbd> <kbd>ctrl</kbd>-<kbd>m</kbd></p> <p>On Windows Use: <kbd>ctrl</kbd>-<kbd>q</kbd> <kbd>ctrl</kbd>-<kbd>m</kbd></p> <p><kbd>Ctrl</kbd>-<kbd>V</kbd> tells vi that the next character typed should be inserted literally and <kbd>ctrl</kbd>-<kbd>m</kbd> is the keystroke for a carriage return.</p>
59,337,838
OpenSSL 1.0.2m on macOS
<p>For building one particular library I need openssl library version 1.0.2m with devel package. I am working on macOS. Using <code>brew install openssl</code> installs latest version 1.1.1d.</p>
59,340,180
8
0
null
2019-12-14 18:12:03.813 UTC
13
2021-08-06 09:01:32.353 UTC
2019-12-29 02:22:01.273 UTC
null
1,033,581
null
3,677,539
null
1
26
macos|openssl|homebrew
31,405
<p>Since OpenSSL 1.0.2 is end of lifed by the end of 2019, it is no longer available via Homebrew. This is mentioned in the <a href="https://brew.sh/2019/11/27/homebrew-2.2.0/" rel="noreferrer">Homebrew 2.2.0 announcement</a>.</p> <p>It is fairly straightforward to build and install OpenSSL 1.0.2 yourself from source. You can download your required version from the <a href="https://www.openssl.org/source/old/1.0.2/" rel="noreferrer">Old 1.0.2 Releases</a> page and follow the instructions found in <a href="https://github.com/openssl/openssl/blob/OpenSSL_1_0_2m/INSTALL" rel="noreferrer">INSTALL</a>.</p> <hr> <p>It may be possible as well to recover an older formula and install from that, but I can not guarantee how well that works. The following steps did complete the installation process:</p> <pre><code>$ git clone https://github.com/Homebrew/homebrew-core.git $ cd homebrew-core $ git checkout 75b57384 Formula/openssl.rb $ brew install Formula/openssl.rb </code></pre> <p>For me, this showed:</p> <pre><code>Warning: openssl 1.1.1d is available and more recent than version 1.0.2m. ==&gt; Downloading https://homebrew.bintray.com/bottles/openssl-1.0.2m.high_sierra.bottle.tar.gz </code></pre> <p>and went on happily after that. A quick try at the end gives some confidence that it worked out well:</p> <pre><code>$ /usr/local/opt/openssl/bin/openssl version OpenSSL 1.0.2m 2 Nov 2017 </code></pre> <hr> <p>If you prefer not to use <code>git</code> directly, you can also try downloading that version of <a href="https://github.com/Homebrew/homebrew-core/blob/75b573845a17aaf3f7c84dc58e97cf5fe39a502b/Formula/openssl.rb" rel="noreferrer"><code>openssl.rb</code> from <code>gitHub.com</code></a> and run <code>brew install</code> on it.</p> <hr> <p>If you wonder where that commit hash came from, I happened to know that the formula used to be called -- surprise -- <code>openssl.rb</code> (but using <code>git</code> to query for removed files would have worked as well). Therefore, I inspected the history for <code>Formula/openssl.rb</code> and found:</p> <pre><code>$ git log -- Formula/openssl.rb ... commit 75b573845a17aaf3f7c84dc58e97cf5fe39a502b Author: BrewTestBot &lt;[email protected]&gt; Date: Thu Nov 2 17:20:33 2017 +0000 openssl: update 1.0.2m bottle. </code></pre>
43,728,332
Vue Chart.js - Chart is not updating when data is changing
<p>I'm using Vue.js and Chart.js to draw some charts. Each time I call the function <code>generateChart()</code>, the chart is not updated automatically. When I check the data in Vue Devtools, they are correct but the chart does not reflect the data. However, the chart does update when I resize the window.</p> <ul> <li>What is wrong with what I'm doing?</li> <li>How do I update the chart each time I call <code>generateChart()</code> ?</li> </ul> <p>I feel this is going to be something related with <code>object</code> and <code>array</code> change detection caveats, but I'm not sure what to do.</p> <p><a href="https://codepen.io/anon/pen/bWRVKB?editors=1010" rel="noreferrer">https://codepen.io/anon/pen/bWRVKB?editors=1010</a></p> <pre class="lang-html prettyprint-override"><code>&lt;template&gt; &lt;el-dialog title=&quot;Chart&quot; v-model=&quot;showGeneratedChart&quot;&gt; &lt;line-chart :chartData=&quot;dataChart&quot;&gt;&lt;/line-chart&gt; &lt;/el-dialog&gt; &lt;/template&gt; &lt;script&gt; export default { data() { const self = this; return { dataChart: { labels: [], datasets: [ { label: &quot;label&quot;, backgroundColor: &quot;#FC2525&quot;, data: [0, 1, 2, 3, 4], }, ], }, }; }, methods: { generateChart() { this.dataChart[&quot;labels&quot;] = []; this.dataChart[&quot;datasets&quot;] = []; // ... compute datasets and formattedLabels this.dataChart[&quot;labels&quot;] = formattedLabels; this.dataChart[&quot;datasets&quot;] = datasets; }, }, }; &lt;/script&gt; </code></pre> <h3>LineChart.js</h3> <pre class="lang-js prettyprint-override"><code>import { Line, mixins } from 'vue-chartjs' export default Line.extend({ mixins: [mixins.reactiveProp], props: [&quot;options&quot;], mounted () { this.renderChart(this.chartData, this.options) } }) </code></pre>
43,742,013
7
0
null
2017-05-02 00:26:26.623 UTC
9
2022-09-17 09:40:35.91 UTC
2021-06-17 21:17:00.163 UTC
null
2,518,200
null
6,068,447
null
1
33
javascript|vue.js|charts|vue-chartjs
59,698
<p>Use a computed property for the chart data. And instead of calling <code>this.renderChart</code> on watch wrap it in a method and reuse that method on <code>mounted</code> and in <code>watch</code>.</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>Vue.component("line-chart", { extends: VueChartJs.Line, props: ["data", "options"], mounted() { this.renderLineChart(); }, computed: { chartData: function() { return this.data; } }, methods: { renderLineChart: function() { this.renderChart( { labels: [ "January", "February", "March", "April", "May", "June", "July" ], datasets: [ { label: "Data One", backgroundColor: "#f87979", data: this.chartData } ] }, { responsive: true, maintainAspectRatio: false } ); } }, watch: { data: function() { this._chart.destroy(); //this.renderChart(this.data, this.options); this.renderLineChart(); } } }); var vm = new Vue({ el: ".app", data: { message: "Hello World", dataChart: [10, 39, 10, 40, 39, 0, 0], test: [4, 4, 4, 4, 4, 4] }, methods: { changeData: function() { this.dataChart = [6, 6, 3, 5, 5, 6]; } } });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;meta name="viewport" content="width=device-width"&gt; &lt;title&gt;Vue.jS Chart&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="app"&gt; {{ dataChart }} &lt;button v-on:click="changeData"&gt;Change data&lt;/button&gt; &lt;line-chart :data="dataChart" :options="{responsive: true, maintainAspectRatio: false}"&gt;&lt;/line-chart&gt; &lt;/div&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.6/vue.min.js"&gt;&lt;/script&gt; &lt;script src="https://unpkg.com/[email protected]/dist/vue-chartjs.full.min.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p>You could also make the options a computed property, and if option not going to change much you can setup default props. <a href="https://v2.vuejs.org/v2/guide/components.html#Prop-Validation" rel="nofollow noreferrer">https://v2.vuejs.org/v2/guide/components.html#Prop-Validation</a></p> <p>Here is a working codepen <a href="https://codepen.io/azs06/pen/KmqyaN?editors=1010" rel="nofollow noreferrer">https://codepen.io/azs06/pen/KmqyaN?editors=1010</a></p>
45,995,425
How to combine Intent flags in Kotlin
<p>I want to combine two intent flags as we do below in Android:</p> <pre><code>Intent intent = new Intent(this, MapsActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK); </code></pre> <p>I tried doing something like this but it didn't work for me:</p> <pre><code>val intent = Intent(context, MapActivity::class.java) intent.flags = (Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK) </code></pre>
45,996,002
3
0
null
2017-09-01 07:41:40.043 UTC
6
2021-09-15 11:37:58.457 UTC
2021-09-15 11:37:58.457 UTC
null
1,788,806
null
3,779,368
null
1
70
java|android|android-intent|kotlin|bitwise-operators
23,524
<p><strong>Explanation:</strong></p> <p>The operation that is applied to the flags is a bitwise or. In Java you have the <code>|</code> operator for that.</p> <blockquote> <p>As of bitwise operations [in Kotlin], there're no special characters for them, but just named functions that can be called in infix form.</p> </blockquote> <p><a href="https://kotlinlang.org/docs/reference/basic-types.html#operations" rel="noreferrer">Source</a></p> <p>Here a list of all bitwise operations for <code>Int</code> and <code>Long</code></p> <ul> <li><code>shl(bits)</code> – signed shift left (Java's <code>&lt;&lt;</code>)</li> <li><code>shr(bits)</code> – signed shift right (Java's <code>&gt;&gt;</code>)</li> <li><code>ushr(bits)</code> – unsigned shift right (Java's <code>&gt;&gt;&gt;</code>)</li> <li><code>and(bits)</code> – bitwise and (Java's <code>&amp;</code>)</li> <li><code>or(bits)</code> – bitwise or (Java's <code>|</code>)</li> <li><code>xor(bits)</code> – bitwise xor (Java's <code>^</code>)</li> <li><code>inv()</code> – bitwise inversion (Java's <code>~</code>)</li> </ul> <p><strong>Solution:</strong></p> <p>So, in your case you only need to call <code>or</code> in between your arguments like so.</p> <pre><code>intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK </code></pre>
21,997,924
Export (or print) with a google script new version of google spreadsheets to pdf file, using pdf options
<p>I'm trying to make a google script for exporting (or printing) a new version of google spreadsheet (or sheet) to pdf, with page parameters (portrait/landscape, ...)</p> <p>I've researched about this and found a possible solution <a href="https://stackoverflow.com/questions/21168167/include-sheet-names-when-exporting-google-spreadsheets-to-pdf-with-google-apps-s/21172633#21172633">here</a>. There are several similar solutions like this, but only work with old version of google spreadsheet.</p> <p>Please, consider this code:</p> <pre><code>function exportAsPDF() { //This code runs from a NEW version of spreadsheet var oauthConfig = UrlFetchApp.addOAuthService("google"); oauthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken"); oauthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope=https://spreadsheets.google.com/feeds/"); oauthConfig.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken"); oauthConfig.setConsumerKey("anonymous"); oauthConfig.setConsumerSecret("anonymous"); var requestData = { "method": "GET", "oAuthServiceName": "google","oAuthUseToken": "always" }; var ssID1="0AhKhywpH-YlQdDhXZFNCRFROZ3NqWkhBWHhYTVhtQnc"; //ID of an Old version of spreadsheet var ssID2="10xZX9Yz95AUAPu92BkBTtO0fhVk9dz5LxUmJQsJ7yPM"; //ID of a NEW version of spreadsheet var ss1 = SpreadsheetApp.openById(ssID1); //Old version ss object var ss2 = SpreadsheetApp.openById(ssID2); //New version ss object var sID1=ss1.getActiveSheet().getSheetId().toString(); // old version sheet id var sID2=ss2.getActiveSheet().getSheetId().toString(); // new version sheet id //For Old version, this runs ok. var url1 = "https://spreadsheets.google.com/feeds/download/spreadsheets/Export?key="+ssID1+"&amp;gid="+sID1+"&amp;portrait=true"+"&amp;exportFormat=pdf"; var result1 = UrlFetchApp.fetch(url1 , requestData); var contents1=result1.getBlob(); var pdfFile1=DriveApp.createFile(contents1).setName("FILE1.pdf"); ////////////////////////////////////////////// var url2 = "https://spreadsheets.google.com/feeds/download/spreadsheets/Export?key="+ssID2+"&amp;gid="+sID2+"&amp;portrait=true"+"&amp;exportFormat=pdf"; var result2 = UrlFetchApp.fetch(url2 , requestData); var contents2=result2.getBlob(); var pdfFile2=DriveApp.createFile(contents2).setName("FILE2.pdf"); } </code></pre> <p>It works right and generates the file “FILE1.pdf”, that can be opened correctly. But for the new version of spreadsheet, it results in error 302 (<em>truncated server response</em>) at “<em>var result2 = UrlFetchApp.fetch(url2 , requestData);</em>”. Well, it’s ok because the url format for the new version doesn’t include the “key” argument. A correct url for new versions must be like <em><code>"https://docs.google.com/spreadsheets/d/"+ssID2+"/export?gid="+sID2+"&amp;portrait=true&amp;format=pdf"</code></em> </p> <p>Using this for url2 (<em><code>var url2 = "https://docs.google.com/spreadsheets/d/"+ssID2+"/export?gid="+sID2+"&amp;portrait=true&amp;format=pdf"</code></em>) it fails again with error “<em>Authorization can’t be performed for service: google</em>”. Well, this error could be due to an incorrect scope for the <em>RequestTokenUrl</em>. I’ve found the alternative scope <code>https://docs.google.com/feeds</code> and set it: <code>oauthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope=https://docs.google.com/feed/");</code> After the code runs again, a new error happens at the line with <code>UrlFetchApp.fetch(url2 , requestData);</code>: “<em>Error OAuth</em>” … I don’t know how to continue … I’ve tested hundreds of variations without good results.</p> <p>Any ideas? is correct the scope <em>docs.google.com/feeds</em> for new version of spreadsheets? is correct the <em>oauthConfig</em>?</p> <p>Thanks in advance.</p>
22,284,142
3
0
null
2014-02-24 20:08:46.17 UTC
9
2019-06-10 17:49:35.783 UTC
2017-05-23 10:27:58.713 UTC
null
-1
null
3,347,511
null
1
8
google-apps-script|google-sheets
28,949
<p>Here is my spreadsheet-to-pdf script. It works with the new Google Spreadsheet API.</p> <pre><code>// Convert spreadsheet to PDF file. function spreadsheetToPDF(id,index,url,name) { SpreadsheetApp.flush(); //define usefull vars var oauthConfig = UrlFetchApp.addOAuthService("google"); var scope = "https://docs.google.com/feeds/"; //make OAuth connection oauthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken"); oauthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope="+scope); oauthConfig.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken"); oauthConfig.setConsumerKey("anonymous"); oauthConfig.setConsumerSecret("anonymous"); //get request var request = { "method": "GET", "oAuthServiceName": "google", "oAuthUseToken": "always", "muteHttpExceptions": true }; //define the params URL to fetch var params = '?gid='+index+'&amp;fitw=true&amp;exportFormat=pdf&amp;format=pdf&amp;size=A4&amp;portrait=true&amp;sheetnames=false&amp;printtitle=false&amp;gridlines=false'; //fetching file url var blob = UrlFetchApp.fetch("https://docs.google.com/a/"+url+"/spreadsheets/d/"+id+"/export"+params, request); blob = blob.getBlob().setName(name); //return file return blob; } </code></pre> <p>I've had to use the "muteHttpExceptions" parameter to know exactly the new URL. With this parameter, I downloaded my file with the HTML extension to get a "Moved permanently" page with my final url ("<a href="https://docs.google.com/a/" rel="noreferrer">https://docs.google.com/a/</a>"+url+"/spreadsheets/d/"+id+"/export"+params").</p> <p>And note that I am in an organization. So I've had to specify its domain name ("url" parameter, ie "mydomain.com").</p>
40,479,712
How can I tell if a given git tag is annotated or lightweight?
<p>I type <code>git tag</code> and it lists my current tags:</p> <pre><code>1.2.3 1.2.4 </code></pre> <p>How can I determine which of these is annotated, and which is lightweight?</p>
40,499,437
4
4
null
2016-11-08 05:36:29.527 UTC
22
2021-03-17 14:37:24.247 UTC
2021-02-19 08:41:45.457 UTC
null
574,419
null
5,819,286
null
1
106
git|git-tag
20,856
<p><a href="https://git-scm.com/docs/git-for-each-ref" rel="noreferrer"><code>git for-each-ref</code></a> tells you what each ref is to by default, its id and its type. To restrict it to just tags, do <code>git for-each-ref refs/tags</code>.</p> <blockquote> <p>[T]he output has three fields: The hash of an object, the type of the object, and the name in refs/tags that refers to the object. A so-called &quot;lightweight&quot; tag is a name in refs/tags that refers to a <code>commit</code>¹ object. An &quot;annotated&quot; tag is a name in refs/tags that refers to a <code>tag</code> object.</p> <p><em>- <a href="https://stackoverflow.com/users/801894/solomon-slow">Solomon Slow</a> (in the comments)</em></p> </blockquote> <p>Here is an example:</p> <pre><code>$ git for-each-ref refs/tags 902fa933e4a9d018574cbb7b5783a130338b47b8 commit refs/tags/v1.0-light 1f486472ccac3250c19235d843d196a3a7fbd78b tag refs/tags/v1.1-annot fd3cf147ac6b0bb9da13ae2fb2b73122b919a036 commit refs/tags/v1.2-light </code></pre> <p>To do this for just one ref, you can use <a href="https://git-scm.com/docs/git-cat-file" rel="noreferrer"><code>git cat-file</code></a> <code>-t</code> on the local ref, to continue the example:</p> <pre><code>$ git cat-file -t v1.0-light commit $ git cat-file -t v1.1-annot tag </code></pre> <hr /> <p><sup>¹ tags can refer to any Git object, if you want a buddy to fetch just one file and your repo's got a git server, you can <code>git tag forsam :that.file</code> and Sam can fetch it and show it. Most of the convenience commands don't know what to do with tagged blobs or trees, but the core commands like update-index and such do</sup></p>
21,986,886
How does Facebook Messenger clear push notifications from the lock screen if you’ve read them on desktop?
<p>When I receive a message on Facebook I get a push notification on a lock screen (iOS). Then I read this message on desktop. Right after that this push notification disappear without any interactions with the phone. How can I implement the same thing myself for removing outdated notifications?</p> <p>The second usage could be stitching notifications together. For instance Instagram sends you a push when someone liked your photo. After 20 likes your notifications screen is ruined and unreadable. But using the same principal as Facebook does it seem to be possible remove previous notification of the same sort and create new with the increased counter. No "User A liked photo X, User B liked photo Y etc", but "20 users liked photo Z" instead.</p> <p>I've seen couple of treads on similar topics here, but still no answer so far. Thanks!</p>
21,987,803
4
1
null
2014-02-24 11:48:43.35 UTC
19
2020-02-11 14:15:16.283 UTC
2014-03-19 09:41:22.35 UTC
null
17,279
null
3,346,421
null
1
35
ios|notifications|push-notification|apple-push-notifications
6,858
<p>See the <a href="https://developer.apple.com/library/ios/releasenotes/General/WhatsNewIniOS/Articles/iOS7.html">Multitasking Enhancements</a> and the silent push notifications in particular. Using the silent push you can notify your app that new content is available and also download that content and/or set the badge number for example without displaying the notification in the "Notification Center". You'll have to set the UIBackgroundModes with the remote-notification value in order to make this work.</p> <p>You can send silent push if the user has seen the content on another platform and clear the badge number on your iOS app.</p>
23,543,909
Plotting pandas timedelta
<p>I have a pandas dataframe that has two datetime64 columns and one timedelta64 column that is the difference between the two columns. I'm trying to plot a histogram of the timedelta column to visualize the time differences between the two events.</p> <p>However, just using <code>df['time_delta']</code> results in: <code>TypeError: ufunc add cannot use operands with types dtype('&lt;m8[ns]') and dtype('float64')</code></p> <p>Trying to convert the timedelta column to : <code>float--&gt; df2 = df1['time_delta'].astype(float)</code> results in: <code>TypeError: cannot astype a timedelta from [timedelta64[ns]] to [float64]</code></p> <p>How would one create a histogram of pandas timedelta data?</p>
23,544,011
4
1
null
2014-05-08 13:57:39.613 UTC
12
2021-08-11 17:52:17.667 UTC
2014-05-08 14:02:51.167 UTC
null
1,398,915
null
3,325,052
null
1
69
python|matplotlib|pandas
48,377
<p>Here are ways to convert timedeltas, docs are <a href="http://pandas-docs.github.io/pandas-docs-travis/timeseries.html#time-deltas">here</a></p> <pre><code>In [2]: pd.to_timedelta(np.arange(5),unit='d')+pd.to_timedelta(1,unit='s') Out[2]: 0 0 days, 00:00:01 1 1 days, 00:00:01 2 2 days, 00:00:01 3 3 days, 00:00:01 4 4 days, 00:00:01 dtype: timedelta64[ns] </code></pre> <p>Convert to seconds (is an exact conversion)</p> <pre><code>In [3]: (pd.to_timedelta(np.arange(5),unit='d')+pd.to_timedelta(1,unit='s')).astype('timedelta64[s]') Out[3]: 0 1 1 86401 2 172801 3 259201 4 345601 dtype: float64 </code></pre> <p>Convert using astype will round to that unit</p> <pre><code>In [4]: (pd.to_timedelta(np.arange(5),unit='d')+pd.to_timedelta(1,unit='s')).astype('timedelta64[D]') Out[4]: 0 0 1 1 2 2 3 3 4 4 dtype: float64 </code></pre> <p>Division will give an exact repr</p> <pre><code>In [5]: (pd.to_timedelta(np.arange(5),unit='d')+pd.to_timedelta(1,unit='s')) / np.timedelta64(1,'D') Out[5]: 0 0.000012 1 1.000012 2 2.000012 3 3.000012 4 4.000012 dtype: float64 </code></pre>
48,029,542
Data augmentation in test/validation set?
<p>It is common practice to augment data (add samples programmatically, such as random crops, etc. in the case of a dataset consisting of images) on both training and test set, or just the training data set?</p>
48,031,128
11
2
null
2017-12-29 23:31:56.63 UTC
11
2022-04-26 13:59:37.217 UTC
2017-12-30 21:42:01.04 UTC
null
774,907
null
774,907
null
1
38
machine-learning|deep-learning
25,068
<p>Only on training. Data augmentation is used to increase the size of the training set and to get more different images. Technically, you could use data augmentation on the test set to see how the model behaves on such images, but usually, people don't do it.</p>
25,447,803
Python socket connection exception
<p>I have a socket-connection going on and I wanna improve the exception handling and I'm stuck. Whenever I call <code>socket.connect(server_address)</code> with an invalid argument the program stops, but doesn't seem to raise an exception. Here is my code:</p> <pre><code>import socket import sys import struct class ARToolkit(): def __init__(self): self.x = 0 self.y = 0 self.z = 0 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.logging = False def connect(self,server_address): try: self.sock.connect(server_address) except socket.error, msg: print &quot;Couldnt connect with the socket-server: %s\n terminating program&quot; % msg sys.exit(1) def initiate(self): self.sock.send(&quot;start_logging&quot;) def log(self): self.logging = True buf = self.sock.recv(6000) if len(buf)&gt;0: nbuf = buf[len(buf)-12:len(buf)] self.x, self.y, self.z = struct.unpack(&quot;&lt;iii&quot;, nbuf) def stop_logging(self): print &quot;Stopping logging&quot; self.logging = False self.sock.close() </code></pre> <p>The class maybe looks a bit wierd but its used for receiving coordinates from another computer running ARToolKit. Anyway, the issue is at the function <code>connect()</code>:</p> <pre><code>def connect(self,server_address): try: self.sock.connect(server_address) except socket.error, msg: print &quot;Couldnt connect with the socket-server: %s\n terminating program&quot; % msg sys.exit(1) </code></pre> <p>If I call that function with a random IP-address and portnumber the whole program just stops up at the line:</p> <pre><code>self.sock.connect(server_address) </code></pre> <p>The documentation I've read states that in case of an error it will throw a socket.error-exception. I've also tried with just:</p> <pre><code>except Exception, msg: </code></pre> <p>This, if I'm not mistaken, will catch any exceptions, and still it yields no result. I would be very grateful for a helping hand. Also, is it okay to exit programs using sys.exit when an unwanted exception occurs?</p> <p>Thank you</p>
25,448,603
2
1
null
2014-08-22 13:07:21.833 UTC
8
2021-10-09 13:30:29.007 UTC
2021-10-09 13:30:29.007 UTC
null
4,298,200
null
3,928,985
null
1
19
python|sockets|exception
122,685
<p>If you have chosen a random, but valid, IP address and port, <code>socket.connect()</code> will attempt to make a connection to that endpoint. By default, if no explicit timeout is set for the socket, it will block while doing so and eventually timeout, raising exception <code>socket.error: [Errno 110] Connection timed out</code>.</p> <p>The default timeout on my machine is 120 seconds. Perhaps you are not waiting long enough for <code>socket.connect()</code> to return (or timeout)?</p> <p>You can try reducing the timeout like this:</p> <pre><code>import socket s = socket.socket() s.settimeout(5) # 5 seconds try: s.connect(('123.123.123.123', 12345)) # "random" IP address and port except socket.error, exc: print "Caught exception socket.error : %s" % exc </code></pre> <p>Note that if a timeout is explicitly set for the socket, the exception will be <code>socket.timeout</code> which is derived from <code>socket.error</code> and will therefore be caught by the above except clause.</p>
20,632,940
How to set String Array in Java Annotation
<p>I have declared a annotation like this:</p> <pre><code>public @interface CustomAnnot { String[] author() default "me"; String description() default ""; } </code></pre> <p>A valid Annotation therefore would be</p> <pre><code>@CustomAnnot(author="author1", description="test") </code></pre> <p>What I can't figure out is, how to set more than one author, since author() has return String[] this should be possible.</p> <pre><code>@CustomAnnot(author="author1","autor2", description="test") </code></pre> <p>doesn't work!</p>
20,632,992
1
1
null
2013-12-17 11:30:07.393 UTC
10
2015-10-30 09:23:16.343 UTC
null
null
null
null
1,804,317
null
1
95
java|annotations
77,378
<p>Do it like this:</p> <pre><code>public @interface CustomAnnot { String[] author() default "me"; String description() default ""; } </code></pre> <p>And your annotation:</p> <pre><code> @CustomAnnot(author={"author1","author2"}, description="test") </code></pre>
20,845,210
Setting selected values for ng-options bound select elements
<p>Fiddle with the relevant code: <a href="http://jsfiddle.net/gFCzV/7/">http://jsfiddle.net/gFCzV/7/</a></p> <p>I'm trying to set the selected value of a drop down that is bound to a child collection of an object referenced in an ng-repeat. I don't know how to set the selected option since I can't reference the collection it's being bound to in any way that I'm aware of.</p> <p><strong>HTML</strong>:</p> <pre><code>&lt;div ng-app="myApp" ng-controller="SomeController"&gt; &lt;div ng-repeat="Person in People"&gt; &lt;div class="listheader"&gt;{{Person.firstName}} {{Person.lastName}}&lt;/div&gt; &lt;div class="listitem" ng-repeat="Choice in Person.Choices"&gt; {{Choice.Name}}: &lt;select ng-model="Choice.SelectedOption" ng-options="choice.Name for choice in Choice.Options"&gt;&lt;/select&gt; {{Choice.SelectedOption.ID}} &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p><strong>JS</strong>:</p> <pre><code>var myApp = angular.module('myApp', []); myApp.controller("SomeController", function($scope) { $scope.People = [{ "firstName": "John", "lastName": "Doe", "Choices": [ { "Name":"Dinner", "Options":[{Name:"Fish",ID:1}, {Name:"Chicken",ID:2}, {Name:"Beef",ID:3}], "SelectedOption":{Name:"Chicken",ID:2} //this doesn't work }, { "Name":"Lunch", "Options":[{Name:"Macaroni",ID:1}, {Name:"PB&amp;J",ID:2}, {Name:"Fish",ID:3}], "SelectedOption":"" } ], }, { "firstName": "Jane", "lastName": "Doe" }]; }); </code></pre> <p>Is this the one case where I should actually be using ng-init with a SelectedIndex on the model?</p>
25,218,943
3
1
null
2013-12-30 18:24:05.807 UTC
16
2020-11-21 08:18:50.01 UTC
null
null
null
null
166,060
null
1
33
angularjs|ng-options
109,655
<p>If using AngularJS 1.2 you can use 'track by' to tell Angular how to compare objects. </p> <pre><code>&lt;select ng-model="Choice.SelectedOption" ng-options="choice.Name for choice in Choice.Options track by choice.ID"&gt; &lt;/select&gt; </code></pre> <p>Updated fiddle <a href="http://jsfiddle.net/gFCzV/34/" rel="noreferrer">http://jsfiddle.net/gFCzV/34/</a></p>
29,788,181
Kyle Simpson's OLOO Pattern vs Prototype Design Pattern
<p>Does Kyle Simpson's &quot;OLOO (Objects Linking to Other Objects) Pattern&quot; differ in any way from the the Prototype design pattern? Other than coining it by something that specifically indicates &quot;linking&quot; (the behavior of prototypes) and clarifying that there's no to &quot;copying&quot; happening here (a behavior of classes), what exactly does his pattern introduce?</p> <p>Here's <a href="https://github.com/getify/You-Dont-Know-JS/blob/1st-ed/this%20%26%20object%20prototypes/ch6.md#delegation-theory" rel="nofollow noreferrer">an example of Kyle's pattern</a> from his book, &quot;You Don't Know JS: this &amp; Object Prototypes&quot;:</p> <pre><code>var Foo = { init: function(who) { this.me = who; }, identify: function() { return &quot;I am &quot; + this.me; } }; var Bar = Object.create(Foo); Bar.speak = function() { alert(&quot;Hello, &quot; + this.identify() + &quot;.&quot;); }; var b1 = Object.create(Bar); b1.init(&quot;b1&quot;); var b2 = Object.create(Bar); b2.init(&quot;b2&quot;); b1.speak(); // alerts: &quot;Hello, I am b1.&quot; b2.speak(); // alerts: &quot;Hello, I am b2.&quot; </code></pre>
30,468,602
8
2
null
2015-04-22 05:05:50.223 UTC
74
2022-08-15 07:08:06.03 UTC
2022-08-15 07:08:06.03 UTC
null
12,054,184
null
2,399,980
null
1
117
javascript|design-patterns
28,436
<blockquote> <p>what exactly does his pattern introduce?</p> </blockquote> <p>OLOO embraces the prototype chain as-is, without needing to layer on other (IMO confusing) semantics to get the linkage.</p> <p>So, these two snippets have the EXACT same outcome, but get there differently.</p> <p><strong>Constructor Form:</strong></p> <pre><code>function Foo() {} Foo.prototype.y = 11; function Bar() {} Bar.prototype = Object.create(Foo.prototype); Bar.prototype.z = 31; var x = new Bar(); x.y + x.z; // 42 </code></pre> <p><strong>OLOO Form:</strong></p> <pre><code>var FooObj = { y: 11 }; var BarObj = Object.create(FooObj); BarObj.z = 31; var x = Object.create(BarObj); x.y + x.z; // 42 </code></pre> <p>In both snippets, an <code>x</code> object is <code>[[Prototype]]</code>-linked to an object (<code>Bar.prototype</code> or <code>BarObj</code>), which in turn is linked to third object (<code>Foo.prototype</code> or <code>FooObj</code>).</p> <p>The relationships and delegation are identical between the snippets. The memory usage is identical between the snippets. The ability to create many "children" (aka, many objects like <code>x1</code> through <code>x1000</code>, etc) is identical between the snippets. The performance of the delegation (<code>x.y</code> and <code>x.z</code>) is identical between the snippets. The object creation performance <em>is</em> slower with OLOO, but <a href="http://web.archive.org/web/20141012195436/http://blog.getify.com/sanity-check-object-creation-performance" rel="noreferrer">sanity checking that</a> reveals that the slower performance is really not an issue.</p> <p>What I argue OLOO offers is that it's much simpler to just express the objects and directly link them, than to indirectly link them through the constructor/<code>new</code> mechanisms. The latter pretends to be about classes but really is just a terrible syntax for expressing delegation (<strong>side note:</strong> so is ES6 <code>class</code> syntax!).</p> <p><strong>OLOO is just cutting out the middle-man.</strong></p> <p>Here's <a href="https://gist.github.com/getify/d0cdddfa4673657a9941" rel="noreferrer">another comparison</a> of <code>class</code> vs OLOO.</p>
32,563,173
Installing node.js on raspberry pi 2
<p>I have installed Raspbian on my Raspberry Pi 2 and now I am trying to install node.js on it, however I am hitting an issue.</p> <p>I followed the instructions and typed these commands into the terminal</p> <pre><code>wget http://node-arm.herokuapp.com/node_latest_armhf.deb sudo dpkg -i node_latest_armhf.deb </code></pre> <p>But when I check the version of node using</p> <pre><code>node -v </code></pre> <p>I get this error:</p> <pre><code>node: /usr/lib/arm-linux-gnueabihf/libstdc++.so.6: version `GLIBCXX_3.4.20' not found (required by node) node: /lib/arm-linus-gnueabihf/libc.so.6: version `GLIBC_2.16' not found (required by node) </code></pre> <p>I am quite new to using raspberry pi, so any help to fix this issue would be great!</p>
32,576,711
6
3
null
2015-09-14 11:03:07.067 UTC
11
2018-07-13 20:37:43.363 UTC
null
null
null
null
2,351,559
null
1
16
node.js|debian|raspbian|raspberry-pi2|dpkg
27,944
<p>Just putting the response from @Prashant Pathak above here:</p> <ol> <li><p>Download latest nodejs build for Raspberry Pi: </p> <pre><code>wget https://nodejs.org/download/release/v0.10.0/node-v0.10.0-linux-arm-pi.tar.gz </code></pre></li> <li><p>Unpack files in local directory:</p> <pre><code>cd /usr/local sudo tar xzvf ~/node-v0.10.0-linux-arm-pi.tar.gz --strip=1 </code></pre></li> </ol> <p>That's it. You can confirm it's there by checking the node version with:</p> <pre><code>node -v </code></pre> <p>and:</p> <pre><code>npm -v </code></pre> <p>The actual url to get the files for node will change as the version changes, you can always see the list of files available for download here: <a href="http://nodejs.org/download/" rel="nofollow noreferrer">http://nodejs.org/download/</a></p> <p>All these instructions came from: <a href="http://www.robert-drummond.com/2015/01/08/server-side-javascript-on-a-raspberry-pi-how-to-install-node-js-2/" rel="nofollow noreferrer" title="robert-drummond.com">http://www.robert-drummond.com/2015/01/08/server-side-javascript-on-a-raspberry-pi-how-to-install-node-js-2/</a></p>
32,210,389
Pause an Elastic Beanstalk app environment?
<p>I want to shut down the app servers while I upgrade the database. </p> <p>Is there a way to pause or stop the app servers without terminating/destroying the environment?</p> <p>Can I just go to the Elastic Beanstalk load balancer and change that temporarily without any issues or consequences to the Elastic Beanstalk configurations or the way it manages its servers?</p>
40,865,989
5
3
null
2015-08-25 17:27:02.67 UTC
22
2021-09-04 20:44:12.433 UTC
2015-08-25 17:53:28.723 UTC
null
1,132,806
null
611,750
null
1
80
amazon-web-services|amazon-elastic-beanstalk
30,695
<p>This is the only method that worked for me.</p> <p>1) Go to the environment you want to pause on <a href="https://console.aws.amazon.com/elasticbeanstalk/home" rel="noreferrer">AWS Management Console</a></p> <p>2) Select "Configuration"</p> <p>3) Open "Capacity"</p> <p>4) Scroll all the way down to "Time-based Scaling"</p> <p>5) Click the "Add schedule action" button</p> <p>6) Set the action to few minutes in the future (recommended: 5 minutes so environment has time to reset), give it a name (for example "terminate") and set minimum and maximum instances to '0':</p> <p><a href="https://i.stack.imgur.com/W1wbP.png" rel="noreferrer"><img src="https://i.stack.imgur.com/W1wbP.png" alt="New scheduled action"></a></p> <blockquote> <p>Note that times are set in UTC. You can use <a href="https://time.is/UTC" rel="noreferrer">time.is/UTC</a> to determine the current UTC.</p> </blockquote> <p>This would create an error that would shut down your environment so you won't have to pay for it. Any other methods suggested just create a error at time of applying so it doesn't pass through and environment would still work.</p> <p>To re-enable the environment, just schedule another action with instance min 1 and max 4 for example (those are the defaults).</p>
20,067,636
Pandas dataframe get first row of each group
<p>I have a pandas <code>DataFrame</code> like following:</p> <pre><code>df = pd.DataFrame({'id' : [1,1,1,2,2,3,3,3,3,4,4,5,6,6,6,7,7], 'value' : [&quot;first&quot;,&quot;second&quot;,&quot;second&quot;,&quot;first&quot;, &quot;second&quot;,&quot;first&quot;,&quot;third&quot;,&quot;fourth&quot;, &quot;fifth&quot;,&quot;second&quot;,&quot;fifth&quot;,&quot;first&quot;, &quot;first&quot;,&quot;second&quot;,&quot;third&quot;,&quot;fourth&quot;,&quot;fifth&quot;]}) </code></pre> <p>I want to group this by <code>[&quot;id&quot;,&quot;value&quot;]</code> and get the first row of each group:</p> <pre><code> id value 0 1 first 1 1 second 2 1 second 3 2 first 4 2 second 5 3 first 6 3 third 7 3 fourth 8 3 fifth 9 4 second 10 4 fifth 11 5 first 12 6 first 13 6 second 14 6 third 15 7 fourth 16 7 fifth </code></pre> <p>Expected outcome:</p> <pre><code> id value 1 first 2 first 3 first 4 second 5 first 6 first 7 fourth </code></pre> <p>I tried following, which only gives the first row of the <code>DataFrame</code>. Any help regarding this is appreciated.</p> <pre><code>In [25]: for index, row in df.iterrows(): ....: df2 = pd.DataFrame(df.groupby(['id','value']).reset_index().ix[0]) </code></pre>
20,067,665
8
1
null
2013-11-19 09:24:34.953 UTC
63
2022-05-13 21:32:58.04 UTC
2022-05-13 21:32:58.04 UTC
null
8,973,620
null
461,436
null
1
238
python|pandas|dataframe|group-by|row
269,475
<pre><code>&gt;&gt;&gt; df.groupby('id').first() value id 1 first 2 first 3 first 4 second 5 first 6 first 7 fourth </code></pre> <p>If you need <code>id</code> as column:</p> <pre><code>&gt;&gt;&gt; df.groupby('id').first().reset_index() id value 0 1 first 1 2 first 2 3 first 3 4 second 4 5 first 5 6 first 6 7 fourth </code></pre> <p>To get n first records, you can use head():</p> <pre><code>&gt;&gt;&gt; df.groupby('id').head(2).reset_index(drop=True) id value 0 1 first 1 1 second 2 2 first 3 2 second 4 3 first 5 3 third 6 4 second 7 4 fifth 8 5 first 9 6 first 10 6 second 11 7 fourth 12 7 fifth </code></pre>
6,857,082
Redo merge of just a single file
<p>I'm in the middle of a large merge, and I've used <code>git mergetool</code> to resolve all the conflicts, but I have not committed yet, as I wanted to make sure the merge was ok first.</p> <p>It turns out that I made a mistake while resolving the conflicts in one file, and I would like to redo the conflict resolution with <code>git mergetool</code> on that file. As this is a large merge I would like to avoid redoing the merge on all the other files, as I understand I would have to do with <code>git merge --abort</code>.</p> <p>I know I could just edit the file manually, but this would be quite tedious and it would be much easier to just redo the <code>git mergetool</code> operation. Is this possible?</p>
6,865,041
2
1
null
2011-07-28 09:54:34.02 UTC
30
2012-11-30 21:58:53.56 UTC
2012-11-30 21:58:53.56 UTC
null
98,117
null
98,117
null
1
132
git|merge
20,468
<p>It seems I was just looking in the wrong place. The solution turned out to be quite simple.</p> <pre><code>git checkout -m &lt;file&gt; </code></pre> <p>This returns the file to its conflicted state. I can then run <code>git mergetool</code> to redo the merge.</p>
7,358,821
requestvalidationmode="2.0" validaterequest="false" in web.config not working
<p>I'm looking for a bit of help as this is now driving me crazy.</p> <p>I have a tinyMCE text editor on my page which is populated with content which is already stored in the database as html.</p> <p>eg. <code>&lt;p&gt;first paragraph&lt;/p&gt; &lt;p&gt;second paragraph&lt;/p&gt;</code> etc, etc with no problems there.</p> <p>but when I make a change in the editor and then try to update the content in the database I get the error <strong>potentially dangerous request.form value was detected from the client</strong></p> <p>I made all the recommended changes in the web.config</p> <ul> <li>requestvalidationmode="2.0" </li> <li>validaterequest="false"</li> </ul> <p>But still get the <strong>potentially dangerous request.form value was detected from the client</strong> error. This is happening in .NET 4.0 any help/advice would be great.</p>
7,358,888
4
1
null
2011-09-09 08:11:27.447 UTC
null
2019-04-15 11:53:23.007 UTC
2017-02-22 09:29:21.13 UTC
null
133
null
911,553
null
1
9
c#|.net|asp.net|.net-4.0
59,817
<p>I wouldn't even try to enable this on a site-wide level in the web.config file - just do it per page, when you know specifically input data is safe:</p> <pre><code>&lt;%@ Page ... ValidateRequest="false" %&gt; </code></pre> <p>You can use an Umbraco control exposed specifically for this purpose from within a Template as such:</p> <pre><code>&lt;umbraco:DisableRequestValidation runat="server" /&gt; </code></pre>
23,995,019
What is the modern method for setting general compile flags in CMake?
<p>There are multiple mechanisms offered by CMake for getting flags to the compiler:</p> <ul> <li><a href="http://www.cmake.org/cmake/help/v2.8.12/cmake.html#variable%3aCMAKE_LANG_FLAGS"><code>CMAKE_&lt;LANG&gt;_FLAGS_&lt;CONFIG&gt;</code> variables</a></li> <li><a href="http://www.cmake.org/cmake/help/v2.8.12/cmake.html#command%3aadd_compile_options"><code>add_compile_options</code> command</a></li> <li><a href="http://www.cmake.org/cmake/help/v2.8.12/cmake.html#command%3aset_target_properties"><code>set_target_properties</code> command</a></li> </ul> <p>Is there one method that is preferred over the other in modern use? If so why? Also, how can this method be used with multiple configuration systems such as MSVC?</p>
23,995,391
1
1
null
2014-06-02 12:53:02.477 UTC
39
2022-09-17 05:46:37.08 UTC
null
null
null
null
2,507,444
null
1
105
cmake
63,646
<p>For modern CMake (versions 2.8.12 and up) you should use <a href="https://www.cmake.org/cmake/help/latest/command/target_compile_options.html" rel="nofollow noreferrer"><code>target_compile_options</code></a>, which uses target properties internally.</p> <p><code>CMAKE_&lt;LANG&gt;_FLAGS</code> is a global variable and the most error-prone to use. It also does not support <a href="https://www.cmake.org/cmake/help/latest/manual/cmake-generator-expressions.7.html" rel="nofollow noreferrer">generator expressions</a>, which can come in very handy.</p> <p><code>add_compile_options</code> is based on directory properties, which is fine in some situations, but usually not the most natural way to specify options.</p> <p><code>target_compile_options</code> works on a per-target basis (through setting the <a href="https://www.cmake.org/cmake/help/latest/prop_tgt/COMPILE_OPTIONS.html" rel="nofollow noreferrer"><code>COMPILE_OPTIONS</code></a> and <a href="https://www.cmake.org/cmake/help/latest/prop_tgt/INTERFACE_COMPILE_OPTIONS.html" rel="nofollow noreferrer"><code>INTERFACE_COMPILE_OPTIONS</code></a> target properties), which usually results in the cleanest CMake code, as the compile options for a source file are determined by which project the file belongs to (rather than which directory it is placed in on the hard disk). This has the additional advantage that it <a href="https://www.cmake.org/cmake/help/latest/manual/cmake-buildsystem.7.html#transitive-usage-requirements" rel="nofollow noreferrer">automatically takes care of passing options on</a> to dependent targets if requested.</p> <p>Even though they are little bit more verbose, the per-target commands allow a reasonably fine-grained control over the different build options and (in my personal experience) are the least likely to cause headaches in the long run.</p> <p>In theory, you could also set the respective properties directly using <code>set_target_properties</code>, but <code>target_compile_options</code> is usually more readable.</p> <p>For example, to set the compile options of a target <code>foo</code> based on the configuration using generator expressions you could write:</p> <pre><code>target_compile_options(foo PUBLIC &quot;$&lt;$&lt;CONFIG:DEBUG&gt;:${MY_DEBUG_OPTIONS}&gt;&quot;) target_compile_options(foo PUBLIC &quot;$&lt;$&lt;CONFIG:RELEASE&gt;:${MY_RELEASE_OPTIONS}&gt;&quot;) </code></pre> <p>The <code>PUBLIC</code>, <code>PRIVATE</code>, and <code>INTERFACE</code> keywords define the <a href="https://cmake.org/cmake/help/latest/command/target_compile_options.html" rel="nofollow noreferrer">scope of the options</a>. E.g., if we link <code>foo</code> into <code>bar</code> with <code>target_link_libraries(bar foo)</code>:</p> <ul> <li><code>PRIVATE</code> options will only be applied to the target itself (<code>foo</code>) and not to other libraries (consumers) linking against it.</li> <li><code>INTERFACE</code> options will only be applied to the consuming target <code>bar</code></li> <li><code>PUBLIC</code> options will be applied to both, the original target <code>foo</code> and the consuming target <code>bar</code></li> </ul>
24,421,745
How can I set just `Widget` size?
<p>How can I set just <code>Widget</code> size?</p> <p>My code:</p> <pre><code>from PySide.QtGui import QApplication, QWidget, QLabel import sys app = QApplication(sys.argv) mainWindow = QWidget() gameWidget = QWidget(mainWindow) #gameWidget.setGeometry(gameWidth, gameHeight) &lt;-- I want to set size of gameWidget such like this. How can I do this. gameWidget.move(100,0) gameLabel = QLabel("This is game widget", gameWidget) mainWindow.show() </code></pre> <p>Output:</p> <p><img src="https://i.stack.imgur.com/GYjiL.png" alt="enter image description here"></p> <p>Description:</p> <p>This will create <code>Window</code> that contain <code>Widget</code>. I want to set this <code>Widget</code> size. I know There is a method <code>Widget.setGeometry</code>, but it takes 4 parameter <i>(x, y, width, height)</i>. I want a method like <code>Widget.setGeometry</code> which takes just size parameter <i>(width, height)</i>.</p> <p><b>P.S.</b> Feel free to modify my question. Because I'm always learning English!!</p> <p>Thanks.</p>
24,421,789
1
1
null
2014-06-26 03:06:31.907 UTC
2
2014-06-26 03:21:47.07 UTC
null
null
null
null
2,931,409
null
1
10
qt|pyqt|pyside
39,908
<p>Just use <a href="http://srinikom.github.io/pyside-docs/PySide/QtGui/QWidget.html#PySide.QtGui.PySide.QtGui.QWidget.resize" rel="noreferrer"><code>QWidget.resize(weight, height)</code></a>.</p> <p>For example:</p> <pre><code>gameLabel.resize(200, 100); </code></pre> <hr> <p>Besides, you can also use <a href="http://srinikom.github.io/pyside-docs/PySide/QtGui/QWidget.html#PySide.QtGui.PySide.QtGui.QWidget.sizeHint" rel="noreferrer"><code>QWidget.sizeHint()</code></a> to get a proper size automatically, for example:</p> <pre><code>gameLabel.resize(gameLabel.sizeHint()); </code></pre>
8,004,001
How does jsFiddle allow and execute user-defined JavaScript without being dangerous?
<p>I've been working on a JS library and would like to setup a demo page on Github that allows, for example, users to define their own callbacks and execute commands. </p> <p>I know "<code>eval()</code> is evil" and I can see how blind <code>eval()</code> of scripts could lead to XSS and other security issues. I'm trying to cook up some alternative schemes.</p> <p>I really enjoy the interactivity of jsFiddle. I've taken a look at their source but was hoping someone could lay out here how jsFiddle allows and executes user-defined JavaScript without being dangerous. So long as it doesn't involve a 3rd party echo server, I'm hoping I can emulate the approach.</p>
8,004,010
1
0
null
2011-11-04 01:36:17.87 UTC
9
2011-11-04 01:44:23.2 UTC
null
null
null
null
317,937
null
1
23
javascript|security|cross-domain|eval|user-input
4,258
<p>jsFiddle executes user scripts on a separate domain, <code>http://fiddle.jshell.net</code> (<a href="http://jsfiddle.net/SLaks/rAXbE/">try it and see</a>).<br> Therefore, it can't interact with the parent frame and it can't steal cookies.</p> <p>You can actually do this without a separate server by placing a static page in a separate domain that reads from its querystring in Javascript.<br> You can communicate back using the page title (and so can the enemy).</p>
7,780,760
WCF what should be the endpointConfigurationName?
<p>I have the following config for my WCF service:</p> <pre><code>&lt;system.serviceModel&gt; &lt;services&gt; &lt;service behaviorConfiguration="After.BehaviourConfig" name="ServiceInstancingDemo.Service1"&gt; &lt;endpoint address="" binding="wsHttpBinding" bindingConfiguration="After.BindingConfig" name="After.ConfigName" contract="ServiceInstancingDemo.IService1"&gt; &lt;identity&gt; &lt;dns value="localhost" /&gt; &lt;/identity&gt; &lt;/endpoint&gt; &lt;endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /&gt; &lt;host&gt; &lt;baseAddresses&gt; &lt;add baseAddress="http://rb-t510/NGCInstancing/Service1.svc" /&gt; &lt;/baseAddresses&gt; &lt;/host&gt; &lt;/service&gt; &lt;/services&gt; &lt;bindings&gt; &lt;wsHttpBinding&gt; &lt;binding name="After.BindingConfig" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" maxBufferPoolSize="524288111" maxReceivedMessageSize="524288111" allowCookies="false"&gt; &lt;security mode="None" /&gt; &lt;/binding&gt; &lt;/wsHttpBinding&gt; &lt;/bindings&gt; &lt;behaviors&gt; &lt;serviceBehaviors&gt; &lt;behavior name="After.BehaviourConfig"&gt; &lt;serviceMetadata httpGetEnabled="true" /&gt; &lt;serviceDebug includeExceptionDetailInFaults="true" /&gt; &lt;serviceThrottling maxConcurrentCalls="30" maxConcurrentInstances="2147483647" maxConcurrentSessions="30" /&gt; &lt;/behavior&gt; &lt;/serviceBehaviors&gt; &lt;/behaviors&gt; </code></pre> <p></p> <p>I am able to call the service with the following client code:</p> <pre><code>NGC.Service1Client ngc = new NGC.Service1Client(); var taskA = Task&lt;string&gt;.Factory.StartNew(() =&gt; ngc.WaitThenReturnString(5)); this.listBox1.Items.Add(taskA.Result); </code></pre> <p>The config for the client that calls the service is as follows:</p> <pre><code> &lt;system.serviceModel&gt; &lt;bindings&gt; &lt;wsHttpBinding&gt; &lt;binding name="Before" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" maxBufferPoolSize="524288111" maxReceivedMessageSize="524288111" allowCookies="false" /&gt; &lt;binding name="After" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" maxBufferPoolSize="524288111" maxReceivedMessageSize="524288111" allowCookies="false"&gt; &lt;security mode="None" /&gt; &lt;/binding&gt; &lt;binding name="WSHttpBinding_IService1" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true" allowCookies="false"&gt; &lt;readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" /&gt; &lt;reliableSession ordered="true" inactivityTimeout="00:10:00" enabled="false" /&gt; &lt;security mode="None"&gt; &lt;transport clientCredentialType="Windows" proxyCredentialType="None" realm="" /&gt; &lt;message clientCredentialType="Windows" negotiateServiceCredential="true" /&gt; &lt;/security&gt; &lt;/binding&gt; &lt;/wsHttpBinding&gt; &lt;/bindings&gt; &lt;client&gt; &lt;endpoint address="http://rb-t510/NGCInstancing/Service1.svc" binding="wsHttpBinding" bindingConfiguration="Before" contract="NGCInstance.IService1" name="Before" /&gt; &lt;endpoint address="http://rb-t510/NGCInstancing/Service1.svc" binding="wsHttpBinding" bindingConfiguration="After" contract="NGCInstance.IService1" name="After" /&gt; &lt;endpoint address="http://rb-t510/NGCInstancing/Service1.svc" binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IService1" contract="NGC.IService1" name="WSHttpBinding_IService1"&gt; &lt;identity&gt; &lt;dns value="localhost" /&gt; &lt;/identity&gt; &lt;/endpoint&gt; &lt;/client&gt; &lt;/system.serviceModel&gt; </code></pre> <p>Problem is, I want to add another endpoint that will execute the same functionality but with a different behavior. To do this, I think I'm going to need to pass a string of the enpointConfigurationName to the constructor in the line=new NGC.Service1Client. I don't know what string I need to pass - I would have expected it to be the endpoint configuration name "After.ConfigName" but I tried this and got the following error message:</p> <p><em>Could not find endpoint element with name 'After.ConfigName' and contract 'NGC.IService1' in the ServiceModel client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this name could be found in the client element.</em></p> <p>Can anyone please help?</p>
7,780,811
1
0
null
2011-10-15 21:29:38.007 UTC
3
2016-07-21 13:22:11.893 UTC
2016-07-21 13:22:11.893 UTC
null
133
null
41,169
null
1
25
wcf
53,471
<p>You would pass the value of the <code>name</code> attribute of the corresponding client endpoint you would like to use. For example if you wanted to use the third endpoint:</p> <pre><code>new NGC.Service1Client("WSHttpBinding_IService1") </code></pre>
1,781,046
Dynamically invoke a class method in Objective C
<p>Suppose I have Objective C interface <code>SomeClass</code> which has a class method called <code>someMethod</code>: </p> <pre><code>@interface SomeClass : NSObject { } + (id)someMethod; @end </code></pre> <p>In some other interface I want to have a helper method that would dynamically invoke <code>someMethod</code> on a class like this:</p> <pre><code>[someOtherObject invokeSelector:@selector(someMethod) forClass:[SomeClass class]; </code></pre> <p>What should be the implementation for <code>invokeSelector</code>? Is it possible at all?</p> <pre><code>- (void)invokeSelector:(SEL)aSelector forClass:(Class)aClass { // ??? } </code></pre>
1,781,062
4
2
null
2009-11-23 04:04:34.09 UTC
11
2018-06-04 13:56:51.42 UTC
2009-11-23 17:59:48.913 UTC
null
8,653
null
8,653
null
1
41
objective-c|cocoa|cocoa-touch
33,241
<p>Instead of:</p> <pre><code>[someOtherObject invokeSelector:@selector(someMethod) forClass:[SomeClass class]; </code></pre> <p>call:</p> <pre><code>[[SomeClass class] performSelector:@selector(someMethod)]; </code></pre> <p>Example (using GNUstep ...)</p> <p>file A.h</p> <pre><code>#import &lt;Foundation/Foundation.h&gt; @interface A : NSObject {} - (NSString *)description; + (NSString *)action; @end </code></pre> <p>file A.m</p> <pre><code>#import &lt;Foundation/Foundation.h&gt; #import "A.h" @implementation A - (NSString *)description { return [NSString stringWithString: @"A"]; } + (NSString *)action { return [NSString stringWithString:@"A::action"]; } @end </code></pre> <p>Somewhere else:</p> <pre><code>A *a = [[A class] performSelector:@selector(action)]; NSLog(@"%@",a); </code></pre> <p>Output:</p> <pre><code>2009-11-22 23:32:41.974 abc[3200] A::action </code></pre> <hr> <p>nice explanation from <a href="http://www.cocoabuilder.com/archive/cocoa/197631-how-do-classes-respond-to-performselector.html" rel="noreferrer">http://www.cocoabuilder.com/archive/cocoa/197631-how-do-classes-respond-to-performselector.html</a>:</p> <p>"In Objective-C, a class object gets all the instance methods of the root class for its hierarchy. This means that every class object that descends from NSObject gets all of NSObject's instance methods - including performSelector:."</p>
10,662,902
CSS "outline" different behavior behavior on Webkit & Gecko
<p>I'm working on an experiment &amp; I found out that the "outline" CSS2 property is not implemented the same way on Webkit &amp; Gecko</p> <p>In the script below, I have a absolute position div inside another div but floating outside of it. The outline on Webkit outlines the actual parent div while on Gecko, it expands to cover the child item. </p> <p><a href="http://jsfiddle.net/KrCs4/" rel="noreferrer">http://jsfiddle.net/KrCs4/</a></p> <p>Am I missing anything? Is there a property that I need to overwrite on Gecko? or it should be reported as a bug?</p> <p>Webkit Screenshot:</p> <p><img src="https://i.stack.imgur.com/khftZ.png" alt="Webkit Screenshot"></p> <p>Firefox Screenshot:</p> <p><img src="https://i.stack.imgur.com/Cnl4g.png" alt="Firefox Screenshot"></p> <p>EDIT:</p> <p>It's confirmed to be a bug and here's a workaround: <a href="http://jsfiddle.net/7Vfee/" rel="noreferrer">http://jsfiddle.net/7Vfee/</a> (You need to make sure that the parent is positioned: relative or absolute for this workaround to work.</p>
10,662,977
3
2
null
2012-05-19 06:28:03.493 UTC
6
2020-10-30 16:33:20.617 UTC
2012-05-19 07:01:22.29 UTC
null
246,077
null
246,077
null
1
36
css|firefox|webkit|gecko
6,901
<p>This inconsistent behavior of Gecko is well-known and quite adequately documented, although strangely not at MDN but at the <a href="http://reference.sitepoint.com/css/outline" rel="noreferrer">SitePoint Reference</a>:</p> <blockquote> <p>Firefox up to and including version 3.5 will draw the outline outline around the content of an element that has overflowed its boundaries rather than around the element’s actual set dimensions.</p> </blockquote> <p>This continues to affect all versions of Firefox. I don't see a viable workaround for it at the moment, other than to remove your absolutely-positioned <code>div</code> from its parent and place it relative to... something else.</p>
10,581,843
Where is git-blame in SourceTree
<p>I'd like to see who contributed which line/change to a file. git-blame does exactly that. So does SourceTree have a git-blame view?</p>
53,251,577
5
2
null
2012-05-14 10:45:31.283 UTC
5
2021-09-01 12:30:01.593 UTC
2018-11-11 19:42:55.987 UTC
null
3,040,446
null
345,520
null
1
75
git|atlassian-sourcetree|git-gui|blame|git-blame
29,981
<p>Starting sourcetree 3.0</p> <p>Right click file &gt; <code>Annotate Selected</code></p> <p><a href="https://i.stack.imgur.com/fQDb3.png" rel="noreferrer"><img src="https://i.stack.imgur.com/fQDb3.png" alt="enter image description here" /></a></p>
7,658,228
MongoDB 'count()' is very slow. How do we refine/work around with it?
<p>I am currently using MongoDB with millions of data records. I discovered one thing that's pretty annoying.</p> <p>When I use 'count()' function with a small number of queried data collection, it's very fast. However, when the queried data collection contains thousand or even millions of data records, the entire system becomes very slow.</p> <p>I made sure that I have indexed the required fields.</p> <p>Has anybody encountered an identical thing? How do you do to improve that?</p>
7,658,467
5
0
null
2011-10-05 07:48:38.24 UTC
9
2021-03-16 20:50:16.877 UTC
null
null
null
null
113,037
null
1
65
performance|mongodb|count
52,686
<p>There is now another optimization than create proper index.</p> <pre><code>db.users.ensureIndex({name:1}); db.users.find({name:"Andrei"}).count(); </code></pre> <p>If you need some counters i suggest to precalculate them whenever it possible. By using atomic <a href="http://www.mongodb.org/display/DOCS/Updating#Updating-$inc" rel="noreferrer">$inc</a> operation and not use <code>count({})</code> at all.</p> <p>But mongodb guys working hard on mongodb, so, <code>count({})</code> improvements they are planning in mongodb 2.1 according to jira <a href="https://jira.mongodb.org/browse/SERVER-1752" rel="noreferrer">bug</a>.</p>
7,222,906
Failed to allocate memory: 8
<p>From today, when I tried to run an app in NetBeans on a 2.3.3 Android platform, it shows me that:</p> <blockquote> <p>Failed to allocate memory: 8</p> <p>This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information.</p> </blockquote> <p>and the Emulator doesn't want to start.</p> <p>This is for the first time when I see it, and google has no asnwers for this, I tried even with 2 versions of NetBeans 6.9.1 and 7.0.1, still the same error.</p>
7,249,408
20
9
2013-07-30 15:56:48.98 UTC
2011-08-28 18:14:30.453 UTC
66
2014-01-28 09:01:32.19 UTC
2014-01-28 09:01:32.19 UTC
null
881,229
null
715,437
null
1
371
android|netbeans|android-emulator
233,805
<p>I figured it out. The problem was in the amount of ram I had specified for the virtual machine, and it was 1024MB, now I have 512MB and it is ok, now I need to find how to improve this amount of ram, 512 is not so much, and the machine is a little bit laggy.</p>
14,120,346
C++: Fastest method to check if all array elements are equal
<p>What is the fastest method to check if all elements of an array(preferable integer array) are equal. Till now I have been using the following code:</p> <pre><code>bool check(int array[], int n) { bool flag = 0; for(int i = 0; i &lt; n - 1; i++) { if(array[i] != array[i + 1]) flag = 1; } return flag; } </code></pre>
14,120,508
12
5
null
2013-01-02 10:23:47.693 UTC
7
2021-05-22 13:29:43.51 UTC
2013-01-02 10:30:49.977 UTC
null
818,182
null
1,853,660
null
1
21
c++|arrays
60,012
<pre><code>int check(const int a[], int n) { while(--n&gt;0 &amp;&amp; a[n]==a[0]); return n!=0; } </code></pre>
13,865,537
SDWebImage clearing cache
<p>I'm displaying a list of icons downloaded from the web with text in a table view. The icons can be changed on server side and I need to replace them as soon as new icons are getting available. I try using the following code:</p> <pre><code>[imgView setImageWithURL:url placeholderImage:[UIImage imageNamed:@"table_avatar_icon"] options:SDWebImageCacheMemoryOnly]; </code></pre> <p>And call <code>[[SDImageCache sharedImageCache] clearMemory];</code> In my refresh callback, but it does not purge the contents of the cache. More to it, even if I close the application and open it again the image is still there.</p> <p>I found only one way to clear the cache and it is by calling <code>[[SDImageCache sharedImageCache] clearDisk];</code>. Which only works after I close and reopen the app.</p> <p>How can I force SDWebImage to not to use disk caching?</p>
16,277,427
5
1
null
2012-12-13 17:50:17.26 UTC
9
2022-01-12 02:31:12.263 UTC
null
null
null
null
874,027
null
1
35
iphone|objective-c|ios|sdwebimage
33,890
<pre><code>SDImageCache *imageCache = [SDImageCache sharedImageCache]; [imageCache clearMemory]; [imageCache clearDisk]; </code></pre> <p>Don't forget to put these lines of code in your <code>didReceiveMemoryWarning</code>, too.</p>
13,831,472
Using a Variable in OPENROWSET Query
<p>I'm having trouble with this query:</p> <pre><code>SELECT * FROM OPENROWSET( 'SQLNCLI', 'DRIVER={SQL Server};', 'EXEC dbo.sProc1 @ID = ' + @id ) </code></pre> <p>Gives an error:</p> <blockquote> <p>Incorrect syntax near '+'.</p> </blockquote> <p>Anyone know why I'm getting this error?</p>
13,831,792
6
0
null
2012-12-12 01:40:54.3 UTC
10
2021-02-19 12:38:25.397 UTC
2015-05-23 07:43:57.853 UTC
null
4,519,059
null
916,535
null
1
36
sql|sql-server|sql-server-2008|openrowset
84,297
<p>As suggested by Scott , you cannot use expressions in <code>OPENROWSET</code>.Try creating a dynamic sql to pass the parameters</p> <pre><code>Declare @ID int Declare @sql nvarchar(max) Set @ID=1 Set @sql='SELECT * FROM OPENROWSET( ''SQLNCLI'', ''DRIVER={SQL Server};'', ''EXEC dbo.usp_SO @ID =' + convert(varchar(10),@ID) + ''')' -- Print @sql Exec(@sql) </code></pre>
47,523,610
Android Oreo - how do I set Adaptive Icons in Cordova?
<p>Just wondering if anyone been able to set adaptive icons on Cordova for Android Oreo? I'm using the android 6.4.0 and my square icon shrinks to fit the circle. I just want it to not shrink. I don't care if the corners are clipped off from the rounding.</p>
48,000,536
9
3
null
2017-11-28 03:39:29.077 UTC
12
2020-11-27 14:39:31.647 UTC
null
null
null
null
7,544,745
null
1
28
android|cordova
23,528
<p><strong>WARNING: Don't use this answer. This is now supported out of the box as of Cordova 9. See <a href="https://stackoverflow.com/a/55169307/2947592">https://stackoverflow.com/a/55169307/2947592</a></strong></p> <p>I created the icons as described in <a href="https://developer.android.com/studio/write/image-asset-studio.html#create-adaptive" rel="nofollow noreferrer">https://developer.android.com/studio/write/image-asset-studio.html#create-adaptive</a>, copied them to <code>res/android</code> and use the following configuration:</p> <p>config.xml:</p> <pre><code>&lt;widget ... xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;&gt; &lt;platform name=&quot;android&quot;&gt; &lt;edit-config file=&quot;app/src/main/AndroidManifest.xml&quot; mode=&quot;merge&quot; target=&quot;/manifest/application&quot;&gt; &lt;application android:icon=&quot;@mipmap/ic_launcher&quot; android:roundIcon=&quot;@mipmap/ic_launcher_round&quot; /&gt; &lt;/edit-config&gt; &lt;resource-file src=&quot;res/android/drawable/ic_launcher_background.xml&quot; target=&quot;app/src/main/res/drawable/ic_launcher_background.xml&quot; /&gt; &lt;resource-file src=&quot;res/android/drawable/ic_launcher_foreground.xml&quot; target=&quot;app/src/main/res/drawable/ic_launcher_foreground.xml&quot; /&gt; &lt;resource-file src=&quot;res/android/mipmap-anydpi-v26/ic_launcher.xml&quot; target=&quot;app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml&quot; /&gt; &lt;resource-file src=&quot;res/android/mipmap-anydpi-v26/ic_launcher_round.xml&quot; target=&quot;app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml&quot; /&gt; &lt;resource-file src=&quot;res/android/mipmap-hdpi/ic_launcher.png&quot; target=&quot;app/src/main/res/mipmap-hdpi/ic_launcher.png&quot; /&gt; &lt;resource-file src=&quot;res/android/mipmap-hdpi/ic_launcher_round.png&quot; target=&quot;app/src/main/res/mipmap-hdpi/ic_launcher_round.png&quot; /&gt; &lt;resource-file src=&quot;res/android/mipmap-mdpi/ic_launcher.png&quot; target=&quot;app/src/main/res/mipmap-mdpi/ic_launcher.png&quot; /&gt; &lt;resource-file src=&quot;res/android/mipmap-mdpi/ic_launcher_round.png&quot; target=&quot;app/src/main/res/mipmap-mdpi/ic_launcher_round.png&quot; /&gt; &lt;resource-file src=&quot;res/android/mipmap-xhdpi/ic_launcher.png&quot; target=&quot;app/src/main/res/mipmap-xhdpi/ic_launcher.png&quot; /&gt; &lt;resource-file src=&quot;res/android/mipmap-xhdpi/ic_launcher_round.png&quot; target=&quot;app/src/main/res/mipmap-xhdpi/ic_launcher_round.png&quot; /&gt; &lt;resource-file src=&quot;res/android/mipmap-xxhdpi/ic_launcher.png&quot; target=&quot;app/src/main/res/mipmap-xxhdpi/ic_launcher.png&quot; /&gt; &lt;resource-file src=&quot;res/android/mipmap-xxhdpi/ic_launcher_round.png&quot; target=&quot;app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png&quot; /&gt; &lt;resource-file src=&quot;res/android/mipmap-xxxhdpi/ic_launcher.png&quot; target=&quot;app/src/main/res/mipmap-xxxhdpi/ic_launcher.png&quot; /&gt; &lt;resource-file src=&quot;res/android/mipmap-xxxhdpi/ic_launcher_round.png&quot; target=&quot;app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png&quot; /&gt; &lt;/platform&gt; &lt;/widget&gt; </code></pre>
9,469,590
Check permission inside a template in Django
<p>Can I use the Auth application's permission checking inside a template in Django? (I want to display a simple form at the end of the template for privileged users)</p> <p>And more importantly, should I do it at all or is this no the "Django way"?</p>
9,479,717
5
1
null
2012-02-27 17:44:07.347 UTC
13
2021-06-09 10:33:35.267 UTC
null
null
null
null
241,456
null
1
116
django|django-authentication
81,784
<p>If you are looking to check for permissions in templates, the following code would suffice:</p> <pre><code>{% if perms.app_label.can_do_something %} &lt;form here&gt; {% endif %} </code></pre> <p>Where model refers to the model that the user need permissions to see the form for.</p> <p>Refer to <a href="https://docs.djangoproject.com/en/stable/topics/auth/default/#permissions" rel="noreferrer">https://docs.djangoproject.com/en/stable/topics/auth/default/#permissions</a> for more examples.</p> <blockquote> <p>The currently logged-in user's permissions are stored in the template variable <code>{{ perms }}</code></p> </blockquote> <p>(This requires the following context processor to be enabled: <code>django.contrib.auth.context_processors.auth</code>)</p>
49,768,774
How to get access token from HttpContext in .Net core 2.0
<p>I'm trying to upgrade a project from .Net core 1.1 to .Net core 2.0 there's a lot of breaking changes.</p> <p>One of the things I'm currently having an issue with is that <code>HttpContext.Authentication</code> is now obsolete.</p> <p>I've been trying to figure out how to get the Access token for the current request. I need to make a call to another API which requires a bearer token.</p> <p><strong>Old Method .Net core 1.1</strong></p> <pre><code>[Authorize] public async Task&lt;IActionResult&gt; ClientUpdate(ClientModel client) { var accessToken = await HttpContext.Authentication.GetTokenAsync(&quot;access_token&quot;); return View(); } </code></pre> <p><strong>Method .Net core 2.0</strong></p> <p>This is not working becouse context isnt registered.</p> <pre><code>[Authorize] public async Task&lt;IActionResult&gt; ClientUpdate(ClientModel client) { var accessToken = await context.HttpContext.GetTokenAsync(&quot;access_token&quot;); return View(); } </code></pre> <blockquote> <p>Unable to resolve service for type 'Microsoft.AspNetCore.Http.HttpContext'</p> </blockquote> <p>I tried registering it but that doesnt work either</p> <pre><code>public ConsoleController(IOptions&lt;ServiceSettings&gt; serviceSettings, HttpContext context) </code></pre> <p>In startup.cs</p> <pre><code>services.TryAddSingleton&lt;HttpContext, HttpContext&gt;(); </code></pre> <p><strong>Update:</strong></p> <p>This returns null</p> <pre><code>var accessToken = await HttpContext.GetTokenAsync(&quot;access_token&quot;); </code></pre> <p><strong>Startup.cs ConfigureServices</strong></p> <p>I wouldn't be surprised if it was something in the startup as there were a lot of breaking changes here as well.</p> <pre><code>services.Configure&lt;ServiceSettings&gt;(Configuration.GetSection(&quot;ServiceSettings&quot;)); //services.TryAddSingleton&lt;HttpContext, HttpContext&gt;(); services.TryAddSingleton&lt;IHttpContextAccessor, HttpContextAccessor&gt;(); services.AddMvc(); services.AddAuthentication(options =&gt; { options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme; }) .AddCookie() .AddOpenIdConnect(options =&gt; { options.Authority = &quot;http://localhost:5000&quot;; options.ClientId = &quot;testclient&quot;; options.ClientSecret = &quot;secret&quot;; options.ResponseType = &quot;code id_token&quot;; options.RequireHttpsMetadata = false; options.GetClaimsFromUserInfoEndpoint = true; }); </code></pre> <p><strong>Startup.cs Configure</strong></p> <pre><code>loggerFactory.AddDebug(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseBrowserLink(); } else { app.UseExceptionHandler(&quot;/Home/Error&quot;); } JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); app.UseStaticFiles(); app.UseAuthentication(); app.UseMvc(routes =&gt; { routes.MapRoute( name: &quot;default&quot;, template: &quot;{controller=Home}/{action=Index}/{id?}&quot;); }); </code></pre>
49,773,344
8
9
null
2018-04-11 07:15:55.29 UTC
13
2022-06-01 10:13:17.85 UTC
2021-07-15 10:55:35.427 UTC
null
9,401,556
null
1,841,839
null
1
66
c#|http|asp.net-core|.net-core
123,697
<p>It ended up being a configuration issue. There needs to be a link between AddAuthentication and AddOpenIdConnect in order for it to read the cookie into the headers.</p> <pre><code>services.TryAddSingleton&lt;IHttpContextAccessor, HttpContextAccessor&gt;(); services.AddAuthentication(options =&gt; { options.DefaultScheme = "Cookies"; options.DefaultChallengeScheme = "oidc"; }) .AddCookie("Cookies") .AddOpenIdConnect("oidc", options =&gt; { options.SignInScheme = "Cookies"; options.Authority = "http://localhost:5000"; options.RequireHttpsMetadata = false; options.ClientId = "testclient"; options.ClientSecret = "secret"; options.ResponseType = "code id_token"; options.SaveTokens = true; options.GetClaimsFromUserInfoEndpoint = true; options.Scope.Add("testapi"); options.Scope.Add("offline_access"); }); </code></pre> <p><strong>Controller</strong></p> <pre><code> [Authorize] public async Task&lt;IActionResult&gt; Index() { var accessToken = await HttpContext.GetTokenAsync("access_token"); return View(); } </code></pre> <p>Access token is now populated. </p> <p>Note: I ended up digging it out of this project <a href="https://github.com/IdentityServer/IdentityServer4.Samples/blob/release/Quickstarts/5_HybridFlowAuthenticationWithApiAccess/src/MvcClient/Startup.cs" rel="noreferrer">Startup.cs</a></p>
49,628,726
What is the purpose of Angular animations?
<p>I've been wondering for some time now <strong>why should I use Angular animations over CSS animations</strong>. I see few areas one might consider before using them:</p> <hr /> <h2>Performance</h2> <p>In the first step I found this <a href="https://stackoverflow.com/questions/40949262/angular-2-animation-vs-css-animation-when-to-use-what">question</a> which deals only with performace side of things. The accepted answer is not satisfying for me because it states that <em>one should use CSS animations wherever possible so that optimizations like running the animations in separate thread can apply</em>. This doesn't seem to be true, because <a href="https://angular.io/guide/animations#overview" rel="noreferrer">Angular documentation</a> states</p> <blockquote> <p>Angular animations are <strong>built on top of the standard Web Animations API</strong> and run natively on browsers that support it.</p> </blockquote> <p>(emphasis mine)</p> <p>And when we look at <a href="https://drafts.csswg.org/web-animations/#introduction" rel="noreferrer">Web Animations API Draft</a> we see that the same optimizations can apply to Web Animations as to CSS specified in sheets.</p> <blockquote> <p>While it is possible to use ECMAScript to perform animation using requestAnimationFrame [HTML], such animations behave differently to declarative animation in terms of how they are represented in the CSS cascade and the performance optimizations that are possible such as performing the animation on a separate thread. <strong>Using the Web Animations</strong> programming interface, it is <strong>possible to create animations</strong> from script <strong>that have the same behavior and performance characteristics as declarative animations</strong>.</p> </blockquote> <p>(emphasis mine again)</p> <p>Apart from some browsers like IE don't support Web Animations, <strong>is there any reason to use either CSS declarations over Angular animations or vice versa?</strong> I see them as exchangeable performace-wise.</p> <hr /> <h2>More control over the animations</h2> <p>This might look as an argument for Angular animations, because you can <a href="https://stackoverflow.com/questions/48713488/pause-angular-animations">pause animation</a> or use JS variables with it etc., but the same is true while using eg. CSS <code>animation-play-state: pause</code> or using <strong>CSS variables</strong> specified in JS, see <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_variables#Values_in_JavaScript" rel="noreferrer">documentation</a>.</p> <p>Now I can see it might be inconvenient to set the CSS variables in JS code, but the same is true while using Angular animations. These are typically declared in <code>@Component</code> <code>animations</code> field and don't have, except for via the animation state data bound property, access to instance fields (if you don't create your animation via <code>AnimationBuilder</code> of course, which btw is also not very convenient or beautiful either).</p> <p>Other point is, with Web Animations API it is possible to <a href="https://drafts.csswg.org/web-animations/#use-cases" rel="noreferrer">inspect, debug or test</a> the animations, but I don't see how this is possible with Angular animations. If it is, could you please show me how? If it isn't, I really <strong>don't see any advantage of using Angular animations over CSS ones for the sake of control either</strong>.</p> <hr /> <h2>Cleaner code</h2> <p>I've read for example <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Animations_API/Using_the_Web_Animations_API#Meet_the_Web_Animations_API" rel="noreferrer">here</a> a paragraph stating that separating animations from &quot;normal&quot; styles is actually separation of behaviour and presentation. <strong>Is really declaring animations in styles sheets mixing those responsibilities?</strong> I saw that always the other way, especially looking at CSS rules in the <code>@Component</code> animations gave me a feeling of having CSS declarations on one too many places.</p> <hr /> <h3>So how is it with Angular animations?</h3> <ul> <li>Is it just a convenience utility to extract animations away from the rest of the styles, or does it bring anything worthy feature-wise?</li> <li>Does a usage of Angular animations pay off only in special cases or is it a convention a team chooses to go all the way with it?</li> </ul> <p>I would love to here about tangible advantages of using Angular animations. Thanks guys upfront!</p>
49,705,048
1
11
null
2018-04-03 11:16:43.66 UTC
36
2020-04-28 20:47:54.567 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
4,256,274
null
1
85
javascript|css|angular|animation|angular-animations
6,815
<p>So I did some research and although I didn't find any argument for nor against Angular animations performance-wise (as already stated in the question above), <strong>there are very good arguments to use Angular animations feature-wise</strong> which should be good enough for purists who want to have CSS only in sheets, at least in certain cases.</p> <p>Let me list some useful features where each alone makes a convincing case for Angular animations. Most of them can be found in <a href="https://angular.io/guide/animations#animations" rel="noreferrer">Angular animations documentation</a>:</p> <ol> <li><p><strong>Transition styles</strong> - these styles are only applied during transition from one state to another - only while an element is being animated, and one uses them like this:</p> <pre><code>transition('stateA =&gt; stateB', [style({...}), animate(100)]) </code></pre> <p>Trying to do the same with CSS only might not be as expressive in terms of which previous state led to the next. And it can be outright clunky if the animation has to differ based on the initial state but the end state is the same.</p></li> <li><p>The <strong><code>void</code></strong> state together with <strong><code>:enter</code></strong> and <strong><code>:leave</code></strong> aliases (<a href="https://angular.io/guide/transition-and-triggers#void-state" rel="noreferrer">void documentation</a>, <a href="https://angular.io/guide/transition-and-triggers#enter-and-leave-aliases" rel="noreferrer">:leave and :enter documentation</a>) - <strong>Let you animate elements being added or removed from the DOM.</strong> </p> <pre><code>transition('stateA =&gt; void', animate(...)) </code></pre> <p>This is very cool because previously, although it was easy enough to animate the addition, the removal was more complicated and required to trigger animation, wait till its end and only after that remove the element from the DOM, all with JS.</p></li> <li><p><strong>Automatic property calculation</strong> <code>'*'</code> (<a href="https://angular.io/guide/transition-and-triggers#automatic-property-calculation-with-wildcards" rel="noreferrer">documentation</a>) - Allows for performing traditionally difficult animations like <a href="https://stackoverflow.com/questions/3508605/how-can-i-transition-height-0-to-height-auto-using-css">height transitions for elements with dynamic height</a>. This problem required either to set fixed height on element (inflexible), use max-height with tuned transition function (not perfect) or query element's height with JS (potentially causing unnecessary reflows). But now with Angular it is as easy as this:</p> <pre><code>trigger('collapsible', [ state('expanded', style({ height: '*' })), state('collapsed', style({ height: '0' })), transition('expanded &lt;=&gt; collapsed', animate(100)) ]) </code></pre> <p>And the animation is smooth and "complete" because the <em>actual</em> height of the element is used for the transition.</p></li> <li><p><strong>Animation callbacks</strong> (<a href="https://angular.io/guide/transition-and-triggers#animation-callbacks" rel="noreferrer">documentation</a>) - this is something that wasn't possible with CSS animations (if not maybe emulated with <code>setTimeout</code>) and is handy eg. for debugging.</p></li> <li><p>Unlike stated in the question, <strong>it is actually possible to use instance fields as params in Angular animations</strong>, see <a href="https://stackoverflow.com/questions/41966673/parameter-in-to-animation-angular2">this question</a>. I find it much easier to use than manipulating CSS variables through DOM API as shown <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_variables#Values_in_JavaScript" rel="noreferrer">here on MDN</a>, not mentioning the limited support in some browsers.</p></li> </ol> <p>If you need any of the features listed above, Angular can be a better tool for the task. Also when there is many animations to manage in a component, and this is just my personal opinion, I find it easier to organize animations the Angular way than have them in sheets, where it is harder too see the relationships between them and various element states.</p>
19,370,417
How to load external html into a div?
<p>I've created this little code using jquery to load an external HTML file into my div, but it doesn't work, I'm running out of ideas. Any other jquery code works well. Any help appreciated:</p> <pre><code>&lt;div id="zaladuj"&gt; load external html file &lt;/div&gt; &lt;script type="text/javascript" src="jquery.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; $('#zaladuj').click(function () { $(this).load('s1.htm'); }); &lt;/script&gt; </code></pre>
19,370,444
2
2
null
2013-10-14 22:38:33.193 UTC
5
2013-10-14 22:55:17.023 UTC
null
null
null
null
2,660,811
null
1
9
jquery|html|load|external
51,607
<p>You need to wrap your code within <a href="http://api.jquery.com/ready/">jQuery.ready()</a> function since you have to wait for DOM to be fully loaded.</p> <pre><code>&lt;script type="text/javascript"&gt; $(document).ready(function(){ $('#zaladuj').click(function () { $(this).load('s1.htm'); }); }); &lt;/script&gt; </code></pre>
19,311,044
The type or namespace name 'HttpGet' could not be found when add 'System.Web.Http' namespace
<p>I have one issue in MVC .</p> <p>Currently I am working in MVC and the version is MVC4 . And I have 2 ActionResult Method, see below </p> <pre><code>[HttpGet] public ActionResult About() { ViewBag.Message = "Your app description page."; return View(); } [HttpPost] public ActionResult About(ModelName ccc) { ViewBag.Message = "Your app description page."; return View(); } </code></pre> <p>We need the <code>using System.Web.Mvc;</code> namespace for <em>[HttpPost]</em> and <em>[HttpGet]</em> attributes. So I added the <code>using System.Web.Mvc;</code> namespace in my controller . But i need to add another one Namespace <code>using System.Web.Http;</code> for <em>httpsresponseexpection</em> error handling in my controller .Si I added in the namespace . At this time <code>System.Web.Mvc;</code> is not working . </p> <blockquote> <p>I got this error: <em>The type or namespace name 'HttpGet' could not be found</em> . Why ? anything relation between System.Web.Mvc and System.Web.Http for HttpGet ?</p> </blockquote>
19,311,419
4
3
null
2013-10-11 05:45:14.567 UTC
6
2020-07-29 16:26:36.457 UTC
2013-10-11 08:24:22.643 UTC
null
727,208
null
2,218,635
null
1
23
c#|asp.net-mvc|http-post|http-get
41,394
<p>The reason you are getting this exception is because there are 2 different <code>HttpGetAttribute</code> classes in 2 different namespaces:</p> <ul> <li><a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.httpgetattribute%28v=vs.108%29.aspx"><code>System.Web.Mvc.HttpGetAttribute</code></a></li> <li><a href="http://msdn.microsoft.com/en-us/library/system.web.http.httpgetattribute%28v=vs.108%29.aspx"><code>System.Web.Http.HttpGetAttribute</code></a></li> </ul> <p>The first is used in ASP.NET MVC controllers and the second is used in ASP.NET Web API controllers.</p> <p>When you imported the second namespace the compiler is no longer able to disambiguate which of the 2 classes you are referring to because the 2 namespaces are in scope.</p> <p>Basically Microsoft duplicated all the classes that existed in ASP.NET MVC for the Web API but placed them in different namespace. Basically you shouldn't be mixing those namespaces.</p> <blockquote> <p>But i need to add another one Namespace using System.Web.Http; for httpsresponseexpection error handling in my controller</p> </blockquote> <p>Why would you need to use this in an ASP.NET MVC controller? Normally that's something you should be doing in a Web API controller.</p> <p>But if for some reason you need to mix the 2 you will have to explicitly specify which attribute you need to use by fully qualifying it:</p> <pre><code>[System.Web.Mvc.HttpGet] public ActionResult About() { ViewBag.Message = "Your app description page."; return View(); } </code></pre>
56,393,880
How do I detect dark mode using JavaScript?
<p>Windows and macOS now have dark mode.</p> <p>For CSS I can use:</p> <pre class="lang-css prettyprint-override"><code>@media (prefers-dark-interface) { color: white; background: black } </code></pre> <p>But I am using <a href="https://stripe.com/docs/stripe-js/reference#the-elements-object" rel="noreferrer">the Stripe Elements API, which puts colors in JavaScript</a></p> <p>For example:</p> <pre class="lang-js prettyprint-override"><code>const stripeElementStyles = { base: { color: COLORS.darkGrey, fontFamily: `-apple-system, BlinkMacSystemFont, &quot;Segoe UI&quot;, Roboto, &quot;Helvetica Neue&quot;, Arial, &quot;Noto Sans&quot;, sans-serif, &quot;Apple Color Emoji&quot;, &quot;Segoe UI Emoji&quot;, &quot;Segoe UI Symbol&quot;, &quot;Noto Color Emoji&quot;`, fontSize: '18px', fontSmoothing: 'antialiased', '::placeholder': { color: COLORS.midgrey }, ':-webkit-autofill': { color: COLORS.icyWhite } } } </code></pre> <p><strong>How can I detect the OS's preferred color scheme in JavaScript?</strong></p>
57,795,495
4
3
null
2019-05-31 11:02:47.487 UTC
69
2022-05-24 21:29:00.277 UTC
2021-12-15 14:14:39.857 UTC
null
107,625
null
123,671
null
1
240
javascript|macos-darkmode
93,798
<pre class="lang-js prettyprint-override"><code>if (window.matchMedia &amp;&amp; window.matchMedia('(prefers-color-scheme: dark)').matches) { // dark mode } </code></pre> <p>To watch for changes:</p> <pre class="lang-js prettyprint-override"><code>window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', event =&gt; { const newColorScheme = event.matches ? &quot;dark&quot; : &quot;light&quot;; }); </code></pre>
531,096
What are some good sample applications using Spring and Hibernate?
<p>I need a quick jump start for using Spring and Hibernate together and I was looking for some sample code to modify and extend. Bonus points for Struts2 and Spring Security integration.</p>
535,394
5
0
null
2009-02-10 04:53:57.91 UTC
11
2012-03-04 02:10:38.617 UTC
null
null
null
Peter Kelley
14,893
null
1
12
java|hibernate|spring|spring-security
13,293
<p>There is a <a href="http://struts.apache.org/2.0.14/docs/struts-2-spring-2-jpa-ajax.html" rel="nofollow noreferrer">sample project</a> that includes Spring, Hibernate and Struts2 available from the Struts2 website that appears to have most of what I want. It includes a basic JPA configuration but it does not provide DAO classes. </p> <p>The generic DAO pattern is documented on the Hibernate site <a href="http://www.hibernate.org/328.html" rel="nofollow noreferrer">here</a>. This gives a good DAO foundation but the code is using Hibernate directly with no JPA or Spring.</p> <p>The <a href="http://icoloma.blogspot.com/2006/11/jpa-and-spring-fucking-cooltm_26.html" rel="nofollow noreferrer">following post</a> (<strong>warning:</strong> language) gives some information about using Spring with JPA and not the HibernateTemplate class.</p> <p>Put together this information has me well on the way to my skeleton project. </p>
281,579
Ruby - Passing Blocks To Methods
<p>I'm trying to do Ruby password input with the <a href="http://highline.rubyforge.org/" rel="noreferrer">Highline gem</a> and since I have the user input the password twice, I'd like to eliminate the duplication on the blocks I'm passing in. For example, a simple version of what I'm doing right now is:</p> <pre><code>new_pass = ask("Enter your new password: ") { |prompt| prompt.echo = false } verify_pass = ask("Enter again to verify: ") { |prompt| prompt.echo = false } </code></pre> <p>And what I'd like to change it to is something like this:</p> <pre><code>foo = Proc.new { |prompt| prompt.echo = false } new_pass = ask("Enter your new password: ") foo verify_pass = ask("Enter again to verify: ") foo </code></pre> <p>Which unfortunately doesn't work. What's the correct way to do this?</p>
281,681
5
0
null
2008-11-11 17:31:55.34 UTC
13
2016-10-11 14:47:46.28 UTC
2015-04-15 21:36:50.743 UTC
null
1,571,407
Chris Bunch
422
null
1
43
ruby|highline
45,341
<p>The code by David will work fine, but this is an easier and shorter solution:</p> <pre><code>foo = Proc.new { |prompt| prompt.echo = false } new_pass = ask("Enter your new password: ", &amp;foo) verify_pass = ask("Enter again to verify: ", &amp;foo) </code></pre> <p>You can also use an ampersand to assign a block to a variable when defining a method:</p> <pre><code>def ask(msg, &amp;block) puts block.inspect end </code></pre>
110,804
Integrating gyro and accelerometer readings
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/1586658/combine-gyroscope-and-accelerometer-data">Combine Gyroscope and Accelerometer Data</a> </p> </blockquote> <p>I have read a number of papers on <code>Kalman filters</code>, but there seem to be few good publically accessible worked examples of getting from mathematical paper to actual working code.</p> <p>I have a system containing a three-axis accelerometer and a single gyro measuring rotation around one of the accelerometer axes. The system is designed to be held by a human, and much of the time the gyro will be measuring rotation about the gravity vector or close to it. (People working in the same industry will likely recognise what I am talking about from that ;)) I realise this is underconstrained.</p> <p>The gyros appear to have a near-constant bias that is slightly different for each instance of the system. How would I go about coding a filter to use the accelerometer readings to calibrate the gyro at times when the system is tilted so the gyro axis is not collinear with gravity, and is being rotated about the gyro axis? It seems like there should be enough information to do that, but being told that there isn't and why would be an answer too :)</p>
984,366
6
4
null
2008-09-21 11:27:44.967 UTC
18
2015-01-11 20:50:55.543 UTC
2017-05-23 11:57:58.907 UTC
moonshadow
-1
moonshadow
11,834
null
1
14
signal-processing|robotics|gyroscope|kalman-filter
17,714
<p><a href="http://www.geology.smu.edu/~dpa-www/robo/nbot/" rel="nofollow noreferrer">nBot, a two wheel balancing robot</a><br> Quite a bit of info and links about how this author chose to solve the balance problem for his two wheeled robot. </p>
546,819
strange warning about ExtensionAttribute
<p>I'm getting a strange warning:</p> <blockquote> <p>The predefined type 'System.Runtime.CompilerServices.ExtensionAttribute' is defined in multiple assemblies in the global alias; using definition from 'c:\Program Files\Reference Assemblies\Microsoft\Framework\v3.5\System.Core.dll'</p> </blockquote> <p>There is no line number given, so it's hard to figure out what it's on about.</p> <p>The compiler error code is <a href="http://msdn.microsoft.com/en-us/library/8xys0hxk.aspx" rel="noreferrer">CS1685</a></p>
546,826
6
2
null
2009-02-13 17:17:44.093 UTC
4
2015-06-02 14:13:45.693 UTC
2013-05-24 23:06:35.887 UTC
ShuggyCoUk
41,956
JoelFan
16,012
null
1
33
c#|compiler-warnings
21,283
<p>Are you using someone's dll (or your own) which had implemented this attribute (with exactly the same name) itself as a means of using some c# 3.0 features on pre .Net 3.5 runtimes? (A common trick)</p> <p>This is the probable cause. Since it is using the correct one (the MS one in the GAC) this is not a problem though you should hunt down the other and remove it.</p>
1,059,480
Math opposite sign function?
<p>Does such function exist? I created my own but would like to use an official one:</p> <pre><code>private function opposite(number:Number):Number { if (number &lt; 0) { number = Math.abs(number); } else { number = -(number); } return number; } </code></pre> <p>So, -5 becomes 5 and 3 becomes -3.</p> <p>Edit: Forgive me for being stupid. I'm human. :)</p>
1,059,485
6
3
null
2009-06-29 17:30:01.913 UTC
8
2011-11-27 23:54:41.613 UTC
2011-11-27 23:54:41.613 UTC
null
912,144
null
45,974
null
1
40
math|function
31,322
<p>yes it does...</p> <pre><code>return num*-1; </code></pre> <p>or simply</p> <pre><code>return -num; </code></pre>
507,247
Recommend a C# Task Scheduling Library
<p>I'm looking for a C# library, preferably open source, that will let me schedule tasks with a fair amount of flexibility. Specifically, I should be able to schedule things to run every N units of time as well as "Every weekday at XXXX time" or "Every Monday at XXXX time". More features than that would be nice, but not necessary. This is something I want to use in an Azure WorkerRole, which immediately rules out Windows Scheduled Tasks, "at", "Cron", and any third party app that requires installation and/or a GUI to operate. I'm looking for a library. </p>
507,261
6
1
null
2009-02-03 14:20:00.623 UTC
23
2015-02-28 08:58:56.867 UTC
2010-03-06 04:40:04.993 UTC
null
164,901
ssmith
13,729
null
1
53
c#|azure|scheduled-tasks
44,276
<p><a href="http://quartznet.sourceforge.net" rel="noreferrer">http://quartznet.sourceforge.net/</a></p> <p>"Quartz.NET is a port of very propular(sic!) open source Java job scheduling framework, Quartz."</p> <p>PS: Word to the wise, don't try to just navigate to quartz.net when at work ;-)</p>
250,517
Java SE 6 vs. JRE 1.6 vs. JDK 1.6 - What do these mean?
<p>I see many different Java terms floating around. I need to install the JDK 1.6. It was my understanding that Java 6 == Java 1.6. However, when I install Java SE 6, I get a JVM that reports as version 11.0! Who can solve the madness?</p>
250,559
6
1
null
2008-10-30 15:10:09.907 UTC
55
2022-06-27 10:51:13.133 UTC
2011-10-24 15:02:44.14 UTC
null
40,342
Joe Schneider
1,541
null
1
200
java
294,310
<p>When you type "java -version", you see three version numbers - the java version (on mine, that's "<code>1.6.0_07</code>"), the Java SE Runtime Environment version ("build <code>1.6.0_07-b06</code>"), and the HotSpot version (on mine, that's "<code>build 10.0-b23, mixed mode"</code>). I suspect the "11.0" you are seeing is the HotSpot version.</p> <p>Update: HotSpot is (or used to be, now they seem to use it to mean the whole VM) the just-in-time compiler that is built in to the Java Virtual Machine. God only knows why Sun gives it a separate version number.</p>
32,357,774
Scala: How can I replace value in Dataframes using scala
<p>For example I want to replace all numbers equal to 0.2 in a column to 0. How can I do that in Scala? Thanks</p> <p><strong>Edit</strong>:</p> <pre><code>|year| make|model| comment |blank| |2012|Tesla| S | No comment | | |1997| Ford| E350|Go get one now th...| | |2015|Chevy| Volt| null | null| </code></pre> <p>This is my Dataframe I'm trying to change Tesla in make column to S</p>
32,360,998
6
12
null
2015-09-02 15:55:39.23 UTC
11
2022-02-02 10:21:31.37 UTC
2017-08-25 13:27:59.457 UTC
null
7,041,871
null
5,293,341
null
1
38
scala|apache-spark|dataframe
106,858
<p>Note: <strong>As mentionned by Olivier Girardot, this answer is not optimized and the <code>withColumn</code> solution is the one to use (Azeroth2b answer)</strong></p> <p>Can not delete this answer as it has been accepted</p> <hr> <p>Here is my take on this one:</p> <pre><code> val rdd = sc.parallelize( List( (2012,"Tesla","S"), (1997,"Ford","E350"), (2015,"Chevy","Volt")) ) val sqlContext = new SQLContext(sc) // this is used to implicitly convert an RDD to a DataFrame. import sqlContext.implicits._ val dataframe = rdd.toDF() dataframe.foreach(println) dataframe.map(row =&gt; { val row1 = row.getAs[String](1) val make = if (row1.toLowerCase == "tesla") "S" else row1 Row(row(0),make,row(2)) }).collect().foreach(println) //[2012,S,S] //[1997,Ford,E350] //[2015,Chevy,Volt] </code></pre> <p>You can actually use directly <code>map</code> on the <code>DataFrame</code>. </p> <p>So you basically check the column 1 for the String <code>tesla</code>. If it's <code>tesla</code>, use the value <code>S</code> for <code>make</code> else you the current value of column 1</p> <p>Then build a tuple with all data from the row using the indexes (zero based) (<code>Row(row(0),make,row(2))</code>) in my example)</p> <p>There is probably a better way to do it. I am not that familiar yet with the Spark umbrella</p>
35,709,595
Why would you use a string in JSON to represent a decimal number
<p>Some APIs, like the <a href="https://developer.paypal.com/docs/api/payments/v2/#definition-money" rel="noreferrer">paypal API</a> use a string type in JSON to represent a decimal number. So <code>"7.47"</code> instead of <code>7.47</code>. </p> <p>Why/when would this be a good idea over using the json number value type? AFAIK the number value type allows for infinite precision as well as scientific notation.</p>
38,357,877
4
4
null
2016-02-29 21:03:07.923 UTC
32
2020-06-30 08:08:07.34 UTC
2019-07-31 17:17:46.21 UTC
null
2,133,111
null
2,133,111
null
1
103
json|serialization|paypal
99,226
<p>The main reason to transfer numeric values in JSON as strings is to eliminate any loss of precision or ambiguity in transfer. </p> <p>It's true that the JSON spec does not specify a precision for numeric values. This does not mean that JSON numbers have infinite precision. It means that numeric precision is not specified, which means JSON implementations are free to choose whatever numeric precision is convenient to their implementation or goals. It is this variability that can be a pain if your application has specific precision requirements.</p> <p>Loss of precision generally isn't apparent in the JSON encoding of the numeric value (1.7 is nice and succinct) but manifests in the JSON parsing and intermediate representations on the receiving end. A JSON parsing function would quite reasonably parse 1.7 into an IEEE double precision floating point number. However, finite length / finite precision decimal representations will always run into numbers whose decimal expansions cannot be represented as a finite sequence of digits:</p> <ol> <li><p>Irrational numbers (like pi and e)</p></li> <li><p>1.7 has a finite representation in base 10 notation, but in binary (base 2) notation, 1.7 cannot be encoded exactly. Even with a near infinite number of binary digits, you'll only get closer to 1.7, but you'll never get to 1.7 exactly.</p></li> </ol> <p>So, parsing 1.7 into an in-memory floating point number, then printing out the number will likely return something like 1.69 - not 1.7.</p> <p>Consumers of the JSON 1.7 value could use more sophisticated techniques to parse and retain the value in memory, such as using a fixed-point data type or a "string int" data type with arbitrary precision, but this will not entirely eliminate the specter of loss of precision in conversion for some numbers. And the reality is, very few JSON parsers bother with such extreme measures, as the benefits for most situations are low and the memory and CPU costs are high.</p> <p>So if you are wanting to send a precise numeric value to a consumer and you don't want automatic conversion of the value into the typical internal numeric representation, your best bet is to ship the numeric value out as a string and tell the consumer exactly how that string should be processed if and when numeric operations need to be performed on it. </p> <p>For example: In some JSON producers (JRuby, for one), BigInteger values automatically output to JSON as strings, largely because the range and precision of BigInteger is so much larger than the IEEE double precision float. Reducing the BigInteger value to double in order to output as a JSON numeric will often lose significant digits. </p> <p>Also, the JSON spec (<a href="http://www.json.org/" rel="noreferrer">http://www.json.org/</a>) explicitly states that NaNs and Infinities (INFs) are invalid for JSON numeric values. If you need to express these fringe elements, you cannot use JSON number. You have to use a string or object structure.</p> <p>Finally, there is another aspect which can lead to choosing to send numeric data as strings: control of display formatting. Leading zeros and trailing zeros are insignificant to the numeric value. If you send JSON number value 2.10 or 004, after conversion to internal numeric form they will be displayed as 2.1 and 4. </p> <p>If you are sending data that will be directly displayed to the user, you probably want your money figures to line up nicely on the screen, decimal aligned. One way to do that is to make the client responsible for formatting the data for display. Another way to do it is to have the server format the data for display. Simpler for the client to display stuff on screen perhaps, but this can make extracting the numeric value from the string difficult if the client also needs to make computations on the values.</p>
17,819,524
curl through proxy syntax
<p>I don't understand how to read this general syntax. I want to request a URL through our proxy and it requires a specific host, port, username, and password. I don't know how to figure out what the protocol is. I want to do curl through a proxy. Based on the helpfile below, I would guess the line should be:</p> <p>curl -x [whatever-my-protocol-is://]my-host-which-i-know[:my-port-which-i-know] -U my-username-which-i-know[:my-pass-which-i-know] <a href="http://www.google.com" rel="nofollow noreferrer">http://www.google.com</a></p> <p>Is this right? How do I figure out the protocol?</p> <p>Relevant info from man: </p> <pre><code>-x, --proxy [PROTOCOL://]HOST[:PORT] Use proxy on given port --proxy-anyauth Pick "any" proxy authentication method (H) --proxy-basic Use Basic authentication on the proxy (H) --proxy-digest Use Digest authentication on the proxy (H) --proxy-negotiate Use Negotiate authentication on the proxy (H) --proxy-ntlm Use NTLM authentication on the proxy (H) -U, --proxy-user USER[:PASSWORD] Proxy user and password --proxy1.0 HOST[:PORT] Use HTTP/1.0 proxy on given port </code></pre>
17,819,662
2
0
null
2013-07-23 19:37:59.033 UTC
2
2020-02-18 13:51:06.48 UTC
2020-02-18 13:51:06.48 UTC
null
1,839,439
null
1,236,326
null
1
5
curl|proxy
39,385
<p>Ignore <code>"["</code> when reading general syntax. Also, windows likes double vs single quotes. </p> <p>So the command is: </p> <pre><code>curl -x my-host-which-i-know:my-port-which-i-know -U my-username-which-i-know:my-pass-which-i-know http://www.google.com </code></pre>
18,077,072
How to convert MultipartFile into byte stream
<p>//Or any other solution to saving multipartfile into DB. I tried with this way but getting error.</p> <pre><code>File fileOne = new File("file.getOrignalFileName");//what should be kept inside this method byte[] bFile = new byte[(int) fileOne.length()]; try { FileInputStream fileInputStream = new FileInputStream(fileOne); //convert file into array of bytes fileInputStream.read(bFile); fileInputStream.close(); } catch (Exception e) { e.printStackTrace(); } questionDao.saveImage(bFile); </code></pre>
18,077,223
2
3
null
2013-08-06 10:03:26.117 UTC
8
2019-05-01 15:16:10.18 UTC
2019-05-01 15:16:10.18 UTC
null
5,919,568
null
2,583,506
null
1
22
java|spring|hibernate
51,958
<pre><code>MultipartFile file; byte [] byteArr=file.getBytes(); InputStream inputStream = new ByteArrayInputStream(byteArr); </code></pre>
63,117,797
Azure Pipelines - Is there a way to view the folder structure?
<p>I'm struggling to picture the folder structure of azure pipelines. I know there are some implicit directories like:</p> <ul> <li>$(System.DefaultWorkingDirectory)</li> <li>$(Build.ArtifactStagingDirectory)</li> </ul> <p>Which are both folders on a specific build agent available from the pool.</p> <p>Is there a way to view the folder structure and get a better understanding how things are laid out?</p>
63,129,192
5
2
null
2020-07-27 14:46:24.733 UTC
5
2022-05-20 15:44:43.267 UTC
null
null
null
null
1,274,440
null
1
35
azure-devops|azure-pipelines
32,291
<p>You can use <a href="https://docs.microsoft.com/en-us/azure/devops/pipelines/tasks/utility/command-line?view=azure-devops&amp;tabs=yaml" rel="noreferrer">CMD task</a> to call <a href="https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/tree" rel="noreferrer">tree command</a> in Microsoft-Hosted windows agent to get the folder structure.</p> <p><strong>My script:</strong></p> <pre><code>echo &quot;Structure of work folder of this pipeline:&quot; tree $(Agent.WorkFolder)\1 /f echo &quot;Build.ArtifactStagingDirectory:&quot; echo &quot;$(Build.ArtifactStagingDirectory)&quot; echo &quot;Build.BinariesDirectory:&quot; echo &quot;$(Build.BinariesDirectory)&quot; echo &quot;Build.SourcesDirectory:&quot; echo &quot;$(Build.SourcesDirectory)&quot; </code></pre> <p><strong>The result:</strong></p> <p><a href="https://i.stack.imgur.com/0vem3.png" rel="noreferrer"><img src="https://i.stack.imgur.com/0vem3.png" alt="enter image description here" /></a></p> <p><code>$(Agent.WorkFolder)</code> represents the working folder for current agent, <code>$(Agent.WorkFolder)\1</code> represents the working folder for current pipeline.(Normally the first pipeline will be put in <code>$(Agent.WorkFolder)\1</code>, and the second <code>$(Agent.WorkFolder)\2</code>...)</p> <p>So it's obvious that for one pipeline run, it has four folders by default: a(artifact folder), b(binaries folder), s(source folder) and TestResults(Test results folder). The <code>s</code> folder is where the source code files are downloaded. For build pipeline: <code>$(Build.SourcesDirectory)</code>,<code>$(Build.Repository.LocalPath)</code> and <code>$(System.DefaultWorkingDirectory)</code> represent the same folder. More details see <a href="https://docs.microsoft.com/en-us/azure/devops/pipelines/build/variables?view=azure-devops&amp;tabs=yaml" rel="noreferrer">predefined variables</a>.</p>
54,305,880
How can I restrict client access to only one group of users in keycloak?
<p>I have a client in <code>keycloak</code> for my awx(ansible tower) webpage.</p> <p>I need only the users from one specific <code>keycloak</code> group to be able to log in through this client.</p> <p>How can I forbid all other users(except from one particular group) from using this <code>keycloak</code> client?</p>
54,384,513
10
4
null
2019-01-22 10:11:46.18 UTC
17
2021-07-01 10:53:55.793 UTC
2020-12-28 01:43:06.72 UTC
null
1,783,163
null
6,516,538
null
1
35
single-sign-on|saml|keycloak|idp
40,426
<p>I solved it like this:</p> <ol> <li>Create a new role in Keycloak.</li> <li>Assign this role to the group.</li> <li>Create a new authentication script in Kycloak. Configure which role is allowed upon login (e.g. <code>user.hasRole(realm.getRole("yourRoleName"))</code>).</li> <li>In the client's settings, under "Authentication Flow Overrides", choose the authentication script that was just created.</li> </ol>
21,374,534
CSS Background image not loading
<p>I have followed all of the tutorials, which all say the say thing. I specify my background inside of body in my css style sheet, but the page just displays a blank white background. Image is in the same directory as the .html and the .css pages. The tutorial says that</p> <pre><code>&lt;body background="image.jpeg"&gt; </code></pre> <p>is deprecated, so I use, in css,</p> <pre><code>body {background: url('image.jpeg');} </code></pre> <p>no success. Here is the entire css style sheet:</p> <pre><code>body { background-image: url('nickcage.jpg'); padding-left: 11em; padding-right: 20em; font-family: Georgia, "Times New Roman", Times, serif; color: red; } </code></pre>
21,374,602
18
10
null
2014-01-27 06:44:30.02 UTC
14
2021-10-29 13:16:56.27 UTC
2014-01-27 07:09:45.827 UTC
null
3,106,062
null
2,374,233
null
1
40
html|css|image|background
335,000
<p>here is another image url result..working fine...i'm just put only a image path..please check it..</p> <p>Fiddel:<a href="http://jsfiddle.net/287Kw/" rel="noreferrer">http://jsfiddle.net/287Kw/</a></p> <pre><code>body { background-image: url('http://www.birds.com/wp-content/uploads/home/bird4.jpg'); padding-left: 11em; padding-right: 20em; font-family: Georgia, "Times New Roman", Times, serif; color: red; } </code></pre>
47,025,373
Fastest Implementation of the Natural Exponential Function Using SSE
<p>I'm looking for an approximation of the natural exponential function operating on SSE element. Namely - <code>__m128 exp( __m128 x )</code>. </p> <p>I have an implementation which is quick but seems to be very low in accuracy:</p> <pre><code>static inline __m128 FastExpSse(__m128 x) { __m128 a = _mm_set1_ps(12102203.2f); // (1 &lt;&lt; 23) / ln(2) __m128i b = _mm_set1_epi32(127 * (1 &lt;&lt; 23) - 486411); __m128 m87 = _mm_set1_ps(-87); // fast exponential function, x should be in [-87, 87] __m128 mask = _mm_cmpge_ps(x, m87); __m128i tmp = _mm_add_epi32(_mm_cvtps_epi32(_mm_mul_ps(a, x)), b); return _mm_and_ps(_mm_castsi128_ps(tmp), mask); } </code></pre> <p>Could anybody have an implementation with better accuracy yet as fast (Or faster)?</p> <p>I'd be happy if it is written in C Style.</p> <p>Thank You.</p>
47,025,627
6
7
null
2017-10-30 22:48:41.727 UTC
11
2022-05-02 15:05:56.067 UTC
2020-05-01 08:21:24.423 UTC
null
480,894
null
195,787
null
1
16
c|optimization|vectorization|sse|simd
13,961
<p>The C code below is a translation into SSE intrinsics of an algorithm I used in a <a href="https://stackoverflow.com/a/10792321/780717">previous answer</a> to a similar question.</p> <p>The basic idea is to transform the computation of the standard exponential function into computation of a power of 2: <code>expf (x) = exp2f (x / logf (2.0f)) = exp2f (x * 1.44269504)</code>. We split <code>t = x * 1.44269504</code> into an integer <code>i</code> and a fraction <code>f</code>, such that <code>t = i + f</code> and <code>0 &lt;= f &lt;= 1</code>. We can now compute 2<sup>f</sup> with a polynomial approximation, then scale the result by 2<sup>i</sup> by adding <code>i</code> to the exponent field of the single-precision floating-point result.</p> <p>One problem that exists with an SSE implementation is that we want to compute <code>i = floorf (t)</code>, but there is no fast way to compute the <code>floor()</code> function. However, we observe that for positive numbers, <code>floor(x) == trunc(x)</code>, and that for negative numbers, <code>floor(x) == trunc(x) - 1</code>, except when <code>x</code> is a negative integer. However, since the core approximation can handle an <code>f</code> value of <code>1.0f</code>, using the approximation for negative arguments is harmless. SSE provides an instruction to convert single-precision floating point operands to integers with truncation, so this solution is efficient.</p> <p><a href="https://stackoverflow.com/users/224132/peter-cordes">Peter Cordes</a> points out that SSE4.1 supports a fast floor function <code>_mm_floor_ps()</code>, so a variant using SSE4.1 is also shown below. Not all toolchains automatically predefine the macro <code>__SSE4_1__</code> when SSE 4.1 code generation is enabled, but gcc does. </p> <p>Compiler Explorer (Godbolt) shows that gcc 7.2 compiles the code below into <a href="https://godbolt.org/g/V8KvUB" rel="noreferrer">sixteen instructions</a> for plain SSE and <a href="https://godbolt.org/g/Ej6YzD" rel="noreferrer">twelve instructions</a> for SSE 4.1.</p> <pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;math.h&gt; #include &lt;emmintrin.h&gt; #ifdef __SSE4_1__ #include &lt;smmintrin.h&gt; #endif /* max. rel. error = 1.72863156e-3 on [-87.33654, 88.72283] */ __m128 fast_exp_sse (__m128 x) { __m128 t, f, e, p, r; __m128i i, j; __m128 l2e = _mm_set1_ps (1.442695041f); /* log2(e) */ __m128 c0 = _mm_set1_ps (0.3371894346f); __m128 c1 = _mm_set1_ps (0.657636276f); __m128 c2 = _mm_set1_ps (1.00172476f); /* exp(x) = 2^i * 2^f; i = floor (log2(e) * x), 0 &lt;= f &lt;= 1 */ t = _mm_mul_ps (x, l2e); /* t = log2(e) * x */ #ifdef __SSE4_1__ e = _mm_floor_ps (t); /* floor(t) */ i = _mm_cvtps_epi32 (e); /* (int)floor(t) */ #else /* __SSE4_1__*/ i = _mm_cvttps_epi32 (t); /* i = (int)t */ j = _mm_srli_epi32 (_mm_castps_si128 (x), 31); /* signbit(t) */ i = _mm_sub_epi32 (i, j); /* (int)t - signbit(t) */ e = _mm_cvtepi32_ps (i); /* floor(t) ~= (int)t - signbit(t) */ #endif /* __SSE4_1__*/ f = _mm_sub_ps (t, e); /* f = t - floor(t) */ p = c0; /* c0 */ p = _mm_mul_ps (p, f); /* c0 * f */ p = _mm_add_ps (p, c1); /* c0 * f + c1 */ p = _mm_mul_ps (p, f); /* (c0 * f + c1) * f */ p = _mm_add_ps (p, c2); /* p = (c0 * f + c1) * f + c2 ~= 2^f */ j = _mm_slli_epi32 (i, 23); /* i &lt;&lt; 23 */ r = _mm_castsi128_ps (_mm_add_epi32 (j, _mm_castps_si128 (p))); /* r = p * 2^i*/ return r; } int main (void) { union { float f[4]; unsigned int i[4]; } arg, res; double relerr, maxrelerr = 0.0; int i, j; __m128 x, y; float start[2] = {-0.0f, 0.0f}; float finish[2] = {-87.33654f, 88.72283f}; for (i = 0; i &lt; 2; i++) { arg.f[0] = start[i]; arg.i[1] = arg.i[0] + 1; arg.i[2] = arg.i[0] + 2; arg.i[3] = arg.i[0] + 3; do { memcpy (&amp;x, &amp;arg, sizeof(x)); y = fast_exp_sse (x); memcpy (&amp;res, &amp;y, sizeof(y)); for (j = 0; j &lt; 4; j++) { double ref = exp ((double)arg.f[j]); relerr = fabs ((res.f[j] - ref) / ref); if (relerr &gt; maxrelerr) { printf ("arg=% 15.8e res=%15.8e ref=%15.8e err=%15.8e\n", arg.f[j], res.f[j], ref, relerr); maxrelerr = relerr; } } arg.i[0] += 4; arg.i[1] += 4; arg.i[2] += 4; arg.i[3] += 4; } while (fabsf (arg.f[3]) &lt; fabsf (finish[i])); } printf ("maximum relative errror = %15.8e\n", maxrelerr); return EXIT_SUCCESS; } </code></pre> <p>An alternative design for <code>fast_sse_exp()</code> extracts the integer portion of the adjusted argument <code>x / log(2)</code> in round-to-nearest mode, using the well-known technique of adding the "magic" conversion constant 1.5 * 2<sup>23</sup> to force rounding in the correct bit position, then subtracting out the same number again. This requires that the SSE rounding mode in effect during the addition is "round to nearest or even", which is the default. <a href="https://stackoverflow.com/users/2439725/wim">wim</a> pointed out in comments that some compilers may optimize out the addition and subtraction of the conversion constant <code>cvt</code> as redundant when aggressive optimization is used, interfering with the functionality of this code sequence, so it is recommended to inspect the machine code generated. The approximation interval for computation of 2<sup>f</sup> is now centered around zero, since <code>-0.5 &lt;= f &lt;= 0.5</code>, requiring a different core approximation.</p> <pre class="lang-c prettyprint-override"><code>/* max. rel. error &lt;= 1.72860465e-3 on [-87.33654, 88.72283] */ __m128 fast_exp_sse (__m128 x) { __m128 t, f, p, r; __m128i i, j; const __m128 l2e = _mm_set1_ps (1.442695041f); /* log2(e) */ const __m128 cvt = _mm_set1_ps (12582912.0f); /* 1.5 * (1 &lt;&lt; 23) */ const __m128 c0 = _mm_set1_ps (0.238428936f); const __m128 c1 = _mm_set1_ps (0.703448006f); const __m128 c2 = _mm_set1_ps (1.000443142f); /* exp(x) = 2^i * 2^f; i = rint (log2(e) * x), -0.5 &lt;= f &lt;= 0.5 */ t = _mm_mul_ps (x, l2e); /* t = log2(e) * x */ r = _mm_sub_ps (_mm_add_ps (t, cvt), cvt); /* r = rint (t) */ f = _mm_sub_ps (t, r); /* f = t - rint (t) */ i = _mm_cvtps_epi32 (t); /* i = (int)t */ p = c0; /* c0 */ p = _mm_mul_ps (p, f); /* c0 * f */ p = _mm_add_ps (p, c1); /* c0 * f + c1 */ p = _mm_mul_ps (p, f); /* (c0 * f + c1) * f */ p = _mm_add_ps (p, c2); /* p = (c0 * f + c1) * f + c2 ~= exp2(f) */ j = _mm_slli_epi32 (i, 23); /* i &lt;&lt; 23 */ r = _mm_castsi128_ps (_mm_add_epi32 (j, _mm_castps_si128 (p))); /* r = p * 2^i*/ return r; } </code></pre> <p>The algorithm for the code in the question appears to be taken from the work of Nicol N. Schraudolph, which cleverly exploits the semi-logarithmic nature of IEEE-754 binary floating-point formats:</p> <p><a href="https://nic.schraudolph.org/bib2html/b2hd-Schraudolph99.html" rel="noreferrer">N. N. Schraudolph. "A fast, compact approximation of the exponential function."</a> <em>Neural Computation</em>, 11(4), May 1999, pp.853-862.</p> <p>After removal of the argument clamping code, it reduces to just three SSE instructions. The "magical" correction constant <code>486411</code> is not optimal for minimizing maximum relative error over the entire input domain. Based on simple binary search, the value <code>298765</code> seems to be superior, reducing maximum relative error for <code>FastExpSse()</code> to 3.56e-2 vs. maximum relative error of 1.73e-3 for <code>fast_exp_sse()</code>.</p> <pre class="lang-c prettyprint-override"><code>/* max. rel. error = 3.55959567e-2 on [-87.33654, 88.72283] */ __m128 FastExpSse (__m128 x) { __m128 a = _mm_set1_ps (12102203.0f); /* (1 &lt;&lt; 23) / log(2) */ __m128i b = _mm_set1_epi32 (127 * (1 &lt;&lt; 23) - 298765); __m128i t = _mm_add_epi32 (_mm_cvtps_epi32 (_mm_mul_ps (a, x)), b); return _mm_castsi128_ps (t); } </code></pre> <p>Schraudolph's algorithm basically uses the linear approximation 2<sup>f</sup> ~= <code>1.0 + f</code> for <code>f</code> in [0,1], and its accuracy could be improved by adding a quadratic term. The clever part of Schraudolph's approach is computing 2<sup>i</sup> * 2<sup>f</sup> without explicitly separating the integer portion <code>i = floor(x * 1.44269504)</code> from the fraction. I see no way to extend that trick to a quadratic approximation, but one can certainly combine the <code>floor()</code> computation from Schraudolph with the quadratic approximation used above:</p> <pre><code>/* max. rel. error &lt;= 1.72886892e-3 on [-87.33654, 88.72283] */ __m128 fast_exp_sse (__m128 x) { __m128 f, p, r; __m128i t, j; const __m128 a = _mm_set1_ps (12102203.0f); /* (1 &lt;&lt; 23) / log(2) */ const __m128i m = _mm_set1_epi32 (0xff800000); /* mask for integer bits */ const __m128 ttm23 = _mm_set1_ps (1.1920929e-7f); /* exp2(-23) */ const __m128 c0 = _mm_set1_ps (0.3371894346f); const __m128 c1 = _mm_set1_ps (0.657636276f); const __m128 c2 = _mm_set1_ps (1.00172476f); t = _mm_cvtps_epi32 (_mm_mul_ps (a, x)); j = _mm_and_si128 (t, m); /* j = (int)(floor (x/log(2))) &lt;&lt; 23 */ t = _mm_sub_epi32 (t, j); f = _mm_mul_ps (ttm23, _mm_cvtepi32_ps (t)); /* f = (x/log(2)) - floor (x/log(2)) */ p = c0; /* c0 */ p = _mm_mul_ps (p, f); /* c0 * f */ p = _mm_add_ps (p, c1); /* c0 * f + c1 */ p = _mm_mul_ps (p, f); /* (c0 * f + c1) * f */ p = _mm_add_ps (p, c2); /* p = (c0 * f + c1) * f + c2 ~= 2^f */ r = _mm_castsi128_ps (_mm_add_epi32 (j, _mm_castps_si128 (p))); /* r = p * 2^i*/ return r; } </code></pre>
1,434,443
Exporting a CLOB to a text file using Oracle SQL Developer
<p>I am using Oracle SQL Developer and trying to export a table to a CSV file. Some of the fields are CLOB fields, and in many cases the entries are truncated when the export happens. I'm looking for a way to get the whole thing out, as my end goal is to not use Oracle here (I received an Oracle dump - which was loaded into an oracle db, but am using the data in another format so going via CSV as an intermediary).</p> <p>If there are multiple solutions to this, given that it is a one time procedure for me, I don't mind the more hack-ish type solutions to more involved "do it right" solutions.</p>
1,434,527
5
0
null
2009-09-16 17:37:44.137 UTC
6
2019-03-06 12:02:01.703 UTC
2015-07-26 04:14:55.22 UTC
null
395,857
null
144,642
null
1
13
sql|oracle|clob|oracle-sqldeveloper
64,981
<p>if you have access to the file system on your database box you could do something like this:</p> <pre><code>CREATE OR REPLACE DIRECTORY documents AS 'C:\'; SET SERVEROUTPUT ON DECLARE l_file UTL_FILE.FILE_TYPE; l_clob CLOB; l_buffer VARCHAR2(32767); l_amount BINARY_INTEGER := 32767; l_pos INTEGER := 1; BEGIN SELECT col1 INTO l_clob FROM tab1 WHERE rownum = 1; l_file := UTL_FILE.fopen('DOCUMENTS', 'Sample2.txt', 'w', 32767); LOOP DBMS_LOB.read (l_clob, l_amount, l_pos, l_buffer); UTL_FILE.put(l_file, l_buffer); l_pos := l_pos + l_amount; END LOOP; EXCEPTION WHEN OTHERS THEN DBMS_OUTPUT.put_line(SQLERRM); UTL_FILE.fclose(l_file); END; / </code></pre> <p>Which I copied and pasted <a href="http://www.oracle-base.com/articles/8i/ExportClob.php" rel="nofollow noreferrer">from this site</a>.</p> <p>You may also find this <a href="https://stackoverflow.com/questions/857744/oracle-how-to-export-query-to-a-text-csv-file">previous question about UTL_FILE</a> useful. It addresses exporting to CSV. I have no idea or experience with how UTL_FILE handles CLOBs, however.</p>
1,813,239
What's wrong with type classes?
<p><a href="http://en.wikipedia.org/wiki/Type_class" rel="noreferrer">Type classes</a> seem to be a great possibility to write generic and reusable functions in a very consistent, efficient and extensible way. But still <em>no</em> "mainstream-language" provides them - On the contrary: <a href="http://en.wikipedia.org/wiki/Concepts_(C%2B%2B0x)" rel="noreferrer">Concepts</a>, which are a quite analogical idea, have been <em>excluded</em> from the next C++!</p> <p>What's the reasoning against typeclasses? Apparently many languages are looking for a way to deal with similar problems: .NET introduced generic constraints and interfaces like <code>IComparable</code> which allow functions like</p> <pre><code>T Max&lt;T&gt;(T a, T b) where T : IComparable&lt;T&gt; { // } </code></pre> <p>to operate on all types that implement the interface.</p> <p>Scala instead uses a combination of <em>traits</em> and so called <a href="http://www.scala-lang.org/node/114" rel="noreferrer"><em>implicit parameters</em></a>/<em>view bounds</em>, which are automatically passed to generic functions.</p> <p>But both concepts shown here have great disadvantages - Interfaces are inheritance-based and thus relatively slow due to indirection and moreover there is no possibility of letting an existing type implement them.</p> <p>If we needed an abstraction for a Monoid, we could pretty well write an interface and let our types implement this, but builtin types like <code>int</code> could never operate on your functions natively.</p> <p>Implicit parameters instead are inconsistent with regular interfaces/traits.</p> <p>With type classes, there wouldn't be a problem (pseudo-code)</p> <pre><code>typeclass Monoid of A where static operator (+) (x : A, y : A) : A static val Zero : A end instance Int of Monoid where static operator (+) (x : Int, y : Int) : Int = x + y static val Zero : Int = 0 end </code></pre> <p>So why don't we use type classes? Do they have serious disadvantages after all?</p> <p><strong>Edit</strong>: Please don't confuse typeclasses with structural typing, pure C++ templates or duck typing. A typeclass is <em>explicitly instantiated</em> by types and not just satisfied <em>by convention</em>. Moreover it can carry useful implementations and not just define an interface.</p>
1,813,307
5
7
null
2009-11-28 18:04:41.403 UTC
10
2013-11-10 02:33:56.623 UTC
2009-11-28 18:43:17.317 UTC
null
105,459
null
105,459
null
1
16
.net|language-agnostic|language-design|typeclass
1,883
<p>Concepts were excluded because the committee didn't think it could get them right in time, and because they weren't considered essential to the release. It's not that they don't think they're a good idea, they just don't think the expression of them for C++ is mature: <a href="http://herbsutter.wordpress.com/2009/07/21/trip-report/" rel="nofollow noreferrer">http://herbsutter.wordpress.com/2009/07/21/trip-report/</a></p> <p>Static types try to prevent you passing an object to a function, that doesn't satisfy the requirements of the function. In C++ this is a huge big deal, because at the time the object is accessed by the code, there's no checking that it's the right thing.</p> <p>Concepts try to prevent you passing a template parameter, that doesn't satisfy the requirements of the template. But at the time the template parameter is accessed by the compiler, there already <em>is</em> checking that it's the right thing, even without Concepts. If you try to use it in a way it doesn't support, you get a compiler error[*]. In the case of heavy template-using code you might get three screens full of angle brackets, but in principle that's an informative message. The need to catch errors before a failed compile is less urgent than the need to catch errors before undefined behaviour at runtime.</p> <p>Concepts make it easier to specify template interfaces that will work <em>across multiple instantiations</em>. This is significant, but a much less pressing problem than specifying function interfaces that will work across multiple calls.</p> <p>In answer to your question - any formal statement "I implement this interface" has one big disadvantage, that it requires the interface to be invented before the implementation is. Type inference systems don't, but they have the big disadvantage that languages in general cannot express the whole of an interface using types, and so you might have an object which is inferred to be of the correct type, but which does not have the semantics ascribed to that type. If your language addresses interfaces at all (in particular if it matches them to classes), then AFAIK you have to take a stance here, and pick your disadvantage.</p> <p>[*] Usually. There are some exceptions, for instance the C++ type system currently does not prevent you from using an input iterator as if it were a forward iterator. You need iterator traits for that. Duck typing alone doesn't stop you passing an object which walks, swims and quacks, but on close inspection doesn't actually do any of those things the way a duck does, and is astonished to learn that you thought it would ;-)</p>
1,899,201
JavaScript game framework
<p>Nowadays with <code>&lt;canvas&gt;</code>, it is easy to find all kind of cool stuff around the Internet. Like emulators, demos, games, just visual stuff, etc.<br/> But it seems that everyone is programming using the basic primitives of canvas.</p> <p>There exist any framework working over <code>&lt;canvas&gt;</code> or utility library?</p>
1,899,476
6
2
null
2009-12-14 06:15:40.113 UTC
10
2015-07-17 20:06:43.53 UTC
2015-07-17 20:04:31.38 UTC
null
63,550
null
81,085
null
1
16
javascript|canvas
6,377
<p>You could look at something like Processing.js:</p> <p><a href="http://processingjs.org/exhibition" rel="nofollow noreferrer">http://processingjs.org/exhibition</a></p> <p><strong>UPDATE:</strong></p> <p>If you want a game API, I haven't tried it, but the comments are promising, you can look at:</p> <p><a href="http://ajaxian.com/archives/gamejs-canvas-game-library" rel="nofollow noreferrer">http://ajaxian.com/archives/gamejs-canvas-game-library</a></p> <p>In order to keep the javascript small and optimized I tend to just access the elements directly, but, over time people will create libraries of their own, but it may not be libraries that are useful in certain situations.</p> <p><strong>UPDATE 2:</strong></p> <p>Looks like you can get a version of gamejs from here:</p> <p><a href="http://tommysmind.com/gamejs/GameJS-0.1.rar" rel="nofollow noreferrer">http://tommysmind.com/gamejs/GameJS-0.1.rar</a></p> <p>This also was an interesting article on GameJS by the author: <a href="http://tommysmind.com/gamejs/" rel="nofollow noreferrer">http://tommysmind.com/gamejs/</a></p>
1,605,341
Where does SVN client store user authentication data?
<p>I am trying to simulate a problem we have with a particular domain ID which has issues accessing a subversion repository. Towards this, I tried a <code>svn checkout</code> with the option <code>--username domain\problematic_ID</code> on another windows machine. But I am not able to reproduce the problem as the checkout still succeeds using my own ID. This led me to wonder if SVN caches user authentication data in more than one place and if so where. </p> <p>I have cleared the auth directory in the application data area, changed the options in the config file to disable caching of user auth data - but to no avail. The system does not even prompt me for the new user name and password, but simply checks out with the old ID.(I know it is the old ID in use by looking through the SVN logs). I am obviously missing something here -- but what? :-( </p> <p>Does anyone know? </p> <p>The subversion client version I use is 1.4.6(r28521)</p>
1,605,448
6
0
null
2009-10-22 06:23:04.63 UTC
9
2017-06-21 15:11:27.97 UTC
2015-12-14 00:40:55.007 UTC
null
2,581,872
null
55,291
null
1
68
svn|authentication
180,936
<p>It sounds like you are doing everything exactly as the <a href="http://svnbook.red-bean.com/en/1.8/svn.serverconfig.netmodel.html#svn.serverconfig.netmodel.creds" rel="nofollow noreferrer">client credential section of the Subversion book</a> suggests. The only thing I can think of is that the server isn't asking for the username and password because is getting it from somewhere else.</p>
2,119,060
Android - Getting audio to play through earpiece
<p>I currently have code that reads a recording in from the devices mic using the AudioRecord class and then playing it back out using the AudioTrack class.</p> <p>My problem is that when I play it out it plays via the speaker phone.</p> <p>I want it to play out via the ear piece on the device.</p> <p>Here is my code:</p> <pre><code>public class LoopProg extends Activity { boolean isRecording; //currently not used AudioManager am; int count = 0; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); am = (AudioManager) getSystemService(Context.AUDIO_SERVICE); am.setMicrophoneMute(true); while(count &lt;= 1000000){ Record record = new Record(); record.run(); count ++; Log.d("COUNT", "Count is : " + count); } } public class Record extends Thread{ static final int bufferSize = 200000; final short[] buffer = new short[bufferSize]; short[] readBuffer = new short[bufferSize]; public void run() { isRecording = true; android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO); int buffersize = AudioRecord.getMinBufferSize(11025, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT); AudioRecord arec = new AudioRecord(MediaRecorder.AudioSource.MIC, 11025, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, buffersize); AudioTrack atrack = new AudioTrack(AudioManager.STREAM_MUSIC, 11025, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, buffersize, AudioTrack.MODE_STREAM); am.setRouting(AudioManager.MODE_NORMAL,1, AudioManager.STREAM_MUSIC); int ok = am.getRouting(AudioManager.ROUTE_EARPIECE); Log.d("ROUTING", "getRouting = " + ok); setVolumeControlStream(AudioManager.STREAM_VOICE_CALL); //am.setSpeakerphoneOn(true); Log.d("SPEAKERPHONE", "Is speakerphone on? : " + am.isSpeakerphoneOn()); am.setSpeakerphoneOn(false); Log.d("SPEAKERPHONE", "Is speakerphone on? : " + am.isSpeakerphoneOn()); atrack.setPlaybackRate(11025); byte[] buffer = new byte[buffersize]; arec.startRecording(); atrack.play(); while(isRecording) { arec.read(buffer, 0, buffersize); atrack.write(buffer, 0, buffer.length); } arec.stop(); atrack.stop(); isRecording = false; } } } </code></pre> <p>As you can see if the code I have tried using the AudioManager class and its methods including the deprecated setRouting method and nothing works, the setSpeakerphoneOn method seems to have no effect at all, neither does the routing method.</p> <p>Has anyone got any ideas on how to get it to play via the earpiece instead of the spaker phone?</p>
4,663,831
8
0
null
2010-01-22 17:15:52.063 UTC
24
2022-02-11 19:27:12.243 UTC
2013-05-29 11:40:40.1 UTC
null
1,055,764
null
243,999
null
1
34
android|audio|routes
56,747
<p>Just got it to work on 2.2. I still needed the In_Call setup which I don't really like but I'll deal with it for now. I was able to ditch the call routing stuff which is deprecated now. I found you definitely need the <code>Modify_Audio_Settings</code> permission, no error without it but it the <code>setSpeakerPhone</code> method just does nothing. Here is the mock up of the code I used.</p> <pre><code>private AudioManager m_amAudioManager; m_amAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE); m_amAudioManager.setMode(AudioManager.MODE_IN_CALL); m_amAudioManager.setSpeakerphoneOn(false); </code></pre>
2,148,587
Finding quoted strings with escaped quotes in C# using a regular expression
<p>I'm trying to find all of the quoted text on a single line.</p> <p>Example:</p> <pre class="lang-none prettyprint-override"><code>"Some Text" "Some more Text" "Even more text about \"this text\"" </code></pre> <p>I need to get: </p> <ul> <li><code>"Some Text"</code></li> <li><code>"Some more Text"</code></li> <li><code>"Even more text about \"this text\""</code></li> </ul> <p><code>\"[^\"\r]*\"</code> gives me everything except for the last one, because of the escaped quotes.</p> <p>I have read about <code>\"[^\"\\]*(?:\\.[^\"\\]*)*\"</code> working, but I get an error at run time:</p> <pre class="lang-none prettyprint-override"><code>parsing ""[^"\]*(?:\.[^"\]*)*"" - Unterminated [] set. </code></pre> <p>How do I fix this?</p>
2,151,720
11
0
null
2010-01-27 16:33:19.74 UTC
14
2019-12-20 12:53:11.393 UTC
2013-11-27 07:21:04.077 UTC
null
20,938
null
92,953
null
1
44
c#|regex|quotes|escaping
62,011
<p>What you've got there is an example of Friedl's "unrolled loop" technique, but you seem to have some confusion about how to express it as a string literal. Here's how it should look to the regex compiler:</p> <pre><code>"[^"\\]*(?:\\.[^"\\]*)*" </code></pre> <p>The initial <code>"[^"\\]*</code> matches a quotation mark followed by zero or more of any characters other than quotation marks or backslashes. That part alone, along with the final <code>"</code>, will match a simple quoted string with no embedded escape sequences, like <code>"this"</code> or <code>""</code>. </p> <p>If it <em>does</em> encounter a backslash, <code>\\.</code> consumes the backslash and whatever follows it, and <code>[^"\\]*</code> (again) consumes everything up to the next backslash or quotation mark. That part gets repeated as many times as necessary until an unescaped quotation mark turns up (or it reaches the end of the string and the match attempt fails).</p> <p>Note that this will match <code>"foo\"-</code> in <code>\"foo\"-"bar"</code>. That may seem to expose a flaw in the regex, but it doesn't; it's the <em>input</em> that's invalid. The goal was to match quoted strings, optionally containing backslash-escaped quotes, embedded in other text--why would there be escaped quotes <em>outside</em> of quoted strings? If you really need to support that, you have a much more complex problem, requiring a very different approach.</p> <p>As I said, the above is how the regex should look to the regex compiler. But you're writing it in the form of a string literal, and those tend to treat certain characters specially--i.e., backslashes and quotation marks. Fortunately, C#'s verbatim strings save you the hassle of having to double-escape backslashes; you just have to escape each quotation mark with another quotation mark:</p> <pre><code>Regex r = new Regex(@"""[^""\\]*(?:\\.[^""\\]*)*"""); </code></pre> <p>So the rule is double quotation marks for the C# compiler and double backslashes for the regex compiler--nice and easy. This particular regex may look a little awkward, with the three quotation marks at either end, but consider the alternative:</p> <pre><code>Regex r = new Regex("\"[^\"\\\\]*(?:\\\\.[^\"\\\\]*)*\""); </code></pre> <p>In Java, you <em>always</em> have to write them that way. :-(</p>
1,759,794
How to print pthread_t
<p>Searched, but don't come across a satisfying answer. </p> <p>I know there's no a portable way to print a pthread_t. </p> <p>How do you do it in your app?</p> <p><strong>Update:</strong> </p> <p>Actually I don't need pthread_t, but some small numeric id, identifying in debug message different threads. </p> <p>On my system (64 bit RHEL 5.3) it's defined as unsigned long int, so it's big number and just printing it eats a valuable place in debug line. How does <strong>gdb assign</strong> short tids?</p>
1,759,846
13
0
null
2009-11-18 23:08:30.91 UTC
27
2020-07-28 01:29:37.073 UTC
2013-07-09 09:36:25.353 UTC
null
204,665
null
135,960
null
1
64
c++|c|linux|pthreads
116,660
<p>This will print out a hexadecimal representation of a <code>pthread_t</code>, no matter what that actually is:</p> <pre><code>void fprintPt(FILE *f, pthread_t pt) { unsigned char *ptc = (unsigned char*)(void*)(&amp;pt); fprintf(f, "0x"); for (size_t i=0; i&lt;sizeof(pt); i++) { fprintf(f, "%02x", (unsigned)(ptc[i])); } } </code></pre> <p>To just print a small id for a each <code>pthread_t</code> something like this could be used (this time using iostreams):</p> <pre><code>void printPt(std::ostream &amp;strm, pthread_t pt) { static int nextindex = 0; static std::map&lt;pthread_t, int&gt; ids; if (ids.find(pt) == ids.end()) { ids[pt] = nextindex++; } strm &lt;&lt; ids[pt]; } </code></pre> <p>Depending on the platform and the actual representation of <code>pthread_t</code> it might here be necessary to define an <code>operator&lt;</code> for <code>pthread_t</code>, because <code>std::map</code> needs an ordering on the elements:</p> <pre><code>bool operator&lt;(const pthread_t &amp;left, const pthread_t &amp;right) { ... } </code></pre>
1,440,733
Replace single quotes in SQL Server
<p>I have this function in SQL Server to replace single quotes.</p> <p>But when I insert a single quote it throws an error on <code>Replace(@strip,''',''))</code>:</p> <pre><code>Create Function [dbo].[fn_stripsingleQuote] (@strStrip varchar(Max)) returns varchar as begin declare @CleanString varchar(Max) SET @var=(Replace(@strip,'','')) return @var end </code></pre>
1,440,762
14
0
null
2009-09-17 19:01:19.767 UTC
9
2022-05-19 08:04:14.853 UTC
2016-01-25 14:49:17.5 UTC
null
63,550
null
168,706
null
1
62
sql-server|replace|error-handling
343,651
<p>You need to double up your single quotes as follows:</p> <pre><code>REPLACE(@strip, '''', '') </code></pre>
1,496,313
Returning a C string from a function
<p>I am trying to return a C string from a function, but it's not working. Here is my code.</p> <pre><code>char myFunction() { return "My String"; } </code></pre> <p>In <code>main</code> I am calling it like this:</p> <pre><code>int main() { printf("%s", myFunction()); } </code></pre> <p>I have also tried some other ways for <code>myFunction</code>, but they are not working. For example:</p> <pre><code>char myFunction() { char array[] = "my string"; return array; } </code></pre> <p>Note: I am not allowed to use pointers!</p> <p>Little background on this problem:</p> <p>There is function which is finding out which month it is. For example, if it's 1 then it returns January, etc.</p> <p>So when it's going to print, it's doing it like this: <code>printf("Month: %s",calculateMonth(month));</code>. Now the problem is how to return that string from the <code>calculateMonth</code> function.</p>
1,496,328
15
14
null
2009-09-30 05:59:45.6 UTC
66
2021-04-09 21:03:19.18 UTC
2020-04-30 13:56:02.217 UTC
null
63,550
null
146,603
null
1
132
c
361,335
<p>Your function signature needs to be:</p> <pre><code>const char * myFunction() { return &quot;my String&quot;; } </code></pre> <h2>Background:</h2> <p>It's so fundamental to C &amp; C++, but little more discussion should be in order.</p> <p>In C (&amp; C++ for that matter), a string is just an array of bytes terminated with a zero byte - hence the term &quot;string-zero&quot; is used to represent this particular flavour of string. There are other kinds of strings, but in C (&amp; C++), this flavour is inherently understood by the language itself. Other languages (Java, Pascal, etc.) use different methodologies to understand <code>&quot;my string&quot;</code>.</p> <p>If you ever use the Windows API (which is in C++), you'll see quite regularly function parameters like: &quot;LPCSTR lpszName&quot;. The 'sz' part represents this notion of 'string-zero': an array of bytes with a null (/zero) terminator.</p> <h2>Clarification:</h2> <p>For the sake of this 'intro', I use the word 'bytes' and 'characters' interchangeably, because it's easier to learn this way. Be aware that there are other methods (wide-characters, and multi-byte character systems (<em>mbcs</em>)) that are used to cope with international characters. <a href="https://en.wikipedia.org/wiki/UTF-8" rel="noreferrer">UTF-8</a> is an example of an mbcs. For the sake of intro, I quietly 'skip over' all of this.</p> <h2>Memory:</h2> <p>This means that a string like <code>&quot;my string&quot;</code> actually uses 9+1 (=10!) bytes. This is important to know when you finally get around to allocating strings dynamically.</p> <p>So, without this 'terminating zero', you don't have a string. You have an array of characters (also called a buffer) hanging around in memory.</p> <h2>Longevity of data:</h2> <p>The use of the function this way:</p> <pre><code>const char * myFunction() { return &quot;my String&quot;; } int main() { const char* szSomeString = myFunction(); // Fraught with problems printf(&quot;%s&quot;, szSomeString); } </code></pre> <p>... will generally land you with random unhandled-exceptions/segment faults and the like, especially 'down the road'.</p> <p>In short, although my answer is correct - 9 times out of 10 you'll end up with a program that crashes if you use it that way, especially if you think it's 'good practice' to do it that way. In short: It's generally not.</p> <p>For example, imagine some time in the future, the string now needs to be manipulated in some way. Generally, a coder will 'take the easy path' and (try to) write code like this:</p> <pre><code>const char * myFunction(const char* name) { char szBuffer[255]; snprintf(szBuffer, sizeof(szBuffer), &quot;Hi %s&quot;, name); return szBuffer; } </code></pre> <p>That is, your program will crash because the compiler (may/may not) have released the memory used by <code>szBuffer</code> by the time the <code>printf()</code> in <code>main()</code> is called. (Your compiler should also warn you of such problems beforehand.)</p> <p>There are two ways to return strings that won't barf so readily.</p> <ol> <li>returning buffers (static or dynamically allocated) that live for a while. In C++ use 'helper classes' (for example, <code>std::string</code>) to handle the longevity of data (which requires changing the function's return value), or</li> <li>pass a buffer to the function that gets filled in with information.</li> </ol> <p>Note that it is impossible to use strings without using pointers in C. As I have shown, they are synonymous. Even in C++ with template classes, there are always buffers (that is, pointers) being used in the background.</p> <p>So, to better answer the (now modified question). (There are sure to be a variety of 'other answers' that can be provided.)</p> <h2>Safer Answers:</h2> <p><strong>Example 1, using statically allocated strings:</strong></p> <pre><code>const char* calculateMonth(int month) { static char* months[] = {&quot;Jan&quot;, &quot;Feb&quot;, &quot;Mar&quot; .... }; static char badFood[] = &quot;Unknown&quot;; if (month &lt; 1 || month &gt; 12) return badFood; // Choose whatever is appropriate for bad input. Crashing is never appropriate however. else return months[month-1]; } int main() { printf(&quot;%s&quot;, calculateMonth(2)); // Prints &quot;Feb&quot; } </code></pre> <p>What the <code>static</code> does here (many programmers do not like this type of 'allocation') is that the strings get put into the data segment of the program. That is, it's permanently allocated.</p> <p>If you move over to C++ you'll use similar strategies:</p> <pre><code>class Foo { char _someData[12]; public: const char* someFunction() const { // The final 'const' is to let the compiler know that nothing is changed in the class when this function is called. return _someData; } } </code></pre> <p>... but it's probably easier to use helper classes, such as <code>std::string</code>, if you're writing the code for your own use (and not part of a library to be shared with others).</p> <p><em><strong>Example 2, using caller-defined buffers:</strong></em></p> <p>This is the more 'foolproof' way of passing strings around. The data returned isn't subject to manipulation by the calling party. That is, example 1 can easily be abused by a calling party and expose you to application faults. This way, it's much safer (albeit uses more lines of code):</p> <pre><code>void calculateMonth(int month, char* pszMonth, int buffersize) { const char* months[] = {&quot;Jan&quot;, &quot;Feb&quot;, &quot;Mar&quot; .... }; // Allocated dynamically during the function call. (Can be inefficient with a bad compiler) if (!pszMonth || buffersize&lt;1) return; // Bad input. Let junk deal with junk data. if (month&lt;1 || month&gt;12) { *pszMonth = '\0'; // Return an 'empty' string // OR: strncpy(pszMonth, &quot;Bad Month&quot;, buffersize-1); } else { strncpy(pszMonth, months[month-1], buffersize-1); } pszMonth[buffersize-1] = '\0'; // Ensure a valid terminating zero! Many people forget this! } int main() { char month[16]; // 16 bytes allocated here on the stack. calculateMonth(3, month, sizeof(month)); printf(&quot;%s&quot;, month); // Prints &quot;Mar&quot; } </code></pre> <p>There are lots of reasons why the second method is better, particularly if you're writing a library to be used by others (you don't need to lock into a particular allocation/deallocation scheme, third parties can't break your code, and you don't need to link to a specific memory management library), but like all code, it's up to you on what you like best. For that reason, most people opt for example 1 until they've been burnt so many times that they refuse to write it that way anymore ;)</p> <h2>Disclaimer:</h2> <p>I retired several years back and my C is a bit rusty now. This demo code should all compile properly with C (it is OK for any C++ compiler though).</p>
1,427,608
Fast stable sorting algorithm implementation in javascript
<p>I'm looking to sort an array of about 200-300 objects, sorting on a specific key and a given order (asc/desc). The order of results must be consistent and stable.</p> <p>What would be the best algorithm to use, and could you provide an example of it's implementation in javascript?</p> <p>Thanks!</p>
2,085,225
16
8
null
2009-09-15 14:40:32.02 UTC
37
2021-03-01 23:22:39.09 UTC
null
null
null
null
10,486
null
1
110
javascript|algorithm|sorting
61,885
<p>It is possible to get a stable sorting from a non-stable sort function.</p> <p>Before sorting you get the position of all the elements. In your sort condition, if both elements are equal, then you sort by the position.</p> <p>Tada! You've got a stable sort.</p> <p>I've written an article about it on my blog if you want to know more about this technique and how to implement it: <a href="http://blog.vjeux.com/2010/javascript/javascript-sorting-table.html" rel="noreferrer">http://blog.vjeux.com/2010/javascript/javascript-sorting-table.html</a></p>
2,220,560
Can an Android Toast be longer than Toast.LENGTH_LONG?
<p>When using setDuration() for a Toast, is it possible to set a custom length or at least something longer than <code>Toast.LENGTH_LONG</code>?</p>
2,221,285
27
3
null
2010-02-08 09:27:17.873 UTC
65
2021-09-16 21:01:36.407 UTC
2016-08-26 19:37:10.78 UTC
null
4,843,993
user268481
null
null
1
299
android|android-toast
216,239
<p>The values of <a href="http://developer.android.com/reference/android/widget/Toast.html#LENGTH_SHORT" rel="noreferrer"><code>LENGTH_SHORT</code></a> and <a href="http://developer.android.com/reference/android/widget/Toast.html#LENGTH_LONG" rel="noreferrer"><code>LENGTH_LONG</code></a> are 0 and 1. This means they are treated as flags rather than actual durations so I don't think it will be possible to set the duration to anything other than these values.</p> <p>If you want to display a message to the user for longer, consider a <a href="https://developer.android.com/guide/topics/ui/notifiers/notifications.html" rel="noreferrer">Status Bar Notification</a>. Status Bar Notifications can be programmatically canceled when they are no longer relevant.</p>
17,713,919
Two geom_points add a legend
<p>I plot a 2 geom_point graph with the following code:</p> <pre><code>source("http://www.openintro.org/stat/data/arbuthnot.R") library(ggplot2) ggplot() + geom_point(aes(x = year,y = boys),data=arbuthnot,colour = '#3399ff') + geom_point(aes(x = year,y = girls),data=arbuthnot,shape = 17,colour = '#ff00ff') + xlab(label = 'Year') + ylab(label = 'Rate') </code></pre> <p>I simply want to know how to add a legend on the right side. With the same shape and color. Triangle pink should have the legend "woman" and blue circle the legend "men". Seems quite simple but after many trial I could not do it. (I'm a beginner with ggplot).</p> <p><img src="https://i.stack.imgur.com/YgUd3.png" alt="enter image description here"></p>
17,714,395
4
0
null
2013-07-18 03:18:26.923 UTC
8
2019-10-09 18:13:50.47 UTC
2016-05-01 20:45:09.137 UTC
null
680,068
null
1,364,364
null
1
25
r|ggplot2|legend|legend-properties
63,821
<p>If you rename your columns of the original data frame and then melt it into long format with<code>reshape2::melt</code>, it's much easier to handle in ggplot2. By specifying the <code>color</code> and <code>shape</code> aesthetics in the ggplot command, and specifying the scales for the colors and shapes manually, the legend will appear. </p> <pre><code>source("http://www.openintro.org/stat/data/arbuthnot.R") library(ggplot2) library(reshape2) names(arbuthnot) &lt;- c("Year", "Men", "Women") arbuthnot.melt &lt;- melt(arbuthnot, id.vars = 'Year', variable.name = 'Sex', value.name = 'Rate') ggplot(arbuthnot.melt, aes(x = Year, y = Rate, shape = Sex, color = Sex))+ geom_point() + scale_color_manual(values = c("Women" = '#ff00ff','Men' = '#3399ff')) + scale_shape_manual(values = c('Women' = 17, 'Men' = 16)) </code></pre> <p><img src="https://i.stack.imgur.com/vZynP.png" alt="enter image description here"></p>
18,141,825
Comma separated list in twig
<p>What is the shortest (and clearest) way to add comma after each element of the list except the last one?</p> <pre><code>{% for role in user.roles %} {{ role.name }}, {% endfor %} </code></pre> <p>This example will add comma after all lines, including the last one.</p>
18,141,926
6
2
null
2013-08-09 07:18:08.34 UTC
8
2021-01-17 18:12:33.077 UTC
null
null
null
null
966,972
null
1
43
php|twig
20,224
<p>Don't know about shortest but this could be clear. Try the following to add comma after all lines in the loop except the last one:</p> <pre><code>{% for role in user.roles %} {{ role.name }} {% if not loop.last %},{% endif %} {% endfor %} </code></pre> <p>Shorter version as suggested in comments:</p> <pre><code>{% for role in user.roles %} {{ role.name }} {{ not loop.last ? ',' }} {% endfor %} </code></pre>
6,624,529
Redirect after POST request with jquery
<p>I'm working with Django. I have an HTML page, where I do some Javascript stuff, and then I do a jQuery post, in this way: </p> <pre><code>$.ajax({ url: '/xenopatients/measurement/qual', type: 'POST', data: {'obj':data}, dataType: 'json', contentType: "application/json; charset=utf-8", //questo ok }); </code></pre> <p>After this post request, my Django view correctly handles the call for this URL. What I want it to do is process the data, send the user to another page, and send this data to the new page. The problem is that I cannot perform the redirect like usual in Python, it's like the code ignores the redirect.</p> <p>My Python code is: </p> <pre><code>@csrf_protect @login_required#(login_url='/xenopatients/login/') def qualMeasure(request): name = request.user.username print "enter" if request.method == 'POST': print request.POST if "obj" in request.POST: print 'obj received' return render_to_response('mice/mice_status.html', RequestContext(request)) return render_to_response('measure/qual.html', {'name': name, 'form': QualMeasureForm()}, RequestContext(request)) </code></pre> <p>The only way I've found to change the page is through Javascript after the code above: </p> <pre><code>top.location.href = "/xenopatients/measurement"; </code></pre> <p>But I don't know how to pass the data I need when using this method.</p> <p>The HTML code: </p> <pre><code>&lt;form action="" method=""&gt; &lt;table id="dataTable" width="100%" border="1"&gt;&lt;/table&gt;&lt;br&gt; &lt;script language="javascript"&gt; document.measureForm.id_barcode.focus(); document.measureForm.Add.disabled = false; $('#dataTable').tablePagination({}); &lt;/script&gt; &lt;input type="button" name="save" value="Save Measure Serie" onclick="table2JSON('dataTable')"/&gt; &lt;/form&gt; </code></pre> <p>P.S. I've also tried <code>$.post</code>, but with the same results.</p> <p>How can I do a redirect after a post request made with jQuery in Django?</p>
10,581,336
3
4
null
2011-07-08 12:38:30.863 UTC
9
2016-06-06 23:29:10.467 UTC
2016-06-06 23:29:10.467 UTC
null
3,155,933
null
819,161
null
1
6
jquery|ajax|django|post|redirect
29,234
<p>Ok, I've found the magical solution! :)</p> <p>The situation: there is a view's method called by jQUery.ajax()</p> <p>To redirect after Ajax, I've used the tips found <a href="http://hunterford.me/how-to-handle-http-redirects-with-jquery-and-django/" rel="noreferrer">here</a> (use document instead of 'body' in the jQuery selecotor)</p> <p>But, I've had also further operations to do.</p> <p>in the called view, call another method, like this:</p> <pre><code>[...] if request.method == 'POST': if "obj" in request.POST: #ricevuti dati da ajax request.session['qual'] = request.POST['obj'] return HttpResponseRedirect(reverse("xenopatients.views.qualReport")) </code></pre> <p>I save the data that I need in the session. I use this data in the called view.</p> <p>Call another method it's the key for redirect the page of the browser. In fact, at the end of the called method, you can normally write&amp;execute:</p> <pre><code>return render_to_response('measure/qualReport.html', {'name':name, 'list_report': report, 'message':'Measures correctly saved'}, RequestContext(request)) </code></pre> <p>Hope this can be useful for someone! ;)</p>
6,599,707
2D character array initialization in C
<p>I am trying to build a list of strings that I need to pass to a function expecting <code>char **</code></p> <p>How do I build this array? I want to pass in two options, each with less than 100 characters.</p> <pre><code>char **options[2][100]; options[0][0] = 'test1'; options[1][0] = 'test2'; </code></pre> <p>This does not compile. What am I doing wrong exactly? How do I create a 2D character array in C?</p>
6,599,747
4
1
null
2011-07-06 16:20:17.69 UTC
9
2015-03-08 02:10:42.58 UTC
2013-09-30 20:59:54.07 UTC
null
445,131
null
229,072
null
1
14
c|arrays|multidimensional-array|char
144,977
<p>C strings are enclosed in double quotes:</p> <pre><code>const char *options[2][100]; options[0][0] = "test1"; options[1][0] = "test2"; </code></pre> <p>Re-reading your question and comments though I'm guessing that what you <em>really</em> want to do is this:</p> <pre><code>const char *options[2] = { "test1", "test2" }; </code></pre>
6,329,108
Moving a div from inside one div to another div using Prototype?
<p>In prototype or normal-but-cross-browser-compatible Javascript, how do I move the contents of a div to the contents of another div?</p> <p>Inside the div is a form with ids and dependent Javascript code with event observers. I don't want this to break just because I have moved a block in the DOM. A 'this innerHTML = that innerHTML' solution is not what I am looking for. I will also be needing to do this when the DOM is loaded.</p> <p>I want to go from this:</p> <pre><code>&lt;div id='here'&gt; &lt;div id='MacGuffin'&gt; &lt;p&gt;Hello Worlds!&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id='there'&gt; &lt;/div&gt; </code></pre> <p>to this:</p> <pre><code>&lt;div id='here'&gt; &lt;/div&gt; &lt;div id='there'&gt; &lt;div id='MacGuffin'&gt; &lt;p&gt;Hello Worlds!&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>...when the document loads with nothing jumping about.</p>
6,329,160
4
0
null
2011-06-13 10:13:04.363 UTC
8
2016-01-22 17:51:14.693 UTC
2011-12-28 22:11:32.347 UTC
null
377,037
null
600,342
null
1
18
javascript|prototypejs
63,839
<p>You can add this at the very end of the BODY tag:</p> <pre><code>&lt;script&gt; document.getElementById('there').appendChild( document.getElementById('MacGuffin') ); &lt;/script&gt; </code></pre> <p><code>MacGuffin</code> will be moved automatically from one to the other.<br/> And there won't be any flickering.</p>
15,698,360
Hide div with class name having space in it using jquery
<pre><code>&lt;div class="rcbScroll rcbWidth rcbNoWrap" style="height: 200px; width: 100%; overflow: auto"&gt; &lt;/div&gt; </code></pre> <p>This is my div. I want to hide the div using the class name. I am not able to do as class name as space in it. It is only one class.</p>
15,698,388
3
1
null
2013-03-29 06:17:36.457 UTC
0
2016-05-02 01:04:44.457 UTC
2013-03-29 06:18:37.767 UTC
null
1,493,698
null
2,194,674
null
1
6
jquery|html
50,724
<p>Class names can not have spaces in them. So you have to think of it as 2 class names.</p> <p>Eg: <code>class="word1 word2"</code> </p> <p>Can be selected with the following:</p> <pre><code>var myVar = $('.word1.word2'); </code></pre> <p>In your specific case, it becomes:</p> <pre><code>$('.rcbScroll.rcbWidth.rcbNoWrap').hide(); </code></pre>
35,247,436
CloudKit Server-to-Server authentication
<p>Apple published a new method to authenticate against CloudKit, server-to-server. <a href="https://developer.apple.com/library/content/documentation/DataManagement/Conceptual/CloudKitWebServicesReference/SettingUpWebServices.html#//apple_ref/doc/uid/TP40015240-CH24-SW6" rel="noreferrer">https://developer.apple.com/library/content/documentation/DataManagement/Conceptual/CloudKitWebServicesReference/SettingUpWebServices.html#//apple_ref/doc/uid/TP40015240-CH24-SW6</a></p> <p>I tried to authenticate against CloudKit and this method. At first I generated the key pair and gave the public key to CloudKit, no problem so far.</p> <p>I started to build the request header. According to the documentation it should look like this:</p> <pre><code>X-Apple-CloudKit-Request-KeyID: [keyID] X-Apple-CloudKit-Request-ISO8601Date: [date] X-Apple-CloudKit-Request-SignatureV1: [signature] </code></pre> <ul> <li>[keyID], no problem. You can find this in the CloudKit dashboard. </li> <li>[Date], I think this should work: 2016-02-06T20:41:00Z</li> <li>[signature], here is the problem...</li> </ul> <p>The documentation says: </p> <blockquote> <p>The signature created in Step 1. </p> </blockquote> <p>Step 1 says: </p> <blockquote> <p>Concatenate the following parameters and separate them with colons.<br> <code>[Current date]:[Request body]:[Web Service URL]</code> </p> </blockquote> <p>I asked myself "Why do I have to generate the key pair?".<br> But step 2 says:</p> <blockquote> <p>Compute the ECDSA signature of this message with your private key.</p> </blockquote> <p>Maybe they mean to sign the concatenated signature with the private key and put this into the header? Anyway I tried both... </p> <p>My sample for this (unsigned) signature value looks like:</p> <pre><code>2016-02-06T20:41:00Z:YTdkNzAwYTllNjI1M2EyZTllNDNiZjVmYjg0MWFhMGRiMTE2MjI1NTYwNTA2YzQyODc4MjUwNTQ0YTE5YTg4Yw==:https://api.apple-cloudkit.com/database/1/[iCloud Container]/development/public/records/lookup </code></pre> <p>The request body value is SHA256 hashed and after that base64 encoded. My question is, I should concatenate with a ":" but the url and the date also contains ":". Is it correct? (I also tried to URL-Encode the URL and delete the ":" in the date).<br> At next I signed this signature string with ECDSA, put it into the header and send it. But I always get 401 "Authentication failed" back. To sign it, I used the <a href="https://github.com/warner/python-ecdsa" rel="noreferrer">ecdsa</a> python module, with following commands: </p> <pre><code>from ecdsa import SigningKey a = SigningKey.from_pem(open("path_to_pem_file").read()) b = "[date]:[base64(request_body)]:/database/1/iCloud....." print a.sign(b).encode('hex') </code></pre> <p>Maybe the python module doesn't work correctly. But it can generate the right public key from the private key. So I hope the other functions also work. </p> <p>Has anybody managed to authenticate against CloudKit with the server-to-server method? How does it work correctly?</p> <p><strong>Edit: Correct python version that works</strong> </p> <pre><code>from ecdsa import SigningKey import ecdsa, base64, hashlib a = SigningKey.from_pem(open("path_to_pem_file").read()) b = "[date]:[base64(sha256(request_body))]:/database/1/iCloud....." signature = a.sign(b, hashfunc=hashlib.sha256, sigencode=ecdsa.util.sigencode_der) signature = base64.b64encode(signature) print signature #include this into the header </code></pre>
35,258,332
6
11
null
2016-02-06 22:45:01.96 UTC
17
2018-11-19 16:03:35.01 UTC
2017-06-30 13:26:38.733 UTC
null
1,033,581
null
5,893,400
null
1
27
authentication|cloudkit|server-to-server
3,910
<p>The last part of the message</p> <pre><code>[Current date]:[Request body]:[Web Service URL] </code></pre> <p><em>must not</em> include the domain (it <em>must</em> include any query parameters):</p> <pre><code>2016-02-06T20:41:00Z:YTdkNzAwYTllNjI1M2EyZTllNDNiZjVmYjg0MWFhMGRiMTE2MjI1NTYwNTA2YzQyODc4MjUwNTQ0YTE5YTg4Yw==:/database/1/[iCloud Container]/development/public/records/lookup </code></pre> <p>With newlines for better readability:</p> <pre><code>2016-02-06T20:41:00Z :YTdkNzAwYTllNjI1M2EyZTllNDNiZjVmYjg0MWFhMGRiMTE2MjI1NTYwNTA2YzQyODc4MjUwNTQ0YTE5YTg4Yw== :/database/1/[iCloud Container]/development/public/records/lookup </code></pre> <h2>The following shows how to compute the header value in pseudocode</h2> <p>The exact API calls depend on the concrete language and crypto library you use.</p> <pre><code>//1. Date //Example: 2016-02-07T18:58:24Z //Pitfall: make sure to not include milliseconds date = isoDateWithoutMilliseconds() //2. Payload //Example (empty string base64 encoded; GET requests): //47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU= //Pitfall: make sure the output is base64 encoded (not hex) payload = base64encode(sha256(body)) //3. Path //Example: /database/1/[containerIdentifier]/development/public/records/lookup //Pitfall: Don't include the domain; do include any query parameter path = stripDomainKeepQueryParams(url) //4. Message //Join date, payload, and path with colons message = date + ':' + payload + ':' + path //5. Compute a signature for the message using your private key. //This step looks very different for every language/crypto lib. //Pitfall: make sure the output is base64 encoded. //Hint: the key itself contains information about the signature algorithm // (on NodeJS you can use the signature name 'RSA-SHA256' to compute a // the correct ECDSA signature with an ECDSA key). signature = base64encode(sign(message, key)) //6. Set headers X-Apple-CloudKit-Request-KeyID = keyID X-Apple-CloudKit-Request-ISO8601Date = date X-Apple-CloudKit-Request-SignatureV1 = signature //7. For POST requests, don't forget to actually send the unsigned request body // (not just the headers) </code></pre>
1,301,399
JPA using multiple database schemas
<p>I'm having a bit of trouble with one particular issue using JPA/Spring:</p> <p>How can I dynamically assign a schema to an entity?</p> <p>We have TABLE1 that belongs to schema AD and TABLE2 that is under BD.</p> <pre><code>@Entity @Table(name = "TABLE1", schema="S1D") ... @Entity @Table(name = "TABLE2", schema="S2D") ... </code></pre> <p>The schemas may not be hardcoded in an annotation attribute as it depends on the environment (Dev/Acc/Prd). (In acceptance the schemas are S1A and S2A) </p> <p>How can I achieve this? Is it possible to specify some kind of placeholders like this:</p> <pre><code>@Entity @Table(name = "TABLE1", schema="${schema1}") ... @Entity @Table(name = "TABLE2", schema="${schema2}") ... </code></pre> <p>so that schemas are replaced based on a property file residing in the environment?</p> <p>Cheers</p>
5,066,829
7
0
null
2009-08-19 17:18:49.55 UTC
10
2022-03-22 22:17:44.797 UTC
null
null
null
null
138,699
null
1
28
java|database|spring|jpa|schema
64,185
<p>I had the same problem I solved that with a persistence.xml in which I refer to the needed orm.xml files within I declared the db shema</p> <pre><code>&lt;persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd" version="2.0" &gt; &lt;persistence-unit name="schemaOne"&gt; . . . &lt;mapping-file&gt;ormOne.xml&lt;/mapping-file&gt; . . . &lt;/persistence-unit&gt; &lt;persistence-unit name="schemaTwo"&gt; . . . &lt;mapping-file&gt;ormTwo.xml&lt;/mapping-file&gt; . . . &lt;/persistence-unit&gt; &lt;/persistence&gt; </code></pre> <p>now you can create a EntityManagerFactory for your special schema</p> <pre><code>EntityManagerFactory emf = Persistence.createEntityManagerFactory("schemaOne"); </code></pre>
357,813
Remembering a quote from Alan Kay
<p>Alan Kay was quoted several years ago to the effect that there had been only three new things in software in the preceding 20 years (effectively the lifespan of PCs). One of them was Spreadsheets.</p> <p>Does anyone remember the other two?</p> <p>Who is Alan Kay? (a few may ask.) His work at Xerox Parc arguably did more to shape our current software paradigm than any other influence.</p>
389,642
7
2
null
2008-12-10 22:20:53.227 UTC
65
2018-02-18 19:02:51.093 UTC
2018-02-18 19:02:51.093 UTC
Out Into Space
102,937
doofledorfer
31,641
null
1
38
history|quotes|innovation
24,153
<p>I will try to remember what I said, but none of the answers so far are correct (every one of them was done in the 60s and 70s before the commercialization of PCs in the 80s).</p> <p>However, we could start all over and try to think of <a href="https://stackoverflow.com/q/432922/1288">new inventions in computing since the 1980s</a>.</p>
38,561
What is the argument for printf that formats a long?
<p>The <code>printf</code> function takes an argument type, such as <code>%d</code> or <code>%i</code> for a <code>signed int</code>. However, I don't see anything for a <code>long</code> value.</p>
38,570
7
1
null
2008-09-01 22:45:25.903 UTC
67
2018-06-15 00:47:37.953 UTC
2018-06-15 00:47:37.953 UTC
null
6,338,725
Thomas Owens
572
null
1
576
c|printf|long-integer
1,002,279
<p>Put an <code>l</code> (lowercased letter L) directly before the specifier. </p> <pre><code>unsigned long n; long m; printf("%lu %ld", n, m); </code></pre>
1,000,162
What are the use cases of Graph-based Databases (http://neo4j.org/)?
<p>I have used Relational DB's a lot and decided to venture out on other types available.</p> <p>This particular product looks good and promising: <a href="http://neo4j.org/" rel="noreferrer">http://neo4j.org/</a></p> <p>Has anyone used graph-based databases? What are the pros and cons from a usability prespective?</p> <p>Have you used these in a production environment? What was the requirement that prompted you to use them?</p>
1,000,803
7
1
null
2009-06-16 08:23:47.813 UTC
73
2017-09-10 09:47:07.317 UTC
2017-09-10 09:47:07.317 UTC
null
3,755,196
null
111,919
null
1
136
database|neo4j|graph-databases
34,237
<p>I used a graph database in a previous job. We weren't using neo4j, it was an in-house thing built on top of Berkeley DB, but it was similar. It was used in production (it still is).</p> <p>The reason we used a graph database was that the data being stored by the system and the operations the system was doing with the data were exactly the weak spot of relational databases and were exactly the strong spot of graph databases. The system needed to store collections of objects that lack a fixed schema and are linked together by relationships. To reason about the data, the system needed to do a lot of operations that would be a couple of traversals in a graph database, but that would be quite complex queries in SQL.</p> <p>The main advantages of the graph model were rapid development time and flexibility. We could quickly add new functionality without impacting existing deployments. If a potential customer wanted to import some of their own data and graft it on top of our model, it could usually be done on site by the sales rep. Flexibility also helped when we were designing a new feature, saving us from trying to squeeze new data into a rigid data model.</p> <p>Having a weird database let us build a lot of our other weird technologies, giving us lots of secret-sauce to distinguish our product from those of our competitors. </p> <p>The main disadvantage was that we weren't using the standard relational database technology, which can be a problem when your customers are enterprisey. Our customers would ask why we couldn't just host our data on their giant Oracle clusters (our customers usually had large datacenters). One of the team actually rewrote the database layer to use Oracle (or PostgreSQL, or MySQL), but it was slightly slower than the original. At least one large enterprise even had an Oracle-only policy, but luckily Oracle bought Berkeley DB. We also had to write a lot of extra tools - we couldn't just use Crystal Reports for example.</p> <p>The other disadvantage of our graph database was that we built it ourselves, which meant when we hit a problem (usually with scalability) we had to solve it ourselves. If we'd used a relational database, the vendor would have already solved the problem ten years ago.</p> <p>If you're building a product for enterprisey customers and your data fits into the relational model, use a relational database if you can. If your application doesn't fit the relational model but it does fit the graph model, use a graph database. If it only fits something else, use that.</p> <p>If your application doesn't need to fit into the current blub architecture, use a graph database, or CouchDB, or BigTable, or whatever fits your app and you think is cool. It might give you an advantage, and its fun to try new things.</p> <p>Whatever you chose, try not to build the database engine yourself unless you really like building database engines.</p>
26,567
How do I set a textbox to multi-line in SSRS?
<p>I have a report with many fields that I'm trying to get down to 1 page horizontally (I don't care whether it's 2 or 200 pages vertically... just don't want to have to deal with 2 pages wide by x pages long train-wreck). That said, it deals with contact information.</p> <p>My idea was to do:</p> <pre><code>Name: Address: City: State: ... Jon Doe Addr1 ThisTown XX ... Addr2 Addr3 ----------------------------------------------- Jane Doe Addr1 ThisTown XX ... Addr2 Addr3 ----------------------------------------------- </code></pre> <p>Is there some way to set a <code>textbox</code> to be multi-line (or the SQL result)? Have I missed something bloody obvious?</p> <hr> <p>The CanGrow Property is on by default, and I've double checked that this is true. My problem is that I don't know how to force a line-break. I get the 3 address fields that just fills a line, then wraps to another. I've tried <code>/n</code>, <code>\n</code> (since I can never remember which is the correct slash to put), <code>&lt;br&gt;</code>, <code>&lt;br /&gt;</code> (since the report will be viewed in a ReportViewer control in an ASP.NET website). I can't think of any other ways to wrap the text. </p> <p>Is there some way to get the results from the database as 3 lines of text/characters? ­­­­­­­­­­­­­­­­­­­­­­­­­­­</p>
30,409
8
0
null
2008-08-25 18:19:18.627 UTC
null
2017-08-13 05:06:38.15 UTC
2017-07-19 17:04:08.63 UTC
null
7,750,640
Pulsehead
2,156
null
1
17
reporting-services|textbox|multiline
63,612
<p>Alter the report's text box to:</p> <pre><code>= Fields!Addr1.Value + VbCrLf + Fields!Addr2.Value + VbCrLf + Fields!Addr3.Value </code></pre>
800,017
Why do SQL Server Scalar-valued functions get slower?
<p>Why do Scalar-valued functions seem to cause queries to run cumulatively slower the more times in succession that they are used?</p> <p>I have this table that was built with data purchased from a 3rd party.</p> <p>I've trimmed out some stuff to make this post shorter... but just so you get the idea of how things are setup.</p> <pre><code>CREATE TABLE [dbo].[GIS_Location]( [ID] [int] IDENTITY(1,1) NOT NULL, --PK [Lat] [int] NOT NULL, [Lon] [int] NOT NULL, [Postal_Code] [varchar](7) NOT NULL, [State] [char](2) NOT NULL, [City] [varchar](30) NOT NULL, [Country] [char](3) NOT NULL, CREATE TABLE [dbo].[Address_Location]( [ID] [int] IDENTITY(1,1) NOT NULL, --PK [Address_Type_ID] [int] NULL, [Location] [varchar](100) NOT NULL, [State] [char](2) NOT NULL, [City] [varchar](30) NOT NULL, [Postal_Code] [varchar](10) NOT NULL, [Postal_Extension] [varchar](10) NULL, [Country_Code] [varchar](10) NULL, </code></pre> <p>Then I have two functions that look up LAT and LON.</p> <pre><code>CREATE FUNCTION [dbo].[usf_GIS_GET_LAT] ( @City VARCHAR(30), @State CHAR(2) ) RETURNS INT WITH EXECUTE AS CALLER AS BEGIN DECLARE @LAT INT SET @LAT = (SELECT TOP 1 LAT FROM GIS_Location WITH(NOLOCK) WHERE [State] = @State AND [City] = @City) RETURN @LAT END CREATE FUNCTION [dbo].[usf_GIS_GET_LON] ( @City VARCHAR(30), @State CHAR(2) ) RETURNS INT WITH EXECUTE AS CALLER AS BEGIN DECLARE @LON INT SET @LON = (SELECT TOP 1 LON FROM GIS_Location WITH(NOLOCK) WHERE [State] = @State AND [City] = @City) RETURN @LON END </code></pre> <p>When I run the following...</p> <pre><code>SET STATISTICS TIME ON SELECT dbo.usf_GIS_GET_LAT(City,[State]) AS Lat, dbo.usf_GIS_GET_LON(City,[State]) AS Lon FROM Address_Location WITH(NOLOCK) WHERE ID IN (SELECT TOP 100 ID FROM Address_Location WITH(NOLOCK) ORDER BY ID DESC) SET STATISTICS TIME OFF </code></pre> <p>100 ~= 8 ms, 200 ~= 32 ms, 400 ~= 876 ms</p> <p>--Edit Sorry I should have been more clear. I'm not looking to tune the query listed above. This is just a sample to show the execution time getting slower the more records it crunches through. In the real world application the functions are used as part of a where clause to build a radius around a city and state to include all records with in that region.</p>
809,789
8
2
null
2009-04-28 22:01:43.377 UTC
11
2019-08-28 20:37:04.263 UTC
2018-11-07 15:37:39.243 UTC
null
5,070,879
null
87,822
null
1
17
sql|sql-server|tsql|sql-server-2005|sql-function
47,305
<p>In most cases, it's best to avoid scalar valued functions that reference tables because (as others said) they are basically black boxes that need to be ran once for every row, and cannot be optimized by the query plan engine. Therefore, they tend to scale linearly even if the associated tables have indexes.</p> <p>You may want to consider using an inline-table-valued function, since they are evaluated inline with the query, and can be optimized. You get the encapsulation you want, but the performance of pasting the expressions right in the select statement.</p> <p>As a side effect of being inlined, they can't contain any procedural code (no declare @variable; set @variable = ..; return). However, they can return several rows and columns.</p> <p>You could re-write your functions something like this:</p> <pre><code>create function usf_GIS_GET_LAT( @City varchar (30), @State char (2) ) returns table as return ( select top 1 lat from GIS_Location with (nolock) where [State] = @State and [City] = @City ); GO create function usf_GIS_GET_LON ( @City varchar (30), @State char (2) ) returns table as return ( select top 1 LON from GIS_Location with (nolock) where [State] = @State and [City] = @City ); </code></pre> <p>The syntax to use them is also a little different:</p> <pre><code>select Lat.Lat, Lon.Lon from Address_Location with (nolock) cross apply dbo.usf_GIS_GET_LAT(City,[State]) AS Lat cross apply dbo.usf_GIS_GET_LON(City,[State]) AS Lon WHERE ID IN (SELECT TOP 100 ID FROM Address_Location WITH(NOLOCK) ORDER BY ID DESC) </code></pre>
342,268
Return FileName Only when using OpenFileDialog
<p>I am using the following method to browse for a file:</p> <pre><code> OpenFileDialog.ShowDialog() PictureNameTextEdit.Text = OpenFileDialog.FileName </code></pre> <p>Is there a way get ONLY the file name?</p> <p>The <strong>FileName</strong> method returns the entire path and file name.</p> <p>i.e. I want Foo.txt instead of C:\SomeDirectory\Foo.txt</p>
342,272
8
0
null
2008-12-04 22:05:24.137 UTC
3
2017-07-06 18:55:49.147 UTC
null
null
null
Gerhard Weiss
4,964
null
1
24
vb.net
68,047
<p>Use <a href="http://msdn.microsoft.com/en-us/library/system.io.path.getfilename.aspx" rel="noreferrer"><code>Path.GetFileName(fullPath)</code></a> to get just the filename part, like this:</p> <pre><code>OpenFileDialog.ShowDialog() PictureNameTextEdit.Text = System.IO.Path.GetFileName(OpenFileDialog.FileName) </code></pre>
333,690
Any easy REST tutorials for Java?
<p>Every tutorial or explanation of REST just goes too complicated too quickly - the learning curve rises so fast after the initial explanation of CRUD and the supposed simplicity over SOAP. Why can't people write decent tutorials anymore!</p> <p>I'm looking at Restlet - and its not the best, there are things missing in the tutorial and the language/grammar is a bit confusing and unclear. It has took me hours to untangle their First Steps tutorial (with the help of another Java programmer!)</p> <p><strong>RESTlet Tutorial Comments</strong></p> <p>Overall I'm not sure exactly who the tutorial was aimed at - because there is a fair degree of assumed knowledge all round, so coming into REST and Restlet framework cold leaves you with a lot of 'catchup work' to do, and re-reading paragraphs over and over again.</p> <ol> <li><p>We had difficulty working out that the jars had to be in copied into the correct lib folder. </p></li> <li><p>Problems with web.xml creating a HTTP Status 500 error - </p></li> </ol> <blockquote> <p>The server encountered an internal error () that prevented it from fulfilling this request</p> </blockquote> <p>, the tutorial says: </p> <blockquote> <p>"Create a new Servlet Web application as usual, add a "com.firstStepsServlet" package and put the resource and application classes in."</p> </blockquote> <p>This means that your fully qualified name for your class <strong>FirstStepsApplication</strong> is <strong>com.firstStepsServlet.FirstStepsApplication</strong>, so we had to alter web.xml to refer to the correct class e.g:</p> <p>original:</p> <pre><code>&lt;param-value&gt; firstStepsServlet.FirstStepsApplication &lt;/param-value&gt; </code></pre> <p>should be:</p> <pre><code>&lt;param-value&gt; com.firstStepsServlet.FirstStepsApplication &lt;/param-value&gt; </code></pre> <hr> <p><strong>Conclusion</strong></p> <p>I was under the impression that the concepts of REST were supposed to be much simpler than SOAP - but it seems just as bad if not more complicated - don't get it at all! grrrr</p> <p>Any good links - much appreciated.</p>
333,716
8
3
null
2008-12-02 11:26:14.333 UTC
13
2013-03-07 22:40:03.163 UTC
2013-03-07 22:38:43.977 UTC
Simon E
417,685
Simon E
5,175
null
1
33
java|rest
28,732
<p>It sounds like you could use a solid understanding of the fundamentals of REST, and for that I <em>highly</em> recommend <a href="https://rads.stackoverflow.com/amzn/click/com/0596529260" rel="noreferrer" rel="nofollow noreferrer">RESTful Web Services</a> by Leonard Richardson and Sam Ruby. I provides a great introduction to REST: what it is and how to implement a (practical) RESTful web service.</p> <p>Most of the example code in the book is actually Ruby, but it's easy enough to understand even if you're not a Ruby expert. But one thing that should help you specifically is that one of the later chapters of the book contains overviews of several RESTful frameworks, including Restlet. It doesn't really get into any code (it's a 50,000-foot flyover) but I think it'll give you just what you need at this stage.</p>
301,924
Python: urllib/urllib2/httplib confusion
<p>I'm trying to test the functionality of a web app by scripting a login sequence in Python, but I'm having some troubles.</p> <p>Here's what I need to do:</p> <ol> <li>Do a POST with a few parameters and headers.</li> <li>Follow a redirect</li> <li>Retrieve the HTML body.</li> </ol> <p>Now, I'm relatively new to python, but the two things I've tested so far haven't worked. First I used httplib, with putrequest() (passing the parameters within the URL), and putheader(). This didn't seem to follow the redirects.</p> <p>Then I tried urllib and urllib2, passing both headers and parameters as dicts. This seems to return the login page, instead of the page I'm trying to login to, I guess it's because of lack of cookies or something.</p> <p>Am I missing something simple?</p> <p>Thanks.</p>
302,099
8
1
null
2008-11-19 13:44:20.577 UTC
34
2011-01-29 09:33:42.02 UTC
2008-11-20 14:21:00.393 UTC
null
1,694
Ace
18,673
null
1
52
python|http|urllib2
30,982
<p>Focus on <code>urllib2</code> for this, it works quite well. Don't mess with <code>httplib</code>, it's not the top-level API.</p> <p>What you're noting is that <code>urllib2</code> doesn't follow the redirect.</p> <p>You need to fold in an instance of <code>HTTPRedirectHandler</code> that will catch and follow the redirects.</p> <p>Further, you may want to subclass the default <code>HTTPRedirectHandler</code> to capture information that you'll then check as part of your unit testing.</p> <pre><code>cookie_handler= urllib2.HTTPCookieProcessor( self.cookies ) redirect_handler= HTTPRedirectHandler() opener = urllib2.build_opener(redirect_handler,cookie_handler) </code></pre> <p>You can then use this <code>opener</code> object to POST and GET, handling redirects and cookies properly.</p> <p>You may want to add your own subclass of <code>HTTPHandler</code> to capture and log various error codes, also.</p>
1,237,575
How do I find out what all symbols are exported from a shared object?
<p>I have a shared object (dll). How do I find out what all symbols are exported from that?</p>
1,250,597
9
4
null
2009-08-06 08:21:09.043 UTC
60
2021-11-10 15:15:32.273 UTC
2020-12-16 10:53:28.6 UTC
null
1,783,163
null
39,615
null
1
160
linux|shared-libraries
217,147
<p>Do you have a &quot;shared object&quot; (usually a shared library on AIX), a UNIX shared library, or a Windows DLL? These are all different things, and your question conflates them all :-(</p> <ul> <li>For an AIX shared object, use <code>dump -Tv /path/to/foo.o</code>.</li> <li>For an ELF shared library, use <code>readelf -Ws --dyn-syms /path/to/libfoo.so</code>, or (if you have GNU nm) <code>nm -D /path/to/libfoo.so</code>.</li> <li>For a non-ELF UNIX shared library, please state <em>which</em> UNIX you are interested in.</li> <li>For a Windows DLL, use <code>dumpbin /EXPORTS foo.dll</code>.</li> </ul>
272,900
Undefined reference to static class member
<p>Can anyone explain why following code won't compile? At least on g++ 4.2.4.</p> <p>And more interesting, why it will compile when I cast MEMBER to int?</p> <pre><code>#include &lt;vector&gt; class Foo { public: static const int MEMBER = 1; }; int main(){ vector&lt;int&gt; v; v.push_back( Foo::MEMBER ); // undefined reference to `Foo::MEMBER' v.push_back( (int) Foo::MEMBER ); // OK return 0; } </code></pre>
272,965
9
3
null
2008-11-07 17:39:56.217 UTC
66
2021-09-19 01:35:27.003 UTC
2015-12-18 11:56:54.963 UTC
onebyone.livejournal.com
671,366
null
35,281
null
1
213
c++|g++
120,515
<p>You need to actually define the static member somewhere (after the class definition). Try this:</p> <pre><code>class Foo { /* ... */ }; const int Foo::MEMBER; int main() { /* ... */ } </code></pre> <p>That should get rid of the undefined reference.</p>
1,338,960
Ruby templates: How to pass variables into inlined ERB?
<p>I have an ERB template inlined into Ruby code:</p> <pre><code>require 'erb' DATA = { :a =&gt; "HELLO", :b =&gt; "WORLD", } template = ERB.new &lt;&lt;-EOF current key is: &lt;%= current %&gt; current value is: &lt;%= DATA[current] %&gt; EOF DATA.keys.each do |current| result = template.result outputFile = File.new(current.to_s,File::CREAT|File::TRUNC|File::RDWR) outputFile.write(result) outputFile.close end </code></pre> <p>I can't pass the variable "current" into the template.</p> <p>The error is:</p> <pre><code>(erb):1: undefined local variable or method `current' for main:Object (NameError) </code></pre> <p>How do I fix this?</p>
1,341,138
10
0
null
2009-08-27 05:08:14.01 UTC
23
2020-01-03 13:49:48.093 UTC
null
null
null
null
76,393
null
1
57
ruby|templates|syntax|erb
62,266
<p>Got it!</p> <p>I create a bindings class</p> <pre><code>class BindMe def initialize(key,val) @key=key @val=val end def get_binding return binding() end end </code></pre> <p>and pass an instance to ERB</p> <pre><code>dataHash.keys.each do |current| key = current.to_s val = dataHash[key] # here, I pass the bindings instance to ERB bindMe = BindMe.new(key,val) result = template.result(bindMe.get_binding) # unnecessary code goes here end </code></pre> <p>The .erb template file looks like this:</p> <pre><code>Key: &lt;%= @key %&gt; </code></pre>
40,273
What's the best way to use SOAP with Ruby?
<p>A client of mine has asked me to integrate a 3rd party API into their Rails app. The only problem is that the API uses SOAP. Ruby has basically dropped SOAP in favor of REST. They provide a Java adapter that apparently works with the Java-Ruby bridge, but we'd like to keep it all in Ruby, if possible. I looked into soap4r, but it seems to have a slightly bad reputation.</p> <p>So what's the best way to integrate SOAP calls into a Rails app?</p>
40,961
10
0
null
2008-09-02 18:46:09.06 UTC
44
2018-04-09 21:41:55.81 UTC
null
null
null
jcoby
2,884
null
1
91
ruby-on-rails|ruby|soap
87,574
<p>We used the built in <code>soap/wsdlDriver</code> class, which is actually SOAP4R. It's dog slow, but really simple. The SOAP4R that you get from gems/etc is just an updated version of the same thing.</p> <p>Example code:</p> <pre><code>require 'soap/wsdlDriver' client = SOAP::WSDLDriverFactory.new( 'http://example.com/service.wsdl' ).create_rpc_driver result = client.doStuff(); </code></pre> <p>That's about it</p>
342,365
What should coding guidelines do, and are there any good examples of guidelines?
<p>What are some good examples of coding guidelines. I'm not really looking for anything specific to a single language.</p> <p>But what should I be doing/evaluating as I write coding guidelines? Such as how flexible should the guidelines and how much should decisions be left to the programmer or to someone else or even pre-decided by the guidelines.</p> <p>This set of guidelines that I am working on is supposed to cover a wide range of topics: comments, database design, and even some user interface guidelines.</p>
342,704
11
1
null
2008-12-04 22:45:43.633 UTC
15
2009-05-25 15:33:58.417 UTC
null
null
null
jtyost2
657
null
1
8
language-agnostic|user-interface|coding-style
1,311
<p>There are generally three purposes for coding standards:</p> <ul> <li>Reduce the likelihood of bugs</li> <li>Reduce the time required to analyze code written by someone else</li> <li>Give someone a power trip</li> </ul> <p>Obviously, the third is a waste of everyone else's time, but you do need to consider it, specifically so you <em>don't</em> go down that road.</p> <p>Having said that, there are some definite do's and dont's that I've noticed:</p> <ul> <li>Enforce consistent whitespace usage. Tabs, 2-spaces, 4-spaces, doesn't matter. Keep it consistent, so indent levels aren't screwed up by people using different editors. I've seen mistakes made because maintenance programmers misinterpreted the nesting level of a block of code.</li> <li>Enforce consistent logging methodology. It's a huge drain on support staff's time if they aren't able to skim over logs, because everyone's module logs for different reasons, and everyone has a different definition of Info vs. Warning vs. Error.</li> <li>Enforce consistent error handling. If module A throws exceptions, module B returns error codes, and module C simply logs and moves on, it'll be a pain to integrate them without letting an error slip through the cracks.</li> <li>Try to avoid petty things like placement of curly-braces. That's going to get a lot of people arguing over their pet style, and in the end, it really doesn't have a huge impact on the readability of code. On the other hand, enforcing the <em>presence</em> of brackets can make a difference.</li> <li>When integrating disparate code bases, don't be tempted to change everyone's variable naming conventions to match the golden standard. You may have a standard for moving forward, but what's most important is that any localized standards that already exist are preserved consistently. If one module uses <code>m_member</code>, a maintenance programmer should be using <code>m_member2</code> rather than applying any other standard (such as <code>member2_</code> or <code>m_lpcstrMember2</code> or whatever). Local consistency is king.</li> <li>Filesystem layout is important. Keep it consistent. Make it easy for someone to jump into a library sourcebase and instantly know where are the headers, the Makefile, the sources, etc. If you're working with Java or Python, this is a no-brainer because the package system enforces it. If you're working with C, C++, or any other myriad of scripting languages, you'll need to devise a standard layout yourself and stick with it.</li> <li>Don't sweat the little stuff. Variable naming conventions, spaces between parentheses or keywords or function names... most of that doesn't matter, because it doesn't reduce the likelihood of a mistake. Every rule you set should have a concrete rationale, and you shouldn't be afraid to change or remove it if you discover it's causing more grief than it's worth.</li> <li>Don't enforce gratuitous comment blocks everywhere. They'll end up as a waste, and most comments are better off being expressed in the code itself (as variable or function names, for example).</li> </ul> <p>Finally, the most important thing is to have regular code reviews between peers. Encourage people to speak up when they see a "code smell." Also be sure people realize that constructive code criticism is not meant to be personal - the source is shared by everone on the team, it doesn't just belong to the original author. In my experience, the most heinous problems have been design problems that wouldn't have been solved by any amount of coding guidelines. Software design is still something of an art form (for better or for worse), and a pool of brains is much better than a single one.</p>
448,206
Detecting if a string is all CAPS
<p>In C# is there a way to detect if a string is all caps?</p> <p>Most of the strings will be short(ie under 100 characters)</p>
448,225
11
6
null
2009-01-15 19:52:05.81 UTC
8
2018-10-31 20:11:26.427 UTC
2009-01-16 21:41:16.863 UTC
StubbornMule
13,341
StubbornMule
13,341
null
1
67
c#|string
53,296
<p>No need to create a new string:</p> <pre><code>bool IsAllUpper(string input) { for (int i = 0; i &lt; input.Length; i++) { if (!Char.IsUpper(input[i])) return false; } return true; } </code></pre> <p><strong>Edit:</strong> If you want to skip non-alphabetic characters (<em>The OP's original implementation does not, but his/her comments indicate that they might want to</em>) :</p> <pre><code> bool IsAllUpper(string input) { for (int i = 0; i &lt; input.Length; i++) { if (Char.IsLetter(input[i]) &amp;&amp; !Char.IsUpper(input[i])) return false; } return true; } </code></pre>
306,313
"is" operator behaves unexpectedly with integers
<p>Why does the following behave unexpectedly in Python?</p> <pre><code>&gt;&gt;&gt; a = 256 &gt;&gt;&gt; b = 256 &gt;&gt;&gt; a is b True # This is an expected result &gt;&gt;&gt; a = 257 &gt;&gt;&gt; b = 257 &gt;&gt;&gt; a is b False # What happened here? Why is this False? &gt;&gt;&gt; 257 is 257 True # Yet the literal numbers compare properly </code></pre> <p>I am using Python 2.5.2. Trying some different versions of Python, it appears that Python 2.3.3 shows the above behaviour between 99 and 100.</p> <p>Based on the above, I can hypothesize that Python is internally implemented such that "small" integers are stored in a different way than larger integers and the <code>is</code> operator can tell the difference. Why the leaky abstraction? What is a better way of comparing two arbitrary objects to see whether they are the same when I don't know in advance whether they are numbers or not?</p>
306,353
11
3
null
2008-11-20 18:21:16.603 UTC
203
2021-03-18 16:08:30.997 UTC
2019-11-09 23:59:37.643 UTC
null
4,518,341
Greg Hewgill
893
null
1
600
python|int|operators|identity|python-internals
98,326
<p>Take a look at this:</p> <pre><code>&gt;&gt;&gt; a = 256 &gt;&gt;&gt; b = 256 &gt;&gt;&gt; id(a) 9987148 &gt;&gt;&gt; id(b) 9987148 &gt;&gt;&gt; a = 257 &gt;&gt;&gt; b = 257 &gt;&gt;&gt; id(a) 11662816 &gt;&gt;&gt; id(b) 11662828 </code></pre> <p>Here's what I found in the Python 2 documentation, <a href="https://docs.python.org/2/c-api/int.html" rel="noreferrer">"Plain Integer Objects"</a> (It's the same for <a href="https://docs.python.org/3/c-api/long.html" rel="noreferrer">Python 3</a>):</p> <blockquote> <p>The current implementation keeps an array of integer objects for all integers between -5 and 256, when you create an int in that range you actually just get back a reference to the existing object. So it should be possible to change the value of 1. I suspect the behaviour of Python in this case is undefined. :-)</p> </blockquote>
1,222,713
how do I create a line of arbitrary thickness using Bresenham?
<p>I am currently using Bresenham's algorithm to draw lines but they are (of course) one pixel in thickness. My question is what is the most efficient way to draw lines of arbitrary thickness? </p> <p>The language I am using is C.</p>
1,222,785
12
3
null
2009-08-03 14:37:02.963 UTC
15
2021-06-01 13:19:07.243 UTC
2012-08-30 18:52:39.953 UTC
null
50,776
null
66,725
null
1
34
algorithm|graphics
24,699
<p>I think the best way is to draw a rectangle rather than a line since a line with width is a two dimensional object. Tring to draw a set of parallel lines to avoid overdraw (to reduce write bandwidth) and underdraw (missing pixels) would be quite complex. It's not too hard to calculate the corner points of the rectangle from the start and end point and the width.</p> <p>So, following a comment below, the process to do this would be:-</p> <ol> <li>Create a rectangle the same length as the required line and width equal to the desired width, so (0,0) to (width,length)</li> <li>Rotate and translate the rectangles corner coordinates to the desired position using a 2D transformation</li> <li>Rasterise the rotated rectangle, either using a hardware accelerated renderer (an OpenGL quad for example*) or use a software rasteriser. It can be rendered using a quad rasteriser or as a pair of triangles (top left and bottom right for example).</li> </ol> <p>Note *: If you're using OpenGL you can also do Step 2 at the same time. Of course, using OpenGL does mean understanding OpenGL (big and complex) and this application may make that a tricky thing to implement at such a late stage in development.</p>
623,458
Rails select helper - Default selected value, how?
<p>Here is a piece of code I'm using now:</p> <pre><code>&lt;%= f.select :project_id, @project_select %&gt; </code></pre> <p>How to modify it to make its default value equal to to <code>params[:pid]</code> when page is loaded?</p>
629,080
15
1
null
2009-03-08 11:49:42.713 UTC
44
2019-12-17 21:03:25.813 UTC
2015-10-27 11:48:01.513 UTC
null
2,202,702
totocaster
27,257
null
1
194
ruby-on-rails
204,728
<p>This should do it:</p> <pre><code>&lt;%= f.select :project_id, @project_select, :selected =&gt; params[:pid] %&gt; </code></pre>
839,178
Why is Java's Iterator not an Iterable?
<p>Why does the <code>Iterator</code> interface not extend <code>Iterable</code>?</p> <p>The <code>iterator()</code> method could simply return <code>this</code>.</p> <p>Is it on purpose or just an oversight of Java's designers?</p> <p>It would be convenient to be able to use a for-each loop with iterators like this:</p> <pre><code>for(Object o : someContainer.listSomeObjects()) { .... } </code></pre> <p>where <code>listSomeObjects()</code> returns an iterator.</p>
839,192
16
3
null
2009-05-08 10:19:43.387 UTC
37
2020-03-09 09:40:08.173 UTC
2012-10-28 12:21:24.587 UTC
null
967,945
null
24,028
null
1
186
java|iterator|iterable
51,385
<p>Because an iterator generally points to a single instance in a collection. Iterable implies that one may obtain an iterator from an object to traverse over its elements - and there's no need to iterate over a single instance, which is what an iterator represents.</p>
107,701
How can I Remove .DS_Store files from a Git repository?
<p>How can I remove those annoying Mac OS X <code>.DS_Store</code> files from a Git repository?</p>
107,921
28
2
null
2008-09-20 09:15:50.033 UTC
653
2022-08-10 10:13:57.97 UTC
2014-12-20 15:45:30.29 UTC
null
2,541,573
John Topley
1,450
null
1
1,595
macos|git|gitignore
893,116
<p>Remove existing <code>.DS_Store</code> files from the repository:</p> <pre><code>find . -name .DS_Store -print0 | xargs -0 git rm -f --ignore-unmatch </code></pre> <p>Add this line:</p> <pre><code>.DS_Store </code></pre> <p>to the file <code>.gitignore</code>, which can be found at the top level of your repository (or create the file if it isn't there already). You can do this easily with this command in the top directory:</p> <pre><code>echo .DS_Store &gt;&gt; .gitignore </code></pre> <p>Then commit the file to the repo:</p> <pre><code>git add .gitignore git commit -m '.DS_Store banished!' </code></pre>