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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
412,562 | Execute a terminal command from a Cocoa app | <p>How can I execute a terminal command (like <code>grep</code>) from my Objective-C Cocoa application?</p> | 412,573 | 12 | 3 | null | 2009-01-05 08:21:32.097 UTC | 180 | 2019-06-21 08:04:50.023 UTC | 2011-02-03 01:41:40.08 UTC | Gordon Wilson | 213,269 | lostInTransit | 46,297 | null | 1 | 210 | objective-c|cocoa|macos | 132,412 | <p>You can use <code><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSTask_Class/Reference/Reference.html" rel="noreferrer">NSTask</a></code>. Here's an example that would run '<code>/usr/bin/grep foo bar.txt</code>'. </p>
<pre><code>int pid = [[NSProcessInfo processInfo] processIdentifier];
NSPipe *pipe = [NSPipe pipe];
NSFileHandle *file = pipe.fileHandleForReading;
NSTask *task = [[NSTask alloc] init];
task.launchPath = @"/usr/bin/grep";
task.arguments = @[@"foo", @"bar.txt"];
task.standardOutput = pipe;
[task launch];
NSData *data = [file readDataToEndOfFile];
[file closeFile];
NSString *grepOutput = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog (@"grep returned:\n%@", grepOutput);
</code></pre>
<p><code>NSPipe</code> and <code>NSFileHandle</code> are used to redirect the standard output of the task. </p>
<p>For more detailed information on interacting with the operating system from within your Objective-C application, you can see this document on Apple's Development Center: <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/OperatingSystem/OperatingSystem.html#//apple_ref/doc/uid/10000058" rel="noreferrer">Interacting with the Operating System</a>. </p>
<p>Edit: Included fix for NSLog problem</p>
<p>If you are using NSTask to run a command-line utility via bash, then you need to include this magic line to keep NSLog working:</p>
<pre><code>//The magic line that keeps your log where it belongs
task.standardOutput = pipe;
</code></pre>
<p>An explanation is here: <a href="https://web.archive.org/web/20141121094204/https://cocoadev.com/HowToPipeCommandsWithNSTask" rel="noreferrer">https://web.archive.org/web/20141121094204/https://cocoadev.com/HowToPipeCommandsWithNSTask</a></p> |
906,499 | getting type T from IEnumerable<T> | <p>is there a way to retrieve type <code>T</code> from <code>IEnumerable<T></code> through reflection?</p>
<p>e.g.</p>
<p>i have a variable <code>IEnumerable<Child></code> info; i want to retrieve Child's type through reflection</p> | 906,513 | 13 | 1 | null | 2009-05-25 12:12:43.407 UTC | 27 | 2020-10-02 12:57:56.4 UTC | 2009-05-26 09:36:30.59 UTC | null | 105,533 | null | 105,533 | null | 1 | 120 | c#|generics|reflection | 75,694 | <pre><code>IEnumerable<T> myEnumerable;
Type type = myEnumerable.GetType().GetGenericArguments()[0];
</code></pre>
<p>Thusly,</p>
<pre><code>IEnumerable<string> strings = new List<string>();
Console.WriteLine(strings.GetType().GetGenericArguments()[0]);
</code></pre>
<p>prints <code>System.String</code>.</p>
<p>See <a href="http://msdn.microsoft.com/en-us/library/system.type.getgenericarguments.aspx" rel="noreferrer">MSDN</a> for <code>Type.GetGenericArguments</code>.</p>
<p><strong>Edit:</strong> I believe this will address the concerns in the comments:</p>
<pre><code>// returns an enumeration of T where o : IEnumerable<T>
public IEnumerable<Type> GetGenericIEnumerables(object o) {
return o.GetType()
.GetInterfaces()
.Where(t => t.IsGenericType
&& t.GetGenericTypeDefinition() == typeof(IEnumerable<>))
.Select(t => t.GetGenericArguments()[0]);
}
</code></pre>
<p>Some objects implement more than one generic <code>IEnumerable</code> so it is necessary to return an enumeration of them.</p>
<p><strong>Edit:</strong> Although, I have to say, it's a terrible idea for a class to implement <code>IEnumerable<T></code> for more than one <code>T</code>.</p> |
917,392 | How should I Fix "svn: Inconsistent line ending style"? | <p>When I run "svn propedit svn:ignore ." at the root of my svn repository, I get this error:
svn: Inconsistent line ending style</p>
<p>I have tried to run this script: <a href="http://blog.eflow.org/archives/130" rel="noreferrer">http://blog.eflow.org/archives/130</a> which runs dos2unix and sets the eol-style on all of the files, however this problem still persists. Any idea what could be wrong?</p> | 920,709 | 21 | 0 | null | 2009-05-27 18:51:14.34 UTC | 13 | 2022-07-06 08:57:29.343 UTC | null | null | null | null | 66,355 | null | 1 | 40 | svn|line-endings | 82,757 | <p>Subversion is not complaining about the content of any file, but about the content of the svn:ignore property. One way to fix this is to simply delete the <code>svn:ignore</code> property with <code>svn propdel</code> and then recreate it. </p>
<p>Another way which may be easier if you have a lot of lines in your <code>svn:ignore</code>:</p>
<ol>
<li><p>fetch the value of svn:ignore in a
temporary file like this:</p>
<p><code>svn
propget svn:ignore . > temp</code></p></li>
<li>fix the line endings in the <code>temp</code>
file</li>
<li><p>set the value of svn:ignore from the fixed file like
this:</p>
<p><code>svn propset svn:ignore -F
temp .</code></p></li>
</ol> |
1,102,986 | Most powerful examples of Unix commands or scripts every programmer should know | <p>There are many things that all programmers should know, but I am particularly interested in the Unix/Linux commands that we should all know. For accomplishing tasks that we may come up against at some point such as <strong>refactoring</strong>, <strong>reporting</strong>, <strong>network updates</strong> etc.</p>
<p>The reason I am curious is because having previously worked as a software tester at a software company while I am studying my degree, I noticed that all of developers (who were developing Windows software) had 2 computers.</p>
<p>To their left was their Windows XP development machine, and to the right was a Linux box. I think it was Ubuntu. Anyway they told me that they used it because it provided powerful unix operations that Windows couldn't do in their development process.</p>
<p>This makes me curious to know, as a software engineer what do you believe are some of the most powerful scripts/commands/uses that you can perform on a Unix/Linux operating system that every programmer should know for solving real world tasks that may not necessarily relate to writing code?</p>
<p>We all know what <strong>sed</strong>, <strong>awk</strong> and <strong>grep</strong> do. I am interested in some actual Unix/Linux scripting pieces that have solved a difficult problem for you, so that other programmers may benefit. Please provide your story and source.</p>
<p>I am sure there are numerous examples like this that people keep in their '<strong>Scripts</strong>' folder.</p>
<p><strong>Update:</strong> People seem to be misinterpreting the question. I am not asking for the names of individual unix commands, rather UNIX code <strong>snippets</strong> that have solved a problem for you.</p>
<h2>Best answers from the Community</h2>
<hr>
<p><strong>Traverse a directory tree and print out paths to any files that match a regular expression:</strong></p>
<pre><code>find . -exec grep -l -e 'myregex' {} \; >> outfile.txt
</code></pre>
<p><strong>Invoke the default editor(Nano/ViM)</strong> </p>
<blockquote>
<p>(works on most Unix systems including Mac OS X)
Default editor is whatever your
"<strong>EDITOR</strong>" environment variable is
set to. ie: <strong>export
EDITOR=/usr/bin/pico</strong> which is
located at <strong>~/.profile</strong> under Mac OS
X.</p>
</blockquote>
<pre><code>Ctrl+x Ctrl+e
</code></pre>
<p><strong>List all running network connections (including which app they belong to)</strong></p>
<pre><code>lsof -i -nP
</code></pre>
<p><strong>Clear the Terminal's search history</strong> (Another of my favourites)</p>
<pre><code>history -c
</code></pre> | 1,124,572 | 25 | 4 | 2009-07-09 10:46:53.067 UTC | 2009-07-09 10:07:37.373 UTC | 47 | 2015-06-19 06:04:45.12 UTC | 2009-07-16 05:20:28.317 UTC | null | 40,002 | null | 40,002 | null | 1 | 27 | unix|command-line|scripting | 31,489 | <h2>Best answers from the Community</h2>
<hr>
<p><strong>Traverse a directory tree and print out paths to any files that match a regular expression:</strong></p>
<pre><code>find . -exec grep -l -e 'myregex' {} \; >> outfile.txt
</code></pre>
<p><strong>Invoke the default editor(Nano/ViM)</strong> </p>
<blockquote>
<p>(works on most Unix systems including Mac OS X)
Default editor is whatever your
"<strong>EDITOR</strong>" environment variable is
set to. ie: <strong>export
EDITOR=/usr/bin/pico</strong> which is
located at <strong>~/.profile</strong> under Mac OS
X.</p>
</blockquote>
<pre><code>Ctrl+x Ctrl+e
</code></pre>
<p><strong>List all running network connections (including which app they belong to)</strong></p>
<pre><code>lsof -i -nP
</code></pre>
<p><strong>Clear the Terminal's search history</strong> (Another of my favourites)</p>
<pre><code>history -c
</code></pre> |
34,728,962 | React renderToString() Performance and Caching React Components | <p>I've noticed that the <code>reactDOM.renderToString()</code> method starts to slow down significantly when rendering a large component tree on the server.</p>
<h2>Background</h2>
<p>A bit of background. The system is a fully isomorphic stack. The highest level <code>App</code> component renders templates, pages, dom elements, and more components. Looking in the react code, I found it renders ~1500 components (this is inclusive of any simple dom tag that gets treated as a simple component, <code><p>this is a react component</p></code>.</p>
<p>In development, rendering ~1500 components takes ~200-300ms. By removing some components I was able to get ~1200 components to render in ~175-225ms.</p>
<p>In production, renderToString on ~1500 components takes around ~50-200ms.</p>
<p>The time does appear to be linear. No one component is slow, rather it is the sum of many.</p>
<h2>Problem</h2>
<p>This creates some problems on the server. The lengthy method results in long server response times. The TTFB is a lot higher than it should be. With api calls and business logic the response should be 250ms, but with a 250ms renderToString it is doubled! Bad for SEO and users. Also, being a synchronous method, <code>renderToString()</code> can block the node server and backup subsequent requests (this could be solved by using 2 separate node servers: 1 as a web server, and 1 as a service to solely render react).</p>
<h2>Attempts</h2>
<p>Ideally, it would take 5-50ms to renderToString in production. I've been working on some ideas, but I'm not exactly sure what the best approach would be.</p>
<h3>Idea 1: Caching components</h3>
<p>Any component that is marked as 'static' could be cached. By keeping a cache with the rendered markup, the <code>renderToString()</code> could check the cache before rendering. If it finds a component, it automatically grabs the string. Doing this at a high level component would save all the nested children component's mounting. You would have to replace the cached component markup's react rootID with the current rootID.</p>
<h3>Idea 2: Marking components as simple/dumb</h3>
<p>By defining a component as 'simple', react should be able to skip all the lifecycle methods when rendering. React already does this for the core react dom components (<code><p/></code>, <code><h1/></code>, etc). Would be nice to extend custom components to use the same optimization.</p>
<h3>Idea 3: Skip components on server-side render</h3>
<p>Components that do not need to be returned by the server (no SEO value) could simply be skipped on the server. Once the client loads, set a <code>clientLoaded</code> flag to <code>true</code> and pass it down to enforce a re-render.</p>
<h3>Closing and other attempts</h3>
<p>The only solution I've implemented thus far is to reduce the number of components that are rendered on the server.</p>
<p>Some projects we're looking at include:</p>
<ul>
<li><a href="https://github.com/aickin/react-dom-stream" rel="noreferrer">React-dom-stream</a> (still working on implementing this for a test)</li>
<li><a href="https://babeljs.io/docs/plugins/transform-react-inline-elements/" rel="noreferrer">Babel inline elements</a> (seems like this is along the lines of Idea 2)</li>
</ul>
<p>Has anybody faced similar issues? What have you been able to do?
Thanks.</p> | 34,907,209 | 4 | 9 | null | 2016-01-11 18:55:57.94 UTC | 16 | 2020-10-11 18:29:51.577 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 4,086,590 | null | 1 | 62 | performance|reactjs|isomorphic-javascript|render-to-string|react-dom | 24,871 | <p>Using react-router1.0 and react0.14, we were mistakenly serializing our flux object multiple times.</p>
<p><code>RoutingContext</code> will call <code>createElement</code> for every template in your react-router routes. This allows you to inject whatever props you want. We also use flux. We send down a serialized version of a large object. In our case, we were doing <code>flux.serialize()</code> within createElement. The serialization method could take ~20ms. With 4 templates, that would be an extra 80ms to your <code>renderToString()</code> method!</p>
<p>Old code: </p>
<pre><code>function createElement(Component, props) {
props = _.extend(props, {
flux: flux,
path: path,
serializedFlux: flux.serialize();
});
return <Component {...props} />;
}
var start = Date.now();
markup = renderToString(<RoutingContext {...renderProps} createElement={createElement} />);
console.log(Date.now() - start);
</code></pre>
<p>Easily optimized to this:</p>
<pre><code>var serializedFlux = flux.serialize(); // serialize one time only!
function createElement(Component, props) {
props = _.extend(props, {
flux: flux,
path: path,
serializedFlux: serializedFlux
});
return <Component {...props} />;
}
var start = Date.now();
markup = renderToString(<RoutingContext {...renderProps} createElement={createElement} />);
console.log(Date.now() - start);
</code></pre>
<p>In my case this helped reduce the <code>renderToString()</code> time from ~120ms to ~30ms. (You still need to add the 1x <code>serialize()</code>'s ~20ms to the total, which happens before the <code>renderToString()</code>) It was a nice quick improvement. -- It's important to remember to always do things correctly, even if you don't know the immediate impact!</p> |
6,613,110 | What is the best way to deal with the NSDateFormatter locale "feechur"? | <p>It seems that <code>NSDateFormatter</code> has a "feature" that bites you unexpectedly: If you do a simple "fixed" format operation such as:</p>
<pre><code>NSDateFormatter* fmt = [[NSDateFormatter alloc] init];
[fmt setDateFormat:@"yyyyMMddHHmmss"];
NSString* dateStr = [fmt stringFromDate:someDate];
[fmt release];
</code></pre>
<p>Then it works fine in the US and most locales UNTIL ... someone with their phone set to a 24-hour region sets the 12/24 hour switch in settings to 12. Then the above starts tacking "AM" or "PM" onto the end of the resulting string.</p>
<p>(See, eg, <a href="https://stackoverflow.com/questions/143075/nsdateformatter-am-i-doing-something-wrong-or-is-this-a-bug">NSDateFormatter, am I doing something wrong or is this a bug?</a>)</p>
<p>(And see <a href="https://developer.apple.com/library/content/qa/qa1480/_index.html" rel="noreferrer">https://developer.apple.com/library/content/qa/qa1480/_index.html</a>)</p>
<p>Apparently Apple has declared this to be "BAD" -- Broken As Designed, and they aren't going to fix it.</p>
<p>The circumvention is apparently to set the locale of the date formatter for a specific region, generally the US, but this is a bit messy:</p>
<pre><code>NSLocale *loc = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
[df setLocale: loc];
[loc release];
</code></pre>
<p>Not too bad in onsies-twosies, but I'm dealing with about ten different apps, and the first one I look at has 43 instances of this scenario.</p>
<p>So any clever ideas for a macro/overridden class/whatever to minimize the effort to change everything, without making the code to obscure? (My first instinct is to override NSDateFormatter with a version that would set the locale in the init method. Requires changing two lines -- the alloc/init line and the added import.)</p>
<h2>Added</h2>
<p>This is what I've come up with so far -- seems to work in all scenarios:</p>
<pre><code>@implementation BNSDateFormatter
-(id)init {
static NSLocale* en_US_POSIX = nil;
NSDateFormatter* me = [super init];
if (en_US_POSIX == nil) {
en_US_POSIX = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
}
[me setLocale:en_US_POSIX];
return me;
}
@end
</code></pre>
<h2>Bounty!</h2>
<p>I'll award the bounty to the best (legitimate) suggestion/critique I see by mid-day Tuesday. [See below -- deadline extended.]</p>
<h2>Update</h2>
<p>Re OMZ's proposal, here is what I'm finding --</p>
<p>Here is the category version -- h file:</p>
<pre><code>#import <Foundation/Foundation.h>
@interface NSDateFormatter (Locale)
- (id)initWithSafeLocale;
@end
</code></pre>
<p>Category m file:</p>
<pre><code>#import "NSDateFormatter+Locale.h"
@implementation NSDateFormatter (Locale)
- (id)initWithSafeLocale {
static NSLocale* en_US_POSIX = nil;
self = [super init];
if (en_US_POSIX == nil) {
en_US_POSIX = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
}
NSLog(@"Category's locale: %@ %@", en_US_POSIX.description, [en_US_POSIX localeIdentifier]);
[self setLocale:en_US_POSIX];
return self;
}
@end
</code></pre>
<p>The code:</p>
<pre><code>NSDateFormatter* fmt;
NSString* dateString;
NSDate* date1;
NSDate* date2;
NSDate* date3;
NSDate* date4;
fmt = [[NSDateFormatter alloc] initWithSafeLocale];
[fmt setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
dateString = [fmt stringFromDate:[NSDate date]];
NSLog(@"dateString = %@", dateString);
date1 = [fmt dateFromString:@"2001-05-05 12:34:56"];
NSLog(@"date1 = %@", date1.description);
date2 = [fmt dateFromString:@"2001-05-05 22:34:56"];
NSLog(@"date2 = %@", date2.description);
date3 = [fmt dateFromString:@"2001-05-05 12:34:56PM"];
NSLog(@"date3 = %@", date3.description);
date4 = [fmt dateFromString:@"2001-05-05 12:34:56 PM"];
NSLog(@"date4 = %@", date4.description);
[fmt release];
fmt = [[BNSDateFormatter alloc] init];
[fmt setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
dateString = [fmt stringFromDate:[NSDate date]];
NSLog(@"dateString = %@", dateString);
date1 = [fmt dateFromString:@"2001-05-05 12:34:56"];
NSLog(@"date1 = %@", date1.description);
date2 = [fmt dateFromString:@"2001-05-05 22:34:56"];
NSLog(@"date2 = %@", date2.description);
date3 = [fmt dateFromString:@"2001-05-05 12:34:56PM"];
NSLog(@"date3 = %@", date3.description);
date4 = [fmt dateFromString:@"2001-05-05 12:34:56 PM"];
NSLog(@"date4 = %@", date4.description);
[fmt release];
</code></pre>
<p>The result:</p>
<pre><code>2011-07-11 17:44:43.243 DemoApp[160:307] Category's locale: <__NSCFLocale: 0x11a820> en_US_POSIX
2011-07-11 17:44:43.257 DemoApp[160:307] dateString = 2011-07-11 05:44:43 PM
2011-07-11 17:44:43.264 DemoApp[160:307] date1 = (null)
2011-07-11 17:44:43.272 DemoApp[160:307] date2 = (null)
2011-07-11 17:44:43.280 DemoApp[160:307] date3 = (null)
2011-07-11 17:44:43.298 DemoApp[160:307] date4 = 2001-05-05 05:34:56 PM +0000
2011-07-11 17:44:43.311 DemoApp[160:307] Extended class's locale: <__NSCFLocale: 0x11a820> en_US_POSIX
2011-07-11 17:44:43.336 DemoApp[160:307] dateString = 2011-07-11 17:44:43
2011-07-11 17:44:43.352 DemoApp[160:307] date1 = 2001-05-05 05:34:56 PM +0000
2011-07-11 17:44:43.369 DemoApp[160:307] date2 = 2001-05-06 03:34:56 AM +0000
2011-07-11 17:44:43.380 DemoApp[160:307] date3 = (null)
2011-07-11 17:44:43.392 DemoApp[160:307] date4 = (null)
</code></pre>
<p>The phone [make that an iPod Touch] is set to Great Britain, with the 12/24 switch set to 12. There's a clear difference in the two results, and I judge the category version to be wrong. Note that the log in the category version IS getting executed (and stops placed in the code are hit), so it's not simply a case of the code somehow not getting used.</p>
<h2>Bounty update:</h2>
<p>Since I haven't gotten any applicable replies yet I'll extend the bounty deadline for another day or two.</p>
<p>Bounty ends in 21 hours -- it'll go to whoever makes the most effort to help, even if the answer isn't really useful in my case.</p>
<h2>A curious observation</h2>
<p>Modified the category implementation slightly:</p>
<pre><code>#import "NSDateFormatter+Locale.h"
@implementation NSDateFormatter (Locale)
- (id)initWithSafeLocale {
static NSLocale* en_US_POSIX2 = nil;
self = [super init];
if (en_US_POSIX2 == nil) {
en_US_POSIX2 = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
}
NSLog(@"Category's locale: %@ %@", en_US_POSIX2.description, [en_US_POSIX2 localeIdentifier]);
[self setLocale:en_US_POSIX2];
NSLog(@"Category's object: %@ and object's locale: %@ %@", self.description, self.locale.description, [self.locale localeIdentifier]);
return self;
}
@end
</code></pre>
<p>Basically just changed the name of the static locale variable (in case there was some conflict with the static declared in the subclass) and added the extra NSLog. But look what that NSLog prints:</p>
<pre><code>2011-07-15 16:35:24.322 DemoApp[214:307] Category's locale: <__NSCFLocale: 0x160550> en_US_POSIX
2011-07-15 16:35:24.338 DemoApp[214:307] Category's object: <NSDateFormatter: 0x160d90> and object's locale: <__NSCFLocale: 0x12be70> en_GB
2011-07-15 16:35:24.345 DemoApp[214:307] dateString = 2011-07-15 04:35:24 PM
2011-07-15 16:35:24.370 DemoApp[214:307] date1 = (null)
2011-07-15 16:35:24.378 DemoApp[214:307] date2 = (null)
2011-07-15 16:35:24.390 DemoApp[214:307] date3 = (null)
2011-07-15 16:35:24.404 DemoApp[214:307] date4 = 2001-05-05 05:34:56 PM +0000
</code></pre>
<p>As you can see, the setLocale simply didn't. The locale of the formatter is still en_GB. It appears that there is something "strange" about an init method in a category.</p>
<h2>Final answer</h2>
<p>See the <a href="https://stackoverflow.com/a/6735644/581994">accepted answer</a> below.</p> | 6,735,644 | 4 | 9 | null | 2011-07-07 15:30:14.707 UTC | 56 | 2018-06-22 12:29:37.273 UTC | 2017-06-28 14:49:22.833 UTC | null | 1,033,581 | null | 581,994 | null | 1 | 173 | ios|objective-c|iphone|locale|nsdateformatter | 47,040 | <h2>Duh!!</h2>
<p>Sometimes you have an "Aha!!" moment, sometimes it's more of a "Duh!!" This is the latter. In the category for <code>initWithSafeLocale</code> the "super" <code>init</code> was coded as <code>self = [super init];</code>. This inits the SUPERCLASS of <code>NSDateFormatter</code> but does not <code>init</code> the <code>NSDateFormatter</code> object itself.</p>
<p>Apparently when this initialization is skipped, <code>setLocale</code> "bounces off", presumably because of some missing data structure in the object. Changing the <code>init</code> to <code>self = [self init];</code> causes the <code>NSDateFormatter</code> initialization to occur, and <code>setLocale</code> is happy again.</p>
<p>Here is the "final" source for the category's .m:</p>
<pre><code>#import "NSDateFormatter+Locale.h"
@implementation NSDateFormatter (Locale)
- (id)initWithSafeLocale {
static NSLocale* en_US_POSIX = nil;
self = [self init];
if (en_US_POSIX == nil) {
en_US_POSIX = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
}
[self setLocale:en_US_POSIX];
return self;
}
@end
</code></pre> |
6,425,062 | Passing functions to setTimeout in a loop: always the last value? | <p>I'm trying to use setTimeout to execute an anonymous function that I pass information into and I'm having trouble. This (hard-coded version) would work just fine:</p>
<pre><code>setTimeout(function(){alert("hello");},1000);
setTimeout(function(){alert("world");},2000);
</code></pre>
<p>But I'm trying to take the hello and world from an array and pass them into the function without (a) using global variables, and (2) using eval. I know how I could do it using globals or eval, but how can I do it without. Here is what I'd like to do (but I know it won't work):</p>
<pre><code>var strings = [ "hello", "world" ];
var delay = 1000;
for(var i=0;i<strings.length;i++) {
setTimeout( function(){alert(strings[i]);}, delay);
delay += 1000;
}
</code></pre>
<p>Of course strings[i] will be out of context. How can I pass strings[i] into that anonymous function without eval or globals?</p> | 6,425,113 | 5 | 3 | null | 2011-06-21 12:15:16.28 UTC | 12 | 2013-07-16 22:05:59.037 UTC | 2011-12-11 07:57:04.417 UTC | user166390 | null | null | 730,160 | null | 1 | 17 | javascript|settimeout | 14,317 | <p>This is the very frequently repeated "how do I use a loop variable in a closure" problem.</p>
<p>The canonical solution is to call a function which returns a function that's bound to the current value of the loop variable:</p>
<pre><code>var strings = [ "hello", "world" ];
var delay = 1000;
for(var i=0;i<strings.length;i++) {
setTimeout(
(function(s) {
return function() {
alert(s);
}
})(strings[i]), delay);
delay += 1000;
}
</code></pre>
<p>The outer definition <code>function(s) { ... }</code> creates a new scope where <code>s</code> is bound to the current value of the supplied parameter - i.e. <code>strings[i]</code> - where it's available to the <em>inner</em> scope.</p> |
6,356,231 | android how to convert json array to string array | <p>I have an app where I fetch data from server(json) in the form of array & by using the index i used in my app, like below.</p>
<pre><code>JSONObject topobj = new JSONObject(page);
JSONObject innerobj = topobj.getJSONObject("restarutant");
JSONArray phone = innerobj.getJSONArray("phone");
textViewPhone.setText("Phone: " + phone.get(0).toString() + " ,"
+ phone.get(1).toString());
</code></pre>
<p>for small size array I can get like this. But when array contains 'n' no of elements and dynamically i have to use this, at that time it required to convert into String Array.
Can anybody tell me how I convert the json array to String array ?
Thank you</p> | 6,356,282 | 6 | 3 | null | 2011-06-15 10:20:13.513 UTC | 4 | 2021-11-12 18:00:31.367 UTC | 2011-06-15 10:34:31.123 UTC | null | 514,945 | null | 1,147,007 | null | 1 | 9 | android|json | 48,834 | <p><a href="https://stackoverflow.com/questions/5983932/converting-from-jsonarray-to-string-then-back-again">This</a> should help you.</p>
<p>Edit:</p>
<p>Maybe this is what you need:</p>
<pre><code>ArrayList<String> stringArray = new ArrayList<String>();
JSONArray jsonArray = new JSONArray();
for(int i = 0, count = jsonArray.length(); i< count; i++)
{
try {
JSONObject jsonObject = jsonArray.getJSONObject(i);
stringArray.add(jsonObject.toString());
}
catch (JSONException e) {
e.printStackTrace();
}
}
</code></pre> |
6,876,666 | Convert float to string in php? | <p>Like:</p>
<pre><code>float(1.2345678901235E+19) => string(20) "12345678901234567890"
</code></pre>
<p>Can it be done?</p>
<p>(it's for json_decode...)</p> | 6,876,715 | 6 | 0 | null | 2011-07-29 17:16:48.327 UTC | 3 | 2022-09-01 07:22:17.773 UTC | 2022-09-01 07:22:17.773 UTC | null | 107,625 | null | 869,800 | null | 1 | 27 | php|string|floating-point|type-conversion | 70,954 | <pre><code>echo number_format($float,0,'.','');
</code></pre>
<p>note: this is for integers, increase 0 for extra fractional digits</p> |
6,405,127 | How do I specify a password to 'psql' non-interactively? | <p>I am trying to automate database creation process with a shell script and one thing I've hit a road block with passing a password to <a href="https://en.wikipedia.org/wiki/PostgreSQL#Database_administration" rel="noreferrer">psql</a>.
Here is a bit of code from the shell script:</p>
<pre><code>psql -U $DB_USER -h localhost -c"$DB_RECREATE_SQL"
</code></pre>
<p>How do I pass a password to <code>psql</code> in a non-interactive way?</p> | 6,405,162 | 11 | 2 | null | 2011-06-19 21:06:06.343 UTC | 85 | 2022-09-08 18:37:58.853 UTC | 2021-09-15 20:11:12.87 UTC | null | 330,315 | null | 90,268 | null | 1 | 570 | postgresql|bash|command-line|psql | 517,269 | <p>From the <a href="http://www.postgresql.org/docs/8.3/static/app-psql.html" rel="noreferrer">official documentation</a>:</p>
<blockquote>
<p>It is also convenient to have a ~/.pgpass file to avoid regularly having to type in passwords. See <a href="http://www.postgresql.org/docs/8.3/static/libpq-pgpass.html" rel="noreferrer">Section 30.13</a> for more information.</p>
</blockquote>
<p>...</p>
<blockquote>
<p>This file should contain lines of the following format:</p>
</blockquote>
<pre><code>hostname:port:database:username:password
</code></pre>
<blockquote>
<p>The password field from the first line that matches the current connection parameters will be used. </p>
</blockquote> |
15,685,975 | Google Forms onsubmit | <p>How does one reference the default 'Submit' Forms button to link the <em>'onsubmit'</em> trigger with another action? Thank you.</p>
<p>For example, with onsubmit, </p>
<pre><code>Logger.log('do something');
</code></pre> | 15,689,011 | 6 | 1 | null | 2013-03-28 15:34:20.09 UTC | 8 | 2020-10-27 08:04:43.83 UTC | 2016-06-08 14:16:15.607 UTC | null | 1,677,912 | null | 2,012,403 | null | 1 | 18 | google-apps-script|google-forms | 56,451 | <p>One doesn't. The Form Service does not allow any programmatic control over the product. There is an <a href="http://code.google.com/p/google-apps-script-issues/issues/detail?id=2383" rel="noreferrer">open issue</a> on the Issue Tracker for this general topic. Star it to "vote", and receive updates.</p>
<p>However, you're not lost. In the spreadsheet receiving your form responses, you can add a script with an Installable Trigger to fire "On form submit". From there, you can do many things to the submitted data, including Logging as you wish... but nothing to the Form itself.</p>
<p><img src="https://i.stack.imgur.com/QlYK4.png" alt="Triggers"></p>
<p>These references explain triggers and events.</p>
<ul>
<li><a href="https://developers.google.com/apps-script/understanding_triggers" rel="noreferrer">Using Container-Specific Installable Triggers</a></li>
<li><a href="https://developers.google.com/apps-script/understanding_events" rel="noreferrer">Understanding Events</a></li>
</ul> |
16,015,022 | WebRTC: How to add stream after offer and answer? | <p>I am working on webRTC video calling. I got datachannel successfully implemented. Now I would like to add video stream to the same peer connection. </p>
<p>I have read that stream should be added before answer and offer. Is there a way to add stream after answer or offer?</p>
<p>In case I have added stream before offer or answer, how could I stop streaming and start it again when needed?</p>
<p>Could there be any issues in maintaining so many streams?</p> | 16,460,621 | 3 | 0 | null | 2013-04-15 12:20:57.947 UTC | 9 | 2017-07-28 06:53:03.337 UTC | 2017-07-28 06:53:03.337 UTC | null | 5,894,241 | null | 1,307,915 | null | 1 | 28 | javascript|webrtc | 12,880 | <p>To add stream after creating complete signalling, the Peer connection should <strong>renegotiate</strong> with stream.</p>
<pre><code>pc1.addstream(stream)
</code></pre>
<p>Then once again create offer and send it to other Peer.</p>
<p>Remote peer will add stream and send answer SDP.</p>
<p>To stop streams:</p>
<pre><code>stream.stop();
pc1.removeStream(stream);
</code></pre> |
15,521,954 | Deleting using LEFT JOIN | <p>I want to delete from a table depending on data that exists on another table that references the first, however, I have the code that works and shows the value to be deleted when I run it as a SELECT stetement, however when I change that to DELETE it gives me errors, that I don't understand why they're there.</p>
<pre><code>DELETE leadCustomer.* FROM coursework.leadCustomer LEFT JOIN coursework.flightBooking
ON leadCustomer.customerID = flightBooking.customerID
WHERE leadCustomer.customerID NOT IN (
SELECT customerID FROM (SELECT customerID, status FROM coursework.flightBooking) AS
StatusCount where status IN ('R','H') GROUP BY customerID
)
AND leadCustomer.customerID = 8;
</code></pre>
<p>Error: </p>
<pre><code>ERROR: syntax error at or near "leadCustomer"
LINE 1: DELETE leadCustomer.* FROM coursework.leadCustomer LEFT JOIN...
^
********** Error **********
ERROR: syntax error at or near "leadCustomer"
SQL state: 42601
Character: 8
</code></pre>
<p>I am using postgres</p> | 15,522,132 | 5 | 3 | null | 2013-03-20 11:14:24.8 UTC | 3 | 2015-07-03 21:42:30.387 UTC | 2015-07-03 21:42:30.387 UTC | null | 4,370,109 | null | 495,123 | null | 1 | 36 | sql|postgresql|join|left-join | 93,236 | <p>From where I see it, you don't actually need a join to perform this...</p>
<pre><code>DELETE FROM coursework.leadCustomer
WHERE leadCustomer.customerID NOT IN (
SELECT distinct customerID FROM coursework.flightBooking where status IN ('R','H')
)
AND leadCustomer.customerID = 8;
</code></pre>
<p>it will delete all records in leadcustomer with a customerID that is :
1) different from 8
2) Not in table flightbooking with status 'R' or 'H'</p>
<p>Isn't that what you're trying to do ?</p> |
15,773,662 | Symfony2 Doctrine Expr 'IS NOT NULL' | <p>I'm using the <strong>FormType</strong> for an <strong>Entity</strong> of mine, and setting up an <a href="http://symfony.com/doc/2.1/reference/forms/types/entity.html" rel="nofollow noreferrer">entity field</a>.
I need two <code>Where</code> clauses in an <code>And</code>, and from what I've read on <a href="http://docs.doctrine-project.org/en/2.0.x/reference/query-builder.html" rel="nofollow noreferrer">the Query Builder page</a>, this is at least how I should go about it:</p>
<pre><code>'query_builder' => function ($er){
$qb = $er->createQueryBuilder('p');
$qb
->where($qb->expr()->andx(
$qb->expr()->in('p', '?1'),
$qb->expr()->not(
$qb->expr()->eq('p.location', 'NULL')
)
))
->setParameter(1, $this->totalScope)
;
return $qb;
},
</code></pre>
<p>However, the <code>not(eq('col', 'NULL'))</code> doesn't achieve the desired result, and in fact, errors with:</p>
<blockquote>
<p>Error: Expected Literal, got 'NULL'</p>
</blockquote> | 15,781,504 | 3 | 0 | null | 2013-04-02 20:23:51.97 UTC | 3 | 2019-11-25 12:24:09.883 UTC | 2019-07-16 20:56:35.533 UTC | null | 6,349,751 | null | 212,307 | null | 1 | 38 | symfony|doctrine-orm | 66,805 | <p>You can use <a href="https://github.com/doctrine/doctrine2/blob/2.3.2/lib/Doctrine/ORM/Query/Expr.php#L459-L468"><code>isNotNull</code></a>:</p>
<pre class="lang-php prettyprint-override"><code>'query_builder' => function ($er){
$qb = $er->createQueryBuilder('p');
$qb
->where($qb->expr()->andx(
$qb->expr()->in('p', '?1'),
$qb->expr()->isNotNull('p.location')
))
->setParameter(1, $this->totalScope);
return $qb;
},
</code></pre> |
50,332,119 | Is it possible to make an in-app button that triggers the PWA "Add to Home Screen" install banner? | <p>I understand that with a properly made Progressive Web App mobile browsers will display a banner prompting users to 'Install' the app on their home screen.</p>
<p>I have been looking around for a way to trigger that prompt from within the app, but have not been able to find anything.</p>
<p>Is there a line of JavaScript that can be used to call the install prompt banner at any time?? Something that I could add to a install button tucked away in a help screen for instance?</p>
<p>It might be difficult for some users to find the "Add to Home Screen" option if they missed the install banner prompt. I'd like to give them a button they can click to be prompted again.</p>
<h3><strong>2020 EDIT</strong>: Yes, this is possible in Chrome - see <a href="https://stackoverflow.com/a/64727286/8620945">answer below</a></h3>
<p>See this great article: <a href="https://web.dev/customize-install/" rel="noreferrer">How to provide your own in-app install experience</a> and <a href="https://pwa-install-demo.netlify.app/" rel="noreferrer">my working demo</a> of the article's process <a href="https://github.com/adueck/pwa-install-demo" rel="noreferrer">applied in a React app</a>.</p>
<p>Or for a slightly different approach, see <a href="https://github.com/RobinLinus/snapdrop" rel="noreferrer">how snapdrop.net did it</a>.</p> | 64,727,286 | 7 | 6 | null | 2018-05-14 13:56:06.023 UTC | 14 | 2021-01-20 13:30:44.677 UTC | 2020-11-07 11:44:30.013 UTC | null | 8,620,945 | null | 8,620,945 | null | 1 | 50 | javascript|service-worker|progressive-web-apps | 48,052 | <p>Thanks for all the great answers. Recently it appears that things have become more standardized, and there is a solid way of doing things <em>in chrome at least</em> that allows users to click and install the app even if they missed the prompt etc.</p>
<p><a href="https://petelepage.com/" rel="noreferrer">Pete LePage</a> wrote a very clear article on web.dev called <a href="https://web.dev/customize-install/" rel="noreferrer">How to provide your own in-app install experience</a> which details the process. The code snippets and process is taken directly from the article.</p>
<ol>
<li>Listen for the <code>beforeinstallprompt</code> event.</li>
</ol>
<pre class="lang-js prettyprint-override"><code>let deferredPrompt;
window.addEventListener('beforeinstallprompt', (e) => {
// Prevent the mini-infobar from appearing on mobile
e.preventDefault();
// Stash the event so it can be triggered later.
deferredPrompt = e;
// Update UI notify the user they can install the PWA
showInstallPromotion();
});
</code></pre>
<ol start="2">
<li>Save the beforeinstallprompt event, so it can be used to trigger the install flow later.</li>
</ol>
<pre class="lang-js prettyprint-override"><code>buttonInstall.addEventListener('click', (e) => {
// Hide the app provided install promotion
hideMyInstallPromotion();
// Show the install prompt
deferredPrompt.prompt();
// Wait for the user to respond to the prompt
deferredPrompt.userChoice.then((choiceResult) => {
if (choiceResult.outcome === 'accepted') {
console.log('User accepted the install prompt');
} else {
console.log('User dismissed the install prompt');
}
});
});
</code></pre>
<ol start="3">
<li>Alert the user that your PWA is installable, and provide a button or other element to start the in-app installation flow.</li>
</ol>
<p>For more details and other capabilities, see <a href="https://web.dev/customize-install/" rel="noreferrer">the full article</a>.</p>
<p>I made a <a href="https://pwa-install-demo.netlify.app/" rel="noreferrer">working demo of a this process implemented in React</a>. (<a href="https://github.com/adueck/pwa-install-demo" rel="noreferrer">source code</a>)</p>
<p>Also, for a slightly different approach, you can see how the maker(s) of <a href="https://snapdrop.net/" rel="noreferrer">Snapdrop</a> implemented an install button in the <a href="https://github.com/RobinLinus/snapdrop" rel="noreferrer">source code</a>.</p> |
10,611,927 | SimpleCursorTreeAdapter and CursorLoader for ExpandableListView | <p>I am trying to asynchronously query a provider by using a <code>CursorLoader</code> with a <code>SimpleCursorTreeAdapter</code> </p>
<p>Here is my <code>Fragment</code> class which implements the <code>CursorLoader</code> </p>
<pre><code>public class GroupsListFragment extends ExpandableListFragment implements
LoaderManager.LoaderCallbacks<Cursor> {
private final String DEBUG_TAG = getClass().getSimpleName().toString();
private static final String[] CONTACTS_PROJECTION = new String[] {
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME };
private static final String[] GROUPS_SUMMARY_PROJECTION = new String[] {
ContactsContract.Groups.TITLE, ContactsContract.Groups._ID,
ContactsContract.Groups.SUMMARY_COUNT,
ContactsContract.Groups.ACCOUNT_NAME,
ContactsContract.Groups.ACCOUNT_TYPE,
ContactsContract.Groups.DATA_SET };
GroupsAdapter mAdapter;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
populateContactList();
getLoaderManager().initLoader(-1, null, this);
}
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
// This is called when a new Loader needs to be created.
Log.d(DEBUG_TAG, "onCreateLoader for loader_id " + id);
CursorLoader cl;
if (id != -1) {
// child cursor
Uri contactsUri = ContactsContract.Data.CONTENT_URI;
String selection = "(("
+ ContactsContract.CommonDataKinds.GroupMembership.DISPLAY_NAME
+ " NOTNULL) AND ("
+ ContactsContract.CommonDataKinds.GroupMembership.HAS_PHONE_NUMBER
+ "=1) AND ("
+ ContactsContract.CommonDataKinds.GroupMembership.DISPLAY_NAME
+ " != '') AND ("
+ ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID
+ " = ? ))";
String sortOrder = ContactsContract.CommonDataKinds.GroupMembership.DISPLAY_NAME
+ " COLLATE LOCALIZED ASC";
String[] selectionArgs = new String[] { String.valueOf(id) };
cl = new CursorLoader(getActivity(), contactsUri,
CONTACTS_PROJECTION, selection, selectionArgs, sortOrder);
} else {
// group cursor
Uri groupsUri = ContactsContract.Groups.CONTENT_SUMMARY_URI;
String selection = "((" + ContactsContract.Groups.TITLE
+ " NOTNULL) AND (" + ContactsContract.Groups.TITLE
+ " != '' ))";
String sortOrder = ContactsContract.Groups.TITLE
+ " COLLATE LOCALIZED ASC";
cl = new CursorLoader(getActivity(), groupsUri,
GROUPS_SUMMARY_PROJECTION, selection, null, sortOrder);
}
return cl;
}
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
// Swap the new cursor in.
int id = loader.getId();
Log.d(DEBUG_TAG, "onLoadFinished() for loader_id " + id);
if (id != -1) {
// child cursor
if (!data.isClosed()) {
Log.d(DEBUG_TAG, "data.getCount() " + data.getCount());
try {
mAdapter.setChildrenCursor(id, data);
} catch (NullPointerException e) {
Log.w("DEBUG","Adapter expired, try again on the next query: "
+ e.getMessage());
}
}
} else {
mAdapter.setGroupCursor(data);
}
}
public void onLoaderReset(Loader<Cursor> loader) {
// This is called when the last Cursor provided to onLoadFinished()
// is about to be closed.
int id = loader.getId();
Log.d(DEBUG_TAG, "onLoaderReset() for loader_id " + id);
if (id != -1) {
// child cursor
try {
mAdapter.setChildrenCursor(id, null);
} catch (NullPointerException e) {
Log.w("TAG", "Adapter expired, try again on the next query: "
+ e.getMessage());
}
} else {
mAdapter.setGroupCursor(null);
}
}
/**
* Populate the contact list
*/
private void populateContactList() {
// Set up our adapter
mAdapter = new GroupsAdapter(getActivity(),this,
android.R.layout.simple_expandable_list_item_1,
android.R.layout.simple_expandable_list_item_1,
new String[] { ContactsContract.Groups.TITLE }, // Name for group layouts
new int[] { android.R.id.text1 },
new String[] { ContactsContract.Contacts.DISPLAY_NAME }, // Name for child layouts
new int[] { android.R.id.text1 });
setListAdapter(mAdapter);
}
}
</code></pre>
<p>And here is my adapter which subclasses <code>SimpleCursorTreeAdapter</code> </p>
<pre><code>public class GroupsAdapter extends SimpleCursorTreeAdapter {
private final String DEBUG_TAG = getClass().getSimpleName().toString();
private ContactManager mActivity;
private GroupsListFragment mFragment;
// Note that the constructor does not take a Cursor. This is done to avoid
// querying the database on the main thread.
public GroupsAdapter(Context context, GroupsListFragment glf,
int groupLayout, int childLayout, String[] groupFrom,
int[] groupTo, String[] childrenFrom, int[] childrenTo) {
super(context, null, groupLayout, groupFrom, groupTo, childLayout,
childrenFrom, childrenTo);
mActivity = (ContactManager) context;
mFragment = glf;
}
@Override
protected Cursor getChildrenCursor(Cursor groupCursor) {
// Given the group, we return a cursor for all the children within that group
int groupId = groupCursor.getInt(groupCursor
.getColumnIndex(ContactsContract.Groups._ID));
Log.d(DEBUG_TAG, "getChildrenCursor() for groupId " + groupId);
Loader loader = mActivity.getLoaderManager().getLoader(groupId);
if ( loader != null && loader.isReset() ) {
mActivity.getLoaderManager().restartLoader(groupId, null, mFragment);
} else {
mActivity.getLoaderManager().initLoader(groupId, null, mFragment);
}
}
}
</code></pre>
<p>The problem is that when i click one of the parent groups one of three things happens in what appears to be a inconsistent fashion. </p>
<p>1) Either the group opens up and the children appear below it</p>
<p>2) The group does not open and the <code>setChildrenCursor()</code> call throws an <code>NullPointerException</code> error which gets caught in the try catch block</p>
<p>3) The group does not open and no error is thrown</p>
<p>Here is some debugging output in a scenario in which a group is expanded and showing the children:</p>
<p>When all groups are displayed it ouputs:</p>
<pre><code>05-20 10:08:22.765: D/GroupsListFragment(22132): onCreateLoader for loader_id -1
05-20 10:08:23.613: D/GroupsListFragment(22132): onLoadFinished() for loader_id -1
</code></pre>
<p>-1 is the loader_id of the group cursor</p>
<p>Then if i select one group in particular (let's just call it group A) it outputs:</p>
<pre><code>05-20 23:22:31.140: D/GroupsAdapter(13844): getChildrenCursor() for groupId 67
05-20 23:22:31.140: D/GroupsListFragment(13844): onCreateLoader for loader_id 67
05-20 23:22:31.254: D/GroupsListFragment(13844): onLoadFinished() for loader_id 67
05-20 23:22:31.254: D/GroupsListFragment(13844): data.getCount() 4
05-20 23:22:31.254: W/GroupsListFragment(13844): Adapter expired, try again on the next query: null
</code></pre>
<p>The group does not expand and the <code>NullPointerException</code> is caught. Then if i select another group (let's just call it group B) it outputs:</p>
<pre><code>05-20 23:25:38.089: D/GroupsAdapter(13844): getChildrenCursor() for groupId 3
05-20 23:25:38.089: D/GroupsListFragment(13844): onCreateLoader for loader_id 3
05-20 23:25:38.207: D/GroupsListFragment(13844): onLoadFinished() for loader_id 3
05-20 23:25:38.207: D/GroupsListFragment(13844): data.getCount() 6
</code></pre>
<p>This time, the <code>NullPointerException</code> is not thrown. And instead of group B expanding, group A is expanded.</p>
<p>Can anyone explain the behavior that the <code>setChildrenCursor()</code> call is exhibiting?</p>
<p>I am thinking there is a problem with how the group/child CursorLoaders are instantiated in <code>onCreateLoader()</code>. For the group <code>CursorLoader</code> i just want all groups in my phone. The child <code>CursorLoader</code> should contain all contacts within a group. Does anyone have any ideas what could be the issue?</p>
<p><strong>UPDATE</strong></p>
<p>Thanks to @Yam's advice I have now modified the <code>getChildrenCursor()</code> method. I am now selecting the groupCursor position not the value of ContactsContract.Groups._ID to pass into the initLoader() call. I also changed the logic to call restartLoader() only when loader is not null and loader isReset is false.</p>
<pre><code>protected Cursor getChildrenCursor(Cursor groupCursor) {
// Given the group, we return a cursor for all the children within that
// group
int groupPos = groupCursor.getPosition();
Log.d(DEBUG_TAG, "getChildrenCursor() for groupPos " + groupPos);
Loader loader = mActivity.getLoaderManager().getLoader(groupPos);
if (loader != null && !loader.isReset()) {
mActivity.getLoaderManager().restartLoader(groupPos, null, mFragment);
} else {
mActivity.getLoaderManager().initLoader(groupPos, null, mFragment);
}
return null;
}
</code></pre>
<p>This definitely makes more sense and does not exhibit some of the erratic behavior of a group expanding sometimes and not other times. </p>
<p>However, there are contacts that are being displayed under a group that they don't belong to. And also some groups that do have contacts in them but it won't show any contacts. So it seems that the <code>getChildrenCursor()</code> issues may now be resolved. </p>
<p>But now it looks to be an issue of how the CursorLoaders are instantiated in the <code>onCreateLoader()</code> method. Is the <code>CursorLoader</code> returned in the <code>onCreateLoader()</code> method for the child cursor being instantiated improperly? </p>
<p><strong>UPDATE</strong></p>
<p>So I have identified one of my issues. In the <code>getChildrenCursor()</code> method if I pass the groupId into the <code>initLoader()</code> method then in the <code>onCreateLoader()</code> method, when the <code>CursorLoader</code> is created it will get the correct groupid parameter for the query. However, in the <code>onLoadFinished()</code> the call to <code>setChildrenCursor()</code> is getting passed the loader id for the first parameter not the groupPosition. I'm guessing i have to map loader ids to group positions in some data structure. But i'm not sure if this is the best approach. Does anyone have any suggestions?</p> | 10,989,548 | 3 | 4 | 2012-05-21 06:45:40.077 UTC | 2012-05-16 04:18:42.827 UTC | 22 | 2014-12-17 12:04:21.107 UTC | 2012-10-20 22:28:41.73 UTC | null | 502,671 | null | 502,671 | null | 1 | 22 | android|simplecursoradapter|expandablelistadapter|android-cursorloader | 21,918 | <p>So i figured out that I needed to map loaderids to groupPositions and this solved my issue:</p>
<p>Here is my <code>Fragment</code> class which implements the <code>CursorLoader</code> </p>
<pre><code>public class GroupsListFragment extends ExpandableListFragment implements
LoaderManager.LoaderCallbacks<Cursor> {
private final String DEBUG_TAG = getClass().getSimpleName().toString();
private static final String[] CONTACTS_PROJECTION = new String[] {
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME };
private static final String[] GROUPS_PROJECTION = new String[] {
ContactsContract.Groups.TITLE, ContactsContract.Groups._ID };
GroupsAdapter mAdapter;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
populateContactList();
// Prepare the loader. Either re-connect with an existing one,
// or start a new one.
Loader loader = getLoaderManager().getLoader(-1);
if (loader != null && !loader.isReset()) {
getLoaderManager().restartLoader(-1, null, this);
} else {
getLoaderManager().initLoader(-1, null, this);
}
}
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
// This is called when a new Loader needs to be created.
Log.d(DEBUG_TAG, "onCreateLoader for loader_id " + id);
CursorLoader cl;
if (id != -1) {
// child cursor
Uri contactsUri = ContactsContract.Data.CONTENT_URI;
String selection = "((" + ContactsContract.Contacts.DISPLAY_NAME
+ " NOTNULL) AND ("
+ ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1) AND ("
+ ContactsContract.Contacts.DISPLAY_NAME + " != '') AND ("
+ ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID
+ " = ? ))";
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME
+ " COLLATE LOCALIZED ASC";
String[] selectionArgs = new String[] { String.valueOf(id) };
cl = new CursorLoader(getActivity(), contactsUri,
CONTACTS_PROJECTION, selection, selectionArgs, sortOrder);
} else {
// group cursor
Uri groupsUri = ContactsContract.Groups.CONTENT_URI;
String selection = "((" + ContactsContract.Groups.TITLE
+ " NOTNULL) AND (" + ContactsContract.Groups.TITLE
+ " != '' ))";
String sortOrder = ContactsContract.Groups.TITLE
+ " COLLATE LOCALIZED ASC";
cl = new CursorLoader(getActivity(), groupsUri,
GROUPS_PROJECTION, selection, null, sortOrder);
}
return cl;
}
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
// Swap the new cursor in.
int id = loader.getId();
Log.d(DEBUG_TAG, "onLoadFinished() for loader_id " + id);
if (id != -1) {
// child cursor
if (!data.isClosed()) {
Log.d(DEBUG_TAG, "data.getCount() " + data.getCount());
HashMap<Integer,Integer> groupMap = mAdapter.getGroupMap();
try {
int groupPos = groupMap.get(id);
Log.d(DEBUG_TAG, "onLoadFinished() for groupPos " + groupPos);
mAdapter.setChildrenCursor(groupPos, data);
} catch (NullPointerException e) {
Log.w("DEBUG","Adapter expired, try again on the next query: "
+ e.getMessage());
}
}
} else {
mAdapter.setGroupCursor(data);
}
}
public void onLoaderReset(Loader<Cursor> loader) {
// This is called when the last Cursor provided to onLoadFinished()
// is about to be closed.
int id = loader.getId();
Log.d(DEBUG_TAG, "onLoaderReset() for loader_id " + id);
if (id != -1) {
// child cursor
try {
mAdapter.setChildrenCursor(id, null);
} catch (NullPointerException e) {
Log.w("TAG", "Adapter expired, try again on the next query: "
+ e.getMessage());
}
} else {
mAdapter.setGroupCursor(null);
}
}
/**
* Populate the contact list
*/
private void populateContactList() {
// Set up our adapter
mAdapter = new GroupsAdapter(getActivity(),this,
android.R.layout.simple_expandable_list_item_1,
android.R.layout.simple_expandable_list_item_1,
new String[] { ContactsContract.Groups.TITLE }, // Name for group layouts
new int[] { android.R.id.text1 },
new String[] { ContactsContract.Contacts.DISPLAY_NAME }, // Name for child layouts
new int[] { android.R.id.text1 });
setListAdapter(mAdapter);
}
}
</code></pre>
<p>And here is my adapter which subclasses <code>SimpleCursorTreeAdapter</code> </p>
<pre><code>public class GroupsAdapter extends SimpleCursorTreeAdapter {
private final String DEBUG_TAG = getClass().getSimpleName().toString();
private ContactManager mActivity;
private GroupsListFragment mFragment;
protected final HashMap<Integer, Integer> mGroupMap;
// Note that the constructor does not take a Cursor. This is done to avoid
// querying the database on the main thread.
public GroupsAdapter(Context context, GroupsListFragment glf,
int groupLayout, int childLayout, String[] groupFrom,
int[] groupTo, String[] childrenFrom, int[] childrenTo) {
super(context, null, groupLayout, groupFrom, groupTo, childLayout,
childrenFrom, childrenTo);
mActivity = (ContactManager) context;
mFragment = glf;
mGroupMap = new HashMap<Integer, Integer>();
}
@Override
protected Cursor getChildrenCursor(Cursor groupCursor) {
// Given the group, we return a cursor for all the children within that group
int groupPos = groupCursor.getPosition();
int groupId = groupCursor.getInt(groupCursor
.getColumnIndex(ContactsContract.Groups._ID));
Log.d(DEBUG_TAG, "getChildrenCursor() for groupPos " + groupPos);
Log.d(DEBUG_TAG, "getChildrenCursor() for groupId " + groupId);
mGroupMap.put(groupId, groupPos);
Loader loader = mActivity.getLoaderManager().getLoader(groupId);
if ( loader != null && !loader.isReset() ) {
mActivity.getLoaderManager().restartLoader(groupId, null, mFragment);
} else {
mActivity.getLoaderManager().initLoader(groupId, null, mFragment);
}
return null;
}
//Accessor method
public HashMap<Integer, Integer> getGroupMap() {
return mGroupMap;
}
}
</code></pre> |
10,600,863 | Overlaying DIVs with z-index | <p>I am trying to overlay a div over my entire page to show a pop-up. The problem is, it won't overlay over the entire page. Here is an approximation of the code:</p>
<pre><code><div style="z-index:902;">
<div style="position: fixed; width: 100%; height: 100%; left: 0; top: 0;">
Overlay
</div>
Contents of container 1
</div>
<div style="z-index:902;">
Contents of container 2
</div>
<div style="z-index:902;">
Contents of container 3
</div>
</code></pre>
<p>The overlay div appears on top of container 1, but the contents of container 2 and 3 appear on top of the overlay.</p>
<p>I cannot move my overlay div outside of the container 1, as I am using a CMS (DotNetNuke if that helps).</p>
<p>I have tried setting the z-index of my overlay higher than the containers, but nothing is working.</p>
<p>Can anyone help?</p> | 10,600,924 | 6 | 6 | null | 2012-05-15 12:40:12.87 UTC | 1 | 2018-09-12 17:54:13.89 UTC | null | null | null | null | 970,789 | null | 1 | 3 | css|html|overlay | 46,740 | <p>Working <a href="http://jsfiddle.net/zuul/H5NB8/" rel="nofollow noreferrer">Fiddle Example!</a></p>
<p>If you limit the scope of this problem to the code that you've presented, it is working just fine! e.g., On the Fiddle you can see that I placed a background color to the <code>position:fixed</code> <code>div</code> as to illustrate that the solution is working.</p>
<p><strong>However</strong>, if you are using <code>z-index</code>, is safe to assume that your elements with <code>z-index</code> have some <code>position</code> applied.</p>
<p>Taking this into consideration, this part:</p>
<pre><code><div style="z-index:902;">
<div style="position: fixed; width: 100%; height: 100%; left: 0; top: 0;">
Overlay
</div>
Contents of container 1
</div>
</code></pre>
<p><strong>cannot work</strong> as an "entire page" overlay since the inner div with <code>position:fixed</code> is inside a stacked element that has other stacked elements on the side (siblings), on the same stack position with <code>z-index:902;</code>.</p>
<p>See this <a href="http://jsfiddle.net/zuul/H5NB8/7/" rel="nofollow noreferrer">Fiddle to illustrate!</a></p>
<p>If you move the siblings elements to a lower stack position, you can make it work. See this <a href="http://jsfiddle.net/zuul/H5NB8/8/" rel="nofollow noreferrer">Fiddle Example!</a></p>
<blockquote>
<p><strong>Edited</strong></p>
<p>This first part of my answer was edited as advised by <a href="https://stackoverflow.com/users/681807/my-head-hurts">My Head Hurts</a> (see comments), to better explain that the first Fiddle works because the OP placed the question leaving place to guesses! No changes were made to the two solutions presented and approved at this answer!</p>
</blockquote>
<hr>
<p><h2>A solution</h2> would be placing the overlay outside all other divs, but this depends on your goal:</p>
<pre><code><div style="z-index:902;">
Contents of container 1
</div>
<div style="z-index:902;">
Contents of container 2
</div>
<div style="z-index:902;">
Contents of container 3
</div>
<div style="position:fixed; z-index:10000; left:0; top:0; right:0; bottom:0; background:#ccc;">
Overlay
</div>
</code></pre>
<p>See this <a href="http://jsfiddle.net/zuul/H5NB8/2/" rel="nofollow noreferrer">Fiddle Example!</a></p>
<hr>
<h1>EDITED</h1>
<p><strong>because of this comment:</strong></p>
<p><em>Yes this would be the ideal answer, and I will accept it as it answers my question as written, but the problem I was facing was from some JavaScript that was dynamically changing the z-index of the other containers that I couldn't control making it impossible to place my div on top of them all.</em></p>
<p><strong>Assuming that you can</strong> place whatever you wish inside <code>container 1</code>, and assuming that you are using or can use jQuery, you can do this to solve the problem:</p>
<pre><code><div style="z-index:902;">
<div class="placeOutside" style="position:fixed; z-index:903; right:0; bottom:0; left:0; top:0; background:#ccc;">
Overlay
</div>
<script type="text/javascript">
jQuery(document).ready(function($) {
$('.placeOutside').appendTo('body');
});
</script>
Contents of container 1
</div>
<div style="z-index:902;">
Contents of container 2
</div>
<div style="z-index:902;">
Contents of container 3
</div>
</code></pre>
<p>See this working <a href="http://jsfiddle.net/zuul/H5NB8/5/" rel="nofollow noreferrer">Fiddle example!</a></p> |
46,358,013 | Secure Google Cloud Functions http trigger with auth | <p>I am trying out Google Cloud Functions today following this guide: <a href="https://cloud.google.com/functions/docs/quickstart" rel="noreferrer">https://cloud.google.com/functions/docs/quickstart</a></p>
<p>I created a function with an HTTP trigger, and was able to perform a POST request to trigger a function to write to Datastore.</p>
<p>I was wondering if there's a way I can secure this HTTP endpoint? Currently it seems that it will accept a request from anywhere/anyone. </p>
<p>When googling around, I see most results talk about securing things with Firebase. However, I am not using the Firebase service here.</p>
<p>Would my options be either let it open, and hope no one knows the URL endpoint (security by obscurity), or implement my own auth check in the function itself?</p> | 46,924,504 | 7 | 11 | null | 2017-09-22 06:14:49.75 UTC | 12 | 2021-10-29 19:30:36.77 UTC | null | null | null | null | 1,368,032 | null | 1 | 48 | security|authentication|google-cloud-datastore|google-cloud-functions | 18,252 | <p>After looking into this further, and taking a hint from @ricka's answer, I have decided to implement an authentication check for my cloud functions with a JWT token passed in in the form of an Authorization header access token.</p>
<p>Here's the implementation in Node:</p>
<pre><code>const client = jwksClient({
cache: true,
rateLimit: true,
jwksRequestsPerMinute: 5,
jwksUri: "https://<auth0-account>.auth0.com/.well-known/jwks.json"
});
function verifyToken(token, cb) {
let decodedToken;
try {
decodedToken = jwt.decode(token, {complete: true});
} catch (e) {
console.error(e);
cb(e);
return;
}
client.getSigningKey(decodedToken.header.kid, function (err, key) {
if (err) {
console.error(err);
cb(err);
return;
}
const signingKey = key.publicKey || key.rsaPublicKey;
jwt.verify(token, signingKey, function (err, decoded) {
if (err) {
console.error(err);
cb(err);
return
}
console.log(decoded);
cb(null, decoded);
});
});
}
function checkAuth (fn) {
return function (req, res) {
if (!req.headers || !req.headers.authorization) {
res.status(401).send('No authorization token found.');
return;
}
const parts = req.headers.authorization.split(' ');
if (parts.length != 2) {
res.status(401).send('Bad credential format.');
return;
}
const scheme = parts[0];
const credentials = parts[1];
if (!/^Bearer$/i.test(scheme)) {
res.status(401).send('Bad credential format.');
return;
}
verifyToken(credentials, function (err) {
if (err) {
res.status(401).send('Invalid token');
return;
}
fn(req, res);
});
};
}
</code></pre>
<p>I use <code>jsonwebtoken</code> to verify the JWT token, and <code>jwks-rsa</code> to retrieve the public key. I use Auth0, so <code>jwks-rsa</code> reaches out to the list of public keys to retrieve them.</p>
<p>The <code>checkAuth</code> function can then be used to safeguard the cloud function as:</p>
<pre><code>exports.get = checkAuth(function (req, res) {
// do things safely here
});
</code></pre>
<p>You can see this change on my github repo at <a href="https://github.com/tnguyen14/functions-datastore/commit/a6b32704f0b0a50cd719df8c1239f993ef74dab6" rel="noreferrer">https://github.com/tnguyen14/functions-datastore/commit/a6b32704f0b0a50cd719df8c1239f993ef74dab6</a></p>
<p>The JWT / access token can be retrieved in a number of way. For Auth0, the API doc can be found at <a href="https://auth0.com/docs/api/authentication#authorize-client" rel="noreferrer">https://auth0.com/docs/api/authentication#authorize-client</a></p>
<p>Once this is in place, you can trigger the cloud function (if you have yours enabled with http trigger) with something like</p>
<pre><code>curl -X POST -H "Content-Type: application/json" \
-H "Authorization: Bearer access-token" \
-d '{"foo": "bar"}' \
"https://<cloud-function-endpoint>.cloudfunctions.net/get"
</code></pre> |
31,745,168 | How to test Classes with @ConfigurationProperties and @Autowired | <p>I want to test small parts of the application that rely on properties loaded with <code>@Autowired</code> and <code>@ConfigurationProperties</code>. I am looking for a solution loading only the required properties and not always the whole <code>ApplicationContext</code>.
Here as reduced example:</p>
<pre><code>@TestPropertySource(locations = "/SettingsTest.properties")
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {TestSettings.class, TestConfiguration.class})
public class SettingsTest {
@Autowired
TestConfiguration config;
@Test
public void testConfig(){
Assert.assertEquals("TEST_PROPERTY", config.settings().getProperty());
}
}
</code></pre>
<p>Configuration Class:</p>
<pre><code>public class TestConfiguration {
@Bean
@ConfigurationProperties(prefix = "test")
public TestSettings settings (){
return new TestSettings();
}
}
</code></pre>
<p>Settings Class:</p>
<pre><code>public class TestSettings {
private String property;
public String getProperty() {
return property;
}
public void setProperty(String property) {
this.property = property;
}
}
</code></pre>
<p>The properties file in the resource folder contains the entry:</p>
<pre><code>test.property=TEST_PROPERTY
</code></pre>
<p>In my current setup config is not null, but no fields are available.
The reason the fields are not field should have something to do with the fact that I am not using Springboot but Spring.
So what would be the Springboot way to get this running?</p>
<p><strong>edit:</strong>
The reason why I want to do this is: I have a parser that parses Textfiles, the regular expressions used are stored in a properties file.
To test this I would like to load only the properties needed for this parser which are in the exaple above the <em>TestSettings</em>.</p>
<p>While reading the comments I already noticed that this are no Unit tests anymore. However using the full Spring boot configuration for this small test seems a bit too much to me. That's why I asked if there is a posibilty to load only the one class with properties.</p> | 31,748,450 | 5 | 5 | null | 2015-07-31 11:33:07.973 UTC | 10 | 2020-09-28 18:35:13.817 UTC | 2019-10-21 10:42:34.267 UTC | null | 3,657,460 | null | 4,494,324 | null | 1 | 51 | java|properties|spring-boot | 78,613 | <p>A couple points:</p>
<ol>
<li><p>You don't need a "TestConfiguration" class in your main package, because all it's doing is configuring the "TestSettings" bean. You can do this simply by annotating the TestSettings class itself.</p></li>
<li><p>Normally you would load the context you need for the test using the <strong>@SpringApplicationConfiguration</strong> annotation, passing the name of your Application class. However, you said you don't want to load the whole ApplicationContext (though it's not clear why), so you need to create a special configuration class to do the loading only for tests. Below I call it "TestConfigurationNew" to avoid confusion with the TestConfiguration class that you had originally.</p></li>
<li><p>In the Spring Boot world, all properties are generally kept in the "application.properties" file; but it is possible to store them elsewhere. Below, I have specified the "SettingsTest.properties" file that you proposed. Note that you can have two copies of this file, the one in the main/resources folder, and the one in the test/resources folder for testing.</p></li>
</ol>
<p>Change the code as follows:</p>
<p>TestSettings.java (in main package)</p>
<pre><code>@Configuration
@ConfigurationProperties(prefix="test", locations = "classpath:SettingsTest.properties")
public class TestSettings {
private String property;
public String getProperty() {
return property;
}
public void setProperty(String property) {
this.property = property;
}
}
</code></pre>
<p>SettingsTest.java (in test package)</p>
<pre><code>@TestPropertySource(locations="classpath:SettingsTest.properties")
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = TestConfigurationNew.class)
public class SettingsTest {
@Autowired
TestSettings settings;
@Test
public void testConfig(){
Assert.assertEquals("TEST_PROPERTY", settings.getProperty());
}
}
</code></pre>
<p>TestConfigurationNew.java (in test package):</p>
<pre><code>@EnableAutoConfiguration
@ComponentScan(basePackages = { "my.package.main" })
@Configuration
public class TestConfigurationNew {
}
</code></pre>
<p>This should now work the way you wanted.</p> |
10,680,961 | mysql - How to concatenate strings and convert to date the strings? | <h2>Please take a look at my stored procedure code.</h2>
<pre><code>CREATE DEFINER=`ninjaboy`@`%` PROCEDURE `getMonthlyTotalScore`(IN ninjaId int, IN month int, IN year int)
BEGIN
DECLARE startDate DATE;
DECLARE endDate DATE;
DECLARE maxDay INTEGER;
SELECT DAY(LAST_DAY(year + '-' + month + '-01')) INTO maxDay;
SET startDate = year + '-' + month + '-01';
SET endDate = year + '-' + month + '-' + maxDay;
SELECT SUM(SCORE) FROM NINJA_ACTIVITY WHERE NINJA_ID = ninjaId AND DATE BETWEEN startDate AND endDate ORDER BY DATE;
END
</code></pre>
<h2>Test Data:</h2>
<pre>
NINJA_ACTIVITY_ID | NINJA_ID | SCORE | DATE
1 1 24 2012-05-01
2 1 36 2012-05-06
3 1 29 2012-05-11
</pre>
<p>Function call : <code>call getTotalMonthlyScore (1, 5, 2012)</code></p>
<p>I'm trying to get the monthly score of any ninja based on the <code>ninjaId</code>.</p>
<p>Why is not working? Any idea where I am getting wrong?</p> | 10,681,317 | 3 | 13 | null | 2012-05-21 07:20:25.117 UTC | null | 2012-05-21 08:15:33.383 UTC | 2012-05-21 07:45:52.903 UTC | null | 1,066,828 | null | 991,229 | null | 1 | 3 | mysql|stored-procedures | 68,118 | <p><strong>CONCAT() is the key.</strong></p>
<h2>BEFORE:</h2>
<pre><code>mysql> CREATE PROCEDURE `getMonthlyTotalScore`(IN ninjaId int, IN month int, IN year int)
-> BEGIN
-> DECLARE startDate DATE;
-> DECLARE endDate DATE;
-> DECLARE maxDay INTEGER;
->
-> SELECT year + '-' + month + '-01'; #NOTE THIS
->
->
-> END;
-> |
Query OK, 0 rows affected (0.00 sec)
mysql> call getMonthlyTotalScore(1,5,2012);
-> |
+----------------------------+
| year + '-' + month + '-01' |
+----------------------------+
| 2016 |
+----------------------------+
1 row in set (0.00 sec)
</code></pre>
<h2>AFTER:</h2>
<pre><code>mysql> CREATE PROCEDURE `getMonthlyTotalScore`(IN ninjaId int, IN month int, IN year int)
-> BEGIN
-> DECLARE startDate DATE;
-> DECLARE endDate DATE;
-> DECLARE maxDay INTEGER;
->
-> SELECT CONCAT(year,'-',month,'-01'); # NOTE THIS
->
->
-> END; |
Query OK, 0 rows affected (0.00 sec)
mysql> call getMonthlyTotalScore(1,5,2012);
-> |
+------------------------------+
| CONCAT(year,'-',month,'-01') |
+------------------------------+
| 2012-5-01 |
+------------------------------+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.00 sec)
</code></pre> |
13,268,361 | bootstrap "tooltip" and "popover" add extra size in table | <blockquote>
<p><strong>Note:</strong><br>
Depending on you Bootstrap version (prior to 3.3 or not), you may need a different answer.<br>
Pay attention to the notes.</p>
</blockquote>
<p>When I activate tooltips (hover over the cell) or popovers in this code, size of table is increasing. How can I avoid this?</p>
<p>Here emptyRow - function to generate tr with 100
<pre><code><html>
<head>
<title></title>
<script type="text/javascript" language="javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<link type="text/css" rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css">
<script type="text/javascript" language="javascript" src="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.2.1/bootstrap.min.js"></script>
<style>
#matrix td {
width: 10px;
height: 10px;
border: 1px solid gray;
padding: 0px;
}
</style>
<script>
function emptyRow() {
str = '<tr>'
for (j = 0; j < 100; j++) {
str += '<td rel="tooltip" data-original-title="text"></td>'
}
str += '</tr>'
return str
}
$(document).ready(function () {
$("#matrix tr:last").after(emptyRow())
$("[rel=tooltip]").tooltip();
});
</script>
</head>
<body style="margin-top: 40px;">
<table id="matrix">
<tr>
</tr>
</table>
</body>
</html>
</code></pre>
<p>thank in advice!</p> | 13,269,857 | 7 | 5 | null | 2012-11-07 11:01:45.593 UTC | 17 | 2019-01-22 05:30:29.187 UTC | 2016-01-19 17:00:19.703 UTC | null | 1,238,019 | null | 1,291,049 | null | 1 | 85 | javascript|twitter-bootstrap|twitter-bootstrap-3|tooltip | 79,108 | <blockquote>
<p><strong>Note:</strong> Solution for Bootstrap 3.0 ~ 3.2</p>
</blockquote>
<p>You need to create an element inside a <code>td</code> and apply a tooltip to it, like <a href="http://jsfiddle.net/sZdYE/3/">this</a>, because a tooltip itself is a div, and when it is placed after a <code>td</code> element it brakes table layout.</p>
<p>This problem was introduced with the latest release of Bootstrap. There are ongoing discussions about fixes on <a href="https://github.com/twbs/bootstrap/issues/5687">GitHub here</a>. Hopefully the next version includes the fixed files.</p> |
13,400,075 | Reflection generic get field value | <p>I am trying to obtain a field's value via reflection. The problem is I don't know the field's type and have to decide it while getting the value.</p>
<p>This code results with this exception:</p>
<blockquote>
<p>Can not set java.lang.String field com....fieldName to java.lang.String</p>
</blockquote>
<pre class="lang-java prettyprint-override"><code>Field field = object.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
Class<?> targetType = field.getType();
Object objectValue = targetType.newInstance();
Object value = field.get(objectValue);
</code></pre>
<p>I tried to cast, but I get compilation errors:</p>
<pre><code>field.get((targetType)objectValue)
</code></pre>
<p>or</p>
<pre><code>targetType objectValue = targetType.newInstance();
</code></pre>
<p>How can I do this?</p> | 13,401,094 | 9 | 1 | null | 2012-11-15 14:55:24.02 UTC | 41 | 2022-07-07 05:29:55.597 UTC | 2021-03-11 11:41:22 UTC | null | 2,164,365 | null | 1,012,646 | null | 1 | 170 | java|reflection | 448,392 | <p>Like answered before, you should use:</p>
<pre><code>Object value = field.get(objectInstance);
</code></pre>
<p>Another way, which is sometimes prefered, is calling the getter dynamically. example code:</p>
<pre><code>public static Object runGetter(Field field, BaseValidationObject o)
{
// MZ: Find the correct method
for (Method method : o.getMethods())
{
if ((method.getName().startsWith("get")) && (method.getName().length() == (field.getName().length() + 3)))
{
if (method.getName().toLowerCase().endsWith(field.getName().toLowerCase()))
{
// MZ: Method found, run it
try
{
return method.invoke(o);
}
catch (IllegalAccessException e)
{
Logger.fatal("Could not determine method: " + method.getName());
}
catch (InvocationTargetException e)
{
Logger.fatal("Could not determine method: " + method.getName());
}
}
}
}
return null;
}
</code></pre>
<p>Also be aware that when your class inherits from another class, you need to recursively determine the Field. for instance, to fetch all Fields of a given class;</p>
<pre><code> for (Class<?> c = someClass; c != null; c = c.getSuperclass())
{
Field[] fields = c.getDeclaredFields();
for (Field classField : fields)
{
result.add(classField);
}
}
</code></pre> |
39,500,634 | Use xcodebuild (Xcode 8) and automatic signing in CI (Travis/Jenkins) environments | <p>With the release of Xcode 8, Apple introduced a new way of managing the signing configuration. Now you have two options <code>Manual</code> and <code>Automatic</code>.</p>
<p>According to the WWDC 2016 Session about Code signing <a href="https://developer.apple.com/videos/play/wwdc2016/401/" rel="noreferrer">(WWDC 2016 - 401 - What's new in Xcode app signing)</a>, when you select <code>Automatic</code> signing, Xcode is going to:</p>
<ul>
<li>Create signing certificates</li>
<li>Create and update App IDs</li>
<li>Create and update provisioning profiles</li>
</ul>
<p>But according to what Apple says in that session, the <code>Automatic Signing</code> is going to use <code>Development signing</code> and will be limited to Xcode-created provisioning profiles.</p>
<p>The issue comes when you try to use <code>Automatic Signing</code> on a CI environment (like Travis CI or Jenkins). I'm not able to figure out an easy way to keep using Automatic and sign for Distribution (as Xcode forces you to use Development and Xcode-created provisioning profiles).</p>
<p>The new "Xcode-created provisioning profiles" do not show up in the developer portal, although I can find then in my machine... should I move those profiles to the CI machine, build for <code>Development</code> and export for <code>Distribution</code>? Is there a way to override the <code>Automatic Signing</code> using <code>xcodebuild</code>?</p> | 39,598,052 | 8 | 5 | null | 2016-09-14 22:32:07.01 UTC | 45 | 2017-09-28 15:11:43.353 UTC | 2016-09-15 04:37:26.527 UTC | null | 805,755 | null | 805,755 | null | 1 | 80 | xcode|jenkins|continuous-integration|travis-ci|xcodebuild | 63,110 | <p>After trying a few options, these are the solutions that I was able to use on my CI server:</p>
<ul>
<li><h3>Include the Developer certificate and private key as well as the auto generated provisioning profiles in the CI environment:</h3></li>
</ul>
<p>Using <code>Automatic signing</code> forces you to use a <code>Developer</code> certificate and <code>auto-generated provisioning profiles</code>. One option is to export your development certificate and private key (Application -> Utilities -> Keychain Access) and the auto-generated provisioning profiles to the CI machine. A way to locate the auto-generated provisioning profiles is to navigate to <code>~/Library/MobileDevice/Provisioning\ Profiles/</code>, move all files to a backup folder, open Xcode and archive the project. Xcode will create auto-generated development provisioning profiles and will copy them to the <code>Provisioning Profiles</code> folder.</p>
<p><code>xcodebuild archive ...</code> will create a <code>.xcarchive</code> signed for <code>Development</code>. <code>xcodebuild -exportArchive ...</code> can then resign the build for <code>Distribution</code> </p>
<ul>
<li><h3>Replace 'Automatic' with 'Manual' when building on a CI environment</h3></li>
</ul>
<p>Before calling <code>xcodebuild</code> a workaround is to replace all instances of <code>ProvisioningStyle = Automatic</code> with <code>ProvisioningStyle = Manual</code> in the project file. <code>sed</code> can be used for a simple find an replace in the <code>pbxproj</code> file:</p>
<p><code>sed -i '' 's/ProvisioningStyle = Automatic;/ProvisioningStyle = Manual;/' <ProjectName>.xcodeproj/project.pbxproj</code></p>
<p>@thelvis also created a <a href="https://gist.github.com/thelvis4/253a2cdea8360da519b2a025c5d8fbac" rel="noreferrer">Ruby script</a> to do this using the <code>xcodeproj</code> gem. The script gives you a better control over what is changed.</p>
<p><code>xcodebuild</code> will then use the code signing identity (<code>CODE_SIGN_IDENTITY</code>) set in the project, as well as the provisioning profiles (<code>PROVISIONING_PROFILE_SPECIFIER</code>). Those settings can also be provided as parameters to <code>xcodebuild</code> and they will override the code signing identity and/or provisioning profile set in the project.</p>
<blockquote>
<p>EDIT: with Xcode 9, <code>xcodebuild</code> has a new build settings parameter <code>CODE_SIGN_STYLE</code> to select between <code>Automatic</code> and <code>Manual</code> so there's no need to find and replace instances of automatic with manual in the project file, more info in <a href="https://developer.apple.com/videos/play/wwdc2017/403/" rel="noreferrer">WWDC 2017 Session 403 What's New in Signing for Xcode and Xcode Server</a></p>
</blockquote>
<ul>
<li><h3>Switch to manual signing</h3></li>
</ul>
<p>Manual signing will provide total control over the code signing identities and provisioning profiles being used. It's probably the cleanest solution, but with the downside of losing all the benefits of Automatic signing.</p>
<p>To learn more about code signing with Xcode 8 I really recommend this <a href="https://pewpewthespells.com/blog/migrating_code_signing.html" rel="noreferrer">article</a> as well as the WWDC2016 session <a href="https://developer.apple.com/videos/play/wwdc2016/401/" rel="noreferrer">401 - What's new in Xcode app signing</a></p> |
20,532,640 | What is the maximum size for the postMessage method that enables inter-frame communication? | <p>It's not clear from searching on Google and looking through documentation. What's the maximum length on a message sent via <code>Window.postMessage</code> (<a href="https://developer.mozilla.org/en-US/docs/Web/API/Window.postMessage" rel="noreferrer">https://developer.mozilla.org/en-US/docs/Web/API/Window.postMessage</a>)? We assume this varies by browser?</p> | 24,712,574 | 1 | 2 | null | 2013-12-12 00:16:59.113 UTC | 4 | 2021-10-03 08:25:04.59 UTC | 2021-10-03 08:25:04.59 UTC | null | 4,370,109 | null | 144,088 | null | 1 | 31 | javascript|html|iframe|dom-events | 11,839 | <p>As a data point, the WebKit implementation (used by Safari and Chrome)
doesn't currently enforce any limits (other than those imposed by running
out of memory).</p>
<p>Source : <a href="https://lists.w3.org/Archives/Public/public-whatwg-archive/2009Oct/0546.html" rel="nofollow noreferrer">https://lists.w3.org/Archives/Public/public-whatwg-archive/2009Oct/0546.html</a></p> |
24,119,920 | How to plot a density map in python? | <p>I have a .txt file containing the x,y values of regularly spaced points in a 2D map, the 3rd coordinate being the density at that point.</p>
<pre><code>4.882812500000000E-004 4.882812500000000E-004 0.9072267
1.464843750000000E-003 4.882812500000000E-004 1.405174
2.441406250000000E-003 4.882812500000000E-004 24.32851
3.417968750000000E-003 4.882812500000000E-004 101.4136
4.394531250000000E-003 4.882812500000000E-004 199.1388
5.371093750000000E-003 4.882812500000000E-004 1278.898
6.347656250000000E-003 4.882812500000000E-004 1636.955
7.324218750000000E-003 4.882812500000000E-004 1504.590
8.300781250000000E-003 4.882812500000000E-004 814.6337
9.277343750000000E-003 4.882812500000000E-004 273.8610
</code></pre>
<p>When I plot this density map in gnuplot, with the following commands:</p>
<pre><code>set palette rgbformulae 34,35,0
set size square
set pm3d map
splot "dens_map.map" u 1:2:(log10($3+10.)) title "Density map"`
</code></pre>
<p>Which gives me this beautiful image: </p>
<p><img src="https://i.stack.imgur.com/AZsBO.jpg" alt="enter image description here"></p>
<p>Now I would like to have the same result with matplotlib. </p> | 24,122,985 | 2 | 2 | null | 2014-06-09 12:04:27.08 UTC | 14 | 2016-02-04 21:51:11.107 UTC | 2014-06-09 13:53:34.243 UTC | null | 249,341 | null | 3,722,235 | null | 1 | 32 | python|matplotlib|histogram | 70,754 | <p>Here is my aim at a more complete answer including choosing the color map and a logarithmic normalization of the color axis.</p>
<pre><code>import matplotlib.pyplot as plt
import matplotlib.cm as cm
from matplotlib.colors import LogNorm
import numpy as np
x, y, z = np.loadtxt('data.txt', unpack=True)
N = int(len(z)**.5)
z = z.reshape(N, N)
plt.imshow(z+10, extent=(np.amin(x), np.amax(x), np.amin(y), np.amax(y)),
cmap=cm.hot, norm=LogNorm())
plt.colorbar()
plt.show()
</code></pre>
<p>I assume here that your data can be transformed into a 2d array by a simple reshape. If this is not the case than you need to work a bit harder on getting the data in this form. Using imshow and not pcolormesh is more efficient here if you data lies on a grid (as it seems to do). The above code snippet results in the following image, that comes pretty close to what you wanted:</p>
<p><img src="https://i.stack.imgur.com/XdRlN.png" alt="Resulting image"></p> |
4,032,829 | Correct way to poll server in background | <p>Assuming this is possible, I would like my iOS application, when backgrounded, to poll a server (i.e. essentially, retrieve the contents of a URL every 30 minutes and notify the user if it contains something "interesting"), essentially in a similar way to the way the built-in mail client assumedly works if you're not using push notifications.</p>
<p>Now, from my reading so far (I'm an experienced programmer, but new to iOS), I think there may be two potential ways to do this:</p>
<ul>
<li>Method 1: In applicationDidEnterBackground:, start a background task which does the periodic polling;</li>
<li>Method 2: Send your own app a UILocalNotification with no visible text to the user, but which simply serves to wake your app up in X minutes time to do the polling (and then send itself another notification for next tim etc).</li>
</ul>
<p>I see in Apple's documentation of <a href="http://developer.apple.com/library/ios/#documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/IPhoneOSClientImp/IPhoneOSClientImp.html" rel="noreferrer">Scheduling, Registering, and Handling Notifications</a>, they actually seem to have an example usign Method 1 (their "chat" example, Listing 2-2). But what is surprising about this method is that it appears to just sit in a continual loop doing the polling, with no intervening sleep; on platforms I'm more familiar with, this would be inadvisable and would burn CPU.</p>
<p>So subparts of my question are essentially:
- Is Method 2 possible (or <em>must</em> a UILocalNotification always cause a visible alert to the user, which is not what I want) and if so is it the recommended way to do this?
- If the way to do it is Method 1, is Apple's "chat" example of sitting in a continual loop actually OK (e.g. does iOS ration the CPU so that this isn't an issue), and if not what is the way in iOS to tell the background process to "sleep for X seconds/minutes"? And if Apple's continuous loop is OK for whatever reason, what would then be the way to time the intervals between polling?</p>
<p>N.B. I appreciate that being able to run in the background at all is essentially an iOS 4 feature. I don't mind if my app will only run in iOS 4.</p> | 4,032,990 | 2 | 0 | null | 2010-10-27 11:46:19.093 UTC | 12 | 2010-10-27 12:13:06.49 UTC | null | null | null | null | 48,933 | null | 1 | 17 | iphone|multitasking | 7,607 | <p>What you want to do, is not covered under the multitasking features of iOS4. There are only a few types of applications allowed to run in the background for long periods of time (more than 10 minutes), and generic networking applications aren't one of them.</p>
<p>However, all is not lost. What you can do, and what I believe you <strong><em>should</em></strong> do is to use push notifications. On your server, you link up with apple's push notification service, the user registers for push notifications, and you either know what "interesting data" is, or they tell you. When that data is available, you send it to the user immediately via a push notification.</p>
<p>It provides a nicer user experience, and your app doesn't need to be running in the background. iOS will handle delivery of the push notification. If they swipe to unlock the phone when they get the notification, your app will open up, and at which time, you can load that useful information in your app.</p>
<p>Your method 1 won't work long term, even if you do manage to pause input for a while, and this is why: Launching a background task runs a task for NO MORE than 10 minutes, unless you are one of the three types of applications that is allowed to stay running. After 10 minutes, the OS will suspend you.</p>
<p>Your method 2 won't work at all. All local notifications present an alert view to users.</p> |
3,962,939 | What's the difference between undefined in Haskell and null in Java? | <p>Both are terms whose type is the intersection of all types (uninhabited). Both can be passed around in code without failing until one attempts to evaluate them. The only difference I can see is that in Java, there is a loophole which allows <code>null</code> to be evaluated for exactly one operation, which is reference equality comparison (<code>==</code>)--whereas in Haskell <code>undefined</code> can't be evaluated at all without throwing an exception. Is this the only difference?</p>
<h2>Edit</h2>
<p>What I'm really trying to get at with this question is, why was including <code>null</code> in Java such an apparently poor decision, and how does Haskell escape it? It seems to me that the real problem is that you can do something <em>useful</em> with <code>null</code>, namely you can check it for <em>nullness</em>. Because you are allowed to do this, it has become standard convention to pass around null values in code and have them indicate "no result" instead of "there is a logical error in this program". Whereas in Haskell, there's no way to check if a term evaluates to bottom without evaluating it and the program exploding, so it could never be used in such a way to indicate "no result". Instead, one is forced to use something like <code>Maybe</code>.</p>
<p>Sorry if it seems like I'm playing fast and loose with the term "evaluate"... I'm trying to draw an analogy here and having trouble phrasing it precisely. I guess that's a sign that the analogy is imprecise.</p> | 3,963,464 | 2 | 6 | null | 2010-10-18 20:05:41.483 UTC | 11 | 2011-04-16 20:22:58.563 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 231,853 | null | 1 | 52 | java|haskell|types|null|option-type | 8,026 | <blockquote>
<p>What's the difference between undefined in Haskell and null in Java?</p>
</blockquote>
<p>Ok, let's back up a little.</p>
<p>"undefined" in Haskell is an example of a "bottom" value (denoted ⊥). Such a value represents any undefined, stuck or partial state in the program.</p>
<p>Many different forms of bottom exist: non-terminating loops, exceptions, pattern match failures -- basically any state in the program that is undefined in some sense. The value <code>undefined :: a</code> is a canonical example of a value that puts the program in an undefined state.</p>
<p><code>undefined</code> itself isn't particularly special -- its not wired in -- and you can implement Haskell's <code>undefined</code> using any bottom-yielding expression. E.g. this is a valid implementation of <code>undefined</code>:</p>
<pre><code> > undefined = undefined
</code></pre>
<p>Or exiting immediately (the old Gofer compiler used this definition):</p>
<pre><code> > undefined | False = undefined
</code></pre>
<p>The primary property of bottom is that if an expression evaluates to bottom, your entire program will evaluate to bottom: the program is in an undefined state.</p>
<p>Why would you want such a value? Well, in a lazy language, you can often manipulate structures or functions that store bottom values, without the program being itself bottom.</p>
<p>E.g. a list of infinite loops is perfectly cromulent:</p>
<pre><code> > let xs = [ let f = f in f
, let g n = g (n+1) in g 0
]
> :t xs
xs :: [t]
> length xs
2
</code></pre>
<p>I just can't do much with the elements of the list:</p>
<pre><code> > head xs
^CInterrupted.
</code></pre>
<p>This manipulation of infinite stuff is part of why Haskell's so fun and expressive. A result of laziness is Haskell pays particularly close attention to <code>bottom</code> values.</p>
<p>However, clearly, the concept of bottom applies equally well to Java, or any (non-total) language. In Java, there are many expressions that yield "bottom" values:</p>
<ul>
<li>comparing a reference against null (though note, not <code>null</code> itself, which is well-defined);</li>
<li>division by zero;</li>
<li>out-of-bounds exceptions;</li>
<li>an infinite loop, etc.</li>
</ul>
<p>You just don't have the ability to substitute one bottom for another very easily, and the Java compiler doesn't do a lot to reason about bottom values. However, such values are there.</p>
<p>In summary,</p>
<ul>
<li>dereferencing a <code>null</code> value in Java is one specific expression that yields a bottom value in Java;</li>
<li>the <code>undefined</code> value in Haskell is a generic bottom-yielding expression that can be used anywhere a bottom value is required in Haskell.</li>
</ul>
<p>That's how they're similar.</p>
<p><strong>Postscript</strong></p>
<p>As to the question of <code>null</code> itself: why it is considered bad form?</p>
<ul>
<li>Firstly, Java's <code>null</code> is essentially equivalent to <strong>adding an implicit <code>Maybe a</code> to every type <code>a</code> in Haskell</strong>.</li>
<li>Dereferencing <code>null</code> is equivalent to pattern matching for only the <code>Just</code> case: <code>f (Just a) = ... a ...</code></li>
</ul>
<p>So when the value passed in is <code>Nothing</code> (in Haskell), or <code>null</code> (in Java), your program reaches an undefined state. This is bad: your program crashes.</p>
<p>So, by adding <code>null</code> to <em>every</em> type, you've just made it far easier to create <code>bottom</code> values by accident -- the types no longer help you. Your language is no longer helping you prevent that particular kind of error, and that's bad.</p>
<p>Of course, other bottom values are still there: exceptions (like <code>undefined</code>) , or infinite loops. Adding a new possible failure mode to every function -- dereferencing <code>null</code> -- just makes it easier to write programs that crash.</p> |
9,639,642 | How to round unix timestamp up and down to nearest half hour? | <p>Ok so I am working on a calendar application within my CRM system and I need to find the upper and lower bounds of the half an hour surrorunding the timestamp at which somebody entered an event in the calendar in order to run some SQL on the DB to determine if they already have something booked in within that timeslot. </p>
<p>For example I have the timestamp of 1330518155 = 29 February 2012 16:22:35 GMT+4
so I need to get 1330516800 and 1330518600 which equal 16:00 and 16:30. </p>
<p>If anyone has any ideas or think I am approaching developing the calendar in a stupid way let me know! Its my first time on such a task involving so much work with times and dates so any advice appreciated!</p> | 9,639,719 | 10 | 2 | null | 2012-03-09 19:09:20.907 UTC | 8 | 2018-11-12 18:31:23.567 UTC | null | null | null | null | 1,232,920 | null | 1 | 30 | php|datetime|unix-timestamp | 44,496 | <p>Use modulo.</p>
<pre><code>$prev = 1330518155 - (1330518155 % 1800);
$next = $prev + 1800;
</code></pre>
<p>The modulo operator gives the remainder part of division.</p> |
16,286,921 | How do I remove a specific bullet point within a ul in CSS? | <p>I have a simple list and all I want to do is remove a specific bullet point (just the icon, not the content within the li) within the <code>ul</code>.</p>
<p>I've used first-child to take away the first but I'd like to remove the sixth bullet point!</p>
<p>I could so it inline but I'd prefer to do it with CSS.</p>
<p>How can I do this?</p> | 16,286,954 | 2 | 3 | null | 2013-04-29 19:43:25.357 UTC | null | 2013-04-29 20:06:34.46 UTC | 2013-04-29 19:54:07.14 UTC | null | 2,333,483 | null | 2,333,483 | null | 1 | 26 | css | 65,418 | <p><a href="http://jsfiddle.net/5d4TU/"><strong>jsFiddle here.</strong></a></p>
<p>You can use the <a href="http://www.w3schools.com/cssref/sel_nth-child.asp"><strong>nth-child</strong></a> selector to achieve this.</p>
<hr>
<pre><code>li:nth-child(6) {
list-style-type: none;
}
</code></pre>
<hr>
<p><strong>Edit:</strong></p>
<p>It now seems you want to hide it for the last child, you can use the last-child selector instead:</p>
<p><a href="http://jsfiddle.net/5d4TU/2/"><strong>New jsFiddle here.</strong></a></p>
<pre><code>li:last-child {
list-style-type: none;
}
</code></pre>
<hr>
<p>If you'd like to get either of these working in IE6-8, you could use <a href="http://selectivizr.com/"><strong>Selectivizr</strong></a>.</p>
<blockquote>
<p>"Selectivizr is a JavaScript utility that emulates CSS3 pseudo-classes
and attribute selectors in Internet Explorer 6-8"</p>
</blockquote>
<p>nth-child and last-child are some of those supported selectors in Selectivizr.</p> |
16,179,293 | System.Web.Optimization and Microsoft.Web.Optimization won't load reference in vs 2012 | <p>I'm working on an MVC 4 project started in Visual Studio 2010. Right now I'm working on a machine with Visual Studio 2012 as I don't have access to the machine I was originally working on. I tried all morning to find answers, but they don't seem to help my situation.</p>
<p>I followed <a href="https://stackoverflow.com/questions/9475893/how-to-add-reference-to-system-web-optimization-for-mvc-3-converted-to-4-app">How to add reference to System.Web.Optimization for MVC-3-converted-to-4 app</a> and installed from nuget right into my solution. Even though I have all the required reference packages downloaded and installed on my machine, <code>System.Web.Optimization</code> continues to remain missing. Is there anything else I can do?</p>
<p>Edit: When I try to build the project I receive the following errors</p>
<ul>
<li>The type or namespace name 'Optimization' does not exist in the namespace 'System.Web' (are you missing an assembly reference?) - BundleConfig.cs</li>
<li>The type or namespace name 'Optimization' does not exist in the namespace 'System.Web' (are you missing an assembly reference?) - Global.asax.cs</li>
<li>The type or namespace 'BundleCollection' could not be found (are you missing a using directive or an assembly reference?) - BundleConfig.cs</li>
</ul>
<p>My BundleConfig.cs contains</p>
<pre><code>using System.Web;
using System.Web.Optimization;
namespace BCCDC_AdminTool
{
public class BundleConfig
{
// For more information on Bundling, visit http://go.microsoft.com/fwlink/? LinkId=254725
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include(
"~/Scripts/jquery-ui-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.unobtrusive*",
"~/Scripts/jquery.validate*"));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.css"));
bundles.Add(new StyleBundle("~/Content/themes/base/css").Include(
"~/Content/themes/base/jquery.ui.core.css",
"~/Content/themes/base/jquery.ui.resizable.css",
"~/Content/themes/base/jquery.ui.selectable.css",
"~/Content/themes/base/jquery.ui.accordion.css",
"~/Content/themes/base/jquery.ui.autocomplete.css",
"~/Content/themes/base/jquery.ui.button.css",
"~/Content/themes/base/jquery.ui.dialog.css",
"~/Content/themes/base/jquery.ui.slider.css",
"~/Content/themes/base/jquery.ui.tabs.css",
"~/Content/themes/base/jquery.ui.datepicker.css",
"~/Content/themes/base/jquery.ui.progressbar.css",
"~/Content/themes/base/jquery.ui.theme.css"));
}
}
}
</code></pre> | 16,179,825 | 12 | 2 | null | 2013-04-23 21:13:53.057 UTC | 5 | 2020-05-01 15:05:42.84 UTC | 2017-05-23 12:02:14.477 UTC | null | -1 | null | 1,721,849 | null | 1 | 34 | asp.net-mvc|asp.net-optimization | 69,631 | <p>This is a long shot but here it goes anyway, right click on the project --> Property Pages and make sure System.Web.Optimization entry exists. If not, copy the System.Web.Optimization.dll to your bin folder or import it as a reference.</p>
<p>Edit: mvc projects don't have the "Property pages" menu option.</p>
<p>One other thing you can try is create a new mvc4 basic project, go to the bin folder of the solution and copy the System.Web.Optimization.dll to the bin folder of your other project that is giving you the error. If you can't find the dll then try updating the nuget packages.</p> |
16,240,581 | How to get a Brush from a RGB Code? | <p>How can I get a <code>Brush</code> to set a Background of e.g. a <code>Grid</code> from a RGB Code.</p>
<p>I hace the RGB Code as a <code>int</code>:</p>
<pre><code>R = 12
B = 0
G = 255
</code></pre>
<p>I need to know how to convert it into a <code>Brush</code></p> | 16,240,625 | 1 | 1 | null | 2013-04-26 15:57:31.243 UTC | 6 | 2017-11-14 11:04:13.75 UTC | null | null | null | null | 437,242 | null | 1 | 47 | c#|windows-runtime | 66,665 | <pre><code>var brush = new SolidColorBrush(Color.FromArgb(255, (byte)R, (byte)G, (byte)B));
myGrid.Background = brush;
</code></pre> |
16,353,211 | Check if year is leap year in javascript | <pre><code> function leapYear(year){
var result;
year = parseInt(document.getElementById("isYear").value);
if (years/400){
result = true
}
else if(years/100){
result = false
}
else if(years/4){
result= true
}
else{
result= false
}
return result
}
</code></pre>
<p>This is what I have so far (the entry is on a from thus stored in "isYear"), I basically followed this <a href="http://en.wikipedia.org/wiki/Leap_year#Algorithm">here</a>, so using what I already have, how can I check if the entry is a leap year based on these conditions(note I may have done it wrong when implementing the pseudocode, please correct me if I have)
Edit: Note this needs to use an integer not a date function</p> | 16,353,241 | 7 | 3 | null | 2013-05-03 06:49:24.967 UTC | 16 | 2020-09-29 16:53:58.763 UTC | 2014-06-25 20:54:48.407 UTC | null | 2,246,344 | null | 2,342,934 | null | 1 | 91 | javascript|date|conditional-statements|date-arithmetic | 133,743 | <pre><code>function leapYear(year)
{
return ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
}
</code></pre> |
37,347,690 | How to replace div with another div in javascript? | <p>How to replace div with another div in javascript? </p>
<p>This is what I have:</p>
<pre><code><div id="main_place">
main
</div>
<button onclick="show(operation1)">Replace to operation 1</button>
<button onclick="show(operation2)">Replace to operation 2</button>
<button onclick="show(operation3)">Replace to operation 3</button>
<div id=operation1 style=“display:none”>
Some textboxes and text
</div>
<div id=operation2 style=“display:none”>
Again some textboxes and text
</div>
<div id=operation3 style=“display:none”>
And again some textboxes and text
</div>
<script>
function show(param_div_id){
document.getElementById('main_place').innerHTML = Here should be div from param;
}
</script>
</code></pre>
<p>Is it even possible to do it without jquery?</p> | 37,347,842 | 7 | 4 | null | 2016-05-20 13:14:40.223 UTC | 5 | 2021-11-28 22:00:55.61 UTC | null | null | null | null | 5,515,945 | null | 1 | 4 | javascript|html | 51,691 | <p>Pass strings into your method and get the other div</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="main_place">
main
</div>
<button onclick="show('operation1')">Replace to operation 1</button>
<button onclick="show('operation2')">Replace to operation 2</button>
<button onclick="show('operation3')">Replace to operation 3</button>
<div id=operation1 style=“display:none”>
Some textboxes and text
</div>
<div id=operation2 style=“display:none”>
Again some textboxes and text
</div>
<div id=operation3 style=“display:none”>
And again some textboxes and text
</div>
<script>
function show(param_div_id) {
document.getElementById('main_place').innerHTML = document.getElementById(param_div_id).innerHTML;
}
</script></code></pre>
</div>
</div>
</p> |
26,865,596 | No injectable field found in FXML Controller class | <p>It's about JavaFX. When i want to inject fx:id in Scene Builder, i get this warning: <br />No injectable field found in FXML Controller class for the id 'something'. <br />I wanted to ignore it, and created a function, but it didn't work either. I created mainController class and added it into my FXML file. Here are my codes...<br />
<br />mainController.java</p>
<pre><code>package main;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressBar;
import javafx.scene.control.Slider;
public class mainController implements Initializable {
@Override
public void initialize(URL arg0, ResourceBundle arg1) {
// TODO Auto-generated method stub
}
@FXML
private ProgressBar pb;
@FXML
private Slider sl;
@FXML
private Label label;
public void changed(ActionEvent event){
}
}
</code></pre>
<p><br />Main.java</p>
<pre><code>package main;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ProgressBar;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception{
Parent root = FXMLLoader.load(getClass().getResource("/fxml/main.fxml"));
Scene scene = new Scene(root, 600, 400);
scene.getStylesheets().add("/fxml/styles/main.css");
ProgressBar pb1 = new ProgressBar();
ProgressBar pb2 = new ProgressBar();
//pb1.
//primaryStage.setResizable(false);
primaryStage.setScene(scene);
primaryStage.setTitle("Something");
primaryStage.show();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
</code></pre>
<p><br />main.fxml</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<?import javafx.geometry.*?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<AnchorPane id="AnchorPane" prefHeight="400.0" prefWidth="600.0" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/8" fx:controller="main.mainController">
<children>
<BorderPane layoutX="14.0" layoutY="14.0" prefHeight="200.0" prefWidth="200.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
<top>
<ProgressBar fx:id="pb" prefWidth="200.0" progress="0.0" BorderPane.alignment="CENTER">
<BorderPane.margin>
<Insets bottom="30.0" left="30.0" right="30.0" top="30.0" />
</BorderPane.margin>
</ProgressBar>
</top>
<bottom>
<Slider fx:id="sl" onDragDetected="#changed" BorderPane.alignment="CENTER">
<BorderPane.margin>
<Insets bottom="30.0" left="30.0" right="30.0" top="30.0" />
</BorderPane.margin>
</Slider>
</bottom>
</BorderPane>
</children>
</AnchorPane>
</code></pre>
<p>I did same things in my old projects, and they work like a charm. But this one seems not to obey me. Thanks in advance...</p> | 26,867,348 | 2 | 2 | null | 2014-11-11 13:03:04.707 UTC | 3 | 2016-08-15 16:22:14.25 UTC | 2014-11-11 14:08:10.89 UTC | null | 3,497,814 | null | 3,497,814 | null | 1 | 6 | java|javafx|fxml|scenebuilder | 38,492 | <p>In Scene Builder, if the FXML file is associated to a controller class, you know that what makes the connection between the variable in the controller class (<code>pb</code>) and the object in the FXML file (<code><ProgressBar ... /></code>) is the value of the object's <code>fx:id</code>.</p>
<p>So when you set an <code>fx:id</code> on an object, Scene Builder tries to parse the controller class trying to find a variable of that name. </p>
<p>If it doesn't find any, it displays this warning. It's just a reminder that you may want to add such a variable to the controller class, or that you have to choose other valid name from a list.</p>
<p>Since you have <code>label</code> defined on your controller, if you try to add a <code>Label</code> on Scene Builder, you can get its <code>fx:id</code> from the list:</p>
<p><img src="https://i.stack.imgur.com/N5JD2.png" alt="Scene Builder"></p>
<p>But if you assing another name, you will get the warning:</p>
<p><img src="https://i.stack.imgur.com/RAb0L.png" alt="Scene Builder warning"></p>
<p>On a side note, you don't need to instantiate the progress bar on the main class, since it will be instantiated in the controller. And ìf you try to link <code>change(ActionEvent event)</code> to a method in Scene Builder (<code>#change</code>), you have to annotate it with <code>@FXML</code>. Anyway, don't use <code>onDragDetected</code> with the slider.</p> |
17,462,682 | Set element to unclickable and then to clickable | <p>I want to have a div element set to not be clickable and then set it to clickable after another element is clicked.</p>
<p>So, when .case is clicked:</p>
<pre><code>$('.case').click(function() {
$('#patient').addClass('active').on('click');
});
</code></pre>
<p>But how do I set #patient to unclickable in the first instance when I have further down:</p>
<pre><code>$('#patient').click(function() {
alert('clicked');
});
</code></pre> | 17,462,715 | 6 | 2 | null | 2013-07-04 05:45:09.287 UTC | 7 | 2017-09-20 01:48:47.76 UTC | null | null | null | null | 1,911,619 | null | 1 | 20 | jquery | 61,545 | <pre><code>$('#patient').on('click', function() {
if ( $(this).hasClass('active') ) {
// do whatever when it's active.
}
return false;
});
</code></pre>
<p>If you just want it to not accept, you can add this to your css (<a href="https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events" rel="noreferrer">pointer-events</a>):</p>
<pre class="lang-css prettyprint-override"><code>#patient { pointer-events: none; }
#patient.active { pointer-events: auto; }
</code></pre> |
17,336,943 | Removing non numeric characters from a string | <p>I have been given the task to remove all non numeric characters including spaces from a either text file or string and then print the new result next to the old characters for example:</p>
<p>Before:</p>
<pre><code>sd67637 8
</code></pre>
<p>After:</p>
<pre><code>676378
</code></pre>
<p>As i am a beginner i do not know where to start with this task. Please Help</p> | 17,337,613 | 8 | 2 | null | 2013-06-27 07:19:03.147 UTC | 7 | 2022-09-11 18:13:24.667 UTC | 2020-12-02 04:57:32.66 UTC | null | 3,691,003 | null | 1,840,618 | null | 1 | 61 | python|python-3.x|python-3.3 | 94,712 | <p>The easiest way is with a regexp</p>
<pre><code>import re
a = 'lkdfhisoe78347834 (())&/&745 '
result = re.sub('[^0-9]','', a)
print result
>>> '78347834745'
</code></pre> |
18,731,559 | Pass html string to server side with Jquery Ajax | <p>i have seen a lot of answers in this site that have helped me a lot but in this one i need to ask guys to help me out.</p>
<p>i have a textarea as a Html editor to pass html content to the server and append it to a newly created Html page( for user POST,etc), but jquery or ASP.NET does not accept the Html content passed by jquery through data: {}</p>
<p>--For Jquery: </p>
<pre><code> $("#btnC").click(function (e) {
e.preventDefault();
//get the content of the div box
var HTML = $("#t").val();
$.ajax({ url: "EditingTextarea.aspx/GetValue",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: '{num: "' + HTML + '"}', // pass that text to the server as a correct JSON String
success: function (msg) { alert(msg.d); },
error: function (type) { alert("ERROR!!" + type.responseText); }
});
</code></pre>
<p>and Server-Side ASP.NET:</p>
<pre><code>[WebMethod]
public static string GetValue(string num)
{
StreamWriter sw = new StreamWriter("C://HTMLTemplate1.html", true);
sw.WriteLine(num);
sw.Close();
return num;//return what was sent from the client to the client again
}//end get value
</code></pre>
<p>Jquery part gives me an error:
Invalid object passed in and error in
<code>System.Web.Script.Serialization.JavascriptObjectDeserializer.</code></p>
<p>It's like jquery doesnt accept string with html content.what is wrong with my code ?</p> | 18,733,994 | 3 | 2 | null | 2013-09-11 02:05:19.047 UTC | 1 | 2014-10-20 15:54:47.873 UTC | 2013-09-11 02:29:39.373 UTC | null | 1,404,239 | null | 2,766,936 | null | 1 | 6 | c#|jquery|asp.net|ajax | 39,333 | <p>Pass it like this</p>
<pre><code>JSON.stringify({'num':HTML});
</code></pre>
<p>You have to stringify the content to JSON properly. HTML may contain synataxes that would make the JSON notation invalid.</p>
<pre><code>var dataToSend = JSON.stringify({'num':HTML});
$.ajax({ url: "EditingTextarea.aspx/GetValue",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: dataToSend , // pass that text to the server as a correct JSON String
success: function (msg) { alert(msg.d); },
error: function (type) { alert("ERROR!!" + type.responseText); }
});
</code></pre> |
26,019,011 | Sql Server Operand type clash: date is incompatible with int | <p>When I try to execute this code I get an error at the 'with DateDimension' line:</p>
<blockquote>
<p>Msg 206, Level 16, State 2, Line 15<br>
Operand type clash: date is incompatible with int</p>
</blockquote>
<p>This is the SQL query I am using:</p>
<pre><code>declare @DateCalendarStart date,
@DateCalendarEnd date,
@FiscalCounter date,
@FiscalMonthOffset int;
set @DateCalendarStart = '2011-01-28';
set @DateCalendarEnd = '2012-10-26';
set @FiscalMonthOffset = 3;
with DateDimension //Error got this line
as
(
select @DateCalendarStart as DateCalendarValue,
dateadd(m, @FiscalMonthOffset, @DateCalendarStart) as FiscalCounter
union all
select DateCalendarValue + 1,
dateadd(m, @FiscalMonthOffset, (DateCalendarValue + 1)) as FiscalCounter
from DateDimension
where DateCalendarValue + 1 < = @DateCalendarEnd
)
</code></pre> | 26,019,251 | 1 | 3 | null | 2014-09-24 14:07:27.483 UTC | 1 | 2014-09-24 14:42:34.41 UTC | 2014-09-24 14:42:34.41 UTC | null | 13,302 | null | 3,890,722 | null | 1 | 2 | sql|sql-server | 38,937 | <p>Your problem is with the <code>DateCalendarValue + 1</code> portion. Try using <code>DATEADD()</code>, as below:</p>
<pre><code>declare @DateCalendarStart date,
@DateCalendarEnd date,
@FiscalCounter date,
@FiscalMonthOffset int;
set @DateCalendarStart = '2011-01-28';
set @DateCalendarEnd = '2012-10-26';
-- Set this to the number of months to add or extract to the current date to get the beginning
-- of the Fiscal Year. Example: If the Fiscal Year begins July 1, assign the value of 6
-- to the @FiscalMonthOffset variable. Negative values are also allowed, thus if your
-- 2012 Fiscal Year begins in July of 2011, assign a value of -6.
set @FiscalMonthOffset = 3;
with DateDimension
as
(
select @DateCalendarStart as DateCalendarValue,
dateadd(m, @FiscalMonthOffset, @DateCalendarStart) as FiscalCounter
union all
select DATEADD(DAY, 1, DateCalendarValue), -- Using a DATEADD() function here works for SQL Server
DATEADD(m, @FiscalMonthOffset, (DATEADD(DAY, 1, DateCalendarValue))) as FiscalCounter
from DateDimension
where DATEADD(DAY, 1, DateCalendarValue) < = @DateCalendarEnd
)
SELECT * FROM DateDimension OPTION (MAXRECURSION 1000)
</code></pre>
<p>EDIT: I don't know if your original code was going to use the <code>MAXRECURSION</code> option or not, but if you didn't know already I would recommend you <a href="http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=137696" rel="noreferrer">read this</a>. Basically, in this circumstance it means that you can list out 1,000 dates with the CTE. If you need more than that, you'll have to change that 1000 to match your needs. </p> |
9,272,535 | How to get a file via GitHub APIs | <p>I need to get the contents of a file hosted in a GitHub repo. I'd prefer to get a JSON response with metadata along with it. I've tried numerous URLs with cURL with to only get a response of <code>{"message":"Not Found"}</code>. I just need the URL structure. If it matters, it's from an organization on GitHub. Here's what I think should work but doesn't:</p>
<pre><code>http://api.github.com/repos/<organization>/<repository>/git/branches/<branch>/<file>
</code></pre> | 14,773,895 | 2 | 4 | null | 2012-02-14 06:15:25.75 UTC | 6 | 2021-11-27 15:56:34.86 UTC | null | null | null | null | 652,722 | null | 1 | 20 | api|github | 60,552 | <p>As the description (located at <a href="http://developer.github.com/v3/repos/contents/">http://developer.github.com/v3/repos/contents/</a>) says:</p>
<p>/repos/:owner/:repo/contents/:path</p>
<p>An ajax code will be:</p>
<pre><code>$.ajax({
url: readme_uri,
dataType: 'jsonp',
success: function(results)
{
var content = results.data.content;
});
</code></pre>
<p>Replace the readme_uri by the proper /repos/:owner/:repo/contents/:path.</p> |
9,031,023 | Filter Map by key set | <p>Is there a shortcut to filter a Map keeping only the entries where the key is contained in a given Set?</p>
<p>Here is some example code</p>
<pre><code>scala> val map = Map("1"->1, "2"->2, "3"->3)
map: scala.collection.immutable.Map[java.lang.String,Int] = Map(1 -> 1, 2 -> 2, 3 -> 3)
scala> map.filterKeys(Set("1","2").contains)
res0: scala.collection.immutable.Map[java.lang.String,Int] = Map(1 -> 1, 2 -> 2)
</code></pre>
<p>I am searching for something shorter than this.</p> | 9,031,524 | 3 | 4 | null | 2012-01-27 09:08:42.487 UTC | 8 | 2012-02-09 20:23:17.977 UTC | 2012-01-27 09:16:34.963 UTC | null | 252,552 | null | 252,552 | null | 1 | 29 | scala | 18,974 | <h2>Answering the Question</h2>
<p>You can take advantage of the fact that a <code>Set[A]</code> is a predicate; i.e. <code>A => Boolean</code></p>
<pre><code>map filterKeys set
</code></pre>
<p>Here it is at work:</p>
<pre><code>scala> val map = Map("1" -> 1, "2" -> 2, "3" -> 3)
map: scala.collection.immutable.Map[java.lang.String,Int] = Map(1 -> 1, 2 -> 2, 3 -> 3)
scala> val set = Set("1", "2")
set: scala.collection.immutable.Set[java.lang.String] = Set(1, 2)
scala> map filterKeys set
res0: scala.collection.immutable.Map[java.lang.String,Int] = Map(1 -> 1, 2 -> 2)
</code></pre>
<p>Or if you prefer:</p>
<pre><code>scala> map filterKeys Set("1", "2")
res1: scala.collection.immutable.Map[java.lang.String,Int] = Map(1 -> 1, 2 -> 2)
</code></pre>
<hr>
<h2>Predicates</h2>
<p>It's actually really useful to have some wrapper around a predicate. Like so:</p>
<pre><code>scala> class PredicateW[A](self: A => Boolean) {
| def and(other: A => Boolean): A => Boolean = a => self(a) && other(a)
| def or(other: A => Boolean): A => Boolean = a => self(a) || other(a)
| def unary_! : A => Boolean = a => !self(a)
| }
defined class PredicateW
</code></pre>
<p>And an implicit conversion:</p>
<pre><code>scala> implicit def Predicate_Is_PredicateW[A](p: A => Boolean) = new PredicateW(p)
Predicate_Is_PredicateW: [A](p: A => Boolean)PredicateW[A]
</code></pre>
<p>And then you can use it:</p>
<pre><code>scala> map filterKeys (Set("1", "2") and Set("2", "3"))
res2: scala.collection.immutable.Map[java.lang.String,Int] = Map(2 -> 2)
scala> map filterKeys (Set("1", "2") or Set("2", "3"))
res3: scala.collection.immutable.Map[java.lang.String,Int] = Map(1 -> 1, 2 -> 2, 3 -> 3)
scala> map filterKeys !Set("2", "3")
res4: scala.collection.immutable.Map[java.lang.String,Int] = Map(1 -> 1)
</code></pre>
<p>This can be extended to <code>xor</code>, <code>nand</code> etc etc and if you include symbolic unicode can make for amazingly readable code:</p>
<pre><code>val mustReport = trades filter (uncoveredShort ∨ exceedsDollarMax)
val european = {
val Europe = (_ : Market).exchange.country.region == Region.EU
trades filter (_.market ∈: Europe)
}
</code></pre> |
9,024,819 | free cloud data stores that use get/post? | <p>I know that there are other key/value stores similar to <a href="http://openkeyval.org">http://openkeyval.org</a> out there but i cannot remember their names. </p>
<p>Please enlighten me.</p>
<p>i need the following features:</p>
<ul>
<li>free</li>
<li>can be used via 100% clientside code</li>
<li>fast and easy to integrate with</li>
</ul>
<p><em>edit</em>:<br>
dropped the security requirement, since its not very important to me and was skewing the answers towards self-hosted solutions. </p>
<p>found another service:<br>
<a href="http://rastajs.errorjs.com/">http://rastajs.errorjs.com/</a></p>
<p>this one is easy to use but seems to mangle my values by removing all the spaces!</p> | 30,934,715 | 5 | 5 | null | 2012-01-26 20:25:33.067 UTC | 14 | 2015-08-04 20:15:13.05 UTC | 2012-02-08 20:38:29.217 UTC | null | 26,188 | null | 26,188 | null | 1 | 36 | javascript|hashmap|cloud | 20,095 | <p>I needed something like that, so I've built this: <a href="http://www.kvstore.io" rel="noreferrer">KVStore.io, a simple key/value API based storage service</a></p>
<p>It's still under heavy development (it's an alpha version...) but I'm using it to store some stuffs (like website marketing forms) and it's working nicely...</p> |
18,376,416 | The target ... overrides the `OTHER_LDFLAGS` build setting defined in `Pods/Pods.xcconfig | <p>I have incorporate <code>SpatialIite</code> into a Xcode project which uses a header file from <code>Proj.4</code>, just one header. Both are Xcode projects and have static targets.</p>
<p>I'm trying to migrate from git submodule to Cocoapods. Since static targets seems to be difficult to use with Cocoapods, I just want to have the project built in the usual way. I made podspec for <code>Proj.4</code>. After writing podfile for <code>SpatialLite</code> I got the warnings:</p>
<pre><code>[!] The target `SpatialiteIOS [Debug]` overrides the `OTHER_LDFLAGS` build setting defined in `Pods/Pods.xcconfig'.
- Use the `$(inherited)` flag, or
- Remove the build settings from the target.
[!] The target `SpatialiteIOS [Debug]` overrides the `HEADER_SEARCH_PATHS` build setting defined in `Pods/Pods.xcconfig'.
- Use the `$(inherited)` flag, or
- Remove the build settings from the target.
[!] The target `SpatialiteIOS [Debug - Release]` overrides the `OTHER_LDFLAGS` build setting defined in `Pods/Pods.xcconfig'.
- Use the `$(inherited)` flag, or
- Remove the build settings from the target.
[!] The target `SpatialiteIOS [Debug - Release]` overrides the `HEADER_SEARCH_PATHS` build setting defined in `Pods/Pods.xcconfig'.
- Use the `$(inherited)` flag, or
- Remove the build settings from the target.
</code></pre>
<p>I read <a href="https://github.com/CocoaPods/CocoaPods/issues/1125">this issue</a> but I'm pretty clueless to what the warnings mean and what can I do to fix it.</p>
<p>Additionally problem, when I open the workspace as well as opening SpatiaLite project alone, both are targeted to Mac OSX 64, when it is suppose to be an iOS project. My podfile does say "platform :ios".</p> | 26,077,106 | 12 | 1 | null | 2013-08-22 09:22:45.103 UTC | 72 | 2021-12-18 17:11:17.277 UTC | 2016-12-06 06:30:09.54 UTC | null | 3,909,115 | null | 133,747 | null | 1 | 250 | xcode|cocoapods | 146,277 | <p>This definitely works most of the time:</p>
<p>Go to your target Build Settings -> Other linker flags -> double click . Add <code>$(inherited)</code> to a new line.</p>
<p>If you have problem with "...target overrides the GCC_PREPROCESSOR_DEFINITIONS build setting defined in..." then you must add $(inherited) to your target Build Settings -> Preprocessor Macros</p> |
15,234,959 | Cross-compiling for ARM with Autoconf | <p>I am having trouble cross-compiling a library for my arm board using autconf.</p>
<p>I am using this line:</p>
<pre><code>./configure --target=arm-linux --host=arm-linux --prefix=/bla/bla/bla/linux_arm_tool CFLAGS='-m32'
make
make install
</code></pre>
<p>When I do <code>file</code> to check it I get:</p>
<pre><code>libjpeg.so.8.4.0: ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV), dynamically linked, not stripped
</code></pre>
<p>That doesn't seem right at all, but I tried using it anyway... and I get:</p>
<pre><code>/usr/lib/gcc/arm-linux-gnueabi/4.5.3/../../../../arm-linux-gnueabi/bin/ld: skipping incompatible /bla/bla/bla/bla/../linux_arm_tool/lib/libjpeg.so when searching for -ljpeg
</code></pre>
<p>I'm at a loss, I've been googling for an hour now...</p> | 15,235,752 | 4 | 0 | null | 2013-03-05 21:58:29.753 UTC | 6 | 2018-10-11 02:17:22.427 UTC | 2018-10-08 12:24:12.167 UTC | null | 608,639 | null | 1,070,108 | null | 1 | 16 | c|cross-compiling|autoconf | 54,774 | <p>So I knew I've cross compiled before using really basic method calls and I figured out why I've gotten away with this before after examining the output:</p>
<pre><code>checking for arm-linux-gnueabi-gcc... no
checking for gcc... gcc
...
...
checking for arm-linux-gnueabi-gcc... gcc
</code></pre>
<p>In my <code>/usr/bin</code> there was no <code>arm-linux-gnueabi-gcc</code>, I had to:</p>
<pre><code>ln -s /usr/bin/arm-linux-gnueabi-gcc-4.5 /usr/bin/arm-linux-gnueabi-gcc
</code></pre>
<hr>
<p>I successfully cross-compiled using:</p>
<pre><code>./configure --host=arm-linux-gnueabi -prefix=${CSTOOL_DIR}/linux_arm_tool
</code></pre>
<p>as for linking ... I still have to check some things, but I am going to assume I might need to throw some <code>-rpath-link</code> flags in more advanced compiles.</p> |
14,922,130 | Which error message is better when users entered a wrong password? | <p>Is there any differences between the following two error messages from security point of view when users entered a wrong password?</p>
<blockquote>
<p>Wrong username or password.</p>
<p>Wrong password.</p>
</blockquote>
<p>For example, when you enter a wrong password on the <code>Gmail.com</code>, it will tell you "The username or password you entered is incorrect".</p>
<p>Is there any considerations for security reasons? I think the error message: "The password you entered is incorrect" is more clear to users, And, What's more, it's very easy to check whether a username is exists on the <code>Gmail.com</code>: just click "Can't access your account?" and enter the username. If the username doesn't exists, it will tell you.</p> | 14,922,163 | 5 | 2 | null | 2013-02-17 14:30:25.82 UTC | 1 | 2022-07-27 02:50:06.61 UTC | 2021-02-17 22:29:57.62 UTC | null | 4,539,709 | null | 1,109,791 | null | 1 | 26 | security|authentication|passwords | 72,455 | <p>The idea is to not give hackers extra information. If you say wrong password, you've told a hacker that they have a correct username, and vice-versa. Although what you've said is true, on some sites it is possible to determine if you've guessed a username via other means. </p> |
7,762,838 | Forward References - why does this code compile? | <p>Consider this snippet:</p>
<pre><code> object A {
val b = c
val c = "foo"
}
println( A.b ) // prints "null"
</code></pre>
<p>As part of a larger program, this would lead to a failure at runtime. The compiler apparently permits the forward reference from 'b' to (uninitialized) 'c' but 'b' is left with c's original null value. Why is this permitted? Are there programming scenarios that would benefit from this feature? </p>
<p>Change the code to a straight sequence and the behavior changes: </p>
<pre><code> val b = c
val c = "foo"
println( b ) // prints "foo"
</code></pre>
<p>Why is the behavior different? And why does this even work? Thanks.</p>
<p><strong>Update 1:</strong></p>
<p>The question came up how I ran the second example. I simplified the setup a bit and compiled it using Scala 2.9.0.1 inside IntelliJ IDEA 10.5.2 with the latest Scala plugin. Here is the exact code, in a freshly created and otherwise empty project, which I am using to test this, which compiles and runs fine in this environment:</p>
<pre><code> package test
object Main {
def main( args: Array[String] ) {
val b = c
val c = "foo"
println( b ) // prints "foo"
}
}
</code></pre>
<p>For what it's worth, IDEA also thinks (when I click "through" the reference to 'c' in val b = c) that I am referring to the (later) declaration of 'c'. </p> | 7,763,041 | 2 | 4 | null | 2011-10-14 03:49:39.93 UTC | 8 | 2018-05-22 08:38:35.76 UTC | 2013-06-13 17:21:35.787 UTC | null | 442,945 | null | 820,380 | null | 1 | 31 | scala|initialization|lazy-evaluation | 5,854 | <p>The body of a class or an object is the primary constructor. A constructor, like a method, is a sequence of statements that are executed in order -- to do anything else, it would have to be a very different language. I'm pretty sure you wouldn't like for Scala to execute the statements of your methods in any other order than sequential.</p>
<p>The problem here is that the body of classes and objects are also the declaration of members, and this is the source of your confusion. You see <code>val</code> declarations as being precisely that: a declarative form of programming, like a Prolog program or an XML configuration file. But they are really two things:</p>
<pre><code>// This is the declarative part
object A {
val b
val c
}
// This is the constructor part
object A {
b = c
c = "foo"
}
</code></pre>
<p>Another part of your problem is that your example is very simple. It is a special case in which a certain behavior seems to make sense. But consider something like:</p>
<pre><code>abstract class A {
def c: String
}
class B extends A {
val b = c
override val c = "foo"
}
class C extends { override val c = "foobar" } with B
val x = new C
println(x.b)
println(x.c)
</code></pre>
<p>What do you expect to happen? The semantics of constructor execution guarantees two things:</p>
<ol>
<li>Predictability. You might find it non-intuitive at first, but the rules are clear and relatively easy to follow.</li>
<li>Subclasses can depend on superclasses having initialized themselves (and, therefore, its methods being available).</li>
</ol>
<p><strong>Output:</strong></p>
<p>it will print "foobar" twice for more => <a href="https://docs.scala-lang.org/tutorials/FAQ/initialization-order.html" rel="nofollow noreferrer">https://docs.scala-lang.org/tutorials/FAQ/initialization-order.html</a></p> |
66,734,015 | LateInitializationError: Field '_userData@32329253' has not been initialized | <p>Getting this when trying to initialize data.</p>
<blockquote>
<p>The following LateError was thrown building UserProfile(dirty, state: _UserProfileState#752a9):
LateInitializationError: Field '_userData@32329253' has not been initialized."</p>
</blockquote>
<p>Here's the code:</p>
<pre><code> late final User _user;
late final DocumentSnapshot _userData;
@override
void initState() {
super.initState();
_initUser();
}
void _initUser() async {
_user = FirebaseAuth.instance.currentUser!;
try {
_userData = await FirebaseFirestore.instance
.collection('users')
.doc(_user.uid)
.get();
} catch (e) {
print("something went wrong");
}
}
</code></pre>
<p>The build function is not even running as i tried to print _user and _userData to check if they have been initialized.<br>
If i try to print _user and _userData in initUser() function, _user gets printed and _userData gets printed after the error statements. <br>
Please help me find a way out through this error.</p> | 66,734,486 | 3 | 5 | null | 2021-03-21 15:13:57.627 UTC | 2 | 2022-01-25 08:41:56.597 UTC | 2021-03-21 17:40:18.99 UTC | null | 7,015,400 | null | 14,416,421 | null | 1 | 25 | firebase|flutter|dart|google-cloud-firestore | 57,922 | <p>Even though you are initializing these variables inside the <code>initUser()</code>, but you will get this error if you are using the variables inside the <code>build()</code> method since <code>initUser()</code> is asynchronous meaning it will take time to get the data from the collection. To solve this you can do:</p>
<pre><code>@override
void initState() {
super.initState();
_initUser().whenComplete((){
setState(() {});
});
}
</code></pre>
<p>This will rebuild the widget tree with the new values.</p> |
8,824,831 | Make div stay at bottom of page's content all the time even when there are scrollbars | <p><a href="https://stackoverflow.com/questions/2140763/css-push-div-to-bottom-of-page">CSS Push Div to bottom of page</a></p>
<p>Please look at that link, I want the opposite: When the content overflows to the scrollbars, I want my footer to be always at the <strong>complete</strong> bottom of the page, like Stack Overflow.</p>
<p>I have a div with <code>id="footer"</code> and this CSS:</p>
<pre><code>#footer {
position: absolute;
bottom: 30px;
width: 100%;
}
</code></pre>
<p>But all it does is go to the bottom of the viewport, and stays there even if you scroll down, so it is no longer at the bottom.</p>
<p>Image: <img src="https://i.stack.imgur.com/ahmtx.png" alt="Examlple"></p>
<p>Sorry if not clarified, I don't want it to be fixed, only for it to be at the actual bottom of all the content.</p> | 8,824,859 | 12 | 3 | null | 2012-01-11 18:43:22.863 UTC | 114 | 2020-08-07 04:26:50.657 UTC | 2017-05-23 12:34:45.403 UTC | null | -1 | null | 1,020,773 | null | 1 | 313 | css|positioning|css-position|footer | 835,051 | <p>This is precisely what <code>position: fixed</code> was designed for:</p>
<pre class="lang-css prettyprint-override"><code>#footer {
position: fixed;
bottom: 0;
width: 100%;
}
</code></pre>
<p>Here's the fiddle: <a href="http://jsfiddle.net/uw8f9/">http://jsfiddle.net/uw8f9/</a></p> |
8,378,338 | What does Connect.js methodOverride do? | <p>The Connect.js <a href="http://www.senchalabs.org/connect/methodOverride.html">very terse documentation</a> says <code>methodOverride</code></p>
<blockquote>
<p>Provides faux HTTP method support.</p>
</blockquote>
<p>What does that mean? The <a href="http://www.google.co.uk/#sclient=psy-ab&hl=en&source=hp&q=faux+HTTP&pbx=1&oq=faux+HTTP&aq=f&aqi=&aql=&gs_sm=e&gs_upl=854l2146l0l2389l9l7l0l0l0l0l401l1403l1.3.1.1.1l7l0&bav=on.2,or.r_gc.r_pw.r_cp.,cf.osb&fp=6f7dcc85a1201a75&biw=1181&bih=698">obvious Google search</a> is less than helpful. Why is <code>methodOverride</code> useful?</p> | 8,378,414 | 1 | 3 | null | 2011-12-04 20:23:57.16 UTC | 37 | 2014-12-14 16:15:28.37 UTC | 2014-12-14 16:15:28.37 UTC | null | 1,779,688 | null | 707,381 | null | 1 | 116 | node.js|connect.js | 22,939 | <ul>
<li>If you want to simulate <code>DELETE</code> and <code>PUT</code>, <code>methodOverride</code> is for that.</li>
<li>If you pass in the _method post parameter set to <em>'delete'</em> or <em>'put'</em>, then you can use <code>app.delete</code> and <code>app.put</code> in Express instead of using <code>app.post</code> all the time (thus more descriptive, verbose):</li>
</ul>
<p><strong>Backend:</strong></p>
<pre><code>// the app
app.put('/users/:id', function (req, res, next) {
// edit your user here
});
</code></pre>
<p><strong>Client logic:</strong></p>
<pre><code>// client side must be..
<form> ...
<input type="hidden" name="_method" value="put" />
</form>
</code></pre> |
5,437,335 | Django Queryset with filtering on reverse foreign key | <p>I have the following Django model:</p>
<pre><code>class Make:
name = models.CharField(max_length=200)
class MakeContent:
make = models.ForeignKey(Make)
published = models.BooleanField()
</code></pre>
<p>I'd like to know if it's possible (without writing SQL directly) for me to generate a queryset that contains all <code>Make</code>s and each one's related <code>MakeContent</code>s where <code>published = True</code>.</p> | 5,437,609 | 5 | 1 | null | 2011-03-25 19:40:58.407 UTC | 28 | 2020-01-28 19:21:27.947 UTC | 2016-05-23 20:30:44.96 UTC | null | 895,245 | null | 369,722 | null | 1 | 86 | django|model|filter|django-queryset | 74,744 | <p>Django doesn't support the <code>select_related()</code> method for reverse foreign key lookups, so the best you can do without leaving Python is two database queries. The first is to grab all the <code>Makes</code> that contain <code>MakeContents</code> where <code>published = True</code>, and the second is to grab all the <code>MakeContents</code> where <code>published = True</code>. You then have to loop through and arrange the data how you want it. Here's a good article about how to do this:</p>
<p><a href="http://blog.roseman.org.uk/2010/01/11/django-patterns-part-2-efficient-reverse-lookups/" rel="noreferrer">http://blog.roseman.org.uk/2010/01/11/django-patterns-part-2-efficient-reverse-lookups/</a></p> |
5,188,224 | "throw new Warning" in JavaScript? | <p>At the moment I'm extending my JavaScript project with error handling. The <code>throw</code> statement is playing an important role here:</p>
<pre><code>throw new Error("text"); // Error: text
</code></pre>
<p>However, can I also throw a warning? I tried the following to no avail:</p>
<pre><code>throw new Warning("text"); // Warning is not defined
</code></pre>
<p>The errors make Chrome's Developer Tools show a red cross, but how can I make it display a warning icon (yellow exclamation mark)?</p> | 5,188,244 | 6 | 0 | null | 2011-03-04 00:09:49.377 UTC | 6 | 2019-03-14 21:23:04.723 UTC | 2012-01-30 16:12:25.203 UTC | null | 514,749 | null | 514,749 | null | 1 | 63 | javascript|error-handling|throw | 37,928 | <p>Like this:</p>
<pre><code>console.warn('Hi!');
</code></pre>
<p>Note that unlike exceptions, this will not interrupt your code; the calling function will continue normally.</p>
<p>Also note that this will throw an error in any browser except for WebKits or Firefox with Firebug, because <code>console</code> won't exist.</p>
<p>To fix that, you can include <a href="http://getfirebug.com/firebuglite" rel="noreferrer">Firebug Lite</a>, or make a fake NOP-ing <code>console</code> object.</p> |
4,941,288 | How can I get the executing assembly version? | <p>I am trying to get the executing assembly version in C# 3.0 using the following code:</p>
<pre><code>var assemblyFullName = Assembly.GetExecutingAssembly().FullName;
var version = assemblyFullName .Split(',')[1].Split('=')[1];
</code></pre>
<p>Is there another proper way of doing so?</p> | 4,941,305 | 6 | 0 | null | 2011-02-09 04:23:02.667 UTC | 24 | 2019-06-06 20:13:31.257 UTC | 2015-07-19 11:56:26.283 UTC | null | 63,550 | null | 609,182 | null | 1 | 201 | c#|.net|.net-assembly | 156,150 | <p>Two options... regardless of application type you can always invoke:</p>
<pre><code>Assembly.GetExecutingAssembly().GetName().Version
</code></pre>
<p>If a <a href="http://en.wikipedia.org/wiki/Windows_Forms">Windows Forms</a> application, you can always access via application if looking specifically for product version.</p>
<pre><code>Application.ProductVersion
</code></pre>
<p>Using <code>GetExecutingAssembly</code> for an assembly reference is not always an option. As such, I personally find it useful to create a static helper class in projects where I may need to reference the underlying assembly or assembly version:</p>
<pre><code>// A sample assembly reference class that would exist in the `Core` project.
public static class CoreAssembly
{
public static readonly Assembly Reference = typeof(CoreAssembly).Assembly;
public static readonly Version Version = Reference.GetName().Version;
}
</code></pre>
<p>Then I can cleanly reference <code>CoreAssembly.Version</code> in my code as required.</p> |
4,890,915 | Is there a Task based replacement for System.Threading.Timer? | <p>I'm new to .Net 4.0's Tasks and I wasn't able to find what I thought would be a Task based replacement or implementation of a Timer, e.g. a periodic Task. Is there such a thing?</p>
<p><em><strong>Update</em></strong>
I came up with what I think is a solution to my needs which is to wrap the "Timer" functionality inside a Task with child Tasks all taking advantage of the CancellationToken and returns the Task to be able to participate in further Task steps. </p>
<pre><code>public static Task StartPeriodicTask(Action action, int intervalInMilliseconds, int delayInMilliseconds, CancellationToken cancelToken)
{
Action wrapperAction = () =>
{
if (cancelToken.IsCancellationRequested) { return; }
action();
};
Action mainAction = () =>
{
TaskCreationOptions attachedToParent = TaskCreationOptions.AttachedToParent;
if (cancelToken.IsCancellationRequested) { return; }
if (delayInMilliseconds > 0)
Thread.Sleep(delayInMilliseconds);
while (true)
{
if (cancelToken.IsCancellationRequested) { break; }
Task.Factory.StartNew(wrapperAction, cancelToken, attachedToParent, TaskScheduler.Current);
if (cancelToken.IsCancellationRequested || intervalInMilliseconds == Timeout.Infinite) { break; }
Thread.Sleep(intervalInMilliseconds);
}
};
return Task.Factory.StartNew(mainAction, cancelToken);
}
</code></pre> | 23,814,733 | 7 | 1 | null | 2011-02-03 19:48:22.613 UTC | 56 | 2021-05-03 02:58:29.62 UTC | 2013-05-06 15:29:14.673 UTC | null | 200,449 | null | 222,434 | null | 1 | 99 | c#|.net-4.0|timer|timeout|task-parallel-library | 76,490 | <p>It depends on 4.5, but this works. </p>
<pre><code>public class PeriodicTask
{
public static async Task Run(Action action, TimeSpan period, CancellationToken cancellationToken)
{
while(!cancellationToken.IsCancellationRequested)
{
await Task.Delay(period, cancellationToken);
if (!cancellationToken.IsCancellationRequested)
action();
}
}
public static Task Run(Action action, TimeSpan period)
{
return Run(action, period, CancellationToken.None);
}
}
</code></pre>
<p>Obviously you could add a generic version that takes arguments as well. This is actually similar to other suggested approaches since under the hood Task.Delay is using a timer expiration as a task completion source.</p> |
16,784,460 | PrimeFaces p:selectOneMenu width | <p>I want <code>p:selectOneMenu</code> width to be auto regarding to the parent cell not regarding to the values it has.</p>
<pre><code><p:panelGrid>
<p:row>
<p:column><p:outputLabel value="Value01" for="idInput01"/></p:column>
<p:column><p:inputText value="#{bean.input01}" id="idInput01" /></p:column>
<p:column><p:outputLabel value="Value02" for="idSelect" /></p:column>
<p:column>
<p:selectOneMenu value="#{bean.selectedObject}" id="idSelect" converter="objectConverter">
<f:selectItems value="#{bean.objectsList}" var="varObject" itemLabel="#{varObject.label}" itemValue="#{varObject}" />
</p:selectOneMenu>
</p:column>
</p:row>
</p:panelGrid>
</code></pre>
<p><strong>What I've got :</strong></p>
<p><img src="https://i.stack.imgur.com/pOYSb.png" alt="enter image description here"></p>
<p><strong>What I'm expecting :</strong></p>
<p><img src="https://i.stack.imgur.com/7WV7e.png" alt="enter image description here"></p>
<p><strong>Note: I don't want to specify a fixed width.</strong></p> | 16,807,465 | 9 | 1 | null | 2013-05-28 05:26:44.767 UTC | 2 | 2018-06-19 04:16:39.067 UTC | 2013-05-29 09:01:06.487 UTC | null | 354,831 | null | 248,222 | null | 1 | 8 | css|jsf-2|primefaces | 52,748 | <p><strong>i overrode</strong> <code>.ui-selectonemenu, .ui-selectonemenu-label</code> to:</p>
<pre><code>.ui-selectonemenu{
width: 100% !important;
}
.ui-selectonemenu-label{
width: 100% !important;
}
</code></pre> |
12,109,642 | Loading .NET UserControls in IE with .NET 4.5 | <p>There is a similar question: <a href="https://stackoverflow.com/questions/3334664/loading-net-usercontrols-in-ie-with-net-4-0">Loading .NET UserControls in IE with .NET 4.0</a> This question is essentially the same, but for <strong>.NET 4.5</strong></p>
<p>That question starts with:
<i>I've got a legacy app where there's a UserControl which is used as an activex in a web page loaded in IE. Before .NET 4.0, there were security policies and a MMC console for creating code groups, etc. It seems like that is all gone with .NET 4.0.</i></p>
<p>After installing .NET 4.5 it seems the workaround is no longer working, and that IE is unable to load <strong>any</strong> usercontrol. My fear is that this feature is removed altogether. In that case we have some serious rewriting to do before our users can install .NET 4.5</p>
<p>Some notes:
<li>Everything was working perfectly fine with the .NET 4.5 RC. 8-(</li>
<li>Fuslogvw (Assembly Binding Log Viewer) Behaves as expected before upgrade, but after upgrade it is not logging anything. (And usercontrol is not being loaded.)</li>
<li>In production the controll will have to run with full trust, but all my testing has been done with a simple control that does not require this</li>
</p>
<p>Anybody who has sugestions or information regarding this feature?</p>
<p>thanks</p> | 12,119,796 | 1 | 1 | null | 2012-08-24 12:44:24.91 UTC | 14 | 2014-03-10 23:10:43.837 UTC | 2017-05-23 12:19:20.7 UTC | null | -1 | null | 111,182 | null | 1 | 16 | internet-explorer|user-controls|.net-4.5 | 17,005 | <p>This is documented in the .NET 4.5 Application Compatibility Page on MSDN:
<a href="http://msdn.microsoft.com/en-us/library/hh367887.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/hh367887.aspx</a> . Hosting managed controls inside IE is no longer supported out of the box (see half-way down under "Web Applications"): </p>
<blockquote>
<p>Feature:
Managed browser hosting controls from the .NET Framework 1.1 and 2.0</p>
<p>Change:
Hosting these controls is blocked in Internet Explorer. </p>
<p>Impact:
Internet Explorer will fail to launch an application that uses managed browser hosting controls. The previous behavior can be restored by setting the EnableLegacyIEHosting value of the registry subkey HKLM/SOFTWARE/MICROSOFT/.NETFramework to 1. </p>
</blockquote>
<p>Unfortunately, the information on the registry key appears to be incomplete and wrong:</p>
<ul>
<li><p>The setting is actually called "EnableIEHosting".</p></li>
<li><p>It must be located either in the HKCU Hive: HKCU\SOFTWARE\Microsoft\.NETFramework</p></li>
<li>or the HKLM hive, but under different paths, depending on the 32/64bit type of Windows:
<ul>
<li>32-bit System: HKLM\SOFTWARE\MICROSOFT\.NETFramework </li>
<li>64-bit System: HKLM\SOFTWARE\Wow6432Node\Microsoft\.NETFramework</li>
</ul></li>
</ul>
<p>This was tested on both Windows Server 2008R2 and Windows 8.</p> |
12,460,712 | Convert LPWSTR to string | <p>Function <code>CommandLineToArgvW</code> is giving me commandline arguments in <code>LPWSTR</code> type. I need these arguments in <code>string</code>.
Would someone please tell me how to convert <code>LPWSTR</code> to <code>string</code>?<br>
I'm using mingw.</p> | 12,460,812 | 4 | 1 | null | 2012-09-17 13:51:29.08 UTC | 4 | 2022-07-30 17:33:52.167 UTC | 2012-09-17 13:55:19.217 UTC | null | 238,902 | null | 1,677,734 | null | 1 | 23 | c++|winapi|mingw | 46,515 | <p>Try to use following API functions :</p>
<ol>
<li><p><a href="http://msdn.microsoft.com/en-us/library/windows/desktop/dd374130%28v=vs.85%29.aspx" rel="nofollow noreferrer">WideCharToMultiByte</a> </p></li>
<li><p><a href="http://msdn.microsoft.com/en-us/library/5d7tc9zw%28v=vs.71%29.aspx" rel="nofollow noreferrer">wcstombs</a> </p></li>
</ol>
<p>And comparision of both methods <a href="https://stackoverflow.com/questions/5620831/widechartomultibyte-vs-wcstombs">WideCharToMultiByte() vs. wcstombs()</a></p> |
12,167,654 | Fastest way to compute k largest eigenvalues and corresponding eigenvectors with numpy | <p>I have a large NxN dense symmetric matrix and want the eigenvectors corresponding to the k largest eigenvalues. What's the best way to find them (preferably using numpy but perhaps in general using blas/atlas/lapack if that's the only way to go)? In general N is much much larger then k (say N > 5000, k < 10).</p>
<p>Numpy seems to only have functions for finding the k largest eigenvalues if my starting matrix is sparse.</p> | 12,168,664 | 2 | 0 | null | 2012-08-28 21:16:18.98 UTC | 11 | 2012-08-31 10:10:28.657 UTC | null | null | null | null | 589,624 | null | 1 | 24 | python|numpy|scipy|linear-algebra | 38,165 | <p>In SciPy, you can use the <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.eigh.html">linalg.eigh</a> function, with the <code>eigvals</code> parameter.</p>
<blockquote>
<p>eigvals : tuple (lo, hi) Indexes of the smallest and largest (in
ascending order) eigenvalues and corresponding eigenvectors to be
returned: 0 <= lo < hi <= M-1. If omitted, all eigenvalues and
eigenvectors are returned.</p>
</blockquote>
<p>Which in your case should be set to <code>(N-k,N-1)</code>.</p> |
12,501,231 | What is the difference between $.proxy() and bind()? | <p>In 2009, ECMAScript 5 added a built-in <code>bind()</code> function which takes an object as a parameter and returns an identical function in which <code>this</code> will always refer to the object you passed it. (I couldn't find anything that looked like a canonical documentation link.)</p>
<p>How is this different from <a href="http://api.jquery.com/jQuery.proxy/">jQuery's <code>$.proxy()</code> function</a>? Did <code>$.proxy()</code> come first before ECMAScript 5 was released? Is there a particular reason to favor <code>$.proxy(function(){}, this)</code> over <code>function(){}.bind(this)</code>?</p> | 12,501,276 | 5 | 0 | null | 2012-09-19 19:05:17.027 UTC | 6 | 2015-05-19 17:16:40.903 UTC | 2014-01-15 14:41:15.137 UTC | null | 1,588,642 | null | 16,034 | null | 1 | 30 | javascript|jquery|scope|closures|bind | 16,259 | <p><code>proxy</code> came first and you should likely favor <code>bind</code> as it is a standard. The way they are called varies slightly (due to being attached to <code>Function.prototype</code> vs just being a function) but their behavior is the same.</p>
<p>There is a pretty good post here: <a href="https://stackoverflow.com/questions/3349380/jquery-proxy-usage">jQuery.proxy() usage</a>, that ends with that advice.</p> |
12,593,576 | Adapt an iterator to behave like a file-like object in Python | <p>I have a generator producing a list of strings. Is there a utility/adapter in Python that could make it look like a file?</p>
<p>For example,</p>
<pre><code>>>> def str_fn():
... for c in 'a', 'b', 'c':
... yield c * 3
...
>>> for s in str_fn():
... print s
...
aaa
bbb
ccc
>>> stream = some_magic_adaptor(str_fn())
>>> while True:
... data = stream.read(4)
... if not data:
... break
... print data
aaab
bbcc
c
</code></pre>
<p>Because data may be big and needs to be streamable (each fragment is a few kilobytes, the entire stream is tens of megabytes), I do not want to eagerly evaluate the whole generator before passing it to stream adaptor.</p> | 12,593,795 | 8 | 0 | null | 2012-09-26 02:04:12.4 UTC | 13 | 2022-09-24 10:36:37.07 UTC | 2012-09-26 02:29:15.113 UTC | null | 23,643 | null | 23,643 | null | 1 | 32 | python | 13,171 | <p>Here's a solution that should read from your iterator in chunks.</p>
<pre><code>class some_magic_adaptor:
def __init__( self, it ):
self.it = it
self.next_chunk = ""
def growChunk( self ):
self.next_chunk = self.next_chunk + self.it.next()
def read( self, n ):
if self.next_chunk == None:
return None
try:
while len(self.next_chunk)<n:
self.growChunk()
rv = self.next_chunk[:n]
self.next_chunk = self.next_chunk[n:]
return rv
except StopIteration:
rv = self.next_chunk
self.next_chunk = None
return rv
def str_fn():
for c in 'a', 'b', 'c':
yield c * 3
ff = some_magic_adaptor( str_fn() )
while True:
data = ff.read(4)
if not data:
break
print data
</code></pre> |
12,089,655 | Oracle client installation error - path too long | <p>I'm trying to install Oracle 11g Release 2 (client). But it gives an error like that :</p>
<pre><code>Environment variable: "PATH" - This test checks whether the length of the
environment variable "PATH" does not exceed the recommended length.
Expected Value: 1023
Actual Value : 1028
List of errors: - PRVF-3929 : Adding the Oracle binary location to the PATH
environment variable will exceed the OS length limit of [ "1023" ] for the
variable on the node "KamalNuriyev-PC" -
Cause: The installer needs to update the PATH environment variable to
include the value "%ORACLE_HOME%/bin;". However, doing so will
cause PATH to exceed the maximum allowable length that this
operating system allows. - Action: Ensure that the sum of the
lengths of your current PATH environment variable and that of
"%ORACLE_HOME%/bin;" does not exceed the operating system limit.
Restart the installer after correcting the setting for
environment variable.
</code></pre> | 19,536,622 | 12 | 3 | null | 2012-08-23 10:31:18.187 UTC | 3 | 2020-02-27 23:26:35.223 UTC | 2019-12-13 19:04:45.35 UTC | null | 10,908,375 | null | 1,293,752 | null | 1 | 33 | oracle|oracle11g|oracleclient | 96,778 | <p>This limitation is <em>based on older Windows restrictions,</em> where length of environmental variables was important. This limitation is still there in the Oracle installation.</p>
<p><strong><em>Work around this:</em></strong></p>
<ul>
<li>Step 1: Copy the value of your 'path' variable to a text-editor (Ex.: notepad) and save this value as backup.</li>
<li>Step 2: <strong>Reduce the size of this path</strong> to less that 1023 characters. Remove path variables at the end. You will mostly not need any of them during the oracle installation. Keep those removed values in a separate text-file, because you need to add them again later!</li>
<li>Step 3: <strong>Start the oracle installation</strong> again.</li>
<li>Step 4: After Oracle installation: <strong>Add those removed path values again</strong> at the end of the path.</li>
</ul>
<p>Good luck!</p>
<p><img src="https://i.stack.imgur.com/aT3vU.png" alt="Extra screenshot"></p> |
12,272,778 | How / Where to find Linux Kernel Bugs to Fix? | <p>I'm trying to find bugs that needs to be fixed in the Linux Kernel but I don't know where to look. I watched the video "How to Submit Your First Linux Kernel Patch" by Greg Kroah-Hartman on Youtube, but he doesn't really mention where to find bugs that needs to be fixed. </p>
<p>In the video, he briefly mentions mailing-list and looking at TODOs in the kernel code. Does anyone know where I can join the mailing-list? Also, I found the kernel Bugzilla, but according to Kernel.org only bugs from 2.6 are listed there. I actually signed up, but do I just find a bug there that interest me and try to fix it if it hasn't already been fixed on the latest kernel? Does it matter if its already been assigned to someone?</p>
<p>It would be great if I can find a site where a list of all existing bugs are listed, then I can look for something that is low-priority and low-severity. I'm really looking for a bug that is relatively easy to fix, that way I can learn the ropes and work my way up. </p>
<p>Any advice, input, websites to read, etc. from anyone would be greatly appreciated. Thanks for reading/answering. =)</p> | 12,294,564 | 1 | 2 | null | 2012-09-04 23:48:59.353 UTC | 17 | 2016-01-22 06:48:34.473 UTC | null | null | null | null | 763,621 | null | 1 | 39 | linux|kernel|patch | 15,963 | <p>1.
Yes, you are right, one of the places to look is <a href="https://bugzilla.kernel.org/query.cgi?format=advanced">the kernel bug tracker</a>.</p>
<p>Searching the Linux kernel mailing list as well as the subsystem-related mailing lists could also be helpful but is probably more difficult.</p>
<p>2.
The main kernel mailing list is <a href="http://vger.kernel.org/vger-lists.html#linux-kernel">here</a>. You can find subscription instructions there.</p>
<p>3.
There is also a very useful information about contributing to the Linux kernel and the development process in general in the kernel docs: see <a href="http://www.mjmwired.net/kernel/Documentation/development-process/">Documentation/development-process</a>.</p>
<p>4.
If a bug has already been assigned, this does not always mean the assignee is actually going to work on it anytime soon. It may mean that (s)he is just responsible for a particular subsystem.
So, I suppose, if you find the assigned bug you would like to fix yourself, you could contact the person the bug is currently assigned to and offer your help. If a mailing list address is used instead of a personal email address of the assignee, you could write to that mailing list, ask if anyone already works on the bug and, again offer your help.</p>
<p>5.
One of the ways to see if the bug has been fixed is to try to reproduce it both on the kernel it was reported for and on the latest kernel variant for a particular subsystem. Its is not always easy but still can be very useful to get you into the development process.</p> |
12,188,381 | Render partial :collection => @array specify variable name | <p>I am rendering a partial like this:</p>
<pre><code>$("#box_container").html("<%= escape_javascript( render :partial => 'contacts/contact_tile', :collection => @contacts) %>")
</code></pre>
<p>Problem is that my partial is expecting the variable 'contact'.</p>
<pre><code>ActionView::Template::Error (undefined local variable or method `contact'
</code></pre>
<p>I simply want to tell the partial to expect a variable <code>contact</code>. Should iterate through <code>@contacts</code> as <code>contact</code>. How do I do that?</p> | 12,755,382 | 4 | 0 | null | 2012-08-30 00:34:56.63 UTC | 10 | 2021-05-18 13:05:31.33 UTC | 2012-08-30 00:41:13.14 UTC | null | 211,563 | null | 683,216 | null | 1 | 60 | ruby-on-rails | 44,144 | <p>Found this is also helpful from the docs. You aren't limited to having the variable named after the partial:</p>
<p><a href="http://guides.rubyonrails.org/layouts_and_rendering.html" rel="noreferrer">http://guides.rubyonrails.org/layouts_and_rendering.html</a></p>
<blockquote>
<p>To use a custom local variable name within the partial, specify the
:as option in the call to the partial: </p>
</blockquote>
<pre><code><%= render :partial => "product", :collection => @products, :as => :item %>
</code></pre>
<p>With this change, you can access an instance of the @products collection as the item local variable within the partial."</p> |
19,143,857 | Pandas: bar plot xtick frequency | <p>I want to create a simple bar chart for pandas DataFrame object. However, the xtick on the chart appears to be too granular, whereas if I change the plot to line chart, xtick is optimized for better viewing. I was wondering if I can bring the same line chart xtick frequency to bar chart? Thanks.</p>
<pre><code>locks.plot(kind='bar',y='SUM')
</code></pre>
<p><em>EDIT</em></p>
<p>Resultant plot:<img src="https://i.stack.imgur.com/W4DYE.png" alt="enter image description here"></p> | 19,387,765 | 1 | 3 | null | 2013-10-02 18:14:04.237 UTC | 14 | 2019-09-22 20:19:00.29 UTC | 2014-07-10 01:04:50.313 UTC | null | 283,296 | null | 2,058,335 | null | 1 | 20 | python|matplotlib|plot|pandas | 12,509 | <p>You can reduce the number of thicks by setting one every <code>n</code> ticks, doing something like:</p>
<pre><code>n = 10
ax = locks.plot(kind='bar', y='SUM')
ticks = ax.xaxis.get_ticklocs()
ticklabels = [l.get_text() for l in ax.xaxis.get_ticklabels()]
ax.xaxis.set_ticks(ticks[::n])
ax.xaxis.set_ticklabels(ticklabels[::n])
ax.figure.show()
</code></pre> |
3,732,808 | Find index of number from a string in C# | <p>Form the below string I would like to get the index of the starting number.Please let me know how this can be done in C#.net.</p>
<p>For example</p>
<pre><code>University of California, 1980-85.
University of Colorado, 1999-02
</code></pre> | 3,732,864 | 3 | 3 | null | 2010-09-17 05:17:15.14 UTC | 10 | 2017-10-06 00:09:59.513 UTC | 2017-10-06 00:09:59.513 UTC | null | 46,914 | null | 401,768 | null | 1 | 48 | c# | 52,749 | <pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace IndexOfAny
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("University of California, 1980-85".IndexOfAny("0123456789".ToCharArray()));
}
}
}
</code></pre> |
38,213,467 | What does intrinsic lock actually mean for a Java class? | <p>In order to properly understand the issues and solutions for concurrency in Java, I was going through the official Java tutorial. In one of the pages they defined <strong>Intrinsic Locks and Synchronization</strong> <a href="https://docs.oracle.com/javase/tutorial/essential/concurrency/locksync.html" rel="noreferrer">link</a>. In this page, they say that:</p>
<blockquote>
<p>As long as a thread owns an intrinsic lock, no other thread can
acquire the same lock. The other thread will block when it attempts to
acquire the lock.</p>
</blockquote>
<p>Also, they mention in the section <strong>Locks In Synchronized Methods</strong> that:</p>
<blockquote>
<p>When a thread invokes a synchronized method, it automatically acquires
the intrinsic lock for that method's object and releases it when the
method returns. The lock release occurs even if the return was caused
by an uncaught exception.</p>
</blockquote>
<p>For me this means that once I call a synchronized method from one of the threads, I will have hold of the intrinsic lock of the thread and since</p>
<blockquote>
<p>Intrinsic locks play a role in both aspects of synchronization:
enforcing exclusive access to an object's state and establishing
happens-before relationships that are essential to visibility.</p>
</blockquote>
<p>would another thread be unable to call another synchronized method of the same class? If yes, then the whole purpose of having synchronized methods is defeated. Isn't it?</p> | 38,213,802 | 7 | 6 | null | 2016-07-05 21:57:25.693 UTC | 10 | 2021-11-09 14:22:25.13 UTC | 2016-07-06 06:45:35.343 UTC | null | 2,606,411 | null | 2,606,411 | null | 1 | 14 | java|multithreading|concurrency|synchronization | 10,080 | <p>So just to repeat my comment above as an answer. Intrinsic locking means that you don't have to create an object to synchronize your methods on. In comparison you can use an extrinsic lock by calling <code>synchronized(myLock) {...}</code>.</p>
<p>This is an excerpt from the book <a href="https://www.goodreads.com/book/show/127932.Java_Concurrency_in_Practice" rel="nofollow noreferrer">Java Concurrency in Practice</a>: "The fact that every object has a built-in lock is just a convenience so that you needn't explicitly create lock objects"</p>
<p>The book also says:</p>
<blockquote>
<p>There is no inherent relationship between an object's intrinsic lock
and its state; an object's fields need not be guarded by its intrinsic
lock, though this is a perfectly valid locking convention that is used
by many classes. Acquiring the lock associated with an object does not
prevent other threads from accessing that objectthe only thing that
acquiring a lock prevents any other thread from doing is acquiring
that same lock. The fact that every object has a built-in lock is just
a convenience so that you needn't explicitly create lock objects. [9]
It is up to you to construct locking protocols or synchronization
policies that let you access shared state safely, and to use them
consistently throughout your program.</p>
</blockquote>
<p>But in the footnote it says:</p>
<blockquote>
<p>[9] In retrospect, this design decision was probably a bad one: not
only can it be confusing, but it forces JVM implementors to make
tradeoffs between object size and locking performance.</p>
</blockquote>
<p>And to answer your last questions: you won't be able to call the synchronized methods from another thread, but you can keep entering from the same thread (intrinsic locks are re-entrant). So you have to imagine locking in this case as serializing method access from different caller threads.</p>
<p>If you use locking improperly and then you introduce liveness hazards, then yes it is defeated. That's why you have to make sure that your concurrent threads are not contending with each other too hard.</p>
<p>As <a href="http://www.ibm.com/developerworks/java/library/j-threads1/index.html" rel="nofollow noreferrer">Brian Goetz puts in this blog entry</a>:</p>
<blockquote>
<p>In tuning an application's use of synchronization, then, we should try
hard to reduce the amount of actual contention, rather than simply try
to avoid using synchronization at all</p>
</blockquote> |
8,542,661 | General Polymorphism with PHP examples | <p>As only Dogs can play "fetch", is this example a good or a bad idea? I suspect it's a really bad idea due to the usage of instanceof, but I'm not entirely sure why.</p>
<pre><code>class Animal {
var $name;
function __construct($name) {
$this->name = $name;
}
}
class Dog extends Animal {
function speak() {
return "Woof, woof!";
}
function playFetch() {
return 'getting the stick';
}
}
class Cat extends Animal {
function speak() {
return "Meow...";
}
}
$animals = array(new Dog('Skip'), new Cat('Snowball'));
foreach($animals as $animal) {
print $animal->name . " says: " . $animal->speak() . '<br>';
if ($animal instanceof Dog) echo $animal->playFetch();
}
</code></pre>
<p>Another example. As I am constantly creating data objects that have an ID, I figured I might as well extend them all from a base class to avoid code duplication. Again, this was bad right? As a Chair doesn't have a name and a Dog doesn't have wheels. But they <strong>are</strong> both Data Objects so it's very confusing.</p>
<pre><code>class Data_Object {
protected $_id;
function setId($id) {
$this->_id = $id;
}
function getId() {
return $this->_id;
}
}
class Dog extends Data_Object {
protected $_name;
function setName($name) {
$this->_name =
}
function getName() {
return $this->_name;
}
}
class Chair extends Data_Object {
protected $_numberOfWheels;
function setNumberOfWheels($number) {
$this->_numberOfWheels = $number;
}
function getNumberOfWheels() {
return $this->_numberOfWheels;
}
}
</code></pre>
<p>Essentially what I <em>think</em> I'm asking is: <strong>"should all subclasses have the same interface or can they have different ones?"</strong></p> | 8,542,880 | 3 | 10 | null | 2011-12-17 04:49:17.41 UTC | 20 | 2018-11-13 15:30:08.097 UTC | 2011-12-17 06:18:35.693 UTC | null | 486,233 | null | 895,470 | null | 1 | 29 | php|polymorphism | 54,842 | <p>In this context it's useful to talk about <em>interfaces</em>.</p>
<pre><code>interface Talkative {
public function speak();
}
class Dog extends Animal implements Talkative {
public function speak() {
return "Woof, woof!";
}
}
</code></pre>
<p>Any animal <em>or human</em> (or alien) that implements the Talkative interface can be used in a context where talkative beings are needed:</p>
<pre><code>protected function makeItSpeak(Talkative $being) {
echo $being->speak();
}
</code></pre>
<p>This is a properly used polymorphic method. You don't care <em>what</em> you're dealing with as long as it can <code>speak()</code>.</p>
<p>If <code>Dog</code>s can also play fetch, that's great for them. If you want to generalize that, think about it in terms of an interface as well. Maybe one day you'll get a highly trained cat which can play fetch as well.</p>
<pre><code>class Cog extends Cat implements Playfulness {
public function playFetch() { ... }
}
</code></pre>
<p>The important point here being that when you <em>call</em> <code>playFetch()</code> on something, it's because you want to play fetch with that animal. You don't call <code>playFetch</code> because, well... you can, but because you want to play fetch in this very moment. If you don't want to play fetch, then you don't call it. If you need to play fetch in a certain situation, then you need something that can play fetch. You ensure this through interface declarations.</p>
<p>You can achieve the same thing using class inheritance, it's just less flexible. In some situations where rigid hierarchies exist though it's perfectly useful:</p>
<pre><code>abstract class Animal { }
abstract class Pet extends Animal { }
class Dog extends Pet {
public function playFetch() { ... }
}
class GermanShepherd extends Dog {
public function beAwesome() { ... }
}
</code></pre>
<p>Then, in some specific context, you may not require <em>any object</em> that can do something (interface), but you are specifically looking for a <code>GermanShepherd</code>, because only it can be awesome:</p>
<pre><code>protected function awesomeness(GermanShepherd $dog) {
$dog->beAwesome();
}
</code></pre>
<p>Maybe down the road you'll make a new breed of <code>GermanShepherd</code>s that are also awesome, but <code>extend</code> the <code>GermanShepherd</code> class. They'll still work with the <code>awesomeness</code> function, just like with interfaces.</p>
<p>What you certainly should not do is to loop through a bunch of random things, check what they are and make them do their own thing. That's just not very sensible in any context.</p> |
11,331,388 | from array to datatable | <p>ok i now it supose to be simple y have a multidimensional array, I try to fill my data table using the following code:</p>
<pre><code>System.Data.DataTable _myDataTable =new System.Data.DataTable();
for (int j=0; j < ele; j++)
{
_myDataTable.Columns.Add();
for (int i = 0; i < caract+1; i++)
{
row[i]=(datar[j,i].ToString());
}
_myDataTable.Rows.Add(row);
}
</code></pre>
<p>My array name is <code>datar</code> but the error I receive:</p>
<pre><code> System.IndexOutOfRangeException: cant find column 1.
</code></pre>
<p>What am I doing wrong? By the way: I am using C#, asp.net, NOT Visual Studio.</p> | 11,332,086 | 6 | 7 | null | 2012-07-04 14:51:25.817 UTC | 4 | 2020-09-24 07:19:08.747 UTC | 2012-07-04 15:40:49.99 UTC | null | 76,337 | null | 953,227 | null | 1 | 13 | c#|asp.net | 103,472 | <p>As pointed out by <strong>chiffre</strong> you actually have 3 problems: You will have to add all columns before you can start to add rows and you will have to create a <code>DataRow</code> before you can add it to your <code>DataTable</code>. Your third problem is your row-dimension counter <code>caract+1</code> which will yield an IndexOutOfRange exception.</p>
<pre><code>DataTable _myDataTable = new DataTable();
// create columns
for (int i = 0; i < ele; i++)
{
_myDataTable.Columns.Add();
}
for (int j = 0; j < caract; j++)
{
// create a DataRow using .NewRow()
DataRow row = _myDataTable.NewRow();
// iterate over all columns to fill the row
for (int i = 0; i < ele; i++)
{
row[i] = datar[i, j];
}
// add the current row to the DataTable
_myDataTable.Rows.Add(row);
}
</code></pre> |
10,938,483 | Why can't I specify an environment variable and echo it in the same command line? | <p>Consider this snippet: </p>
<pre><code>$ SOMEVAR=AAA
$ echo zzz $SOMEVAR zzz
zzz AAA zzz
</code></pre>
<p>Here I've set <code>$SOMEVAR</code> to <code>AAA</code> on the first line - and when I echo it on the second line, I get the <code>AAA</code> contents as expected. </p>
<p>But then, if I try to specify the variable on the same command line as the <code>echo</code>:</p>
<pre><code>$ SOMEVAR=BBB echo zzz $SOMEVAR zzz
zzz AAA zzz
</code></pre>
<p>... I do not get <code>BBB</code> as I expected - I get the old value (<code>AAA</code>). </p>
<p>Is this how things are supposed to be? If so, how come then you can specify variables like <code>LD_PRELOAD=/... program args ...</code> and have it work? What am I missing?</p> | 10,938,530 | 9 | 0 | null | 2012-06-07 19:20:26.227 UTC | 28 | 2021-01-26 16:19:28.113 UTC | 2019-11-05 14:52:29.003 UTC | null | 3,266,847 | null | 277,826 | null | 1 | 111 | bash|environment-variables|echo | 39,448 | <p>What you see is the expected behaviour. The trouble is that the parent shell evaluates <code>$SOMEVAR</code> on the command line before it invokes the command with the modified environment. You need to get the evaluation of <code>$SOMEVAR</code> deferred until after the environment is set.</p>
<p>Your immediate options include:</p>
<ol>
<li><code>SOMEVAR=BBB eval echo zzz '$SOMEVAR' zzz</code>.</li>
<li><code>SOMEVAR=BBB sh -c 'echo zzz $SOMEVAR zzz'</code>.</li>
</ol>
<p>Both these use single quotes to prevent the parent shell from evaluating <code>$SOMEVAR</code>; it is only evaluated after it is set in the environment (temporarily, for the duration of the single command).</p>
<p>Another option is to use the sub-shell notation (as also suggested by <a href="https://stackoverflow.com/users/1990689/markus-kuhn">Marcus Kuhn</a> in his <a href="https://stackoverflow.com/a/14400951/15168">answer</a>):</p>
<pre><code>(SOMEVAR=BBB; echo zzz $SOMEVAR zzz)
</code></pre>
<p>The variable is set only in the sub-shell</p> |
11,328,988 | Find all files with name containing string | <p>I have been searching for a command that will return files from the current directory which contain a string in the filename. I have seen <code>locate</code> and <code>find</code> commands that can find files beginning with something <code>first_word*</code> or ending with something <code>*.jpg</code>. </p>
<p>How can I return a list of files which contain a string in the filename? </p>
<p>For example, if <code>2012-06-04-touch-multiple-files-in-linux.markdown</code> was a file in the current directory. </p>
<p>How could I return this file and others containing the string <code>touch</code>? Using a command such as <code>find '/touch/'</code></p> | 11,329,078 | 8 | 1 | null | 2012-07-04 12:19:37.173 UTC | 71 | 2019-04-10 17:31:13.7 UTC | 2018-12-03 12:22:35.957 UTC | null | 608,639 | null | 830,554 | null | 1 | 248 | linux|unix|command-line|locate | 394,274 | <p>Use <code>find</code>:</p>
<p><code>find . -maxdepth 1 -name "*string*" -print</code></p>
<p>It will find all files in the current directory (delete <code>maxdepth 1</code> if you want it recursive) containing "string" and will print it on the screen.</p>
<p>If you want to avoid file containing ':', you can type:</p>
<p><code>find . -maxdepth 1 -name "*string*" ! -name "*:*" -print</code></p>
<p>If you want to use <code>grep</code> (but I think it's not necessary as far as you don't want to check file content) you can use:</p>
<p><code>ls | grep touch</code></p>
<p>But, I repeat, <code>find</code> is a better and cleaner solution for your task.</p> |
16,709,404 | how to automate the "commit-and-push" process? (git) | <p>I have a git repo. And after each major change, that I make in the codebase, what I do is that I go to the terminal and execute a set of commands. </p>
<pre><code>git add .
git commit -m 'some message'
git push origin master
</code></pre>
<p>These are the same each day and the process is quite boring. Can anyone suggest a way to somehow automate this process?</p>
<p>I am running a Linux Mint 14 OS.</p> | 16,709,405 | 7 | 7 | null | 2013-05-23 08:46:53.57 UTC | 14 | 2022-04-08 13:30:42.917 UTC | 2013-05-23 09:01:59.503 UTC | null | 2,080,089 | null | 2,080,089 | null | 1 | 29 | git | 38,468 | <p>You can very easily automate this using Bash scripting.</p>
<pre><code>git add .
echo 'Enter the commit message:'
read commitMessage
git commit -m "$commitMessage"
echo 'Enter the name of the branch:'
read branch
git push origin $branch
read
</code></pre>
<p>store the above code as a <code>.sh</code> file(say <code>gitpush.sh</code>)</p>
<p>And since you have to make this sh file an executable you need to run the following command in the terminal once:</p>
<pre><code>chmod +x gitpush.sh
</code></pre>
<p>And now run this <code>.sh</code> file.</p>
<p>Each time you run it, It will ask you for the commit message and the name of the branch. In case the branch does not exist or the push destination is not defined then git will generate an error. TO read this error, I have added the last <code>read</code> statement. If there are no errors, then git generates the <code>pushed successfully</code> type-of message.</p> |
16,976,523 | Why isn't my Stringer interface method getting invoked? When using fmt.Println | <p>Suppose I have the following code:</p>
<pre><code>package main
import "fmt"
type Car struct{
year int
make string
}
func (c *Car)String() string{
return fmt.Sprintf("{make:%s, year:%d}", c.make, c.year)
}
func main() {
myCar := Car{year:1996, make:"Toyota"}
fmt.Println(myCar)
}
</code></pre>
<p>When I call fmt.Println(myCar) and the object in question is a pointer, my String() method gets called properly. If, however the object is a value, my output is formatted using the default formatting built into Go and my code to format the said object is not called.</p>
<p>The interesting thing is in either case if I call myCar.String() manually it works properly whether my object is either a pointer or value.</p>
<p>How can I get my object formatted the way I want no matter if the object is value-based or pointer-based when used with Println? </p>
<p>I don't want to use a value method for String because then that means every time it's invoked the object is copied which seams unreasonable. And I don't want to have to always manually called .String() either because I'm trying to let the duck-typing system do it's work.</p> | 16,978,611 | 6 | 0 | null | 2013-06-07 04:59:17.49 UTC | 21 | 2019-11-19 15:12:46.07 UTC | 2019-06-10 11:35:00.987 UTC | null | 13,860 | null | 71,079 | null | 1 | 58 | go | 15,040 | <p>When calling <code>fmt.Println</code>, <code>myCar</code> is implicitly converted to a value of type <code>interface{}</code> as you can see from the function signature. The code from the <code>fmt</code> package then does a <a href="http://golang.org/ref/spec#Switch_statements">type switch</a> to figure out how to print this value, looking something like this:</p>
<pre><code>switch v := v.(type) {
case string:
os.Stdout.WriteString(v)
case fmt.Stringer:
os.Stdout.WriteString(v.String())
// ...
}
</code></pre>
<p>However, the <code>fmt.Stringer</code> case fails because <code>Car</code> doesn't implement <code>String</code> (as it is defined on <code>*Car</code>). Calling <code>String</code> manually works because the compiler sees that <code>String</code> needs a <code>*Car</code> and thus automatically converts <code>myCar.String()</code> to <code>(&myCar).String()</code>. For anything regarding interfaces, you have to do it manually. So you either have to implement <code>String</code> on <code>Car</code> or always pass a pointer to <code>fmt.Println</code>:</p>
<pre><code>fmt.Println(&myCar)
</code></pre> |
17,095,443 | How to use Simple Ajax Beginform in Asp.net MVC 4? | <p>I am new in Asp.net MVC and i researched about <code>Ajax.BeginForm</code> but when i apply codes it did not work. Can you share very simple example with <code>Ajax.Beginform</code> with View, Controller, Model?
Thanks.</p> | 17,096,835 | 3 | 2 | null | 2013-06-13 19:27:45.75 UTC | 27 | 2016-12-06 23:17:10.72 UTC | 2015-02-19 21:22:26.803 UTC | null | 1,743,997 | null | 2,483,273 | null | 1 | 60 | ajax|asp.net-mvc|form-helpers|ajax.beginform | 175,459 | <p>Simple example: Form with textbox and Search button. </p>
<p>If you write "name" into the <code>textbox</code> and submit form, it will brings you patients with "name" in table.</p>
<p><strong>View:</strong></p>
<pre><code>@using (Ajax.BeginForm("GetPatients", "Patient", new AjaxOptions {//GetPatients is name of method in PatientController
InsertionMode = InsertionMode.Replace, //target element(#patientList) will be replaced
UpdateTargetId = "patientList",
LoadingElementId = "loader" // div with .gif loader - that is shown when data are loading
}))
{
string patient_Name = "";
@Html.EditorFor(x=>patient_Name) //text box with name and id, that it will pass to controller
<input type="submit" value="Search" />
}
@* ... *@
<div id="loader" class=" aletr" style="display:none">
Loading...<img src="~/Images/ajax-loader.gif" />
</div>
@Html.Partial("_patientList") @* this is view with patient table. Same view you will return from controller *@
</code></pre>
<p><strong>_patientList.cshtml:</strong></p>
<pre><code>@model IEnumerable<YourApp.Models.Patient>
<table id="patientList" >
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Number)
</th>
</tr>
@foreach (var patient in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => patient.Name)
</td>
<td>
@Html.DisplayFor(modelItem => patient.Number)
</td>
</tr>
}
</table>
</code></pre>
<p><strong>Patient.cs</strong></p>
<pre><code>public class Patient
{
public string Name { get; set; }
public int Number{ get; set; }
}
</code></pre>
<p><strong>PatientController.cs</strong></p>
<pre><code>public PartialViewResult GetPatients(string patient_Name="")
{
var patients = yourDBcontext.Patients.Where(x=>x.Name.Contains(patient_Name))
return PartialView("_patientList", patients);
}
</code></pre>
<p>And also as TSmith said in comments, don´t forget to install <em>jQuery Unobtrusive Ajax</em> library through <a href="https://www.nuget.org/packages/Microsoft.jQuery.Unobtrusive.Ajax">NuGet</a>.</p> |
16,739,771 | How can I change a project's location pointer in Eclipse? | <p>A project has moved to a different location, so Eclipse won't open the project. You'll immediately think about simply changing the pointer to the location, but in Eclipse they try to make this impossible for some reason.</p>
<p>You cannot change the project location in the <code>Project Explorer</code> properties.</p>
<p>You can go to <code>[workspace]/eclipse/.metadata/.plugins/org.eclipse.core.resources/.projects/ProjectName</code> and try to edit <code>.location</code> which is the pointer to the project, but this file is purposely stored in binary.</p>
<p>How do I change this <code>.location</code>, is there a tool for that? Any other way to <strong>simply</strong> point my old project entry to it's new location?</p> | 16,740,557 | 11 | 1 | null | 2013-05-24 16:38:28.907 UTC | 17 | 2020-09-16 23:59:38.923 UTC | 2020-04-28 09:31:13.717 UTC | null | 9,216,858 | null | 754,174 | null | 1 | 68 | eclipse|directory|location|project|target | 84,894 | <p>Delete the project from eclipse. </p>
<p><strong>ENSURE THAT THE CHECK BOX is UNSELECTED, during this delete</strong></p>
<p>And then import the project by <code>File</code> -> <code>Import</code> -> <code>Import existing project</code> and choose it from the new location.</p>
<p><strong>Don't</strong> try to modify the eclipse files manually!</p> |
16,908,476 | Object property name as number | <p>According to the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Values,_variables,_and_literals" rel="nofollow noreferrer">MDN JavaScript documentation</a> you can define object literal property names using integers:</p>
<blockquote>
<p>Additionally, you can use a numeric or string literal for the name of a property.</p>
</blockquote>
<p>Like so:</p>
<pre><code>me = {
name: "Robert Rocha",
123: 26,
origin: "Mexico"
}
</code></pre>
<p>My question is, how do you reference the property that has an integer as a name? I tried the usual <code>me.123</code> but got an error. The only workaround that I can think of is using a <code>for-in</code> loop. Any suggestions?</p> | 16,908,505 | 6 | 3 | null | 2013-06-04 01:34:58.577 UTC | 21 | 2022-09-01 10:15:28.44 UTC | 2022-09-01 10:15:28.44 UTC | null | -1 | null | 1,798,677 | null | 1 | 74 | javascript|object | 84,989 | <p>You can reference the object's properties as you would an array and use either <code>me[123]</code> or <code>me["123"]</code></p> |
4,777,070 | Hamming distance on binary strings in SQL | <p>I have a table in my DB where I store SHA256 hashes in a BINARY(32) column. I'm looking for a way to compute the Hamming distance of the entries in the column to a supplied value, i.e. something like:</p>
<pre><code>SELECT * FROM table
ORDER BY HAMMINGDISTANCE(hash, UNHEX(<insert supplied sha256 hash here>)) ASC
LIMIT 10
</code></pre>
<p>(in case you're wondering, the Hamming distance of strings A and B is defined as <code>BIT_COUNT(A^B)</code>, where ^ is the bitwise XOR operator and BIT_COUNT returns the number of 1s in the binary string).</p>
<p>Now, I know that both the ^ operator and BIT_COUNT function only work on INTEGERs and so I'd say that probably the only way to do it would be to break up the binary strings in substrings, cast each binary substring to integer, compute the Hamming distance substring-wise and then add them. The problem with this is that it sounds terribly complicated, not efficient and definitely not elegant. My question therefore is: could you suggest any better way? (please note that I'm on shared hosting and therefore I can't modify the DB server or load libraries)</p>
<p>edit(1): Obviously loading the whole table in PHP and doing the computations there would be possible but I'd rather avoid it because this table will probably grow quite large.</p>
<p>edit(2): The DB server is MySQL 5.1</p>
<p>edit(3): My answer below contains the code that I just described above.</p>
<p><strong>edit(4): I just found out that using 4 BIGINTs to store the hash instead of a BINARY(32) yields massive speed improvements (more than 100 times faster). See the comments to my answer below.</strong></p> | 4,783,415 | 2 | 9 | null | 2011-01-23 22:45:32.08 UTC | 15 | 2021-07-26 05:32:27.377 UTC | 2011-02-12 14:18:19.53 UTC | null | 414,813 | null | 414,813 | null | 1 | 25 | sql|mysql|hash|binary-data|hamming-distance | 10,910 | <p>It appears that storing the data in a <code>BINARY</code> column is an approach bound to perform poorly. The only fast way to get decent performance is to split the content of the <code>BINARY</code> column in multiple <code>BIGINT</code> columns, each containing an 8-byte substring of the original data.</p>
<p>In my case (32 bytes) this would mean using 4 <code>BIGINT</code> columns and using this function:</p>
<pre><code>CREATE FUNCTION HAMMINGDISTANCE(
A0 BIGINT, A1 BIGINT, A2 BIGINT, A3 BIGINT,
B0 BIGINT, B1 BIGINT, B2 BIGINT, B3 BIGINT
)
RETURNS INT DETERMINISTIC
RETURN
BIT_COUNT(A0 ^ B0) +
BIT_COUNT(A1 ^ B1) +
BIT_COUNT(A2 ^ B2) +
BIT_COUNT(A3 ^ B3);
</code></pre>
<p>Using this approach, in my testing, is over 100 times faster than using the <code>BINARY</code> approach.</p>
<hr>
<p>FWIW, this is the code I was hinting at while explaining the problem. Better ways to accomplish the same thing are welcome (I especially don't like the binary > hex > decimal conversions):</p>
<pre><code>CREATE FUNCTION HAMMINGDISTANCE(A BINARY(32), B BINARY(32))
RETURNS INT DETERMINISTIC
RETURN
BIT_COUNT(
CONV(HEX(SUBSTRING(A, 1, 8)), 16, 10) ^
CONV(HEX(SUBSTRING(B, 1, 8)), 16, 10)
) +
BIT_COUNT(
CONV(HEX(SUBSTRING(A, 9, 8)), 16, 10) ^
CONV(HEX(SUBSTRING(B, 9, 8)), 16, 10)
) +
BIT_COUNT(
CONV(HEX(SUBSTRING(A, 17, 8)), 16, 10) ^
CONV(HEX(SUBSTRING(B, 17, 8)), 16, 10)
) +
BIT_COUNT(
CONV(HEX(SUBSTRING(A, 25, 8)), 16, 10) ^
CONV(HEX(SUBSTRING(B, 25, 8)), 16, 10)
);
</code></pre> |
26,434,923 | Parse command line arguments in a Ruby script | <p>I want to call a Ruby script from the command line, and pass in parameters that are key/value pairs.</p>
<p>Command line call:</p>
<pre><code>$ ruby my_script.rb --first_name=donald --last_name=knuth
</code></pre>
<p>my_script.rb:</p>
<pre><code>puts args.first_name + args.last_name
</code></pre>
<p>What is the standard Ruby way to do this? In other languages I usually have to use an option parser. In Ruby I saw we have <code>ARGF.read</code>, but that does not seem to work key/value pairs like in this example.</p>
<p><a href="http://ruby-doc.org/stdlib-2.1.1/libdoc/optparse/rdoc/OptionParser.html#method-i-getopts" rel="noreferrer">OptionParser</a> looks promising, but I can't tell if it actually supports this case.</p> | 26,435,303 | 7 | 4 | null | 2014-10-17 23:48:30.88 UTC | 21 | 2021-02-17 21:27:38.87 UTC | 2014-10-18 20:36:14.423 UTC | null | 128,421 | null | 1,001,938 | null | 1 | 62 | ruby|command-line | 44,873 | <p>Based on the answer by @MartinCortez here's a short one-off that makes a hash of key/value pairs, where the values must be joined with an <code>=</code> sign. It also supports flag arguments without values:</p>
<pre><code>args = Hash[ ARGV.join(' ').scan(/--?([^=\s]+)(?:=(\S+))?/) ]
</code></pre>
<p>…or alternatively…</p>
<pre><code>args = Hash[ ARGV.flat_map{|s| s.scan(/--?([^=\s]+)(?:=(\S+))?/) } ]
</code></pre>
<p>Called with <code>-x=foo -h --jim=jam</code> it returns <code>{"x"=>"foo", "h"=>nil, "jim"=>"jam"}</code> so you can do things like:</p>
<pre><code>puts args['jim'] if args.key?('h')
#=> jam
</code></pre>
<hr>
<p>While there are multiple libraries to handle this—including <a href="http://ruby-doc.org/stdlib-2.1.3/libdoc/getoptlong/rdoc/GetoptLong.html"><code>GetoptLong</code> included with Ruby</a>—I personally prefer to roll my own. Here's the pattern I use, which makes it reasonably generic, not tied to a specific usage format, and flexible enough to allow intermixed flags, options, and required arguments in various orders:</p>
<pre><code>USAGE = <<ENDUSAGE
Usage:
docubot [-h] [-v] [create [-s shell] [-f]] directory [-w writer] [-o output_file] [-n] [-l log_file]
ENDUSAGE
HELP = <<ENDHELP
-h, --help Show this help.
-v, --version Show the version number (#{DocuBot::VERSION}).
create Create a starter directory filled with example files;
also copies the template for easy modification, if desired.
-s, --shell The shell to copy from.
Available shells: #{DocuBot::SHELLS.join(', ')}
-f, --force Force create over an existing directory,
deleting any existing files.
-w, --writer The output type to create [Defaults to 'chm']
Available writers: #{DocuBot::Writer::INSTALLED_WRITERS.join(', ')}
-o, --output The file or folder (depending on the writer) to create.
[Default value depends on the writer chosen.]
-n, --nopreview Disable automatic preview of .chm.
-l, --logfile Specify the filename to log to.
ENDHELP
ARGS = { :shell=>'default', :writer=>'chm' } # Setting default values
UNFLAGGED_ARGS = [ :directory ] # Bare arguments (no flag)
next_arg = UNFLAGGED_ARGS.first
ARGV.each do |arg|
case arg
when '-h','--help' then ARGS[:help] = true
when 'create' then ARGS[:create] = true
when '-f','--force' then ARGS[:force] = true
when '-n','--nopreview' then ARGS[:nopreview] = true
when '-v','--version' then ARGS[:version] = true
when '-s','--shell' then next_arg = :shell
when '-w','--writer' then next_arg = :writer
when '-o','--output' then next_arg = :output
when '-l','--logfile' then next_arg = :logfile
else
if next_arg
ARGS[next_arg] = arg
UNFLAGGED_ARGS.delete( next_arg )
end
next_arg = UNFLAGGED_ARGS.first
end
end
puts "DocuBot v#{DocuBot::VERSION}" if ARGS[:version]
if ARGS[:help] or !ARGS[:directory]
puts USAGE unless ARGS[:version]
puts HELP if ARGS[:help]
exit
end
if ARGS[:logfile]
$stdout.reopen( ARGS[:logfile], "w" )
$stdout.sync = true
$stderr.reopen( $stdout )
end
# etc.
</code></pre> |
9,930,562 | is autoupdating possible in Android without using android market? | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/3057771/is-there-a-way-to-automatically-update-application-on-android">Is there a way to automatically update application on Android?</a> </p>
</blockquote>
<p>As a property of an application(NOT USING GOOGLE PLAY), an auto-updating possible in android?
I mean can a application check and download the new apk file, and install after downloading it?</p> | 9,930,651 | 3 | 0 | null | 2012-03-29 17:41:35.197 UTC | 9 | 2013-02-28 16:17:32.777 UTC | 2017-05-23 10:32:41.96 UTC | null | -1 | null | 1,281,930 | null | 1 | 6 | android|auto-update | 10,930 | <p>Check out the CWAC-Updater project: <a href="https://github.com/commonsguy/cwac-updater" rel="noreferrer">https://github.com/commonsguy/cwac-updater</a></p> |
10,016,936 | In jquery fullcalendar, can I add a new event without refreshing the whole month? | <p>I am using <a href="http://arshaw.com/fullcalendar/">jquery fullcalendar</a> and it works great. My events come in from an ajax call and get returned as json.</p>
<p>I am trying to figure out if there is a way to add events from the client side without refreshing the whole server.</p>
<p>I have the ability to add a new event in my code (which adds it to my database) but the only way i know how to refresh the UI to show this new event is to call refetchevents (but this reloads everything for the month back from the server.</p>
<p>Is there anyway I can stick in additional events all clientside to avoid a full month event refresh ?</p>
<p>I see i can remove events one by one by the removeEvents method (with an id filter) but i don't see the equivalent around adding an event.</p>
<h2>Update:</h2>
<p>I have a followup question given the answers below which both worked. (didn't make sense to create another question). I wanted to see the recommended way to "refresh" a single event on the clientside. I tried to simply call 'renderEvent' with an event with the same Id but that creates a new event on the calendar. </p>
<p>I see there is the: <strong>UpdateEvent</strong> method which I would assume would be the answer but it seems like this only works if you are inside an eventClick (you can't just create a new event object, set the Id and change a field and call update.</p>
<pre><code> http://arshaw.com/fullcalendar/docs/event_data/updateEvent/
</code></pre>
<p>Is there a recommended way of refreshing an event from the client side similar to the "Add Clientside" event logic below?</p>
<p>Right now I am just removing and readding in the event like this:</p>
<pre><code> $('#calendar').fullCalendar('removeEvents', data.Event.id);
$('#calendar').fullCalendar('renderEvent', data.Event, true);
</code></pre> | 10,017,476 | 8 | 1 | null | 2012-04-04 18:13:14.813 UTC | 6 | 2020-06-03 10:58:05.42 UTC | 2012-04-09 12:26:55.297 UTC | null | 4,653 | null | 4,653 | null | 1 | 15 | jquery|fullcalendar | 51,710 | <p>to add events on the client side into the fullCalendar you can call:</p>
<pre><code>var myCalendar = $('#my-calendar-id');
myCalendar.fullCalendar();
var myEvent = {
title:"my new event",
allDay: true,
start: new Date(),
end: new Date()
};
myCalendar.fullCalendar( 'renderEvent', myEvent );
</code></pre>
<p>I haven't test this code, but this should get the job done.</p> |
9,809,357 | Regex for validating multiple E-Mail-Addresses | <p>I got a Regex that validates my mail-addresses like this:</p>
<p><code>([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)</code></p>
<p>This works perfectly fine, but only allows one e-mail to be entered. Now I wanted to extend that and allow multiple mail-addresses to be added (just like MS Outlook, for example) with a semicolon as a mail-splitter.</p>
<p><code>[email protected];[email protected];[email protected]</code></p>
<p>Now I've searched and found this one:</p>
<p><code>([A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}(;|$))</code></p>
<p>This works on one point, but sadly <strong>requires</strong> a semicolon at the end of a mail:</p>
<pre><code>[email protected];
</code></pre>
<p>This is not what I want when the user only enters one e-mail.</p>
<p>How can I extend my regex above (the first one) to allow multiple mail-addresses to be added while let them be splitted through a semicolon?</p> | 9,809,636 | 11 | 4 | null | 2012-03-21 17:02:10.237 UTC | 20 | 2022-04-05 14:42:49.38 UTC | 2012-03-21 17:19:05.643 UTC | null | 917,465 | null | 917,465 | null | 1 | 36 | c#|regex|validation|email|rfc | 58,121 | <p>This is your original expression, changed so that it allows several emails separated by semicolon and (optionally) spaces besides the semicolon. It also allows a single email address that doesn't end in semicolon.</p>
<p>This allows blank entries (no email addresses). You can replace the final * by + to require at least one address.</p>
<pre><code>(([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)(\s*;\s*|\s*$))*
</code></pre>
<p>If you need to allow comma, apart from semicolon, you can change this group:</p>
<pre><code>(\s*;\s*|\s*$)
</code></pre>
<p>by this one:</p>
<pre><code>(\s*(;|,)\s*|\s*$)
</code></pre>
<p>Important note: as states in the comment by Martin, if there are additional text before or after the correct email address list, the validation will not fail. So it would work as an "email searcher". To make it work as a validator you need to add <code>^</code> at the beginning of the regex, and <code>$</code> at the end. This will ensure that the expression matches all the text. So the full regex would be:</p>
<pre><code>^(([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)(\s*;\s*|\s*$))*$
</code></pre>
<p>You can add an extra <code>\s*</code> after the <code>^</code> to tolerate blanks at the beginning of the list, like this. I.e. include <code>^\s*</code> instead of simply <code>^</code> The expression already tolerates blanks at the end as is.</p> |
10,087,467 | Passing annotation properties to meta-annotations | <p>Say I have an annotation with a property:</p>
<pre><code>@Named(name = "Steve")
private Person person
</code></pre>
<p>and I want to create a compound annotation with several meta-annotations, including the one that takes a property</p>
<pre><code>@Named
@AnotherAnnotation
@YetAnotherAnnotation
public @interface CompoundAnnotation {
...
}
</code></pre>
<p>Is there a way that I can pass properties to the compound annotation to one of the meta annotations?</p>
<p>Eg, something like this:</p>
<pre><code>@CompoundAnnotation(name = "Bob")
private Person person;
</code></pre>
<p>that is equivalent to, but much more convenient than</p>
<pre><code>@Named(name = "Bob")
@AnotherAnnotation
@YetAnotherAnnotation
private Person person;
</code></pre>
<p>Thanks!</p>
<p>PS apologies for my poor choice of an example annotation - I didn't have the javax.inject.@Named annotation in mind, just some arbitrary annotation that has properties.</p>
<hr>
<p>Thank you everyone for your answers/comments.</p>
<p>It definitely seems to be the case that this is not possible. However, it just happens that there is a simple work-around for my case-in-point, which I will share in case it helps anyone:</p>
<p>I am working with Spring and want to create my own Annotations that have @Component as a meta-annotation, thus being autodetected by component scanning. However, I also wanted to be able to set the BeanName property (corresponding to the value property in @Component) so I could have custom bean names.</p>
<p>Well it turns out that the thoughtful guys at Spring made it possible to do just that - the AnnotationBeanNameGenerator will take the 'value' property of whatever annotation it is passed and use that as the bean name (and of course, by default, it will only get passed annotations that are @Component or have @Component as a meta-annotation). In retrospect this should have been obvious to me from the start - this is how existing annotations with @Component as a meta-annotation, such as @Service and @Registry, can provide bean names.</p>
<p>Hope that is useful to someone. I still think it's a shame that this is not possible more generally though!</p> | 10,088,998 | 2 | 4 | null | 2012-04-10 11:02:00.18 UTC | 9 | 2022-01-25 00:31:24.803 UTC | 2012-04-10 13:18:53.26 UTC | null | 996,309 | null | 996,309 | null | 1 | 47 | java|annotations | 10,034 | <blockquote>
<p>Is there a way that I can pass properties to the compound annotation to one of the meta annotations?</p>
</blockquote>
<p>I think the simple answer is "no". There is no way to ask <code>Person</code> what annotations it has on it and get <code>@Named</code> for example.</p>
<p>The more complex answer is that you can chain annotations but you would have to investigate these annotations via reflection. For example, the following works:</p>
<pre><code>@Bar
public class Foo {
public static void main(String[] args) {
Annotation[] fooAnnotations = Foo.class.getAnnotations();
assertEquals(1, fooAnnotations.length);
for (Annotation annotation : fooAnnotations) {
Annotation[] annotations =
annotation.annotationType().getAnnotations();
assertEquals(2, annotations.length);
assertEquals(Baz.class, annotations[0].annotationType());
}
}
@Baz
@Retention(RetentionPolicy.RUNTIME)
public @interface Bar {
}
@Retention(RetentionPolicy.RUNTIME)
public @interface Baz {
}
}
</code></pre>
<p>However the following statement will return null:</p>
<pre><code>// this always returns null
Baz baz = Foo.class.getAnnotation(Baz.class)
</code></pre>
<p>This means that any 3rd party class that is looking for the <code>@Baz</code> annotation won't see it.</p> |
28,199,212 | Why does libc++'s implementation of shared_ptr use full memory barriers instead of relaxed? | <p>In boost's implementation of <code>shared_ptr</code>, it uses <a href="https://github.com/boostorg/smart_ptr/blob/master/include/boost/smart_ptr/detail/sp_counted_base_clang.hpp#L29" rel="noreferrer">relaxed memory ordering to increment its reference count</a>. This appears safe as decrements use acquire/release to make sure that any previous decrements are visible to the thread before releasing memory. This method seems correct and appears in Herb Sutters <a href="http://channel9.msdn.com/Shows/Going+Deep/Cpp-and-Beyond-2012-Herb-Sutter-atomic-Weapons-1-of-2" rel="noreferrer">talk on atomics</a></p>
<p>In libc++'s implementation uses <a href="http://llvm.org/svn/llvm-project/libcxx/trunk/src/memory.cpp" rel="noreferrer">full memory barriers</a></p>
<pre><code>template <class T>
inline T
increment(T& t) _NOEXCEPT
{
return __sync_add_and_fetch(&t, 1);
}
template <class T>
inline T
decrement(T& t) _NOEXCEPT
{
return __sync_add_and_fetch(&t, -1);
}
} // name
</code></pre>
<p>Is there a reason for this decision? Are there any performance or safety differences between them? </p> | 28,204,322 | 1 | 5 | null | 2015-01-28 18:01:35.813 UTC | 8 | 2015-01-28 23:21:47.577 UTC | 2015-01-28 20:15:04.707 UTC | null | 148,766 | null | 148,766 | null | 1 | 29 | c++|boost|thread-safety|shared-ptr|libc++ | 1,939 | <p>Because when I wrote that code, the compiler (clang) had not yet implemented C++11 atomics. And I never got back to it to clean it up. </p>
<p>Nothing subtle here. :-)</p> |
9,737,616 | UITableView: hide header from empty section | <p>i have a UITableView, that displays expenses from a current month (see screenshot):</p>
<p>My problem is with the header for empty sections. is there any way to hide them?
The data is loaded from coredata.</p>
<p>this is the code that generates the header title:</p>
<p>TitleForHeader</p>
<pre><code>-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
if ([tableView.dataSource tableView:tableView numberOfRowsInSection:section] == 0) {
return nil;
} else {
NSDate *today = [NSDate date ];
int todayInt = [dataHandler getDayNumber:today].intValue;
NSDate *date = [NSDate dateWithTimeIntervalSinceNow:(-(todayInt-section-1)*60*60*24)];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:[[NSLocale preferredLanguages] objectAtIndex:0]]];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
NSString *formattedDateString = [dateFormatter stringFromDate:date];
return formattedDateString;}
}
</code></pre>
<p>ViewForHeader</p>
<pre><code>-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
if ([tableView.dataSource tableView:tableView numberOfRowsInSection:section] == 0) {
return nil;
} else {
UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 312, 30)];
UILabel *title = [[UILabel alloc]initWithFrame:CGRectMake(4, 9, 312, 20)];
UIView *top = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 312, 5)];
UIView *bottom = [[UIView alloc]initWithFrame:CGRectMake(0, 5, 312, 1)];
[top setBackgroundColor:[UIColor lightGrayColor]];
[bottom setBackgroundColor:[UIColor lightGrayColor]];
[title setText:[expenseTable.dataSource tableView:tableView titleForHeaderInSection:section]];
[title setTextColor:[UIColor darkGrayColor]];
UIFont *fontName = [UIFont fontWithName:@"Cochin-Bold" size:15.0];
[title setFont:fontName];
[headerView addSubview:title];
[headerView addSubview:top];
[headerView addSubview:bottom];
return headerView;
}
}
</code></pre>
<p>heightForHeader</p>
<pre><code>- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
NSLog(@"Height: %d",[tableView.dataSource tableView:tableView numberOfRowsInSection:section] == 0);
if ([tableView.dataSource tableView:tableView numberOfRowsInSection:section == 0]) {
return 0;
} else {
return 30;
}
}
</code></pre>
<p>numberOfRowsInSection</p>
<pre><code>- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
int rows = 0;
for (Expense* exp in [dataHandler allMonthExpenses]) {
if ([exp day].intValue == section) {
rows++;
}
}
return rows;
}
</code></pre>
<p><img src="https://i.stack.imgur.com/srwoS.png" alt="enter image description here">
sebastian</p> | 9,737,690 | 8 | 0 | null | 2012-03-16 12:53:13.057 UTC | 19 | 2019-04-16 00:11:53.59 UTC | 2012-03-16 16:10:41.63 UTC | null | 1,146,393 | null | 1,146,393 | null | 1 | 80 | objective-c|ios|uitableview|tableview | 68,498 | <p>What if in – <code>tableView:viewForHeaderInSection:</code> you <code>return nil</code> if the section count is 0.</p>
<p><strong>EDIT</strong> :
You can use <code>numberOfRowsInSection</code> for obtaining the number of elements in the section.</p>
<p><strong>EDIT</strong>:
Probably you should return nil also in <code>titleForHeaderInSection</code> if <code>numberOfRowsInSection</code> is 0.</p>
<p><strong>EDIT</strong>:
Did you implement the following method?</p>
<pre><code>-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
</code></pre>
<p><strong>EDIT</strong> : <strong>Swift 3</strong> example</p>
<pre><code>override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
switch section {
case 0:
if self.tableView(tableView, numberOfRowsInSection: section) > 0 {
return "Title example for section 1"
}
case 1:
if self.tableView(tableView, numberOfRowsInSection: section) > 0 {
return "Title example for section 2"
}
default:
return nil // when return nil no header will be shown
}
return nil
}
</code></pre> |
7,818,277 | Is there a standard option workflow in F#? | <p>Is there an option (maybe) wokflow (monad) in the standrd F# library?</p>
<p>I've found a dozen of hand-made implementations (<a href="http://stevehorsfield.wordpress.com/2009/09/06/f-delayed-compositional-maybe-monad-workflow-full-source/" rel="noreferrer">1</a>, <a href="https://stackoverflow.com/questions/3157154/implementing-the-haskell-maybemonad-in-f-how-can-we-get-this-lazy">2</a>) of this workflow, but I don't really want to introduce non-standard and not very trusted code into my project. And all imaginable queries to google and msdn gave me no clue where to find it.</p> | 7,818,354 | 3 | 0 | null | 2011-10-19 08:06:05.617 UTC | 1 | 2022-08-31 16:44:25.493 UTC | 2022-08-31 16:44:25.493 UTC | null | 3,744,182 | null | 599,628 | null | 1 | 29 | f#|workflow|option-type|monads | 4,901 | <p>There's no Maybe monad in the standard F# library. You may want to look at <a href="http://bugsquash.blogspot.com/2011/10/introducing-fsharpx.html">FSharpx</a>, a F# extension written by highly-qualified members of F# community, which has quite a number of useful monads. </p> |
11,779,082 | listener for pressing and releasing a button | <p>How can I listen for when a <code>Button</code> is pressed and released?</p> | 11,779,177 | 3 | 0 | null | 2012-08-02 14:02:13.833 UTC | 11 | 2018-01-24 15:10:23.203 UTC | 2014-06-18 16:12:29.947 UTC | null | 569,558 | null | 1,160,337 | null | 1 | 44 | android|view | 38,332 | <p>You can use a <code>onTouchListener</code>:</p>
<pre><code>view.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch(event.getAction()) {
case MotionEvent.ACTION_DOWN:
// PRESSED
return true; // if you want to handle the touch event
case MotionEvent.ACTION_UP:
// RELEASED
return true; // if you want to handle the touch event
}
return false;
}
});
</code></pre> |
11,544,460 | How to get a backtrace from a SystemStackError: stack level too deep? | <p>Often I get hard to debug infinite recursions when coding ruby. Is there a way to get a backtrace out of a <code>SystemStackError</code> to find out, where exactly the infinite loop occurs?</p>
<h2>Example</h2>
<p>Given some methods <code>foo</code>, <code>bar</code> and <code>baz</code> which call each other in a loop:</p>
<pre><code>def foo
bar
end
def bar
baz
end
def baz
foo
end
foo
</code></pre>
<p>When I run this code, I just get the message <code>test.rb:6: stack level too deep (SystemStackError)</code>. It would be useful to get at least the last 100 lines of the stack, so I could immediately see this is a loop between <code>foo</code>, <code>bar</code> and <code>baz</code>, like this:</p>
<pre><code>test.rb:6: stack level too deep (SystemStackError)
test.rb:2:in `foo'
test.rb:10:in `baz'
test.rb:6:in `bar'
test.rb:2:in `foo'
test.rb:10:in `baz'
test.rb:6:in `bar'
test.rb:2:in `foo'
[...]
</code></pre>
<p>Is there any way to accomplish this?</p>
<p><strong>EDIT:</strong></p>
<p>As you may see from the answer below, Rubinius can do it. Unfortunately some <a href="http://github.com/rubinius/rubinius/issues/1692">rubinius bugs</a> prevent me from using it with the software I'd like to debug. So to be precise the question is:</p>
<p><strong>How do I get a backtrace with MRI (the default ruby) 1.9?</strong></p> | 31,835,021 | 8 | 0 | null | 2012-07-18 15:05:13.617 UTC | 21 | 2015-08-05 14:13:15.007 UTC | 2012-07-18 15:54:39.58 UTC | null | 773,690 | null | 773,690 | null | 1 | 50 | ruby | 15,551 | <p>Apparently this was tracked as <a href="https://bugs.ruby-lang.org/issues/6216" rel="nofollow">feature 6216</a> and fixed in Ruby 2.2.</p>
<pre class="lang-none prettyprint-override"><code>$ ruby system-stack-error.rb
system-stack-error.rb:6:in `bar': stack level too deep (SystemStackError)
from system-stack-error.rb:2:in `foo'
from system-stack-error.rb:10:in `baz'
from system-stack-error.rb:6:in `bar'
from system-stack-error.rb:2:in `foo'
from system-stack-error.rb:10:in `baz'
from system-stack-error.rb:6:in `bar'
from system-stack-error.rb:2:in `foo'
from system-stack-error.rb:10:in `baz'
... 10067 levels...
from system-stack-error.rb:10:in `baz'
from system-stack-error.rb:6:in `bar'
from system-stack-error.rb:2:in `foo'
from system-stack-error.rb:13:in `<main>'
</code></pre> |
3,738,836 | How do I check if a Perl scalar variable has been initialized? | <p>Is the following the best way to check if a scalar variable is initialized in Perl, using <code>defined</code>?</p>
<pre><code>my $var;
if (cond) {
$var = "string1";
}
# Is this the correct way?
if (defined $var) {
...
}
</code></pre> | 3,738,936 | 5 | 0 | null | 2010-09-17 20:35:00.897 UTC | 10 | 2016-09-08 11:54:39.703 UTC | 2016-09-08 11:52:39.17 UTC | null | 63,550 | null | 43,756 | null | 1 | 36 | perl | 56,832 | <p>Perl doesn't offer a way to check whether or not a variable has been initialized.</p>
<p>However, scalar variables that haven't been explicitly initialized with some value happen to have the value of <code>undef</code> by default. You are right about <code>defined</code> being the right way to check whether or not a variable has a value of <code>undef</code>.</p>
<p>There's several other ways tho. If you want to assign to the variable if it's <code>undef</code>, which your example code seems to indicate, you could, for example, use perl's defined-or operator:</p>
<pre><code>$var //= 'a default value';
</code></pre> |
4,008,546 | How to pad with n characters in Python | <p>I should define a function <code>pad_with_n_chars(s, n, c)</code> that takes a
string 's', an integer 'n', and a character 'c' and returns
a string consisting of 's' padded with 'c' to create a
string with a centered 's' of length 'n'. For example,
<code>pad_with_n_chars(”dog”, 5, ”x”)</code> should return the
string "<code>xdogx</code>".</p> | 4,008,562 | 6 | 1 | null | 2010-10-24 14:01:30.537 UTC | 8 | 2022-05-06 06:14:09.213 UTC | 2010-10-24 14:58:30.033 UTC | null | 19,750 | null | 485,611 | null | 1 | 42 | python|string | 48,359 | <p>With Python2.6 or better, there's no need to define your own function; the string <a href="http://docs.python.org/library/string.html#format-string-syntax" rel="nofollow noreferrer">format</a> method can do all this for you:</p>
<pre><code>In [18]: '{s:{c}^{n}}'.format(s='dog',n=5,c='x')
Out[18]: 'xdogx'
</code></pre>
<p>Using f-string: <code>f'{"dog":x^5}'</code></p> |
3,352,020 | How to declare a global variable in JavaScript | <p>How can I declare a global variable in JavaScript?</p> | 3,352,033 | 6 | 0 | null | 2010-07-28 10:38:08.927 UTC | 32 | 2020-10-16 20:22:14.117 UTC | 2020-10-15 18:51:59.927 UTC | null | 63,550 | null | 385,563 | null | 1 | 144 | javascript|global-variables | 322,997 | <p>If you have to generate global variables in production code (which should be avoided) <strong>always</strong> declare them <strong>explicitly</strong>:</p>
<pre><code>window.globalVar = "This is global!";
</code></pre>
<p>While it is possible to define a global variable by just omitting <code>var</code> (assuming there is no local variable of the same name), doing so generates an <em>implicit</em> global, which is a bad thing to do and would generate an error in <em>strict mode</em>.</p> |
4,013,591 | attr_reader with question mark in a name | <p>Sorry for this, probably, really newbie question:</p>
<p>I want to define a getter that returns bool value. f.i.:</p>
<pre><code> attr_reader :server_error?
</code></pre>
<p>But then, how do I update it, as Ruby (1.9) throws syntax error if there is a question mark at the end:</p>
<pre><code>#unexpected '='
@server_error? = true
self.server_error? = true
</code></pre> | 4,013,983 | 7 | 0 | null | 2010-10-25 10:14:23.487 UTC | 4 | 2022-07-13 07:53:42.687 UTC | 2010-10-25 12:09:44.653 UTC | null | 437,301 | null | 409,475 | null | 1 | 30 | ruby | 9,118 | <p>I suggest defining your own method rather than using <code>:attr_reader</code></p>
<pre><code>def server_error?
!!@server_error # Or any other idiom that you generally use for checking boolean
end
</code></pre>
<p>for brevity's sake, you could do it in one line:</p>
<pre><code>def server_error?; !!@server_error; end
</code></pre> |
3,463,796 | How to only show certain parts with CSS for Print? | <p>I have a page with lots of data, tables and content.
I want to make a print version that will only display very few selected things.</p>
<p>Instead of writing another page just for printing, I was reading about CSS's feature for "@media print".</p>
<p>First, what browsers support it? Since this is an internal feature, it's OK if only the latest browsers support it.</p>
<p>I was thinking of tagging a few DOM elements with a "printable" class, and basically apply "display:none" to everything except those elements with the "printable" class.
Is that doable?</p>
<p>How do I achieve this?</p>
<p>EDIT:
This is what I have so far:</p>
<pre><code><style type="text/css">
@media print {
* {display:none;}
.printable, .printable > * {display:block;}
}
</style>
</code></pre>
<p>But it hides everything. How do I make those "printable" elements visible?</p>
<p>EDIT:
Trying now the negative approach</p>
<pre><code><style type="text/css">
@media print {
body *:not(.printable *) {display:none;}
}
</style>
</code></pre>
<p>This looks good in theory, however it doesn't work. Maybe "not" doesn't support advanced css ...</p> | 3,463,801 | 7 | 2 | null | 2010-08-12 00:04:52.863 UTC | 6 | 2022-01-17 19:55:48.767 UTC | 2010-08-12 00:54:15.11 UTC | null | 25,645 | null | 25,645 | null | 1 | 41 | css|printing|css-selectors | 73,946 | <p>Start <a href="http://www.alistapart.com/articles/goingtoprint/" rel="noreferrer">here</a>. But basically what you are thinking is the correct approach.</p>
<blockquote>
<p>Thanks, Now my question is actually
becoming: How do I apply CSS to a
class AND ALL OF ITS DESCENDANT
ELEMENTS? So that I can apply
"display:block" to whatever is in the
"printable" zones.</p>
</blockquote>
<p>If an element is set to <code>display:none;</code> all its children will be hidden as well. But in any case. If you want a style to apply to all children of something else, you do the following:</p>
<pre><code>.printable * {
display: block;
}
</code></pre>
<p>That would apply the style to all children of the "printable" zone.</p> |
3,580,013 | Should I use past or present tense in git commit messages? | <p>I <a href="https://web.archive.org/web/20100827225248/http://progit.org/book/ch5-2.html" rel="noreferrer">read once</a> that git commit messages should be in the imperative present tense, e.g. "Add tests for x". I always find myself using the past tense, e.g. "Added tests for x" though, which feels a lot more natural to me.</p>
<p><a href="http://github.com/jquery/jquery/commit/c5382ad7c118ca54dde630b6c7146f1c3b6afb80" rel="noreferrer">Here's a recent John Resig commit</a> showing the two in one message:</p>
<blockquote>
<p>Tweak some more jQuery set results in the manipulation tests. Also fixed the order of the expected test results.</p>
</blockquote>
<p>Does it matter? Which should I use?</p> | 3,580,764 | 7 | 13 | null | 2010-08-26 22:21:20.07 UTC | 198 | 2022-05-17 17:13:16.23 UTC | 2021-12-16 06:32:56.443 UTC | null | 947,271 | null | 49,376 | null | 1 | 644 | git|git-commit|conventions|commit-message | 133,589 | <p>The preference for present-tense, imperative-style commit messages comes from Git itself. From <a href="https://git.kernel.org/pub/scm/git/git.git/tree/Documentation/SubmittingPatches?h=v2.36.1#n181" rel="noreferrer">Documentation/SubmittingPatches</a> in the Git repo:</p>
<blockquote>
<p>Describe your changes in imperative mood, e.g. "make xyzzy do frotz"
instead of "[This patch] makes xyzzy do frotz" or "[I] changed xyzzy
to do frotz", as if you are giving orders to the codebase to change
its behavior.</p>
</blockquote>
<p>So you'll see a lot of Git commit messages written in that style. If you're working on a team or on open source software, it is helpful if everyone sticks to that style for consistency. Even if you're working on a private project, and you're the only one who will ever see your git history, it's helpful to use the imperative mood because it establishes good habits that will be appreciated when you're working with others.</p> |
3,700,637 | How do I correctly set an association between two objects in the Entity Framework 4 Entitydesigner? | <p>For a new project I'm trying to create my business classes first and create the real database tables later. Therefore I'm using the Entity Framework 4 Designer. A created a new "ADO.Net Entity Data model" file, with the extension .edmx.</p>
<p>I created two Entities:<br>
<img src="https://i.stack.imgur.com/w65e1.png" alt="alt text"></p>
<p>I want to add a 1 to nc relation between Product -> Group. If I'd created the MSSQL database first, I would have added a column IDGroup to the Table Product and referenced Product.IDGroup to Group.IDGroup. As far as I can see, I can't add such association in the designer if I add a new Property called IDGroup to the Product Entity</p>
<p>This is how I add the mapping:
<img src="https://i.stack.imgur.com/dcPvl.png" alt="alt text"></p>
<p>Which results in:<br>
<img src="https://i.stack.imgur.com/JQ8WB.png" alt="alt text"></p>
<p>Now the part what this question is about: If I add two tables from an existing MSSQL database to the edmx file, I'll get the compile error:</p>
<pre><code>Error 3027: No mapping specified for the following EntitySet/AssociationSet - GroupSet, ProductSet
</code></pre>
<p>What does that error mean and what must I do to fix this?
If I delete those two tables, I'll receive a warning instead:</p>
<pre><code>Error 2062: No mapping specified for instances of the EntitySet and AssociationSet in the EntityContainer myContainer.
</code></pre>
<p>Something tells me, I'm doing this all wrong and this is just basic stuff. How can I do it right?</p> | 3,703,465 | 8 | 1 | null | 2010-09-13 13:04:54.107 UTC | 7 | 2017-01-25 22:25:59.29 UTC | null | null | null | null | 225,808 | null | 1 | 54 | c#|asp.net|entity-framework-4 | 59,179 | <p>I just ran into this myself & when I Googled it (I hit your question).</p>
<p>I was able to double click on the line (association line) in the designer. Fill in the properties there and I got it working.</p>
<p>I also had to close VS and re-open it to get some of the errors reported to go away...</p>
<p>Can't say this is the correct answer - just fumbling around and seeming to get results.</p> |
8,322,550 | How to activate the mysql database in xampp on windows platform? | <p>I've installed XAMPP on my Windows XP. I started the XAMPP control panel and it shows apache and mysql are running.</p>
<p>When I check the status by going to <code>localhost/xampp</code> it shows:</p>
<pre><code>mysql : deactivated
</code></pre>
<p>When I run php files that access the mysql database, it shows the following errors:</p>
<pre><code>Warning: mysql_connect() [function.mysql-connect]: [2002] No connection could
be made because the target machine actively refused it. (trying to connect
via tcp://localhost:3306) in C:\xampp\htdocs\Elo_algorithm.php on
line 18
</code></pre>
<p>I've been through the XAMPP troubleshooting page and FAQ but I don't understand what to do. The XAMPP control panel shows mysql is running, but xampp status shows: <code>deactivated</code>.</p>
<p>What is going on here?</p> | 8,322,709 | 5 | 2 | null | 2011-11-30 07:35:43.053 UTC | null | 2015-10-01 20:56:23.69 UTC | 2013-08-12 01:18:50.32 UTC | null | 445,131 | null | 1,029,133 | null | 1 | 1 | php|xampp | 41,190 | <p>You should view in the xampp installation the file "\xampp\mysql\data\mysql_error.log".</p>
<p>This file contais the error log of MySQL and in it you can detect any problem like por in use.</p>
<p>For example, this lines of log show that the port 3306 (the mysql default) is used by another application and can't be accessed.</p>
<pre><code>111130 8:39:56 [ERROR] Can't start server: Bind on TCP/IP port: No such file or directory
111130 8:39:56 [ERROR] Do you already have another mysqld server running on port: 3306 ?
111130 8:39:56 [ERROR] Aborting
</code></pre>
<p>If all in the MySQL is correct probably the problem is related to the driver in the php application. Currently PHP has two MySQL connector types, the "mysql" and the "mysqli", MySQL "mysql" connector, that use "<strong>mysql_</strong>" (the method that you are using to connect is mysql_connect) prefixed functions, is used for old MySQL 4 applications and when the MySQL 5.x if is in configured with the "old password" parameter. The "mysqli" is used for the new mysql 5.x versions and in php you must use "<strong>mysqli_</strong>" prefixed functions like "mysqli_connect. </p>
<p>The version used by the lastest versions of xampp is MySQL 5.5 and you require to used the mysqli connector.</p> |
4,473,216 | Diagnose ObjectDisposedException "Safe handle has been closed" | <p>I have a C# application which is hitting an ObjectDisposedException with the message </p>
<blockquote>
<p>Safe handle has been closed</p>
</blockquote>
<p>This happens as soon as I launch the application.</p>
<p>Sadly the stack trace is really unhelpful (see below). Is there any way for me to determine what call was being attempted asynchronously here? </p>
<p>Does DoAsyncCall() really imply an async method call?</p>
<blockquote>
<p>mscorlib.dll!System.Threading.EventWaitHandle.Set() + 0xe bytes<br>
mscorlib.dll!System.Runtime.Remoting.Messaging.AsyncResult.SyncProcessMessage(System.Runtime.Remoting.Messaging.IMessage
msg) + 0x12f bytes<br>
mscorlib.dll!System.Runtime.Remoting.Messaging.StackBuilderSink.AsyncProcessMessage(System.Runtime.Remoting.Messaging.IMessage
msg, System.Runtime.Remoting.Messaging.IMessageSink replySink =
{System.Runtime.Remoting.Messaging.AsyncResult}) + 0x279 bytes<br>
mscorlib.dll!System.Runtime.Remoting.Proxies.AgileAsyncWorkerItem.DoAsyncCall()
+ 0x32 bytes mscorlib.dll!System.Runtime.Remoting.Proxies.AgileAsyncWorkerItem.ThreadPoolCallBack(object
o) + 0x28 bytes<br>
mscorlib.dll!System.Threading._ThreadPoolWaitCallback.WaitCallback_Context(object
state) + 0x2f bytes<br>
mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext
executionContext, System.Threading.ContextCallback callback, object
state) + 0x6f bytes<br>
mscorlib.dll!System.Threading._ThreadPoolWaitCallback.PerformWaitCallbackInternal(System.Threading._ThreadPoolWaitCallback
tpWaitCallBack) + 0x53 bytes<br>
mscorlib.dll!System.Threading._ThreadPoolWaitCallback.PerformWaitCallback(object
state) + 0x59 bytes</p>
</blockquote> | 4,592,214 | 3 | 0 | null | 2010-12-17 17:35:06.373 UTC | 2 | 2018-05-16 17:42:08.433 UTC | 2015-10-01 14:57:23.067 UTC | null | 2,686,013 | null | 325,129 | null | 1 | 18 | c#|debugging | 41,115 | <p>The problem was caused by my use of a using(){} block.</p>
<pre><code> using (WaitHandle handle = asyncResponse.AsyncWaitHandle)
{
asyncResponse.AsyncWaitHandle.WaitOne();
string response = asyncRequest.EndInvoke(asyncResponse);
asyncResponse.AsyncWaitHandle.Close();
return response;
}
</code></pre>
<p>When the calling thread is interrupted the using block is still calling Close on the WaitHandle.</p> |
4,166,445 | Anonymous functions syntax in CoffeeScript | <p>I've been looking at <a href="http://jashkenas.github.com/coffee-script/">CoffeeScript</a> and I'm not understanding how you would write code like this. How does it handle nested anonymous functions in its syntax?</p>
<pre><code>;(function($) {
var app = $.sammy(function() {
this.get('#/', function() {
$('#main').text('');
});
this.get('#/test', function() {
$('#main').text('Hello World');
});
});
$(function() {
app.run()
});
})(jQuery);
</code></pre> | 4,166,527 | 3 | 1 | null | 2010-11-12 15:56:44.523 UTC | 9 | 2013-02-06 11:21:01.737 UTC | 2010-11-12 16:03:26.817 UTC | null | 149,391 | null | 411,929 | null | 1 | 31 | javascript|coffeescript | 33,701 | <p>didn't actually compile it, but this should work</p>
<pre><code>(($) ->
app = $.sammy ->
this.get '#/', ->
$('#main').text ''
this.get '#/test', ->
$('#main').text 'Hello World'
$(->
app.run()
)
)(jQuery);
</code></pre> |
4,813,307 | The model item is of type CookMeIndexViewModel, but requires a model item of type IEnumerable<CookMeIndexViewModel> | <p>I am following along with the music store example to try learn ASP.NET MVC. I'm creating a cookbook application. </p>
<p>I have created my viewmodel that looks like this:</p>
<pre><code>namespace CookMe_MVC.ViewModels
{
public class CookMeIndexViewModel
{
public int NumberOfReceipes { get; set; }
public List<string> ReceipeName { get; set; }
}
}
</code></pre>
<p>my controller looks like this </p>
<pre><code>public ActionResult Index()
{
var meals= new List<string> { "Dinner 1", "Dinner 2", "3rd not sure" };
//create the view model
var viewModel = new CookMeIndexViewModel
{
NumberOfReceipes = meals.Count(),
ReceipeName = meals
};
return View(viewModel);
}
</code></pre>
<p>Finally my view looks like this </p>
<pre><code> @model IEnumerable<CookMe_MVC.ViewModels.CookMeIndexViewModel>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th></th>
<th>
Meals
</th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
<td>
@item.ReceipeName
</td>
</tr>
}
</table>
</code></pre>
<p>I get this error. </p>
<blockquote>
<p>The model item passed into the dictionary is of type <code>CookMeIndexViewModel</code>, but this dictionary requires a model item of type <code>IEnumerable<CookMeIndexViewModel></code>.</p>
</blockquote>
<p>I have followed the example. I can't see what I am doing wrong. Should I be returning my viewmodel as a generic list?</p> | 4,813,376 | 3 | 0 | null | 2011-01-27 06:16:26.283 UTC | 10 | 2016-01-05 14:39:05.447 UTC | 2016-01-05 14:39:05.447 UTC | null | 4,551,041 | null | 293,545 | null | 1 | 32 | asp.net|asp.net-mvc-3|asp.net-mvc-viewmodel | 90,924 | <p>In your view you are using <code>@model IEnumerable<CookMe_MVC.ViewModels.CookMeIndexViewModel></code> which indicates that the model expected by the View is of type IEnumerable of CookMeIndexViewModel.</p>
<p>However in the controller you are passing an object of type CookMeIndexViewModel as a model <code>return View(viewModel);</code> hence the error.</p>
<p>Either change the view to have <code>@model CookMe_MVC.ViewModels.CookMeIndexViewModel</code></p>
<p>or pass a IEnumerable of CookMeIndexViewModel as model to the view in controller as given below:</p>
<pre><code>public ActionResult Index()
{
var meals= new List<string> { "Dinner 1", "Dinner 2", "3rd not sure" };
//create the view model
var viewModel = new CookMeIndexViewModel
{
NumberOfReceipes = meals.Count(),
ReceipeName = meals
};
List<CookMeIndexViewModel> viewModelList = new List<CookMeIndexViewModel>();
viewModelList.Add(viewModel);
return View(viewModelList);
}
</code></pre> |
4,503,606 | annotation equivalent of <aop:scoped-proxy> | <p>I am moving from an xml config to annoations. i want to convert a session scoped bean that is </p>
<pre><code><aop:scoped-proxy>
</code></pre>
<p>can this be done with annotations, and if not, what can i do to still keep that declaration working?</p>
<p><strong>edit:</strong>
I am interested in doing this in Spring 2.5</p> | 5,725,517 | 3 | 0 | null | 2010-12-21 20:29:25.91 UTC | 13 | 2019-02-11 18:19:23.01 UTC | 2010-12-21 23:41:11.56 UTC | null | 26,188 | null | 26,188 | null | 1 | 45 | spring|spring-aop | 31,151 | <p>in the spring context xml, do something like:</p>
<pre><code><context:component-scan base-package="com.startup.failure" scoped-proxy="interfaces" />
</code></pre>
<p>Note that you would need to write interfaces for all classes in that package, though.</p> |
4,629,571 | ASP.NET, VB: checking which items of a CheckBoxList are selected | <p>I know this is an extremely basic question, but I couldn't find how to do this in VB... I have a CheckBoxList where one of the options includes a textbox to fill in your own value. So I need to have that textbox become enabled when its checkbox (a ListItem in the CheckBoxList) is checked. This is the code behind, I'm not sure what to put in my If statement to test if that certain ListItem is checked.</p>
<pre><code>Protected Sub CheckBoxList1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles CheckBoxList1.SelectedIndexChanged
If ___ Then
txtelect.Enabled = True
Else
txtelect.Enabled = False
End If
End Sub
</code></pre> | 4,629,766 | 4 | 1 | null | 2011-01-07 19:44:02.173 UTC | null | 2018-05-06 07:55:03.557 UTC | 2012-04-03 21:09:34.133 UTC | null | 3,043 | null | 543,843 | null | 1 | 3 | asp.net|vb.net|selecteditem|checkboxlist|listitem | 48,924 | <p>You can loop through the checkboxes in a CheckBoxList, checking each to see if it is checked. Try something like this:</p>
<pre><code>For Each li As ListItem In CheckBoxList1.Items
If li.Value = "ValueOfInterest" Then
'Ok, this is the CheckBox we care about to determine if the TextBox should be enabled... is the CheckBox checked?
If li.Selected Then
'Yes, it is! Enable TextBox
MyTextBox.Enabled = True
Else
'It is not checked, disable TextBox
MyTextBox.Enabled = False
End If
End If
Next
</code></pre>
<p>The above code would be placed in the CheckBoxList's <code>SelectedIndexChanged</code> event handler.</p> |
4,716,485 | How do I add a label, or other element dynamically to a windows form panel? | <p>So this is probably a pretty basic question, but I am working with dragging and dropping ListBox Items onto a panel which will create components depending on the value. </p>
<p>As an easy example, I need it to be able to create a new Label on the panel when an item from the ListBox is dropped onto the panel.</p>
<p>I have the following code, but am not sure how to dynamically add the Label to the panel once it is dropped.</p>
<p>Here is my sample code...</p>
<pre><code>namespace TestApp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
listBox1.Items.Add("First Name");
listBox1.Items.Add("Last Name");
listBox1.Items.Add("Phone");
}
private void listBox1_MouseDown(object sender, MouseEventArgs e)
{
ListBox box = (ListBox)sender;
String selectedValue = box.Text;
DoDragDrop(selectedValue.ToString(), DragDropEffects.Copy);
}
private void panel1_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.Text))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
private void panel1_DragDrop(object sender, DragEventArgs e)
{
Label newLabel = new Label();
newLabel.Name = "testLabel";
newLabel.Text = e.Data.GetData(DataFormats.Text).ToString();
//Do I need to call either of the following code to make it do this?
newLabel.Visible = true;
newLabel.Show();
panel1.Container.Add(newLabel);
}
}
</code></pre>
<p>}</p> | 4,716,710 | 4 | 0 | null | 2011-01-17 18:27:01.523 UTC | 1 | 2011-02-06 06:54:13.093 UTC | null | null | null | null | 180,253 | null | 1 | 8 | c#|.net|windows|winforms | 68,083 | <pre><code> //Do I need to call either of the following code to make it do this?
newLabel.Visible = true;
newLabel.Show();
</code></pre>
<p>is unnecessary.</p>
<hr>
<pre><code>newLabel.AutoSize = true;
</code></pre>
<p>is, most probably, necessary to give it a size.</p>
<hr>
<pre><code> panel1.Container.Add(newLabel);
</code></pre>
<p>must be replaced by</p>
<pre><code> newLabel.Parent = panel1;
</code></pre>
<h2>But, your method should work, unless the drag doesn't work.</h2>
<hr>
<p>Found the bug. It must be <code>panel1.Controls.Add(newLabel);</code> or <code>newLabel.Parent = panel1;</code> instead of <code>panel1.Container.Add(newLabel);</code>. <code>Container</code> is something else.</p> |
4,111,398 | Notify activity from service | <p>I'm trying to start a <code>Service</code> from my <code>Activity</code> to look out for changes on a web page, it's a private app so I don't bother the battery life...</p>
<p>But I'd like to pass data from my <code>Service</code> to my <code>Activity</code>... I can't seem to find a way to call the <code>Activity</code> from my <code>Service</code>. How can I achieve this?</p> | 4,112,657 | 4 | 0 | null | 2010-11-06 01:22:02.827 UTC | 22 | 2015-02-12 17:01:53.39 UTC | 2015-02-12 17:01:53.39 UTC | null | 1,469,208 | null | 219,554 | null | 1 | 43 | android|service|android-activity | 32,514 | <p>As Alex indicated, you can bind to the service and pass some sort of listener or callback to the service to use on events.</p>
<p>Or, you can use a broadcast <code>Intent</code>, perhaps using methods like <code>setPackage()</code> on the <code>Intent</code> to limit the scope of the broadcast.</p>
<p>Or, you can use <code>createPendingResult()</code> to create a <code>PendingIntent</code> that you pass as an <code>Intent</code> extra to the service -- the service can then use that <code>PendingIntent</code> to trigger <code>onActivityResult()</code> in your activity.</p>
<p>Or, you can use a <code>ResultReceiver</code>.</p>
<p>Or, you can use a <code>Messenger</code>.</p>
<p>(admittedly, I have not tried those latter two approaches, but I think they will work here)</p> |
4,130,364 | Does Ruby have a string.startswith("abc") built in method? | <p>Does Ruby have a <code>some_string.starts_with("abc")</code> method that's built in?</p> | 4,130,600 | 4 | 2 | null | 2010-11-09 03:51:35.483 UTC | 15 | 2022-04-20 22:41:43.223 UTC | 2015-10-17 22:16:11.587 UTC | null | 4,948,732 | null | 39,677 | null | 1 | 219 | ruby | 142,301 | <p>It's called <a href="http://RubyDoc.Info/docs/ruby-core/1.9.2/String#start_with%3F-instance_method" rel="noreferrer"><code>String#start_with?</code></a>, not <code>String#startswith</code>: In Ruby, the names of boolean-ish methods end with <code>?</code> and the words in method names are separated with an <code>_</code>. On Rails you can use the alias <a href="https://apidock.com/rails/ActiveSupport/CoreExtensions/String/StartsEndsWith/starts_with%3F" rel="noreferrer"><code>String#starts_with?</code></a> (note the plural - and note that this method is deprecated). Personally, I'd prefer <code>String#starts_with?</code> over the actual <code>String#start_with?</code></p> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.