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
68,473,542
MediaSessionCompat:Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent
<p>I'm trying to update my application to Android SDK 31 but I'm having an issue with MediaSessionCompat.</p> <p>I have a MediaService that extends the MediaBrowserServiceCompat() and in method onCreate of that service I initialise the MediaSessionCompat.</p> <pre><code>override fun onCreate() { super.onCreate() mediaSession = MediaSessionCompat(this, TAG).apply { setCallback(mediaSessionCallback) isActive = true } ... </code></pre> <p>But I'm having the following error</p> <pre><code>java.lang.RuntimeException: Unable to create service com.radio.core.service.MediaService: java.lang.IllegalArgumentException: com.xxx.xxx: Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent. Strongly consider using FLAG_IMMUTABLE, only use FLAG_MUTABLE if some functionality depends on the PendingIntent being mutable, e.g. if it needs to be used with inline replies or bubbles. at android.app.ActivityThread.handleCreateService(ActivityThread.java:4498) at android.app.ActivityThread.access$1500(ActivityThread.java:250) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2064) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loopOnce(Looper.java:201) at android.os.Looper.loop(Looper.java:288) at android.app.ActivityThread.main(ActivityThread.java:7829) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:982) Caused by: java.lang.IllegalArgumentException: com.xxx.xxx: Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent. Strongly consider using FLAG_IMMUTABLE, only use FLAG_MUTABLE if some functionality depends on the PendingIntent being mutable, e.g. if it needs to be used with inline replies or bubbles. at android.app.PendingIntent.checkFlags(PendingIntent.java:375) at android.app.PendingIntent.getBroadcastAsUser(PendingIntent.java:645) at android.app.PendingIntent.getBroadcast(PendingIntent.java:632) at android.support.v4.media.session.MediaSessionCompat.&lt;init&gt;(MediaSessionCompat.java:567) at android.support.v4.media.session.MediaSessionCompat.&lt;init&gt;(MediaSessionCompat.java:537) at android.support.v4.media.session.MediaSessionCompat.&lt;init&gt;(MediaSessionCompat.java:501) at android.support.v4.media.session.MediaSessionCompat.&lt;init&gt;(MediaSessionCompat.java:475) at com.radio.core.service.MediaService.onCreate(MediaService.kt:63) at android.app.ActivityThread.handleCreateService(ActivityThread.java:4485) ... 9 more </code></pre> <p>I'm using the most recent version of media library (&quot;androidx.media:media:1.4.0&quot;) that is able to handle the this requirement from the Andriod &quot;S&quot;&quot;. As it's possible to see in the MediaSessionCompact.java class.</p> <pre><code> // TODO(b/182513352): Use PendingIntent.FLAG_MUTABLE instead from S. /** * @hide */ @RestrictTo(LIBRARY) public static final int PENDING_INTENT_FLAG_MUTABLE = Build.VERSION.CODENAME.equals(&quot;S&quot;) ? 0x02000000 : 0; ... if (mbrComponent != null &amp;&amp; mbrIntent == null) { // construct a PendingIntent for the media button Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON); // the associated intent will be handled by the component being registered mediaButtonIntent.setComponent(mbrComponent); mbrIntent = PendingIntent.getBroadcast(context, 0/* requestCode, ignored */, mediaButtonIntent, PENDING_INTENT_FLAG_MUTABLE); } </code></pre> <p>Source code demonstrating the problem - <a href="https://github.com/adelinolobao/issue-media-session-compat" rel="noreferrer">https://github.com/adelinolobao/issue-media-session-compat</a></p> <p>Do you guys have any idea how can I fix the error?</p>
69,152,986
12
6
null
2021-07-21 16:51:07.72 UTC
17
2022-09-16 18:48:19.563 UTC
2021-07-27 21:18:18.263 UTC
null
650,700
null
650,700
null
1
112
java|android|android-studio|kotlin|android-mediaplayer
60,622
<p>If you are NOT USING <code>PendingIntent</code> anywhere. The issue might be resolved by adding or updating this dependency</p> <pre><code> // required to avoid crash on Android 12 API 31 implementation 'androidx.work:work-runtime-ktx:2.7.0' </code></pre> <p>This fixed my problem.</p>
24,908,686
jQuery open page in a new tab while passing POST data
<p>I have a javascript variable called "list". I need to <strong>send it as a POST data to another page and open that page in a new tab</strong> (with the POST data present).</p> <p>This code:</p> <pre><code>jQuery.post('datadestination.php', list); </code></pre> <p>sends the data all right, but ofcourse it opens the page in the same tab.</p> <p>I saw some solutions to similar problems using invisible form and things like that, but I could not get them to work. Is there any simple solution?</p>
24,908,861
3
2
null
2014-07-23 11:00:53.08 UTC
2
2017-06-10 10:56:21.717 UTC
null
null
null
null
2,042,602
null
1
21
javascript|php|jquery
52,439
<p>1) Why not to pass that list with the <code>jquery.post()</code> function and save it in the <code>SESSION</code> array;</p> <p>2) Then open a new tab with the same file/address/url with the <code>window.open()</code> function;</p> <p>3) Retrieve saved data from the <code>SESSION</code> array;</p> <p>Seems a straightforward and clean way?</p>
45,100,271
Scope of variable within "with" statement?
<p>I am reading only <code>firstline</code> from python using :</p> <pre><code>with open(file_path, 'r') as f: my_count = f.readline() print(my_count) </code></pre> <p>I am bit confused over scope of variable my_count. Although prints work fine, would it be better to do something like <code>my_count = 0</code> outside with statement first (for eg in C in used to do int <code>my_count = 0</code>)</p>
45,100,308
2
2
null
2017-07-14 10:07:12.403 UTC
17
2017-07-14 10:59:50.983 UTC
2017-07-14 10:59:50.983 UTC
null
67,579
null
6,026,051
null
1
73
python|scope|with-statement
26,634
<p>A <code>with</code> statement does <strong>not create a scope</strong> (like <code>if</code>, <code>for</code> and <code>while</code> do not create a scope either).</p> <p>As a result, Python will analyze the code and see that you made an assignment in the <code>with</code> statement, and thus that will make the variable local (to the real scope).</p> <p>In Python variables do not need <em>initialization</em> in <em>all code paths</em>: as a programmer, you are responsible to make sure that a variable is assigned before it is used. This can result in shorter code: say for instance you know for sure that a list contains at least one element, then you can assign in a <code>for</code> loop. In Java assignment in a <code>for</code> loop is not considered safe (since it is possible that the body of the loop is never executed).</p> <p>Initialization <em>before</em> the <code>with</code> scope can be safer in the sense that after the <code>with</code> statement we can safely assume that the variable exists. If on the other hand the variable <em>should</em> be assigned in the <code>with</code> statement, not initializing it before the <code>with</code> statement actually results in an additional check: Python will error if somehow the assignment was skipped in the <code>with</code> statement.</p> <p>A with statement is only used for context management purposes. It forces (by syntax) that the context you open in the <code>with</code> is closed at the end of the indentation.</p>
1,237,078
how to develop internet explorer add-on
<p>Can we create add-on for IE? If yes where can i find required resources/docs?</p>
1,237,081
5
0
null
2009-08-06 05:11:20.783 UTC
13
2018-12-15 18:45:45.627 UTC
2009-08-06 05:24:04.047 UTC
null
70,482
null
135,464
null
1
14
internet-explorer|add-on|ieaddon
18,930
<p>Some references,</p> <ul> <li>At MSDN blogs -- <a href="http://blogs.msdn.com/petel/archive/2006/11/07/writing-ie-addons.aspx" rel="noreferrer"><strong>Writing IE AddOns</strong></a>,</li> <li>The Business of Software <a href="http://discuss.joelonsoftware.com/default.asp?biz.5.736647.8" rel="noreferrer">recent discussion</a></li> </ul> <p><a href="http://blogs.msdn.com/ie/archive/2006/04/25/583369.aspx" rel="noreferrer"><strong>A New IE Add-on Site</strong></a> -- <a href="http://www.ieaddons.com/en/" rel="noreferrer">reference</a>.</p> <blockquote> <p>The site has two objectives: to make it easier for users to find valuable add-ons and to promote our partners who develop add-ons.</p> <p>You can have your add-on included by submitting it through the Internet Explorer Add-on site and you no longer have to be a member of the Microsoft Partner program to be included.</p> </blockquote> <hr /> <p><a href="http://addoncon.com/blog/" rel="noreferrer">Add-on-CON</a> blog.</p>
1,014,053
Why don't I declare NSInteger with a *
<p>I'm trying my hand at the iPhone course from Stanford on iTunes U and I'm a bit confused about pointers. In the first assignment, I tried doing something like this</p> <pre><code>NSString *processName = [[NSProcessInfo processInfo] processName]; NSInteger *processID = [[NSProcessInfo processInfo] processIdentifier]; </code></pre> <p>Which generated an error, after tinkeing around blindly, I discovered that it was the * in the NSInteger line that was causing the problem. </p> <p>So I obviously don't understand what's happening. I'll explain how I think it works and perhaps someone would be kind enough to point out the flaw. </p> <blockquote> <p>Unlike in web development, I now need to worry about memory, well, more so than in web development. So when I create a variable, it gets allocated a bit of memory somewhere (RAM I assume). Instead of passing the variable around, I pass a pointer to that bit of memory around. And pointers are declared by prefixing the variable name with *.</p> </blockquote> <p>Assuming I'm right, what puzzles me is why don't I need to do that for NSInteger?</p>
1,014,078
5
0
null
2009-06-18 17:29:21.957 UTC
10
2019-05-01 15:35:45.503 UTC
null
null
null
null
64,586
null
1
42
objective-c|cocoa|pointers|integer|nsinteger
33,342
<p><code>NSInteger</code> is a primitive type, which means it <strong>can be stored locally on the stack</strong>. You don't need to use a pointer to access it, but you can if you want to. The line:</p> <pre><code>NSInteger *processID = [[NSProcessInfo processInfo] processIdentifier]; </code></pre> <p>returns an actual variable, not its address. To fix this, you need to remove the <code>*</code>:</p> <pre><code>NSInteger processID = [[NSProcessInfo processInfo] processIdentifier]; </code></pre> <p>You can have a pointer to an <code>NSInteger</code> if you really want one:</p> <pre><code>NSInteger *pointerToProcessID = &amp;processID; </code></pre> <p>The ampersand is the address of operator. It sets the pointer to the <code>NSInteger</code> equal to the address of the variable in memory, rather than to the integer in the variable.</p>
1,301,508
Change textbox's css class when ASP.NET Validation fails
<p>How can I execute some javascript when a Required Field Validator attached to a textbox fails client-side validation? What I am trying to do is change the css class of the textbox, to make the textbox's border show red.</p> <p>I am using webforms and I do have the jquery library available to me.</p>
1,301,709
6
0
null
2009-08-19 17:41:52.967 UTC
8
2013-09-18 01:45:36.36 UTC
2009-11-12 02:36:28.483 UTC
null
30,460
null
30,460
null
1
21
asp.net|javascript|jquery|validation|webforms
40,820
<p>Here is quick and dirty thing (but it works!)</p> <pre><code>&lt;form id="form1" runat="server"&gt; &lt;asp:TextBox ID="txtOne" runat="server" /&gt; &lt;asp:RequiredFieldValidator ID="rfv" runat="server" ControlToValidate="txtOne" Text="SomeText 1" /&gt; &lt;asp:TextBox ID="txtTwo" runat="server" /&gt; &lt;asp:RequiredFieldValidator ID="rfv2" runat="server" ControlToValidate="txtTwo" Text="SomeText 2" /&gt; &lt;asp:Button ID="btnOne" runat="server" OnClientClick="return BtnClick();" Text="Click" CausesValidation="true" /&gt; &lt;/form&gt; &lt;script type="text/javascript"&gt; function BtnClick() { //var v1 = "#&lt;%= rfv.ClientID %&gt;"; //var v2 = "#&lt;%= rfv2.ClientID %&gt;"; var val = Page_ClientValidate(); if (!val) { var i = 0; for (; i &lt; Page_Validators.length; i++) { if (!Page_Validators[i].isvalid) { $("#" + Page_Validators[i].controltovalidate) .css("background-color", "red"); } } } return val; } &lt;/script&gt; </code></pre>
432,933
Will HTML 5 validation be worth the candle?
<p>It's widely considered that the best reason to validate one's HTML is to ensure that all browsers will treat it consistently and predictably. </p> <p>The HTML 5 draft, however, contains two specifications in one. First an author spec, describing the elements and attributes that HTML authors should use, and their interrelationships. Validation of an HTML 5 page is based on this spec. The elements and attributes included are not directly drawn from HTML 4, but have needed to be justified from first principles, which means that some HTML 4 features, such as the summary attribute on &lt;table&gt;, longdesc on &lt;img&gt; and the profile attribute on &lt;head&gt;, do not currently appear in this draft. Such features are not considered deprecated, they are simply not included. (Their absence from the draft remains a matter of dispute, although their inclusion any time soon does not seem likely.)</p> <p>Second, the draft defines a browser processing specification that seeks to define exactly how a browser's parser will treat any byte stream it's given, regardless of how well formed and valid the HTML. This means that when the browsers fully support HTML 5, it will be possible to predict how any browser will treat HTML for a much wider range of inputs than merely those that pass validation.</p> <p>In particular, because HTML 5 is defined to be 100% backward compatible with today's web, all valid HTML 4, and all invalid but commonly used mark-up, will continue to be processed exactly the same as it is today, regardless of whether it is HTML 5 valid or not.</p> <p>Therefore, at the very minimum, anyone using any feature from HTML 5, HTML 4, or any previous version of HTML, plus many proprietary extensions, can be confident that their HTML will get consistent and predictable treatment across all browsers.</p> <p>Given this, does it make any sense to limit ones HTML 5 to that which will validate, and what practical benefit will we get from doing so?</p>
446,732
6
7
null
2009-01-11 13:35:56.96 UTC
10
2015-02-27 00:18:45.577 UTC
2011-06-21 13:15:41.597 UTC
null
166,339
Alohci
42,585
null
1
29
html
9,459
<ul> <li>First there’s the layer of validity corresponding to “parse errors” in the <a href="http://www.whatwg.org/specs/web-apps/current-work/#parsing" rel="noreferrer">HTML5 parsing algorithm</a>. This layer is similar to XML well-formedness. The foremost reason to avoid having errors in your documents on this layer is that you may get a surprising parse tree. If your document is error-free on this layer, you get fewer suprises to debug when writing JS or CSS that works with the DOM.</li> <li>As a special case of the above-mentioned layer, there’s the HTML5 doctype: <code>&lt;!DOCTYPE html&gt;</code>. The reason why one would want to comply here is getting the standards mode in the easiest way possible. It’s something you can memorize unlike the HTML 4.01 or XHTML 1.0 doctypes you need to look up and copy and paste each time. Of course, the reason why you’d want the standards mode is fewer surprises on the CSS layer.</li> <li>The main reason to care about validation on the layer higher than the parsing algorithm is catching your typos so that you spend less time debugging why your page isn’t working like you are expecting.</li> <li>The previous point does not explain why you should care about validation when a given element or attribute that you did not misspell is supported by browsers as a matter of legacy but the HTML5 spec still shuns it. Here’s why HTML5 has obsoleted syntax like this: <ul> <li>HTML5 uses obsoletion to signal to authors that some features are a waste of their time. These include <code>longdesc</code>, <code>summary</code> and <code>profile</code>. (Note that people disagree on whether these are, indeed, waste of time, but as currently drafted, HTML5 makes them obsolete.) That is, if you have limited resources to improve accessibility, your limited resources are better spent on something other than <code>longdesc</code> and <code>summary</code>. If you have limited resources for semantic purity, your resources are better spent on something other than making sure you have the right incantation in <code>profile</code>.</li> <li>HTML5 obsoletes some presentational features that can be duplicated in CSS to guide authors to use CSS for their own good. This way, authors who don’t consider maintainability on their own are supposed to be guided to more maintainable code nonetheless. Personally, I’d prefer making more of the legacy presentational stuff conforming and leaving it to authors themselves to decide which way of doing things works for them.</li> <li>Some things are obsoleted for political reasons. The <code>&lt;font&gt;</code> element is obsoleted, because making it conforming would make anti-<code>&lt;font&gt;</code> standardistas think that the HTML5 people have gone crazy, which could lead to bad PR. <code>&lt;applet&gt;</code> is obsoleted mainly as a matter of principle of not giving special markup to one particular plug-in. The <code>classid</code> attribute on <code>&lt;object&gt;</code> is obsoleted, because it’s in practice ActiveX-specific.</li> <li>Some things are obsoleted on the basis of language design aesthetics. This includes the <code>name</code> attribute on <code>&lt;a&gt;</code> and the <code>language</code> attribute on <code>&lt;script&gt;</code>.</li> </ul></li> </ul> <p>(I develop the Validator.nu HTML5 validator which is also the HTML5 validation engine used by the W3C validator.)</p>
241,250
Single Table Inheritance in Django
<p>Is there explicit support for Single Table Inheritance in Django? Last I heard, the feature was still under development and debate. </p> <p>Are there libraries/hacks I can use in the meantime to capture the basic behavior? I have a hierarchy that mixes different objects. The canonical example of a corporation structure with an Employee class, subclasses for types of employees, and a manager_id (parent_id) would be a good approximation of the problem I am solving. </p> <p>In my case, I would like to represent the idea that an employee can manage other employees while being managed by a different employee. There are not separate classes for Manager and Worker, which makes this hard to spread across tables. Sub-classes would represent types of employees-programmers, accountants, sales, etc and would be independent of who supervises who (OK, I guess it's no longer a typical corporation in some respect). </p>
243,543
6
1
null
2008-10-27 20:18:08.133 UTC
10
2021-07-08 08:58:15.86 UTC
2008-10-27 21:42:07.653 UTC
thaiyoshi
1,227,001
thaiyoshi
1,227,001
null
1
35
python|django|django-models|single-table-inheritance
15,318
<p>There are currently two forms of inheritance in Django - MTI (model table inheritance) and ABC (abstract base classes).</p> <p>I wrote a <a href="http://web.archive.org/web/20090227074910/http://thisweekindjango.com/articles/2008/jun/17/abstract-base-classes-vs-model-tab/" rel="noreferrer">tutorial</a> on what's going on under the hood.</p> <p>You can also reference the official docs on <a href="http://docs.djangoproject.com/en/dev/topics/db/models/#model-inheritance" rel="noreferrer">model inheritance</a>.</p>
204,505
Preserving order with LINQ
<p>I use LINQ to Objects instructions on an ordered array. Which operations shouldn't I do to be sure the order of the array is not changed?</p>
204,777
6
0
null
2008-10-15 12:20:13.293 UTC
172
2019-10-23 20:38:23.117 UTC
2017-08-11 17:41:34.35 UTC
Matthieu Durut
2,370,483
Matthieu Durut
28,216
null
1
397
c#|arrays|linq|sorting|data-structures
65,308
<p>I examined the methods of <a href="http://msdn.microsoft.com/en-us/library/system.linq.enumerable_methods.aspx" rel="noreferrer">System.Linq.Enumerable</a>, discarding any that returned non-IEnumerable results. I checked the remarks of each to determine how the order of the result would differ from order of the source.</p> <p>Preserves Order Absolutely. You can map a source element by index to a result element</p> <ul> <li>AsEnumerable</li> <li>Cast</li> <li>Concat</li> <li>Select</li> <li>ToArray</li> <li>ToList</li> </ul> <p>Preserves Order. Elements are filtered or added, but not re-ordered.</p> <ul> <li>Distinct</li> <li>Except</li> <li>Intersect</li> <li>OfType</li> <li>Prepend (new in .net 4.7.1)</li> <li>Skip</li> <li>SkipWhile</li> <li>Take</li> <li>TakeWhile</li> <li>Where</li> <li>Zip (new in .net 4)</li> </ul> <p>Destroys Order - we don't know what order to expect results in.</p> <ul> <li>ToDictionary</li> <li>ToLookup</li> </ul> <p>Redefines Order Explicitly - use these to change the order of the result</p> <ul> <li>OrderBy</li> <li>OrderByDescending</li> <li>Reverse</li> <li>ThenBy</li> <li>ThenByDescending</li> </ul> <p>Redefines Order according to some rules.</p> <ul> <li>GroupBy - The IGrouping objects are yielded in an order based on the order of the elements in source that produced the first key of each IGrouping. Elements in a grouping are yielded in the order they appear in source. </li> <li>GroupJoin - GroupJoin preserves the order of the elements of outer, and for each element of outer, the order of the matching elements from inner.</li> <li>Join - preserves the order of the elements of outer, and for each of these elements, the order of the matching elements of inner. </li> <li>SelectMany - for each element of source, selector is invoked and a sequence of values is returned.</li> <li>Union - When the object returned by this method is enumerated, Union enumerates first and second in that order and yields each element that has not already been yielded. </li> </ul> <hr> <p>Edit: I've moved Distinct to Preserving order based on this <a href="https://github.com/dotnet/corefx/blob/master/src/System.Linq/src/System/Linq/Enumerable.cs" rel="noreferrer">implementation</a>.</p> <pre><code> private static IEnumerable&lt;TSource&gt; DistinctIterator&lt;TSource&gt; (IEnumerable&lt;TSource&gt; source, IEqualityComparer&lt;TSource&gt; comparer) { Set&lt;TSource&gt; set = new Set&lt;TSource&gt;(comparer); foreach (TSource element in source) if (set.Add(element)) yield return element; } </code></pre>
42,318,781
How to configure NDK for Android Studio
<p>I've installed Android Studio 2.2.3 and created a "myApplication" with <code>include C++ support</code>. I get this error: </p> <p><em>Error:NDK not configured.<br> Download it with SDK manager.)</em></p> <p>Is there any good way to solve it please?</p>
42,324,530
1
3
null
2017-02-18 18:04:58.25 UTC
4
2017-02-19 06:56:20.963 UTC
null
null
null
null
4,989,541
null
1
18
android-studio|android-ndk|android-sdk-2.3
54,261
<p>Once you have downloaded the NDK, go to "File" menu, than "Project Structure->SDK Location" and set the Android NDK Location (it is at the bottom of the window).</p>
31,008,598
Python check if a directory exists, then create it if necessary and save graph to new directory?
<p>so I want this to be independent of the computer the code is used on, so I want to be able to create a directory in the current directory and save my plots to that new file. I looked at some other questions and tried this (I have two attempts, one commented out): </p> <pre><code> import os from os import path #trying to make shift_graphs directory if it does not already exist: if not os.path.exists('shift_graphs'): os.mkdirs('shift_graphs') plt.title('Shift by position on '+str(detector_num)+'-Detector') #saving figure to shift_graphs directory plt.savefig(os.path.join('shift_graphs','shift by position on '+str(detector_num)+'-detector')) print "plot 5 done" plt.clf </code></pre> <p>I get the error : </p> <pre><code>AttributeError: 'module' object has no attribute 'mkdirs' </code></pre> <p>I also want to know if my idea of saving it in the directory will work, which I haven't been able to test because of the errors I've been getting in the above portion. </p>
31,008,705
2
3
null
2015-06-23 16:40:13.573 UTC
2
2020-03-11 11:29:51.427 UTC
2020-01-13 02:35:51.117 UTC
null
347,646
null
5,040,956
null
1
32
python
93,589
<p><code>os.mkdirs()</code> is not a method in os module. if you are making only one direcory then use <code>os.mkdir()</code> and if there are multiple directories try using <code>os.makedirs()</code> Check <a href="https://docs.python.org/2/library/os.html#os.makedirs" rel="noreferrer">Documentation</a></p>
39,377,807
Strange Terminal Messages in Xcode 8
<p>Recently, I have updated my Xcode version to 8. When I start and run an entirely new project, I get the following messages in my terminal.</p> <pre><code>2016-09-07 15:28:43.759998 App[7932:128675] subsystem: com.apple.UIKit, category: HIDEventFiltered, enable_level: 0, persist_level: 0, default_ttl: 0, info_ttl: 0, debug_ttl: 0, generate_symptoms: 0, enable_oversize: 1, privacy_setting: 2, enable_private_data: 0 2016-09-07 15:28:43.762544 App[7932:128675] subsystem: com.apple.UIKit, category: HIDEventIncoming, enable_level: 0, persist_level: 0, default_ttl: 0, info_ttl: 0, debug_ttl: 0, generate_symptoms: 0, enable_oversize: 1, privacy_setting: 2, enable_private_data: 0 2016-09-07 15:28:43.790817 App[7932:128648] subsystem: com.apple.BaseBoard, category: MachPort, enable_level: 1, persist_level: 0, default_ttl: 0, info_ttl: 0, debug_ttl: 0, generate_symptoms: 0, enable_oversize: 0, privacy_setting: 0, enable_private_data: 0 2016-09-07 15:28:43.827962 App[7932:128496] subsystem: com.apple.UIKit, category: StatusBar, enable_level: 0, persist_level: 0, default_ttl: 0, info_ttl: 0, debug_ttl: 0, generate_symptoms: 0, enable_oversize: 1, privacy_setting: 2, enable_private_data: 0 2016-09-07 15:28:43.998975 App[7932:128496] subsystem: com.apple.BackBoardServices.fence, category: App, enable_level: 1, persist_level: 0, default_ttl: 0, info_ttl: 0, debug_ttl: 0, generate_symptoms: 0, enable_oversize: 0, privacy_setting: 0, enable_private_data: 0 </code></pre> <p>Can anyone explain what these mean/why they are here?</p> <p>PS: I have never gotten these types of messages with Xcode 7.</p>
39,497,714
1
8
null
2016-09-07 19:37:55.56 UTC
12
2016-11-19 07:26:35.87 UTC
2016-09-29 19:08:05.493 UTC
null
5,943,218
null
5,943,218
null
1
50
ios|swift3|xcode8
8,095
<p>Go to <strong>Product => Scheme => Edit Scheme</strong> or use shortcut: <strong>CMD + &lt;</strong></p> <p>Add <code>OS_ACTIVITY_MODE</code> as <code>disable</code></p> <p><a href="https://i.stack.imgur.com/vUxuE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vUxuE.png" alt="enter image description here"></a></p> <p>And i use this answer: <a href="https://stackoverflow.com/questions/37800790/hide-xcode-8-logs">hide-xcode-8-logs</a> from @iDevzilla to solve this:</p> <blockquote> <p>Try this: On your Environment Variables set OS_ACTIVITY_MODE = disable <a href="https://i.stack.imgur.com/y8bUj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/y8bUj.png" alt="enter image description here"></a></p> </blockquote>
32,159,724
Scroll to top in RecyclerView with LinearLayoutManager
<p>I have a fragment in which there is <code>RecyclerView</code> with <code>LinearLayoutManager</code> in which there are <code>CardView</code> items. There is a floating action button on clicking which the items should scroll to top. I have tried using <code>scrollToPosition</code> as well as <code>scrollToPositionWithOffset</code> with <code>RecyclerView</code> and also with <code>LinearLayoutManager</code> as shown below. But it has no effect at all. Why is this so? Can anyone please help me out.</p> <p>And i have placed the <code>RecyclerView</code> directly inside the <code>SwipeRefreshView</code> in the xml file. I am calling <code>setFloatingActionButton</code> as soon as set adapter to <code>RecyclerView</code>.</p> <pre><code> public void setFloatingActionButton(final View view) { float = (android.support.design.widget.FloatingActionButton) getActivity().findViewById(R.id.float); float.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mRecyclerView.smoothScrollToPosition(0); android.support.design.widget.Snackbar.make(view, "Scrolled to Top", android.support.design.widget.Snackbar.LENGTH_SHORT) .setAction("Ok", new View.OnClickListener() { @Override public void onClick(View v) { LinearLayoutManager llm = (LinearLayoutManager) mRecyclerView.getLayoutManager(); llm.scrollToPosition(0); } }) .setActionTextColor(getActivity().getResources().getColor(R.color.coloLink)) .show(); } }); } </code></pre>
32,160,022
8
7
null
2015-08-22 19:00:31.273 UTC
13
2022-09-12 18:59:25.757 UTC
2017-04-03 08:20:31.683 UTC
null
2,219,237
null
5,134,052
null
1
92
android|android-recyclerview
95,539
<p>Continuing from above comments, ideally, replacing</p> <pre><code>mRecyclerView.smoothScrollToPosition(0); </code></pre> <p>in the <code>onClick</code> of the floating action button with </p> <pre><code>mLayoutManager.scrollToPositionWithOffset(0, 0); </code></pre> <p>should work. You can also remove the <code>SnackBar</code> code, because you don't need it anyways. So, all in all your above method should look like</p> <pre><code>public void setFloatingActionButton(final View view) { float actionButton = (android.support.design.widget.FloatingActionButton) getActivity() .findViewById(R.id.float); actionButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { LinearLayoutManager layoutManager = (LinearLayoutManager) mRecyclerView .getLayoutManager(); layoutManager.scrollToPositionWithOffset(0, 0); } }); } </code></pre> <p>And if you say that the above doesnt work, then test if the <code>onClick()</code> is even being called or not. Try adding a log message in it and see if its printed.</p>
35,403,769
how to read json file using ansible
<p>I have a json file in the same directory where my ansible script is. Following is the content of json file:</p> <pre><code>{ "resources":[ {"name":"package1", "downloadURL":"path-to-file1" }, {"name":"package2", "downloadURL": "path-to-file2"} ] } </code></pre> <p>I am trying to to download these packages using get_url. Following is the approach:</p> <pre><code>--- - hosts: localhost vars: package_dir: "/var/opt/" version_file: "{{lookup('file','/home/shasha/devOps/tests/packageFile.json')}}" tasks: - name: Printing the file. debug: msg="{{version_file}}" - name: Downloading the packages. get_url: url="{{item.downloadURL}}" dest="{{package_dir}}" mode=0777 with_items: version_file.resources </code></pre> <p>The first task is printing the content of the file correctly but in the second task, I am getting the following error:</p> <pre><code>[DEPRECATION WARNING]: Skipping task due to undefined attribute, in the future this will be a fatal error.. This feature will be removed in a future release. Deprecation warnings can be disabled by setting deprecation_warnings=False in ansible.cfg. </code></pre>
36,730,230
3
3
null
2016-02-15 07:33:32.85 UTC
2
2020-11-10 08:10:14.21 UTC
null
null
null
null
5,315,695
null
1
20
ansible|ansible-2.x
39,772
<p>You have to add a <code>from_json</code> jinja2 filter after the lookup:</p> <pre><code>version_file: "{{ lookup('file','/home/shasha/devOps/tests/packageFile.json') | from_json }}" </code></pre>
35,500,322
Expand and collapse CardView
<p>What is the proper way to expand a CardView?</p> <p><a href="https://i.stack.imgur.com/gaIvd.png" rel="noreferrer"><img src="https://i.stack.imgur.com/gaIvd.png" alt="example"></a></p>
35,503,081
7
4
null
2016-02-19 08:07:09.403 UTC
21
2022-04-02 15:46:34.657 UTC
2017-12-20 17:40:38.863 UTC
null
5,921,859
null
5,921,859
null
1
42
android|android-cardview
74,368
<blockquote> <p>Use an expandable list view with cardview</p> </blockquote> <p><strong>or even</strong></p> <blockquote> <p>You can use <strong>wrap content</strong> as <strong>height</strong> of <strong>cardview</strong> and use <strong>textview</strong> inside it below title, so on click make the textview <strong>visible</strong> and <strong>vice-versa</strong>.</p> </blockquote> <p>but isn't it bad design ?</p> <blockquote> <p>nope it isn't if you give some transition or animation when it's expanded or collapsed</p> <p>If you want to see some default transition then just write <strong>android:animateLayoutChanges=&quot;true&quot;</strong> in <strong>parent layout</strong>.</p> </blockquote>
18,211,645
find sql table name with a particular column
<p>Is their any other way or <code>sql</code> query to find the database table names with a particular column than shown below,</p> <pre><code>SELECT TABLE_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME = 'NameID' </code></pre>
18,224,899
3
7
null
2013-08-13 14:20:06.157 UTC
6
2019-05-22 09:08:15.073 UTC
2013-08-14 06:40:32.09 UTC
null
15,498
null
2,553,267
null
1
32
sql|sql-server
22,798
<p>In SQL Server, you can query <a href="http://technet.microsoft.com/en-us/library/ms176106.aspx" rel="noreferrer"><code>sys.columns</code></a>.</p> <p>Something like:</p> <pre><code> SELECT t.name FROM sys.columns c inner join sys.tables t on c.object_id = t.object_id WHERE c.name = 'NameID' </code></pre> <p>You might want an additional lookup to resolve the schema name, if you have tables in multiple schemas.</p>
17,718,759
How to call another scope function in AngularJS
<p>In AngularJS, I have 2 scope function in the controller, </p> <pre><code>$scope.fn1 = function(){ //do something A }; $scope.fn2 = function(){ //do something B //I want to call fn1 here. }; </code></pre> <p>If my fn2 want to call fn1, how can I do? Thanks!</p>
17,720,581
3
0
null
2013-07-18 08:48:10.583 UTC
4
2017-09-19 13:05:06.263 UTC
null
null
null
null
2,450,397
null
1
48
angularjs-scope
70,120
<p>Since both functions are in the same scope you can simply call <code>$scope.fn1()</code> inside fn2.</p>
69,654,531
Android Emulator keeps quitting when taking screenshots
<p>I can't recall if I have ever tinkered with the settings of Android Emulator, but I've been testing my app on an Android Emulator using Android Studio, and every time I take a screenshot, it crashes.</p> <p>I tried deleting, and wiping, and creating a new Emulator. None of it works. I tried also to take a screenshot without running my app, with a fresh emulator, and the same problem occurs. It just crashes whenever I try to take a picture.</p> <p>Android Studio reports this error:</p> <blockquote> <p>Blockquote WARNING | unexpected system image feature string, emulator might not function correctly, please try updating the emulator. WARNING | cannot add library /Users/sbenati/Library/Android/sdk/emulator/qemu/darwin-x86_64/lib64/vulkan/libvulkan.dylib: failed INFO | configAndStartRenderer: setting vsync to 60 hz INFO | added library /Users/sbenati/Library/Android/sdk/emulator/lib64/vulkan/libvulkan.dylib WARNING | cannot add library /Users/sbenati/Library/Android/sdk/emulator/qemu/darwin-x86_64/lib64/vulkan/libMoltenVK.dylib: failed INFO | added library /Users/sbenati/Library/Android/sdk/emulator/lib64/vulkan/libMoltenVK.dylib INFO | Started GRPC server at 127.0.0.1:8554, security: Local INFO | Advertising in: /Users/sbenati/Library/Caches/TemporaryItems/avd/running/pid_935.ini</p> </blockquote> <p>My machine is a Mac with 32GB of RAM and i7 CPU, so I can't imaging this an issue with system performance.</p> <p>If no one has any suggestions, I will have to just reinstall everything. Thanks for the tips everyone.</p> <p><strong>Edit:</strong></p> <p>I ran this on a new Mac mini I recently acquired, and got this really helpful message. I traced it down to a suggested solution about switching off Vulcan, but it did not work for me.</p> <p><a href="https://i.stack.imgur.com/NCaCW.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/NCaCW.jpg" alt="enter image description here" /></a></p>
69,941,260
2
8
null
2021-10-21 00:38:59.153 UTC
5
2021-12-04 02:28:31.643 UTC
2021-10-26 00:40:18.03 UTC
null
13,952,938
null
13,952,938
null
1
41
android|flutter|android-emulator
3,790
<p>This is a <a href="https://issuetracker.google.com/issues/203692316" rel="noreferrer">known issue</a> and has been fixed in Android Emulator 31.1.1.</p> <p>This version currently isn't marked as stable yet. A workaround:</p> <ul> <li>Switch to the Canary channel in Android Studio</li> <li>Update the emulator</li> <li>Switch back to stable</li> </ul> <p><a href="https://i.stack.imgur.com/digjd.png" rel="noreferrer"><img src="https://i.stack.imgur.com/digjd.png" alt="AS" /></a></p> <p>Update emulator:</p> <p><a href="https://i.stack.imgur.com/c4vwT.png" rel="noreferrer"><img src="https://i.stack.imgur.com/c4vwT.png" alt="AS" /></a></p>
1,442,863
How can I set the Secure flag on an ASP.NET Session Cookie?
<p>How can I set the Secure flag on an ASP.NET Session Cookie, so that it will only be transmitted over HTTPS and never over plain HTTP?</p>
1,442,924
5
0
null
2009-09-18 06:29:10.397 UTC
30
2020-05-19 17:42:20.52 UTC
null
null
null
null
114,916
null
1
161
asp.net-session|ssl-security
220,759
<p>There are two ways, one <code>httpCookies</code> element in <code>web.config</code> allows you to turn on <code>requireSSL</code> which only transmit all cookies including session in SSL only and also inside forms authentication, but if you turn on SSL on httpcookies you must also turn it on inside forms configuration too.</p> <p><strong>Edit for clarity:</strong> Put this in <code>&lt;system.web&gt;</code></p> <pre><code>&lt;httpCookies requireSSL="true" /&gt; </code></pre>
1,866,566
Useful WPF utilities
<p>What are some useful utilities that help you when writing WPF applications? I know about <a href="http://blois.us/Snoop/" rel="noreferrer">Snoop</a> for visual debugging of WPF applications at runtime, and <a href="http://blog.wpfwonderland.com/2008/10/08/shazzam-wpf-pixel-shader-effect-testing-tool-now-available/" rel="noreferrer">Shazzam</a> - a WPF pixel shader effect testing tool.</p> <p>I'd like to know about other such applications and what are they useful at.</p>
1,915,196
6
2
null
2009-12-08 12:09:24.12 UTC
51
2016-01-26 23:37:37.953 UTC
null
null
null
null
147,141
null
1
32
c#|wpf|utilities
12,406
<p>There are whole bunch of tools for WPF, and more and more are popping up as WPF grows in popularity. I have listed a few of the most useful ones below, but it really depends on what you are wanting to achieve.</p> <p>For instance, for me the Sketchflow plugin in Blend has made such a difference. Also, with VS2010 comming to release next year you will see the integration of VS2010 with WPF being a lot more fluid.</p> <p>WPF/XAML Specific Utilities</p> <ul> <li><a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=e82db5e2-7106-419e-80b0-65cce89f06bb&amp;displaylang=en" rel="nofollow noreferrer">Microsoft Blend with Sketchflow - Design &amp; Prototype</a></li> <li><a href="http://msdn.microsoft.com/en-us/library/aa969767.aspx" rel="nofollow noreferrer">Performance Profiling Tools for WPF</a></li> <li><a href="http://blogs.msdn.com/llobo/archive/2008/08/25/xamlpadx-4-0.aspx" rel="nofollow noreferrer">XAMLPadX - Xaml editor</a></li> <li><a href="http://karlshifflett.wordpress.com/xaml-power-toys/" rel="nofollow noreferrer">XAML Power Tools - Plugin for Vs</a></li> <li><a href="http://blois.us/Snoop/" rel="nofollow noreferrer">Snoop - Simplify Visual Debugging </a></li> <li><a href="http://shazzam-tool.com/" rel="nofollow noreferrer">Shazzam - Edit Pixel Shading</a></li> <li><a href="http://karlshifflett.wordpress.com/mole-for-visual-studio/" rel="nofollow noreferrer">Mole - Visualizer With Property Editing</a></li> <li><a href="http://www.kaxaml.com/" rel="nofollow noreferrer">Kaxaml - Lightweight XAML Editor</a> </li> <li><a href="http://www.granthinkson.com/2007/11/08/announcing-pistachio-wpf-resource-visualizer/" rel="nofollow noreferrer">Pistachio - Resource Visualizer</a></li> <li><a href="http://www.erain.com/products/zam3d/DefaultPDC.asp" rel="nofollow noreferrer">Zam 3D - 3D XAML Tool</a></li> <li><a href="http://www.codeplex.com/xamlexporter" rel="nofollow noreferrer">XAML Exporter for Blender</a></li> <li><a href="http://www.wpf-graphics.com/Paste2Xaml.aspx" rel="nofollow noreferrer">Paste2XAML - Convert Clipboard and metafiles into xaml</a></li> <li><a href="http://blogs.msdn.com/silverlight_sdk/archive/2007/05/13/Using-Silverlight-Pad-to-Test-XAML-Content.aspx" rel="nofollow noreferrer">Silverlight PAD - Test XAML Content</a></li> <li><a href="http://blog.wpfwonderland.com/2007/01/02/wpf-tools-stylesnooper/" rel="nofollow noreferrer">StyleSnooper - See the styles for any WPF framework control</a></li> <li><a href="http://sellsbrothers.com/2091" rel="nofollow noreferrer">Show me the Template - Exploring Templates of Controls</a></li> <li><a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=ADB47247-4E27-4490-A153-39D8334172D9&amp;displaylang=en" rel="nofollow noreferrer">WPF XBAP Permission Repair Tool - Repairs Registry for WPF Xaml Browser Apps </a></li> <li><a href="http://joshsmithonwpf.wordpress.com/cracknet/" rel="nofollow noreferrer">Crack.Net - Similar to Mole or Snoop</a></li> </ul> <p>I also agree with Andrew, if you are looking at doing a lot of WPF development it is worth giving the MVVM pattern a look at as I feel this is one pattern that does expose a lot of power behind WPF. </p> <p>Also, if you havent had a look at PRISM, give it some time.</p>
1,900,208
PHP : Custom error handler - handling parse & fatal errors
<p>How can i handle <strong>parse</strong> &amp; <strong>fatal</strong> errors using a <strong>custom</strong> error handler?</p>
1,900,224
6
2
null
2009-12-14 10:57:15.48 UTC
38
2016-04-15 19:19:12.12 UTC
null
null
null
null
184,213
null
1
67
php|error-handling|fatal-error|parse-error
56,731
<p>Simple Answer: You can't. See the <a href="http://php.net/manual/en/function.set-error-handler.php" rel="noreferrer">manual</a>:</p> <blockquote> <p>The following error types cannot be handled with a user defined function: E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING, and most of E_STRICT raised in the file where set_error_handler() is called.</p> </blockquote> <p>For every other error, you can use <code>set_error_handler()</code></p> <p>EDIT:</p> <p>Since it seems, that there are some discussions on this topic, with regards to using <code>register_shutdown_function</code>, we should take a look at the definition of handling: To me, handling an error means catching the error and reacting in a way that is "nice" for the user <em>and</em> the underlying data (databases, files, web services, etc.).</p> <p>Using <code>register_shutdown_function</code> you cannot handle an error from within the code where it was called, meaning the code would still stop working at the point where the error occurs. You can, however, present the user with an error message instead of a white page, but you cannot, for example, roll back anything that your code did prior to failing.</p>
2,280,064
Tomcat started in Eclipse but unable to connect to http://localhost:8085/
<p>I configured Tomcat 6.0.24 in Eclipse on port 8085 and started successfully with log as below:</p> <pre><code>Feb 17, 2010 4:24:31 PM org.apache.catalina.core.AprLifecycleListener init INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jre6\bin;.;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:/Program Files/Java/jre6/bin/client;C:/Program Files/Java/jre6/bin;E:\oracle\product\10.2.0\client_1\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\system32\WBEM;C:\Program Files\Microsoft SQL Server\80\Tools\BINN;C:\Program Files\Common Files\Teleca Shared;C:\Program Files\Microsoft SQL Server\90\Tools\binn\;E:\Program Files\Microsoft Visual Studio 8\Common7\IDE\PrivateAssemblies\;C:\Program Files\MySQL\MySQL Server 5.0\bin;E:\komal-gohil\tools\Subversion\bin;C:\Sun\SDK\bin;e:\instantrails\ruby\bin;c:\program files\java\jdk1.6.0_11\bin;E:\komal-gohil\tools\apache-maven-2.2.1\bin;C:\program files\java\jdk1.6.0_11\bin;E:\komal-gohil\tools\Ant\bin;E:\komal-gohil\tools\apache-tomcat-5.5.17\bin;C:\Sun\SDK\lib\j2ee.jar;E:\komal-gohil\tools\android-sdk-windows-1.6_r1\tools;E:\komal-gohil\tools\Scala\bin;E:\komal-gohil\tools\pax-construct-1.4\bin Feb 17, 2010 4:24:31 PM org.apache.coyote.http11.Http11Protocol init INFO: Initializing Coyote HTTP/1.1 on http-8085 Feb 17, 2010 4:24:31 PM org.apache.catalina.startup.Catalina load INFO: Initialization processed in 705 ms Feb 17, 2010 4:24:32 PM org.apache.catalina.core.StandardService start INFO: Starting service Catalina Feb 17, 2010 4:24:32 PM org.apache.catalina.core.StandardEngine start INFO: Starting Servlet Engine: Apache Tomcat/6.0.24 Feb 17, 2010 4:24:32 PM org.apache.coyote.http11.Http11Protocol start INFO: Starting Coyote HTTP/1.1 on http-8085 Feb 17, 2010 4:24:32 PM org.apache.jk.common.ChannelSocket init INFO: JK: ajp13 listening on /0.0.0.0:8010 Feb 17, 2010 4:24:32 PM org.apache.jk.server.JkMain start INFO: Jk running ID=0 time=0/31 config=null Feb 17, 2010 4:24:32 PM org.apache.catalina.startup.Catalina start INFO: Server startup in 421 ms </code></pre> <p>But when I am trying to open <code>http://localhost:8085</code> in webbrowser, it is giving me the following error:</p> <blockquote> <h2>HTTP Status 404 - /</h2> <p><strong>type</strong> Status report</p> <p><strong>message</strong> /</p> <p><strong>description</strong> The requested resource (/) is not available.</p> <p>Apache Tomcat/6.0.24</p> </blockquote> <p>When I start Tomcat outside the Eclipse, then I can just open <code>http://localhost:8085</code> in webbrowser.</p> <p>What could be the reason for this? How do I solve this problem?</p>
2,280,798
6
2
null
2010-02-17 11:08:50.07 UTC
32
2021-04-03 16:52:17.383 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
275,167
null
1
72
eclipse|tomcat|http-status-code-404
169,678
<p>What are you expecting? The default Tomcat homepage? If so, you'll need to configure Eclipse to take control over from Tomcat.</p> <p>Doubleclick the Tomcat server entry in the <em>Servers</em> tab, you'll get the server configuration. At the left column, under <em>Server Locations</em>, select <em>Use Tomcat installation</em>. This way Eclipse will take full control over Tomcat, this way you'll also be able to access the default Tomcat homepage with the Tomcat Manager when running from inside Eclipse. I only don't see how that's useful while developing using Eclipse.</p> <p><img src="https://i.stack.imgur.com/ufmdQ.png" alt="enter image description here" /></p> <p>Note, when it is grayed out, <strong>read</strong> the section leading text! It literally says <em>&quot;Server must be published with no modules present to make changes&quot;</em>. In other words, make sure that you've removed all modules via rightclick server and <em>Add and remove...</em> option, and then performed rightclick server and <em>Publish</em>.</p> <p>The port number is not the problem. You would otherwise have gotten an exception in Tomcat's startup log, and the browser would show a browser-specific &quot;Connection timed out&quot; error page and thus not a Tomcat-specific error page which could impossibly be served when Tomcat was not up and running.</p>
1,823,705
Why use AMQP/ZeroMQ/RabbitMQ
<p>as opposed to writing your own library.</p> <p>We're working on a project here that will be a self-dividing server pool, if one section grows too heavy, the manager would divide it and put it on another machine as a separate process. It would also alert all connected clients this affects to connect to the new server.</p> <p>I am curious about using ZeroMQ for inter-server and inter-process communication. My partner would prefer to roll his own. I'm looking to the community to answer this question.</p> <p>I'm a fairly novice programmer myself and just learned about messaging queues. As i've googled and read, it seems everyone is using messaging queues for all sorts of things, but why? What makes them better than writing your own library? Why are they so common and why are there so many?</p>
1,870,045
6
1
null
2009-12-01 02:54:50.373 UTC
22
2014-02-17 11:23:10.58 UTC
2014-02-17 11:23:10.58 UTC
null
-1
null
127,229
null
1
75
rabbitmq|messaging|zeromq|amqp
22,033
<blockquote> <p>what makes them better than writing your own library?</p> </blockquote> <p>When rolling out the first version of your app, probably nothing: your needs are well defined and you will develop a messaging system that will fit your needs: small feature list, small source code etc.</p> <p>Those tools are <em>very</em> useful <em>after</em> the first release, when you actually have to extend your application and add more features to it. Let me give you a few use cases:</p> <ul> <li>your app will have to talk to a big endian machine (sparc/powerpc) from a little endian machine (x86, intel/amd). Your messaging system had some endian ordering assumption: go and fix it</li> <li>you designed your app so it is not a binary protocol/messaging system and now it is very slow because you spend most of your time parsing it (the number of messages increased and parsing became a bottleneck): adapt it so it can transport binary/fixed encoding</li> <li><p>at the beginning you had 3 machine inside a lan, no noticeable delays everything gets to every machine. your client/boss/pointy-haired-devil-boss shows up and tell you that you will install the app on WAN you do not manage - and then you start having connection failures, bad latency etc. you need to store message and retry sending them later on: go back to the code and plug this stuff in (and enjoy)</p></li> <li><p>messages sent need to have replies, but not all of them: you send some parameters in and expect a spreadsheet as a result instead of just sending and acknowledges, go back to code and plug this stuff in (and enjoy.)</p></li> <li>some messages are critical and there reception/sending needs proper backup/persistence/. Why you ask ? auditing purposes</li> </ul> <p>And many other use cases that I forgot ...</p> <p>You can implement it yourself, but do not spend much time doing so: you will probably replace it later on anyway.</p>
1,984,195
close window event in java
<p>I added an window state listener as follow:</p> <pre><code>this.addWindowStateListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { ExitAction.getInstance().actionPerformed(null); } }); </code></pre> <p>But when I'm using the X close button the event is not called. I think it's something to do with netbean jdesktop framework. But I can't find what could be the problem. Thanks for your help. </p>
1,984,264
7
0
null
2009-12-31 06:19:04.387 UTC
3
2013-09-23 16:23:55.193 UTC
null
null
null
null
241,378
null
1
6
java|user-interface|swing|window
41,828
<p><code>windowClosing</code> is part of the <code>WindowListener</code> interface. Use <code>addWindowListener</code> instead of <code>addWindowStateListener</code>.</p>
1,665,511
Python equivalent to atoi / atof
<p>Python loves raising exceptions, which is usually great. But I'm facing some strings I desperately want to convert to integers using C's atoi / atof semantics - e.g. atoi of "3 of 12", "3/12", "3 / 12", should all become 3; atof("3.14 seconds") should become 3.14; atoi(" -99 score") should become -99. Python of course has atoi and atof functions, which behave nothing like atoi and atof and exactly like Python's own int and float constructors.</p> <p>The best I have so far, which is really ugly and hard to extend to the various float formats available:</p> <pre><code>value = 1 s = str(s).strip() if s.startswith("-"): value = -1 s = s[1:] elif s.startswith("+"): s = s[1:] try: mul = int("".join(itertools.takewhile(str.isdigit, s))) except (TypeError, ValueError, AttributeError): mul = 0 return mul * value </code></pre>
1,681,644
7
0
null
2009-11-03 06:02:24.417 UTC
4
2022-08-18 14:29:31.553 UTC
null
null
null
user79758
null
null
1
16
python
37,999
<p>It's pretty straightforward to do this with regular expressions:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; p = re.compile(r'[^\d-]*(-?[\d]+(\.[\d]*)?([eE][+-]?[\d]+)?)') &gt;&gt;&gt; def test(seq): for s in seq: m = p.match(s) if m: result = m.groups()[0] if "." in result or "e" in result or "E" in result: print "{0} -&gt; {1}".format(s, float(result)) else: print '"{0}" -&gt; {1}'.format(s, int(result)) else: print s, "no match" &gt;&gt;&gt; test(s) "1 0" -&gt; 1 "3 of 12" -&gt; 3 "3 1/2" -&gt; 3 "3/12" -&gt; 3 3.15 seconds -&gt; 3.15 3.0E+102 -&gt; 3e+102 "what about 2?" -&gt; 2 "what about -2?" -&gt; -2 2.10a -&gt; 2.1 </code></pre>
1,363,422
What client tools are available to manage Amazon S3 and CloudFront?
<p>I just started using the <a href="http://aws.amazon.com/s3/" rel="noreferrer">Amazon S3</a> and <a href="http://aws.amazon.com/cloudfront/" rel="noreferrer">Amazon CloudFront</a>. What proper client tools are out there that I can use to manage my account? Like uploading files etc. Yes I am a developer, but, I am pressed for time, I just want to deploy my apps.</p> <p>I came across this one <a href="http://s3browser.com/" rel="noreferrer">S3 Browser</a>. It's almost what I am looking for.</p> <p>EDIT ~ Is it possible to map a bucket as a windows Drive?</p>
1,363,513
7
0
null
2009-09-01 16:27:58.453 UTC
16
2019-09-07 05:42:22.573 UTC
2012-03-21 11:18:10.333 UTC
null
45,773
null
23,667
null
1
41
amazon-s3|amazon-web-services|amazon-cloudfront
73,636
<p>I use CloudBerry FreeWare. Easy to use, just like FTP software. </p> <p><a href="https://www.cloudberrylab.com/explorer/amazon-s3.aspx" rel="noreferrer">https://www.cloudberrylab.com/explorer/amazon-s3.aspx</a></p> <p>Jeff Atwood mentioned S3Fox Organizer on his CodingHorror blog.</p> <p><a href="http://www.s3fox.net/" rel="noreferrer">http://www.s3fox.net/</a></p> <p><a href="https://blog.codinghorror.com/using-amazon-s3-as-an-image-hosting-service/" rel="noreferrer">Using Amazon S3 as an Image Hosting Service</a></p>
1,990,502
Django: signal when user logs in?
<p>In my Django app, I need to start running a few periodic background jobs when a user logs in and stop running them when the user logs out, so I am looking for an elegant way to</p> <ol> <li>get notified of a user login/logout</li> <li>query user login status</li> </ol> <p>From my perspective, the ideal solution would be</p> <ol> <li>a signal sent by each <code>django.contrib.auth.views.login</code> and <code>... views.logout</code></li> <li>a method <code>django.contrib.auth.models.User.is_logged_in()</code>, analogous to <code>... User.is_active()</code> or <code>... User.is_authenticated()</code></li> </ol> <p>Django 1.1.1 does not have that and I am reluctant to patch the source and add it (not sure how to do that, anyway).</p> <p>As a temporary solution, I have added an <code>is_logged_in</code> boolean field to the UserProfile model which is cleared by default, is set the first time the user hits the landing page (defined by <code>LOGIN_REDIRECT_URL = '/'</code>) and is queried in subsequent requests. I added it to UserProfile, so I don't have to derive from and customize the builtin User model for that purpose only.</p> <p>I don't like this solution. If the user explicitely clicks the logout button, I can clear the flag, but most of the time, users just leave the page or close the browser; clearing the flag in these cases does not seem straight forward to me. Besides (that's rather data model clarity nitpicking, though), <code>is_logged_in</code> does not belong in the UserProfile, but in the User model.</p> <p>Can anyone think of alternate approaches ?</p>
6,109,366
7
2
null
2010-01-02 03:19:49.93 UTC
23
2020-11-14 02:25:19.757 UTC
2018-02-17 23:14:06.633 UTC
null
736,054
null
217,844
null
1
84
python|django|authentication|signals
39,588
<p>You can use a signal like this (I put mine in models.py)</p> <pre><code>from django.contrib.auth.signals import user_logged_in def do_stuff(sender, user, request, **kwargs): whatever... user_logged_in.connect(do_stuff) </code></pre> <p>See django docs: <a href="https://docs.djangoproject.com/en/dev/ref/contrib/auth/#module-django.contrib.auth.signals" rel="noreferrer">https://docs.djangoproject.com/en/dev/ref/contrib/auth/#module-django.contrib.auth.signals</a> and here <a href="http://docs.djangoproject.com/en/dev/topics/signals/" rel="noreferrer">http://docs.djangoproject.com/en/dev/topics/signals/</a></p>
1,798,796
python : list index out of range error while iteratively popping elements
<p>I have written a simple python program </p> <pre><code>l=[1,2,3,0,0,1] for i in range(0,len(l)): if l[i]==0: l.pop(i) </code></pre> <p>This gives me error 'list index out of range' on line <code>if l[i]==0:</code></p> <p>After debugging I could figure out that <code>i</code> is getting incremented and list is getting reduced.<br> However, I have loop termination condition <code>i &lt; len(l)</code>. Then why I am getting such error? </p>
1,798,807
12
6
null
2009-11-25 17:57:54.853 UTC
35
2020-07-24 12:23:52.473 UTC
2020-07-24 12:23:52.473 UTC
null
10,908,375
null
209,602
null
1
45
python|list
829,917
<p>You are reducing the length of your list <code>l</code> as you iterate over it, so as you approach the end of your indices in the range statement, some of those indices are no longer valid.</p> <p>It <em>looks</em> like what you want to do is:</p> <pre><code>l = [x for x in l if x != 0] </code></pre> <p>which will return a copy of <code>l</code> without any of the elements that were zero (that operation is called a <a href="http://docs.python.org/tutorial/datastructures.html#list-comprehensions" rel="noreferrer">list comprehension</a>, by the way). You could even shorten that last part to just <code>if x</code>, since non-zero numbers evaluate to <code>True</code>.</p> <p>There is no such thing as a loop termination condition of <code>i &lt; len(l)</code>, in the way you've written the code, because <code>len(l)</code> is <em>pre</em>calculated before the loop, not re-evaluated on each iteration. You <em>could</em> write it in such a way, however:</p> <pre><code>i = 0 while i &lt; len(l): if l[i] == 0: l.pop(i) else: i += 1 </code></pre>
1,769,403
What is the purpose and use of **kwargs?
<p>What are the uses for <code>**kwargs</code> in Python?</p> <p>I know you can do an <code>objects.filter</code> on a table and pass in a <code>**kwargs</code> argument.  </p> <p>Can I also do this for specifying time deltas i.e. <code>timedelta(hours = time1)</code>?</p> <p>How exactly does it work? Is it classified as 'unpacking'? Like <code>a,b=1,2</code>?</p>
1,769,475
13
1
null
2009-11-20 09:40:57.063 UTC
284
2022-08-10 20:46:30.19 UTC
2022-08-10 20:46:30.19 UTC
null
7,487,335
null
154,280
null
1
832
python|keyword-argument
662,140
<p>You can use <code>**kwargs</code> to let your functions take an arbitrary number of keyword arguments (&quot;kwargs&quot; means &quot;keyword arguments&quot;):</p> <pre><code>&gt;&gt;&gt; def print_keyword_args(**kwargs): ... # kwargs is a dict of the keyword args passed to the function ... for key, value in kwargs.iteritems(): ... print &quot;%s = %s&quot; % (key, value) ... &gt;&gt;&gt; print_keyword_args(first_name=&quot;John&quot;, last_name=&quot;Doe&quot;) first_name = John last_name = Doe </code></pre> <p>You can also use the <code>**kwargs</code> syntax when calling functions by constructing a dictionary of keyword arguments and passing it to your function:</p> <pre><code>&gt;&gt;&gt; kwargs = {'first_name': 'Bobby', 'last_name': 'Smith'} &gt;&gt;&gt; print_keyword_args(**kwargs) first_name = Bobby last_name = Smith </code></pre> <p>The <a href="http://docs.python.org/tutorial/controlflow.html#keyword-arguments" rel="noreferrer">Python Tutorial</a> contains a good explanation of how it works, along with some nice examples.</p> <h2>Python 3 update</h2> <p>For Python 3, instead of <code>iteritems()</code>, use <a href="https://docs.python.org/3/library/stdtypes.html#dict.items" rel="noreferrer"><code>items()</code></a></p>
2,259,905
How to disable the highlight control state of a UIButton?
<p>I've got a UIButton that, when selected, shouldn't change state when being touched. The default behaviour is for it to be in UIControlStateHighlighted while being touched, and this is making me angry.</p> <p>Suggestions?</p>
2,259,919
14
1
null
2010-02-14 02:16:52.64 UTC
27
2022-06-17 07:45:05.68 UTC
2016-06-14 00:37:11.163 UTC
null
603,977
null
74,574
null
1
161
ios|cocoa-touch|uibutton|uikit|uicontrol
91,666
<p>Your button must have its <code>buttonType</code> set to Custom.</p> <p>In IB you can uncheck "Highlight adjusts image".</p> <p>Programmatically you can use <code>theButton.adjustsImageWhenHighlighted = NO;</code></p> <p>Similar options are available for the "disabled" state as well.</p>
33,626,519
Uncaught ReferenceError: $ is not defined (ajax)
<p>I have this error on a simple jsp : Uncaught ReferenceError: $ is not defined </p> <p>I've just try to recall a service rest on another project on eclipse but it seem doesn't work..</p> <p>Code is here : </p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt; &lt;html&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"&gt; &lt;script rel="javascript" type="text/javascript" href="js/jquery-1.11.3.min.js" /&gt; &lt;/head&gt; &lt;body&gt; &lt;script&gt; var people = { "address": "Street 12", "name": "twelve", "id": 12, "surname": "twelve" }; function sendobject() { $.ajax({ type: "POST", url: "http://localhost:8080/HibernateTutorialWeb/rest/person/post", data: markers, contentType: "application/json; charset=utf-8", dataType: "json", success: function(data) { alert(data); }, failure: function(errMsg) { alert(errMsg); } }); } &lt;/script&gt; &lt;input type="button" onclick="sendobject()" value="send"&gt; &lt;/input&gt; &lt;/body&gt; &lt;/&lt;html&gt; </code></pre> <p><strong>Update:</strong></p> <p>Tried using the jQuery from Google CDN, but still doesn't work</p> <pre><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"&gt;&lt;/script&gt; </code></pre> <blockquote> <p>Uncaught ReferenceError: $ is not defined sendobject @ index.jsp:15onclick @ index.jsp:28</p> </blockquote> <hr> <p><strong>This question is not a duplicate of <a href="https://stackoverflow.com/questions/2075337/uncaught-referenceerror-is-not-defined">Uncaught ReferenceError: $ is not defined?</a></strong> </p> <p>Because all the answer of that question suggest <em>to put the references to the jquery scripts first</em>, but <strong>it does not work for me</strong> .</p> <p><a href="https://stackoverflow.com/a/33626543/5533075">The right solution was given in tushar's answer</a></p> <p>So it's a <strong>similar</strong> question with a <strong>different problem</strong> and <strong>different solution.</strong></p> <hr>
33,626,543
1
4
null
2015-11-10 09:19:28.787 UTC
null
2019-06-18 11:53:24.943 UTC
2019-06-18 11:53:24.943 UTC
null
5,533,075
null
5,533,075
null
1
8
jquery|ajax
50,385
<p><code>&lt;script&gt;</code> should not be self-closed, it'll not load the script. See <a href="https://stackoverflow.com/questions/69913/why-dont-self-closing-script-tags-work">Why don&#39;t self-closing script tags work?</a></p> <p>Change</p> <pre><code>&lt;script rel="javascript" type="text/javascript" href="js/jquery-1.11.3.min.js"/&gt; </code></pre> <p>to </p> <pre><code>&lt;script rel="javascript" type="text/javascript" href="js/jquery-1.11.3.min.js"&gt;&lt;/script&gt; </code></pre>
8,945,477
Regular Expression for getting everything after last slash
<p>I was browsing stackoverflow and have noticed a regular expression for matching everything after last slash is</p> <pre><code>([^/]+$) </code></pre> <p>So for example if you have <a href="http://www.blah.com/blah/test">http://www.blah.com/blah/test</a> The reg expression will extract 'test' without single quotes.</p> <p>My question is why does it do it? Doesn't ^/ mean beginning of a slash?</p> <p>EDIT: I guess I do not understand how +$ grabs "test". + repeats the previous item once or more so it ignores all data between all the / slashes. how does then $ extract the test</p>
8,945,504
7
2
null
2012-01-20 17:33:49.147 UTC
14
2020-01-22 15:20:12.863 UTC
2012-01-20 21:22:34.61 UTC
null
873,429
null
873,429
null
1
88
regex
121,243
<p>No, an <code>^</code> inside <code>[]</code> means negation.</p> <p><code>[/]</code> stands for 'any character in set [/]'.</p> <p><code>[^/]</code> stands for 'any character not in set [/]'.</p>
17,795,167
xml.LoadData - Data at the root level is invalid. Line 1, position 1
<p>I'm trying to parse some XML inside a WiX installer. The XML would be an object of all my errors returned from a web server. I'm getting the error in the question title with this code:</p> <pre><code>XmlDocument xml = new XmlDocument(); try { xml.LoadXml(myString); } catch (Exception ex) { System.IO.File.WriteAllText(@&quot;C:\text.txt&quot;, myString + &quot;\r\n\r\n&quot; + ex.Message); throw ex; } </code></pre> <p><code>myString</code> is this (as seen in the output of <code>text.txt</code>)</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; &lt;Errors&gt;&lt;/Errors&gt; </code></pre> <p><code>text.txt</code> comes out looking like this:</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; &lt;Errors&gt;&lt;/Errors&gt; Data at the root level is invalid. Line 1, position 1. </code></pre> <p>I need this XML to parse so I can see if I had any errors.</p>
27,743,515
11
5
null
2013-07-22 18:50:44.317 UTC
11
2021-10-01 17:39:38.327 UTC
2021-10-01 17:39:38.327 UTC
null
2,756,409
null
355,689
null
1
92
c#|xml|xml-parsing|wix
280,071
<p>The hidden character is probably BOM. The explanation to the problem and the solution can be found <a href="http://www.ipreferjim.com/2014/09/data-at-the-root-level-is-invalid-line-1-position-1/" rel="noreferrer">here</a>, credits to James Schubert, based on an answer by James Brankin found <a href="https://stackoverflow.com/questions/17947238/why-data-at-the-root-level-is-invalid-line-1-position-1-for-xml-document/24513288#24513288">here</a>. </p> <p>Though the previous answer does remove the hidden character, it also removes the whole first line. The more precise version would be:</p> <pre><code>string _byteOrderMarkUtf8 = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble()); if (xml.StartsWith(_byteOrderMarkUtf8)) { xml = xml.Remove(0, _byteOrderMarkUtf8.Length); } </code></pre> <p>I encountered this problem when fetching an XSLT file from Azure blob and loading it into an XslCompiledTransform object. On my machine the file looked just fine, but after uploading it as a blob and fetching it back, the BOM character was added. </p>
6,735,225
Knockout JS mapping plugin without initial data / empty form
<p>We are using knockout and the knockout mapping plugin to facilitate databinding in our jQTouch web application. The reason we use the mapping plugin, is to be able to use knockout without the need to define/change viewmodels manually in javascript. The mapping plugin works great when you have an initial load of data from the server/client side database. </p> <p>The problem we are having is that we have some screens/views which have a form in which it is possible that there isn't any initial data. Without this initial data, the mapping plugin can't 'generate' the viewmodel (ko.mapping.fromJS). This means that we still need to define our viewmodels by hand for large parts of our views.</p> <p>Am I wrong in assuming that this is a scenario which the mapping plugin (should) support? I mean, this means that the mapping plugin is only usable in scenarios in which you always have an initial load of data.</p>
6,737,908
3
0
null
2011-07-18 15:19:21.79 UTC
10
2014-08-04 09:49:06.79 UTC
2014-08-04 09:49:06.79 UTC
null
491,238
null
491,238
null
1
18
javascript|knockout.js|jqtouch|knockout-mapping-plugin
11,201
<p>A couple of options for you besides just manually managing your view model. The mapping plugin supports a <code>create</code> callback that lets you customize how it gets created. This can be used to add default properties to an object, if they happen to be missing.</p> <p>Something like this: <a href="http://jsfiddle.net/rniemeyer/WQGVC/">http://jsfiddle.net/rniemeyer/WQGVC/</a></p> <p>Another alternative is to use a binding that creates properties that are missing. It might look like:</p> <pre><code>//create an observable if it does not exist and populate it with the input's value ko.bindingHandlers.valueWithInit = { init: function(element, valueAccessor, allBindingsAccessor, data) { var property = valueAccessor(), value = element.value; //create the observable, if it doesn't exist if (!ko.isWriteableObservable(data[property])) { data[property] = ko.observable(); } //populate the observable with the element's value (could be optional) data[property](value); ko.applyBindingsToNode(element, { value: data[property] }); } } </code></pre> <p>You would use it like this (need to pass the property as a string, otherwise it will error):</p> <pre><code>&lt;input data-bind="valueWithInit: 'name'" /&gt; </code></pre> <p>Sample here: <a href="http://jsfiddle.net/rniemeyer/JPYLp/">http://jsfiddle.net/rniemeyer/JPYLp/</a></p>
6,714,202
How can I disable the ENTER key on my textarea?
<pre><code>&lt;form name='qform'&gt; &lt;textarea name='q' rows='3' cols='60' wrap='hard' id='q' onkeydown="if (event.keyCode == 13) document.getElementById('clickit').click()"&gt;&lt;/textarea&gt; &lt;input type='button' value='search' id='clickit' onclick="get();"&gt; &lt;/form&gt; </code></pre> <p>I have this form... it doesn't have a submit button because I am using jquery and under this form is a div area where the results will be shown. It is a search engine that does not have an input box but instead has a textarea. This is because it will be a multiple word searcher.</p> <p>The problem is that if I press enter, the query is submitted and everything is ok ... but the focus on textarea goes down one line and that is a problem for me.</p> <p>Basically I want the enter to have that one function only(submit) end nothing else.</p>
6,714,245
3
2
null
2011-07-15 23:31:35.223 UTC
6
2018-08-31 02:44:21.21 UTC
2011-07-15 23:38:16.897 UTC
null
404
null
725,097
null
1
23
javascript|jquery|events|textarea
46,079
<p>In the jquery function, use event.preventdefault and next do what you like. For example</p> <pre><code>&lt;script&gt; $("a").click(function(event) { event.preventDefault(); //Do your logic here }); &lt;/script&gt; </code></pre> <p><a href="http://api.jquery.com/event.preventDefault/" rel="noreferrer">http://api.jquery.com/event.preventDefault/</a></p>
18,670,392
update using for loop in plsql
<p>i'm having problem updating and insert into below column. Please advise on this.</p> <p>This is the input</p> <pre><code>depnto extra comm ---------------------------- 20 300 NULL 20 300 400 20 NULL NULL 20 500 NULL </code></pre> <p>This is the expected output</p> <pre><code>depnto Extra comm --------------------- 20 300 300 20 300 400 20 NULL NULL 20 500 500 </code></pre> <p>I need to update <code>comm</code> column with <code>extra</code> column on below conditions.</p> <ul> <li>If comm Is null then extra value is updated to comm.</li> <li>If comm Is not null, no need to update,</li> <li>If both are null, leave as null,</li> <li>if comm column has a value no need to overwrite.</li> </ul> <p>My program is below. Even I need to keep track which are rows are updated and to which value in another table.</p> <pre><code>PROCEDURE (dept_id ) AS BEGIN FOR r IN (SELECT * FROM emp WHERE comm IS NULL AND extra IS NOT NULL AND deptno = dept_id) LOOP UPDATE emp SET comm = extra WHERE comm IS NULL AND extra IS NOT NULL AND deptno = dept_id; INSERT INTO changed_comm (deptno, oldval, newval) VALUES (dept_id, r.comm, r.extra); END LOOP; EXCEPTION WHEN NO_DATA_FOUND THEN NULL; END; </code></pre> <p>please provide some opinion on above. Its not inserting correctly.</p>
18,671,872
2
0
null
2013-09-07 06:14:42.613 UTC
0
2018-05-20 04:19:27.673 UTC
2013-09-07 14:32:11.35 UTC
null
2,686,661
null
2,686,661
null
1
7
oracle|plsqldeveloper
76,671
<p>You do not need <code>FOR LOOP</code>, just a single UPDATE does the work:</p> <pre><code>UPDATE emp SET comm = extra WHERE comm IS NULL AND extra IS NOT NULL; </code></pre> <p>Here is a demo: <a href="http://www.sqlfiddle.com/#!4/aacc3/1">http://www.sqlfiddle.com/#!4/aacc3/1</a></p> <p><strong>--- EDIT ----</strong><br><br> I didn't notice, that in the expected output deptno 10 was updated to 20,<br> to update <code>deptno</code> an another query is needed:</p> <pre><code>UPDATE emp SET deptno = 20 WHERE deptno = 10; </code></pre> <p><br><br> <strong>---- EDIT -----</strong> <br><br> If you want to insert changed values to the other table, try a procedure with RETURNING..BULK COLLECT and FORALL:</p> <pre><code>CREATE OR REPLACE PROCEDURE pro_cedure( p_dept_id number ) IS TYPE changed_table_type IS TABLE OF changed%ROWTYPE; changed_buff changed_table_type; BEGIN SELECT deptno, comm, extra BULK COLLECT INTO changed_buff FROM emp WHERE comm IS NULL AND extra IS NOT NULL AND deptno = p_dept_id FOR UPDATE; UPDATE emp SET comm = extra WHERE comm IS NULL AND extra IS NOT NULL AND deptno = p_dept_id; FORALL i IN 1 .. changed_buff.count INSERT INTO changed VALUES changed_buff( i ); END; / </code></pre> <p>The procedure should work if you are not going to process huge number of records in a one call (more than 1000 ... or maximum a few thousands). If one <code>dept_id</code> can contain ten thousands and more rows, then this procedure might be slow, becasue it will consume a huge amount of PGA memory. In such a case, an another approach with bulk collectiong in chunks is required. <br><br> <strong>-- EDIT --- how to store sequence values -------</strong> <br><br> I assume that the table <code>changed</code> has 4 columns, like this:</p> <pre><code> CREATE TABLE "TEST"."CHANGED" ( "DEPTNO" NUMBER, "OLDVAL" NUMBER, "NEWVAL" NUMBER, "SEQ_NEXTVAL" NUMBER ) ; </code></pre> <p>and we will store sequence values in the <code>seq_nextval</code> column.<br> <br> In such a case the procedure might look like this:</p> <pre><code>create or replace PROCEDURE pro_cedure( p_dept_id number ) IS TYPE changed_table_type IS TABLE OF changed%ROWTYPE; changed_buff changed_table_type; BEGIN SELECT deptno, comm, extra, sequence_name.nextval BULK COLLECT INTO changed_buff FROM emp WHERE comm IS NULL AND extra IS NOT NULL AND deptno = p_dept_id FOR UPDATE; UPDATE emp SET comm = extra WHERE comm IS NULL AND extra IS NOT NULL AND deptno = p_dept_id; FORALL i IN 1 .. changed_buff.count INSERT INTO changed VALUES changed_buff( i ); END; </code></pre> <p><br><br> <strong>--- EDIT --- version with cursor for small sets of data -----</strong> <br><br> Yes, for small sets of data bulk collecting doesn't give significant increase of the speed, and plain cursor with for..loop is sufficient in such a case.<br> Below is an example how tu use the cursor together with update, notice the <code>FOR UPDATE</code> clause, it is required when we plan to update a record fetched from the cursor using <code>WHERE CURRENT OF</code> clause.<br> This time a sequence value is evaluated within the INSERT statement.</p> <pre><code>create or replace PROCEDURE pro_cedure( p_dept_id number ) IS CURSOR mycursor IS SELECT deptno, comm, extra FROM emp WHERE comm IS NULL AND extra IS NOT NULL AND deptno = p_dept_id FOR UPDATE; BEGIN FOR emp_rec IN mycursor LOOP UPDATE emp SET comm = extra WHERE CURRENT OF mycursor; INSERT INTO changed( deptno, oldval, newval, seq_nextval) VALUES( emp_rec.deptno, emp_rec.comm, emp_rec.extra, sequence_name.nextval ); END LOOP; END; </code></pre>
15,653,732
Insert data from db to another db
<p>I want to take values from my old database tables to new database tables.</p> <p>Old db structure:</p> <p>Table I: <code>Country</code></p> <ul> <li>CountryId </li> <li>CountryName</li> </ul> <p>New db structure</p> <p>Table II: <code>Countries</code></p> <ul> <li>Id</li> <li>Name</li> </ul> <p>I used the following insert query like,</p> <pre><code>select 'insert into Countries (Id, Name) select ', countryid, countryname from Country </code></pre> <p>But I have the result like,</p> <ul> <li><code>insert into Countries(Id,Name) select 1 India</code></li> <li><code>insert into Countries(Id,Name) select 2 Any Country</code></li> </ul> <p>like that.</p> <p>but I need the result like,</p> <pre><code>insert into Countries (Id, Name) values (1, 'India') </code></pre> <p>To achieve this, what is the query? help me...</p>
15,654,315
4
0
null
2013-03-27 07:30:45.387 UTC
2
2015-09-03 16:53:51.297 UTC
2013-03-27 07:55:52.793 UTC
null
13,302
null
2,207,366
null
1
7
sql|sql-server|sql-server-2008|sql-insert
49,252
<p>If there is a lot of data to transfer and multiple tables, I would suggest using Import/Export wizard provided by SQL Server Management Studio.</p> <p><a href="http://www.mssqltips.com/sqlservertutorial/203/simple-way-to-import-data-into-sql-server/">http://www.mssqltips.com/sqlservertutorial/203/simple-way-to-import-data-into-sql-server/</a></p> <p>Edit: However, if there is not lot of data and the two systems are not connected - and you need to generate script to transfer data, your query should look like this:</p> <pre><code>SELECT 'INSERT INTO Countries (Id, Name) VALUES (' + CAST(countryid AS VARCHAR(50)) + ', ''' + countryname + ''')' from Country </code></pre>
34,016,449
"Could not open input file: bin/console" Error comes when try to Run the Symfony Application
<pre><code>$ cd my_project_name/ $ php bin/console server:run </code></pre> <p>When I added following commands and tried to run my symfony application this error comes,</p> <blockquote> <p>"Error:Could not open input file: bin/console"</p> </blockquote>
34,305,360
6
6
null
2015-12-01 09:06:05.337 UTC
4
2019-06-04 12:48:23.237 UTC
2015-12-01 09:58:23.307 UTC
null
5,321,614
null
2,395,282
null
1
28
php|symfony
84,350
<p>As @chapay and @cered says we can use this command instead.</p> <pre><code>php app/console server:run </code></pre> <p>Its Symfony 2 command and the one I had problems with is Symfony 3 command. And I found out few other times also this issue comes.</p> <p>for sometimes we can replace 'bin' with 'app'. like,</p> <pre><code>php bin/console doctrine:mapping:import --force AcmeBlogBundle xml php app/console doctrine:mapping:import --force AcmeBlogBundle xml </code></pre> <p>And if not we can choose the correct command in '<a href="http://symfony.com/doc/" rel="noreferrer">http://symfony.com/doc/</a>' site by changing the version.</p> <p><a href="https://i.stack.imgur.com/En8Kf.png" rel="noreferrer"><img src="https://i.stack.imgur.com/En8Kf.png" alt="enter image description here"></a></p>
991,349
Resize image while keeping aspect ratio in Java
<p>im trying to resize bufferdImage in memory in java but to keep the aspect ratio of the image im have something like this but this is not good </p> <pre><code>int w = picture.getWidth(); int h = picture.getWidth(); int neww=w; int newh=h; int wfactor = w; int hfactor = h; if(w &gt; DEFULT_PICTURE_WIDTH || h &gt; DEFULT_PICTURE_HIGHT) { while(neww &gt; DEFULT_PICTURE_WIDTH) { neww = wfactor /2; newh = hfactor /2; wfactor = neww; hfactor = newh; } } picture = Utils.resizePicture(picture,neww,newh); </code></pre>
4,403,855
7
0
null
2009-06-13 19:37:01.677 UTC
11
2019-12-01 18:29:24.877 UTC
2013-01-28 16:01:40.07 UTC
null
1,113,435
null
63,898
null
1
18
java|image|resize
57,341
<p>You may have a look at <a href="https://community.oracle.com/docs/DOC-983611" rel="nofollow noreferrer" title="perils-of-image-getscaledinstance.html">perils-of-image-getscaledinstance.html</a> that explains why <code>getScaledInstance()</code>, used in some of the answers, should be avoided.</p> <p>The article also provides alternative code.</p>
227,928
What's win32con module in python? Where can I find it?
<p>I'm building an open source project that uses python and c++ in Windows. I came to the following error message:</p> <pre><code> ImportError: No module named win32con </code></pre> <p>The same happened in a "prebuilt" code that it's working ( except in my computer :P ) </p> <p>I think this is kind of "popular" module in python because I've saw several messages in other forums but none that could help me.</p> <p>I have Python2.6, should I have that module already installed? Is that something of VC++?</p> <p>Thank you for the help.</p> <p>I got this url <a href="http://sourceforge.net/projects/pywin32/" rel="noreferrer">http://sourceforge.net/projects/pywin32/</a> but I'm not sure what to do with the executable :S</p>
227,930
7
1
null
2008-10-22 23:38:30.3 UTC
9
2020-04-26 22:17:31.23 UTC
2009-07-14 23:02:45.563 UTC
Greg Hewgill
20,654
Oscar Reyes
20,654
null
1
48
python|module
93,919
<p>This module contains constants related to Win32 programming. It is not part of the Python 2.6 release, but should be part of the download of the pywin32 project.</p> <p><strong>Edit:</strong> I imagine that the executable is an installation program, though the last time I downloaded pywin32 it was just a zip file.</p>
121,392
How to determine the line ending of a file
<p>I have a bunch (hundreds) of files that are supposed to have Unix line endings. I strongly suspect that some of them have Windows line endings, and I want to programmatically figure out which ones do.</p> <p>I know I can just run <pre>flip -u</pre> or something similar in a script to convert everything, but I want to be able to identify those files that need changing first.</p>
121,464
7
0
null
2008-09-23 14:34:35.263 UTC
16
2016-12-08 08:55:01.837 UTC
null
null
null
null
18,177
null
1
53
scripting|line-endings
51,591
<p>You could use grep</p> <pre><code>egrep -l $'\r'\$ * </code></pre>
454,601
How to Count Duplicates in List with LINQ
<p>I have a list of items</p> <ul> <li>John ID</li> <li>Matt ID</li> <li>John ID</li> <li>Scott ID</li> <li>Matt ID</li> <li>John ID</li> <li>Lucas ID</li> </ul> <p>I want to shove them back into a list like so which also means I want to sort by the highest number of duplicates.</p> <ul> <li>John ID 3</li> <li>Matt ID 2</li> <li>Scott ID 1</li> <li>Lucas ID 1</li> </ul> <p>Let me know how I can do this with LINQ and C#.</p> <p>Thanks All</p> <p><strong>EDIT 2 Showing Code:</strong></p> <pre><code> List&lt;game&gt; inventory = new List&lt;game&gt;(); drinkingforDataContext db = new drinkingforDataContext(); foreach (string item in tbTitle.Text.Split(' ')) { List&lt;game&gt; getItems = (from dfg in db.drinkingfor_Games where dfg.game_Name.Contains(tbTitle.Text) select new game { gameName = dfg.game_Name, gameID = Boomers.Utilities.Guids.Encoder.EncodeURLs(dfg.uid) }).ToList&lt;game&gt;(); for (int i = 0; i &lt; getItems.Count(); i++) { inventory.Add(getItems[i]); } } var items = (from xx in inventory group xx by xx into g let count = g.Count() orderby count descending select new { Count = count, gameName = g.Key.gameName, gameID = g.Key.gameID }); lvRelatedGames.DataSource = items; lvRelatedGames.DataBind(); </code></pre> <p>This query displays these results:</p> <ul> <li>1 hello world times</li> <li>1 hello world times</li> <li>1 Hello World.</li> <li>1 hello world times</li> <li>1 hello world times</li> <li>1 hello world times</li> <li>1 Hello World.</li> <li>1 hello world times</li> </ul> <p>It gives me the count and name, but it doesn't give me the ID of the game....</p> <p>It should display:</p> <ul> <li>6 hello world times 234234</li> <li>2 Hello World. 23432432</li> </ul>
454,621
7
2
null
2009-01-18 03:41:23.703 UTC
29
2022-06-07 10:06:33.997 UTC
2009-01-18 04:45:04.683 UTC
Scott
7,644
Scott
7,644
null
1
82
c#|linq
119,709
<p>You can use "group by" + "orderby". See <a href="http://msdn.microsoft.com/en-us/vcsharp/aa336746.aspx" rel="noreferrer">LINQ 101</a> for details</p> <pre><code>var list = new List&lt;string&gt; {"a", "b", "a", "c", "a", "b"}; var q = from x in list group x by x into g let count = g.Count() orderby count descending select new {Value = g.Key, Count = count}; foreach (var x in q) { Console.WriteLine("Value: " + x.Value + " Count: " + x.Count); } </code></pre> <p><strong>In response to <a href="https://stackoverflow.com/questions/454601/how-to-count-duplicates-in-list-with-linq#454652">this post</a> (now deleted):</strong></p> <p>If you have a list of some custom objects then you need to use <a href="http://msdn.microsoft.com/en-us/vcsharp/aa336754.aspx#comparer" rel="noreferrer">custom comparer</a> or group by specific property.</p> <p>Also query can't display result. Show us complete code to get a better help.</p> <p><strong>Based on your latest update:</strong></p> <p>You have this line of code:</p> <pre><code>group xx by xx into g </code></pre> <p>Since xx is a custom object system doesn't know how to compare one item against another. As I already wrote, you need to guide compiler and provide some property that will be used in objects comparison or provide custom comparer. Here is an example:</p> <p>Note that I use <strong>Foo.Name</strong> as a key - i.e. objects will be grouped based on value of <strong>Name</strong> property.</p> <p>There is one catch - you treat 2 objects to be duplicate based on their names, but what about Id ? In my example I just take Id of the first object in a group. If your objects have different Ids it can be a problem.</p> <pre><code>//Using extension methods var q = list.GroupBy(x =&gt; x.Name) .Select(x =&gt; new {Count = x.Count(), Name = x.Key, ID = x.First().ID}) .OrderByDescending(x =&gt; x.Count); //Using LINQ var q = from x in list group x by x.Name into g let count = g.Count() orderby count descending select new {Name = g.Key, Count = count, ID = g.First().ID}; foreach (var x in q) { Console.WriteLine("Count: " + x.Count + " Name: " + x.Name + " ID: " + x.ID); } </code></pre>
256,511
Skip List vs. Binary Search Tree
<p>I recently came across the data structure known as a <a href="http://en.wikipedia.org/wiki/Skip_list" rel="noreferrer"><em>skip list</em></a>. It seems to have very similar behavior to a binary search tree. </p> <p>Why would you ever want to use a skip list over a binary search tree? </p>
260,277
7
1
null
2008-11-02 04:39:55.603 UTC
199
2021-02-03 08:42:36.517 UTC
2018-03-12 22:26:57.34 UTC
Zach Scrivena
3,924,118
Claudiu
15,055
null
1
255
algorithm|language-agnostic|data-structures|binary-tree|skip-lists
75,782
<p>Skip lists are more amenable to concurrent access/modification. Herb Sutter wrote an <a href="http://www.ddj.com/hpc-high-performance-computing/208801371" rel="noreferrer">article</a> about data structure in concurrent environments. It has more indepth information.</p> <h2>The most frequently used implementation of a binary search tree is a <a href="http://en.wikipedia.org/wiki/Red-black_tree" rel="noreferrer">red-black tree</a>. The concurrent problems come in when the tree is modified it often needs to rebalance. The rebalance operation can affect large portions of the tree, which would require a mutex lock on many of the tree nodes. Inserting a node into a skip list is far more localized, only nodes directly linked to the affected node need to be locked.</h2> <p>Update from Jon Harrops comments</p> <p>I read Fraser and Harris's latest paper <a href="http://www.cl.cam.ac.uk/netos/papers/2007-cpwl.pdf" rel="noreferrer">Concurrent programming without locks</a>. Really good stuff if you're interested in lock-free data structures. The paper focuses on <a href="http://en.wikipedia.org/wiki/Transactional_memory" rel="noreferrer">Transactional Memory</a> and a theoretical operation multiword-compare-and-swap MCAS. Both of these are simulated in software as no hardware supports them yet. I'm fairly impressed that they were able to build MCAS in software at all.</p> <p>I didn't find the transactional memory stuff particularly compelling as it requires a garbage collector. Also <a href="http://en.wikipedia.org/wiki/Software_transactional_memory" rel="noreferrer">software transactional memory</a> is plagued with performance issues. However, I'd be very excited if hardware transactional memory ever becomes common. In the end it's still research and won't be of use for production code for another decade or so.</p> <p>In section 8.2 they compare the performance of several concurrent tree implementations. I'll summarize their findings. It's worth it to download the pdf as it has some very informative graphs on pages 50, 53, and 54.</p> <ul> <li><strong>Locking skip lists</strong> is insanely fast. They scale incredibly well with the number of concurrent accesses. This is what makes skip lists special, other lock based data structures tend to croak under pressure.</li> <li><strong>Lock-free skip lists</strong> are consistently faster than locking skip lists but only barely.</li> <li><strong>transactional skip lists</strong> are consistently 2-3 times slower than the locking and non-locking versions.</li> <li><strong>locking red-black trees</strong> croak under concurrent access. Their performance degrades linearly with each new concurrent user. Of the two known locking red-black tree implementations, one essentially has a global lock during tree rebalancing. The other uses fancy (and complicated) lock escalation but still doesn't significantly outperform the global lock version.</li> <li><strong>lock-free red-black trees</strong> don't exist (no longer true, see Update).</li> <li><strong>transactional red-black trees</strong> are comparable with transactional skip-lists. That was very surprising and very promising. Transactional memory, though slower if far easier to write. It can be as easy as quick search and replace on the non-concurrent version.</li> </ul> <hr /> <p>Update<br /> Here is paper about lock-free trees: <a href="http://www.cs.umanitoba.ca/%7Ehacamero/Research/RBTreesKim.pdf" rel="noreferrer">Lock-Free Red-Black Trees Using CAS</a>.<br /> I haven't looked into it deeply, but on the surface it seems solid.</p>
498,358
How do I do date math in a bash script on OS X Leopard?
<p>I realize I could whip up a little C or Ruby program to do this, but I want my script to have as few dependencies as possible.</p> <p>Given that <em>caveat</em>, how does one do date math in a bash script on OS X? I've seen a post (on another site) where someone did the following:</p> <pre>date -d "-1 day"</pre> <p>But this does not seem to work on OS X.</p> <p><strong>Addendum:</strong></p> <p>Several people have commented and responded that Ruby, Python, Perl, and the like come standard with OS X. I'm familiar with all three of these languages and could easily write a script that does what I want. As a matter of fact, I already have such a script, written in Ruby.</p> <p>So perhaps I should clarify what I mean by 'external dependency'. What I mean is, I don't want my bash script to have to call any other script external to it. In other words, I want it to use some utility available in a vanilla installation of OS X and already on the path.</p> <p>However, it doesn't look like this is possible, so I will have to make due with my external dependency: a Ruby script. </p>
498,398
8
1
null
2009-01-31 05:50:54.553 UTC
8
2019-06-20 14:41:34.51 UTC
2009-02-04 11:40:17.95 UTC
Revolucent
27,779
Revolucent
27,779
null
1
40
bash|macos|date-math
28,463
<pre><code>$ date -v -1d </code></pre> <p>-d sets Daylight Savings time flag.</p> <p>Try man date for more info.</p>
1,018,217
Can I set Java max heap size for running from a jar file?
<p>I am launching a java jar file which often requires more than the default 64MB max heap size. A 256MB heap size is sufficient for this app though. Is there anyway to specify (in the manifest maybe?) to always use a 256MB max heap size when launching the jar? (More specific details below, if needed.)</p> <hr> <p>This is a command-line app that I've written in Java, which does some image manipulation. On high-res images (about 12 megapixels and above, which is not uncommon) I get an OutOfMemoryError.</p> <p>Currently I'm launching the app from a jar file, i.e.</p> <p><code>java -jar MyApp.jar params...</code></p> <p>I can avoid an OutOfMemoryError by specifying 256MB max heap size on the command line, i.e.:</p> <p><code>java -Xmx256m -jar MyApp.jar params...</code></p> <p>However, I don't want to have to specify this, since I know that 256MB is sufficient even for high-res images. I'd like to have that information saved in the jar file. Is that possible?</p>
1,018,304
8
1
null
2009-06-19 14:23:01.137 UTC
8
2016-07-30 07:07:04.273 UTC
null
null
null
null
18,511
null
1
40
java|memory-management|jar
87,666
<p>you could also use a wrapper like <a href="http://launch4j.sourceforge.net/index.html" rel="noreferrer">launch4j</a> which will make an executable for most OS:es and allows you to specify VM options.</p>
672,843
Can templates be used to access struct variables by name?
<p>Let's suppose I have a struct like this:</p> <pre><code>struct my_struct { int a; int b; } </code></pre> <p>I have a function which should set a new value for either "a" or "b". This function also requires to specify which variable to set. A typical example would be like this:</p> <pre><code>void f(int which, my_struct* s, int new_value) { if(which == 0) s-&gt;a = new_value; else s-&gt;b = new_value; } </code></pre> <p>For reasons I won't write here I cannot pass the pointer to a/b to f. So I cannot call f with address of my_struct::a or my_struct::b. Another thing I cannot do is to declare a vector (int vars[2]) within my_struct and pass an integer as index to f. Basically in f I need to access the variables by name.</p> <p>Problem with previous example is that in the future I plan to add more variables to struct and in that case I shall remember to add more if statements to f, which is bad for portability. A thing I could do is write f as a macro, like this:</p> <pre><code>#define FUNC(which) void f(my_struct* s, int new_value) \ { \ s-&gt;which = new_value; \ } </code></pre> <p>and then I could call FUNC(a) or FUNC(b).</p> <p>This would work but I don't like using macros. So my question is: Is there a way to achieve the same goal using templates instead of macros?</p> <p><strong>EDIT</strong>: I'll try to explain why I cannot use pointers and I need access to variable by name. Basically the structure contains the state of a system. This systems needs to "undo" its state when requested. Undo is handled using an interface called undo_token like this:</p> <pre><code>class undo_token { public: void undo(my_struct* s) = 0; }; </code></pre> <p>So I cannot pass pointers to the undo method because of polymorphism (mystruct contains variables of other types as well).</p> <p>When I add a new variable to the structure I generally also add a new class, like this:</p> <pre><code>class undo_a : public undo_token { int new_value; public: undo_a(int new_value) { this-&gt;new_value = new_value; } void undo(my_struct *s) { s-&gt;a = new_value} }; </code></pre> <p>Problem is I don't know pointer to s when I create the token, so I cannot save a pointer to s::a in the constructor (which would have solved the problem). The class for "b" is the same, just I have to write "s->b" instead of s->a</p> <p>Maybe this is a design problem: I need an undo token per variable type, not one per variable...</p>
672,886
9
4
null
2009-03-23 10:20:37.62 UTC
18
2015-05-19 20:06:31.377 UTC
2015-05-19 20:06:31.377 UTC
happy_emi
1,144,157
happy_emi
62,811
null
1
19
c++|templates
19,510
<pre><code>#include &lt;iostream&gt; #include &lt;ostream&gt; #include &lt;string&gt; struct my_struct { int a; std::string b; }; template &lt;typename TObject, typename TMember, typename TValue&gt; void set( TObject* object, TMember member, TValue value ) { ( *object ).*member = value; } class undo_token {}; template &lt;class TValue&gt; class undo_member : public undo_token { TValue new_value_; typedef TValue my_struct::* TMember; TMember member_; public: undo_member(TMember member, TValue new_value): new_value_( new_value ), member_( member ) {} void undo(my_struct *s) { set( s, member_, new_value_ ); } }; int main() { my_struct s; set( &amp;s, &amp;my_struct::a, 2 ); set( &amp;s, &amp;my_struct::b, "hello" ); std::cout &lt;&lt; "s.a = " &lt;&lt; s.a &lt;&lt; std::endl; std::cout &lt;&lt; "s.b = " &lt;&lt; s.b &lt;&lt; std::endl; undo_member&lt;int&gt; um1( &amp;my_struct::a, 4 ); um1.undo( &amp;s ); std::cout &lt;&lt; "s.a = " &lt;&lt; s.a &lt;&lt; std::endl; undo_member&lt;std::string&gt; um2( &amp;my_struct::b, "goodbye" ); um2.undo( &amp;s ); std::cout &lt;&lt; "s.b = " &lt;&lt; s.b &lt;&lt; std::endl; return 0; } </code></pre>
771,973
Are there such things as variables within an Excel formula?
<p>I hate repeating functions, particularly in Excel formulas. Is there any way that I can avoid something like:</p> <pre><code>=IF( VLOOKUP(A1, B:B, 1, 0) &gt; 10, VLOOKUP(A1, B:B, 1, 0) - 10, VLOOKUP(A1, B:B, 1, 0) ) </code></pre> <p>[The above is just a simple example of the problem, and not a particular formula that I'm working with.]</p>
772,031
9
0
null
2009-04-21 10:30:46.683 UTC
13
2021-01-13 14:24:07.043 UTC
2018-12-22 19:56:22.02 UTC
null
6,186,333
null
62,872
null
1
49
excel
172,531
<p>You could define a name for the VLOOKUP part of the formula.</p> <ol> <li>Highlight the cell that contains this formula</li> <li>On the Insert menu, go Name, and click Define</li> <li>Enter a name for your variable (e.g. 'Value')</li> <li>In the Refers To box, enter your VLOOKUP formula: <code>=VLOOKUP(A1,B:B, 1, 0)</code></li> <li>Click Add, and close the dialog</li> <li>In your original formula, replace the VLOOKUP parts with the name you just defined: <code>=IF( Value &gt; 10, Value - 10, Value )</code></li> </ol> <p>Step (1) is important here: I guess on the second row, you want Excel to use <code>VLOOKUP(A2,B:B, 1, 0)</code>, the third row <code>VLOOKUP(A3,B:B, 1, 0)</code>, etc. Step (4) achieves this by using relative references (<code>A1</code> and <code>B:B</code>), not absolute references (<code>$A$1</code> and <code>$B:$B</code>).</p> <blockquote> <p><strong>Note:</strong> </p> <ol> <li><p><strong>For newer Excel versions</strong> with the ribbon, go to Formulas ribbon -> Define Name. It's the same after that. Also, to use your name, you can do "Use in Formula", right under Define Name, while editing the formula, or else start typing it, and Excel will suggest the name (credits: Michael Rusch)</p></li> <li><p><strong>Shortened steps:</strong> 1. Right click a cell and click Define name... 2. Enter a name and the formula which you want to associate with that name/local variable 3. Use variable (credits: Jens Bodal)</p></li> </ol> </blockquote>
246,725
How do I add tab completion to the Python shell?
<p>When starting a django application using <code>python manage.py shell</code>, I get an InteractiveConsole shell - I can use tab completion, etc.</p> <pre><code>Python 2.5.1 (r251:54863, Apr 15 2008, 22:57:26) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) </code></pre> <p>When just starting a python interpreter using <code>python</code>, it doesn't offer tab completion.</p> <p>Can someone tell me what django is doing to give me an interactive console, or what I need to do to start an interactive console without a django app?</p>
246,779
9
3
null
2008-10-29 13:09:10.09 UTC
62
2021-10-07 23:16:00.167 UTC
2015-10-15 09:32:08.613 UTC
S.Lott
11,343
ashchristopher
22,306
null
1
138
python|shell|interpreter
92,339
<p>I may have found a way to do it.</p> <p>Create a file .pythonrc</p> <pre><code># ~/.pythonrc # enable syntax completion try: import readline except ImportError: print("Module readline not available.") else: import rlcompleter readline.parse_and_bind("tab: complete") </code></pre> <p>then in your .bashrc file, add</p> <pre><code>export PYTHONSTARTUP=~/.pythonrc </code></pre> <p>That seems to work.</p>
977,883
Selecting only first-level elements in jquery
<p>How can I select the link elements of only the parent <code>&lt;ul&gt;</code> from a list like this? </p> <pre><code>&lt;ul&gt; &lt;li&gt;&lt;a href="#"&gt;Link&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Link&lt;/a&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="#"&gt;Link&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Link&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Link&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Link&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Link&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Link&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Link&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Link&lt;/a&gt;&lt;/li&gt; </code></pre> <p></p> <p>So in css <code>ul li a</code>, but not <code>ul li ul li a</code></p> <p>Thanks</p>
977,891
10
0
null
2009-06-10 20:11:31.42 UTC
29
2018-04-27 15:54:51.61 UTC
2009-06-10 20:20:04.447 UTC
null
16,417
null
120,832
null
1
97
jquery|html|css|css-selectors
133,770
<pre><code>$("ul &gt; li a") </code></pre> <p>But you would need to set a class on the root ul if you specifically want to target the outermost ul:</p> <pre><code>&lt;ul class="rootlist"&gt; ... </code></pre> <p>Then it's:</p> <pre><code>$("ul.rootlist &gt; li a").... </code></pre> <p>Another way of making sure you only have the root li elements:</p> <pre><code>$("ul &gt; li a").not("ul li ul a") </code></pre> <p>It looks kludgy, but it should do the trick</p>
48,935
How can I register a global hot key to say CTRL+SHIFT+(LETTER) using WPF and .NET 3.5?
<p>I'm building an application in C# using WPF. How can I bind to some keys?</p> <p>Also, how can I bind to the <a href="http://en.wikipedia.org/wiki/Windows_key" rel="noreferrer">Windows key</a>?</p>
49,171
11
2
null
2008-09-08 00:35:47.477 UTC
29
2020-09-11 08:08:35.757 UTC
2011-08-19 16:16:28.56 UTC
null
63,550
dubayou
146,637
null
1
52
c#|.net|wpf|windows|hotkeys
70,860
<p>I'm not sure of what you mean by &quot;global&quot; here, but here it goes (I'm assuming you mean a command at the application level, for example, <em>Save All</em> that can be triggered from anywhere by <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>S</kbd>.)</p> <p>You find the global <code>UIElement</code> of your choice, for example, the top level window which is the parent of all the controls where you need this binding. Due to &quot;bubbling&quot; of WPF events, events at child elements will bubble all the way up to the root of the control tree.</p> <p>Now, first you need</p> <ol> <li>to bind the Key-Combo with a Command using an <code>InputBinding</code> like this</li> <li>you can then hookup the command to your handler (e.g. code that gets called by <code>SaveAll</code>) via a <code>CommandBinding</code>.</li> </ol> <p>For the <kbd>Windows</kbd> Key, you use the right <a href="http://msdn.microsoft.com/en-us/library/system.windows.input.key.aspx" rel="nofollow noreferrer">Key</a> enumerated member, <strong><code>Key.LWin</code></strong> or <strong><code>Key.RWin</code></strong></p> <pre><code>public WindowMain() { InitializeComponent(); // Bind Key var ib = new InputBinding( MyAppCommands.SaveAll, new KeyGesture(Key.S, ModifierKeys.Shift | ModifierKeys.Control)); this.InputBindings.Add(ib); // Bind handler var cb = new CommandBinding( MyAppCommands.SaveAll); cb.Executed += new ExecutedRoutedEventHandler( HandlerThatSavesEverthing ); this.CommandBindings.Add (cb ); } private void HandlerThatSavesEverthing (object obSender, ExecutedRoutedEventArgs e) { // Do the Save All thing here. } </code></pre>
898,498
How can I reset the NSUserDefaults data in the iPhone simulator?
<p>I've added <code>NSUserDefaults</code> data retrieval to my app, which is pretty nice. But for testing I would like to reset all the data I added to the defaults database, so that everything is in the state when the user launches the app the first time.</p> <p>I tried to call:</p> <pre><code>[NSUserDefaults resetStandardUserDefaults]; </code></pre> <p>but that doesn't do anything. The defaults are still saved and can be retrieved.</p>
898,651
11
1
null
2009-05-22 15:32:32.633 UTC
16
2021-09-13 14:19:07.78 UTC
2020-10-10 01:56:24.877 UTC
null
819,340
null
62,553
null
1
56
iphone|ios|cocoa-touch|uikit|nsuserdefaults
48,048
<p>The easiest way is to remove the app from the simulator-- just like you'd remove it from a real phone, by tapping (clicking) and holding until the icons start vibrating. That removes all app data, and the next time you install from Xcode it's like the first time.</p> <p>If you have other app data you need to keep, you have a couple of options.</p> <p>One way would be to have some debug code that calls removeObjectForKey: on each of your defaults keys.</p> <p>The other is to find the directory where the simulator copy is installed, and remove the file containing the preferences. Use this to find the app:</p> <pre><code>ls -ld ~/Library/Application\ Support/iPhone\ Simulator/User/Applications/*/*.app </code></pre> <p>The full path to your app will contain directory whose name is a UUID. In that directory, look in Library/Preferences for the preferences file. Remove that, and user preferences are gone.</p>
216,748
Pros and cons of using nested C++ classes and enumerations?
<p>What are the pros and cons of using nested public C++ classes and enumerations? For example, suppose you have a class called <code>printer</code>, and this class also stores information on output trays, you could have:</p> <pre><code>class printer { public: std::string name_; enum TYPE { TYPE_LOCAL, TYPE_NETWORK, }; class output_tray { ... }; ... }; printer prn; printer::TYPE type; printer::output_tray tray; </code></pre> <p>Alternatively:</p> <pre><code>class printer { public: std::string name_; ... }; enum PRINTER_TYPE { PRINTER_TYPE_LOCAL, PRINTER_TYPE_NETWORK, }; class output_tray { ... }; printer prn; PRINTER_TYPE type; output_tray tray; </code></pre> <p>I can see the benefits of nesting private enums/classes, but when it comes to public ones, the office is split - it seems to be more of a style choice.</p> <p>So, which do you prefer and why?</p>
216,760
13
0
null
2008-10-19 18:05:21.08 UTC
17
2015-06-07 01:24:45.267 UTC
2015-06-07 01:24:45.267 UTC
null
64,046
Rob
9,236
null
1
49
c++|class|enums|nested
24,106
<h2>Nested classes</h2> <p>There are several side effects to classes nested inside classes that I usually consider flaws (if not pure antipatterns).</p> <p>Let's imagine the following code :</p> <pre><code>class A { public : class B { /* etc. */ } ; // etc. } ; </code></pre> <p>Or even:</p> <pre><code>class A { public : class B ; // etc. } ; class A::B { public : // etc. } ; </code></pre> <p>So:</p> <ul> <li><b>Privilegied Access:</b> A::B has privilegied access to all members of A (methods, variables, symbols, etc.), which weakens encapsulation</li> <li><b>A's scope is candidate for symbol lookup:</b> code from inside B will see <b>all</b> symbols from A as possible candidates for a symbol lookup, which can confuse the code</li> <li><b>forward-declaration:</b> There is no way to forward-declare A::B without giving a full declaration of A</li> <li><b>Extensibility:</b> It is impossible to add another class A::C unless you are owner of A</li> <li><b>Code verbosity:</b> putting classes into classes only makes headers larger. You can still separate this into multiple declarations, but there's no way to use namespace-like aliases, imports or usings.</li> </ul> <p>As a conclusion, unless exceptions (e.g. the nested class is an intimate part of the nesting class... And even then...), I see no point in nested classes in normal code, as the flaws outweights by magnitudes the perceived advantages.</p> <p>Furthermore, it smells as a clumsy attempt to simulate namespacing without using C++ namespaces.</p> <p>On the pro-side, you isolate this code, and if private, make it unusable but from the &quot;outside&quot; class...</p> <h2>Nested enums</h2> <p>Pros: Everything.</p> <p>Con: Nothing.</p> <p>The fact is enum items will pollute the global scope:</p> <pre><code>// collision enum Value { empty = 7, undefined, defined } ; enum Glass { empty = 42, half, full } ; // empty is from Value or Glass? </code></pre> <p>Ony by putting each enum in a different namespace/class will enable you to avoid this collision:</p> <pre><code>namespace Value { enum type { empty = 7, undefined, defined } ; } namespace Glass { enum type { empty = 42, half, full } ; } // Value::type e = Value::empty ; // Glass::type f = Glass::empty ; </code></pre> <p>Note that C++0x defined the class enum:</p> <pre><code>enum class Value { empty, undefined, defined } ; enum class Glass { empty, half, full } ; // Value e = Value::empty ; // Glass f = Glass::empty ; </code></pre> <p>exactly for this kind of problems.</p>
538,996
Constants in Objective-C
<p>I'm developing a <a href="http://en.wikipedia.org/wiki/Cocoa_%28API%29" rel="noreferrer">Cocoa</a> application, and I'm using constant <code>NSString</code>s as ways to store key names for my preferences.</p> <p>I understand this is a good idea because it allows easy changing of keys if necessary.<br> Plus, it's the whole 'separate your data from your logic' notion.</p> <blockquote> <p>Anyway, is there a good way to make these constants defined once for the whole application? </p> </blockquote> <p>I'm sure that there's an easy and intelligent way, but right now my classes just redefine the ones they use. </p>
539,191
14
1
null
2009-02-11 21:52:02.593 UTC
587
2022-01-20 18:45:31.353 UTC
2020-04-17 14:21:58.087 UTC
eJames
806,202
Allyn
57,414
null
1
1,043
ios|objective-c|cocoa|nsstring|constants
441,293
<p>You should create a header file like:</p> <pre><code>// Constants.h FOUNDATION_EXPORT NSString *const MyFirstConstant; FOUNDATION_EXPORT NSString *const MySecondConstant; //etc. </code></pre> <p>(You can use <code>extern</code> instead of <code>FOUNDATION_EXPORT</code> if your code will not be used in mixed C/C++ environments or on other platforms.)</p> <p>You can include this file in each file that uses the constants or in the pre-compiled header for the project.</p> <p>You define these constants in a <code>.m</code> file like:</p> <pre><code>// Constants.m NSString *const MyFirstConstant = @&quot;FirstConstant&quot;; NSString *const MySecondConstant = @&quot;SecondConstant&quot;; </code></pre> <p><code>Constants.m</code> should be added to your application/framework's target so that it is linked in to the final product.</p> <p>The advantage of using string constants instead of <code>#define</code>'d constants is that you can test for equality using pointer comparison (<code>stringInstance == MyFirstConstant</code>) which is much faster than string comparison (<code>[stringInstance isEqualToString:MyFirstConstant]</code>) (and easier to read, IMO).</p>
106,206
Fastest way to remove non-numeric characters from a VARCHAR in SQL Server
<p>I'm writing an import utility that is using phone numbers as a unique key within the import.</p> <p>I need to check that the phone number does not already exist in my DB. The problem is that phone numbers in the DB could have things like dashes and parenthesis and possibly other things. I wrote a function to remove these things, the problem is that it is <strong>slow</strong> and with thousands of records in my DB and thousands of records to import at once, this process can be unacceptably slow. I've already made the phone number column an index.</p> <p>I tried using the script from this post:<br> <a href="https://stackoverflow.com/questions/52315/t-sql-trim-nbsp-and-other-non-alphanumeric-characters">T-SQL trim &amp;nbsp (and other non-alphanumeric characters)</a></p> <p>But that didn't speed it up any.</p> <p>Is there a faster way to remove non-numeric characters? Something that can perform well when 10,000 to 100,000 records have to be compared.</p> <p>Whatever is done needs to perform <strong>fast</strong>.</p> <p><strong>Update</strong><br> Given what people responded with, I think I'm going to have to clean the fields before I run the import utility. </p> <p>To answer the question of what I'm writing the import utility in, it is a C# app. I'm comparing BIGINT to BIGINT now, with no need to alter DB data and I'm still taking a performance hit with a very small set of data (about 2000 records). </p> <p>Could comparing BIGINT to BIGINT be slowing things down?</p> <p>I've optimized the code side of my app as much as I can (removed regexes, removed unneccessary DB calls). Although I can't isolate SQL as the source of the problem anymore, I still feel like it is.</p>
106,226
15
0
null
2008-09-19 22:42:41.613 UTC
20
2017-03-14 13:37:20.533 UTC
2017-05-23 12:10:26.62 UTC
Nigel Campbell
-1
Dan
392
null
1
68
sql|sql-server|performance|optimization
202,708
<p>I may misunderstand, but you've got two sets of data to remove the strings from one for current data in the database and then a new set whenever you import.</p> <p>For updating the existing records, I would just use SQL, that only has to happen once.</p> <p>However, SQL isn't optimized for this sort of operation, since you said you are writing an import utility, I would do those updates in the context of the import utility itself, not in SQL. This would be much better performance wise. What are you writing the utility in?</p> <p>Also, I may be completely misunderstanding the process, so I apologize if off-base.</p> <p><b>Edit: </b><br> For the initial update, if you are using SQL Server 2005, you could try a CLR function. Here's a quick one using regex. Not sure how the performance would compare, I've never used this myself except for a quick test right now.</p> <pre><code>using System; using System.Data; using System.Text.RegularExpressions; using System.Data.SqlClient; using System.Data.SqlTypes; using Microsoft.SqlServer.Server; public partial class UserDefinedFunctions { [Microsoft.SqlServer.Server.SqlFunction] public static SqlString StripNonNumeric(SqlString input) { Regex regEx = new Regex(@"\D"); return regEx.Replace(input.Value, ""); } }; </code></pre> <p>After this is deployed, to update you could just use:</p> <pre><code>UPDATE table SET phoneNumber = dbo.StripNonNumeric(phoneNumber) </code></pre>
147,557
Error logging in C#
<p>I am making my switch from coding in C++ to C#. I need to replace my C++ error logging/reporting macro system with something similar in C#.</p> <p>In my C++ source I can write</p> <p>LOGERR("Some error"); or LOGERR("Error with inputs %s and %d", stringvar, intvar);</p> <p>The macro &amp; supporting library code then passes the (possibly varargs) formatted message into a database along with the source file, source line, user name, and time. The same data is also stuffed into a data structure for later reporting to the user.</p> <p>Does anybody have C# code snippets or pointers to examples that do this basic error reporting/logging?</p> <p><strong>Edit:</strong> At the time I asked this question I was really new to .NET and was unaware of System.Diagnostics.Trace. System.Diagnostics.Trace was what I needed at that time. Since then I have used log4net on projects where the logging requirements were larger and more complex. Just edit that 500 line XML configuration file and log4net will do everything you will ever need :)</p>
148,117
15
0
null
2008-09-29 04:53:55.007 UTC
43
2018-11-17 17:37:48.637 UTC
2009-06-11 16:15:25.623 UTC
null
6,188
rschuler
6,188
null
1
74
c#|error-reporting|error-logging
91,980
<p>Lots of log4net advocates here so I'm sure this will be ignored, but I'll add my own preference:</p> <pre><code>System.Diagnostics.Trace </code></pre> <p>This includes listeners that listen for your <code>Trace()</code> methods, and then write to a log file/output window/event log, ones in the framework that are included are <code>DefaultTraceListener</code>, <code>TextWriterTraceListener</code> and the <code>EventLogTraceListener</code>. It allows you to specify levels (Warning,Error,Info) and categories.</p> <p><a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.trace.aspx" rel="noreferrer">Trace class on MSDN</a><br> <a href="https://stackoverflow.com/questions/286060/what-do-i-need-to-change-to-alllow-my-iis7-asp-net-3-5-application-to-create-an/7848414#7848414">Writing to the Event Log in a Web Application</a><br> <a href="http://www.anotherchris.net/log4net/udptracelistener-a-udp-tracelistener-compatible-with-log4netlog4j/" rel="noreferrer">UdpTraceListener - write log4net compatible XML messages to a log viewer such as log2console</a></p>
141,855
Programmatically Lighten a Color
<p><strong>Motivation</strong></p> <p>I'd like to find a way to take an arbitrary color and lighten it a few shades, so that I can programatically create a nice gradient from the one color to a lighter version. The gradient will be used as a background in a UI.</p> <p><strong>Possibility 1</strong></p> <p>Obviously I can just split out the RGB values and increase them individually by a certain amount. Is this actually what I want?</p> <p><strong>Possibility 2</strong></p> <p>My second thought was to convert the RGB to HSV/HSB/HSL (Hue, Saturation, Value/Brightness/Lightness), increase the brightness a bit, decrease the saturation a bit, and then convert it back to RGB. Will this have the desired effect in general?</p>
141,861
19
1
null
2008-09-26 20:43:35.59 UTC
37
2021-11-28 00:21:23.643 UTC
2008-10-21 13:25:58.523 UTC
Keng
730
Dave Lockhart
9,960
null
1
77
user-interface|language-agnostic|colors
61,252
<p>I would go for the second option. Generally speaking the RGB space is not really good for doing color manipulation (creating transition from one color to an other, lightening / darkening a color, etc). Below are two sites I've found with a quick search to convert from/to RGB to/from HSL:</p> <ul> <li><a href="http://marcocorvi.altervista.org/games/imgpr/rgb-hsl.htm" rel="noreferrer">from the "Fundamentals of Computer Graphics"</a></li> <li><a href="http://www.geekymonkey.com/Programming/CSharp/RGB2HSL_HSL2RGB.htm" rel="noreferrer">some sourcecode in C#</a> - should be easy to adapt to other programming languages.</li> </ul>
543,579
What is the most impressive Lisp application?
<p>I know that this is subjective and all, but still, can you provide some list of serious applications that were written in Lisp (perhaps along with what Lisp it is)?</p>
543,661
21
0
null
2009-02-12 21:57:38.733 UTC
35
2017-09-08 12:50:36.46 UTC
2017-09-08 12:45:06.603 UTC
starblue
3,924,118
Bartosz Radaczyński
985
null
1
49
lisp
25,977
<p><a href="http://itasoftware.com/careers/l_e_t_lisp.html?catid=8" rel="noreferrer">ITA Software's</a> airline-fare search service. See <a href="http://www.demarcken.org/carl/papers/ITA-software-travel-complexity/ITA-software-travel-complexity.pdf" rel="noreferrer">here</a> to understand why this is impressive.</p>
208,580
Naming of ID columns in database tables
<p>I was wondering peoples opinions on the naming of ID columns in database tables.</p> <p>If I have a table called Invoices with a primary key of an identity column I would call that column InvoiceID so that I would not conflict with other tables and it's obvious what it is.</p> <p>Where I am workind current they have called all ID columns ID.</p> <p>So they would do the following:</p> <pre><code>Select i.ID , il.ID From Invoices i Left Join InvoiceLines il on i.ID = il.InvoiceID </code></pre> <p>Now, I see a few problems here:<br> 1. You would need to alias the columns on the select<br> 2. ID = InvoiceID does not fit in my brain<br> 3. If you did not alias the tables and referred to InvoiceID is it obvious what table it is on?</p> <p>What are other peoples thoughts on the topic?</p>
7,504,177
24
2
null
2008-10-16 13:34:43.28 UTC
30
2021-08-17 10:34:46.19 UTC
null
null
null
Arry
26,792
null
1
114
sql|naming-conventions
56,457
<p>ID is a SQL Antipattern. See <a href="http://www.amazon.com/s/ref=nb_sb_ss_i_1_5?url=search-alias%3Dstripbooks&amp;field-keywords=sql+antipatterns&amp;sprefix=sql+a" rel="noreferrer">http://www.amazon.com/s/ref=nb_sb_ss_i_1_5?url=search-alias%3Dstripbooks&amp;field-keywords=sql+antipatterns&amp;sprefix=sql+a</a></p> <p>If you have many tables with ID as the id you are making reporting that much more difficult. It obscures meaning and makes complex queries harder to read as well as requiring you to use aliases to differentiate on the report itself. </p> <p>Further if someone is foolish enough to use a natural join in a database where they are available, you will join to the wrong records. </p> <p>If you would like to use the USING syntax that some dbs allow, you cannot if you use ID. </p> <p>If you use ID you can easily end up with a mistaken join if you happen to be copying the join syntax (don't tell me that no one ever does this!)and forget to change the alias in the join condition. </p> <p>So you now have</p> <pre><code>select t1.field1, t2.field2, t3.field3 from table1 t1 join table2 t2 on t1.id = t2.table1id join table3 t3 on t1.id = t3.table2id </code></pre> <p>when you meant</p> <pre><code>select t1.field1, t2.field2, t3.field3 from table1 t1 join table2 t2 on t1.id = t2.table1id join table3 t3 on t2.id = t3.table2id </code></pre> <p>If you use tablenameID as the id field, this kind of accidental mistake is far less likely to happen and much easier to find. </p>
2,524
Visual Studio "Unable to start debugging on the web server. The web server did not respond in a timely manner."
<p>I get the following error pretty regularly when compiling in Visual Studio and running my web application:</p> <p>"Unable to start debugging on the web server. The web server did not respond in a timely manner. This may be because another debugger is already attached to the web server."</p> <p>Normally this is after having debug the application once already. From the command line I run "iisreset /restart" and it fixes the problem.</p> <p>How do I prevent this from happening in the first place?</p>
151,931
31
1
null
2008-08-05 16:18:18.853 UTC
8
2021-10-25 11:57:41.453 UTC
2015-12-16 11:12:22.233 UTC
hop
1,657,610
null
417
null
1
55
asp.net|visual-studio|visual-studio-2008|debugging|iis
73,716
<p>I find that this happens if I'm debugging with Firefox as my browser. When I exit Firefox the VS2005/8 debug session doesn't terminate. I have not found a solution for this (yet).</p> <p>If this is what's happening with you then a quicker solution than running iisreset is to hit Shift-F5 when in Visual Studio and this will terminate the current debug session. You can then hit F5 and this will start a new debug session.</p>
34,566,806
Why use contextlib.suppress as opposed to try/except with pass?
<p>Why would one use <a href="https://docs.python.org/3/library/contextlib.html#contextlib.suppress"><code>contextlib.suppress</code></a> to suppress an exception, instead of <code>try</code>/<code>except</code> with a <code>pass</code>?</p> <p>There is no difference in the amount of characters between these two methods (if anything, <code>suppress</code> has more characters), and even though code is often counted in LOC instead of characters, <code>suppress</code> also seems to be much slower than <code>try</code>/<code>except</code> in both cases, when an error is raised and when it's not:</p> <pre><code>Python 3.5.0 (v3.5.0:374f501f4567, Sep 13 2015, 02:27:37) [MSC v.1900 64 bit (AMD64)] on win32 Type "copyright", "credits" or "license()" for more information. &gt;&gt;&gt; from timeit import timeit &gt;&gt;&gt; # With an error &gt;&gt;&gt; timeit("""with suppress(ValueError): x = int('a')""", setup="from contextlib import suppress") 1.9571568971892543 &gt;&gt;&gt; timeit("""try: x = int('a') except ValueError: pass""") 1.0758466499161656 &gt;&gt;&gt; # With no error &gt;&gt;&gt; timeit("""with suppress(ValueError): x = int(3)""", setup="from contextlib import suppress") 0.7513525708063895 &gt;&gt;&gt; timeit("""try: x = int(3) except ValueError: pass""") 0.10141028937128027 &gt;&gt;&gt; </code></pre>
34,574,395
2
5
null
2016-01-02 14:13:03.26 UTC
5
2016-01-03 07:43:15.033 UTC
null
null
null
null
2,505,645
null
1
52
python|python-3.x
15,713
<p>It is two lines less code without sacrificing readability.</p> <p>It might be especially convenient for nested or consecutive code blocks. Compare:</p> <pre><code>try: a() try: b() except B: pass except A: pass </code></pre> <p>vs.:</p> <pre><code>with suppress(A): a() with suppress(B): b() </code></pre> <p>It also allows to express the intent: </p> <ul> <li><code>with suppress(SpecificError): do_something()</code> says <em>don't propagate the error if it is raised while doing something</em></li> <li><code>try: do_something() except SpecificError: pass</code> says <em>do something and don't propagate the error if it is raised</em></li> </ul> <p>It is less important because most people won't notice the difference.</p>
34,429,622
How can I clear test data in Stripe via the API?
<p>I'm familiar with the process of clearing test data via the dashboard in Stripe (as per the image). </p> <p>For testing purposes, I would like to clear the test data as part of the tear down process of our unit tests - to have a clean state at the end of each test cycle. </p> <p>The API documentation doesn't mention anything, so is there an undocumented way to clear the test data?</p> <p>Just a note, in the new dashboard, test data deletion lives on the <a href="https://dashboard.stripe.com/developers" rel="noreferrer">Developers tab</a>:</p> <p><a href="https://i.stack.imgur.com/kTtFY.png" rel="noreferrer"><img src="https://i.stack.imgur.com/kTtFY.png" alt="enter image description here"></a></p>
34,431,782
4
8
null
2015-12-23 06:08:52.443 UTC
3
2020-02-25 04:16:55.14 UTC
2020-02-25 04:16:55.14 UTC
null
1,606,729
null
614,112
null
1
45
php|stripe-payments
21,004
<p>No, it isn't possible to clean all test data via the API -- only via the dashboard. Sorry!</p> <p>In the Dashboard, the option now lives at the bottom of the <a href="https://dashboard.stripe.com/developers" rel="noreferrer">Developers page</a></p>
6,787,142
BigDecimal equals() versus compareTo()
<p>Consider the simple test class:</p> <pre><code>import java.math.BigDecimal; /** * @author The Elite Gentleman * */ public class Main { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub BigDecimal x = new BigDecimal("1"); BigDecimal y = new BigDecimal("1.00"); System.out.println(x.equals(y)); System.out.println(x.compareTo(y) == 0 ? "true": "false"); } } </code></pre> <p>You can (consciously) say that <code>x</code> is equal to <code>y</code> (not object reference), but when you run the program, the following result shows:</p> <pre><code>false true </code></pre> <p>Question: What's the difference between <code>compareTo()</code> and <code>equals()</code> in <code>BigDecimal</code> that <code>compareTo</code> can determine that <code>x</code> is equal to <code>y</code>?</p> <p>PS: I see that BigDecimal has an <code>inflate()</code> method on <code>equals()</code> method. What does <code>inflate()</code> do actually?</p>
6,787,166
4
2
null
2011-07-22 07:56:17.577 UTC
22
2020-05-28 12:56:02.95 UTC
2011-07-22 08:52:31.527 UTC
null
213,269
null
251,173
null
1
184
java|equals|bigdecimal|compareto
147,515
<p>The answer is in <a href="http://download.oracle.com/javase/6/docs/api/java/math/BigDecimal.html#equals%28java.lang.Object%29" rel="noreferrer">the JavaDoc of the <code>equals()</code> method</a>:</p> <blockquote> <p>Unlike <a href="http://download.oracle.com/javase/6/docs/api/java/math/BigDecimal.html#compareTo%28java.math.BigDecimal%29" rel="noreferrer"><code>compareTo</code></a>, this method considers two <code>BigDecimal</code> objects equal only if they are equal in value and scale (thus 2.0 is not equal to 2.00 when compared by this method).</p> </blockquote> <p>In other words: <code>equals()</code> checks if the <code>BigDecimal</code> objects are <strong>exactly</strong> the same in <strong>every</strong> aspect. <code>compareTo()</code> "only" compares their numeric value.</p> <p>As to <em>why</em> <code>equals()</code> behaves this way, this has been answered <a href="https://stackoverflow.com/questions/14102083/why-is-bigdecimal-equals-specified-to-compare-both-value-and-scale-individually">in this SO question</a>.</p>
15,980,318
Trigger Error: The current transaction cannot be committed and cannot support operations that write to the log file
<p>So I am getting the following error message from SQL Server when sp_SomeProc tries to execute an invalid sql statement. I get the error: </p> <pre><code>The current transaction cannot be committed and cannot support operations that write to the log file. </code></pre> <p><strong>Any ideas on what I am doing wrong? (this is just a sample that I created to mimic the problem so please no "why are you doing this?", "this has security implications", etc..)</strong></p> <hr> <p>So my table looks like:</p> <pre><code>CREATE TABLE tSOMETABLE ( RecID INT NOT NULL IDENTITY(1,1) Val VARCHAR(20), CONSTRAINT [PK_tSOMETABLE] PRIMARY KEY CLUSTERED ( RecID ASC ) ) </code></pre> <p>So in my trigger I have:</p> <pre><code>CREATE TRIGGER [dbo].[TR_tSOMETABLE_INSERT] ON [dbo].[tSOMETABLE] FOR INSERT AS SET NOCOUNT ON BEGIN BEGIN SELECT * INTO #temp FROM INSERTED WHILE EXISTS (SELECT 1 FROM #temp) BEGIN DECLARE @RecID INT SELECT @RecID = RecID FROM #temp t EXEC dbo.sp_SomeProc @EventType = 'ON INSERT', @RecID = @RecID DELETE #temp WHERE @RecID = RecID END END END </code></pre> <p>Now the code of sp_SomeProc looks like:</p> <pre><code>CREATE PROC sp_SomeProc ( @EventType VARCHAR(50), @RecID INT, @Debug BIT = 0 ) AS BEGIN SET NOCOUNT ON DECLARE @ProcTable TABLE ( RecID INT NOT NULL IDENTITY(1,1), Cmd VARCHAR(MAX) ) INSERT INTO @ProcTable(Cmd) SELECT 'EXEC sp_who' UNION SELECT 'EXEC sp_SomeStoredProcThatDoesntExist' DECLARE @RecID INT SELECT @RecID = MIN(RecID) FROM @ProcTable WHILE @RecID IS NOT NULL BEGIN DECLARE @sql VARCHAR(MAX) SELECT @sql = cmd FROM @ProcTable WHERE RecID = @RecID IF @Debug = 1 PRINT @sql ELSE BEGIN BEGIN TRY EXEC(@sql) END TRY BEGIN CATCH DECLARE @Msg VARCHAR(MAX), @ErrorNumber INT, @ErrorSeverity INT, @ErrorState int, @ErrorProcedure nvarchar(256), @ErrorLine int, @ErrorMessage nvarchar(MAX) SELECT @Msg = 'Failed While Executing: ' + @sql SELECT @ErrorNumber = ERROR_NUMBER(), @ErrorSeverity = ERROR_SEVERITY(), @ErrorState = ERROR_STATE(), @ErrorProcedure = ERROR_PROCEDURE(), @ErrorLine = ERROR_LINE(), @ErrorMessage = ERROR_MESSAGE() -- DO SOME MORE STUFF HERE AND THEN ... RAISERROR(@ErrorMessage, @ErrorSeverity, @ErrorState) END CATCH END SELECT @RecID = MIN(RecID) FROM @ProcTable WHERE RecID &gt; @RecID END END </code></pre> <p>So to test I try:</p> <pre><code>INSERT INTO tSOMETABLE(Val) SELECT 'Hello' </code></pre>
15,984,867
1
2
null
2013-04-12 20:29:02.853 UTC
9
2013-04-13 06:13:32.153 UTC
2013-04-12 22:10:18.553 UTC
null
400,589
null
400,589
null
1
13
sql|sql-server|sql-server-2008|sql-server-2008-r2
48,844
<p>This error occurs when you use a try/catch block inside of a transaction. Let's consider a trivial example:</p> <pre><code>SET XACT_ABORT ON IF object_id('tempdb..#t') IS NOT NULL DROP TABLE #t CREATE TABLE #t (i INT NOT NULL PRIMARY KEY) BEGIN TRAN INSERT INTO #t (i) VALUES (1) INSERT INTO #t (i) VALUES (2) INSERT INTO #t (i) VALUES (3) INSERT INTO #t (i) VALUES (1) -- dup key error, XACT_ABORT kills the batch INSERT INTO #t (i) VALUES (4) COMMIT TRAN SELECT * FROM #t </code></pre> <p>When the fourth insert causes an error, the batch is terminated and the transaction rolls back. No surprises so far. </p> <p>Now let's attempt to handle that error with a TRY/CATCH block:</p> <pre><code>SET XACT_ABORT ON IF object_id('tempdb..#t') IS NOT NULL DROP TABLE #t CREATE TABLE #t (i INT NOT NULL PRIMARY KEY) BEGIN TRAN INSERT INTO #t (i) VALUES (1) INSERT INTO #t (i) VALUES (2) BEGIN TRY INSERT INTO #t (i) VALUES (3) INSERT INTO #t (i) VALUES (1) -- dup key error END TRY BEGIN CATCH SELECT ERROR_MESSAGE() END CATCH INSERT INTO #t (i) VALUES (4) /* Error the Current Transaction cannot be committed and cannot support operations that write to the log file. Roll back the transaction. */ COMMIT TRAN SELECT * FROM #t </code></pre> <p>We caught the duplicate key error, but otherwise, we're not better off. Our batch still gets terminated, and our transaction still gets rolled back. The reason is actually very simple: </p> <p><strong>TRY/CATCH blocks don't affect transactions.</strong> </p> <p>Due to having XACT_ABORT ON, the moment the duplicate key error occurs, the transaction is doomed. It's done for. It's been fatally wounded. It's been shot through the heart...and the error's to blame. TRY/CATCH gives SQL Server...a bad name. (sorry, couldn't resist) </p> <p>In other words, it will <strong>NEVER</strong> commit and will <strong>ALWAYS</strong> be rolled back. All a TRY/CATCH block can do is break the fall of the corpse. We can use the <strong>XACT_STATE()</strong> function to see if our transaction is committable. If it is not, the only option is to roll back the transaction. </p> <pre><code>SET XACT_ABORT ON -- Try with it OFF as well. IF object_id('tempdb..#t') IS NOT NULL DROP TABLE #t CREATE TABLE #t (i INT NOT NULL PRIMARY KEY) BEGIN TRAN INSERT INTO #t (i) VALUES (1) INSERT INTO #t (i) VALUES (2) SAVE TRANSACTION Save1 BEGIN TRY INSERT INTO #t (i) VALUES (3) INSERT INTO #t (i) VALUES (1) -- dup key error END TRY BEGIN CATCH SELECT ERROR_MESSAGE() IF XACT_STATE() = -1 -- Transaction is doomed, Rollback everything. ROLLBACK TRAN IF XACT_STATE() = 1 --Transaction is commitable, we can rollback to a save point ROLLBACK TRAN Save1 END CATCH INSERT INTO #t (i) VALUES (4) IF @@TRANCOUNT &gt; 0 COMMIT TRAN SELECT * FROM #t </code></pre> <p>Triggers always execute within the context of a transaction, so if you can avoid using TRY/CATCH inside them, things are much simpler. </p> <p>For a solution to your problem, a CLR Stored Proc could connect back to SQL Server in a separate connection to execute the dynamic SQL. You gain the ability to execute the code in a new transaction and the error handling logic is both easy to write and easy to understand in C#.</p>
15,639,781
How to find the Qt5 CMake module on Windows
<p>I'm trying to make a very basic Qt5 application using CMake on Windows. I used the documentation <a href="http://qt-project.org/doc/qt-5.0/qtdoc/cmake-manual.html#imported-targets" rel="noreferrer">of Qt5 to use CMake</a>, and my <code>main.cpp</code> file just contains a <code>main</code> function.</p> <p>My <code>CMakeLists.txt</code> is exactly:</p> <pre><code>cmake_minimum_required(VERSION 2.8.9) project(testproject) # Find includes in corresponding build directories set(CMAKE_INCLUDE_CURRENT_DIR ON) # Instruct CMake to run moc automatically when needed. set(CMAKE_AUTOMOC ON) # Find the QtWidgets library find_package(Qt5Widgets) # Tell CMake to create the helloworld executable add_executable(helloworld hello.cpp) # Use the Widgets module from Qt 5. qt5_use_modules(helloworld Widgets) </code></pre> <p>When in MSysGit bash I enter</p> <pre><code>$ cmake -G"Visual Studio 11" </code></pre> <p>I get this output:</p> <pre><code>$ cmake -G"Visual Studio 11" -- The C compiler identification is MSVC 17.0.60204.1 -- The CXX compiler identification is MSVC 17.0.60204.1 -- Check for working C compiler using: Visual Studio 11 -- Check for working C compiler using: Visual Studio 11 -- works -- Detecting C compiler ABI info -- Detecting C compiler ABI info - done -- Check for working CXX compiler using: Visual Studio 11 -- Check for working CXX compiler using: Visual Studio 11 -- works -- Detecting CXX compiler ABI info -- Detecting CXX compiler ABI info - done CMake Warning at CMakeLists.txt:11 (find_package): By not providing "FindQt5Widgets.cmake" in CMAKE_MODULE_PATH this project has asked CMake to find a package configuration file provided by "Qt5Widgets", but CMake did not find one. Could not find a package configuration file provided by "Qt5Widgets" with any of the following names: Qt5WidgetsConfig.cmake qt5widgets-config.cmake Add the installation prefix of "Qt5Widgets" to CMAKE_PREFIX_PATH or set "Qt5Widgets_DIR" to a directory containing one of the above files. If "Qt5Widgets" provides a separate development package or SDK, be sure it has been installed. CMake Error at CMakeLists.txt:17 (qt5_use_modules): Unknown CMake command "qt5_use_modules". -- Configuring incomplete, errors occurred! </code></pre> <p>Do you have any ideas?</p>
15,663,114
6
0
null
2013-03-26 14:37:40.413 UTC
16
2020-02-12 22:12:13.3 UTC
2020-02-12 22:09:38.493 UTC
null
3,440,745
null
466,464
null
1
48
c++|windows|visual-c++|cmake|qt5
86,999
<p>After the lines</p> <pre><code>cmake_minimum_required(VERSION 2.8.9) project(testproject) </code></pre> <p>add</p> <pre><code>set (CMAKE_PREFIX_PATH "C:\\Qt\\Qt5.0.1\\5.0.1\\msvc2010\\") </code></pre> <p>This solves the problem.</p>
15,568,700
Best java server implementation for socket.io
<p>I wanted to use <a href="http://socket.io/">socket.io</a> to push data from server to browser but the project is java tomcat one, and there are many implementation in <em>Github</em> for the server implementation of <code>socket.io</code>. Most of them say they are <em>deprecated</em> or better ones are available.Can anyone suggest me a good implementation.</p> <p>And I see lot of demo and sample code about broadcasting with <code>socket.io</code>. My requirement is to push different messages to different clients. Could someone point me to some good demo or tutorial dealing with such stuff?</p> <p>Thanks </p>
16,711,894
3
2
null
2013-03-22 11:01:55.553 UTC
13
2016-08-30 14:17:10.423 UTC
2013-03-27 19:38:14.82 UTC
null
1,554,314
null
2,182,269
null
1
49
java|socket.io
69,328
<p>As author, I suggest to try my SocketIO server implementation on Java:</p> <p><a href="https://github.com/mrniko/netty-socketio" rel="noreferrer">https://github.com/mrniko/netty-socketio</a></p> <p>Stable and production ready lib.</p>
33,030,933
Android 6.0 open failed: EACCES (Permission denied)
<p>I have added <code>uses-permission</code> including <code>WRITE_EXTERNAL_STORAGE</code>,<code>MOUNT_UNMOUNT_FILESYSTEMS</code>,<code>READ_EXTERNAL_STORAGE</code> to <code>AndroidManifest.xml</code>.</p> <p>When I tried to run my application in Nexus5 (Android 6.0),it threw a exception as below:</p> <p><code>java.io.IOException: open failed: EACCES (Permission denied)</code></p> <p>And I tried another Android phone(Android 5.1),everything was OK.Here's the code:</p> <pre><code>private File createImageFile() throws IOException { String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); String imageFileName = "JPEG_" + timeStamp + "_"; File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); File image = File.createTempFile(imageFileName, ".jpg", storageDir); currentPhotoPath = image.getAbsolutePath(); return image; } </code></pre> <p>Does Android 6.0 have difference about permission? </p>
33,031,091
9
5
null
2015-10-09 06:01:56.45 UTC
18
2020-05-25 11:02:07.423 UTC
2017-06-02 08:51:27.687 UTC
user6796473
null
null
4,666,365
null
1
58
java|android|android-6.0-marshmallow
99,060
<p>Android added new permission model for <strong>Android 6.0 (Marshmallow)</strong>.</p> <p><a href="http://www.captechconsulting.com/blogs/runtime-permissions-best-practices-and-how-to-gracefully-handle-permission-removal" rel="noreferrer">http://www.captechconsulting.com/blogs/runtime-permissions-best-practices-and-how-to-gracefully-handle-permission-removal</a></p> <p>So you have to check <code>Runtime Permission</code> :</p> <p><strong>What Are Runtime Permissions?</strong></p> <p>With Android 6.0 Marshmallow, Google introduced a new permission model that allows users to better understand why an application may be requesting specific permissions. Rather than the user blindly accepting all permissions at install time, the user is now prompted to accept permissions as they become necessary during application use.</p> <p><strong>When to Implement the New Model?</strong></p> <p>it doesn’t require full support until you choose to target version 23 in your application. If you are targeting version 22 or below, your application will request all permissions at install time just as it would on any device running an OS below Marshmallow.</p> <p>This information is taken from here :</p> <p>Please check How to implement from this link :</p> <p><a href="http://www.captechconsulting.com/blogs/runtime-permissions-best-practices-and-how-to-gracefully-handle-permission-removal" rel="noreferrer">http://www.captechconsulting.com/blogs/runtime-permissions-best-practices-and-how-to-gracefully-handle-permission-removal</a></p>
50,497,583
when to disconnect and when to end a pg client or pool
<p>My stack is node, express and the pg module. I really try to understand by the documentation and some outdated tutorials. <strong>I dont know when and how to disconnect and to end a client.</strong></p> <p>For some routes I decided to use a pool. This is my code</p> <pre><code>const pool = new pg.Pool({ user: 'pooluser',host: 'localhost',database: 'mydb',password: 'pooluser',port: 5432}); pool.on('error', (err, client) =&gt; { console.log('error ', err); process.exit(-1); }); app.get('/', (req, res)=&gt;{ pool.connect() .then(client =&gt; { return client.query('select ....') .then(resolved =&gt; { client.release(); console.log(resolved.rows); }) .catch(e =&gt; { client.release(); console.log('error', e); }) pool.end(); }) }); </code></pre> <p>In the routes of the CMS, I use client instead of pool that has different db privileges than the pool.</p> <pre><code>const client = new pg.Client({ user: 'clientuser',host: 'localhost',database: 'mydb',password: 'clientuser',port: 5432}); client.connect(); const signup = (user) =&gt; { return new Promise((resolved, rejeted)=&gt;{ getUser(user.email) .then(getUserRes =&gt; { if (!getUserRes) { return resolved(false); } client.query('insert into user(username, password) values ($1,$2)',[user.username,user.password]) .then(queryRes =&gt; { client.end(); resolved(true); }) .catch(queryError =&gt; { client.end(); rejeted('username already used'); }); }) .catch(getUserError =&gt; { return rejeted('error'); }); }) }; const getUser = (username) =&gt; { return new Promise((resolved, rejeted)=&gt;{ client.query('select username from user WHERE username= $1',[username]) .then(res =&gt; { client.end(); if (res.rows.length == 0) { return resolved(true); } resolved(false); }) .catch(e =&gt; { client.end(); console.error('error ', e); }); }) } </code></pre> <p>In this case if I get a <code>username already used</code> and try to re-post with another username, the query of the <code>getUser</code> never starts and the page hangs. If I remove the <code>client.end();</code> from both functions, it will work. </p> <p>I am confused, so please advice on how and when to disconnect and to completely end a pool or a client. Any hint or explanation or tutorial will be appreciated. </p> <p>Thank you</p>
50,630,792
4
6
null
2018-05-23 21:15:28.453 UTC
11
2021-02-04 08:07:27.84 UTC
2021-02-04 08:07:27.84 UTC
null
12,788,110
null
2,045,016
null
1
46
node.js|postgresql|node-postgres
41,446
<p>First, from the <a href="https://node-postgres.com/features/pooling" rel="noreferrer">pg documentation</a>*:</p> <pre><code>const { Pool } = require('pg') const pool = new Pool() // the pool with emit an error on behalf of any idle clients // it contains if a backend error or network partition happens pool.on('error', (err, client) =&gt; { console.error('Unexpected error on idle client', err) // your callback here process.exit(-1) }) // promise - checkout a client pool.connect() .then(client =&gt; { return client.query('SELECT * FROM users WHERE id = $1', [1]) // your query string here .then(res =&gt; { client.release() console.log(res.rows[0]) // your callback here }) .catch(e =&gt; { client.release() console.log(err.stack) // your callback here }) }) </code></pre> <p>This code/construct is <strong>suficient</strong>/made to get your pool working, providing the <strong>your thing here</strong> things. If you shut down your application, the connection will hang normaly, since the pool is created well, exactly not to hang, even if it does provides a manual way of hanging, see last section of the <a href="https://node-postgres.com/features/pooling" rel="noreferrer">article</a>. Also look at the previous red section which says "You must always return the client..." to accept</p> <ul> <li>the mandatory <code>client.release()</code> instruction</li> <li>before accesing argument.</li> <li>you scope/closure client within your callbacks.</li> </ul> <p><strong>Then</strong>, from the <a href="https://node-postgres.com/api/client" rel="noreferrer">pg.client documentation</a>*:</p> <p><em>Plain text query with a promise</em> </p> <pre><code>const { Client } = require('pg').Client const client = new Client() client.connect() client.query('SELECT NOW()') // your query string here .then(result =&gt; console.log(result)) // your callback here .catch(e =&gt; console.error(e.stack)) // your callback here .then(() =&gt; client.end()) </code></pre> <p>seems to me the clearest syntax:</p> <ul> <li>you end the client whatever the results.</li> <li>you access the result before <em>ending</em> the client.</li> <li>you don´t scope/closure the client within your callbacks</li> </ul> <p>It is this sort of oposition between the two syntaxes that may be confusing at first sight, but there is no magic in there, it is implementation construction syntax. Focus on <strong>your</strong> callbacks and queries, not on those constructs, just pick up the most elegant for your eyes and <strong>feed it with your</strong> code.</p> <p>*I added the comments <em>// your xxx here</em> for clarity</p>
10,723,700
How can vim keep the content of register when pasting over selected text?
<p>I have a line of text I have yanked <code>yy</code>. Now I want to use this text to replace lines at several other places. The trouble is that when I select <code>V</code> the line to be replaced, and paste <code>p</code>, the text that was selected is automatically yanked! That's what I don't want.</p> <p>Changing the register does not work, because both the paste and the yank are done with the newly selected register.</p> <p>What is the command to keep the content of the register when pasting over selected text?</p>
10,723,838
2
5
null
2012-05-23 15:58:44.973 UTC
6
2016-04-09 21:21:07.027 UTC
null
null
null
null
212,063
null
1
44
vim|copy-paste
8,148
<p>Each time you <code>p</code> over something it goes into the default register.</p> <p>To work around this feature you have to use <code>"_</code>, "the black hole register", before you <code>p</code>. Here is a custom mapping I have in my <code>~/.vimrc</code>:</p> <pre><code>vnoremap &lt;leader&gt;p "_dP </code></pre> <p>It deletes the selected content and drops it in the black hole register (this means that the selected text disappears forever) and puts the content of the default register in place of the previously selected text while leaving the default register intact.</p> <p>I use it often when I need to replace a loooooooong url in a few places with another looooooong url and crafting a <code>s//</code> would be too cumbersome.</p>
10,393,462
Placing Unicode character in CSS content value
<p>I have a problem. I have found the HTML code for the downwards arrow, <code>&amp;darr;</code> (&darr;)</p> <p>Cool. Now I need to use it in CSS like so:</p> <pre><code>nav a:hover {content:"&amp;darr";} </code></pre> <p>That obviously won't work since <code>&amp;darr;</code> is an HTML symbol. There seems to be less info about these "escaped unicode" symbols that are used in css. There are other symbols like <code>\2020</code> that I found but no arrows. What are the arrow codes?</p>
10,393,517
1
7
null
2012-05-01 04:13:25.583 UTC
65
2015-04-26 09:29:40.183 UTC
2012-05-01 04:35:44.167 UTC
null
405,017
null
901,834
null
1
375
css|unicode|symbols|unicode-escapes
446,130
<p>Why don't you just save/serve the CSS file as UTF-8?</p> <pre><code>nav a:hover:after { content: "↓"; } </code></pre> <p>If that's not good enough, and you want to keep it all-ASCII:</p> <pre><code>nav a:hover:after { content: "\2193"; } </code></pre> <p>The general format for a Unicode character inside a string is <code>\000000</code> to <code>\FFFFFF</code> – a backslash followed by six hexadecimal digits. You can leave out leading <code>0</code> digits when the Unicode character is the last character in the string or when you add a space after the Unicode character. See the spec below for full details.</p> <hr> <p><a href="http://www.w3.org/TR/CSS2/syndata.html#characters" rel="noreferrer">Relevant part of the CSS2 spec</a>:</p> <blockquote> <p>Third, backslash escapes allow authors to refer to characters they cannot easily put in a document. In this case, the backslash is followed by at most six hexadecimal digits (0..9A..F), which stand for the ISO 10646 (<a href="http://www.w3.org/TR/CSS2/refs.html#ref-ISO10646" rel="noreferrer">[ISO10646]</a>) character with that number, which must not be zero. (It is undefined in CSS 2.1 what happens if a style sheet <em>does</em> contain a character with Unicode codepoint zero.) If a character in the range [0-9a-fA-F] follows the hexadecimal number, the end of the number needs to be made clear. There are two ways to do that:</p> <ol> <li>with a space (or other white space character): "\26 B" ("&amp;B"). In this case, user agents should treat a "CR/LF" pair (U+000D/U+000A) as a single white space character.</li> <li>by providing exactly 6 hexadecimal digits: "\000026B" ("&amp;B")</li> </ol> <p>In fact, these two methods may be combined. Only one white space character is ignored after a hexadecimal escape. Note that this means that a "real" space after the escape sequence must be doubled.</p> <p>If the number is outside the range allowed by Unicode (e.g., "\110000" is above the maximum 10FFFF allowed in current Unicode), the UA may replace the escape with the "replacement character" (U+FFFD). If the character is to be displayed, the UA should show a visible symbol, such as a "missing character" glyph (cf. <a href="http://www.w3.org/TR/CSS2/fonts.html#algorithm" rel="noreferrer">15.2,</a> point 5).</p> <ul> <li>Note: Backslash escapes are always considered to be part of an <a href="http://www.w3.org/TR/CSS2/syndata.html#value-def-identifier" rel="noreferrer">identifier</a> or a string (i.e., "\7B" is not punctuation, even though "{" is, and "\32" is allowed at the start of a class name, even though "2" is not).<br> The identifier "te\st" is exactly the same identifier as "test".</li> </ul> </blockquote> <hr> <p>Comprehensive list: <a href="http://www.fileformat.info/info/unicode/char/2193/index.htm" rel="noreferrer">Unicode Character 'DOWNWARDS ARROW' (U+2193)</a>.</p>
31,824,660
what is the control flow of django rest framework
<p>I am developing an api for a webapp. I was initially using tastypie and switched to <code>django-rest-framework (drf)</code>. Drf seems very easy to me. What I intend to do is to create nested user profile object. My models are as below</p> <pre><code>from django.db import models from django.contrib.auth.models import User class nestedmodel(models.Model): info = models.CharField(null=True, blank=True, max_length=100) class UserProfile(models.Model): add_info = models.CharField(null=True, blank=True, max_length=100) user = models.OneToOneField(User) nst = models.ForeignKey(nestedmodel) </code></pre> <p>I have other models that have Foreignkey Relation. My Serializers are as below</p> <pre><code>from django.contrib.auth.models import User, Group from rest_framework import serializers from quickstart.models import UserProfile, nestedmodel class NestedSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = nestedmodel fields = ('info', ) class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('url', 'username', 'email', 'groups') class GroupSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Group fields = ('url', 'name') class UserProfileSerializer(serializers.HyperlinkedModelSerializer): user = UserSerializer() nst = NestedSerializer() class Meta: model = UserProfile user = UserSerializer(many=True) nested = NestedSerializer(many=True) fields = ('nst', 'user') </code></pre> <p>I can override methods like <code>create(self, validated_data):</code> without any issues. But What I want to know is <code>to which method should the response returned by create() goes</code>, or in other words <code>Which method calls create()</code>. In tastypie <code>Resources.py</code> is the file to override to implement custom methods. And Resources.py contains the order in which methods are being called. Which is the file in drf that serves the same purpose and illustrates the control flow like Resources.py in tastypie?. </p>
31,833,300
2
2
null
2015-08-05 06:12:50.2 UTC
12
2015-08-06 15:32:28.9 UTC
2015-08-05 10:13:24.367 UTC
null
3,127,207
null
3,127,207
null
1
13
django|django-rest-framework|tastypie|control-flow
8,387
<p>So the flow goes something like:</p> <ol> <li>Viewset's <a href="https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/mixins.py#L18-L23" rel="noreferrer"><code>create()</code></a> method which is implemented in <code>CreateModelMixin</code></li> <li>That creates serializer and validates it. Once valid, it uses viewset's <a href="https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/mixins.py#L25-L26" rel="noreferrer"><code>perform_create()</code></a></li> <li>That calls serializer's <a href="https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/serializers.py#L138-L180" rel="noreferrer"><code>save()</code></a> method</li> <li>That then in turn calls serializer's either <a href="https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/serializers.py#L175" rel="noreferrer"><code>create()</code></a> or <a href="https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/serializers.py#L170" rel="noreferrer"><code>update()</code></a> depending if instance was passed to serializer (which it was not in step 1)</li> <li><code>create()</code> or <code>update()</code> then create/update instance which is then saved on <code>serializer.instance</code></li> <li>Viewset then returns response with data coming from <a href="https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/mixins.py#L23" rel="noreferrer"><code>serializer.data</code></a></li> <li><a href="https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/serializers.py#L210-L228" rel="noreferrer"><code>serializer.data</code></a> is actually a property on serializer which is responsible for serializing the instance to a dict</li> <li>To serialize data, <a href="https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/serializers.py#L438-L458" rel="noreferrer"><code>to_representation()</code></a> is used.</li> <li>Then response data (Python dict) is rendered to a output format via <a href="https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/renderers.py" rel="noreferrer">renderers</a> which could be json, xml, etc</li> </ol> <blockquote> <p>And Resources.py contains the order in which methods are being called. Which is the file in drf that serves the same purpose and illustrates the control flow like Resources.py in tastypie?.</p> </blockquote> <p>Guess that would be a combination of files. Its probably better to think in terms of classes/concepts you are touching since in DRF you can inherit from multiple things for create your classes. So the thing which glues everything together are <a href="http://www.django-rest-framework.org/api-guide/viewsets/" rel="noreferrer">viewsets</a>. Then there are various viewset mixins which actually glue the viewset to the serializer and different CRUD operations.</p>
33,266,156
React + Redux - Input onChange is very slow when typing in when the input have a value from the state
<p>I got my input who is filled by a value from my state.</p> <pre><code>&lt;input id="flashVars" name="flashVars" type="text" value={settings.flashVarsValue} disabled={isDisabled} onChange={handleChange} /&gt; </code></pre> <p><code>Settings</code>is my state with Redux. When i put a value into my input, i must specify a <code>onChange</code> function. This is my onChange function:</p> <pre><code>handleFlashVarsChange(e) { let { dispatch } = this.props; dispatch( changeFlashVarsValue(e.target.value) ); } </code></pre> <p>It change the state value <code>flashVarsValue</code> for the value of the input. But when i type in my input, it lags. I don't understand why i should call the dispatch each time i change the input value. </p> <p>Is there any way who can give less lags?</p> <p>My reducer:</p> <pre><code>import { ACTIONS } from '../utils/consts'; const initialState = { ... flashVarsValue: '', ... }; export function formSettings(state = initialState, action = '') { switch (action.type) { ... case ACTIONS.CHANGE_FLASHVARS_VALUE: return Object.assign({}, state, { flashVarsValue: action.data }); default: return state; } } </code></pre> <p>My action:</p> <pre><code>export function changeFlashVarsValue(data) { return { type: ACTIONS.CHANGE_FLASHVARS_VALUE, data: data } } </code></pre> <p>Thank you</p>
33,587,618
7
10
null
2015-10-21 17:59:03.933 UTC
11
2021-02-08 21:14:31.84 UTC
2015-10-21 19:07:28.24 UTC
null
1,060,566
null
1,060,566
null
1
54
javascript|reactjs|redux
41,860
<p>I had a similar problem when I was editing a grid with a million rows, so what I did was to change the update logic, in your case <code>handleChange</code> to be called only on the event <code>onBlur</code> instead of <code>onChange</code>. This will only trigger the update when you lose focus. But don't know if this would be a satisfactory solution for you.</p>
22,548,223
How to retrieve Facebook friend's information with Python-Social-auth and Django
<p>How can I retrieve Facebook friend's information using Python-Social-auth and Django? I already retrieve a profile information and authenticate the user, but I want to get more information about their friends and invite them to my app. Thanks!</p>
22,790,358
2
2
null
2014-03-21 00:57:57.733 UTC
8
2017-01-02 22:00:13.03 UTC
2015-10-28 13:47:24.847 UTC
null
2,301,092
null
2,301,092
null
1
11
python|django|facebook|facebook-graph-api|python-social-auth
7,141
<p>You can do it using Facebook API. Firstly, you need obtain the token of your Facebook application (<code>FACEBOOK_APP_ACCESS_TOKEN</code>) <a href="https://developers.facebook.com/tools/accesstoken/" rel="noreferrer">https://developers.facebook.com/tools/accesstoken/</a> or from <code>social_user.extra_data['access_token']</code></p> <p>Then with this token you can send the requests you need, for example, this code gets all the friends of the authenticated user with their id, name, location, picture:</p> <pre><code>social_user = request.user.social_auth.filter( provider='facebook', ).first() if social_user: url = u'https://graph.facebook.com/{0}/' \ u'friends?fields=id,name,location,picture' \ u'&amp;access_token={1}'.format( social_user.uid, social_user.extra_data['access_token'], ) request = urllib2.Request(url) friends = json.loads(urllib2.urlopen(request).read()).get('data') for friend in friends: # do something </code></pre> <p>Depending on what fields you want to get you can set the permissions here: <a href="https://developers.facebook.com/apps/" rel="noreferrer">https://developers.facebook.com/apps/</a> -> Your App -> App Details -> App Centre Permissions</p> <p>or set your permissions in <code>settings.py</code>:</p> <pre><code>SOCIAL_AUTH_FACEBOOK_SCOPE = [ 'email', 'user_friends', 'friends_location', ] </code></pre>
13,672,543
Removing the common elements between two lists
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/3428536/python-list-subtraction-operation">Python list subtraction operation</a> </p> </blockquote> <p>I want to remove the common elements between two lists. I mean something like this</p> <hr> <pre><code>a=[1,2,3,4,5,6,7,8] b=[2,4,1] # I want the result to be like res=[3,5,6,7,8] </code></pre> <hr> <p>Is there any simple pythonic way to do this ?</p>
13,672,616
2
1
null
2012-12-02 18:50:39.72 UTC
6
2020-01-21 12:23:33.613 UTC
2017-05-23 12:08:54.16 UTC
null
-1
null
1,522,454
null
1
20
python
55,712
<p>use sets :</p> <pre><code>res = list(set(a)^set(b)) </code></pre>
13,653,692
device descriptor read/64, error -110
<p>I have a storage server running openmediavault which is based on debian. The OS is in a USB 3.0 Stick pluged directly on the motherboard (no USB-Hub or sth). The system was running fine for about 3 Months and 2 days ago I got this errors:</p> <pre><code>usb 1-3: device descriptor read/64, error -110 usb 1-3: device not accepting address 33, error -110 usb 1-3: device not accepting address 34, error -110 hub 1-0:1.0: unable to enumerate USB device on port 3 </code></pre> <p>When I restart the server, everything is fine again. The next day I face the same error...</p> <p>What can I do to fix this. I dont want to loose 3TB of data...</p>
13,661,508
5
0
null
2012-11-30 21:49:13.93 UTC
7
2020-02-02 16:29:31.677 UTC
2017-09-26 16:26:46.51 UTC
null
2,602,718
null
891,624
null
1
23
usb|debian
75,487
<p>USB error -110 means "Timeout expired before the transfer completed", which could be caused by anything. Most commonly, it's because power was exceeded; the host could not provide enough electric power for the pendrive to operate. Because it has not enough power also the USB stick cannot provide the device descriptor to the host, as a result it cannot be identified and so on. Maybe your motherboard it's overloaded with devices that consume all the available power.</p>
13,426,142
BufferedWriter not writing everything to its output file
<p>I have a Java program that reads some text from a file, line by line, and writes new text to an output file. But not all the text I write to my <code>BufferedWriter</code> appears in the output file after the program has finished. Why is that?</p> <p>The details: the program takes a CSV text document and converts it into SQL commands to insert the data into a table. The text file has more than 10000 lines which look similar to following:</p> <pre><code>2007,10,9,1,1,1006134,19423882 </code></pre> <p>The program seems to work fine except it just stops in the file randomly half way through creating a new SQL statement having printed it into the SQL file. It looks something like:</p> <pre><code>insert into nyccrash values (2007, 1, 2, 1, 4, 1033092, 259916); insert into nyccrash values (2007, 1, 1, 1, 1, 1020246, 197687); insert into nyccrash values (2007, 10, 9, 1 </code></pre> <p>This happens after about 10000 lines but several hundred lines before the end of the file. Where the break happens is between a <code>1</code> and a <code>,</code>. However, the characters doesn't seem important because if I change the <code>1</code> to a <code>42</code> the last thing written to the new file is <code>4</code>, which is cutting off the 2 from that integer. So it seems like the reader or writer must just be dying after writing/reading a certain amount.</p> <p>My Java code is as follows:</p> <pre><code>import java.io.*; public class InsertCrashData { public static void main (String args[]) { try { //Open the input file. FileReader istream = new FileReader("nyccrash.txt"); BufferedReader in = new BufferedReader(istream); //Open the output file. FileWriter ostream = new FileWriter("nyccrash.sql"); BufferedWriter out = new BufferedWriter(ostream); String line, sqlstr; sqlstr = "CREATE TABLE nyccrash (crash_year integer, accident_type integer, collision_type integer, weather_condition integer, light_condition integer, x_coordinate integer, y_coordinate integer);\n\n"; out.write(sqlstr); while((line = in.readLine())!= null) { String[] esa = line.split(","); sqlstr = "insert into nyccrash values ("+esa[0]+", "+esa[1]+", "+esa[2]+", "+esa[3]+", "+esa[4]+", "+esa[5]+", "+esa[6]+");\n"; out.write(sqlstr); } } catch(Exception e) { System.out.println(e); } } } </code></pre>
13,426,160
8
0
null
2012-11-16 23:55:54.717 UTC
9
2020-09-12 09:12:36.153 UTC
2015-01-03 11:43:51.583 UTC
null
545,127
null
1,191,087
null
1
34
java|file-io|bufferedwriter
51,208
<p>You need to close your <code>OutputStream</code> which will flush the remainder of your data:</p> <pre><code>out.close(); </code></pre> <p>The default buffer size for <code>BufferedWriter</code> is <a href="http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/io/BufferedWriter.java#BufferedWriter.0defaultCharBufferSize">8192 characters</a>, large enough to easily hold hundreds of lines of unwritten data.</p>
24,371,734
Firefox 'Cross-Origin Request Blocked' despite headers
<p>I'm trying to make a simple cross-origin request, and Firefox is consistently blocking it with this error: </p> <blockquote> <p>Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at [url]. This can be fixed by moving the resource to the same domain or enabling CORS. [url] </p> </blockquote> <p>It works fine in Chrome and Safari. </p> <p>As far as I can tell I've set all the correct headers on my PHP to allow this to work. Here's what my server is responding with </p> <pre><code>HTTP/1.1 200 OK Date: Mon, 23 Jun 2014 17:15:20 GMT Server: Apache/2.2.22 (Debian) X-Powered-By: PHP/5.4.4-14+deb7u8 Access-Control-Allow-Origin: * Access-Control-Allow-Methods: GET, POST, OPTIONS Access-Control-Allow-Headers: Content-Type Access-Control-Request-Headers: X-Requested-With, accept, content-type Vary: Accept-Encoding Content-Length: 186 Content-Type: text/html </code></pre> <p>I've tried using Angular, jQuery, and a basic XMLHTTPRequest object, like so:</p> <pre><code>var data = "id=1234" var request = new XMLHttpRequest({mozSystem: true}) request.onload = onSuccess; request.open('GET', 'https://myurl.com' + '?' + data, true) request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded') request.send() </code></pre> <p>...and it works in every browser except Firefox. Can anyone help with this?</p>
24,383,474
17
3
null
2014-06-23 17:22:15.473 UTC
37
2021-02-27 22:00:43.183 UTC
2019-01-03 20:24:49.07 UTC
null
2,756,409
null
1,727,254
null
1
158
javascript|firefox|cors|cross-domain
316,313
<p>Turns out this has nothing to do with CORS- it was a problem with the security certificate. Misleading errors = 4 hours of headaches.</p>
3,260,345
List of Rails Model Types
<p>Does someone have a complete list of model types that be specified when generating a model scaffolding </p> <p>e.g.</p> <pre><code>foo:string bar:text baz:boolean </code></pre> <p>etc...</p> <p>And what do these types map to in terms of default UI elements? Text field, Text area, radio button, checkbox, etc...</p>
3,260,466
2
1
null
2010-07-15 21:45:53.56 UTC
59
2017-12-23 02:42:22.463 UTC
null
null
null
null
135,435
null
1
125
ruby-on-rails
103,133
<p>The attributes are SQL types, hence the following are supported:</p> <ul> <li><code>:binary</code></li> <li><code>:boolean</code></li> <li><code>:date</code></li> <li><code>:datetime</code></li> <li><code>:decimal</code></li> <li><code>:float</code></li> <li><code>:integer</code></li> <li><code>:primary_key</code></li> <li><code>:string</code></li> <li><code>:text</code></li> <li><code>:time</code></li> <li><code>:timestamp</code></li> </ul> <p>These are documented under <strong>column</strong> in the <a href="http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#method-i-add_column" rel="noreferrer">Active Record API</a>.</p>
28,754,603
Indexing Pandas data frames: integer rows, named columns
<p>Say <code>df</code> is a pandas dataframe.</p> <ul> <li><code>df.loc[]</code> only accepts names </li> <li><code>df.iloc[]</code> only accepts integers (actual placements)</li> <li><code>df.ix[]</code> accepts both names and integers:</li> </ul> <p>When referencing rows, <code>df.ix[row_idx, ]</code> only wants to be given names. e.g. </p> <pre><code>df = pd.DataFrame({'a' : ['one', 'two', 'three','four', 'five', 'six'], '1' : np.arange(6)}) df = df.ix[2:6] print(df) 1 a 2 2 three 3 3 four 4 4 five 5 5 six df.ix[0, 'a'] </code></pre> <p>throws an error, it doesn't give return 'two'. </p> <p>When referencing columns, iloc is prefers integers, not names. e.g.</p> <pre><code>df.ix[2, 1] </code></pre> <p>returns 'three', not 2. (Although <code>df.idx[2, '1']</code> does return <code>2</code>).</p> <p>Oddly, I'd like the exact opposite functionality. Usually my column names are very meaningful, so in my code I reference them directly. But due to a lot of observation cleaning, the row names in my pandas data frames don't usually correspond to <code>range(len(df))</code>. </p> <p>I realize I can use:</p> <pre><code>df.iloc[0].loc['a'] # returns three </code></pre> <p>But it seems ugly! Does anyone know of a better way to do this, so that the code would look like this?</p> <pre><code>df.foo[0, 'a'] # returns three </code></pre> <p>In fact, is it possible to add on my own new method to <code>pandas.core.frame.DataFrame</code>s, so e.g. <code>df.idx(rows, cols)</code> is in fact <code>df.iloc[rows].loc[cols]</code>?</p>
67,260,019
6
4
null
2015-02-26 23:10:30.957 UTC
24
2022-03-16 15:00:40.943 UTC
2015-02-27 22:52:12.047 UTC
null
190,597
null
2,521,469
null
1
83
python|pandas|dataframe
80,593
<p>A very late answer but it amzed me that pandas still doesn't have such a function after all these years. If it irks you a lot, you can monkey-patch a custom indexer into the DataFrame:</p> <pre class="lang-py prettyprint-override"><code>class XLocIndexer: def __init__(self, frame): self.frame = frame def __getitem__(self, key): row, col = key return self.frame.iloc[row][col] pd.core.indexing.IndexingMixin.xloc = property(lambda frame: XLocIndexer(frame)) # Usage df.xloc[0, 'a'] # one </code></pre>
16,484,451
Change package name to existing Phonegap projects
<p>I have an android phonegap project, and an ios phonegap project.</p> <p>They were created using a given package name, but I now have to change this package name.</p> <p>In Android, I think I have to change package name in manifest, plus rename/move the java file in the src folder, and change inside this java file to reflect the new package name. Then clean and build. Does this sound right? </p> <p>I also noticed an option in Eclipse Android Tools >> Rename Application Package, where it asks for a package name. Would it make all necessary changes?</p> <p>How would I change the bundle ID in the XCode project so the project builds ok? Just edit the Bundle identifier as explained in this ticket would do? <a href="https://stackoverflow.com/questions/13927433/changing-xcode-package-name-without-creating-and-importing-to-new-project">Changing xcode package name without creating and importing to new project</a></p> <p>Thanks for any help.</p>
16,486,398
5
0
null
2013-05-10 14:20:29.51 UTC
9
2015-09-02 07:50:51.167 UTC
2017-05-23 12:25:26.727 UTC
null
-1
null
1,442,480
null
1
23
android|ios|cordova|package
34,791
<p>Yes, basically just change the android:package attribute in your manifest, and then refactor your src/ folders to follow that same package name.</p> <p>As an alternative you can use the rename option in Eclipse, but it will have to modify all of the R.class imports in <em>any</em> of your java files that use resources. This will look a little intimidating, but should work fine.</p>
16,277,339
Decrement value in mysql but not negative
<p>I want to decrement a value when user delete it in php and mysql. I want to check not to go below than 0. If value is 0 then do not <strong>decrement</strong>.</p> <pre><code>mysql_query("UPDATE table SET field = field - 1 WHERE id = $number"); </code></pre> <p>If field is <strong>0</strong> then do not do anything</p>
16,277,360
7
0
null
2013-04-29 11:19:41.63 UTC
8
2022-02-04 06:45:41.613 UTC
2013-04-29 11:45:11.57 UTC
null
460,368
user2244804
null
null
1
50
mysql|decrement
48,624
<p>Add another condition to update only if the <code>field</code> is greater <code>0</code></p> <pre><code>UPDATE table SET field = field - 1 WHERE id = $number and field &gt; 0 </code></pre>
17,634,627
How To Center A CSS Drop Down Menu
<p>I'm in need of some help. I have a CSS dropdown menu but i want the titles to be centered so on all screen sizes it would be in the middle, as at the moment its stuck to the left.</p> <p><a href="http://jsfiddle.net/y4vDC/" rel="noreferrer">http://jsfiddle.net/y4vDC/</a></p> <p>Any help would be greatly appreciated.</p> <p>Here is a bit of the HTML code:</p> <pre><code>&lt;div id='cssmenu'&gt; &lt;ul&gt; &lt;li&gt;&lt;a href='events.html'&gt;&lt;span&gt;Events&lt;/span&gt;&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; </code></pre>
17,634,713
3
0
null
2013-07-13 22:06:13.693 UTC
2
2019-11-02 17:44:31.893 UTC
2013-07-13 23:51:29.133 UTC
null
2,579,931
null
2,579,931
null
1
6
css|drop-down-menu|menu|center
71,004
<p>replace this css with what you have for #cssmenu > ul > li:</p> <pre><code>#cssmenu &gt; ul &gt; li { display:inline-block; margin-left: 15px; /* This is when the drop down box appears */ position: relative; } </code></pre> <p>and add this to your css codes:</p> <pre><code> #cssmenu &gt; ul { text-align:center; } </code></pre> <p>here it is: <a href="http://jsfiddle.net/y4vDC/10/" rel="noreferrer">http://jsfiddle.net/y4vDC/10/</a></p>
24,573,047
How can I find the number of unique characters in a string?
<p>I have found nothing particular for this purpose.</p> <p>I am trying to figure out a function that counts each of the characters' occurrences in a string, so that I can pull them out at the end from the length to find how many homogeneous characters are used in that string.</p> <p>I've tried with nested loop, the first to apply and the second to scan the string and conditionally fulfill the character if it does not appear elsewhere in the string:</p> <pre><code>size_t CountUniqueCharacters(char *str) { int i,j; char unique[CHAR_MAX]; for(i=strlen(str); i&gt;=0; i--) { for(j=strlen(str); j&gt;=0; j--) { if(str[i] != unique[j]) unique[j] = str[i]; } } return strlen(unique); } </code></pre> <p>This didn't work well.</p> <p>This is useful if you are willing to limit someone to type lazy names such as <code>"aaaaaaaaaaaaa"</code>.</p>
24,573,350
9
6
null
2014-07-04 11:13:57.693 UTC
3
2021-09-29 08:08:08.243 UTC
2019-09-22 12:24:55.397 UTC
null
10,795,151
null
3,696,914
null
1
5
c|count|character|charactercount
51,408
<p>This method has <code>O(n^2)</code> complexity, but it's very possible (though a bit more complex) to do this in <code>O(n)</code>.</p> <pre><code>int CountUniqueCharacters(char* str){ int count = 0; for (int i = 0; i &lt; strlen(str); i++){ bool appears = false; for (int j = 0; j &lt; i; j++){ if (str[j] == str[i]){ appears = true; break; } } if (!appears){ count++; } } return count; } </code></pre> <p>The method iterates over all the characters in the string - for each character, it checks if the character appeared in any of the previous characters. If it didn't, then the character is unique, and the count is incremented.</p>
24,678,045
Routing optional parameters in ASP.NET MVC 5
<p>I am creating an ASP.NET MVC 5 application and I have some issues with routing. We are using the attribute <code>Route</code> to map our routes in the web application. I have the following action:</p> <pre><code>[Route("{type}/{library}/{version}/{file?}/{renew?}")] public ActionResult Index(EFileType type, string library, string version, string file = null, ECacheType renew = ECacheType.cache) { // code... } </code></pre> <p>We only can access this URL if we pass the slash char <code>/</code> in the end of <code>url</code>, like this:</p> <pre><code>type/lib/version/file/cache/ </code></pre> <p>It works fine but does not work without <code>/</code>, I get a <code>404</code> not found error, like this</p> <pre><code>type/lib/version/file/cache </code></pre> <p>or this (without optional parameters):</p> <pre><code>type/lib/version </code></pre> <p>I would like to access with or without <code>/</code> char at the end of <code>url</code>. My two last parameters are optional. </p> <p>My <code>RouteConfig.cs</code> is like this:</p> <pre><code>public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapMvcAttributeRoutes(); } } </code></pre> <p>How can I solve it? Make the slash <code>/</code> be optional too?</p>
24,691,984
2
10
null
2014-07-10 13:37:55.967 UTC
8
2019-10-30 12:34:16.533 UTC
2014-07-10 14:20:10.237 UTC
null
316,799
null
316,799
null
1
38
c#|asp.net|asp.net-mvc|routing|asp.net-mvc-5
93,541
<p>Maybe you should try to have your enums as integers instead?</p> <p>This is how I did it</p> <pre><code>public enum ECacheType { cache=1, none=2 } public enum EFileType { t1=1, t2=2 } public class TestController { [Route("{type}/{library}/{version}/{file?}/{renew?}")] public ActionResult Index2(EFileType type, string library, string version, string file = null, ECacheType renew = ECacheType.cache) { return View("Index"); } } </code></pre> <p>And my routing file</p> <pre><code>public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); // To enable route attribute in controllers routes.MapMvcAttributeRoutes(); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }); } </code></pre> <p>I can then make calls like</p> <pre><code>http://localhost:52392/2/lib1/ver1/file1/1 http://localhost:52392/2/lib1/ver1/file1 http://localhost:52392/2/lib1/ver1 </code></pre> <p>or</p> <pre><code>http://localhost:52392/2/lib1/ver1/file1/1/ http://localhost:52392/2/lib1/ver1/file1/ http://localhost:52392/2/lib1/ver1/ </code></pre> <p>and it works fine...</p>
37,588,405
How to crop SVG file within HTML/CSS
<p>I have the following HTML file (<code>mypage.html</code>). A SVG <strong>file</strong> is attached as image into it.</p> <pre><code>&lt;!doctype html&gt; &lt;html&gt; &lt;body&gt; &lt;!-- Display legend --&gt; &lt;div&gt; &lt;center&gt; &lt;img src="circos-table-image-medium.svg" height=3500; width=3500; /&gt; &lt;/center&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>The page it generates looks like this:</p> <p><a href="https://i.stack.imgur.com/Glb4C.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/Glb4C.jpg" alt="enter image description here"></a></p> <p>Notice there are a large white space around the circle. How can I crop that within html or CSS?</p>
37,589,395
7
3
null
2016-06-02 09:52:11.607 UTC
13
2021-08-28 17:18:53.797 UTC
2016-06-02 12:17:59.64 UTC
null
67,405
null
67,405
null
1
36
html|css|image|svg
78,110
<h1>Crop</h1> <p>You can crop the image by using negative margins and fixing the size of the parent element: </p> <p><a href="https://stackoverflow.com/questions/493296/css-display-an-image-resized-and-cropped">CSS Display an Image Resized and Cropped</a></p> <h1>BUT THIS IS AN SVG!</h1> <p>Not only can you display an svg directly in html: </p> <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;svg viewBox="0 0 100 100" height="150px" width="150px"&gt; &lt;rect x="10" y="10" rx="5" width="80" height="80" fill="pink" stroke="green" stroke-width="5"/&gt; &lt;/svg&gt;</code></pre> </div> </div> </p> <p>but to crop/resize you can simply alter the viewBox attribute on the &lt;svg&gt; tag: </p> <pre><code>viewBox="0 0 100 100" </code></pre> <p>will display anything within 0 and 100 unit x &amp; y</p> <pre><code>viewBox="-100 -100 100 100" </code></pre> <p>Will display anything from -100 to 100 units x &amp; y</p> <pre><code>viewBox="50 50 500 500" </code></pre> <p>Will display anything from 50 to 500 units x &amp; y</p>
26,929,438
SSIS Access to SQL. Binding error: The binding status was "DT_NTEXT"
<p>I am trying to get an <strong>SSIS</strong> package inherited from a previous colleague to execute. The package pulls from an <strong>Access</strong> database and then puts the data into an <strong>SQL</strong> database.</p> <p>One of the fields, let's call it 'Recommendations' is of the type <strong>'memo'</strong> in the Access database. The column in the SQL output database is of the type <strong>varchar(max).</strong></p> <blockquote> <p>Error: 0xC002F446 at Data Flow Task, OLE DB Destination [218]: An error occurred while setting up a binding for the "Recommendations" column. The binding status was "DT_NTEXT". The data flow column type is "DBBINDSTATUS_UNSUPPORTEDCONVERSION". The conversion from the OLE DB type of "DBTYPE_IUNKNOWN" to the destination column type of "DBTYPE_WVARCHAR" might not be supported by this provider.</p> </blockquote> <p>What confused me further is that a different column of type <strong>memo</strong>, which is also processed as <strong>DT_NTEXT</strong>, and is also placed into a <strong>varchar(max)</strong> data type in the SQL db, does not throw an error message. I have tried numerous conversion object types but have yet to successfully execute the package.</p>
26,974,933
5
6
null
2014-11-14 11:53:32.497 UTC
2
2021-09-11 19:08:29.8 UTC
2014-11-14 23:23:14.22 UTC
null
1,808,674
null
2,344,998
null
1
10
sql-server|ms-access|visual-studio-2012|ssis
43,916
<p>I was able to reproduce this error by doing the following:</p> <ul> <li>Change the datatype of the destination column to <code>nvarchar(100)</code></li> <li>Make the incoming row from the dataflow be <code>ntext</code> with a length greater than <code>100</code></li> </ul> <p>This causes the destination column to overflow and throw the error that you stated in your problem:</p> <pre><code>Error: 0xC002F446 at Data Flow Task, OLE DB Destination [2]: An error occurred while setting up a binding for the "myCol" column. The binding status was "DT_NTEXT". The data flow column type is "DBBINDSTATUS_UNSUPPORTEDCONVERSION". The conversion from the OLE DB type of "DBTYPE_IUNKNOWN" to the destination column type of "DBTYPE_WVARCHAR" might not be supported by this provider. </code></pre> <p>So what I think is happening for you is that the <code>ntext</code> column has a value that exceeds <code>nvarchar(max)</code> causing it to overflow. </p> <p>In the previous version in which you convert the column to <code>dt_wstr(510)</code> - this works because you are probably truncating the ntext value to a size that will fit in the destination column. If the values do indeed fit into that size, then go with that as the solution. If your source values can be greater, than change the destination column in SQL to something that will fit. This can be <code>ntext</code>, but that is being deprecated, so it would be recommended to change this to <code>varbinary(max)</code>.</p>
21,755,799
Xcode: No Scheme
<p>I recently opened project in Xcode is now saying I have <code>No Scheme</code>: <img src="https://i.stack.imgur.com/k96WW.png" alt="enter image description here"></p> <p>When I try and <code>Manage Schemes</code> I am unable to <code>Autocreate Schemes Now</code> (a separate post but possibly related) and no Schemes are listed: <img src="https://i.stack.imgur.com/VIaYs.png" alt="enter image description here"></p> <p>and when I try and add a Scheme I get dialog saying <code>Target None</code>. <img src="https://i.stack.imgur.com/V6IBQ.png" alt="enter image description here"></p> <p>What's going on and how do I fix my Xcode project?</p>
23,207,699
20
4
null
2014-02-13 13:34:45.123 UTC
28
2022-09-02 08:25:20.037 UTC
2016-10-29 19:35:54.087 UTC
null
1,135,714
null
343,204
null
1
105
xcode
46,034
<p>Close Xcode and delete the folder <code>&lt;username&gt;.xcuserdatad</code> from within <code>&lt;projectname&gt;.xcodeproj/xcuserdata/</code>. Then restart Xcode, the schemes should re-appear.</p> <p><strong>EDIT:</strong> You may need to delete from <code>.xcodeproj</code> file and <code>.xcworkspace</code> file</p>
19,535,357
No best type found for implicitly-typed array
<p>Can someone explain me why this code:</p> <pre><code>var marketValueData = new[] { new { A = "" }, new { A = "" }, new { B = "" }, }; </code></pre> <p>Is giving me the error:</p> <blockquote> <p>No best type found for implicitly-typed array</p> </blockquote> <p>while this one works perfectly fine:</p> <pre><code>var marketValueData = new[] { new { A = "" }, new { A = "" }, new { A = "" }, }; </code></pre> <p>Apart from a different property (<code>B</code> in the last entry of the first example), they are the same. Yet the first one is not compiling. Why?</p>
34,368,861
5
4
null
2013-10-23 07:23:34.973 UTC
2
2021-07-02 19:46:55.93 UTC
2013-10-23 07:33:12.7 UTC
null
266,143
null
1,307,020
null
1
33
c#
18,770
<p>You can use:</p> <pre><code>var marketValueData = new object[] { new { A = "" }, new { A = "" }, new { B = "" }, ..., }; </code></pre>
19,630,994
How to check if a string is a valid regex in Python?
<p>In Java, I could use the following function to check if a string is a valid regex (<a href="https://stackoverflow.com/questions/6341367/how-to-check-if-the-string-is-a-regular-expression-or-not">source</a>):</p> <pre><code>boolean isRegex; try { Pattern.compile(input); isRegex = true; } catch (PatternSyntaxException e) { isRegex = false; } </code></pre> <p>Is there a Python equivalent of the <code>Pattern.compile()</code> and <code>PatternSyntaxException</code>? If so, what is it?</p>
19,631,067
2
7
null
2013-10-28 09:21:50.707 UTC
10
2020-09-17 14:46:47.297 UTC
2020-04-18 09:38:15.053 UTC
null
4,621,513
null
610,569
null
1
67
python|regex|string|validation
56,182
<p>Similar to Java. Use <a href="http://docs.python.org/2/library/re.html#re.error"><code>re.error</code></a> exception:</p> <pre><code>import re try: re.compile('[') is_valid = True except re.error: is_valid = False </code></pre> <blockquote> <p>exception <code>re.error</code></p> <p>Exception raised when a string passed to one of the functions here is not a valid regular expression (for example, it might contain unmatched parentheses) or when some other error occurs during compilation or matching. It is never an error if a string contains no match for a pattern.</p> </blockquote>
45,215,992
How to get img src in string in selenium using python
<p>I have a google search result, something like</p> <pre><code>div class="rc" h3 class="r" &lt;a href="somelink"&gt; &lt;img id="idFOO" src="data:somethingFOO" style="..."&gt; &lt;/a&gt; </code></pre> <p>I want to add somethingFOO (or data:somethingFOO) to a string using python &amp; selenium. How can I do that?</p>
45,216,303
2
5
null
2017-07-20 13:19:42.283 UTC
3
2017-07-20 13:34:24.88 UTC
null
null
null
null
8,332,655
null
1
8
python|image|selenium|src
41,384
<p>what you are interested is not a text, it's an attribute with name src. so if you will do something like that, you won't get what you want. </p> <p><code>find_element_by_id("idFOO").text</code></p> <p>if your html is like this, </p> <pre><code>&lt;input id="demo"&gt;hello world &lt;/input&gt; </code></pre> <p>then the following code will give you hello world </p> <pre><code>driver.find_element_by_id("demo").text </code></pre> <p>and following code will give you demo </p> <pre><code>driver.find_element_by_id("demo").get_attribute("id") </code></pre> <p>so in your case, it should be </p> <p><code>driver.find_element_by_id("idFOO").get_attribute("src")</code></p>
17,662,550
How to remove all instances of a class in javascript/jquery?
<p>I have this class called .m-active that is used multiple times throughout my HTML.</p> <p>Basically what I want to do is remove all instances of that class when a user clicks on an image (which does not have the m-active class) and add the m-active class to that image.</p> <p>For instance in a Backgrid row you might have a click handler as follows:</p> <pre><code>"click": function () { this.$el.addClass('m-active'); } </code></pre> <p>But you also want to remove that class from any rows to which it was previously added, so that only one row at a time has the .m-active class</p> <p>Does anyone know how this can be done in javascript/jquery?</p>
17,662,567
5
3
null
2013-07-15 19:46:08.763 UTC
5
2021-11-14 17:38:36.867 UTC
2015-02-05 15:12:13.94 UTC
null
34,806
null
2,584,871
null
1
29
javascript|jquery|removeclass
24,878
<p>With jQuery:</p> <pre><code>$('.m-active').removeClass('m-active'); </code></pre> <p>Explanation:</p> <ul> <li>Calling <code>$('.m-active')</code> selects all elements from the document that contain class <code>m-active</code></li> <li>Whatever you chain after this selector <strong>gets applied to all selected elements</strong></li> <li>Chaining the call with <code>removeClass('m-active')</code> removes class <code>m-active</code> from all of the selected elements</li> </ul> <p>For documentation on this specific method, see: <a href="http://api.jquery.com/removeClass/" rel="noreferrer">http://api.jquery.com/removeClass/</a></p> <p>Getting grasp of the whole selector thing with jQuery is challenging at first, but once you get it, you see everything in very different light. I encourage you to take a look into some good jQuery tutorials. I personally recommend checking out Codeacademy's jQuery track: <a href="http://www.codecademy.com/tracks/jquery" rel="noreferrer">http://www.codecademy.com/tracks/jquery</a></p>
17,308,629
Specify Vagrantfile path explicity, if not plugin
<p>Is there any way to explicity specify the path of a Vagrantfile? My company wants to do something like this: For testing on a confluence machine, type a command like <code>vagrant spinup confluence</code>, and then point that to a Vagrantfile in a different directory that contains the confluence environment, and then brings up all of these machines. </p> <p>However, it doesn't look like there is any way to explicitly state what Vagrantfile to use, and I'm somewhat (very) new at ruby, so I'm having a hard time writing my own plugin for it. Does anyone have recommendations on what to do? Or has anyone done something similar to this?</p>
17,312,425
6
0
null
2013-06-25 22:26:53.543 UTC
6
2022-01-06 12:10:24.287 UTC
null
null
null
null
2,498,414
null
1
34
ruby|plugins|development-environment|provisioning|vagrant
18,332
<p>There is no need to have a separate Vagrantfile, you can just define multiple VM's in the same file. See the documentation here: <a href="http://docs.vagrantup.com/v2/multi-machine/index.html" rel="noreferrer">http://docs.vagrantup.com/v2/multi-machine/index.html</a></p> <p>If you are just using one VM in your 'normal' environment and one VM for your 'confluence' environment then it is simply a case of just defining each VM and <code>vagrant up</code>-ing the specific VM.</p> <p>If you have multiple machines that make up each of your environments then you have two options, you can use regular expressions and make sure you name and type the commands correctly or you can put a bit of logic into your Vagrantfile to make it easier for people.</p> <p>For example with a little bit of a hack in your Vagrantfile you can do the following:</p> <pre><code>Vagrant.configure('2') do |config| if ARGV[1] == 'confluence' ARGV.delete_at(1) confluence = true else confluence = false end config.vm.provider :virtualbox do |virtualbox, override| #virtualbox.gui = true virtualbox.customize ["modifyvm", :id, "--natdnshostresolver1", "on"] virtualbox.customize ["modifyvm", :id, "--memory", 512] override.vm.box = 'Ubuntu 12.10 x64 Server' override.vm.box_url = 'http://goo.gl/wxdwM' end if confluence == false config.vm.define :normal1 do |normal1| normal1.vm.hostname = 'normal1' normal1.vm.network :private_network, ip: "192.168.1.1" end config.vm.define :normal2 do |normal2| normal2.vm.hostname = 'normal2' normal2.vm.network :private_network, ip: "192.168.1.2" end end if confluence == true config.vm.define :confluence1 do |confluence1| confluence1.vm.hostname = 'confluence1' confluence1.vm.network :private_network, ip: "192.168.1.3" end config.vm.define :confluence2 do |confluence2| confluence2.vm.hostname = 'confluence2' confluence2.vm.network :private_network, ip: "192.168.1.4" end end end </code></pre> <p>Now <code>vagrant up</code> brings up your normal vm's and <code>vagrant up confluence</code> brings up your confluence vm's!</p>
17,187,905
Whose responsibility is it to check data validity?
<p>I am confused as to whether it is the <em>caller</em> or the <em>callee's</em> responsibility to check for data legality.</p> <p>Should the <em>callee</em> check whether passed-in arguments should not be <code>null</code> and meet some other requirements so that the <em>callee</em> method can execute normally and successfully, and to catch any potential exceptions? Or it is the <em>caller's</em> responsibility to do this?</p>
17,187,939
13
4
null
2013-06-19 09:38:59.303 UTC
13
2013-06-26 12:43:19.307 UTC
2013-06-26 03:23:25.947 UTC
null
1,527,084
null
1,626,906
null
1
56
language-agnostic
4,010
<p>Both consumer side(client) <em>and</em> provider side(API) validation.</p> <p>Clients should do it because it means a better experience. For example, why do a network round trip just to be told that you've got one bad text field?</p> <p>Providers should do it because they should <em>never</em> trust clients (e.g. XSS and man in the middle attacks). How do you know the request wasn't intercepted? Validate everything.</p> <p>There are several levels of <strong>valid</strong>:</p> <ol> <li>All required fields present, correct formats. This is what the client validates.</li> <li># 1 plus valid relationships between fields (e.g. if X is present then Y is required).</li> <li># 1 plus # 2 plus business valid: meets <em>all</em> business rules for proper processing.</li> </ol> <p>Only the provider side can do #2 and #3.</p>
17,481,545
Migrate from Sublime text 2 to Sublime text3
<p>I need to migrate from sublime text 2 to sublime text 3 to have all the same configuration/plugins I have installed on the sublime text2.</p> <p>I installed sublime text 3, but it does not have any of the sublime text 2 packages and settings. I really dont know if there are any straight forward methods to migrate or just copy of some folders. </p>
17,537,817
5
4
null
2013-07-05 05:18:35.943 UTC
25
2019-04-06 05:06:42.5 UTC
2015-12-21 19:13:18.697 UTC
null
5,017,283
null
1,154,350
null
1
85
sublimetext2|sublimetext3|sublimetext
57,910
<p>I wrote a blog post detailing how to migrate over from Sublime Text 2 over to ST3.</p> <p>Read: <a href="http://wesbos.com/migrating-to-sublime-text-3/" rel="noreferrer">"Can I use ST3 yet? Migrating to Sublime Text 3"</a></p> <p><em>TLDR:</em></p> <ol> <li><p>Use git to install the python3 branch of Package Control. Step by step instructions <a href="http://wbond.net/sublime_packages/package_control/installation#ST3" rel="noreferrer">available here</a>;</p></li> <li><p>Move over all your folders in <code>Sublime Text 2/Packages/</code> to <code>Sublime Text 3/Packages/</code> except two: <code>Default</code> and <code>Package Control</code>.</p></li> </ol>
30,546,542
Token Based Authentication in ASP.NET Core (refreshed)
<p>I'm working with ASP.NET Core application. I'm trying to implement Token Based Authentication but can not figure out how to use new <a href="https://github.com/aspnet/Security">Security System</a>.</p> <p><strong>My scenario:</strong> A client requests a token. My server should authorize the user and return access_token which will be used by the client in following requests.</p> <p>Here are two great articles about implementing exactly what I need:</p> <ul> <li><a href="http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/">Token Based Authentication using ASP.NET Web API 2, Owin, and Identity</a></li> <li><a href="http://odetocode.com/blogs/scott/archive/2015/01/15/using-json-web-tokens-with-katana-and-webapi.aspx">Using JSON Web tokens</a></li> </ul> <p>The problem is - it is not obvious for me how to do the same thing in ASP.NET Core.</p> <p><strong>My question is:</strong> how to configure ASP.NET Core Web Api application to work with token based authentication? What direction should I pursue? Have you written any articles about the newest version, or know where I could find ones?</p> <p>Thank you!</p>
33,217,340
5
2
null
2015-05-30 13:03:21.623 UTC
52
2019-02-07 18:03:45.807 UTC
2016-07-10 12:02:22.777 UTC
null
2,833,802
null
4,610,370
null
1
69
c#|authentication|asp.net-web-api|authorization|asp.net-core
56,044
<p>Working from <a href="https://stackoverflow.com/a/30697031/789529">Matt Dekrey's fabulous answer</a>, I've created a fully working example of token-based authentication, working against ASP.NET Core (1.0.1). You can find the full code <a href="https://github.com/mrsheepuk/ASPNETSelfCreatedTokenAuthExample" rel="noreferrer">in this repository on GitHub</a> (alternative branches for <a href="https://github.com/mrsheepuk/ASPNETSelfCreatedTokenAuthExample/tree/rc1" rel="noreferrer">1.0.0-rc1</a>, <a href="https://github.com/mrsheepuk/ASPNETSelfCreatedTokenAuthExample/tree/beta8" rel="noreferrer">beta8</a>, <a href="https://github.com/mrsheepuk/ASPNETSelfCreatedTokenAuthExample/tree/beta7" rel="noreferrer">beta7</a>), but in brief, the important steps are:</p> <p><strong>Generate a key for your application</strong></p> <p>In my example, I generate a random key each time the app starts, you'll need to generate one and store it somewhere and provide it to your application. <a href="https://github.com/mrsheepuk/ASPNETSelfCreatedTokenAuthExample/blob/master/src/TokenAuthExampleWebApplication/RSAKeyUtils.cs" rel="noreferrer">See this file for how I'm generating a random key and how you might import it from a .json file</a>. As suggested in the comments by @kspearrin, the <a href="https://docs.asp.net/en/latest/security/data-protection/index.html" rel="noreferrer">Data Protection API</a> seems like an ideal candidate for managing the keys "correctly", but I've not worked out if that's possible yet. Please submit a pull request if you work it out! </p> <p><strong>Startup.cs - ConfigureServices</strong></p> <p>Here, we need to load a private key for our tokens to be signed with, which we will also use to verify tokens as they are presented. We're storing the key in a class-level variable <code>key</code> which we'll re-use in the Configure method below. <a href="https://github.com/mrsheepuk/ASPNETSelfCreatedTokenAuthExample/blob/master/src/TokenAuthExampleWebApplication/TokenAuthOptions.cs" rel="noreferrer">TokenAuthOptions</a> is a simple class which holds the signing identity, audience and issuer that we'll need in the TokenController to create our keys.</p> <pre><code>// Replace this with some sort of loading from config / file. RSAParameters keyParams = RSAKeyUtils.GetRandomKey(); // Create the key, and a set of token options to record signing credentials // using that key, along with the other parameters we will need in the // token controlller. key = new RsaSecurityKey(keyParams); tokenOptions = new TokenAuthOptions() { Audience = TokenAudience, Issuer = TokenIssuer, SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.Sha256Digest) }; // Save the token options into an instance so they're accessible to the // controller. services.AddSingleton&lt;TokenAuthOptions&gt;(tokenOptions); // Enable the use of an [Authorize("Bearer")] attribute on methods and // classes to protect. services.AddAuthorization(auth =&gt; { auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder() .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme‌​) .RequireAuthenticatedUser().Build()); }); </code></pre> <p>We've also set up an authorization policy to allow us to use <code>[Authorize("Bearer")]</code> on the endpoints and classes we wish to protect.</p> <p><strong>Startup.cs - Configure</strong></p> <p>Here, we need to configure the JwtBearerAuthentication:</p> <pre><code>app.UseJwtBearerAuthentication(new JwtBearerOptions { TokenValidationParameters = new TokenValidationParameters { IssuerSigningKey = key, ValidAudience = tokenOptions.Audience, ValidIssuer = tokenOptions.Issuer, // When receiving a token, check that it is still valid. ValidateLifetime = true, // This defines the maximum allowable clock skew - i.e. // provides a tolerance on the token expiry time // when validating the lifetime. As we're creating the tokens // locally and validating them on the same machines which // should have synchronised time, this can be set to zero. // Where external tokens are used, some leeway here could be // useful. ClockSkew = TimeSpan.FromMinutes(0) } }); </code></pre> <p><strong>TokenController</strong></p> <p>In the token controller, you need to have a method to generate signed keys using the key that was loaded in Startup.cs. We've registered a TokenAuthOptions instance in Startup, so we need to inject that in the constructor for TokenController:</p> <pre><code>[Route("api/[controller]")] public class TokenController : Controller { private readonly TokenAuthOptions tokenOptions; public TokenController(TokenAuthOptions tokenOptions) { this.tokenOptions = tokenOptions; } ... </code></pre> <p>Then you'll need to generate the token in your handler for the login endpoint, in my example I'm taking a username and password and validating those using an if statement, but the key thing you need to do is create or load a claims-based identity and generate the token for that:</p> <pre><code>public class AuthRequest { public string username { get; set; } public string password { get; set; } } /// &lt;summary&gt; /// Request a new token for a given username/password pair. /// &lt;/summary&gt; /// &lt;param name="req"&gt;&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; [HttpPost] public dynamic Post([FromBody] AuthRequest req) { // Obviously, at this point you need to validate the username and password against whatever system you wish. if ((req.username == "TEST" &amp;&amp; req.password == "TEST") || (req.username == "TEST2" &amp;&amp; req.password == "TEST")) { DateTime? expires = DateTime.UtcNow.AddMinutes(2); var token = GetToken(req.username, expires); return new { authenticated = true, entityId = 1, token = token, tokenExpires = expires }; } return new { authenticated = false }; } private string GetToken(string user, DateTime? expires) { var handler = new JwtSecurityTokenHandler(); // Here, you should create or look up an identity for the user which is being authenticated. // For now, just creating a simple generic identity. ClaimsIdentity identity = new ClaimsIdentity(new GenericIdentity(user, "TokenAuth"), new[] { new Claim("EntityID", "1", ClaimValueTypes.Integer) }); var securityToken = handler.CreateToken(new Microsoft.IdentityModel.Tokens.SecurityTokenDescriptor() { Issuer = tokenOptions.Issuer, Audience = tokenOptions.Audience, SigningCredentials = tokenOptions.SigningCredentials, Subject = identity, Expires = expires }); return handler.WriteToken(securityToken); } </code></pre> <p>And that should be it. Just add <code>[Authorize("Bearer")]</code> to any method or class you want to protect, and you should get an error if you attempt to access it without a token present. If you want to return a 401 instead of a 500 error, you'll need to register a custom exception handler <a href="https://github.com/mrsheepuk/ASPNETSelfCreatedTokenAuthExample/blob/master/src/TokenAuthExampleWebApplication/Startup.cs#L83" rel="noreferrer">as I have in my example here</a>.</p>
18,375,034
Converting a certain range of columns from text to number format with VBA
<p>I get sent a spreadsheet weekly, and for various reasons beyond my control some columns come out as text stored as numbers rather than numbers. I need to convert them to numbers for stuff that happens with them later in the code.</p> <p>I am converting them to numbers at the moment by doing this:</p> <pre><code>Dim rng As Range For Each rng In Range("A:D").Columns rng.TextToColumns Next rng </code></pre> <p>Is there a better (i.e. more efficient) way of doing this?</p> <p>I played around with NumberFormat and it didn't seem to work.</p> <p>Thanks in advance (and apologies if I have missed a solution already here - I did a search and didn't find it).</p>
18,376,758
3
2
null
2013-08-22 08:16:14.23 UTC
0
2017-08-12 17:14:40.243 UTC
2018-07-09 19:34:03.733 UTC
null
-1
null
2,345,046
null
1
8
excel|vba
66,087
<p><strong>Excel</strong>:</p> <ul> <li>Copy an empty cell</li> <li>Select the range in which you need to change the format</li> <li>Select <code>PasteSpecial</code>, and under <code>Operation</code> select <code>Add</code></li> </ul> <hr> <p><strong>VBA</strong> </p> <p>(change <code>Sheet1</code> Accordingly, assuming that <code>A100000</code> is empty):</p> <pre><code>Sheet1.Range("A100000").Copy Sheet1.UsedRange.PasteSpecial , xlPasteSpecialOperationAdd </code></pre> <p>If you place the above into the <code>Workbook_Open</code> event, it will perform the conversion automatically every time you open the workbook.</p> <p>With this method, formulas are preserved.</p> <hr> <p>I hope that helps! </p>
23,075,748
How to compile TypeScript code in the browser?
<p>Is it possible to run the TypeScript compiler in the browser for transpiling TS to JS 100% in the browser. The use case would be implementing an online TypeScript IDE that runs 100% client side and it has a "Play" button to execute the project. So I need to transpile the project to JavaScript in order for the browser to execute the code. </p> <p>I presume it should be as <strong>simple</strong> as loading the relevant typescript JS files, creating an instance of the right class (compiler?) and calling a method or two.</p> <p>What would be the means suitable to load the Compiler in the browser? Where is the TypeScript Compiler API Reference Documentation ? Where should I start digging in ? </p> <p>This isn't asking for any specific tool, but ANY way to do this with this particular computer language, and thus is on topic.</p>
23,076,788
2
9
null
2014-04-15 06:00:48.993 UTC
13
2020-06-23 21:55:47.99 UTC
2020-01-13 15:19:07.223 UTC
null
2,750,743
null
360,014
null
1
51
browser|typescript
32,560
<p>You can use <code>typescript-script</code> : <a href="https://github.com/basarat/typescript-script" rel="noreferrer">https://github.com/basarat/typescript-script</a></p> <p>However <em>do not do this in production</em> as it is going to be slow. </p> <p>You can use webpack (or a similar module bundler) to load npm packages in the browser. </p>
5,047,906
How to detect jQuery $.get failure?
<p>I'm a jQuery beginner. I'm trying to code a very simple using $.get(). The <a href="http://api.jquery.com/jQuery.get/#" rel="nofollow noreferrer">official documentation</a> says:</p> <blockquote> <p>If a request with jQuery.get() returns an error code, it will fail silently unless the script has also called the global .ajaxError() method or.</p> <p>As of jQuery 1.5, the .error() method of the jqXHR object returned by jQuery.get() is also available for error handling.</p> </blockquote> <p>So, if all goes well, my callback function for success will be called. However, if the request fails, I would like to get the HTTP code :404, 502, etc and formulate a meaningful error message for the user.</p> <p>However, since this is an asynchronous call I can imagine that I might have several outstanding. How would .ajaxError() know which request it corresponds to? Maybe it would be better to use the .error() method of the jqXHR object returned by jQuery.get()?</p> <p>I am seeking an extremely simple code example. Perhaps the success routine calls Alert(&quot;Page found&quot;) and the failure routine checks for 404 and does an Alert(&quot;Page not found&quot;).</p> <h2>Update</h2> <p>The following page is extremely helpful: <a href="http://api.jquery.com/jQuery.get/" rel="nofollow noreferrer">http://api.jquery.com/jQuery.get/</a></p>
5,048,056
3
0
null
2011-02-19 00:14:00.953 UTC
8
2021-10-12 08:29:52.557 UTC
2021-03-27 21:38:56.157 UTC
null
472,495
null
192,910
null
1
34
jquery
52,588
<p>You're right that you can use jQuery 1.5's new jqXHR to assign error handlers to <code>$.get()</code> requests. This is how you can do it:</p> <pre><code>var request = $.get('/path/to/resource.ext'); request.success(function(result) { console.log(result); }); request.error(function(jqXHR, textStatus, errorThrown) { if (textStatus == 'timeout') console.log('The server is not responding'); if (textStatus == 'error') console.log(errorThrown); // Etc }); </code></pre> <p>You can also chain handlers directly onto the call:</p> <pre><code>$.get('/path/to/resource.ext') .success(function(result) { }) .error(function(jqXHR, textStatus, errorThrown) { }); </code></pre> <p>I prefer the former to keep the code less tangled, but both are equivalent.</p>
25,885,358
if - else if - else statement and brackets
<p>I understand the usual way to write an "if - else if" statement is as follow:</p> <pre><code>if (2==1) { print("1") } else if (2==2) { print("2") } else { print("3") } </code></pre> <p>or </p> <pre><code>if (2==1) {print("1") } else if (2==2) {print("2") } else print("3") </code></pre> <p>On the contrary, If I write in this way</p> <pre><code>if (2==1) { print("1") } else if (2==2) { print("2") } else (print("3")) </code></pre> <p>or this way:</p> <pre><code>if (2==1) print("1") else if (2==2) print("2") else print("3") </code></pre> <p>the statement does NOT work. Can you explain me why <code>}</code> must precede <code>else</code> or <code>else if</code> in the same line? Are there any other way of writing the if-else if-else statement in R, especially without brackets?</p>
25,885,505
4
4
null
2014-09-17 08:05:43.427 UTC
11
2020-02-01 09:26:00.867 UTC
2019-10-01 07:25:57.587 UTC
null
680,068
null
3,206,948
null
1
36
r|if-statement
101,963
<p>R reads these commands line by line, so it thinks you're done after executing the expression after the if statement. Remember, you can use <code>if</code> <strong>without</strong> adding <code>else</code>.</p> <p>Your third example will work in a function, because the whole function is defined before being executed, so R <em>knows</em> it wasn't done yet (after <code>if() do</code>).</p>
9,335,915
Check if a string contains numbers and letters
<p>I want to detect if a string contains both numbers and letters.</p> <p>For example:</p> <ul> <li>Given <code>PncC1KECj4pPVW</code>, it would be written to a text file because it contains both.</li> <li>Given <code>qdEQ</code>, it would not, because it only contains letters.</li> </ul> <p>Is there a method to do this? </p> <p>I was trying to use</p> <pre><code>$string = PREG_REPLACE("/[^0-9a-zA-Z]/i", '', $buffer); </code></pre> <p>But it didn't work.</p> <p>Any help would be appreciated.</p>
9,336,015
10
3
null
2012-02-17 21:49:01.623 UTC
7
2022-02-27 16:44:25.223 UTC
2015-09-11 03:36:49.117 UTC
null
1,832,942
null
872,489
null
1
39
php
132,585
<pre><code>if (preg_match('/[A-Za-z].*[0-9]|[0-9].*[A-Za-z]/', $myString)) { echo 'Secure enough'; } </code></pre> <p>Answer updated based on <a href="https://stackoverflow.com/a/9336130/315550">https://stackoverflow.com/a/9336130/315550</a>, thnx to <a href="https://stackoverflow.com/users/116286/jb">https://stackoverflow.com/users/116286/jb</a></p>
9,550,079
How to programmatically login/authenticate a user?
<p>I'd like to log the user in right after the registration process, without passing by the login form.</p> <p>Is this possible ? I've found a solution with <code>FOSUserBundle</code>, but I'm not using it on the project I'm actually working on.</p> <p>Here is my security.yml, I'm working with two firewalls. The plain text encoder is just for testing.</p> <pre><code>security: encoders: Symfony\Component\Security\Core\User\User: plaintext Ray\CentralBundle\Entity\Client: md5 role_hierarchy: ROLE_ADMIN: ROLE_USER ROLE_SUPER_ADMIN: [ROLE_USER, ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH] providers: in_memory: users: admin: { password: admin, roles: [ 'ROLE_ADMIN' ] } entity: entity: { class: Ray\CentralBundle\Entity\Client, property: email } firewalls: dev: pattern: ^/(_(profiler|wdt)|css|images|js)/ security: false user_login: pattern: ^/user/login$ anonymous: ~ admin_login: pattern: ^/admin/login$ anonymous: ~ admin: pattern: ^/admin provider: in_memory form_login: check_path: /admin/login/process login_path: /admin/login default_target_path: /admin/dashboard logout: path: /admin/logout target: / site: pattern: ^/ provider: entity anonymous: ~ form_login: check_path: /user/login/process login_path: /user/login default_target_path: /user logout: path: /user/logout target: / access_control: - { path: ^/user/login, roles: IS_AUTHENTICATED_ANONYMOUSLY } - { path: ^/admin/login, roles: IS_AUTHENTICATED_ANONYMOUSLY } - { path: ^/user, roles: ROLE_USER } - { path: ^/admin, roles: ROLE_ADMIN } - { path: ^/, roles: IS_AUTHENTICATED_ANONYMOUSLY } </code></pre>
9,550,356
7
5
null
2012-03-03 21:35:46.587 UTC
35
2022-09-12 09:39:08.59 UTC
2014-10-14 11:24:18.063 UTC
null
390,177
null
1,133,405
null
1
58
php|symfony|authentication|symfony-security
41,056
<p>Yes, you can do this via something similar to the following:</p> <pre><code>use Symfony\Component\EventDispatcher\EventDispatcher, Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken, Symfony\Component\Security\Http\Event\InteractiveLoginEvent; public function registerAction() { // ... if ($this-&gt;get("request")-&gt;getMethod() == "POST") { // ... Do any password setting here etc $em-&gt;persist($user); $em-&gt;flush(); // Here, "public" is the name of the firewall in your security.yml $token = new UsernamePasswordToken($user, $user-&gt;getPassword(), "public", $user-&gt;getRoles()); // For older versions of Symfony, use security.context here $this-&gt;get("security.token_storage")-&gt;setToken($token); // Fire the login event // Logging the user in above the way we do it doesn't do this automatically $event = new InteractiveLoginEvent($request, $token); $this-&gt;get("event_dispatcher")-&gt;dispatch("security.interactive_login", $event); // maybe redirect out here } } </code></pre> <p>The event firing at the end isn't automatically done when you set a token into the context, whereas it would be normally when using eg a login form or similar. Hence the reason for including it here. You may need to adjust the type of token used, depending on your use case - the <code>UsernamePasswordToken</code> shown above is a core token, but you can use others if required.</p> <p><strong>Edit</strong>: Adjusted the above code to explain the 'public' parameter and also add in the roles of the user into the token creation, based on Franco's comment below.</p>