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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
24,626,908 | How to get rid of extra space below svg in div element | <p>Here is an illustration of the problem (tested in Firefox and Chrome):</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div style="background-color: red;"><svg height="100px" width="100" style="background-color: blue;"></svg></div></code></pre>
</div>
</div>
</p>
<p><a href="http://jsfiddle.net/EXLSF/" rel="noreferrer">View on JSFiddle</a></p>
<p>Notice the extra <code>red</code> space inside the <code>div</code> below the blue <code>svg</code>.</p>
<p>Already tried setting <code>padding</code> and <code>margin</code> of both elements to <code>0</code>, but with no luck.</p> | 24,626,986 | 8 | 2 | null | 2014-07-08 08:19:34.1 UTC | 23 | 2021-11-29 19:26:32.04 UTC | 2020-02-18 02:57:35.777 UTC | null | 924,299 | null | 1,981,832 | null | 1 | 127 | html|css|svg | 52,985 | <p>You need <code>display: block;</code> on your <code>svg</code>.</p>
<pre><code><svg style="display: block;"></svg>
</code></pre>
<p>This is because inline-block elements (like <code><svg></code> and <code><img></code>) sit on the text baseline. The extra space you are seeing is the space left to accommodate character descenders (the tail on 'y', 'g' etc).</p>
<p>You can also use <code>vertical-align:top</code> if you need to keep it <code>inline</code> or <code>inline-block</code></p> |
24,728,933 | Sort dictionary alphabetically when the key is a string (name) | <p>First, I know there are a LOT of posts on dictionary sorting but I couldn't find one that was exactly for my case - and I am just not understanding the sorted(...lambda) stuff - so here goes.</p>
<p>Using Python 3.x I have a dictionary like this:</p>
<pre><code>dictUsers[Name] = namedTuple(age, address, email, etc...)
</code></pre>
<p>So as an example my dictionary looks like</p>
<pre><code>[John]="29, 121 bla, [email protected]"
[Jack]="32, 122 ble, [email protected]"
[Rudy]="42, 123 blj, [email protected]"
</code></pre>
<p>And right now for printing I do the following (where response is a dictionary):</p>
<pre><code>for keys, values in response.items():
print("Name= " + keys)
print (" Age= " + values.age)
print (" Address= " + values.address)
print (" Phone Number= " + values.phone)
</code></pre>
<p>And when the user asks to print out the database of users I want it to print in alphabetical order based on the "name" which is used as the KEY.</p>
<p>I got everything to work - but it isn't sorted - and before starting to sort it manually I thought maybe there was a built-in way to do it ...</p>
<p>Thanks,</p> | 24,728,952 | 7 | 3 | null | 2014-07-14 02:52:29.813 UTC | 4 | 2021-08-08 18:07:25.71 UTC | null | null | null | null | 1,030,647 | null | 1 | 25 | python|sorting|dictionary | 81,622 | <p>simple algorithm to sort dictonary keys in alphabetical order, First sort the keys using <code>sorted</code></p>
<pre><code>sortednames=sorted(dictUsers.keys(), key=lambda x:x.lower())
</code></pre>
<p>for each key name retreive the values from the dict</p>
<pre><code>for i in sortednames:
values=dictUsers[i]
print("Name= " + i)
print (" Age= " + values.age)
print (" Address= " + values.address)
print (" Phone Number= " + values.phone)
</code></pre> |
1,228,833 | Sharing a Java synchronized block across a cluster, or using a global lock? | <p>I have some code that I want to only allow access to by one thread. I know how to accomplish this using either <code>synchronized</code> blocks or methods, but will this work in a clustered environment?</p>
<p>The target environment is WebSphere 6.0, with 2 nodes in the cluster.</p>
<p>I have a feeling that <code>synchronized</code> won't work, since each instance of the application on each node will have its own JVM, right?</p>
<p>What I am trying to do here is perform some updates to database records when the system is booted. It will look for any database records that are older that the version of the code, and perform specific tasks to update them. I only want one node to perform these upgrades, since I want to be sure that each work item is only upgraded once, and performance of these upgrades is not a big concern, since it only happens at application startup, and it only really does anything when the code has been changed since the last time it started up.</p>
<p>The database is DB2v9, and I am accessing it directly via JNDI (no ORM layer).</p>
<p>It has been suggested that a global lock might be the way to go here, but I'm not sure how to do that.</p>
<p>Does anyone have any pointers in this arena?</p>
<p>Thanks!</p> | 1,228,929 | 5 | 5 | null | 2009-08-04 17:25:17.603 UTC | 9 | 2022-07-20 11:36:11.743 UTC | 2012-07-02 07:02:52.517 UTC | null | 97,160 | null | 4,257 | null | 1 | 17 | java|sql|locking|db2|cluster-computing | 19,577 | <p>You are correct that synchronization across processes will not work using the Java synchronization constructs. Fortunately, your problem really isn't one of code synchronization, but rather of synchronizing interactions with the database.</p>
<p>The right way to deal with this problem is with database level locks. Presumably you have some table that contains a db schema version, so you should make sure to lock that table for the duration of the startup/upgrade process.</p>
<p>The precise sql/db calls involved would probably be more clear if you specified your database type (DB2?) and access method (raw sql, jpa, etc).</p>
<p><strong>Update (8/4/2009 2:39PM)</strong>: I suggest the <a href="http://publib.boulder.ibm.com/infocenter/db2luw/v8/index.jsp?topic=/com.ibm.db2.udb.doc/admin/r0000972.htm" rel="nofollow noreferrer">LOCK TABLE</a> statement on some table holding the version # of the schema. This will serialize access to that table preventing two instances from running through the upgrade code at once.</p> |
809,607 | NSUserDefaults: Dumping the structure of NSUserDefaults's standardUserDefaults | <p>Does anyone know of a quick way to dump the standardUserDefaults of NSUserDefaults via NSLog? This is what I have:</p>
<pre><code>NSLog(@"NSUserDefaults dump: %@", [NSUserDefaults standardUserDefaults]);
</code></pre>
<p>But it returns:</p>
<pre><code>NSUserDefaults dump: <NSUserDefaults: 0x50b520>
</code></pre>
<p>...which is not quite what I'm looking for. I'd really like to have key-value pairs.</p>
<p>Any help or a point in the right direction would be greatly appreciated. Cheers!</p> | 826,644 | 6 | 0 | null | 2009-04-30 23:41:19.8 UTC | 14 | 2014-02-27 08:12:58.51 UTC | null | null | null | null | 98,842 | null | 1 | 17 | objective-c|cocoa-touch | 10,720 | <p>Thanks to Don McCaughey, my business partner and friend, for fixing up my code for me and supply a concise answer. To share it with the rest of you here is a code snippet:</p>
<pre><code> NSDictionary *bundleInfo = [[NSBundle mainBundle] infoDictionary];
NSString *bundleId = [bundleInfo objectForKey: @"CFBundleIdentifier"];
NSUserDefaults *appUserDefaults = [[NSUserDefaults alloc] init];
NSLog(@"Start dumping userDefaults for %@", bundleId);
NSLog(@"userDefaults dump: %@", [appUserDefaults persistentDomainForName: bundleId]);
NSLog(@"Finished dumping userDefaults for %@", bundleId);
[appUserDefaults release];
</code></pre>
<p>As you can see, everyone who was answering the question was on the right track, but no code offered up was the solution - until Don's editing of our code in source control. Thanks All!</p> |
1,240,057 | Integrating Automated Web Testing Into Build Process | <p>I'm looking for suggestions to improve the process of automating functional testing of a website. Here's what I've tried in the past.</p>
<p>I used to have a test project using <a href="http://watin.sourceforge.net/" rel="nofollow noreferrer">WATIN</a>. You effectively write what look like "unit tests" and use WATIN to automate a browser to click around your site etc.</p>
<p>Of course, you need a site to be running. So I made the test actually copy the code from my web project to a local directory and started a web server pointing to that directory before any of the tests run.</p>
<p>That way, someone new could simply get latest from our source control and run our build script, and see all the tests run. They could also simply run all the tests from the IDE.</p>
<p>The problem I ran into was that I spent a lot of time maintaining the code to set up the test environment more than the tests. Not to mention that it took a long time to run because of all that copying. Also, I needed to test out various scenarios including installation, meaning I needed to be able to set the database to various initial states.</p>
<p>I was curious on what you've done to automate functional testing to solve some of these issues and still keep it simple.</p>
<p><strong>MORE DETAILS</strong>
Since people asked for more details, here it is. I'm running ASP.NET using Visual Studio and Cassini (the built in web server). My unit tests run in MbUnit (but that's not so important. Could be NUnit or XUnit.NET). Typically, I have a separate unit test framework run all my WATIN tests. In the AssemblyLoad phase, I start the webserver and copy all my web application code locally.</p>
<p>I'm interested in solutions for any platform, but I may need more descriptions on what each thing means. :)</p> | 1,248,148 | 6 | 2 | null | 2009-08-06 16:30:55.8 UTC | 18 | 2017-12-04 07:42:56.367 UTC | 2009-08-08 05:04:36.98 UTC | null | 598 | null | 598 | null | 1 | 19 | asp.net|testing|automated-tests|functional-testing|web-testing | 3,348 | <p>Phil,</p>
<p>Automation can just be hard to maintain, but the more you use your automation for deployment, the more you can leverage it for test setup (and vice versa).</p>
<p>Frankly, it's easier to evolve automation code, factoring it and refactoring it into specific, small units of functionality when using a build tool that isn't<br>
just driving statically-compiled, pre-factored units of functionality, as is the case with NAnt and MSBuild. This is one of the reasons that many people who were relatively early users of toole like NAnt have moved off to Rake. The freedom to treat build code as any other code - to cotinually evolve its content and shape - is greater with Rake. You don't end up with the same stasis in automation artifacts as easily and as quickly with Rake, and it's a lot easier to script in Rake than NAnt or MSBuild.</p>
<p>So, some part of your struggle is inherently bound up in the tools. To keep your automation sensible and maintained, you should be wary of obstructions that static build tools like NAnt and MSBuild impose.</p>
<p>I would suggest that you not couple your test environment boot-strapping from assembly load. That's an inside-out coupling that only serves brief convenience. There's nothing wrong (and, likely everything right) with going to the command line and executing the build task that sets up the environment before running tests either from the IDE or from the command line, or from an interactive console, like the C# REPL from the Mono Project, or from IRB.</p>
<p>Test data setup is simply just a pain in the butt sometimes. It has to be done.</p>
<p>You're going to need a library that you can call to create and clean up database state. You can make those calls right from your test code, but I personally tend to avoid doing this because there is more than one good use of test data or sample data control code.</p>
<p>I drive all sample data control from HTTP. I write controllers with actions specifically for controlling sample data and issue GETs against those actions through Selenium. I use these to create and clean up data. I can compose GETs to these actions to create common scenarios of setup data, and I can pass specific values for data as request parameters (or form parameters if needs be).</p>
<p>I keep these controllers in an area that I usually call "test_support".</p>
<p>My automation for deploying the website does not deploy the test_support area or its routes and mapping. As part of my deployment verification automation, I make sure that the test_support code is not in the production app.</p>
<p>I also use the test_support code to automate control over the entire environment - replacing services with fakes, turning off subsystems to simulate failures and failovers, activating or deactivating authentication and access control for functional testing that isn't concerned with these facets, etc. </p>
<p>There's a great secondary value to controlling your web app's sample data or test data from the web: when demoing the app, or when doing exploratory testing, you can create the data scenarios you need just by issuing some gets against known (or guessable) urls in the test_support area. Really making a disciplined effort to stick to restful routes and resource-orientation here will really pay off.</p>
<p>There's a lot more to this functional automation (including test, deployment, demoing, etc) so the better designed these resources are, the better the time you'll have maintaining them over the long hall, and the more opportunities you'll find to leverage them in unforseen but beneficial ways.</p>
<p>For example, writing domain model code over the semantic model of your web pages will help create much more understandable test code and decrease the brittleness. If you do this well, you can use those same models with a variety of different drivers so that you can leverage them in stress tests and load tests as well as functional test as well as using them from the command line as exploratory tools. By the way, this kind of thing is easier to do when you're not bound to driver types as you are when you use a static language. There's a reason why many leading testing thinkers and doers work in Ruby, and why Watir is written in Ruby. Reuse, composition, and expressiveness is much easier to achieve in Ruby than C# test code. But that's another story.</p>
<p>Let's catch up sometime and talk more about the other 90% of this stuff :)</p> |
1,064,361 | Unable to show a Git tree in terminal | <p><a href="http://killswitchcollective.com/articles/36_git_it_got_it_good" rel="noreferrer">Killswitchcollective.com's old article, 30 June 2009</a>, has the following inputs and outputs</p>
<pre><code>git co master
git merge [your_branch]
git push
upstream A-B-C-D-E A-B-C-D-E-F-G
\ ----> \
your branch C-D-E G
</code></pre>
<p>I am interested how you get the tree like-view of commits in your terminal without using Gitk or Gitx in OS/X.</p>
<p><strong>How can you get the tree-like view of commits in terminal?</strong></p> | 1,064,431 | 6 | 1 | null | 2009-06-30 15:30:44.8 UTC | 268 | 2019-03-12 17:34:09.36 UTC | 2015-08-05 10:56:21.227 UTC | null | 600,833 | null | 54,964 | null | 1 | 533 | git|terminal|tree|console|revision-history | 426,077 | <p>How can you get the tree-like view of commits in terminal?</p>
<pre><code>git log --graph --oneline --all
</code></pre>
<p>is a good start.</p>
<p>You may get some strange letters. They are ASCII codes for colors and structure. To solve this problem add the following to your <code>.bashrc</code>:</p>
<pre><code>export LESS="-R"
</code></pre>
<p>such that you do not need use Tig's ASCII filter by</p>
<pre><code>git log --graph --pretty=oneline --abbrev-commit | tig // Masi needed this
</code></pre>
<p>The article <a href="http://www.gitready.com/intermediate/2009/01/26/text-based-graph.html" rel="noreferrer">text-based graph from Git-ready</a> contains other options:</p>
<pre><code>git log --graph --pretty=oneline --abbrev-commit
</code></pre>
<p><img src="https://i.stack.imgur.com/gTXgj.png" alt="git log graph"></p>
<p>Regarding the article you mention, I would go with <a href="https://stackoverflow.com/questions/1064361/unable-to-show-a-git-tree-in-terminal/1064415#1064415">Pod's answer</a>: ad-hoc hand-made output.</p>
<hr>
<p><strong><a href="https://stackoverflow.com/users/46058/jakub-narbski">Jakub Narębski</a></strong> mentions in the comments <strong><a href="http://jonas.nitro.dk/tig/manual.html" rel="noreferrer">tig</a></strong>, a ncurses-based text-mode interface for git. See <a href="http://jonas.nitro.dk/tig/releases/" rel="noreferrer">their releases</a>.<br>
It added <a href="http://markmail.org/message/b4nxlifggqb7nj44" rel="noreferrer">a <code>--graph</code> option</a> back in 2007.</p> |
1,183,645 | "eval" in Scala | <p>Can Scala be used to script a Java application?</p>
<p>I need to load a piece of Scala code from Java, set up an execution scope for it (data exposed by the host application), evaluate it and retrieve a result object from it. </p>
<p>The Scala documentation shows how easy it is to call compiled Scala code from Java (because it gets turned into to regular JVM bytecode).</p>
<p>But how can I evaluate a Scala expression on the fly (from Java or if that is easier, from within Scala) ? </p>
<p>For many other languages, there is the javax.scripting interface. Scala does not seem to support it, and I could not find anything in the Java/Scala interoperability docs that does not rely on ahead-of-time compilation.</p> | 1,185,450 | 6 | 1 | null | 2009-07-26 03:23:21.757 UTC | 17 | 2022-02-15 15:16:54.613 UTC | null | null | null | null | 14,955 | null | 1 | 56 | java|scala|scripting|embedding | 29,595 | <p>Scala is not a scripting language. It may <em>look</em> somewhat like a scripting language, and people may advocate it for that purpose, but it doesn't really fit well within the JSR 223 scripting framework (which is oriented toward dynamically typed languages). To answer your original question, Scala does not have an <code>eval</code> function just like Java does not have an <code>eval</code>. Such a function wouldn't really make sense for either of these languages given their intrinsically static nature.</p>
<p>My advice: rethink your code so that you don't need <code>eval</code> (you rarely do, even in languages which have it, like Ruby). Alternatively, maybe you don't want to be using Scala at all for this part of your application. If you really need <code>eval</code>, try using JRuby. JRuby, Scala and Java mesh very nicely together. It's quite easy to have part of your system in Java, part in Scala and another part (the bit which requires <code>eval</code>) in Ruby.</p> |
30,861,631 | Object.length undefined in javascript | <p>I have an javascript object of arrays like,</p>
<pre><code>var coordinates = {
"a": [
[1, 2],
[8, 9],
[3, 5],
[6, 1]
],
"b": [
[5, 8],
[2, 4],
[6, 8],
[1, 9]
]
};
</code></pre>
<p>but <code>coordinates.length</code> returns undefined.
<a href="http://jsfiddle.net/mpsbhat/3wzb7jen/" rel="noreferrer">Fiddle is here</a>.</p> | 30,861,663 | 3 | 2 | null | 2015-06-16 07:45:19.41 UTC | 8 | 2019-09-04 09:19:30.35 UTC | null | null | null | null | 2,293,455 | null | 1 | 27 | javascript|arrays|object | 59,327 | <p>That's because <code>coordinates</code> is <code>Object</code> not <code>Array</code>, use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in" rel="noreferrer"><code>for..in</code></a></p>
<pre><code>var coordinates = {
"a": [
[1, 2],
[8, 9],
[3, 5],
[6, 1]
],
"b": [
[5, 8],
[2, 4],
[6, 8],
[1, 9]
]
};
for (var i in coordinates) {
console.log(coordinates[i])
}
</code></pre>
<p>or <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys" rel="noreferrer"><code>Object.keys</code></a></p>
<pre><code>var coordinates = {
"a": [
[1, 2],
[8, 9],
[3, 5],
[6, 1]
],
"b": [
[5, 8],
[2, 4],
[6, 8],
[1, 9]
]
};
var keys = Object.keys(coordinates);
for (var i = 0, len = keys.length; i < len; i++) {
console.log(coordinates[keys[i]]);
}
</code></pre> |
32,557,504 | Ionic android build Error - Failed to find 'ANDROID_HOME' environment variable | <p>I am trying to build android for ionic in linux but its showing me an error like this </p>
<pre><code> [Error: Failed to find 'ANDROID_HOME' environment variable.
Try setting setting it manually.
Failed to find 'android' command in your 'PATH'.
Try update your 'PATH' to include path to valid SDK directory.]
ERROR building one of the platforms: Error: /home/kumar/myapp/platforms/android/cordova/build: Command failed with exit code 2
You may not have the required environment or OS to build this project
Error: /home/kumar/myapp/platforms/android/cordova/build: Command failed with exit code 2
at ChildProcess.whenDone (/usr/local/lib/node_modules/cordova/node_modules/cordova-lib/src/cordova/superspawn.js:139:23)
at ChildProcess.EventEmitter.emit (events.js:98:17)
at maybeClose (child_process.js:743:16)
at Process.ChildProcess._handle.onexit (child_process.js:810:5)
</code></pre>
<p>and i've added this in my bashrc file </p>
<pre><code>export ANT_HOME="/usr/bin/ant"
export PATH="$PATH:$ANT_HOME/bin"
export HOME="/home/kumar"
export ANDROID_HOME="$HOME/android-sdk-linux/tools"
export ANDROID_PLATFORM_TOOLS="$HOME/android-sdk-linux/platform-tools"
export PATH="$ANDROID_HOME:$ANDROID_PLATFORM_TOOLS:$PATH"
</code></pre>
<p>I'm thinking i've given the path but i dont know why its showing me this error .. Please help....</p> | 32,557,569 | 12 | 5 | null | 2015-09-14 04:52:00.58 UTC | 12 | 2019-10-23 08:48:23.357 UTC | null | null | null | null | 3,350,086 | null | 1 | 53 | android|linux|cordova|ionic-framework | 129,631 | <p>Android Home should be the root folder of SDK. </p>
<pre><code>export ANDROID_HOME="$HOME/android-sdk-linux"
</code></pre>
<p><strong>EDIT</strong>: Open terminal and type these commands. (yes, on a ternimal , not in bashrc file)</p>
<pre><code>export ANDROID_HOME=~/android-sdk-macosx
PATH=$PATH:$ANDROID_HOME/tools
PATH=$PATH:$ANDROID_HOME/platform-tools
</code></pre>
<p>and then in the same terminal just type <code>android</code>. If configured you would be able to use build commands from this terminal. (it's a temporary solution) </p> |
35,643,192 | Laravel Eloquent limit and offset | <p>This is mine</p>
<pre><code> $art = Article::where('id',$article)->firstOrFail();
$products = $art->products;
</code></pre>
<p>I just wanna take a limit 'product'
This is wrong way</p>
<pre><code> $products = $art->products->offset($offset*$limit)->take($limit)->get();
</code></pre>
<p>Please give me a hand!</p>
<p>Thanks!</p> | 40,635,629 | 10 | 4 | null | 2016-02-26 03:59:00.42 UTC | 19 | 2022-06-19 11:43:53.857 UTC | null | null | null | null | 5,797,796 | null | 1 | 117 | laravel|eloquent|limit|offset | 395,701 | <pre><code>skip = OFFSET
$products = $art->products->skip(0)->take(10)->get(); //get first 10 rows
$products = $art->products->skip(10)->take(10)->get(); //get next 10 rows
</code></pre>
<p>From laravel doc 5.2 <a href="https://laravel.com/docs/5.2/queries#ordering-grouping-limit-and-offset" rel="noreferrer">https://laravel.com/docs/5.2/queries#ordering-grouping-limit-and-offset</a></p>
<blockquote>
<p><strong>skip / take</strong></p>
<p>To limit the number of results returned from the query, or to skip a
given number of results in the query (OFFSET), you may use the skip
and take methods:</p>
<p><code>$users = DB::table('users')->skip(10)->take(5)->get();</code></p>
</blockquote>
<p>In <strong>laravel 5.3</strong> you can write (<a href="https://laravel.com/docs/5.3/queries#ordering-grouping-limit-and-offset" rel="noreferrer">https://laravel.com/docs/5.3/queries#ordering-grouping-limit-and-offset</a>)</p>
<pre><code>$products = $art->products->offset(0)->limit(10)->get();
</code></pre> |
18,090,657 | Getting the CPU, memory usage and free disk space using powershell | <p>Could you help me combine these three scripts to a format that's like this</p>
<pre><code>ComputerName CPUUsageAverage MemoryUsage C PercentFree
xxx 12 50% 30%
</code></pre>
<p>The way I execute this is:
<code>Get-content '.\servers.txt' | Get-CPUusageAverage</code></p>
<p>Here are the scripts:</p>
<p>CPU</p>
<pre><code>Function Get-CPUusageAverage
{
$input|Foreach-Object{Get-WmiObject -computername $_ win32_processor | Measure-Object -property LoadPercentage -Average | Select Average}
}
</code></pre>
<p>Memory</p>
<pre><code> Function get-MemoryUsage
{
$input|Foreach-Object{
gwmi -Class win32_operatingsystem -computername $_ |
Select-Object @{Name = "MemoryUsage"; Expression = { “{0:N2}” -f ((($_.TotalVisibleMemorySize - $_.FreePhysicalMemory)*100)/ $_.TotalVisibleMemorySize) }
}
}
}
</code></pre>
<p>C PercentFree</p>
<pre><code>Function get-CPercentFree
{
$input|ForEach-Object{
Get-WmiObject -Class win32_Volume -ComputerName $_ -Filter "DriveLetter = 'C:'" |
Select-object @{Name = "C PercentFree"; Expression = { “{0:N2}” -f (($_.FreeSpace / $_.Capacity)*100) } }
}
}
</code></pre> | 18,091,659 | 3 | 0 | null | 2013-08-06 21:16:27.33 UTC | 3 | 2016-08-28 02:25:27.54 UTC | null | null | null | null | 414,507 | null | 1 | 5 | powershell | 50,951 | <p>First I would avoid using $input. You can just combine the queries into single function that then outputs a pscustomobject with the data for each computer e.g.:</p>
<pre><code>function Get-ComputerStats {
param(
[Parameter(Mandatory=$true, Position=0,
ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
[ValidateNotNull()]
[string[]]$ComputerName
)
process {
foreach ($c in $ComputerName) {
$avg = Get-WmiObject win32_processor -computername $c |
Measure-Object -property LoadPercentage -Average |
Foreach {$_.Average}
$mem = Get-WmiObject win32_operatingsystem -ComputerName $c |
Foreach {"{0:N2}" -f ((($_.TotalVisibleMemorySize - $_.FreePhysicalMemory)*100)/ $_.TotalVisibleMemorySize)}
$free = Get-WmiObject Win32_Volume -ComputerName $c -Filter "DriveLetter = 'C:'" |
Foreach {"{0:N2}" -f (($_.FreeSpace / $_.Capacity)*100)}
new-object psobject -prop @{ # Work on PowerShell V2 and below
# [pscustomobject] [ordered] @{ # Only if on PowerShell V3
ComputerName = $c
AverageCpu = $avg
MemoryUsage = $mem
PercentFree = $free
}
}
}
cat '.\servers.txt' | Get-ComputerStats | Format-Table
</code></pre> |
21,309,817 | IntelliSense in Razor files (.cshtml) stopped working | <p>Intellisense does not work in razor files:</p>
<p><img src="https://i.stack.imgur.com/HdIDL.jpg" alt="enter image description here"></p>
<p>In my web.conifg file (in the Views folder) is apparently correct:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
<section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
</sectionGroup>
</configSections>
<system.web.webPages.razor>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<pages pageBaseType="System.Web.Mvc.WebViewPage">
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.Optimization" />
<add namespace="MvcSiteMapProvider.Web.Html" />
<add namespace="MvcSiteMapProvider.Web.Html.Models" />
<add namespace="DevTrends.MvcDonutCaching" />
</namespaces>
</pages>
</system.web.webPages.razor>
<appSettings>
<add key="webpages:Enabled" value="false" />
</appSettings>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<handlers>
<remove name="BlockViewHandler" />
<add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
</handlers>
</system.webServer>
</configuration>
</code></pre> | 33,612,416 | 21 | 8 | null | 2014-01-23 13:39:31.89 UTC | 30 | 2022-09-08 14:26:14.247 UTC | 2017-05-31 12:01:37.367 UTC | null | 633,098 | null | 491,181 | null | 1 | 83 | razor|asp.net-mvc-5 | 80,700 | <p>This is what worked for me after IntelliSense suddenly began to bug out and stopped colouring C# code correctly in between the HTML tags in my views:</p>
<hr />
<p>Just delete the contents of the folder at <code>%LOCALAPPDATA%\Microsoft\VisualStudio\16.0_<hash>\ComponentModelCache</code></p>
<hr />
<p><a href="https://i.stack.imgur.com/Bhz43.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Bhz43.png" alt="enter image description here" /></a></p>
<p>As an additional step, you can optionally run the command <code>DevEnv.exe /setup</code> in Developer Command Prompt for VS (as an Administrator) if the above step doesn't resolve the issue.</p> |
1,685,692 | c# : console application - static methods | <p>why in C#, console application, in "program" class , which is default, all methods have to be static along with </p>
<pre><code>static void Main(string[] args)
</code></pre> | 1,685,698 | 5 | 0 | null | 2009-11-06 05:58:58.483 UTC | 11 | 2017-10-16 06:07:22.533 UTC | 2009-11-06 06:03:26.603 UTC | null | 87,053 | null | 71,422 | null | 1 | 46 | c#|static | 80,742 | <p>Member functions don't <em>have</em> to be static; but if they are <em>not</em> static, that requires you to instantiate a <code>Program</code> object in order to call a member method.</p>
<p>With static methods:</p>
<pre><code>public class Program
{
public static void Main()
{
System.Console.WriteLine(Program.Foo());
}
public static string Foo()
{
return "Foo";
}
}
</code></pre>
<p>Without static methods (in other words, requiring you to instantiate <code>Program</code>):</p>
<pre><code>public class Program
{
public static void Main()
{
System.Console.WriteLine(new Program().Foo());
}
public string Foo() // notice this is NOT static anymore
{
return "Foo";
}
}
</code></pre>
<p><code>Main</code> must be static because otherwise you'd have to tell the compiler how to instantiate the <code>Program</code> class, which may or may not be a trivial task.</p> |
1,695,787 | What is quirks mode? | <p>In a lot of articles about design, quirks mode is mentioned.
Anybody have an idea about this thing in plain text and in a development prospective? </p> | 1,695,790 | 6 | 0 | null | 2009-11-08 08:38:25.92 UTC | 14 | 2022-06-27 17:07:51.99 UTC | 2020-08-14 10:15:17.047 UTC | null | 5,395,773 | null | 202,682 | null | 1 | 60 | html|css|quirks-mode | 65,565 | <p>you can read in this links
:</p>
<p><a href="http://en.wikipedia.org/wiki/Quirks_mode" rel="noreferrer">http://en.wikipedia.org/wiki/Quirks_mode</a></p>
<p><a href="http://www.quirksmode.org/css/quirksmode.html" rel="noreferrer">http://www.quirksmode.org/css/quirksmode.html</a></p>
<p><a href="http://www.cs.tut.fi/~jkorpela/quirks-mode.html" rel="noreferrer">http://www.cs.tut.fi/~jkorpela/quirks-mode.html</a></p>
<blockquote>
<p>Modern browsers generally try to
render HTML content according to the
W3C recommendations. However, to
provide compatibility with older web
pages, and to provide additional
"intuitive" functionality, all
browsers support an alternative
"quirks mode".</p>
<p>Quirks mode is not, however, a
standard. The rendering of any page in
quirks mode in different browsers may
be different. Whenever possible, it is
better to adhere to the W3C standards
and try and avoid depending on any
past or present browser quirks.</p>
<p>Generally, quirks mode is turned on
when there is no correct DOCTYPE
declaration, and turned off when there
is a DOCTYPE definition. However,
invalid HTML - with respect to the
chosen DOCTYPE - can also cause the
browser to switch to quirks mode.</p>
<p>More information on the different
quirks modes in different browsers can
be found at <a href="http://QuirksMode.org" rel="noreferrer">QuirksMode.org</a></p>
</blockquote> |
1,607,904 | VIM: Deleting from current position until a space | <p>Often when developing I am confronted with a nested object that I'd like to delete from code in the middle of a line like this:</p>
<pre><code>htmlDoc.WriteLine("<b><h3>" + this.cbAllSyncs.SelectedItem.ToString() + "</h3></b>");
</code></pre>
<p>The part that I'd like to delete is:</p>
<pre><code>this.cbAllSyncs.SelectedItem.ToString()
</code></pre>
<p>I know I can count the number of words and periods and enter <kbd>7</kbd><kbd>d</kbd><kbd>w</kbd> to delete from my current cursor position of "this". However, what I'd love to do is not have to count at all and delete to the space with one command. Is this possible? </p> | 1,607,912 | 6 | 0 | null | 2009-10-22 15:08:50.85 UTC | 49 | 2017-04-16 11:42:41.85 UTC | 2012-11-14 20:45:35.32 UTC | null | 220,060 | null | 82,541 | null | 1 | 198 | vim | 60,378 | <p>Try <kbd>d</kbd><kbd>t</kbd><kbd>space</kbd>. In general <kbd>d</kbd><kbd>t</kbd><kbd>x</kbd> deletes from current position till just before <code>x</code>. Just <kbd>t</kbd><kbd>x</kbd> moves the cursor to just before character <code>x</code> in current line.</p>
<p>To delete up to and including the space, use <kbd>d</kbd><kbd>f</kbd><kbd>space</kbd>.</p> |
1,497,946 | How can I parse a HTML string in Java? | <p>Given the string <code>"<table><tr><td>Hello World!</td></tr></table>"</code>, what is the (easiest) way to get a <a href="http://en.wikipedia.org/wiki/Document_Object_Model" rel="noreferrer">DOM</a> Element representing it?</p> | 1,509,229 | 7 | 0 | null | 2009-09-30 13:00:08.527 UTC | 2 | 2021-04-13 20:02:57.74 UTC | 2009-10-19 17:19:31.78 UTC | null | 63,550 | null | 129,750 | null | 1 | 16 | java|html|parsing | 45,865 | <p>I found this somewhere (don't remember where):</p>
<pre><code> public static DocumentFragment parseXml(Document doc, String fragment)
{
// Wrap the fragment in an arbitrary element.
fragment = "<fragment>"+fragment+"</fragment>";
try
{
// Create a DOM builder and parse the fragment.
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
Document d = factory.newDocumentBuilder().parse(
new InputSource(new StringReader(fragment)));
// Import the nodes of the new document into doc so that they
// will be compatible with doc.
Node node = doc.importNode(d.getDocumentElement(), true);
// Create the document fragment node to hold the new nodes.
DocumentFragment docfrag = doc.createDocumentFragment();
// Move the nodes into the fragment.
while (node.hasChildNodes())
{
docfrag.appendChild(node.removeChild(node.getFirstChild()));
}
// Return the fragment.
return docfrag;
}
catch (SAXException e)
{
// A parsing error occurred; the XML input is not valid.
}
catch (ParserConfigurationException e)
{
}
catch (IOException e)
{
}
return null;
}
</code></pre> |
1,395,356 | How can I make `bin(30)` return `00011110` instead of `0b11110`? | <p>What does the "b" stand for in the output of bin(30): "0b11110"? Is there any way I can get rid of this "b"? How can I get the output of bin() to always return a standard 8 digit output?</p> | 1,395,408 | 7 | 0 | null | 2009-09-08 17:53:38.857 UTC | 13 | 2018-01-17 12:50:22.96 UTC | 2012-10-15 15:56:16.753 UTC | null | 953,482 | null | 153,639 | null | 1 | 50 | python | 75,100 | <p>Using <a href="http://docs.python.org/library/stdtypes.html#str.zfill" rel="noreferrer">zfill()</a>:</p>
<blockquote>
<p>Return the numeric string left filled with zeros in a string of length width. A sign prefix is handled correctly. The original string is returned if width is less than len(s).</p>
</blockquote>
<pre><code>>>> bin(30)[2:].zfill(8)
'00011110'
>>>
</code></pre> |
1,624,084 | Why is it not possible to extend annotations in Java? | <p>I don't understand why there is no inheritance in Java annotations, just as Java classes. I think it would be very useful.</p>
<p>For example: I want to know if a given annotation is a validator. With inheritance, I could reflexively navigate through superclasses to know if this annotation extends a <code>ValidatorAnnotation</code>. Otherwise, how can I achieve this?</p>
<p>So, can anyone give me a reason for this design decision?</p> | 1,644,135 | 8 | 1 | null | 2009-10-26 10:31:23.167 UTC | 51 | 2019-07-10 11:15:15.563 UTC | 2017-08-13 07:38:56.39 UTC | null | 1,472,253 | null | 167,365 | null | 1 | 243 | java|inheritance|annotations | 97,429 | <p>About the reason why it wasn't designed that way you can find the answer in the <a href="http://types.cs.washington.edu/jsr308/java-annotation-design.html#JSR175-PFD2" rel="noreferrer">JSR 175</a> Design FAQ, where it says: </p>
<blockquote>
<p>Why don’t you support annotation subtyping (where one annotation type extends another)?</p>
<p>It complicates the annotation type
system, and makes it much more
difficult to write “Specific Tools”.</p>
<p>…</p>
<p>“Specific Tools” — Programs that query
known annotation types of arbitrary
external programs. Stub generators,
for example, fall into this category.
These programs will read annotated
classes without loading them into the
virtual machine, but will load
annotation interfaces.</p>
</blockquote>
<p>So, yes I guess, the reason is it just KISS. Anyway, it seems this issue (along with many others) are being looked into as part of <a href="https://checkerframework.org/jsr308/java-annotation-design.html" rel="noreferrer">JSR 308</a>, and you can even find an alternative compiler with this functionality already developed by <a href="http://ricken.us/research/xajavac/" rel="noreferrer">Mathias Ricken</a>.</p> |
1,792,470 | Subset of Array in C# | <p>If I have an array with 12 elements and I want a new array with that drops the first and 12th elements. For example, if my array looks like this:</p>
<pre><code>__ __ __ __ __ __ __ __ __ __ __ __
a b c d e f g h i j k l
__ __ __ __ __ __ __ __ __ __ __ __
</code></pre>
<p>I want to either transform it or create a new array that looks like </p>
<pre><code>__ __ __ __ __ __ __ __ __ __
b c d e f g h i j k
__ __ __ __ __ __ __ __ __ __
</code></pre>
<p>I know I can do it by iterating over them. I was just wondering if there was a cleaner way built into C#.</p>
<p>**UPDATED TO FIX A TYPO. Changed 10 elements to 12 elements.</p> | 1,792,483 | 9 | 1 | null | 2009-11-24 19:45:58.863 UTC | 6 | 2022-09-09 11:16:44.763 UTC | 2009-11-24 20:29:51.49 UTC | null | 163,103 | null | 163,103 | null | 1 | 66 | c#|arrays | 80,993 | <p>LINQ is your friend. :)</p>
<pre><code>var newArray = oldArray.Skip(1).Take(oldArray.Length - 2).ToArray();
</code></pre>
<p>Somewhat less efficient than manually creating the array and iterating over it of course, but far simple...</p>
<p>The slightly lengithier method that uses <a href="http://msdn.microsoft.com/en-us/library/z50k9bft.aspx" rel="noreferrer"><code>Array.Copy</code></a> is the following.</p>
<pre><code>var newArray = new int[oldArray.Count - 2];
Array.Copy(oldArray, 1, newArray, 0, newArray.Length);
</code></pre> |
1,950,779 | Is there any way to find the address of a reference? | <p>Is there any way to find the address of a reference?</p>
<p>Making it more specific: The address of the variable itself and not the address of the variable it is initialized with.</p> | 1,950,826 | 10 | 7 | null | 2009-12-23 04:56:44.007 UTC | 37 | 2020-12-21 10:03:11.42 UTC | 2015-03-06 00:44:52.987 UTC | null | 391,161 | null | 228,492 | null | 1 | 77 | c++|reference | 66,476 | <p>References don't have their own addresses. Although references may be implemented as pointers, there is no need or guarantee of this. </p>
<p><a href="https://isocpp.org/wiki/faq/references" rel="noreferrer">The C++ FAQ</a> says it best:</p>
<blockquote>
<p>Unlike a pointer, once a reference is
bound to an object, it can not be
"reseated" to another object. The
reference itself isn't an object (it
has no identity; taking the address of
a reference gives you the address of
the referent; remember: the reference
is its referent).</p>
</blockquote>
<p>Please also see my answer here for a <a href="https://stackoverflow.com/questions/57483/difference-between-pointer-variable-and-reference-variable-in-c">comprehensive list of how references differ from pointers</a>. </p>
<p><strong>The reference is its referent</strong></p> |
1,660,440 | initializing char pointers | <p>I have a char pointer which would be used to store a string. It is used later in the program.</p>
<p>I have declared and initialized like this:</p>
<pre><code>char * p = NULL;
</code></pre>
<p>I am just wondering if this is good practice. I'm using gcc 4.3.3.</p> | 1,660,473 | 12 | 5 | null | 2009-11-02 10:19:26.617 UTC | 4 | 2019-05-03 10:58:25.553 UTC | 2016-03-11 14:23:30.53 UTC | null | 3,924,118 | null | 70,942 | null | 1 | 14 | c|pointers|char-pointer | 53,881 | <p>Yes, it's good idea.
<a href="http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml" rel="noreferrer">Google Code Style</a> recommends:</p>
<ol>
<li>To initialize all your variables even if you don't need them right now.</li>
<li><p>Initialize pointers by <code>NULL</code>, <code>int</code>'s by 0 and <code>float</code>'s by 0.0 -- just for better readability.</p>
<pre><code>int i = 0;
double x = 0.0;
char* c = NULL;
</code></pre></li>
</ol> |
1,373,369 | Which is faster/preferred: memset or for loop to zero out an array of doubles? | <pre><code>double d[10];
int length = 10;
memset(d, length * sizeof(double), 0);
//or
for (int i = length; i--;)
d[i] = 0.0;
</code></pre> | 1,373,422 | 17 | 4 | null | 2009-09-03 13:19:07.063 UTC | 8 | 2020-09-14 16:52:05.76 UTC | 2016-03-12 00:30:47.227 UTC | null | 3,425,536 | null | 149,045 | null | 1 | 32 | c++|c|performance|optimization | 40,803 | <p>Note that for memset you have to pass the number of bytes, not the number of elements because this is an old C function:</p>
<pre><code>memset(d, 0, sizeof(double)*length);
</code></pre>
<p>memset <em>can</em> be faster since it is written in assembler, whereas <code>std::fill</code> is a template function which simply does a loop internally.</p>
<p>But for type safety and more readable code <strong>I would recommend</strong> <code>std::fill()</code> - it is the c++ way of doing things, and consider <code>memset</code> if a performance optimization is needed at this place in the code.</p> |
17,810,501 | PHP - get base64 img string decode and save as jpg (resulting empty image ) | <p>hi i'm actually sending a base64 image string trough ajax to a php script which just decodes string and save content as .jpg file.</p>
<p>But the result is an empty image.</p>
<p>How can this be possible?</p>
<p>php script:</p>
<pre><code>$uploadedPhotos = array('photo_1','photo_2','photo_3','photo_4');
foreach ($uploadedPhotos as $file) {
if($this->input->post('photo_1')){
$photoTemp = base64_decode($this->input->post('photo_1'));
/*Set name of the photo for show in the form*/
$this->session->set_userdata('upload_'.$file,'ant');
/*set time of the upload*/
if(!$this->session->userdata('uploading_on_datetime')){
$this->session->set_userdata('uploading_on_datetime',time());
}
$datetime_upload = $this->session->userdata('uploading_on_datetime',true);
/*create temp dir with time and user id*/
$new_dir = 'temp/user_'.$this->session->userdata('user_id',true).'_on_'.$datetime_upload.'/';
@mkdir($new_dir);
/*move uploaded file with new name*/
@file_put_contents( $new_dir.$file.'.jpg',$photoTemp);
}
</code></pre>
<p>For ajax it is ok because, echo $photoTemp returns the string.</p>
<p>i tried <code>var_dump(@file_put_contents( $new_dir.$file.'.jpg',$photoTemp));</code> and it returns <code>bool(true)</code> since the image is saved but there is no content in the image :( empty image</p>
<blockquote>
<p>for empty image i mean , file is created and named, and it has the same
size of the content i pass to php, but when i try to open that image
to preview it says, file can't be opened because corrupted or bad file type format </p>
</blockquote>
<p>anyway this is the JS that takes photo as base64 and send that to php:</p>
<pre><code><script type="text/javascript">
var _min_width = 470;
var _min_height = 330;
var _which;
var _fyle_type;
var io;
var allowed_types = new Array('image/png','image/jpg','image/jpeg');
if (typeof(FileReader) === 'function'){
$('input[type="file"]').on('change', function(e) {
var _file_name = $(this).val();
$('.'+_which+'_holder').text(_file_name);
var file = e.target.files[0];
if (!in_array(file.type,allowed_types) || file.length === 0){
notify("You must select a valid image file!",false,false);
return;
}
if(file.size > 3145728 /*3MB*/){
notify("<?php echo lang('each-photo-1MB'); ?>",false,false);
return;
}
notify_destroy();
var reader = new FileReader();
reader.onload = fileOnload;
reader.readAsDataURL(file);
});
function fileOnload(e) {
var img = document.createElement('img');
img.src = e.target.result;
img.addEventListener('load', function() {
if(img.width < _min_width || img.height < _min_height ){
notify("<?php echo lang('each-photo-1MB'); ?>",false,false);
return;
}
$.ajax({
type:'post',
dataType:'script',
data:{photo_1:e.target.result},
url:_config_base_url+'/upload/upload_photos',
progress:function(e){
console.log(e);
},
success:function(d){
$('body').append('<img src="'+d+'"/>');
}
});
});
}
}
</script>
</code></pre> | 17,811,089 | 8 | 3 | null | 2013-07-23 12:42:16.74 UTC | 17 | 2021-06-21 21:22:19.423 UTC | 2016-11-11 09:16:17.013 UTC | null | 3,185,747 | null | 2,591,520 | null | 1 | 18 | php|image|codeigniter|save|base64 | 142,417 | <p>AFAIK, You have to use image function imagecreatefromstring, imagejpeg to create the images.</p>
<pre><code>$imageData = base64_decode($imageData);
$source = imagecreatefromstring($imageData);
$rotate = imagerotate($source, $angle, 0); // if want to rotate the image
$imageSave = imagejpeg($rotate,$imageName,100);
imagedestroy($source);
</code></pre>
<p>Hope this will help.</p>
<p><code>PHP CODE WITH IMAGE DATA</code></p>
<pre><code>$imageDataEncoded = base64_encode(file_get_contents('sample.png'));
$imageData = base64_decode($imageDataEncoded);
$source = imagecreatefromstring($imageData);
$angle = 90;
$rotate = imagerotate($source, $angle, 0); // if want to rotate the image
$imageName = "hello1.png";
$imageSave = imagejpeg($rotate,$imageName,100);
imagedestroy($source);
</code></pre>
<p>So Following is the php part of your program .. <code>NOTE</code> the change with comment <code>Change is here</code></p>
<pre><code> $uploadedPhotos = array('photo_1','photo_2','photo_3','photo_4');
foreach ($uploadedPhotos as $file) {
if($this->input->post($file)){
$imageData = base64_decode($this->input->post($file)); // <-- **Change is here for variable name only**
$photo = imagecreatefromstring($imageData); // <-- **Change is here**
/* Set name of the photo for show in the form */
$this->session->set_userdata('upload_'.$file,'ant');
/*set time of the upload*/
if(!$this->session->userdata('uploading_on_datetime')){
$this->session->set_userdata('uploading_on_datetime',time());
}
$datetime_upload = $this->session->userdata('uploading_on_datetime',true);
/* create temp dir with time and user id */
$new_dir = 'temp/user_'.$this->session->userdata('user_id',true).'_on_'.$datetime_upload.'/';
if(!is_dir($new_dir)){
@mkdir($new_dir);
}
/* move uploaded file with new name */
// @file_put_contents( $new_dir.$file.'.jpg',imagejpeg($photo));
imagejpeg($photo,$new_dir.$file.'.jpg',100); // <-- **Change is here**
}
}
</code></pre> |
41,946,457 | Getting Text From Fetch Response Object | <p>I'm using <code>fetch</code> to make API calls and everything works but in this particular instance I'm running into an issue because the API simply returns a string -- not an object.</p>
<p>Typically, the API returns an object and I can parse the JSON object and get what I want but in this case, I'm having trouble finding the text I'm getting from the API in the response object.</p>
<p>Here's what the response object looks like.
<a href="https://i.stack.imgur.com/RapuG.png" rel="noreferrer"><img src="https://i.stack.imgur.com/RapuG.png" alt="enter image description here"></a></p>
<p>I thought I'd find the text inside the body but I can't seem to find it. Where do I look?</p> | 41,946,517 | 3 | 3 | null | 2017-01-30 22:22:24.267 UTC | 8 | 2022-03-16 07:00:19.26 UTC | 2022-03-16 07:00:19.26 UTC | null | 3,689,450 | null | 1,705,266 | null | 1 | 71 | javascript|ajax|fetch-api | 84,357 | <p>Using the fetch JavaScript API you can try:</p>
<pre><code>response.text().then(function (text) {
// do something with the text response
});
</code></pre>
<p>Also take a look at the docs on <a href="https://developer.mozilla.org/en-US/docs/Web/API/Response#Body_Interface_Methods" rel="noreferrer"><strong>fetch</strong> > <strong>response</strong> > <strong>body interface methods</strong></a></p> |
6,653,430 | Task scheduler: run 1 tasks 4 times a day | <p>It seems like I have to add <code>4 tasks</code> to run the same job at <code>9am, 11am, 2pm, and 4pm</code>. Is there a way to run the same job <code>4 times with 1 task</code>? </p>
<p>If yes, how do I configure that.</p> | 6,653,500 | 3 | 0 | null | 2011-07-11 16:37:11.137 UTC | 1 | 2015-11-20 10:58:59.39 UTC | 2015-11-20 10:58:59.39 UTC | null | 3,003,757 | null | 819,414 | null | 1 | 13 | scheduled-tasks | 48,941 | <p>(I'll assume you are using Win 7). In the Create Task dialog, click the Triggers tab. Then click the New button. In the New Trigger dialog, you will see an Advanced Settings section. It has a Repeat Task area. You can put a checkmark in that box and choose a preset value or type your own---e.g. 4 hours or 45 minutes.</p> |
6,857,204 | Html literal in Razor ternary expression | <p>I'm trying to do something like the following</p>
<pre><code><div id="test">
@(
string.IsNullOrEmpty(myString)
? @:&nbsp;
: myString
)
</div>
</code></pre>
<p>The above syntax is invalid, I've tried a bunch of different things but can't get it working.</p> | 6,857,272 | 4 | 4 | null | 2011-07-28 10:05:12.747 UTC | 4 | 2019-10-04 14:30:09.833 UTC | 2011-07-28 10:11:18.387 UTC | null | 207,752 | null | 207,752 | null | 1 | 28 | html|asp.net-mvc-3|razor|ternary-operator | 18,920 | <p>Try the following:</p>
<pre><code>@Html.Raw(string.IsNullOrEmpty(myString) ? "&nbsp;" : Html.Encode(myString))
</code></pre>
<p>But I would recommend you writing a helper that does this job so that you don't have to turn your views into spaghetti:</p>
<pre><code>public static class HtmlExtensions
{
public static IHtmlString ValueOrSpace(this HtmlHelper html, string value)
{
if (string.IsNullOrEmpty(value))
{
return new HtmlString("&nbsp;");
}
return new HtmlString(html.Encode(value));
}
}
</code></pre>
<p>and then in your view simply:</p>
<pre><code>@Html.ValueOrSpace(myString)
</code></pre> |
6,735,862 | Problem when trying to use EventLog.SourceExists method in .NET | <p>I am trying to use eventlogs in my application using C#, so I added the following code</p>
<pre><code>if (!EventLog.SourceExists("SomeName"))
EventLog.CreateEventSource("SomeName", "Application");
</code></pre>
<p>The EventLog.SourceExists causes SecurityException that says<br>
<strong>"The source was not found, but some or all event logs could not be searched. Inaccessible logs: Security."</strong></p>
<p>I am running as administrator in Windows 7.</p>
<p>Any help would be appriciated.</p> | 6,736,019 | 4 | 2 | null | 2011-07-18 16:07:19.913 UTC | 2 | 2020-08-21 21:17:32.493 UTC | null | null | null | null | 850,010 | null | 1 | 29 | c#|.net | 34,695 | <p>This is a permissions problem - you should give the running user permission to read the following registry key:</p>
<pre><code>HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\EventLog
</code></pre>
<p>Alternaitvely you can bypas the <code>CreateEventSource</code> removing the need to access this registry key.</p>
<p>Both solutions are explained in more detail in the following thread - <a href="http://social.msdn.microsoft.com/forums/en-US/windowsgeneraldevelopmentissues/thread/00a043ae-9ea1-4a55-8b7c-d088a4b08f09/" rel="noreferrer">How do I create an Event Log source under Vista?</a>.</p> |
46,171,384 | Disambiguate between two constructors, when two type parameters are the same | <p>Given </p>
<pre><code>class Either<A, B> {
public Either(A x) {}
public Either(B x) {}
}
</code></pre>
<p>How to disambiguate between the two constructors when the two type parameters are the same? </p>
<p>For example, this line:</p>
<pre><code>var e = new Either<string, string>("");
</code></pre>
<p>Fails with:</p>
<blockquote>
<p>The call is ambiguous between the following methods or properties: 'Program.Either.Either(A)' and 'Program.Either.Either(B)'</p>
</blockquote>
<p>I know if I had given the parameters different names (e.g. <code>A a</code> and <code>B b</code> instead of just <code>x</code>), I could use named parameters to disambiguate (e.g. <code>new Either<string, string>(a: "")</code>). But I'm interested in knowing how to solve this without changing the definition of <code>Either</code>.</p>
<p>Edit:</p>
<p>You <em>can</em> write a couple of smart constructors, but I'm interested in knowing if the <code>Either</code>'s constructors can be called directly without ambiguity. (Or if there are other "tricks" besides this one).</p>
<pre><code>static Either<A, B> Left<A, B>(A x) {
return new Either<A, B>(x);
}
static Either<A, B> Right<A, B>(B x) {
return new Either<A, B>(x);
}
var e1 = Left<string, string>("");
var e2 = Right<string, string>("");
</code></pre> | 46,173,133 | 2 | 18 | null | 2017-09-12 08:22:07.497 UTC | 8 | 2017-09-12 10:01:00.427 UTC | 2017-09-12 08:33:20.097 UTC | null | 857,807 | null | 857,807 | null | 1 | 46 | c# | 3,426 | <blockquote>
<p>How to disambiguate between the two constructors when the two type parameters are the same?</p>
</blockquote>
<p>I'll start by not answering your question, and then finish it up with an actual answer that lets you work around this problem.</p>
<p>You don't have to because <strong>you should never get yourself into this position in the first place</strong>. It is a design error to create a generic type which can cause member signatures to be unified in this manner. Never write a class like that.</p>
<p>If you go back and read the original C# 2.0 specification you'll see that the original design was to have the compiler detect generic types in which it was <em>in any way possible</em> for this sort of problem to arise, and to make the class declaration illegal. This made it into the published specification, though that was an error; the design team realized that this rule was too strict because of scenarios like:</p>
<pre><code>class C<T>
{
public C(T t) { ... }
public C(Stream s) { ... deserialize from the stream ... }
}
</code></pre>
<p>It would be bizarre to say that this class is illegal because you might say <code>C<Stream></code> and then be unable to disambiguate the constructors. Instead, a rule was added to overload resolution which says that if there's a choice between <code>(Stream)</code> and <code>(T where Stream is substituted for T)</code> then the former wins.</p>
<p>Thus the rule that this kind of unification is illegal was scrapped and it is now allowed. However it is a very, very bad idea to make types that unify in this manner. The CLR handles it poorly in some cases, and it is confusing to the compiler and the developers alike. For example, would you care to guess at the output of this program?</p>
<pre><code>using System;
public interface I1<U> {
void M(U i);
void M(int i);
}
public interface I2<U> {
void M(int i);
void M(U i);
}
public class C3: I1<int>, I2<int> {
void I1<int>.M(int i) {
Console.WriteLine("c3 explicit I1 " + i);
}
void I2<int>.M(int i) {
Console.WriteLine("c3 explicit I2 " + i);
}
public void M(int i) {
Console.WriteLine("c3 class " + i);
}
}
public class Test {
public static void Main() {
C3 c3 = new C3();
I1<int> i1_c3 = c3;
I2<int> i2_c3 = c3;
i1_c3.M(101);
i2_c3.M(102);
}
}
</code></pre>
<p>If you compile this with warnings turned on you will see the warning I added explaining why this is a really, really bad idea.</p>
<blockquote>
<p>No, really: How to disambiguate between the two constructors when the two type parameters are the same?</p>
</blockquote>
<p>Like this:</p>
<pre><code>static Either<A, B> First<A, B>(A a) => new Either<A, B>(a);
static Either<A, B> Second<A, B>(B b) => new Either<A, B>(b);
...
var ess1 = First<string, string>("hello");
var ess2 = Second<string, string>("goodbye");
</code></pre>
<p><strong>which is how the class should have been designed in the first place</strong>. The author of the <code>Either</code> class should have written</p>
<pre><code>class Either<A, B>
{
private Either(A a) { ... }
private Either(B b) { ... }
public static Either<A, B> First(A a) => new Either<A, B>(a);
public static Either<A, B> Second(B b) => new Either<A, B>(b);
...
}
...
var ess = Either<string, string>.First("hello");
</code></pre> |
15,887,648 | Onmouseover change CSS class from other element | <p>I'm trying to make an JS, but since I'm not an expert on that, maybe someone could help me. I was searching for that in Google and in Stack Overflow, but didn't find what I need. I just found <code>onmouseover</code> that change the class in element itself. But I want something different:</p>
<p>I want to make a <code>onmouseover</code> on <code>a</code> tag to change the class <code>closed</code> to <code>open</code> in other element. Example:</p>
<p><code><a href="#" onmouseover="<active event>">Link</a></code></p>
<p><code><ul class="dropdown closed"><li>Item</li></ul></code></p>
<p>Regards,</p> | 15,887,803 | 4 | 0 | null | 2013-04-08 19:49:16.257 UTC | 1 | 2013-04-08 20:04:33.983 UTC | null | null | null | null | 894,230 | null | 1 | 5 | javascript | 40,205 | <p>If you include jQuery:</p>
<p>Add id for your elements:</p>
<pre><code><a href="#" id="a1">Link</a>
<ul class="dropdown closed" id="ul1"><li>Item</li></ul>
</code></pre>
<p>Javascript:</p>
<pre><code>$("#a1").mouseover(function(){
$("#ul1").addClass("open").removeClass("closed")
})
</code></pre> |
18,962,785 | "OSError: [Errno 2] No such file or directory" while using python subprocess with command and arguments | <p>I am trying to run a program to make some system calls inside Python code using <code>subprocess.call()</code> which throws the following error:</p>
<pre class="lang-none prettyprint-override"><code>Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/lib/python2.7/subprocess.py", line 493, in call
return Popen(*popenargs, **kwargs).wait()
File "/usr/lib/python2.7/subprocess.py", line 679, in __init__
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1249, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
</code></pre>
<p>My actual Python code is as follows:</p>
<pre><code>url = "/media/videos/3cf02324-43e5-4996-bbdf-6377df448ae4.mp4"
real_path = "/home/chanceapp/webapps/chanceapp/chanceapp"+url
fake_crop_path = "/home/chanceapp/webapps/chanceapp/chanceapp/fake1"+url
fake_rotate_path = "/home/chanceapp/webapps/chanceapp.chanceapp/fake2"+url
crop = "ffmpeg -i %s -vf "%(real_path)+"crop=400:400:0:0 "+ "-strict -2 %s"%(fake_crop_path)
rotate = "ffmpeg -i %s -vf "%(fake_crop_path)+"transpose=1 "+"%s"%(fake_rotate_path)
move_rotated = "mv"+" %s"%(fake_rotate_path)+" %s"%(real_path)
delete_cropped = "rm "+"%s"%(fake_crop_path)
#system calls:
subprocess.call(crop)
</code></pre>
<p>Can I get some relevant advice on how to solve this?</p> | 18,962,815 | 3 | 2 | null | 2013-09-23 15:09:41.24 UTC | 34 | 2022-07-20 12:09:38.747 UTC | 2022-07-20 12:09:38.747 UTC | null | 4,621,513 | null | 1,763,088 | null | 1 | 174 | python|subprocess | 228,750 | <p>Use <code>shell=True</code> if you're passing a string to <code>subprocess.call</code>.</p>
<p>From <a href="http://docs.python.org/2/library/subprocess.html#frequently-used-arguments" rel="noreferrer">docs</a>:</p>
<blockquote>
<p>If passing a single string, either <code>shell</code> must be <code>True</code> or
else the string must simply name the program to be executed without
specifying any arguments.</p>
</blockquote>
<pre><code>subprocess.call(crop, shell=True)
</code></pre>
<p>or:</p>
<pre><code>import shlex
subprocess.call(shlex.split(crop))
</code></pre> |
19,238,738 | Style bottom Line in Android | <p>I need to create an android shape so that only the bottom has stroke (a dashed line). When I try the following, the stroke bisects the shape right through the center. Does anyone know how to get it right? the stroke needs to be the bottom line/border. I am using the shape as a background to a TextView. Please, never mind why I need it.</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
<shape android:shape="rectangle" >
<solid android:color="#1bd4f6" />
</shape>
</item>
<item>
<shape android:shape="line" >
<padding android:bottom="1dp" />
<stroke
android:dashGap="10px"
android:dashWidth="10px"
android:width="1dp"
android:color="#ababb2" />
</shape>
</item>
</layer-list>
</code></pre> | 19,239,478 | 16 | 2 | null | 2013-10-08 03:47:31.997 UTC | 52 | 2021-11-01 08:32:44.657 UTC | 2019-11-11 09:36:55.117 UTC | null | 6,717,610 | null | 2,507,741 | null | 1 | 136 | android|android-drawable|android-styles|layer-list | 186,862 | <p>It's kind of a hack, but I think this is probably the best way to do it. The dashed line will always be on the bottom, regardless of the height. </p>
<pre><code><layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle" >
<solid android:color="#1bd4f6" />
</shape>
</item>
<item android:top="-2dp" android:right="-2dp" android:left="-2dp">
<shape>
<solid android:color="@android:color/transparent" />
<stroke
android:dashGap="10px"
android:dashWidth="10px"
android:width="1dp"
android:color="#ababb2" />
</shape>
</item>
</layer-list>
</code></pre>
<h2>Explanation:</h2>
<p>The second shape is transparent rectangle with a dashed outline. The key in making the border only appear along the bottom lies in the negative margins set the other sides. These negative margins "push" the dashed line outside the drawn area on those sides, leaving only the line along the bottom. One potential side-effect (which I haven't tried) is that, for views that draw outside their own bounds, the negative-margin borders may become visible.</p> |
4,959,703 | JQuery to uncheck all checkboxes within div | <pre><code><div id="termSheetPopup">
<div style="text-align:center;">
<select id="termSheetType">
<option>Internal</option>
<option>Borrower Facing</option>
</select>
</div>
<input type="checkbox" name="SummaryInformation">Summary Information<br />
<input type="checkbox" name="ProductLegs">Product Legs<br />
<input type="checkbox" name="AmortizationOptions">Amortization Options<br />
<input type="checkbox" name="Values">Values<br />
<input type="checkbox" name="Rates">Rates<br />
<input type="checkbox" name="RatesSpecific">Rates (All-In-Rate, PV01)<br />
<input type="checkbox" name="AmortizationSchedule">Amortization Schedule<br />
<input type="checkbox" name="SponsorInfo">Sponsor/Affiliate Info<br />
<input type="checkbox" name="BorrowerInfo">Borrower Info<br />
<input type="checkbox" name="SponsorContacts">Sponsor/Affiliate Contacts<br />
<input type="checkbox" name="CashFlows">Cash Flows<br />
<input type="checkbox" name="PrePayment">Pre-Payment<br />
<input type="checkbox" name="FutureExposure">Potential Future Exposure<br />
<input type="checkbox" name="FutureExposureSpecific">Potential Future Exposure (Max Number and Date Only)<br />
<input type="checkbox" name="History">History<br />
</div>
</code></pre>
<p>What's the JQuery to delete all those checkboxes just underneath that div?</p> | 4,959,746 | 2 | 2 | null | 2011-02-10 16:18:26.793 UTC | 3 | 2012-03-29 19:42:41.673 UTC | 2011-02-10 16:24:43.913 UTC | null | 495,935 | null | 534,101 | null | 1 | 22 | jquery|html | 49,585 | <p>To uncheck all the checkboxes (as the title asks):</p>
<pre><code>$('#termSheetPopup').find('input[type=checkbox]:checked').removeAttr('checked');
</code></pre>
<p>To delete all the checkboxes (as the question asks):</p>
<pre><code>$('#termSheetPopup').find('input[type=checkbox]:checked').remove();
</code></pre> |
4,913,834 | How do you add syntax highlighting for Less in Notepad++? | <p>I want Notepad++ to treat my <em>.less</em> files just as my <em>.css</em> files and thereby get syntax highlighting for any <code>.less</code> files I open.</p> | 10,161,795 | 2 | 3 | null | 2011-02-06 14:22:26.83 UTC | 8 | 2019-04-22 19:20:20.437 UTC | 2019-04-22 19:20:20.437 UTC | null | 814,702 | null | 268,946 | null | 1 | 52 | css|notepad++|highlight|less | 32,668 | <p>To get LESS syntax highlighting, you have to download and import a <em>user defined language</em> file. Here are some links to language files:</p>
<ul>
<li><a href="http://notepad-plus.sourceforge.net/commun/userDefinedLang/less.xml" rel="noreferrer">LESS language file</a>, as listed in the <a href="http://docs.notepad-plus-plus.org/index.php?title=User_Defined_Language_Files" rel="noreferrer">Notepad++ User Defined Language List</a> </li>
<li><a href="https://github.com/azrafe7/LESS-for-Notepad-plusplus" rel="noreferrer">LESS language file on GitHub</a></li>
</ul>
<p>Installation instructions from the <a href="https://github.com/azrafe7/LESS-for-Notepad-plusplus" rel="noreferrer">GitHub repository</a>:</p>
<blockquote>
<ul>
<li>Download the <code>less.xml</code> file</li>
<li>Open Notepad++</li>
<li>Go to <code>Language -> Define your language...</code>, click on <code>Import...</code> and select the <code>less.xml</code> file you've downloaded</li>
<li>Close and restart Notepad++</li>
<li>Done</li>
</ul>
</blockquote>
<p>Another way to install language files is to <a href="http://docs.notepad-plus-plus.org/index.php?title=User_Defined_Language_Files#How_to_install_user_defined_language_files" rel="noreferrer">copy them into a file in the Notepad++ installation directory</a>.</p> |
16,064,392 | Multiple AngularJS get requests into one model | <p>Is there a way to call an unknown amount of API calls to a URL via the <code>get()</code> function in AngularJS and add those all into a model (<code>$scope</code> variable). What I've done thus far is the following:</p>
<pre><code>if(theUIDS != "") {
var myDropbox = [];
for(i = 0; i < theUIDS.length; i++) {
var temp = {};
temp.uid = theUIDS[i];
$http({ url: '/dropbox/accounts/get', method: 'GET', params: { uid: theUIDS[i] }}).success(function(acctData) {
temp.accountInfo = acctData;
});
$http({ url: '/dropbox/files/get', method: 'GET', params: { uid: theUIDS[i] }}).success(function(fileData) {
temp.files = fileData;
});
myDropbox.push(temp);
}
$scope.dropboxAccounts = myDropbox;
}
</code></pre>
<p>I check if there are any UID's and for each one I create a <code>temp</code> object which is populated with a <code>uid</code>, then an <code>accountInfo</code> object, and then a <code>files</code> object. After I set up my <code>temp</code> object, I push it onto the <code>myDropbox</code> array. Once the loop has finished, I set the dropboxAccounts model to the <code>myDropbox</code> variable in <code>$scope</code>. I'm new to Angular, but I'm pretty sure this is at least the right idea. Luckily I'm getting the following data in correct order:</p>
<pre><code>{"uid":"332879"}
{"uid":"155478421",
"accountInfo":{
"country":"US",
"display_name":"Patrick Cason",
"name":"Second Dropbox",
"quota_normal":1174504,
"quota_shared":0,
"quota_total":2147483648,
"referral_link":"https://www.dropbox.com/referrals/NTE1NTQ3ODQyMTk?src=app9-203957",
"uid":155478421},
"files":[{
"created_at":"2013-04-17T15:13:46Z",
"directory":true,
"dropbox_user_id":26,
"fileType":"Folder",
"id":198,
"name":"Photos",
"path":"/Photos",
"rev":"10edb44f9",
"size":"-",
"updated_at":"2013-04-17T15:13:46Z"}]
}
</code></pre>
<p>The strange thing is that only one of my UID's gets updated. I know that the loop is correctly going through because I have two UID's and if I alert at the beginning the loop I get two loops. The reason I think the second isn't being populated is because the push statement isn't waiting for both of the promises to go through. How can I ensure that I wait for each of the AJAX calls to finish before assigning <code>myDropbox</code> to the <code>$scope</code> variable?</p> | 16,070,297 | 1 | 0 | null | 2013-04-17 15:39:22.763 UTC | 8 | 2013-04-17 21:08:15.94 UTC | null | null | null | null | 591,776 | null | 1 | 7 | javascript|jquery|ajax|angularjs | 5,263 | <h2>Introduction</h2>
<p>I'm pretty new to AngularJS, so this solution is very much so a <em>work-in-progress</em>. I figure that since I've struggled through learning more about it that other people may be in the same position as well. With that said, I'm going to not only post my answer, but also explain my thinking behind the code. I'd love to get any feedback if anyone feels the answer could be improved any.</p>
<h2>Final Code</h2>
<p>Here's the code I used to get everything working:</p>
<pre><code>var app = angular.module('myApp', []);
app.controller('DropboxCtrl', function($scope, dropbox) {
$scope.dropboxAccounts = dropbox.getAccounts();
$scope.dropboxFiles = dropbox.getFiles();
});
app.factory('dropbox', function($http, $q) {
var theUIDS = [12345,67890];
return {
getAccounts: function() {
var promises = [];
for(i = 0; i < theUIDS.length; i++) {
promises.push($http({
url: '/dropbox/accounts/get',
method: "GET",
params: { uid: theUIDS[i] }
}));
}
return $q.all(promises);
},
getFiles: function() {
var promises = [];
for(i = 0; i < theUIDS.length; i++) {
promises.push($http({
url: '/dropbox/files/get',
method: "GET",
params: { uid: theUIDS[i] }
}));
}
return $q.all(promises);
}
}
});
</code></pre>
<h2>Basic Algorithm</h2>
<p>We start by declaring a module <code>myApp</code> and saving it in a variable <code>app</code>... notice the empty array we're passing which would normally be a parameter for any further requirements which may or may not be inherited from other modules.</p>
<p>After our module is declared we need to create a corresponding controller which will be a gateway for all interactions to take place. In this case we need access to the <code>$scope</code> variable which is relative to our controller (not relative to the app itself). We also declare what factory this controller is related to, in my case it's <code>dropbox</code> (we'll get to factories in a moment). Inside of this controller we assign two models to <code>$scope</code>: <code>dropboxAccounts</code> and <code>dropboxFiles</code>. Note that my original desire was to have one model within my AngularJS app. While this is possible... I opted against it because I found it difficult to differentiate my two types of JSON returns apart. One returns account metadata and the other returns an array of files of that account. I would have liked to have all these under one model and be sorted by a <code>uid</code> parameter, but found this to be impossible to do without changing what JSON my RESTful endpoints output. In the end, I opted for two separate models so I can work with them easier (until I find a way to combine them according to one common parameter).</p>
<p>Lastly, we create a factory which stores my AJAX functions (using <code>$http</code> for the actual AJAX call, and <code>$q</code> for handling the promises). I have two functions: (which remember are called from my controller) <code>getAccounts</code> and <code>getFiles</code>. Each of them has an array called promises which will store the promises of my <code>$http</code> calls. I run through these calls in a for-loop which will look at each of my items in <code>theUIDS</code>, which is used in my AJAX call, and is then pushed onto the <code>promises</code> array. At the end we have our <code>$q</code> which will wait until all the AJAX calls in the <code>promises</code> array has finished successfully before returning all that data in one big promise back to our controller and assigning it to <code>$scope</code>.</p>
<h2>What I Learned</h2>
<p>AngularJS is really tough. This particular issue has taken me two days of debugging and trying again and again. I have been told that while the learning curve to this front-end MVC framework is pretty steep, the payoff is well worth it. I suppose we shall see...</p>
<h2>Resources</h2>
<ul>
<li><a href="http://docs.angularjs.org/api/" rel="nofollow noreferrer">AngularJS API</a></li>
<li><a href="https://groups.google.com/forum/#!msg/angular/56sdORWEoqg/VxECXKbn3gsJ" rel="nofollow noreferrer">Factories and Services comparison</a></li>
<li><a href="https://stackoverflow.com/a/15117739/591776">Good use of AngularJS's <code>all</code> method</a></li>
<li><a href="http://nurkiewicz.blogspot.com/2013/03/promises-and-deferred-objects-in-jquery.html" rel="nofollow noreferrer">Beautiful explanation of AJAX promises both in jQuery and AngularJS</a></li>
</ul> |
373,252 | sizeof with a type or variable | <p>Recently saw someone commending another user on their use of sizeof var instead of sizeof(type). I always thought that was just a style choice. Is there any significant difference? As an example, the lines with f and ff were considered better than the lines with g and gg:</p>
<pre><code> typedef struct _foo {} foo;
foo *f = malloc(count * sizeof f);
foo *g = malloc(sizeof(foo) * count);
foo **ff = malloc(count * sizeof *ff);
foo **gg = malloc(sizeof(foo*) * count);
</code></pre>
<p>In my opinion, the first set is just a matter of style. But in the second pair of lines, the extra second * can easily be confused for a multiplication.</p> | 373,256 | 7 | 2 | null | 2008-12-17 00:13:34.183 UTC | 5 | 2021-10-19 09:19:07.947 UTC | 2021-10-19 09:19:07.947 UTC | null | 817,643 | null | 44,065 | null | 1 | 28 | c|coding-style|sizeof | 18,710 | <p>If the type of the variable is changed, the sizeof will not require changing if the variable is the argument, rather than the type.</p>
<p>Regarding @icepack's comment: the possibility or likelihood of change for type vs. variable name is not the issue. Imagine the variable name is used as the the argument to sizeof and then later changed. In the best case a refactor-rename operation changes all occurrences and no error is introduced. In the worst case an instance of a sizeof is missed and the compiler complains and you fix it. If the type is changed you are done, no possibility of errors at sizeof statements.</p>
<p>Now imagine the type is the argument to sizeof. If the type of the variable is changed, there is no means other than inspection to find all sizeof relating to that variable. You can search, but you will get hits for all the unrelated uses of sizeof of the same type. If one is missed, you will have a runtime problem due to a size mismatch, which is much more trouble to find.</p> |
16,298 | How to redirect siteA to siteB with A or CNAME records | <p>I have 2 hosts and I would like to point a subdomain on host one to a subdomain on host two:</p>
<pre><code>subdomain.hostone.com --> subdomain.hosttwo.com
</code></pre>
<p>I added a CNAME record to host one that points to subdomain.hosttwo.com but all I get is a '<strong>400 Bad Request</strong>' Error.</p>
<p>Can anyone see what I'm doing wrong?</p> | 16,311 | 7 | 3 | null | 2008-08-19 14:42:29.44 UTC | 5 | 2015-11-28 17:56:08.55 UTC | 2008-08-23 16:29:05.727 UTC | Chris Fournier | 2,134 | Peter Coulton | 117 | null | 1 | 45 | dns|web-hosting|cname | 207,165 | <p>Try changing it to "subdomain -> subdomain.hosttwo.com"</p>
<p>The <code>CNAME</code> is an alias for a certain domain, so when you go to the control panel for hostone.com, you shouldn't have to enter the whole name into the <code>CNAME</code> alias.</p>
<p>As far as the error you are getting, can you log onto subdomain.hostwo.com and check the logs?</p> |
983,855 | Python JSON encoding | <p>I'm trying to encode data to JSON in Python and I been having a quite a bit of trouble. I believe the problem is simply a misunderstanding. </p>
<p>I'm relatively new to Python and never really got familiar with the various Python data types, so that's most likely what's messing me up. </p>
<p>Currently I am declaring a list, looping through and another list, and appending one list within another:</p>
<pre><code>import simplejson, json
data = [['apple', 'cat'], ['banana', 'dog'], ['pear', 'fish']]
x = simplejson.loads(data)
# >>> typeError: expected string or buffer..
x = simplejson.dumps(stream)
# >>> [["apple", "cat"], ["banana", "dog"], ["pear", "fish"]]
# - shouldn't JSON encoded strings be like: {{"apple":{"cat"},{"banana":"dog"}}
</code></pre>
<p>So I either: </p>
<ul>
<li>I don't understand JSON Syntax</li>
<li>I don't understand the Pythons JSON module(s)</li>
<li>I'm using an inappropriate data type.</li>
</ul> | 983,879 | 7 | 0 | null | 2009-06-11 21:37:09.83 UTC | 20 | 2014-04-22 13:22:29.813 UTC | null | null | null | null | 84,372 | null | 1 | 61 | python|json|encoding|types|simplejson | 167,071 | <p>Python <code>lists</code> translate to JSON <code>arrays</code>. What it is giving you is a perfectly valid JSON string that could be used in a Javascript application. To get what you expected, you would need to use a <code>dict</code>:</p>
<pre><code>>>> json.dumps({'apple': 'cat', 'banana':'dog', 'pear':'fish'})
'{"pear": "fish", "apple": "cat", "banana": "dog"}'
</code></pre> |
111,954 | Using Python's ftplib to get a directory listing, portably | <p>You can use ftplib for full FTP support in Python. However the preferred way of getting a directory listing is:</p>
<pre><code># File: ftplib-example-1.py
import ftplib
ftp = ftplib.FTP("www.python.org")
ftp.login("anonymous", "ftplib-example-1")
data = []
ftp.dir(data.append)
ftp.quit()
for line in data:
print "-", line
</code></pre>
<p>Which yields:</p>
<pre><code>$ python ftplib-example-1.py
- total 34
- drwxrwxr-x 11 root 4127 512 Sep 14 14:18 .
- drwxrwxr-x 11 root 4127 512 Sep 14 14:18 ..
- drwxrwxr-x 2 root 4127 512 Sep 13 15:18 RCS
- lrwxrwxrwx 1 root bin 11 Jun 29 14:34 README -> welcome.msg
- drwxr-xr-x 3 root wheel 512 May 19 1998 bin
- drwxr-sr-x 3 root 1400 512 Jun 9 1997 dev
- drwxrwxr-- 2 root 4127 512 Feb 8 1998 dup
- drwxr-xr-x 3 root wheel 512 May 19 1998 etc
...
</code></pre>
<p>I guess the idea is to parse the results to get the directory listing. However this listing is directly dependent on the FTP server's way of formatting the list. It would be very messy to write code for this having to anticipate all the different ways FTP servers might format this list.</p>
<p>Is there a portable way to get an array filled with the directory listing?</p>
<p>(The array should only have the folder names.)</p> | 111,966 | 7 | 0 | null | 2008-09-21 20:13:18.477 UTC | 13 | 2021-09-14 19:20:40.24 UTC | 2008-09-21 20:57:34.563 UTC | superjoe30 | 432 | superjoe30 | 432 | null | 1 | 71 | python|ftp|portability | 136,169 | <p>Try using <a href="https://docs.python.org/3/library/ftplib.html#ftplib.FTP.nlst" rel="noreferrer"><code>ftp.nlst(dir)</code></a>.</p>
<p>However, note that if the folder is empty, it might throw an error:</p>
<pre><code>files = []
try:
files = ftp.nlst()
except ftplib.error_perm as resp:
if str(resp) == "550 No files found":
print "No files in this directory"
else:
raise
for f in files:
print f
</code></pre> |
214,764 | Best (free?) decompiler for C# with Visual Studio integration? | <p>In my Java development I have had great benefit from the <a href="http://en.wikipedia.org/wiki/JAD_%28JAva_Decompiler%29" rel="noreferrer">Jad/JadClipse</a> decompiler. It made it possible to <em>know</em> why a third-party library failed rather than the usual guesswork.</p>
<p>I am looking for a similar setup for C# and Visual Studio. That is, a setup where I can point to any class or variable in my code and get a code view for that particular class.</p>
<p>What is the best setup for this? I want to be able to use the usual "jump to declaration/implementation" that I use to navigate my own code. It doesn't <em>have</em> to be free, but it would be a bonus if it was.</p>
<p>It should support Visual Studio 2008 or Visual Studio 2005 and .NET 2 and 3(.5).</p> | 214,788 | 8 | 0 | null | 2008-10-18 08:38:32.41 UTC | 12 | 2015-09-15 08:55:41.133 UTC | 2014-03-07 14:01:37.537 UTC | KTC | 263,525 | null | 24,610 | null | 1 | 18 | c#|visual-studio|decompiling | 44,254 | <p>Here is a good article about <a href="http://en.csharp-online.net/Visual_Studio_Hacks%E2%80%94Hack_64:_Examine_the_Innards_of_Assemblies" rel="nofollow noreferrer">Reflector and how to integrate Reflector into Visual Studio</a>.</p>
<blockquote>
<p>Of particular interest is the Reflector.VisualStudio Add-In. This
add-in, created by Jaime Cansdale, allows for Reflector to be hosted
within Visual Studio. With this add-in, you can have Reflector
integrated within the Visual Studio environment.<br /><br /> To get
started, you will need to have the latest version of Reflector on your
machine. Once you have downloaded Reflector, download the latest
version of the Reflector.VisualStudio Add-In from
<a href="http://www.testdriven.NET/reflector" rel="nofollow noreferrer">http://www.testdriven.NET/reflector</a>. The download contains a number of
files that need to be placed in the same directory as Reflector.exe.
To install the add-in, drop to the command line and run:</p>
<pre><code>Reflector.VisualStudio.exe /install
</code></pre>
<p>After the add-in has been installed, you can start using Reflector from Visual Studio. You’ll notice a new menu item, Addins, which has a
menu option titled Reflector. This option, when selected, displays the
Reflector window, which can be docked in the IDE. Additionally, the
add-in provides context menu support.<br /><br /> When you right-click
in an open code file in Visual Studio, you’ll see a Reflector menu
item that expands into a submenu with options to disassemble the code
into C# or Visual Basic, display the call graph or callee graph, and
other related choices. The context menu also includes a Synchronize
with Reflector menu item that, when clicked, syncs the object browser
tree in the Reflector window with the current code file.</p>
</blockquote> |
476,953 | Xcode: Delete line hot-key | <p>I'm looking for a way to map some hot-keys to "delete the line that my cursor is on" in Xcode. I found "delete to end of line" and "delete to beginning of line" in the text key bindings, but I am missing how to completely delete the line no matter what I have selected. TextMate has this functionality mapped to Ctrl+Shift+D and I'd like the same thing if possible. Any ideas?</p> | 477,961 | 8 | 3 | null | 2009-01-25 00:27:01.73 UTC | 14 | 2017-06-17 11:27:50.7 UTC | 2011-11-06 01:21:09.873 UTC | Chris Hanson | 345,188 | TypeOneError | 53,653 | null | 1 | 19 | objective-c|xcode|keyboard-shortcuts | 21,199 | <p>You can set up a system-wide key binding file that will apply to all Cocoa apps.</p>
<p>To do what you want it should like like this:</p>
<p>In your home folder, Library/KeyBindings/DefaultKeyBinding.dict</p>
<pre><code>{
"^D" = (
"moveToBeginningOfLine:",
"deleteToEndOfLine:",
);
}
</code></pre>
<p>I believe if you only want it to apply to Xcode you can name the file <code>PBKeyBinding.dict</code> instead but I didn't try that myself. You can read more about this system <a href="https://developer.apple.com/library/mac/documentation/cocoa/conceptual/eventoverview/TextDefaultsBindings/TextDefaultsBindings.html" rel="nofollow noreferrer">here</a> and <a href="https://web.archive.org/web/20090826052401/http://www.erasetotheleft.com/post/mac-os-x-key-bindings" rel="nofollow noreferrer">here</a>.</p> |
552,744 | How do I profile memory usage in Python? | <p>I've recently become interested in algorithms and have begun exploring them by writing a naive implementation and then optimizing it in various ways.</p>
<p>I'm already familiar with the standard Python module for profiling runtime (for most things I've found the timeit magic function in IPython to be sufficient), but I'm also interested in memory usage so I can explore those tradeoffs as well (e.g. the cost of caching a table of previously computed values versus recomputing them as needed). Is there a module that will profile the memory usage of a given function for me?</p> | 552,810 | 8 | 1 | null | 2009-02-16 09:34:43.827 UTC | 151 | 2021-02-14 17:24:02.07 UTC | null | null | null | Lawrence Johnston | 1,512 | null | 1 | 319 | python|memory|profiling | 398,049 | <p>This one has been answered already here: <a href="https://stackoverflow.com/questions/110259/python-memory-profiler">Python memory profiler</a></p>
<p>Basically you do something like that (cited from <a href="http://guppy-pe.sourceforge.net/#Heapy" rel="noreferrer">Guppy-PE</a>):</p>
<pre><code>>>> from guppy import hpy; h=hpy()
>>> h.heap()
Partition of a set of 48477 objects. Total size = 3265516 bytes.
Index Count % Size % Cumulative % Kind (class / dict of class)
0 25773 53 1612820 49 1612820 49 str
1 11699 24 483960 15 2096780 64 tuple
2 174 0 241584 7 2338364 72 dict of module
3 3478 7 222592 7 2560956 78 types.CodeType
4 3296 7 184576 6 2745532 84 function
5 401 1 175112 5 2920644 89 dict of class
6 108 0 81888 3 3002532 92 dict (no owner)
7 114 0 79632 2 3082164 94 dict of type
8 117 0 51336 2 3133500 96 type
9 667 1 24012 1 3157512 97 __builtin__.wrapper_descriptor
<76 more rows. Type e.g. '_.more' to view.>
>>> h.iso(1,[],{})
Partition of a set of 3 objects. Total size = 176 bytes.
Index Count % Size % Cumulative % Kind (class / dict of class)
0 1 33 136 77 136 77 dict (no owner)
1 1 33 28 16 164 93 list
2 1 33 12 7 176 100 int
>>> x=[]
>>> h.iso(x).sp
0: h.Root.i0_modules['__main__'].__dict__['x']
>>>
</code></pre> |
158,070 | How to position one element relative to another with jQuery? | <p>I have a hidden DIV which contains a toolbar-like menu.</p>
<p>I have a number of DIVs which are enabled to show the menu DIV when the mouse hovers over them.</p>
<p>Is there a built-in function which will move the menu DIV to the top right of the active (mouse hover) DIV? I'm looking for something like <code>$(menu).position("topright", targetEl);</code></p> | 2,781,557 | 8 | 3 | null | 2008-10-01 15:01:01.66 UTC | 133 | 2019-01-01 07:03:26.177 UTC | 2015-11-03 08:17:39.557 UTC | user57508 | null | paul | 11,249 | null | 1 | 360 | jquery | 434,409 | <p><strong>NOTE:</strong> This requires jQuery UI (not just jQuery).</p>
<p>You can now use:</p>
<pre><code>$("#my_div").position({
my: "left top",
at: "left bottom",
of: this, // or $("#otherdiv")
collision: "fit"
});
</code></pre>
<p>For fast positioning (<em><a href="http://api.jqueryui.com/position/" rel="noreferrer">jQuery UI/Position</a></em>).</p>
<p>You can <a href="http://jqueryui.com/" rel="noreferrer">download jQuery UI here</a>.</p> |
17,840 | How can I learn about parser combinators? | <p>I've found a few resources on the subject, but they all require a deep understanding of <a href="http://en.wikipedia.org/wiki/Smalltalk" rel="noreferrer">SmallTalk</a> or <a href="http://en.wikipedia.org/wiki/Haskell_%28programming_language%29" rel="noreferrer">Haskell</a>, neither of which I know.</p> | 27,699 | 10 | 0 | null | 2008-08-20 12:38:49.83 UTC | 9 | 2014-06-06 11:18:02.41 UTC | 2012-04-25 17:49:16.86 UTC | null | 1,332,690 | Gaius | 1,190 | null | 1 | 18 | parsing|monads | 7,445 | <p>Here are some parser combinator libraries in more mainstream languages:</p>
<ul>
<li><a href="http://spirit.sourceforge.net/documentation.html" rel="noreferrer">Spirit</a> (C++)</li>
<li><a href="http://jparsec.codehaus.org/" rel="noreferrer">Jparsec</a> (Java)</li>
</ul> |
455,237 | Pop off array in C# | <p>I've got a string array in C# and I want to pop the top element off the array (ie. remove the first element, and move all the others up one). Is there a simple way to do this in C#? I can't find an Array.Pop method.</p>
<p>Would I need to use something like an ArrayList? The order of the items in my array is important.</p> | 455,241 | 10 | 3 | null | 2009-01-18 14:41:39.62 UTC | 1 | 2021-03-10 13:37:35.843 UTC | null | null | null | robintw | 1,912 | null | 1 | 30 | c#|arrays | 69,271 | <p>Use a <a href="http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx" rel="noreferrer">List</a>, <a href="http://msdn.microsoft.com/en-us/library/7977ey2c.aspx" rel="noreferrer">Queue</a> or <a href="http://msdn.microsoft.com/en-us/library/3278tedw.aspx" rel="noreferrer">Stack</a> instead..</p>
<pre><code>List<String>
Queue<String>
Stack<String>
</code></pre> |
308,605 | Adding REST to Django | <p>I've got a Django application that works nicely. I'm adding REST services. I'm looking for some additional input on my REST strategy. </p>
<p>Here are some examples of things I'm wringing my hands over.</p>
<ul>
<li>Right now, I'm using the Django-REST API with a pile of patches. </li>
<li>I'm thinking of falling back to simply writing view functions in Django that return JSON results.</li>
<li>I can also see filtering the REST requests in Apache and routing them to a separate, non-Django server instance.</li>
</ul>
<p>Please nominate one approach per answer so we can vote them up or down.</p> | 308,785 | 11 | 0 | null | 2008-11-21 12:24:45.747 UTC | 28 | 2013-08-07 05:27:55.677 UTC | 2012-08-07 14:36:01.593 UTC | null | 1,288 | S.Lott | 10,661 | null | 1 | 51 | python|django|apache|rest | 28,264 | <blockquote>
<p>I'm thinking of falling back to simply
writing view functions in Django that
return JSON results.</p>
</blockquote>
<ul>
<li>Explicit</li>
<li>Portable to other frameworks</li>
<li>Doesn't require patching Django</li>
</ul> |
558,216 | Function to determine if two numbers are nearly equal when rounded to n significant decimal digits | <p>I have been asked to test a library provided by a 3rd party. The library is known to be accurate to <em>n</em> significant figures. Any less-significant errors can safely be ignored. I want to write a function to help me compare the results:</p>
<pre><code>def nearlyequal( a, b, sigfig=5 ):
</code></pre>
<p>The purpose of this function is to determine if two floating-point numbers (a and b) are approximately equal. The function will return True if a==b (exact match) or if a and b have the same value when rounded to <strong>sigfig</strong> significant-figures when written in decimal. </p>
<p>Can anybody suggest a good implementation? I've written a mini unit-test. Unless you can see a bug in my tests then a good implementation should pass the following:</p>
<pre><code>assert nearlyequal(1, 1, 5)
assert nearlyequal(1.0, 1.0, 5)
assert nearlyequal(1.0, 1.0, 5)
assert nearlyequal(-1e-9, 1e-9, 5)
assert nearlyequal(1e9, 1e9 + 1 , 5)
assert not nearlyequal( 1e4, 1e4 + 1, 5)
assert nearlyequal( 0.0, 1e-15, 5 )
assert not nearlyequal( 0.0, 1e-4, 6 )
</code></pre>
<p>Additional notes:</p>
<ol>
<li>Values a and b might be of type int, float or numpy.float64. Values a and b will always be of the same type. It's vital that conversion does not introduce additional error into the function.</li>
<li>Lets keep this numerical, so functions that convert to strings or use non-mathematical tricks are not ideal. This program will be audited by somebody who is a mathematician who will want to be able to prove that the function does what it is supposed to do.</li>
<li>Speed... I've got to compare a lot of numbers so the faster the better.</li>
<li>I've got numpy, scipy and the standard-library. Anything else will be hard for me to get, especially for such a small part of the project.</li>
</ol> | 558,322 | 11 | 2 | null | 2009-02-17 18:49:20.757 UTC | 9 | 2018-08-22 09:27:22.23 UTC | 2016-08-05 16:42:39.457 UTC | starblue | 4,230,591 | Salim Fadhley | 46,411 | null | 1 | 63 | python|math|floating-point|numpy | 81,266 | <p>There is a function <code>assert_approx_equal</code> in <code>numpy.testing</code> (source <a href="https://github.com/numpy/numpy/blob/1225aef37298ec82048d0828f6cb7e0be8ed58cc/numpy/testing/utils.py#L513" rel="noreferrer">here) </a>which may be a good starting point. </p>
<pre><code>def assert_approx_equal(actual,desired,significant=7,err_msg='',verbose=True):
"""
Raise an assertion if two items are not equal up to significant digits.
.. note:: It is recommended to use one of `assert_allclose`,
`assert_array_almost_equal_nulp` or `assert_array_max_ulp`
instead of this function for more consistent floating point
comparisons.
Given two numbers, check that they are approximately equal.
Approximately equal is defined as the number of significant digits
that agree.
</code></pre> |
716,827 | jQuery Click event on asp:button | <p>I have a server side button as </p>
<pre><code><asp:Button ID="btnSummary" runat="server" OnClick="btnSummary_Click" Text="Next" />
</code></pre>
<p>I want to attach the jQuery Click event using its ID and NOT using the alternative class attribute way.
<br/>
<br/>
I tried to attach the click event as:</p>
<pre><code>$("#btnSummary").click(function()
{
alert("1");
});
</code></pre>
<p>But, its click event is not fired. Also, I have also tried <code>$("id[$btnSummary]")</code>.
<br/><br/>
Is there any way to attach the click event on asp:button using jQuery without the class attribute on the button?</p> | 7,033,353 | 13 | 1 | null | 2009-04-04 09:39:51.157 UTC | 1 | 2020-10-09 20:31:36.493 UTC | 2011-08-12 17:50:04.907 UTC | null | 98,970 | Sachin Gaur | 2,572,740 | null | 1 | 5 | asp.net|jquery | 74,864 | <p>Add ClientIDMode="Static" to your asp:button, something like this:</p>
<pre><code><asp:Button ID="Button1" runat="server" ClientIDMode="Static" Text="Button" />
</code></pre>
<p>This will make the ID remain the same. It disables the autogenerated names for this control.</p>
<p>Here is the reference for this: <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.control.clientid.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/system.web.ui.control.clientid.aspx</a></p> |
131,901 | What are possible reasons for java.io.IOException: "The filename, directory name, or volume label syntax is incorrect" | <p>I am trying to copy a file using the following code:</p>
<pre><code>File targetFile = new File(targetPath + File.separator + filename);
...
targetFile.createNewFile();
fileInputStream = new FileInputStream(fileToCopy);
fileOutputStream = new FileOutputStream(targetFile);
byte[] buffer = new byte[64*1024];
int i = 0;
while((i = fileInputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, i);
}
</code></pre>
<p>For some users the <code>targetFile.createNewFile</code> results in this exception:</p>
<pre><code>java.io.IOException: The filename, directory name, or volume label syntax is incorrect
at java.io.WinNTFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(File.java:850)
</code></pre>
<p>Filename and directory name seem to be correct. The directory <code>targetPath</code> is even checked for existence before the copy code is executed and the filename looks like this: <code>AB_timestamp.xml</code></p>
<p>The user has write permissions to the <code>targetPath</code> and can copy the file without problems using the OS.</p>
<p>As I don't have access to a machine this happens on yet and can't reproduce the problem on my own machine I turn to you for hints on the reason for this exception.</p> | 133,845 | 13 | 0 | null | 2008-09-25 07:22:28.593 UTC | 3 | 2020-02-07 14:47:22.24 UTC | 2008-09-26 20:04:39.943 UTC | Dima | 13,313 | Turismo | 5,271 | null | 1 | 18 | java|exception|file-io | 107,103 | <p>Try this, as it takes more care of adjusting directory separator characters in the path between targetPath and filename:</p>
<pre><code>File targetFile = new File(targetPath, filename);
</code></pre> |
173,046 | Is there a simple JavaScript slider? | <p>I need to create a custom volume slider for a WMP object. The current slider is complicated to modify, and use, is there a simple way to generate a slider on an HTML page that can have it's value passed to a javascript function?</p> | 173,049 | 13 | 6 | null | 2008-10-06 02:21:56.98 UTC | 14 | 2014-07-03 10:58:14.283 UTC | 2014-06-11 17:12:45.85 UTC | null | 2,377,343 | Unkwntech | 115 | null | 1 | 43 | javascript|slider|controls|wmp | 101,171 | <p><a href="http://jqueryui.com/demos/slider/" rel="noreferrer">jQuery UI Slider</a> (<a href="http://docs.jquery.com/UI/Slider" rel="noreferrer">API docs</a>)</p> |
1,092,144 | What mobile platform should I start learning? | <p>What mobile platform should I start learning?
What matters is:</p>
<ul>
<li>ease</li>
<li>popularity of the platform</li>
<li>low cost of the SDK and actual handheld</li>
</ul> | 1,092,208 | 22 | 0 | 2009-08-26 05:47:45.117 UTC | 2009-07-07 12:51:01.54 UTC | 23 | 2019-07-29 17:08:51.51 UTC | 2010-12-14 10:28:57.56 UTC | null | 63,550 | null | 63,051 | null | 1 | 27 | iphone|android|windows-mobile|java-me|symbian | 7,560 | <p>I think 3-4 platforms have a future. But it depends on what platform do you like and how you like freedom in distributing your applications :)</p>
<ol>
<li>Windows Phone 7
<ul>
<li>.NET and Silverlight</li>
<li>through <a href="http://en.wikipedia.org/wiki/Windows_Phone_Marketplace" rel="nofollow noreferrer">Windows Phone Marketplace</a></li>
</ul></li>
<li>Android
<ul>
<li>Java </li>
<li>through <a href="http://en.wikipedia.org/wiki/Android_Market" rel="nofollow noreferrer">Android Market</a> (fees) or like normal applications</li>
</ul></li>
<li>iPhone
<ul>
<li>Objective-C or Java (<a href="http://www.youtube.com/watch?v=s8nMpi5-P-I" rel="nofollow noreferrer">Developing iPhone Applications using Java</a>)</li>
<li>through iPhone Market </li>
<li>pay some fees ($99/year)</li>
<li><a href="http://www.stromcode.com/2009/05/24/the-incredible-app-store-hype/" rel="nofollow noreferrer">The Incredible App Store Hype</a></li>
<li>You need Mac (Mac OS) for development (thanks to ctacke)</li>
</ul></li>
<li>Windows Mobile (my favorite)
<ul>
<li>C++ or .NET </li>
<li>free distribution, just like normal applications</li>
<li>Microsoft have a market, too - <a href="http://www.microsoft.com/windowsmobile/catalog/cataloghome.aspx" rel="nofollow noreferrer">here</a></li>
</ul></li>
<li>Java
<ul>
<li>J2ME or <a href="http://en.wikipedia.org/wiki/JavaFX" rel="nofollow noreferrer">JavaFX</a></li>
</ul></li>
</ol> |
1,134,290 | Cookies on localhost with explicit domain | <p>I must be missing some basic thing about cookies. On localhost, when I set a cookie on server side <em>and</em> specify the domain explicitly as localhost (or .localhost). the cookie does not seem to be accepted by some browsers.</p>
<p><strong>Firefox 3.5:</strong> I checked the HTTP request in Firebug. What I see is:</p>
<pre><code>Set-Cookie:
name=value;
domain=localhost;
expires=Thu, 16-Jul-2009 21:25:05 GMT;
path=/
</code></pre>
<p>or (when I set the domain to .localhost):</p>
<pre><code>Set-Cookie:
name=value;
domain=.localhost;
expires=Thu, 16-Jul-2009 21:25:05 GMT;
path=/
</code></pre>
<p>In either case, the cookie is not stored.</p>
<p><strong>IE8:</strong> I did not use any extra tool, but the cookie does not seem to be stored as well, because it’s not being sent back in subsequent requests.</p>
<p><strong>Opera 9.64:</strong> Both localhost and .localhost <em>work</em>, but when I check the list of cookies in Preferences, the domain is set to localhost.local even though it’s listed under localhost (in the list grouping).</p>
<p><strong>Safari 4:</strong> Both localhost and .localhost <em>work</em>, but they are always listed as .localhost in Preferences. On the other hand, a cookie without an explicit domain, it being shown as just localhost (no dot).</p>
<p>What is the problem with localhost? Because of such a number of inconsistencies, there must be some special rules involving localhost. Also, it’s not completely clear to me why domains must be prefixed by a dot? RFC 2109 explicitly states that: </p>
<blockquote>
<p>The value for the Domain attribute
contains no embedded dots or does not
start with a dot.</p>
</blockquote>
<p>Why? The document indicates that it has to do something with security. I have to admit that I have not read the entire specification (may do it later), but it sounds a bit strange. Based on this, setting cookies on localhost would be impossible.</p> | 1,188,145 | 23 | 5 | null | 2009-07-15 21:47:55.48 UTC | 82 | 2022-03-02 09:02:51.227 UTC | 2017-03-06 18:27:17.153 UTC | null | 6,150,115 | null | 15,716 | null | 1 | 260 | cookies|setcookie | 343,942 | <p>By design, domain names must have at least two dots; otherwise the browser will consider them invalid. (See reference on <a href="http://curl.haxx.se/rfc/cookie_spec.html" rel="noreferrer">http://curl.haxx.se/rfc/cookie_spec.html</a>)</p>
<p>When working on <code>localhost</code>, the cookie domain <strong>must be omitted entirely</strong>. You should not set it to <code>""</code> or <code>NULL</code> or <code>FALSE</code> instead of <code>"localhost"</code>. It is not enough.</p>
<p>For PHP, see comments on <a href="http://php.net/manual/en/function.setcookie.php#73107" rel="noreferrer">http://php.net/manual/en/function.setcookie.php#73107</a>.</p>
<p>If working with the Java Servlet API, don't call the <code>cookie.setDomain("...")</code> method at all.</p> |
34,539,786 | Rendering a dynamically created family graph with no overlapping using a depth first search? | <p>I want to generate this:</p>
<p><a href="https://i.stack.imgur.com/goX9M.png" rel="noreferrer"><img src="https://i.stack.imgur.com/goX9M.png" alt="enter image description here"></a></p>
<p>With this data structure (ids are random, btw not sequential):</p>
<pre><code>var tree = [
{ "id": 1, "name": "Me", "dob": "1988", "children": [4], "partners" : [2,3], root:true, level: 0, "parents": [5,6] },
{ "id": 2, "name": "Mistress 1", "dob": "1987", "children": [4], "partners" : [1], level: 0, "parents": [] },
{ "id": 3, "name": "Wife 1", "dob": "1988", "children": [5], "partners" : [1], level: 0, "parents": [] },
{ "id": 4, "name": "son 1", "dob": "", "children": [], "partners" : [], level: -1, "parents": [1,2] },
{ "id": 5, "name": "daughter 1", "dob": "", "children": [7], "partners" : [6], level: -1, "parents": [1,3] },
{ "id": 6, "name": "daughter 1s boyfriend", "dob": "", "children": [7], "partners" : [5], level: -1, "parents": [] },
{ "id": 7, "name": "son (bottom most)", "dob": "", "children": [], "partners" : [], level: -2, "parents": [5,6] },
{ "id": 8, "name": "jeff", "dob": "", "children": [1], "partners" : [9], level: 1, "parents": [10,11] },
{ "id": 9, "name": "maggie", "dob": "", "children": [1], "partners" : [8], level: 1, "parents": [] },
{ "id": 10, "name": "bob", "dob": "", "children": [8], "partners" : [11], level: 2, "parents": [12] },
{ "id": 11, "name": "mary", "dob": "", "children": [], "partners" : [10], level: 2, "parents": [] },
{ "id": 12, "name": "john", "dob": "", "children": [10], "partners" : [], level: 3, "parents": [] },
{ "id": 13, "name": "robert", "dob": "", "children": [9], "partners" : [], level: 2, "parents": [] },
{ "id": 14, "name": "jessie", "dob": "", "children": [9], "partners" : [], level: 2, "parents": [15,16] },
{ "id": 15, "name": "raymond", "dob": "", "children": [14], "partners" : [], level: 3, "parents": [] },
{ "id": 16, "name": "betty", "dob": "", "children": [14], "partners" : [], level: 3, "parents": [] },
];
</code></pre>
<p>To give a description of the data structure, the root/starting node (me) is defined. Any partner (wife,ex) is on the same level. Anything below becomes level -1, -2. Anything above is level 1, 2, etc. There are properties for <strong>parents, siblings, children</strong> and <strong>partners</strong> which define the ids for that particular field.</p>
<p>In my previous <a href="https://stackoverflow.com/questions/34011999/how-can-i-prevent-overlapping-in-a-family-tree-generator">question</a>, eh9 <a href="https://stackoverflow.com/a/34107384/145190">described</a> how he would solve this. I am attempting to do this, but as I've found out, it isn't an easy task.</p>
<p>My <a href="https://jsfiddle.net/txzp7c38/2/" rel="noreferrer">first attempt</a> is rendering this by levels from the top down. In this more simplistic attempt, I basically nest all of the people by levels and render this from the top down. </p>
<p>My <a href="https://jsfiddle.net/txzp7c38/4/" rel="noreferrer">second attempt</a> is rendering this with one of the ancestor nodes using a depth-first search. </p>
<p><strong>My main question is</strong>: How can I actually apply that answer to what I currently have? In my second attempt I'm trying to do a depth first traversal but how can I even begin to account for calculating the distances necessary to offset the grids to make it consistent with how I want to generate this?</p>
<p>Also, is my understanding/implementation of depth-first ideal, or can I traverse this differently?</p>
<p>The nodes obviously overlap in my second example since I have no offsetting/distance calculation code, but I'm lost as to actually figuring out how I can begin that.</p>
<p>Here is a description of the walk function I made, where I am attempting a depth first traversal:</p>
<pre><code>// this is used to map nodes to what they have "traversed". So on the first call of "john", dict would internally store this:
// dict.getItems() = [{ '12': [10] }]
// this means john (id=10) has traversed bob (id=10) and the code makes it not traverse if its already been traversed.
var dict = new Dictionary;
walk( nested[0]['values'][0] ); // this calls walk on the first element in the "highest" level. in this case it's "john"
function walk( person, fromPersonId, callback ) {
// if a person hasn't been defined in the dict map, define them
if ( dict.get(person.id) == null ) {
dict.set(person.id, []);
if ( fromPersonId !== undefined || first ) {
var div = generateBlock ( person, {
// this offset code needs to be replaced
top: first ? 0 : parseInt( $(getNodeById( fromPersonId ).element).css('top'), 10 )+50,
left: first ? 0 : parseInt( $(getNodeById( fromPersonId ).element).css('left'), 10 )+50
});
//append this to the canvas
$(canvas).append(div);
person.element = div;
}
}
// if this is not the first instance, so if we're calling walk on another node, and if the parent node hasn't been defined, define it
if ( fromPersonId !== undefined ) {
if ( dict.get(fromPersonId) == null ) {
dict.set(fromPersonId, []);
}
// if the "caller" person hasn't been defined as traversing the current node, define them
// so on the first call of walk, fromPersonId is null
// it calls walk on the children and passes fromPersonId which is 12
// so this defines {12:[10]} since fromPersonId is 12 and person.id would be 10 (bob)
if ( dict.get(fromPersonId).indexOf(person.id) == -1 )
dict.get(fromPersonId).push( person.id );
}
console.log( person.name );
// list of properties which house ids of relationships
var iterable = ['partners', 'siblings', 'children', 'parents'];
iterable.forEach(function(property) {
if ( person[property] ) {
person[property].forEach(function(nodeId) {
// if this person hasnt been "traversed", walk through them
if ( dict.get(person.id).indexOf(nodeId) == -1 )
walk( getNodeById( nodeId ), person.id, function() {
dict.get(person.id).push( nodeId );
});
});
}
});
}
</code></pre>
<p>}</p>
<p><strong>Requirements/restrictions:</strong></p>
<ol>
<li>This is for an editor and would be similar to familyecho.com. Pretty much any business rules not defined can be assumed through that.</li>
<li>In-family breeding isn't supported as it would make this way too complex. Don't worry about this.</li>
<li>Multiple partners are supported so this isn't as easy as a traditional "family tree" with just 2 parents and 1 child. </li>
<li>There is only one "root" node, which is just the starting node. </li>
</ol>
<p><strong>Notes</strong>: familyecho.com seems to "hide" a branch if there's lots of leaf nodes and there's a collision. May need to implement this.</p> | 34,875,339 | 5 | 11 | null | 2015-12-31 01:25:08.43 UTC | 12 | 2018-07-13 09:01:48.81 UTC | 2017-05-23 12:26:24.367 UTC | null | -1 | null | 145,190 | null | 1 | 51 | javascript|graph|family-tree|genealogy | 5,386 | <p>Although an answer has been posted (and accepted), I thought there is no harm in posting what I worked upon this problem last night.</p>
<p>I approached this problem more from a novice point of view rather than working out with existing algorithms of graph/tree traversal.</p>
<blockquote>
<p>My first attempt is rendering this by levels from the top down. In
this more simplistic attempt, I basically nest all of the people by
levels and render this from the top down.</p>
</blockquote>
<p>This was exactly my first attempt as well. You could traverse the tree top-down, or bottom-up or starting from the root. As you have been inspired by a particular website, starting from the root seems to be a logical choice. However, I found the bottom-up approach to be simpler and easier to understand. </p>
<p>Here is a crude attempt:</p>
<h2>Plotting the data:</h2>
<ol>
<li>We start from the bottom-most layer and work our way upwards. As mentioned in the question that you are trying to work it out via an editor, we can store all related properties in the object array as we build the tree.</li>
</ol>
<p>We cache the levels and use that to walk up the tree:</p>
<pre><code>// For all level starting from lowest one
levels.forEach(function(level) {
// Get all persons from this level
var startAt = data.filter(function(person) {
return person.level == level;
});
startAt.forEach(function(start) {
var person = getPerson(start.id);
// Plot each person in this level
plotNode(person, 'self');
// Plot partners
plotPartners(person);
// And plot the parents of this person walking up
plotParents(person);
});
});
</code></pre>
<p>Where, <code>getPerson</code> gets the object from the data based on its <code>id</code>.</p>
<ol start="2">
<li>As we are walking up, we plot the node itself, its parents (recursively) and its partners. Plotting partners is not really required, but I did it here just so that plotting the connectors could be easy. If a node has already been plotted, we simply skip that part.</li>
</ol>
<p>This is how we plot the partners:</p>
<pre><code>/* Plot partners for the current person */
function plotPartners(start) {
if (! start) { return; }
start.partners.forEach(function(partnerId) {
var partner = getPerson(partnerId);
// Plot node
plotNode(partner, 'partners', start);
// Plot partner connector
plotConnector(start, partner, 'partners');
});
}
</code></pre>
<p>And the parents recursively:</p>
<pre><code>/* Plot parents walking up the tree */
function plotParents(start) {
if (! start) { return; }
start.parents.reduce(function(previousId, currentId) {
var previousParent = getPerson(previousId),
currentParent = getPerson(currentId);
// Plot node
plotNode(currentParent, 'parents', start, start.parents.length);
// Plot partner connector if multiple parents
if (previousParent) { plotConnector(previousParent, currentParent, 'partners'); }
// Plot parent connector
plotConnector(start, currentParent, 'parents');
// Recurse and plot parent by walking up the tree
plotParents(currentParent);
return currentId;
}, 0);
}
</code></pre>
<p>Where we use <code>reduce</code> to simplify plotting a connector between two parents as partners.</p>
<ol start="3">
<li>This is how we plot a node itself:</li>
</ol>
<p>Where, we reuse the coordinates for each unique level via the <code>findLevel</code> utility function. We maintain a map of levels and check that to arrive at the <code>top</code> position. Rest is determined on the basis of relationships. </p>
<pre><code>/* Plot a single node */
function plotNode() {
var person = arguments[0], relationType = arguments[1], relative = arguments[2], numberOfParents = arguments[3],
node = get(person.id), relativeNode, element = {}, thisLevel, exists
;
if (node) { return; }
node = createNodeElement(person);
// Get the current level
thisLevel = findLevel(person.level);
if (! thisLevel) {
thisLevel = { 'level': person.level, 'top': startTop };
levelMap.push(thisLevel);
}
// Depending on relation determine position to plot at relative to current person
if (relationType == 'self') {
node.style.left = startLeft + 'px';
node.style.top = thisLevel.top + 'px';
} else {
relativeNode = get(relative.id);
}
if (relationType == 'partners') {
// Plot to the right
node.style.left = (parseInt(relativeNode.style.left) + size + (gap * 2)) + 'px';
node.style.top = parseInt(relativeNode.style.top) + 'px';
}
if (relationType == 'children') {
// Plot below
node.style.left = (parseInt(relativeNode.style.left) - size) + 'px';
node.style.top = (parseInt(relativeNode.style.top) + size + gap) + 'px';
}
if (relationType == 'parents') {
// Plot above, if single parent plot directly above else plot with an offset to left
if (numberOfParents == 1) {
node.style.left = parseInt(relativeNode.style.left) + 'px';
node.style.top = (parseInt(relativeNode.style.top) - gap - size) + 'px';
} else {
node.style.left = (parseInt(relativeNode.style.left) - size) + 'px';
node.style.top = (parseInt(relativeNode.style.top) - gap - size) + 'px';
}
}
// Avoid collision moving to right
while (exists = detectCollision(node)) {
node.style.left = (exists.left + size + (gap * 2)) + 'px';
}
// Record level position
if (thisLevel.top > parseInt(node.style.top)) {
updateLevel(person.level, 'top', parseInt(node.style.top));
}
element.id = node.id; element.left = parseInt(node.style.left); element.top = parseInt(node.style.top);
elements.push(element);
// Add the node to the DOM tree
tree.appendChild(node);
}
</code></pre>
<p>Here to keep it simple, I used a very crude collision detection to move nodes to right when one already exists. In a much sophisticated app, this would move nodes dynamically to the left or right to maintain a horizontal balance.</p>
<p>Lastly, we add that node to the DOM.</p>
<ol start="4">
<li>Rest are all helper functions.</li>
</ol>
<p>The important ones are:</p>
<pre><code>function detectCollision(node) {
var element = elements.filter(function(elem) {
var left = parseInt(node.style.left);
return ((elem.left == left || (elem.left < left && left < (elem.left + size + gap))) && elem.top == parseInt(node.style.top));
});
return element.pop();
}
</code></pre>
<p>Above is a simple detection of collision taking into account the gap between the nodes.</p>
<p>And, to plot the connectors:</p>
<pre><code>function plotConnector(source, destination, relation) {
var connector = document.createElement('div'), orientation, start, stop,
x1, y1, x2, y2, length, angle, transform
;
orientation = (relation == 'partners') ? 'h' : 'v';
connector.classList.add('asset');
connector.classList.add('connector');
connector.classList.add(orientation);
start = get(source.id); stop = get(destination.id);
if (relation == 'partners') {
x1 = parseInt(start.style.left) + size; y1 = parseInt(start.style.top) + (size/2);
x2 = parseInt(stop.style.left); y2 = parseInt(stop.style.top);
length = (x2 - x1) + 'px';
connector.style.width = length;
connector.style.left = x1 + 'px';
connector.style.top = y1 + 'px';
}
if (relation == 'parents') {
x1 = parseInt(start.style.left) + (size/2); y1 = parseInt(start.style.top);
x2 = parseInt(stop.style.left) + (size/2); y2 = parseInt(stop.style.top) + (size - 2);
length = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
angle = Math.atan2(y2 - y1, x2 - x1) * 180 / Math.PI;
transform = 'rotate(' + angle + 'deg)';
connector.style.width = length + 'px';
connector.style.left = x1 + 'px';
connector.style.top = y1 + 'px';
connector.style.transform = transform;
}
tree.appendChild(connector);
}
</code></pre>
<p>I used two different connectors, a horizontal one to connect partners, and an angled one to connect parent-child relationships. This turned out to be a very tricky part for me, i.e. to plot inverted <code>]</code> horizontal connectors. This is why to keep it simple, I simply rotated a div to make it look like an angled connector.</p>
<ol start="5">
<li>Once the entire tree is drawn/plotted, there could be nodes which go off-screen due to negative positions (because we are traversing bottom-up). To offset this, we simply check if there are any negative positions, and then shift the entire tree downwards.</li>
</ol>
<p>Here is the complete code with a fiddle demo.</p>
<p><strong>Fiddle Demo: <a href="http://jsfiddle.net/abhitalks/fvdw9xfq/embedded/result/">http://jsfiddle.net/abhitalks/fvdw9xfq/embedded/result/</a></strong></p>
<hr>
<blockquote>
<p>This is for an editor and would be similar to</p>
</blockquote>
<h2>Creating an editor:</h2>
<p>The best way to test if it works, is to have an editor which allows you to create such trees/graphs on the fly and see if it plots successfully.</p>
<p>So, I also created a simple editor to test out. The code remains exactly the same, however has been re-factored a little to fit with the routines for the editor. </p>
<p><strong>Fiddle Demo with Editor: <a href="http://jsfiddle.net/abhitalks/56whqh0w/embedded/result">http://jsfiddle.net/abhitalks/56whqh0w/embedded/result</a></strong></p>
<p><strong>Snippet Demo with Editor (view full-screen):</strong></p>
<p><div class="snippet" data-lang="js" data-hide="true">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var sampleData = [
{ "id": 1, "name": "Me", "children": [4], "partners" : [2,3], root:true, level: 0, "parents": [8,9] },
{ "id": 2, "name": "Mistress", "children": [4], "partners" : [1], level: 0, "parents": [] },
{ "id": 3, "name": "Wife", "children": [5], "partners" : [1], level: 0, "parents": [] },
{ "id": 4, "name": "Son", "children": [], "partners" : [], level: -1, "parents": [1,2] },
{ "id": 5, "name": "Daughter", "children": [7], "partners" : [6], level: -1, "parents": [1,3] },
{ "id": 6, "name": "Boyfriend", "children": [7], "partners" : [5], level: -1, "parents": [] },
{ "id": 7, "name": "Son Last", "children": [], "partners" : [], level: -2, "parents": [5,6] },
{ "id": 8, "name": "Jeff", "children": [1], "partners" : [9], level: 1, "parents": [10,11] },
{ "id": 9, "name": "Maggie", "children": [1], "partners" : [8], level: 1, "parents": [13,14] },
{ "id": 10, "name": "Bob", "children": [8], "partners" : [11], level: 2, "parents": [12] },
{ "id": 11, "name": "Mary", "children": [], "partners" : [10], level: 2, "parents": [] },
{ "id": 12, "name": "John", "children": [10], "partners" : [], level: 3, "parents": [] },
{ "id": 13, "name": "Robert", "children": [9], "partners" : [14], level: 2, "parents": [] },
{ "id": 14, "name": "Jessie", "children": [9], "partners" : [13], level: 2, "parents": [15,16] },
{ "id": 15, "name": "Raymond", "children": [14], "partners" : [16], level: 3, "parents": [] },
{ "id": 16, "name": "Betty", "children": [14], "partners" : [15], level: 3, "parents": [] },
],
data = [], elements = [], levels = [], levelMap = [],
tree = document.getElementById('tree'), people = document.getElementById('people'), selectedNode,
startTop, startLeft, gap = 32, size = 64
;
/* Template object for person */
function Person(id) {
this.id = id ? id : '';
this.name = id ? id : '';
this.partners = [];
this.siblings = [];
this.parents = [];
this.children = [];
this.level = 0;
this.root = false;
}
/* Event listeners */
tree.addEventListener('click', function(e) {
if (e.target.classList.contains('node')) {
selectedNode = e.target;
select(selectedNode);
document.getElementById('title').textContent = selectedNode.textContent;
fillPeopleAtLevel();
}
});
document.getElementById('save').addEventListener('click', function() {
var pname = document.getElementById('pname').value;
if (pname.length > 0) {
data.forEach(function(person) {
if (person.id == selectedNode.id) {
person.name = pname;
selectedNode.textContent = pname;
document.getElementById('title').textContent = pname;
}
});
}
});
document.getElementById('add').addEventListener('click', function() {
addPerson(document.getElementById('relation').value);
plotTree();
});
document.getElementById('addExisting').addEventListener('click', function() {
attachParent();
plotTree();
});
document.getElementById('clear').addEventListener('click', startFresh);
document.getElementById('sample').addEventListener('click', function() {
data = sampleData.slice();
plotTree();
});
document.getElementById('download').addEventListener('click', function() {
if (data.length > 1) {
var download = JSON.stringify(data, null, 4);
var payload = "text/json;charset=utf-8," + encodeURIComponent(download);
var a = document.createElement('a');
a.href = 'data:' + payload;
a.download = 'data.json';
a.innerHTML = 'click to download';
var container = document.getElementById('downloadLink');
container.appendChild(a);
}
});
/* Initialize */
function appInit() {
// Approximate center of the div
startTop = parseInt((tree.clientHeight / 2) - (size / 2));
startLeft = parseInt((tree.clientWidth / 2) - (size / 2));
}
/* Start a fresh tree */
function startFresh() {
var start, downloadArea = document.getElementById('downloadLink');
// Reset Data Cache
data = [];
appInit();
while (downloadArea.hasChildNodes()) { downloadArea.removeChild(downloadArea.lastChild); }
// Add a root "me" person to start with
start = new Person('P01'); start.name = 'Me'; start.root = true;
data.push(start);
// Plot the tree
plotTree();
// Pre-select the root node
selectedNode = get('P01');
document.getElementById('title').textContent = selectedNode.textContent;
}
/* Plot entire tree from bottom-up */
function plotTree() {
// Reset other cache and DOM
elements = [], levels = [], levelMap = []
while (tree.hasChildNodes()) { tree.removeChild(tree.lastChild); }
// Get all the available levels from the data
data.forEach(function(elem) {
if (levels.indexOf(elem.level) === -1) { levels.push(elem.level); }
});
// Sort the levels in ascending order
levels.sort(function(a, b) { return a - b; });
// For all level starting from lowest one
levels.forEach(function(level) {
// Get all persons from this level
var startAt = data.filter(function(person) {
return person.level == level;
});
startAt.forEach(function(start) {
var person = getPerson(start.id);
// Plot each person in this level
plotNode(person, 'self');
// Plot partners
plotPartners(person);
// And plot the parents of this person walking up
plotParents(person);
});
});
// Adjust coordinates to keep the tree more or less in center
adjustNegatives();
}
/* Plot partners for the current person */
function plotPartners(start) {
if (! start) { return; }
start.partners.forEach(function(partnerId) {
var partner = getPerson(partnerId);
// Plot node
plotNode(partner, 'partners', start);
// Plot partner connector
plotConnector(start, partner, 'partners');
});
}
/* Plot parents walking up the tree */
function plotParents(start) {
if (! start) { return; }
start.parents.reduce(function(previousId, currentId) {
var previousParent = getPerson(previousId),
currentParent = getPerson(currentId);
// Plot node
plotNode(currentParent, 'parents', start, start.parents.length);
// Plot partner connector if multiple parents
if (previousParent) { plotConnector(previousParent, currentParent, 'partners'); }
// Plot parent connector
plotConnector(start, currentParent, 'parents');
// Recurse and plot parent by walking up the tree
plotParents(currentParent);
return currentId;
}, 0);
}
/* Plot a single node */
function plotNode() {
var person = arguments[0], relationType = arguments[1], relative = arguments[2], numberOfParents = arguments[3],
node = get(person.id), relativeNode, element = {}, thisLevel, exists
;
if (node) { return; }
node = createNodeElement(person);
// Get the current level
thisLevel = findLevel(person.level);
if (! thisLevel) {
thisLevel = { 'level': person.level, 'top': startTop };
levelMap.push(thisLevel);
}
// Depending on relation determine position to plot at relative to current person
if (relationType == 'self') {
node.style.left = startLeft + 'px';
node.style.top = thisLevel.top + 'px';
} else {
relativeNode = get(relative.id);
}
if (relationType == 'partners') {
// Plot to the right
node.style.left = (parseInt(relativeNode.style.left) + size + (gap * 2)) + 'px';
node.style.top = parseInt(relativeNode.style.top) + 'px';
}
if (relationType == 'children') {
// Plot below
node.style.left = (parseInt(relativeNode.style.left) - size) + 'px';
node.style.top = (parseInt(relativeNode.style.top) + size + gap) + 'px';
}
if (relationType == 'parents') {
// Plot above, if single parent plot directly above else plot with an offset to left
if (numberOfParents == 1) {
node.style.left = parseInt(relativeNode.style.left) + 'px';
node.style.top = (parseInt(relativeNode.style.top) - gap - size) + 'px';
} else {
node.style.left = (parseInt(relativeNode.style.left) - size) + 'px';
node.style.top = (parseInt(relativeNode.style.top) - gap - size) + 'px';
}
}
// Avoid collision moving to right
while (exists = detectCollision(node)) {
node.style.left = (exists.left + size + (gap * 2)) + 'px';
}
// Record level position
if (thisLevel.top > parseInt(node.style.top)) {
updateLevel(person.level, 'top', parseInt(node.style.top));
}
element.id = node.id; element.left = parseInt(node.style.left); element.top = parseInt(node.style.top);
elements.push(element);
// Add the node to the DOM tree
tree.appendChild(node);
}
/* Helper Functions */
function createNodeElement(person) {
var node = document.createElement('div');
node.id = person.id;
node.classList.add('node'); node.classList.add('asset');
node.textContent = person.name;
node.setAttribute('data-level', person.level);
return node;
}
function select(selectedNode) {
var allNodes = document.querySelectorAll('div.node');
[].forEach.call(allNodes, function(node) {
node.classList.remove('selected');
});
selectedNode.classList.add('selected');
}
function get(id) { return document.getElementById(id); }
function getPerson(id) {
var element = data.filter(function(elem) {
return elem.id == id;
});
return element.pop();
}
function fillPeopleAtLevel() {
if (!selectedNode) return;
var person = getPerson(selectedNode.id), level = (person.level + 1), persons, option;
while (people.hasChildNodes()) { people.removeChild(people.lastChild); }
data.forEach(function(elem) {
if (elem.level === level) {
option = document.createElement('option');
option.value = elem.id; option.textContent = elem.name;
people.appendChild(option);
}
});
return persons;
}
function attachParent() {
var parentId = people.value, thisId = selectedNode.id;
updatePerson(thisId, 'parents', parentId);
updatePerson(parentId, 'children', thisId);
}
function addPerson(relationType) {
var newId = 'P' + (data.length < 9 ? '0' + (data.length + 1) : data.length + 1),
newPerson = new Person(newId), thisPerson;
;
thisPerson = getPerson(selectedNode.id);
// Add relation between originating person and this person
updatePerson(thisPerson.id, relationType, newId);
switch (relationType) {
case 'children':
newPerson.parents.push(thisPerson.id);
newPerson.level = thisPerson.level - 1;
break;
case 'partners':
newPerson.partners.push(thisPerson.id);
newPerson.level = thisPerson.level;
break;
case 'siblings':
newPerson.siblings.push(thisPerson.id);
newPerson.level = thisPerson.level;
// Add relation for all other relatives of originating person
newPerson = addRelation(thisPerson.id, relationType, newPerson);
break;
case 'parents':
newPerson.children.push(thisPerson.id);
newPerson.level = thisPerson.level + 1;
break;
}
data.push(newPerson);
}
function updatePerson(id, key, value) {
data.forEach(function(person) {
if (person.id === id) {
if (person[key].constructor === Array) { person[key].push(value); }
else { person[key] = value; }
}
});
}
function addRelation(id, relationType, newPerson) {
data.forEach(function(person) {
if (person[relationType].indexOf(id) != -1) {
person[relationType].push(newPerson.id);
newPerson[relationType].push(person.id);
}
});
return newPerson;
}
function findLevel(level) {
var element = levelMap.filter(function(elem) {
return elem.level == level;
});
return element.pop();
}
function updateLevel(id, key, value) {
levelMap.forEach(function(level) {
if (level.level === id) {
level[key] = value;
}
});
}
function detectCollision(node) {
var element = elements.filter(function(elem) {
var left = parseInt(node.style.left);
return ((elem.left == left || (elem.left < left && left < (elem.left + size + gap))) && elem.top == parseInt(node.style.top));
});
return element.pop();
}
function adjustNegatives() {
var allNodes = document.querySelectorAll('div.asset'),
minTop = startTop, diff = 0;
for (var i=0; i < allNodes.length; i++) {
if (parseInt(allNodes[i].style.top) < minTop) { minTop = parseInt(allNodes[i].style.top); }
};
if (minTop < startTop) {
diff = Math.abs(minTop) + gap;
for (var i=0; i < allNodes.length; i++) {
allNodes[i].style.top = parseInt(allNodes[i].style.top) + diff + 'px';
};
}
}
function plotConnector(source, destination, relation) {
var connector = document.createElement('div'), orientation, start, stop,
x1, y1, x2, y2, length, angle, transform
;
orientation = (relation == 'partners') ? 'h' : 'v';
connector.classList.add('asset');
connector.classList.add('connector');
connector.classList.add(orientation);
start = get(source.id); stop = get(destination.id);
if (relation == 'partners') {
x1 = parseInt(start.style.left) + size; y1 = parseInt(start.style.top) + (size/2);
x2 = parseInt(stop.style.left); y2 = parseInt(stop.style.top);
length = (x2 - x1) + 'px';
connector.style.width = length;
connector.style.left = x1 + 'px';
connector.style.top = y1 + 'px';
}
if (relation == 'parents') {
x1 = parseInt(start.style.left) + (size/2); y1 = parseInt(start.style.top);
x2 = parseInt(stop.style.left) + (size/2); y2 = parseInt(stop.style.top) + (size - 2);
length = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
angle = Math.atan2(y2 - y1, x2 - x1) * 180 / Math.PI;
transform = 'rotate(' + angle + 'deg)';
connector.style.width = length + 'px';
connector.style.left = x1 + 'px';
connector.style.top = y1 + 'px';
connector.style.transform = transform;
}
tree.appendChild(connector);
}
/* App Starts Here */
appInit();
startFresh();</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>* { box-sizing: border-box; padding: 0; margin: 0; }
html, body { width: 100vw; height: 100vh; overflow: hidden; font-family: sans-serif; font-size: 0.9em; }
#editor { float: left; width: 20vw; height: 100vh; overflow: hidden; overflow-y: scroll; border: 1px solid #ddd; }
#tree { float: left; width: 80vw; height: 100vh; overflow: auto; position: relative; }
h2 { text-align: center; margin: 12px; color: #bbb; }
fieldset { margin: 12px; padding: 8px 4px; border: 1px solid #bbb; }
legend { margin: 0px 8px; padding: 4px; }
button, input, select { padding: 4px; margin: 8px 0px; }
button { min-width: 64px; }
div.node {
width: 64px; height: 64px; line-height: 64px;
background-color: #339; color: #efefef;
font-family: sans-serif; font-size: 0.7em;
text-align: center; border-radius: 50%;
overflow: hidden; position: absolute; cursor: pointer;
}
div.connector { position: absolute; background-color: #333; z-index: -10; }
div.connector.h { height: 2px; background-color: #ddd; }
div.connector.v { height: 1px; background-color: #66d; -webkit-transform-origin: 0 100%; transform-origin: 0 100%; }
div[data-level='0'] { background-color: #933; }
div[data-level='1'], div[data-level='-1'] { background-color: #393; }
div[data-level='2'], div[data-level='-2'] { background-color: #333; }
div.node.selected { background-color: #efefef; color: #444; }</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="editor">
<h2 id="title">Me</h2>
<div>
<fieldset>
<legend>Change Name</legend>
<label>Name: <input id="pname" type="text" /></label>
<br /><button id="save">Ok</button>
</fieldset>
<fieldset>
<legend>Add Nodes</legend>
<label for="relation">Add: </label>
<select id="relation">
<option value="partners">Partner</option>
<option value="siblings">Sibling</option>
<option value="parents">Parent</option>
<option value="children">Child</option>
</select>
<button id="add">Ok</button><br />
<label for="relation">Add: </label>
<select id="people"></select>
<button id="addExisting">As Parent</button>
</fieldset>
<fieldset>
<legend>Misc</legend>
<button id="clear">Clear</button>&nbsp;&nbsp;<button id="sample">Load Sample</button>
<br/><button id="download">Download Data</button>
</fieldset>
<fieldset id="downloadLink"></fieldset>
</div>
</div>
<div id="tree"></div></code></pre>
</div>
</div>
</p>
<hr>
<p>This is all a very crude attempt and beyond doubts an un-optimized one. What I particularly couldn't get done are:</p>
<ol>
<li>Getting inverted <code>[</code> or <code>]</code> shaped horizontal connectors for parent-child relationships.</li>
<li>Getting the tree to be horizontally balanced. i.e. dynamically figuring out which is the heavier side and then shifting those nodes to the left.</li>
<li>Getting the parent to centrally align with respect to children especially multiple children. Currently, my attempt simply pushes everything to right in order.</li>
</ol>
<p>Hope it helps. And posting it here so that I too can refer to it when needed.</p> |
6,621,653 | Django vs. Model View Controller | <p>Can somebody explain me where the diferences are between Django and the Model View Controller pattern?</p>
<p>Functionally, what can we expect from those differences — i.e. what works differently comparing Django to, for example, Ruby on Rails?</p> | 6,622,043 | 4 | 8 | null | 2011-07-08 08:05:49.703 UTC | 36 | 2019-08-30 20:34:22.123 UTC | 2013-06-01 02:27:00.81 UTC | null | 736,246 | null | 736,246 | null | 1 | 122 | django|model-view-controller|frameworks | 74,698 | <p>According to the <a href="http://www.djangobook.com" rel="noreferrer">Django Book</a>, Django follows the MVC pattern closely enough to be called an MVC framework.</p>
<p>Django has been referred to as an MTV framework because the controller is handled by the framework itself and most of the excitement happens in models, templates and views.</p>
<p>You can read more about MTV / MVC here:</p>
<p><a href="http://djangobook.com/model-view-controller-design-pattern/" rel="noreferrer">The MTV (or MVC) Development Pattern</a></p>
<blockquote>
<p>If you’re familiar with other MVC
Web-development frameworks, such as
Ruby on Rails, you may consider Django
views to be the <em>controllers</em> and
Django templates to be the <em>views</em>.</p>
<p>This is an unfortunate confusion
brought about by differing
interpretations of MVC.</p>
<p>In Django’s interpretation of MVC, the <em>view</em>
describes the data that gets presented
to the user; it’s not necessarily just
how the data looks, but which data is
presented.</p>
<p>In contrast, Ruby on Rails
and similar frameworks suggest that
the controller’s job includes deciding
which data gets presented to the user,
whereas the view is strictly how the
data looks, not which data is
presented.</p>
</blockquote> |
6,582,387 | Image resize under PhotoImage | <p>I need to resize an image, but I want to avoid PIL, since I cannot make it work under OS X - don't ask me why...</p>
<p>Anyway since I am satisfied with gif/pgm/ppm, the PhotoImage class is ok for me:</p>
<pre><code>photoImg = PhotoImage(file=imgfn)
images.append(photoImg)
text.image_create(INSERT, image=photoImg)
</code></pre>
<p>The problem is - how do I resize the image?
The following works only with PIL, which is the non-PIL equivalent?</p>
<pre><code>img = Image.open(imgfn)
img = img.resize((w,h), Image.ANTIALIAS)
photoImg = ImageTk.PhotoImage(img)
images.append(photoImg)
text.image_create(INSERT, image=photoImg)
</code></pre>
<p>Thank you!</p> | 38,241,889 | 5 | 0 | null | 2011-07-05 12:06:32.04 UTC | 6 | 2021-04-28 23:28:01.71 UTC | 2016-12-04 21:24:05.537 UTC | null | 6,374,964 | null | 538,256 | null | 1 | 32 | python|tkinter | 117,748 | <p>Because both <code>zoom()</code> and <code>subsample()</code> want integer as parameters, I used both.</p>
<p>I had to resize 320x320 image to 250x250, I ended up with </p>
<pre><code>imgpath = '/path/to/img.png'
img = PhotoImage(file=imgpath)
img = img.zoom(25) #with 250, I ended up running out of memory
img = img.subsample(32) #mechanically, here it is adjusted to 32 instead of 320
panel = Label(root, image = img)
</code></pre> |
6,950,074 | How does Xcode know who the project was "created by"? | <p>Whenever a new file is added to the project, Xcode adds the following lines of comments on top.</p>
<pre><code>// Created by {my name here} on 8/4/11.
// Copyright 2011 __{my company name here}__. All rights reserved.
</code></pre>
<p>How does it know what my name is? Does it assume that if my account name belongs to "Mike", "Mike" is the name of the developer writing this code?</p>
<p>Does it then look at Address Book trying to find out what company "Mike" works at? It would make sense, however company listed as part of my address book is not what shows up in the Xcode file.</p>
<p>Can one set the following up in some place where Xcode will read it from?</p>
<ul>
<li>Name</li>
<li>Company name</li>
<li>some other text describing something important</li>
</ul> | 6,983,301 | 6 | 0 | null | 2011-08-05 00:13:16.423 UTC | 10 | 2019-04-05 15:03:40.843 UTC | 2018-04-03 10:38:23.897 UTC | null | 1,033,581 | null | 359,862 | null | 1 | 24 | xcode|xcode-template | 15,654 | <p>In Address Book select yourself (or add yourself if you aren't there) and then go to Card -> Make This My Card in menu bar. The name, last name and company name from that card will be used to populate info in file headers when creating files from Xcode templates.</p>
<p>Alternatively, you could set it using defaults via Terminal.app like this:</p>
<pre><code>defaults write com.apple.Xcode PBXCustomTemplateMacroDefinitions '{ORGANIZATIONNAME="ACME Inc.";}'
</code></pre> |
6,704,813 | maven generating pom file | <p>I use maven 3.0.3 and have tried to generate pom for third-party jar like this:</p>
<blockquote>
<p>mvn install:install-file -Dfile=cobra.jar -DgroupId=com.cobra
-DartifactId=cobra -Dversion=0.98.4 -Dpackaging=jar -DgeneratePom=true</p>
</blockquote>
<p>According to link below it should generate proper pom.xml and install artifact in the repo.
<a href="http://maven.apache.org/plugins/maven-install-plugin/examples/generic-pom-generation.html" rel="noreferrer">http://maven.apache.org/plugins/maven-install-plugin/examples/generic-pom-generation.html</a></p>
<p>Meanwhile, it returns such a error:</p>
<blockquote>
<p>[ERROR] The goal you specified requires a project to execute but there
is no POM in this directory (D:\cobra-0.98.4\lib). Please verify you
invoked Maven from the correct directory. -> [Help 1]</p>
</blockquote>
<p>Why is it asking for pom.xml while it should generate pom.xml?</p> | 11,199,865 | 10 | 1 | null | 2011-07-15 09:05:24.143 UTC | 15 | 2022-09-01 16:25:26.663 UTC | 2011-07-15 09:33:13.39 UTC | null | 777,420 | null | 777,420 | null | 1 | 37 | maven|maven-3|pom.xml | 122,451 | <p>This is an old question, but was a serious PITA for me for a few minutes, so I thought I'd share:</p>
<p>I just ran into this problem, and I believe that the issue is probably platform-dependent. The real tip-off was that the solution from Cyril's answer wasn't working as expected: despite my specification of <code>-DgroupId=com.xyz</code> and <code>-DartifactId=whatever</code> on the command-line and the corresponding entry in the POM file, the jar was installed in the local repo under <code>com/whatever</code>.</p>
<p>This led me to experiment with quoting command-line arguments, and the eventual correct result from formatting the command-line like this (after deleting the POM file):</p>
<pre><code>mvn install:install-file "-Dfile=cobra.jar" "-DgroupId=com.cobra" "-DartifactId=cobra" "-Dversion=0.98.4" "-Dpackaging=jar" "-DgeneratePom=true"
</code></pre>
<p>Some of the quoting is doubtless redundant, but better safe than sorry, right? I happen to be running Vista on this computer, and would not be surprised if this problem were specific to this OS version...by the way, this was with Maven v3.0.4.</p> |
6,612,316 | How set Spannable object font with custom font | <p>I have Spannable object which I want to set its font by a custom font I have loaded before.</p>
<pre><code>Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/font_Name.ttf");
Spannable span1 = /*Spannable Item*/;
/// I want to set span1 to have tf font face???
/// Here where I want help.
</code></pre>
<p>EDIT : <br>
My problem is that I want to set two different custom fonts for the text view so I am working with the Spannable</p> | 10,741,161 | 10 | 2 | null | 2011-07-07 14:34:34.493 UTC | 34 | 2021-02-13 19:02:12.6 UTC | 2019-04-02 14:41:43.38 UTC | null | 1,000,551 | null | 833,729 | null | 1 | 93 | android|android-fonts|spannable | 67,528 | <p>This is a late answer but will help others to solve the issue.</p>
<h2>Use the following code:(I'm using Bangla and Tamil font)</h2>
<pre><code> TextView txt = (TextView) findViewById(R.id.custom_fonts);
txt.setTextSize(30);
Typeface font = Typeface.createFromAsset(getAssets(), "Akshar.ttf");
Typeface font2 = Typeface.createFromAsset(getAssets(), "bangla.ttf");
SpannableStringBuilder SS = new SpannableStringBuilder("আমারநல்வரவு");
SS.setSpan (new CustomTypefaceSpan("", font2), 0, 4,Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
SS.setSpan (new CustomTypefaceSpan("", font), 4, 11,Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
txt.setText(SS);
</code></pre>
<hr>
<p>The outcome is:</p>
<p><img src="https://i.stack.imgur.com/eJ55j.png" alt="enter image description here"></p>
<hr>
<h2>CustomTypefaceSpan Class:</h2>
<pre><code>package my.app;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.text.TextPaint;
import android.text.style.TypefaceSpan;
public class CustomTypefaceSpan extends TypefaceSpan {
private final Typeface newType;
public CustomTypefaceSpan(String family, Typeface type) {
super(family);
newType = type;
}
@Override
public void updateDrawState(TextPaint ds) {
applyCustomTypeFace(ds, newType);
}
@Override
public void updateMeasureState(TextPaint paint) {
applyCustomTypeFace(paint, newType);
}
private static void applyCustomTypeFace(Paint paint, Typeface tf) {
int oldStyle;
Typeface old = paint.getTypeface();
if (old == null) {
oldStyle = 0;
} else {
oldStyle = old.getStyle();
}
int fake = oldStyle & ~tf.getStyle();
if ((fake & Typeface.BOLD) != 0) {
paint.setFakeBoldText(true);
}
if ((fake & Typeface.ITALIC) != 0) {
paint.setTextSkewX(-0.25f);
}
paint.setTypeface(tf);
}
}
</code></pre>
<hr>
<p><a href="https://stackoverflow.com/questions/4819049/how-can-i-use-typefacespan-or-stylespan-with-custom-typeface">Reference</a></p> |
6,850,500 | Postgis installation: type "geometry" does not exist | <p>I am trying to create table with Postgis. I do it by this <a href="http://postgis.refractions.net/documentation/manual-1.5/ch02.html#id2619431" rel="noreferrer" title="official documentation">page</a>. But when I import postgis.sql file, I get a lot of errors:</p>
<pre><code>ERROR: type "geometry" does not exist
</code></pre>
<p>Does anybody know how can I fix it?</p> | 20,974,997 | 14 | 0 | null | 2011-07-27 20:01:22.897 UTC | 36 | 2022-06-10 03:47:59.583 UTC | 2014-03-13 21:31:15.14 UTC | null | 835,511 | null | 835,511 | null | 1 | 124 | postgresql|geometry|postgis | 102,963 | <p>I had the same problem, but it was fixed by running following code</p>
<pre><code>CREATE EXTENSION postgis;
</code></pre>
<p>In detail, </p>
<ol>
<li>open pgAdmin</li>
<li>select (click) your database</li>
<li>click "SQL" icon on the bar</li>
<li>run "CREATE EXTENSION postgis;" code</li>
</ol> |
6,737,824 | How to run a hello.js file in Node.js on windows? | <p>I am trying to run a hello world program written in javascript in a separate file named hello.js</p>
<p>Currently running windows version of node.js.</p>
<p>The code runs perfectly in console window but <strong>how do I reference the path in windows environment</strong>.</p>
<pre><code>C:\abc\zyx\hello.js
</code></pre>
<p>in Unix I guess it is showing $ node hello.js</p>
<p>I'm absolutely new to Node.js Please correct me if I am doing something wrong.</p>
<p>I tried </p>
<p><code>> node C:\abc\zyx\hello.js</code> ----didn't work</p>
<p><code>> C:\abc\zyx\hello.js</code> --didn't work</p>
<p><strong>UPDATE1:</strong></p>
<p>Added node.exe to the folder where hello.js file is sitting.<br>
Added path point to the folder c:\abc\zyx\ and I get an error that says </p>
<p>ReferenceError: hello is not defined</p>
<p>see contents of hello.js </p>
<pre><code>setTimeout(function() {
console.log('World!');
}, 2000);
console.log('Hello');
</code></pre>
<p><strong>UPDATE 2:</strong></p>
<p>So far I have tried all these version and <strong>none of them seems to work</strong>. May be I am doing something completely wrong.</p>
<pre><code>>node hello.js
>$ node hello.js
>node.exe hello.js
>node /hello.js
>node \hello.js
> \node \hello.js
> /node /hello.js
> C:\abc\xyz\node.exe C:\abc\xyz\hello.js
> C:\abc\xyz\node.exe C:/abc/xyz/hello.js
> hello.js
> /hello.js
> \hello.js
>node hello
</code></pre>
<p><strong>Refer to my file structure</strong></p>
<pre><code>.
├── hello.js
├── node.exe
└── paths.txt
</code></pre>
<p><strong>RESOLVED:</strong>
Instead of running node.exe, try running in command prompt with the following option and it worked.</p>
<pre><code>c:\>node c:\abc\hello.js
Hello
World! (after 2 secs)
</code></pre> | 6,738,741 | 17 | 6 | null | 2011-07-18 18:52:25.173 UTC | 95 | 2022-06-23 20:44:42.46 UTC | 2020-04-06 15:13:32.523 UTC | null | 36,948 | null | 581,922 | null | 1 | 359 | windows|node.js | 1,102,790 | <p>Here are the exact steps I just took to run the "Hello World" example found at <a href="http://nodejs.org/">http://nodejs.org/</a>. This is a quick and dirty example. For a permanent installation you'd want to store the executable in a more reasonable place than the root directory and update your <code>PATH</code> to include its location.</p>
<ol>
<li>Download the Windows executable here: <a href="http://nodejs.org/#download">http://nodejs.org/#download</a></li>
<li>Copy the file to C:\</li>
<li>Create C:\hello.js</li>
<li>Paste in the following content:</li>
</ol>
<pre class="lang-or-tag-here prettyprint-override"><code> var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(1337, "127.0.0.1");
console.log('Server running at http://127.0.0.1:1337/');
</code></pre>
<ol>
<li>Save the file</li>
<li>Start -> Run... -> cmd</li>
<li>c:</li>
<li><p>C:>node hello.js</p>
<pre><code>Server running at http://127.0.0.1:1337/
</code></pre></li>
</ol>
<p>That's it. This was done on Windows XP.</p> |
16,016,920 | type casting integer to void* | <pre><code>#include <stdio.h>
void pass(void* );
int main()
{
int x;
x = 10;
pass((void*)x);
return 0;
}
void pass(void* x)
{
int y = (int)x;
printf("%d\n", y);
}
output: 10
</code></pre>
<p>my questions from the above code..</p>
<ol>
<li><p>what happens when we typecast normal variable to void* or any pointer variable?</p></li>
<li><p>We have to pass address of the variable to the function because in function definition argument is pointer variable. But this code pass the normal variable ..</p></li>
</ol>
<p>This format is followed in linux pthread programming... I am an entry level C programmer. I am compiling this program in linux gcc compiler..</p> | 16,016,999 | 3 | 3 | null | 2013-04-15 13:49:49.19 UTC | 4 | 2013-04-15 14:01:10.287 UTC | 2013-04-15 13:54:34.243 UTC | null | 2,087,705 | user2282725 | null | null | 1 | 12 | c|linux|pointers|pthreads|void-pointers | 42,479 | <p>I'm only guessing here, but I think what you are supposed to do is actually pass the <em>address</em> of the variable to the function. You use the address-of operator <code>&</code> to do that</p>
<pre><code>int x = 10;
void *pointer = &x;
</code></pre>
<p>And in the function you get the value of the pointer by using the dereference operator <code>*</code>:</p>
<pre><code>int y = *((int *) pointer);
</code></pre> |
15,624,296 | How to find and stop all currently running threads? | <p>I have an multiple-threaded java project and I want to add a method stop() to stop all the running threads. The problem is that this project is developed by someone else, and I am not familiar with how it implements multiple threads. </p>
<p>What I know is that once the project get started, many threads are invoked and they run forever. Is there a way to find all running threads and stop them? I have searched a lot, and found how to get a list of running threads:</p>
<pre><code>Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
</code></pre>
<p>What to do next to stop all the running threads?</p>
<p>The reason why I want to stop these threads is that I need to deploy this project to OSGi container as a bundle. Once the bundle is started, multiple threads run forever. So I need to implement a destroy() method to stop all threads to control the bundle lifecycle.</p>
<p>How about</p>
<pre><code>for (Thread t : Thread.getAllStackTraces().keySet())
{ if (t.getState()==Thread.State.RUNNABLE)
t.interrupt();
}
for (Thread t : Thread.getAllStackTraces().keySet())
{ if (t.getState()==Thread.State.RUNNABLE)
t.stop();
}
</code></pre> | 15,624,615 | 3 | 10 | null | 2013-03-25 20:38:29.383 UTC | 8 | 2019-12-15 02:11:47.793 UTC | 2013-03-25 21:15:57.313 UTC | null | 1,388,157 | null | 1,388,157 | null | 1 | 18 | java|multithreading|osgi | 77,191 | <p>This is a dangerous idea. The Javadoc for <a href="http://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#stop--" rel="nofollow noreferrer"><code>Thread.stop()</code></a> explains:</p>
<blockquote>
<p>This method is inherently unsafe. Stopping a thread with Thread.stop causes it to unlock all of the monitors that it has locked (as a natural consequence of the unchecked ThreadDeath exception propagating up the stack). If any of the objects previously protected by these monitors were in an inconsistent state, the damaged objects become visible to other threads, potentially resulting in arbitrary behavior. Many uses of stop should be replaced by code that simply modifies some variable to indicate that the target thread should stop running. The target thread should check this variable regularly, and return from its run method in an orderly fashion if the variable indicates that it is to stop running. If the target thread waits for long periods (on a condition variable, for example), the interrupt method should be used to interrupt the wait.</p>
</blockquote>
<p>Fundamentally, threads need to be built and designed to safely terminate, it is not possible to safely kill arbitrary threads. A fairly standard pattern is implemented like so:</p>
<pre><code>public abstract class StoppableRunnable implements Runnable {
private volatile boolean stopWork;
private boolean done;
public final void run() {
setup();
while(!stopWork && !done) {
doUnitOfWork();
}
cleanup();
}
/**
* Safely instructs this thread to stop working,
* letting it finish it's current unit of work,
* then doing any necessary cleanup and terminating
* the thread. Notice that this does not guarentee
* the thread will stop, as doUnitOfWork() could
* block if not properly implemented.
*/
public void stop() {
stopWork = true;
}
protected void done() {
done = true;
}
protected void setup() { }
protected void cleanup() { }
/**
* Does as small a unit of work as can be defined
* for this thread. Once there is no more work to
* be done, done() should be called.
*/
protected abstract void doUnitOfWork();
}
</code></pre>
<p>You implied you aren't the author of these threads, which suggest they may not be safely stoppable. In such a case, you can call <a href="http://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#interrupt--" rel="nofollow noreferrer"><code>Thread.interrupt()</code></a> to instruct the thread to stop what it's doing (instead of the pattern described above, you could use <code>Thread.interrupt()</code> to similar effect) however similarly, if the thread's designer hasn't written it to handle interrupts, this may not do anything or cause inconsistent states or other errors.</p>
<p>Ultimately, <code>Thread.stop()</code> is what you want if you just want to "[Force] the thread to stop executing" and can't modify the thread's implementation; however like using <code>kill</code> in Unix, this is a dangerous proposition, and you should essentially consider your JVM to be in an unstable and irreparable state after terminating a thread in this way, and attempt to exit the program as quickly as possible thereafter.</p>
<hr>
<p><strong>Regarding your suggestion of interrupting then stopping:</strong></p>
<p>There's still a lot of problems here, in particular, interrupting does not guarantee the thread will interrupt immediately (it works similarly, though less explicitly, to my <code>StoppableRunnable</code> above) and instead sets a flag that the thread should interrupt when possible. This means you could call <code>Thread.interrupt()</code>, the thread could start it's proper interrupt-handling behavior, then midway through that, your call to <code>Thread.stop()</code> fires, violently killing the thread and potentially breaking your JVM. Calls to <code>Thread.interrupt()</code> provide no guarantee as to when or how the thread will respond to that interrupt, which is why I prefer the explicit behavior in <code>StoppableRunnable</code>. Needless to say, if you're ever going to call <code>Thread.stop()</code> there's little to be gained by calling <code>Thread.interrupt()</code> first. I don't recommend it, but you might as well just call <code>Thread.stop()</code> in the first place.</p>
<p>Additionally, recognize that the code running your loop is <em>itself in a thread</em> - meaning your loop could very well kill itself first, leaving all other threads running.</p> |
15,867,175 | PostgreSQL - DB user should only be allowed to call functions | <p>Currently I'm using PostgreSQL for my application. Since I am trying to put every SQL that contains a transaction (i.e. insert, update, delete) in a function, I stumbled upon this problem:</p>
<p>Is it possible that a database user may only be allowed to call functions and Select-Statements while he can not call SQL-Statements which contains a transaction? By "call functions" I mean any function. Regardless if it contains a transaction or not.</p>
<p>I already tried to create a user which can only call functions and Select-Statements. But I always end up with an error, when calling functions which contains transactions. For what I understand a dbuser needs write permissions if a he calls a function which uses an insert, update or delete statement.</p>
<p>Am I missing something? Is this scenario really not possible? Security-wise this would be really great because you pretty much prevent SQL-injection in the first place.</p> | 15,868,268 | 1 | 2 | null | 2013-04-07 20:03:53.183 UTC | 9 | 2017-05-20 16:52:02.533 UTC | 2013-04-07 22:18:15.193 UTC | null | 939,860 | null | 2,255,333 | null | 1 | 20 | postgresql|stored-procedures|transactions|sql-injection|user-permissions | 14,318 | <p>There is no "privilege on <code>SELECT</code>". All you need is the privilege to <code>EXECUTE</code> functions. Relevant function can run with <a href="http://www.postgresql.org/docs/current/interactive/sql-createfunction.html#SQL-CREATEFUNCTION-SECURITY" rel="noreferrer"><code>SECURITY DEFINER</code></a> to inherit all privileges of the owner. To restrict possible privilege escalation to a minimum a priori, make a daemon role own relevant functions with only the necessary privileges - not a superuser!</p>
<h3>Recipe</h3>
<p>As superuser ...</p>
<p>Create a non-superuser role <code>myuser</code>.</p>
<pre><code>CREATE ROLE myuser PASSWORD ...;
</code></pre>
<p>Create a group role <code>mygroup</code> and make <code>myuser</code> member in it.</p>
<pre><code>CREATE ROLE mygroup;
GRANT mygroup TO myuser;
</code></pre>
<p>You may want to add more users just like <code>myuser</code> later.</p>
<p>Do <strong>not grant any privileges at all</strong> to <code>myuser</code>.<br>
Only grant these to <code>mygroup</code>:</p>
<ul>
<li><code>GRANT CONNECT ON DATABASE mydb TO mygroup;</code></li>
<li><code>GRANT USAGE ON SCHEMA public TO mygroup;</code></li>
<li><code>GRANT EXECUTE ON FUNCTION foo() TO mygroup;</code></li>
</ul>
<p>Remove <em>all</em> privileges for <code>public</code> that <code>myuser</code> shouldn't have.</p>
<pre><code>REVOKE ALL ON ALL TABLES IN SCHEMA myschema FROM public;
</code></pre>
<p>There may be more. <a href="http://www.postgresql.org/docs/current/interactive/sql-grant.html" rel="noreferrer">I quote the manual:</a></p>
<blockquote>
<p>PostgreSQL grants default privileges on some types of objects to
<code>PUBLIC</code>. No privileges are granted to PUBLIC by default on tables,
columns, schemas or tablespaces. For other types, the default
privileges granted to PUBLIC are as follows: <code>CONNECT</code> and <code>CREATE TEMP
TABLE</code> for databases; <code>EXECUTE</code> privilege for functions; and <code>USAGE</code>
privilege for languages. The object owner can, of course, <code>REVOKE</code> both
default and expressly granted privileges. (For maximum security, issue
the <code>REVOKE</code> in the same transaction that creates the object; then there
is no window in which another user can use the object.) Also, these
initial default privilege settings can be changed using the <code>ALTER DEFAULT PRIVILEGES</code> command.</p>
</blockquote>
<p>Create a <strong>daemon role</strong> to <em>own</em> relevant functions.</p>
<pre><code>CREATE ROLE mydaemon;
</code></pre>
<p>Grant only privileges necessary to execute these functions to <code>mydaemon</code>, (including <code>EXECUTE ON FUNCTION</code> to allow another function to be called). Again, you can use group roles to bundle privileges and grant them to <code>mydaemon</code></p>
<pre><code>GRANT bundle1 TO mydaemon;
</code></pre>
<p>In addition you can use <a href="http://www.postgresql.org/docs/current/interactive/sql-alterdefaultprivileges.html" rel="noreferrer"><strong><code>DEFAULT PRIVILEGES</code></strong></a> to automatically grant certain privileges for future objects to a bundle or the daemon directly:</p>
<pre><code>ALTER DEFAULT PRIVILEGES IN SCHEMA myschema GRANT SELECT ON TABLES TO bundle1;
ALTER DEFAULT PRIVILEGES IN SCHEMA myschema GRANT USAGE ON SEQUENCES TO bundle1;
</code></pre>
<p>This applies only to the role it is executed for. <a href="http://www.postgresql.org/docs/current/interactive/sql-alterdefaultprivileges.html" rel="noreferrer">Per the documentation:</a></p>
<blockquote>
<p>If <code>FOR ROLE</code> is omitted, the current role is assumed.</p>
</blockquote>
<p>To also cover pre-existing objects in the schema (see <a href="https://stackoverflow.com/questions/15867175/postgresql-db-user-should-only-be-allowed-to-call-functions/15868268?noredirect=1#comment75197559_15868268">rob's comment</a>):</p>
<pre><code>GRANT SELECT ON ALL TABLES IN SCHEMA public TO bundle1;
GRANT USAGE ON ALL SEQUENCES IN SCHEMA public TO bundle1;
</code></pre>
<p>Make <code>mydaemon</code> own relevant functions. Could look like this:</p>
<pre><code>CREATE OR REPLACE FUNCTION foo()
...
SECURITY DEFINER SET search_path = myschema, pg_temp;
ALTER FUNCTION foo() OWNER TO mydaemon;
REVOKE EXECUTE ON FUNCTION foo() FROM public;
GRANT EXECUTE ON FUNCTION foo() TO mydaemon;
GRANT EXECUTE ON FUNCTION foo() TO mygroup;
-- possibly others ..
</code></pre>
<p><strike>###Note<br>
Due to <a href="http://code.pgadmin.org/trac/ticket/88" rel="noreferrer">this bug</a> in the current version 1.16.1 of <a href="http://www.pgadmin.org/" rel="noreferrer">pgAdmin</a> the necessary command </p>
<pre><code>REVOKE EXECUTE ON FUNCTION foo() FROM public;
</code></pre>
<p>is missing in the reverse engineered DDL script. Remember to add it, when recreating.</strike><br>
This bug is fixed in the current version pgAdmin 1.18.1.</p> |
15,605,925 | How to get the last exception object after an error is raised at a Python prompt? | <p>When debugging Python code at the interactive prompt (REPL), often I'll write some code which raises an exception, but I haven't wrapped it in a <code>try</code>/<code>except</code>, so once the error is raised, I've forever lost the exception object.</p>
<p>Often the traceback and error message Python prints out isn't enough. For example, when fetching a URL, the server might return a 40x error, and you need the content of the response via <code>error.read()</code> ... but you haven't got the error object anymore. For example:</p>
<pre><code>>>> import urllib2
>>> f = urllib2.urlopen('http://example.com/api/?foo=bad-query-string')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
...
urllib2.HTTPError: HTTP Error 400: Bad Request
</code></pre>
<p>Drat, what did the body of the response say? It probably had valuable error information in it...</p>
<p>I realize it's usually easy to re-run your code wrapped in a try/except, but that's not ideal. I also realize that in this specific case if I were using the <code>requests</code> library (which doesn't raise for HTTP errors), I wouldn't have this problem ... but I'm really wondering if there's a more general way to get the last exception object at a Python prompt in these cases.</p> | 15,606,149 | 3 | 0 | null | 2013-03-25 00:34:32.357 UTC | 6 | 2022-06-16 12:15:37.15 UTC | null | null | null | null | 68,707 | null | 1 | 64 | python|exception|try-catch|read-eval-print-loop | 31,596 | <p>The <code>sys</code> module provides some functions for post-hoc examining of exceptions: <a href="http://docs.python.org/2/library/sys.html#sys.last_type"><code>sys.last_type</code></a>, <a href="http://docs.python.org/2/library/sys.html#sys.last_value"><code>sys.last_value</code></a>, and <a href="http://docs.python.org/2/library/sys.html#sys.last_traceback"><code>sys.last_traceback</code></a>.</p>
<p><code>sys.last_value</code> is the one you're looking for.</p> |
15,710,701 | Horizontal list items | <p>So, I have attempted to create a horizontal list for use on a new website I am designing. I have attempted a number of the suggestions found online already such as setting 'float' to left and such - yet none of these have worked when it comes to fixing the problem.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code> ul#menuItems {
background: none;
height: 50px;
width: 100px;
margin: 0;
padding: 0;
}
ul#menuItems li {
display: inline;
list-style: none;
margin-left: auto;
margin-right: auto;
top: 0px;
height: 50px;
}
ul#menuItems li a {
font-family: Arial, Helvetica, sans-serif;
text-decoration: none;
font-weight: bolder;
color: #000;
height: 50px;
width: auto;
display: block;
text-align: center;
line-height: 50px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul id="menuItems">
<li>
<a href="index.php">Home</a>
</li>
<li>
<a href="index.php">DJ Profiles</a>
</li>
</ul></code></pre>
</div>
</div>
</p>
<p>Currently I am unsure of what is causing this issue, how would I go about and resolve it?</p> | 15,710,719 | 6 | 1 | null | 2013-03-29 20:09:40.33 UTC | 7 | 2022-01-04 00:56:02.18 UTC | 2018-11-13 05:59:26.693 UTC | null | 4,076,315 | null | 2,012,008 | null | 1 | 91 | html|css | 216,289 | <h1>Updated Answer</h1>
<p>I've noticed a lot of people are using this answer so I decided to update it a little bit. No longer including support for now-unsupported browsers.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>ul > li {
display: inline-block;
/* You can also add some margins here to make it look prettier */
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
<li> <a href="#">some item</a>
</li>
<li> <a href="#">another item</a>
</li>
</ul></code></pre>
</div>
</div>
</p> |
15,514,593 | "ImportError: No module named" when trying to run Python script | <p>I'm trying to run a script that launches, amongst other things, a python script. I get a ImportError: No module named ..., however, if I launch ipython and import the same module in the same way through the interpreter, the module is accepted. </p>
<p>What's going on, and how can I fix it? I've tried to understand how python uses PYTHONPATH but I'm thoroughly confused. Any help would greatly appreciated. </p> | 15,622,021 | 22 | 7 | null | 2013-03-20 03:10:19.377 UTC | 76 | 2022-07-04 08:50:12.357 UTC | 2022-02-03 18:40:58.743 UTC | user166390 | 1,766,755 | null | 1,516,302 | null | 1 | 198 | python|jupyter-notebook|ipython|jupyter|importerror | 382,191 | <p><strong>This issue arises due to the ways in which the command line IPython interpreter uses your current path vs. the way a separate process does</strong> (be it an IPython notebook, external process, etc). IPython will look for modules to import that are not only found in your sys.path, but also on your current working directory. When starting an interpreter from the command line, the current directory you're operating in is the same one you started ipython in. If you run</p>
<pre class="lang-py prettyprint-override"><code>import os
os.getcwd()
</code></pre>
<p>you'll see this is true.</p>
<p>However, let's say you're using an ipython notebook, run <code>os.getcwd()</code> and your current working directory is instead the folder in which you told the notebook to operate from in your ipython_notebook_config.py file (typically using the <code>c.NotebookManager.notebook_dir</code> setting).</p>
<p>The solution is to provide the python interpreter with the path-to-your-module. The simplest solution is to append that path to your sys.path list. In your notebook, first try:</p>
<pre class="lang-py prettyprint-override"><code>import sys
sys.path.append('my/path/to/module/folder')
import module_of_interest
</code></pre>
<p>If that doesn't work, you've got a different problem on your hands unrelated to path-to-import and you should provide more info about your problem.</p>
<p>The better (and more permanent) way to solve this is to set your <strong>PYTHONPATH</strong>, which provides the interpreter with additional directories look in for python packages/modules. Editing or setting the PYTHONPATH as a global var is os dependent, and is discussed in detail here for <a href="http://scipher.wordpress.com/2010/05/10/setting-your-pythonpath-environment-variable-linuxunixosx/" rel="noreferrer">Unix</a> or <a href="https://stackoverflow.com/questions/3701646/how-to-add-to-the-pythonpath-in-windows-7">Windows</a>.</p> |
10,754,682 | How to add double quotes to a line with SED or AWK? | <p>I have the following list of words:</p>
<pre><code>name,id,3
</code></pre>
<p>I need to have it double quoted like this:</p>
<pre><code>"name,id,3"
</code></pre>
<p>I have tried <code>sed 's/.*/\"&\"/g'</code> and got:</p>
<pre><code>"name,id,3
</code></pre>
<p>Which has only one double quote and is missing the closing double quote.</p>
<p>I've also tried <code>awk {print "\""$1"\""}</code> with exactly the same result. I need help.</p> | 10,755,347 | 7 | 3 | null | 2012-05-25 12:45:12.027 UTC | 9 | 2021-12-18 03:34:20.027 UTC | 2020-06-25 20:14:36.6 UTC | null | 548,225 | null | 2,582,933 | null | 1 | 27 | regex|shell|awk|sed|text-processing | 65,592 | <p>Your input file has carriage returns at the end of the lines. You need to use <code>dos2unix</code> on the file to remove them. Or you can do this:</p>
<pre><code>sed 's/\(.*\)\r/"\1"/g'
</code></pre>
<p>which will remove the carriage return and add the quotes.</p> |
10,720,867 | Why is my webserver in golang not handling concurrent requests? | <p>This simple HTTP server contains a call to time.Sleep() that makes
each request take five seconds. When I try quickly loading multiple
tabs in a browser, it is obvious that each request
is queued and handled sequentially. How can I make it handle concurrent requests?</p>
<pre><code>package main
import (
"fmt"
"net/http"
"time"
)
func serve(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Hello, world.")
time.Sleep(5 * time.Second)
}
func main() {
http.HandleFunc("/", serve)
http.ListenAndServe(":1234", nil)
}
</code></pre>
<p>Actually, I just found the answer to this after writing the question, and it is very subtle. I am posting it anyway, because I couldn't find the answer on Google. Can you see what I am doing wrong?</p> | 10,722,919 | 3 | 4 | null | 2012-05-23 13:23:36.427 UTC | 22 | 2016-06-15 22:22:02.01 UTC | null | null | null | null | 15,947 | null | 1 | 68 | go | 32,457 | <p>Your program already handles the requests concurrently. You can test it with <code>ab</code>, a benchmark tool which is shipped with Apache 2:</p>
<pre><code>ab -c 500 -n 500 http://localhost:1234/
</code></pre>
<p>On my system, the benchmark takes a total of 5043ms to serve all 500 concurrent requests. <strong>It's just your browser which limits the number of connections per website.</strong></p>
<p>Benchmarking Go programs isn't that easy by the way, because you need to make sure that your benchmark tool isn't the bottleneck and that it is also able to handle that many concurrent connections. Therefore, it's a good idea to use a couple of dedicated computers to generate load.</p> |
35,612,428 | Call async/await functions in parallel | <p>As far as I understand, in ES7/ES2016 putting multiple <code>await</code>'s in code will work similar to chaining <code>.then()</code> with promises, meaning that they will execute one after the other rather than in parallel. So, for example, we have this code:</p>
<pre><code>await someCall();
await anotherCall();
</code></pre>
<p>Do I understand it correctly that <code>anotherCall()</code> will be called only when <code>someCall()</code> is completed? What is the most elegant way of calling them in parallel?</p>
<p>I want to use it in Node, so maybe there's a solution with async library?</p>
<p>EDIT: I'm not satisfied with the solution provided in this question: <a href="https://stackoverflow.com/questions/24193595/slowdown-due-to-non-parallel-awaiting-of-promises-in-async-generators">Slowdown due to non-parallel awaiting of promises in async generators</a>, because it uses generators and I'm asking about a more general use case.</p> | 35,612,484 | 12 | 17 | null | 2016-02-24 20:28:46.92 UTC | 191 | 2022-08-23 04:59:14.127 UTC | 2020-12-25 01:07:25.853 UTC | null | 971,141 | null | 860,478 | null | 1 | 768 | javascript|node.js|asynchronous|ecmascript-6|babeljs | 435,107 | <p>You can await on <code>Promise.all()</code>:</p>
<pre><code>await Promise.all([someCall(), anotherCall()]);
</code></pre>
<p>To store the results:</p>
<pre><code>let [someResult, anotherResult] = await Promise.all([someCall(), anotherCall()]);
</code></pre>
<p>Note that <code>Promise.all</code> fails fast, which means that as soon as one of the promises supplied to it rejects, then the entire thing rejects.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const happy = (v, ms) => new Promise((resolve) => setTimeout(() => resolve(v), ms))
const sad = (v, ms) => new Promise((_, reject) => setTimeout(() => reject(v), ms))
Promise.all([happy('happy', 100), sad('sad', 50)])
.then(console.log).catch(console.log) // 'sad'</code></pre>
</div>
</div>
</p>
<p>If, instead, you want to wait for all the promises to either fulfill or reject, then you can use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/allSettled" rel="noreferrer"><code>Promise.allSettled</code></a>. Note that Internet Explorer does not natively support this method.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const happy = (v, ms) => new Promise((resolve) => setTimeout(() => resolve(v), ms))
const sad = (v, ms) => new Promise((_, reject) => setTimeout(() => reject(v), ms))
Promise.allSettled([happy('happy', 100), sad('sad', 50)])
.then(console.log) // [{ "status":"fulfilled", "value":"happy" }, { "status":"rejected", "reason":"sad" }]</code></pre>
</div>
</div>
</p>
<blockquote>
<p><strong>Note:</strong> If you use <code>Promise.all</code> actions that managed to finish before rejection happen are not rolled back, so you may need to take care of such situation. For example
if you have 5 actions, 4 quick, 1 slow and slow rejects. Those 4
actions may be already executed so you may need to roll back. In such situation consider using <code>Promise.allSettled</code> while it will provide exact detail which action failed and which not.</p>
</blockquote> |
13,614,803 | How to check if HTML5 audio has reached different errors | <p>Specifically, if one of the 206 requests for audio fails and buffering stops, is there a way to detect that state? Or should I have to check if buffering stopped by comparing the buffered amounts against past amounts?</p>
<p>Also how can I check if the specified source fails, could you then point it to another source? </p> | 14,489,392 | 3 | 1 | null | 2012-11-28 21:32:06.523 UTC | 14 | 2016-09-28 19:27:23.97 UTC | 2013-01-23 21:10:56.25 UTC | null | 670,377 | null | 720,735 | null | 1 | 25 | javascript|html|audio | 19,615 | <p><strong>1. Specifically, if one of the requests for audio fails and buffering stops, is there a way to detect that state?</strong></p>
<p>Yes, there is few ways to do this! But if you want to catch the error type you can attach the error event listener to the sources:</p>
<pre><code>$('audio').addEventListener('error', function failed(e) {
// audio playback failed - show a message saying why
// to get the source of the audio element use $(this).src
switch (e.target.error.code) {
case e.target.error.MEDIA_ERR_ABORTED:
alert('You aborted the video playback.');
break;
case e.target.error.MEDIA_ERR_NETWORK:
alert('A network error caused the audio download to fail.');
break;
case e.target.error.MEDIA_ERR_DECODE:
alert('The audio playback was aborted due to a corruption problem or because the video used features your browser did not support.');
break;
case e.target.error.MEDIA_ERR_SRC_NOT_SUPPORTED:
alert('The video audio not be loaded, either because the server or network failed or because the format is not supported.');
break;
default:
alert('An unknown error occurred.');
break;
}
}, true);
</code></pre>
<p><strong>2. Could you then point it to another source?</strong></p>
<p>Inside the error handler function you can change the source using the <code>src</code> property of the audio element:</p>
<pre><code>var audio = $(this);
audio.src = "new-audio-file.mp3";
audio.load();
</code></pre>
<p>Another option is to add multiple source to the same audio tag using this syntax:</p>
<pre><code><audio>
<source id="audio_player_ogv" src="test.ogv" type="audio/ogg" />
//In case that you can't load the ogv file it will try to load test.mp3
<source id="audio_player_mp3" src="test.mp3" type="audio/mpeg" />
</audio>
</code></pre>
<p><strong>3. About manage multiple audio files</strong></p>
<p>I would suggest to use a plugin if you are thinking to manage 206 audio files. I have been using <a href="http://www.schillmania.com/projects/soundmanager2/" rel="noreferrer">SoundManager2</a> for a while and it's very good!</p> |
13,721,063 | afterTextChanged() callback being called without the text being actually changed | <p>I have a fragment with an <code>EditText</code> and inside the <code>onCreateView()</code> I add a <code>TextWatcher</code> to the <code>EditText</code>.</p>
<p>Each time the fragment is being added for the second time <code>afterTextChanged(Editable s)</code> callback is being called without the text ever being changed.</p>
<p>Here is a code snippet :</p>
<pre><code>@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
...
myEditText = (EditText) v.findViewById(R.id.edit_text);
myEditText.addTextChangedListener(textWatcher);
...
}
TextWatcher textWatcher = new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
searchProgressBar.setVisibility(View.INVISIBLE);
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
Log.d(TAG, "after text changed");
}
}
</code></pre>
<p>I also set the fragment to retain its state, and I keep the instance of the fragment in the activity.</p> | 13,723,367 | 2 | 2 | null | 2012-12-05 10:27:54.303 UTC | 2 | 2020-10-15 10:52:48.807 UTC | 2013-09-17 15:28:01.397 UTC | null | 1,597,833 | null | 1,597,833 | null | 1 | 33 | android|android-edittext | 11,344 | <p><strong>Edited solution:</strong></p>
<p>As it seems the text was changed from the second time the fragment was attached because the fragment restored the previous state of the views.</p>
<p>My solution was adding the <code>text watcher</code> in the <code>onResume()</code> since the state was restored <strong>before</strong> the <code>onResume</code> was called.</p>
<pre><code>@Override
public void onResume() {
super.onResume();
myEditText.addTextChangedListener(textWatcher);
}
</code></pre>
<p><strong>Edit</strong>
As @MiloszTylenda have mentioned in the comments it is better to remove the <code>Textwatcher</code> in the <code>onPause()</code> callback to avoid leaking the <code>Textwatcher</code>.</p>
<pre><code>@Override public void onPause() {
super.onPause();
myEditText.removeTextChangedListener(watcher);
}
</code></pre> |
13,418,669 | Javascript: Do I need to put this.var for every variable in an object? | <p>In C++, the language I'm most comfortable with, usually one declares an object like this:</p>
<pre><code>class foo
{
public:
int bar;
int getBar() { return bar; }
}
</code></pre>
<p>Calling <code>getBar()</code> works fine (ignoring the fact that <code>bar</code> might be uninitialized). The variable <code>bar</code> within <code>getBar()</code> is in the scope of class <code>foo</code>, so I don't need to say <code>this->bar</code> unless I really need to make it clear that I'm referring to the class' <code>bar</code> instead of, say, a parameter.</p>
<p>Now, I'm trying to get started with OOP in Javascript. So, I look up how to define classes and try the same sort of thing:</p>
<pre><code>function foo()
{
this.bar = 0;
this.getBar = function() { return bar; }
}
</code></pre>
<p>And it gives me <code>bar is undefined</code>. Changing the <code>bar</code> to <code>this.bar</code> fixes the issue, but doing that for every variable clutters up my code quite a bit. Is this necessary for every variable? Since I can't find any questions relating to this, it makes me feel like I'm doing something fundamentally wrong.</p>
<hr>
<p>EDIT: Right, so, from the comments what I'm getting is that <code>this.bar</code>, a property of an object, references something different than <code>bar</code>, a local variable. Can someone say why exactly this is, in terms of scoping and objects, and if there's another way to define an object where this isn't necessary?</p> | 13,418,980 | 6 | 6 | null | 2012-11-16 14:34:00.783 UTC | 17 | 2016-02-01 02:49:19.093 UTC | 2012-11-16 14:45:27.183 UTC | null | 1,110,292 | null | 1,110,292 | null | 1 | 38 | javascript|scope|this | 10,130 | <p>JavaScript has no <s>classes</s> class-based object model. It uses the mightier prototypical inheritance, which can mimic classes, but is not suited well for it. Everything is an object, and objects [can] inherit from other objects.</p>
<p>A constructor is just a function that assigns properties to newly created objects. The object (created by a call with the <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/new" rel="noreferrer"><code>new</code> keyword</a>) can be referenced trough the <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/this" rel="noreferrer"><code>this</code> keyword</a> (which is local to the function).</p>
<p>A method also is just a function which is called <em>on</em> an object - again with <code>this</code> pointing to the object. At least when that function is invoked as a property of the object, using a <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Member_Operators" rel="noreferrer">member operator</a> (dot, brackets). This causes lots of confusion to newbies, because if you pass around that function (e.g. to an event listener) it is "detached" from the object it was accessed on.</p>
<p>Now where is the inheritance? Instances of a "class" inherit from the same prototype object. Methods are defined as function properties on that object (instead of one function for each instance), the instance on which you call them just inherits that property.</p>
<p>Example:</p>
<pre><code>function Foo() {
this.bar = "foo"; // creating a property on the instance
}
Foo.prototype.foo = 0; // of course you also can define other values to inherit
Foo.prototype.getBar = function() {
// quite useless
return this.bar;
}
var foo = new Foo; // creates an object which inherits from Foo.prototype,
// applies the Foo constructor on it and assigns it to the var
foo.getBar(); // "foo" - the inherited function is applied on the object and
// returns its "bar" property
foo.bar; // "foo" - we could have done this easier.
foo[foo.bar]; // 0 - access the "foo" property, which is inherited
foo.foo = 1; // and now overwrite it by creating an own property of foo
foo[foo.getBar()]; // 1 - gets the overwritten property value. Notice that
(new Foo).foo; // is still 0
</code></pre>
<p>So, we did only use properties of that object and are happy with it. But all of them are "public", and can be overwritten/changed/deleted! If that doesn't matter you, you're lucky. You can indicate "privateness" of properties by prefixing their names with underscores, but that's only a hint to other developers and may not be obeyed (especially in error).</p>
<p>So, clever minds have found a solution that uses the constructor function as a closure, allowing the creating of private "attributes". Every execution of a javascript function creates a new variable environment for local variables, which may get garbage collected once the execution has finished. Every function that is declared inside that scope also has access to these variables, and as long as those functions could be called (e.g. by an event listener) the environment must persist. So, by <em>exporting locally defined functions</em> from your constructor you preserve that variable environment with local variables that can only be accessed by these functions.</p>
<p>Let's see it in action:</p>
<pre><code>function Foo() {
var bar = "foo"; // a local variable
this.getBar = function getter() {
return bar; // accesses the local variable
}; // the assignment to a property makes it available to outside
}
var foo = new Foo; // an object with one method, inheriting from a [currently] empty prototype
foo.getBar(); // "foo" - receives us the value of the "bar" variable in the constructor
</code></pre>
<p>This getter function, which is defined inside the constructor, is now called a "<em>privileged</em> method" as it has access to the "private" (local) "attributes" (variables). The value of <code>bar</code> will never change. You also could declare a setter function for it, of course, and with that you might add some validation etc.</p>
<p>Notice that the methods on the prototype object do not have access to the local variables of the constructor, yet they might use the privileged methods. Let's add one:</p>
<pre><code>Foo.prototype.getFooBar = function() {
return this.getBar() + "bar"; // access the "getBar" function on "this" instance
}
// the inheritance is dynamic, so we can use it on our existing foo object
foo.getFooBar(); // "foobar" - concatenated the "bar" value with a custom suffix
</code></pre>
<p>So, you can combine both approaches. Notice that the privileged methods need more memory, as you create distinct function objects with different scope chains (yet the same code). If you are going to create incredibly huge amounts of instances, you should define methods only on the prototype.</p>
<p>It gets even a little more complicated when you are setting up inheritance from one "class" to another - basically you have to make the child prototype object inherit from the parent one, and apply the parent constructor on child instances to create the "private attributes". Have a look at <a href="https://stackoverflow.com/q/10898786/1048572">Correct javascript inheritance</a>, <a href="https://stackoverflow.com/q/3617139/1048572">Private variables in inherited prototypes</a>, <a href="https://stackoverflow.com/q/12463040/1048572">Define Private field Members and Inheritance in JAVASCRIPT module pattern</a> and <a href="https://stackoverflow.com/q/9248655/1048572">How to implement inheritance in JS Revealing prototype pattern?</a></p> |
13,312,679 | Why is the != operator not allowed with OpenMP? | <p>I was trying to compile the following code:</p>
<pre><code>#pragma omp parallel shared (j)
{
#pragma omp for schedule(dynamic)
for(i = 0; i != j; i++)
{
// do something
}
}
</code></pre>
<p>but I got the following error: <strong>error: invalid controlling predicate</strong>.</p>
<p>The <a href="https://www.openmp.org//wp-content/uploads/spec30.pdf" rel="noreferrer">OpenMP standard</a> states that for <code>parallel for</code> constructor it "only" allows one of the following operators: <code><</code>, <code><=</code>, <code>></code> <code>>=</code>.</p>
<p>I do not understand the rationale for not allowing <code>i != j</code>. I could understand, in the case of the <code>static schedule</code>, since the compiler needs to pre-compute the number of iterations assigned to each thread. But I can't understand why this limitation in such case for example. Any clues?</p>
<hr />
<p><strong>EDIT:</strong> even if I make <code>for(i = 0; i != 100; i++)</code>, although I could just have put "<" or "<=" .</p> | 13,403,626 | 5 | 0 | null | 2012-11-09 17:08:15.4 UTC | 18 | 2020-12-24 17:31:43.96 UTC | 2020-12-24 17:31:43.96 UTC | null | 1,366,871 | null | 1,366,871 | null | 1 | 79 | c++|c|multithreading|parallel-processing|openmp | 6,794 | <p>.</p>
<h2><strong>I sent an email to OpenMP developers about this subject, the answer I got:</strong></h2>
<p>For signed int, the wrap around behavior is undefined. If we allow <code>!=</code>, programmers may get unexpected tripcount. The problem is whether the compiler can generate code to compute a trip count for the loop.</p>
<p>For a simple loop, like:</p>
<pre><code>for( i = 0; i < n; ++i )
</code></pre>
<p>the compiler can determine that there are 'n' iterations, <strong>if n>=0</strong>, and zero iterations <strong>if n < 0</strong>.</p>
<p>For a loop like:</p>
<pre><code>for( i = 0; i != n; ++i )
</code></pre>
<p>again, a compiler should be able to determine that there are 'n' iterations, <strong>if n >= 0</strong>; <strong>if n < 0</strong>, we don't know how many iterations it has.</p>
<p>For a loop like:</p>
<pre><code>for( i = 0; i < n; i += 2 )
</code></pre>
<p>the compiler can generate code to compute the trip count (loop iteration count) as <strong>floor((n+1)/2) if n >= 0</strong>, and 0 <strong>if n < 0</strong>.</p>
<p>For a loop like:</p>
<pre><code>for( i = 0; i != n; i += 2 )
</code></pre>
<p>the compiler can't determine whether 'i' will ever hit 'n'. What if 'n' is an odd number?</p>
<p>For a loop like:</p>
<pre><code>for( i = 0; i < n; i += k )
</code></pre>
<p>the compiler can generate code to compute the trip count as <strong>floor((n+k-1)/k) if n >= 0</strong>, and 0 <strong>if n < 0</strong>, because the compiler knows that the loop must count up; in this case, if <strong>k < 0</strong>, it's not a legal OpenMP program.</p>
<p>For a loop like:</p>
<pre><code>for( i = 0; i != n; i += k )
</code></pre>
<p>the compiler doesn't even know if i is counting up or down. It doesn't know if 'i' will ever hit 'n'. It may be an infinite loop.</p>
<p><strong>Credits</strong>: OpenMP ARB</p> |
20,660,999 | The type is defined in an assembly that is not referenced, how to find the cause? | <p>I know the error message is common and there are plenty of questions on SO about this error, but no solutions have helped me so far, so I decided to ask the question. Difference to most of similar questions is me using App_Code directory.</p>
<p>Error message:</p>
<pre class="lang-none prettyprint-override"><code>CS0012: The type 'Project.Rights.OperationsProvider' is defined in an
assembly that is not referenced. You must add a reference to assembly
'Project.Rights, version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.
</code></pre>
<p>Source File:</p>
<pre><code>c:\inetpub\wwwroot\Test\Website\App_Code\Company\Project\BusinessLogic\Manager.cs
</code></pre>
<p>Following suggestions <a href="https://stackoverflow.com/questions/496269/asp-net-page-says-i-need-to-reference-an-assembly-that-does-not-exist">here</a> and <a href="https://stackoverflow.com/questions/284433/strange-error-cs0012-the-type-x-is-defined-in-an-assembly-that-is-not-referen">here</a>, I have deleted all instances of Project.Rights.dll inside C:\Windows\Microsoft.NET/*.*
According to <a href="https://stackoverflow.com/questions/1222281/app-code-classes-not-accessable-asp-net">this</a>, I checked if .cs files in question have build action set to "Compile". They do.
I have also double checked that the .cs file containing the "Project.Rights.OperationsProvider" type is deployed to App_Code directory.</p>
<p>For some reason, application is not looking for the type in the App_Code directory. Since I've deleted all instances of Project.Rights.dll (that I know of), I don't know which assembly the error message is mentioning.</p> | 20,661,147 | 20 | 2 | null | 2013-12-18 14:37:36.097 UTC | 7 | 2022-05-05 14:06:06.123 UTC | 2018-07-23 14:00:10.09 UTC | null | 1,671,066 | null | 764,285 | null | 1 | 98 | c#|asp.net|.net|asp.net-4.0 | 271,983 | <p>When you get this error it isn't always obvious what is going on, but as the error says - you are missing a reference. Take the following line of code as an example:</p>
<pre><code>MyObjectType a = new MyObjectType("parameter");
</code></pre>
<p>It looks simple enough and you probably have referenced "MyObjectType" correctly. But lets say one of the overloads for the "MyObjectType" constructor takes a type that you don't have referenced. For example there is an overload defined as:</p>
<pre><code>public MyObjectType(TypeFromOtherAssembly parameter) {
// ... normal constructor code ...
}
</code></pre>
<p>That is at least one case where you will get this error. So, look for this type of pattern where you have referenced the type but not all the types of the properties or method parameters that are possible for functions being called on that type.</p>
<p>Hopefully this at least gets you going in the right direction!</p> |
3,291,637 | Alternatives to java.lang.reflect.Proxy for creating proxies of abstract classes (rather than interfaces) | <p>According to <a href="http://download.oracle.com/docs/cd/E17409_01/javase/6/docs/api/java/lang/reflect/Proxy.html" rel="noreferrer">the documentation</a>:</p>
<blockquote>
<p>[<code>java.lang.reflect.</code>]<code>Proxy</code> provides static methods for
creating dynamic proxy classes and
instances, and it is also the
superclass of all dynamic proxy
classes created by those methods.</p>
</blockquote>
<p>The <a href="http://download.oracle.com/docs/cd/E17409_01/javase/6/docs/api/java/lang/reflect/Proxy.html#newProxyInstance%28java.lang.ClassLoader,%20java.lang.Class%5b%5d,%20java.lang.reflect.InvocationHandler)" rel="noreferrer"><code>newProxyMethod</code> method</a> (responsible for generating the dynamic proxies) has the following signature:</p>
<pre><code>public static Object newProxyInstance(ClassLoader loader,
Class<?>[] interfaces,
InvocationHandler h)
throws IllegalArgumentException
</code></pre>
<p>Unfortunately, this prevents one from generating a dynamic proxy that <em>extends</em> a specific abstract class (rather than <em>implementing</em> specific interfaces). This makes sense, considering <code>java.lang.reflect.Proxy</code> is "the superclass of all dynamic proxies", thereby preventing another class from being the superclass.</p>
<p>Therefore, are there any alternatives to <code>java.lang.reflect.Proxy</code> that can generate dynamic proxies that <em>inherit</em> from a specific abstract class, redirecting all calls to the <strong>abstract</strong> methods to the invocation handler?</p>
<p>For example, suppose I have an abstract class <code>Dog</code>:</p>
<pre><code>public abstract class Dog {
public void bark() {
System.out.println("Woof!");
}
public abstract void fetch();
}
</code></pre>
<p>Is there a class that allows me to do the following?</p>
<pre><code>Dog dog = SomeOtherProxy.newProxyInstance(classLoader, Dog.class, h);
dog.fetch(); // Will be handled by the invocation handler
dog.bark(); // Will NOT be handled by the invocation handler
</code></pre> | 3,292,208 | 2 | 0 | null | 2010-07-20 15:31:01.35 UTC | 37 | 2015-07-01 17:35:03.853 UTC | 2010-07-21 11:07:24.62 UTC | null | 41,619 | null | 41,619 | null | 1 | 101 | java|dynamic-proxy | 49,204 | <p>It can be done using <a href="http://jboss-javassist.github.io/javassist/" rel="noreferrer">Javassist</a> (see <a href="http://jboss-javassist.github.io/javassist/html/javassist/util/proxy/ProxyFactory.html" rel="noreferrer"><code>ProxyFactory</code></a>) or <a href="https://github.com/cglib/cglib" rel="noreferrer">CGLIB</a>.</p>
<p><strong>Adam's example using Javassist:</strong></p>
<p>I (Adam Paynter) wrote this code using Javassist:</p>
<pre><code>ProxyFactory factory = new ProxyFactory();
factory.setSuperclass(Dog.class);
factory.setFilter(
new MethodFilter() {
@Override
public boolean isHandled(Method method) {
return Modifier.isAbstract(method.getModifiers());
}
}
);
MethodHandler handler = new MethodHandler() {
@Override
public Object invoke(Object self, Method thisMethod, Method proceed, Object[] args) throws Throwable {
System.out.println("Handling " + thisMethod + " via the method handler");
return null;
}
};
Dog dog = (Dog) factory.create(new Class<?>[0], new Object[0], handler);
dog.bark();
dog.fetch();
</code></pre>
<p>Which produces this output:</p>
<pre>
Woof!
Handling public abstract void mock.Dog.fetch() via the method handler
</pre> |
28,413,824 | Installing NumPy on Windows | <p>I'm simply unable to install NumPy on Windows. I keep getting this error -</p>
<pre><code>PS C:\python27> pip install http://sourceforge.net/projects/numpy/file/NumPy/
Collecting http://sourceforge.net/projects/numpy/files/NumPy/
Downloading http://sourceforge.net/projects/numpy/files/NumPy/ (58kB)
100% |################################| 61kB 15kB/s
Cannot unpack file c:\users\toshiba\appdata\local\temp\pip-qev4rz-unpack\NumPy
(downloaded from c:\users\toshiba\appdata\local\temp\pip-omripn-build, content-type: text/html; charset=utf-8); cannot detect archive format
Cannot determine archive format of c:\users\toshiba\appdata\local\temp\pip-omripn-build
</code></pre>
<p>I had a Python 64 bit version earlier and I was not sure if NumPy version was compatible with 64-bit Python. So I uninstalled it and installed a 32-bit Python version. But still I'm getting the same error. Though my Python 32-bit version is working fine.</p>
<p>I tried "pip install numpy", but that gave me the following error at the end -</p>
<pre><code>C:\Python27\lib\distutils\dist.py:267: UserWarning: Unknown distribution option: 'define_macros'
warnings.warn(msg)
error: Unable to find vcvarsall.bat
----------------------------------------
Command "C:\Python27\python.exe -c "import setuptools,tokenize;__file__='c:\\users\\toshiba\\appdata\\local\\temp\\pip-build-hdhqex\\numpy\\setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'),__file__, 'exec'))" install --record c:\users\toshiba\appdata\local\temp\pip-x_6llm-record\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in c:\users\toshiba\appdata\local\temp\pip-build-hdhqex\numpy
</code></pre>
<p>What might I be doing wrong?</p> | 28,414,059 | 5 | 6 | null | 2015-02-09 15:56:41.137 UTC | 8 | 2021-01-06 21:31:03.32 UTC | 2021-01-06 21:31:03.32 UTC | null | 63,550 | null | 3,722,183 | null | 1 | 7 | python|numpy|pip | 55,126 | <h2>Some explanations</h2>
<p>In the first case, I didn't check but I guess that <code>pip</code> directly downloads the resource corresponding to the given URL: <a href="http://sourceforge.net/projects/numpy/file/NumPy/">http://sourceforge.net/projects/numpy/file/NumPy/</a>. The server returns a HTML document, while <code>pip</code> expects an archive one. So that can't work.</p>
<p>Then there are basically two ways to install Python packages: </p>
<ul>
<li>from sources, as you tried then</li>
<li>from pre-compiled packages</li>
</ul>
<p>The first case, you tried it with the command <code>pip install numpy</code>, but since this package contains native code, it requires development tools to be installed properly (which I always found to be a pain in the neck to do on Windows, but I did it so it's clearly feasible). The error you have <code>error: Unable to find vcvarsall.bat</code> means you don't have the tools installed, or the environment properly set up.</p>
<p>For the second case, you have different kinds of pre-compiled packages: </p>
<ul>
<li>wheels, which you install with <code>pip</code> as well</li>
<li>installers, which you use as standard installers on Windows</li>
</ul>
<p>For both, you need to check that the binary has been strictly compiled for your Python architecture (32 or 64 bits) and version.</p>
<h2>An easy solution</h2>
<p>You can find there several wheels for <code>numpy</code>: <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy">http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy</a>. To get the proper architecture, check in the name <code>win32</code> for 32 bits and <code>amd64</code> for 64 bits. To get the proper Python version, check <code>cpXX</code>: first X is major version, and second X is minor version, so for instance <code>cp27</code> means CPython 2.7.</p>
<p>Example: <code>pip install numpy‑1.9.2rc1+mkl‑cp27‑none‑win32.whl</code></p>
<h2>The hard solution: installing and using development tools</h2>
<p><em><strong>DISCLAIMER</strong>: all the following explanations might not be quite clear. They result from several investigations at different moments, but in my configuration they led to a working solution. Some links might be useless, or redundant, but that's what I noted. All of this requires a bit of cleaning, and probably generalization too.</em></p>
<p>First, you need to understand that <code>disutils</code> - which is the pre-installed package which handles packages workflow at lower level than <code>pip</code> (and which is used by the latter) - will try to use a compiler that strictly matches the one that was used to build the Python machine you installed.</p>
<p>Official distributions of Python use Microsoft Visual C++ for Microsoft Windows packages. So you will need to install this compiler in this case.</p>
<h3>How to find proper version of Visual C++</h3>
<p>The string printed by Python with this command <code>python -c "import sys; print(sys.version)"</code> (or when you invoke the interactive shell) will look like this: </p>
<p><code>3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:45:13) [MSC v.1600 64 bit (AMD64)]</code></p>
<p>The last part between square brackets is the identification part of the compiler. Unfortunately, this is not quite straightforward, and you have correspondence lists there: </p>
<ul>
<li><a href="https://stackoverflow.com/questions/2676763/what-version-of-visual-studio-is-python-on-my-computer-compiled-with">windows - What version of Visual Studio is Python on my computer compiled with? - Stack Overflow</a>
<ul>
<li><a href="https://stackoverflow.com/questions/3592805/detecting-compiler-versions-during-compile-time">visual studio - Detecting compiler versions during compile time - Stack Overflow</a>3</li>
<li><a href="http://sourceforge.net/p/predef/wiki/Compilers/">Pre-defined Compiler Macros / Wiki / Compilers</a></li>
<li><a href="http://wincvt.sourceforge.net/">WinCvt - Windows Converter toolkit</a></li>
</ul></li>
</ul>
<p>In the example I gave above, this means <em>Microsoft Visual C++ 2010 64 bits</em>.</p>
<h3>How to install Visual C++</h3>
<p>You cannot find anymore a standalone package of Visual C++ for modern versions. So you will need to install the Windows SDK itself.</p>
<p>Here are some reference links: </p>
<ul>
<li><a href="http://www.microsoft.com/en-us/download/details.aspx?id=3138">Download Microsoft Windows SDK for Windows 7 and .NET Framework 3.5 SP1 from Official Microsoft Download Center</a>: for Visual C++ 15.00 (Visual Studio 2008). Corresponds to WinSDK 7.</li>
<li><a href="http://www.microsoft.com/en-us/download/details.aspx?id=8279">Download Microsoft Windows SDK for Windows 7 and .NET Framework 4 from Official Microsoft Download Center</a>: for Visual C++ 16.00 (Visual Studio 2010). Corresponds to WinSDK 7.1.</li>
<li><a href="https://superuser.com/questions/443617/where-can-i-download-the-full-installer-for-visual-c-express">installation - where can I download the full installer for Visual C++ Express? - Super User</a>
<ul>
<li><a href="http://www.visualstudio.com/en-us/downloads#d-2010-express">Visual Studio & co. downloads</a></li>
</ul></li>
</ul>
<p><strong>Troubleshooting</strong></p>
<p>You might have an error at the installation of the SDK:
<code>
DDSet_Error: Patch Hooks: Missing required property 'ProductFamily': Setup cannot continue.
DDSet_Warning: Setup failed while calling 'getDLLName'. System error: Cannot create a file when that file already exists.
</code></p>
<p>They have been reported in several questions already: </p>
<ul>
<li><a href="https://social.msdn.microsoft.com/Forums/windowsdesktop/en-US/8f3350f9-0b47-40ae-b070-f2ccbf041875/windows-7-sdk-installation-failure">Windows 7 SDK Installation Failure</a></li>
<li><a href="https://social.msdn.microsoft.com/Forums/windowsdesktop/en-US/6e6c8a17-1666-42fa-9b5b-dfc21845d2f9/error-installing-windows-7-sdk-71-with-vs2008-vs2010-premium-on-win-7-32bit?forum=windowssdk">Error installing Windows 7 SDK 7.1 with VS2008, VS2010 Premium on Win 7 32bit</a></li>
</ul>
<p>As a solution, you can check this link: <a href="https://support.microsoft.com/kb/2717426">Windows SDK Fails to Install with Return Code 5100</a></p>
<p>The thing is to remove all conflicting (understand: the ones that the SDK installer tries to install itself) version of the Visual C++ redistributable.</p>
<h3>Use development tools</h3>
<p>Normally you should run <code>vsvarsall.bat</code> (located inside the <code>VC</code> folder of the installation path of Visual Studio - example: <code>C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\vcvarsall.bat</code>) to set up the proper environment variables so that the execution of <code>distutils</code> doesn't fail when trying to compile a package.</p>
<p>This batch script accepts a parameter, which should set the wanted architecture. However I saw that with the free versions of the SDK some additional scripts were missing when trying several of these parameters.</p>
<p>Just to say that if you are compiling for a 32 bits architecture, simply calling <code>vsvarsall.bat</code> should work. If you need to compile for 64 bits, you can directly call <code>SetEnv.cmd</code>, located somewhere under inside the SDK installation path - example: <code>"C:\Program Files\Microsoft SDKs\Windows\v7.1\Bin\SetEnv.cmd" /x64</code>.</p> |
9,586,989 | Difference Between map and each | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/9429034/ruby-what-is-the-difference-between-map-each-and-collect">Ruby - What is the difference between map, each and collect?</a> </p>
</blockquote>
<p>I have looked in Ruby-Doc also but i cant understand the difference between</p>
<pre><code>map
each
</code></pre>
<p>iterators.It would be great if you could give an example and explain.</p> | 9,587,093 | 2 | 2 | null | 2012-03-06 15:45:22.057 UTC | 11 | 2019-02-10 19:22:20.403 UTC | 2017-05-23 12:17:42.97 UTC | null | -1 | user1065734 | null | null | 1 | 28 | ruby|map | 20,291 | <p><a href="https://ruby-doc.org/core/Enumerator.html#method-i-each" rel="noreferrer"><code>each</code></a> simply iterates over the given enumerable, running the block for each value. It discards the return value of the block, and each simply returns the original object it was called on:</p>
<pre><code>[1, 2, 3].each do |x|
x + 1
end # => [1, 2, 3]
</code></pre>
<p>This is simply a nicer, more universal way of doing a traditional iterating <code>for</code> loop, and <code>each</code> is <em>much</em> preferred over <code>for</code> loops in Ruby (in fact, I don't think I've ever used a <code>for</code> loop in Ruby).</p>
<hr>
<p><a href="https://ruby-doc.org/core/Enumerable.html#method-i-map" rel="noreferrer"><code>map</code></a>, however, iterates over each element, using the return value of the block to populate a new array at each respective index and return that new array:</p>
<pre><code>[1, 2, 3].map do |x|
x + 1
end # => [2, 3, 4]
</code></pre>
<p>So it “maps” each element to a new one using the block given, hence the name “map”. Note that neither <code>each</code> nor <code>map</code> themselves modify the original collection. This is a concise, functional alternative to creating an array and pushing to it in an iterative loop.</p> |
16,500,907 | Collapsible Panel in HTML/CSS | <p>I'm putting together a website. I need help creating the following feature: </p>
<p>I want the "About" link to expand into a panel when clicked, and retract when the user presses "hide" in the panel. I've attached a diagram below to clarify what it should look like. When the user presses About in (1), it becomes (2), and when the user presses hide in (2), it becomes (1) again.</p>
<p><img src="https://i.stack.imgur.com/xhPFE.png" alt="layout"></p>
<p>I would like to do this in pure HTML/CSS, if possible. Does anyone know how I can do this?</p> | 16,501,243 | 2 | 5 | null | 2013-05-11 19:26:42.917 UTC | 4 | 2018-04-16 16:47:33.98 UTC | 2013-10-29 20:36:12.86 UTC | null | 183,132 | null | 2,238,976 | null | 1 | 21 | html|css | 82,079 | <p>This answer explains how it can be achieved in full: <a href="https://stackoverflow.com/questions/15095933/pure-css-collapse-expand-div">Pure CSS collapse/expand div</a></p>
<p>Here is a quick rundown:</p>
<pre><code><div class="FAQ">
<a href="#hide1" class="hide" id="hide1">+</a>
<a href="#show1" class="show" id="show1">-</a>
<div class="question"> Question Question Question Question Question Question Question Question Question Question Question? </div>
<div class="list">
<p>Answer Answer Answer Answer Answer Answer Answer Answer Answer Answer Answer Answer Answer Answer Answer Answer Answer Answer </p>
</div>
</div>
</code></pre>
<p>CSS</p>
<pre><code>/* source: http://www.ehow.com/how_12214447_make-collapsing-lists-java.html */
.FAQ {
vertical-align: top;
height: auto;
}
.list {
display:none;
height:auto;
margin:0;
float: left;
}
.show {
display: none;
}
.hide:target + .show {
display: inline;
}
.hide:target {
display: none;
}
.hide:target ~ .list {
display:inline;
}
/*style the (+) and (-) */
.hide, .show {
width: 30px;
height: 30px;
border-radius: 30px;
font-size: 20px;
color: #fff;
text-shadow: 0 1px 0 #666;
text-align: center;
text-decoration: none;
box-shadow: 1px 1px 2px #000;
background: #cccbbb;
opacity: .95;
margin-right: 0;
float: left;
margin-bottom: 25px;
}
.hide:hover, .show:hover {
color: #eee;
text-shadow: 0 0 1px #666;
text-decoration: none;
box-shadow: 0 0 4px #222 inset;
opacity: 1;
margin-bottom: 25px;
}
.list p {
height:auto;
margin:0;
}
.question {
float: left;
height: auto;
width: 90%;
line-height: 20px;
padding-left: 20px;
margin-bottom: 25px;
font-style: italic;
}
</code></pre>
<p>And the working jsFiddle:</p>
<p><a href="http://jsfiddle.net/dmarvs/94ukA/4/" rel="nofollow noreferrer">http://jsfiddle.net/dmarvs/94ukA/4/</a></p>
<p>Again none of the above is my work just to clarify, but it just goes to show how easy it is to find it on Google!!</p> |
16,220,118 | how to add font-size toolbar in tinyMCE? | <p>this way i initialize tinyMCE to a textarea. font, bold italic is working but font size select is not working .</p>
<pre><code>tinymce.init({
selector: "textarea#content",
theme: "modern",
width: 586,
height: 300,
menubar:false,
font_size_classes : "fontSize1, fontSize2, fontSize3, fontSize4, fontSize5, fontSize6",//i used this line for font sizes
content_css: "css/content.css",
toolbar: "sizeselect | bold italic | fontselect | fontsize",//used font size for showing font size toolbar
style_formats: [
{title: 'Bold text', inline: 'b'},
{title: 'Red text', inline: 'span', styles: {color: '#ff0000'}},
{title: 'Red header', block: 'h1', styles: {color: '#ff0000'}},
{title: 'Example 1', inline: 'span', classes: 'example1'},
{title: 'Example 2', inline: 'span', classes: 'example2'},
{title: 'Table styles'},
{title: 'Table row 1', selector: 'tr', classes: 'tablerow1'}
],
});**
</code></pre> | 16,233,781 | 4 | 0 | null | 2013-04-25 16:31:49.923 UTC | 8 | 2018-08-28 17:49:52.087 UTC | 2017-12-19 12:32:04.043 UTC | null | 346,063 | null | 1,996,139 | null | 1 | 45 | javascript|css|fonts|tinymce|wysiwyg | 71,718 | <p>All you need to do is to add <code>fontsizeselect</code> to your toolbar config param:</p>
<pre><code>toolbar: "sizeselect | bold italic | fontselect | fontsizeselect",
</code></pre>
<p>Update:</p>
<pre><code>tinymce.init({
fontsize_formats: "8pt 10pt 12pt 14pt 18pt 24pt 36pt"
});
</code></pre> |
16,105,097 | Why isn't MessageBox TopMost? | <p>I recently found out that by default MessageBoxes were not the top most form when displayed by default and I was wondering if anyone knew any circumstances when you wouldn't want the messagebox to be shown on top of other windows?</p>
<p>I found the issue when I started to show splash screens whilst loading an application, and it looked like my program was still running but there was a <code>MessageBox</code> behind the splash screen that was waiting for input.. The splash screen was shown on a different thread to the thread that called the messagebox so I imagine this is why it didn't appear above the splash; but this still doesn't explain why MessageBox doesn't have the <code>MB_TOPMOST</code> flag by default?</p>
<p><strong>Edit</strong></p>
<p>To better clarify:
in the end I had to do something similar to this in the end to make a messagebox, code isn't exactly correct as wrote from memory)</p>
<pre><code>[DllImport("User32.dll")]
private int extern MessageBox(windowhandle, message, caption, flag);
public static void MessageBox(windowhandle, string message, string caption)
{
MessageBox(windowhandle, message,caption, MB_TOPMOST);
}
</code></pre> | 16,105,626 | 5 | 0 | null | 2013-04-19 12:53:45.183 UTC | 9 | 2017-12-28 07:05:11.04 UTC | 2014-05-18 16:03:15.867 UTC | null | 111,575 | null | 1,324,033 | null | 1 | 54 | c#|messagebox|topmost | 71,656 | <p>To show the MessageBox on top-most of all for the application</p>
<p><strong>Code</strong></p>
<pre><code>//Should be MessageBox.Show() below
MessageBox.Show(this, "My top most message");
</code></pre>
<p><strong>Reason for not being <code>MB_TOPMOST</code> by default</strong></p>
<blockquote>
<p>If MB_TOPMOST will be default then the <code>MessageBox</code> will show up in a 'system modal' mode and it will be exactly on top on that form and side effects are that the 'system modal' mode will cause the <code>MessageBox</code> to <em>Block</em> the windows until the message is dismissed normally it will be 'application modal' mode.</p>
</blockquote>
<p><strong>Reference links</strong></p>
<ol>
<li><a href="http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/7a515f66-8818-4ec5-9213-7ee479f8fb18/" rel="noreferrer">MSDN forum - How to display a MessageBox as topmost window</a></li>
<li><a href="https://stackoverflow.com/a/4834954/468718">SO - C# MessageBox To Front When App is Minimized To Tray</a></li>
</ol> |
11,027,214 | Bitwise ANDING Of Two STD_LOGIC_VECTORS | <p>Hey I was wondering if it was at all possible in VHDL to AND two <code>STD_LOGIC_VECTORS</code> together. For example, I'm writing a VHDL program that will output a character to a VGA monitor. I have a vector <code>PixelRow: IN STD_LOGIC_VECTOR(9 DOWNTO 0)</code> and <code>PixelColumn: IN STD_LOGIC_VECTOR(9 DOWNTO 0)</code>. What I'm trying to do is have a <code>STD_LOGIC</code> Output that takes the two pixel vectors and ANDs them with another vector eg.</p>
<pre><code> Output <= (PixelRow AND NOT "0000000000") OR (PixelColumn AND NOT "0000000000") OR
(PixelRow AND NOT "0111011111") OR (PixelColumn AND NOT "1001111111");
</code></pre>
<p>This code I'm hoping can be used to simplify the following code:</p>
<pre><code> Output <= ((NOT PixelRow(0) AND NOT PixelRow(1) AND NOT PixelRow(2) AND NOT
PixelRow(3) AND NOT PixelRow(4) AND NOT PixelRow(5) AND NOT PixelRow(6)
AND NOT PixelRow(7) AND NOT PixelRow(8) AND NOT PixelRow(9)))
OR ((NOT PixelRow(0) AND PixelRow(1) AND PixelRow(2) AND PixelRow(3) AND
NOT PixelRow(4) AND PixelRow(5) AND PixelRow(6) AND PixelRow(7) AND
PixelRow(8) AND PixelRow(9)))
OR ((NOT PixelColumn(0) AND NOT PixelColumn(1) AND NOT PixelColumn(2) AND
NOT PixelColumn(3) AND NOT PixelColumn(4) AND NOT PixelColumn(5) AND NOT
PixelColumn(6) AND NOT PixelColumn(7) AND NOT PixelColumn(8) AND NOT
PixelColumn(9)))
OR ((PixelColumn(0) AND NOT PixelColumn(1) AND NOT PixelColumn(2) AND
PixelColumn(3) AND PixelColumn(4) AND PixelColumn(5) AND PixelColumn(6)
AND PixelColumn(7) AND PixelColumn(8) AND PixelColumn(9)));
</code></pre>
<p>The bigger block of code draws a box around the screen. I'm hoping there's a MUCH easier way to do this. Does anybody know how to simplify this code?</p>
<p>Thanks</p> | 11,027,445 | 3 | 1 | null | 2012-06-14 05:35:43.393 UTC | 1 | 2012-06-25 14:43:03.15 UTC | null | null | null | null | 1,102,732 | null | 1 | 3 | controller|vhdl|vga | 49,722 | <p>It is not clear to me what you need to and/or, and what you need to reduce to a single bit.</p>
<p>Sure there are the <code>and</code> and <code>or</code> bit-wise vector operators which return a vector of the same size.</p>
<p>If you need to test equality/inequality between <code>PixelRow</code> and <code>"0000000000"</code>, then you can write either: <code>PixelRow /= "0000000000"</code> or <code>PixelRow = "0000000000"</code>.</p>
<p>If you need to and-reduce a vector <code>vect : std_logic_vector(7 downto 0)</code> to a single bit <code>bit : std_logic</code>, the easiest way is probably to use a process:</p>
<pre><code>process (vect) is
variable tmp : std_logic;
begin
tmp := '1';
for I in 7 downto 0 loop
tmp := tmp and vect(I);
end loop;
bit <= tmp;
end process;
</code></pre>
<p>If you need to do this frequently then you can define a <code>function</code> rather than a <code>process</code> to do this.</p> |
29,254,181 | Bundling not working in MVC5 when I turn on release mode | <p>I have the following bundle configured in BundleConfig.cs:</p>
<pre><code>bundles.Add(new StyleBundle("~/bundles/css").Include(
"~/assets/bootstrap/css/bootstrap.css",
"~/assets/css/global/all.css"));
</code></pre>
<p>and I reference it using the following:</p>
<pre><code>@Styles.Render("~/bundles/css")
</code></pre>
<p>When I'm in debug mode (web.config compilation <code>debug="true"</code>) it works as expected in that it renders both css files as normal ie:</p>
<pre><code><link href="/assets/bootstrap/css/bootstrap.css" rel="stylesheet"/>
<link href="/assets/css/global/all.css" rel="stylesheet"/>
</code></pre>
<p>However when I set <code>debug="false"</code> the above behaviour still occurs in that it does recognise the files, however it's just rendering them as normal.</p>
<p>To confirm bundling can definitely work I've enabled optimizations in BundleConfig ie <code>BundleTable.EnableOptimizations = true;</code></p>
<p>Whenever I do the above, it bundles the css and appears as expected ie:</p>
<pre><code><link href="/bundles/css?v=WBKHkZAJly7jUzHrVDT8SwfaQE-CA9dbOUQUlLKadNE1" rel="stylesheet"/>
</code></pre>
<p>EDIT:</p>
<p>A few people have mentioned that adding the following code to my BundleConfig.cs file will achieve what I am after:</p>
<pre><code>#if DEBUG
BundleTable.EnableOptimizations = false;
#else
BundleTable.EnableOptimizations = true;
#endif
</code></pre>
<p>I understand and appreciate this response, however according to the documentation, the default behaviour of MVC bundling is to bundle in release mode but not in debug mode. I don't see why I should need to add extra code to make it do this when it should be doing it already.</p>
<p>EDIT 2</p>
<p>I've a confession to make. It turns out I had the web.config from the Views folder opened and not the main web.config. I changed the setting in the main web.config and this works just fine for me. I blame ReSharper</p> | 29,254,520 | 9 | 7 | null | 2015-03-25 11:18:01.563 UTC | 5 | 2022-05-18 17:19:52.113 UTC | 2015-03-25 13:11:46.14 UTC | null | 162,782 | null | 162,782 | null | 1 | 32 | c#|css|.net|asp.net-mvc|bundling-and-minification | 31,128 | <p>This is the default behavior.</p>
<blockquote>
<p>Bundling and minification is enabled or disabled by setting the value of the debug attribute in the compilation Element in the Web.config file.</p>
</blockquote>
<p><a href="http://www.asp.net/mvc/overview/performance/bundling-and-minification" rel="noreferrer">http://www.asp.net/mvc/overview/performance/bundling-and-minification</a></p>
<blockquote>
<p><img src="https://i.stack.imgur.com/2wMRK.png" alt="enter image description here"></p>
</blockquote> |
17,218,693 | How to pass data from <form:select> Spring MVC | <p>I would like to share my problem with you.</p>
<p>I built on jsp page and use on my page some of <code><form:select></code> it use <code><form:select></code> to extract and render data from DB when I request the page <code>search.jsp</code> and user have to select one:</p>
<pre><code><form action="result" method="get" >
<table>
<tr>
<th>Date fro DB:</th>
<td><form:select path="listOfDates">
<form:option value="NONE"> --SELECT--</form:option>
<form:options items="${listOfDates}"></form:options>
</form:select>
</td>
</tr>
<tr>
<th>Name of company from DB:</th>
<td><form:select path="listOfInstitutionsNames">
<form:option value="NONE"> --SELECT--</form:option>
<form:options items="${listOfInstitutionsNames}"></form:options>
</form:select>
</td>
</tr>
<tr>
<th>Type of company from DB:</th>
<td>
<form:select path="listOfInstitutionsTypes">
<form:option value="NONE"> --SELECT--</form:option>
<form:options items="${listOfInstitutionsTypes}"></form:options>
</form:select>
</td>
</tr>
<tr>
<td><input type="submit" value="Извлечь"/></td>
</tr>
</table>
</form>
</code></pre>
<p>I need to pass what user select as request parameter to my controller, here is the code of controller:</p>
<pre><code>@Controller
public class HomeController{
@Autowired
private ControllerSupportClass controllerSupportClass;
@RequestMapping(value="/search", method=RequestMethod.GET)
public String search(Model model) {
List<Date> listOfDates = controllerSupportClass.findAllDatesForm();
List<String> listOfInstitutionsNames = controllerSupportClass.findAllInstitutionsForm();
List<String> listOfInstitutionsTypes = controllerSupportClass.findAllTypesForm();
model.addAttribute("listOfInstitutionsTypes", listOfInstitutionsTypes);
model.addAttribute("listOfInstitutionsNames", listOfInstitutionsNames);
model.addAttribute("listOfDates", listOfDates);
return "search";
}
@RequestMapping(value ="/result", method=RequestMethod.GET)
public String SecondActionPage(@RequestParam String particularDate,
@RequestParam String nameOfInstitution,
@RequestParam String typeName,
Model model) throws Exception {
if(particularDate !="" && nameOfInstitution.trim() !="" && typeName.trim()=="") {
controllerSupportClass.findWithDateAndName(nameOfInstitution, particularDate, model);
} else if(particularDate.trim() !="" && nameOfInstitution.trim() =="" && typeName.trim() !="") {
controllerSupportClass.findWithAddedDateAndType(typeName, particularDate, model);
} else if(particularDate.trim() !="" && nameOfInstitution.trim() =="" && typeName.trim() ==""){
controllerSupportClass.findWithAddedDate(particularDate, model);
} else if(particularDate.trim() !="" && nameOfInstitution.trim() !="" && typeName.trim() !="") {
throw new Exception("Search by choose all parameters is not exceptable");
} else {
throw new Exception("You didn't put any search parameters");
}
return "search";
}
}
</code></pre>
<p>As you can see my <code>SecondActionPage()</code> method use <code>@RequestParam</code> annotation to get parameters from url and after validate them and pass them to another method to extract data corresponding on request parameters... But problem is that I can't to pass them. It just show me like this <code>http://localhost:8080/controller/result?</code> and after ? nothing passing. How can I pass this all my choosen parameters from <code>serach.jsp</code> thank you.</p> | 17,227,422 | 1 | 0 | null | 2013-06-20 16:16:50.927 UTC | 2 | 2016-04-14 23:07:34.487 UTC | null | null | null | null | 2,408,375 | null | 1 | 12 | spring|jsp|model-view-controller|spring-mvc|controller | 85,861 | <p>I believe you should use <code><form:select></code> inside the <code><form:form></code>.</p>
<p>It should look like this:</p>
<p>search.jsp:</p>
<pre><code><form:form modelAttribute="myform" action="result" method="get" >
<form:select path="nameOfInstitution">
<form:option value="NONE"> --SELECT--</form:option>
<form:options items="${listOfInstitutionsNames}"></form:options>
</form:select>
...
</form:form>
</code></pre>
<p>HomeController.java:</p>
<pre><code>@RequestMapping(value = "/search", method = RequestMethod.GET)
public String search(Model model) {
...
model.addAttribute("myform", new MyForm());
return "search";
}
@RequestMapping(value = "/result", method = RequestMethod.GET)
public String SecondActionPage(@RequestParam String nameOfInstitution,
Model model,
@ModelAttribute("myform") MyForm myform)
throws Exception {
...
}
</code></pre>
<p>MyForm.java:</p>
<pre><code>public class MyForm {
private String nameOfInstitution;
public String getNameOfInstitution() {
return nameOfInstitution;
}
public void setNameOfInstitution(String nameOfInstitution) {
this.nameOfInstitution = nameOfInstitution;
}
}
</code></pre>
<p>Hope this helps.</p> |
17,409,411 | Scala macros, where are they used? | <p>I just noticed that Scala has macros, but I have never seen any code that uses them. They also seem quite different from C preprocessor macros and the like. Reading through the <a href="http://docs.scala-lang.org/overviews/macros/overview.html" rel="noreferrer">overview</a> of macros, it didn't look like they offer anything that wasn't previously possible in Scala. Under the motivation heading, there is a list of things that macros enable:</p>
<blockquote>
<ul>
<li>Language virtualization (overloading/overriding semantics of the
original programming language to enable deep embedding of DSLs),</li>
<li>Program reification (providing programs with means to inspect their
own code), </li>
<li>Self-optimization (self-application of domain-specific
optimizations based on program reification), </li>
<li>Algorithmic program
construction (generation of code that is tedious to write with the
abstractions supported by a programming language).</li>
</ul>
</blockquote>
<p>Later on in the menu, there are experimental macro features, such as type macros, quasiquotes, untyped macros and even more. Clearly there is a demand for this!</p>
<p>All these seem like nice features for people who build very sophisticated libraries with strong understanding of Scala. But do macros offer something for the average Scala developer too? Will using macros make my Scala code better?</p> | 17,410,059 | 1 | 2 | null | 2013-07-01 16:34:03.99 UTC | 10 | 2016-03-16 21:15:52.387 UTC | 2016-03-16 21:15:52.387 UTC | null | 573,032 | null | 879,114 | null | 1 | 16 | scala|macros|metaprogramming|template-meta-programming | 6,350 | <p>As an "average" Scala developer, you will most likely not write macros yourself, unless you have very good reason.</p>
<p>Macros are a method of compile time meta programming, that is to say you program programs. For example, a def-macro—which is part of Scala 2.10 albeit still "experimental"—looks like a regular method, but whenever you call that method in your code, the compiler will replace that call with whatever that macro hidden behind that method will produce (a new code fragment).</p>
<hr>
<p>A very simple example. Incorporate the date when your project was compiled into the code:</p>
<pre><code>import java.util.Date
import reflect.macros.Context
import language.experimental.macros
object CompileTime {
def apply(): Date = macro applyImpl
def applyImpl(c: Context)(): c.Expr[Date] = {
import c.universe._
val now = System.currentTimeMillis() // this is executed during compilation!
val nowExpr = c.Expr[Long](Literal(Constant(now)))
val code = reify(new Date(nowExpr.splice))
c.Expr(code.tree)
}
}
</code></pre>
<p>Using that macro (the following code must be compiled <em>separately</em> from the macro code above):</p>
<pre><code>object MacroTest extends App {
println(s"This project was compiled on ${CompileTime()}")
}
</code></pre>
<p>(If you run that multiple times, you see that the compile time is indeed constant)</p>
<hr>
<p>So in short, macros offer a functionality which was <em>not</em> available in any previous Scala version. You can do things with macros you cannot do otherwise (often you can write similar things using runtime reflection, but macros are checked at compile time).</p>
<p>As a user you will however be exposed more and more to libraries which incorporate macros, because they can provide powerful constructs which are fully type safe. For example, automatic serialisers for JSON from a case class can be realised with macros, because the macro can inspect the type of your case class and build the correct program structure (AST) to read and write that case class, with no danger of runtime failure.</p>
<p>Some random links</p>
<ul>
<li><a href="https://github.com/retronym/macrocosm">https://github.com/retronym/macrocosm</a></li>
<li><a href="http://www.warski.org/blog/2012/12/starting-with-scala-macros-a-short-tutorial/">http://www.warski.org/blog/2012/12/starting-with-scala-macros-a-short-tutorial/</a></li>
</ul> |
17,254,425 | Getting the size in bytes of a vector | <p>Sorry for this maybe simple and stupid question but I couldn't find it anywhere.</p>
<p>I just don't know how to get the size in bytes of a std::vector.</p>
<pre><code>std::vector<int>MyVector;
/* This will print 24 on my system*/
std::cout << "Size of my vector:\t" << sizeof(MyVector) << std::endl;
for(int i = 0; i < 1000; i++)
MyVector.push_back(i);
/* This will still print 24...*/
std::cout << "Size of my vector:\t" << sizeof(MyVector) << std::endl;
</code></pre>
<p>So how do I get the size of a vector?! Maybe by multiplying 24 (vector size) by the number of items?</p> | 17,254,457 | 3 | 2 | null | 2013-06-22 19:18:09.497 UTC | 4 | 2016-07-21 23:17:36.977 UTC | null | null | null | null | 2,420,513 | null | 1 | 16 | c++|byte|sizeof|stdvector | 49,915 | <p>Vector stores its elements in an internally-allocated memory array. You can do this:</p>
<pre><code>sizeof(std::vector<int>) + (sizeof(int) * MyVector.size())
</code></pre>
<p>This will give you the size of the vector structure itself plus the size of all the ints in it, but it may not include whatever small overhead your memory allocator may impose. I'm not sure there's a platform-independent way to include that.</p> |
24,755,468 | Difference between language sql and language plpgsql in PostgreSQL functions | <p>Am very new in <em>Database development</em> so I have some doubts regarding my following example:</p>
<p>Function f1() - <em><strong>language sql</strong></em></p>
<pre><code> create or replace function f1(istr varchar)
returns text as $$
select 'hello! '::varchar || istr;
$$ language sql;
</code></pre>
<p>Function f2() - <em><strong>language plpgsql</strong></em></p>
<pre><code> create or replace function f2(istr varchar)
returns text as $$
begin select 'hello! '::varchar || istr; end;
$$ language plpgsql;
</code></pre>
<ul>
<li><p>Both <em>functions</em> can be called like <code>select f1('world')</code> or <code>select f2('world')</code>.</p>
</li>
<li><p>If I call <code>select f1('world')</code> the <em>output</em> will be:</p>
<pre><code> `hello! world`
</code></pre>
</li>
<li><p>And <em>output</em> for <code>select f2('world')</code>:</p>
<blockquote>
<p>ERROR: query has no destination for result data
HINT: If you want to discard the results of a SELECT, use PERFORM instead.
CONTEXT: PL/pgSQL function f11(character varying) line 2 at SQL statement
********** Error **********</p>
</blockquote>
</li>
<li><p>I wish to know the difference and in which situations I should use <code>language sql</code> or <code>language plpgsql</code>.</p>
</li>
</ul>
<p>Any useful link or answers regarding functions will much appreciated.</p> | 24,771,561 | 3 | 4 | null | 2014-07-15 10:10:41.553 UTC | 40 | 2021-04-29 10:02:30.84 UTC | 2021-03-29 09:39:23.653 UTC | null | 1,419,272 | user3814846 | null | null | 1 | 83 | sql|function|postgresql|stored-procedures|plpgsql | 50,339 | <h2><a href="https://www.postgresql.org/docs/current/xfunc-sql.html" rel="noreferrer"><strong>SQL functions</strong></a></h2>
<p>... are the better choice:</p>
<ul>
<li><p>For <strong>simple scalar queries</strong>. Not much to plan, better save any overhead.</p>
</li>
<li><p>For <strong>single (or very few) calls per session</strong>. Nothing to gain from plan caching via prepared statements that PL/pgSQL has to offer. See below.</p>
</li>
<li><p>If they are typically called in the context of bigger queries and are simple enough to be <a href="https://wiki.postgresql.org/wiki/Inlining_of_SQL_functions" rel="noreferrer"><strong>inlined</strong></a>.</p>
</li>
<li><p>For lack of <strong>experience</strong> with any procedural language like PL/pgSQL. Many know SQL well and that's about all you need for SQL functions. Few can say the same about PL/pgSQL. (Though it's rather simple.)</p>
</li>
<li><p>A bit shorter code. No block overhead.</p>
</li>
</ul>
<h2><a href="https://www.postgresql.org/docs/current/plpgsql.html" rel="noreferrer"><strong>PL/pgSQL functions</strong></a></h2>
<p>... are the better choice:</p>
<ul>
<li><p>When you need any <strong>procedural elements</strong> or <strong>variables</strong> that are not available in SQL functions, obviously.</p>
</li>
<li><p>For any kind of <strong>dynamic SQL</strong>, where you build and <a href="https://www.postgresql.org/docs/current/plpgsql-statements.html#PLPGSQL-STATEMENTS-EXECUTING-DYN" rel="noreferrer"><code>EXECUTE</code></a> statements dynamically. Special care is needed to avoid SQL injection. More details:</p>
<ul>
<li><a href="https://dba.stackexchange.com/a/49718/3684">Postgres functions vs prepared queries</a></li>
</ul>
</li>
<li><p>When you have <strong>computations</strong> that can be <strong>reused</strong> in several places and a CTE can't be stretched for the purpose. In an SQL function you don't have variables and would be forced to compute repeatedly or write to a table. This related answer on dba.SE has side-by-side <strong>code examples</strong> for solving the same problem using an SQL function / a plpgsql function / a query with CTEs:</p>
<ul>
<li><a href="https://dba.stackexchange.com/a/71442/3684">How to pass a parameter into a function</a></li>
</ul>
</li>
</ul>
<p>Assignments are somewhat more expensive than in other procedural languages. Adapt a programming style that doesn't use more assignments than necessary.</p>
<ul>
<li><p>When a function cannot be inlined and is called repeatedly. Unlike with SQL functions, <a href="https://www.postgresql.org/docs/current/plpgsql-implementation.html#PLPGSQL-PLAN-CACHING" rel="noreferrer"><strong>query plans can be cached</strong> for all SQL statements inside a PL/pgSQL functions</a>; they are treated like <strong>prepared statements</strong>, the plan is cached for repeated calls within the same session (if Postgres expects the cached (generic) plan to perform better than re-planning every time. That's the reason why PL/pgSQL functions are <em><strong>typically faster</strong></em> after the first couple of calls in such cases.</p>
<p>Here is a thread on pgsql-performance discussing some of these items:</p>
<ul>
<li><a href="https://www.postgresql.org/message-id/flat/0238E40E527049828C48675488422F6D@CAPRICA#0238E40E527049828C48675488422F6D@CAPRICA" rel="noreferrer">Re: pl/pgsql functions outperforming sql ones?</a></li>
</ul>
</li>
<li><p>When you need to <a href="https://www.postgresql.org/docs/current/plpgsql-control-structures.html#PLPGSQL-ERROR-TRAPPING" rel="noreferrer"><strong>trap errors</strong></a>.</p>
</li>
<li><p>For <a href="https://www.postgresql.org/docs/current/plpgsql-trigger.html" rel="noreferrer"><strong>trigger functions</strong></a>.</p>
</li>
<li><p>When including DDL statements changing objects or altering system catalogs in any way relevant to subsequent commands - because all statements in SQL functions are parsed at once while PL/pgSQL functions plan and execute each statement sequentially (like a prepared statement). See:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/51004980/why-can-pl-pgsql-functions-have-side-effect-while-sql-functions-cant/51033884#51033884">Why can PL/pgSQL functions have side effect, while SQL functions can't?</a></li>
</ul>
</li>
</ul>
<p>Also consider:</p>
<ul>
<li><a href="https://dba.stackexchange.com/a/8189/3684">PostgreSQL Stored Procedure Performance</a></li>
</ul>
<hr />
<p>To actually <em>return</em> from a PL/pgSQL function, you could write:</p>
<pre><code>CREATE FUNCTION f2(istr varchar)
RETURNS text AS
$func$
BEGIN
RETURN 'hello! '; -- defaults to type text anyway
END
$func$ LANGUAGE plpgsql;
</code></pre>
<p>There are other ways:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/8169676/can-i-make-a-plpgsql-function-return-an-integer-without-using-a-variable/8169928#8169928">Can I make a plpgsql function return an integer without using a variable?</a></li>
<li><a href="https://www.postgresql.org/docs/current/plpgsql-control-structures.html#PLPGSQL-STATEMENTS-RETURNING" rel="noreferrer">The manual on "Returning From a Function"</a></li>
</ul> |
22,329,005 | Mac Terminal - 'pointer being freed was not allocated' error when opening terminal | <p>I get the following message when opening the terminal on mac</p>
<blockquote>
<p>Last login: Tue Mar 11 14:33:24 on console
login(291,0x7fff78af9310) malloc: <strong>* error for object 0x7f974be006f0: pointer being freed was not allocated
*</strong> set a breakpoint in malloc_error_break to debug</p>
<p>[Process completed]</p>
</blockquote>
<p>... and I don't seem to be able to escape it. I've been having some weird permissions problems with Adobe CC - could the two be symptoms of a single problem?</p> | 23,293,963 | 5 | 3 | null | 2014-03-11 14:40:24.087 UTC | 10 | 2016-11-10 23:07:42.987 UTC | 2014-10-19 12:29:36.54 UTC | null | 498,677 | null | 498,677 | null | 1 | 39 | macos|terminal | 52,375 | <p>It looks like you don't have the right permissions on the <code>/usr/bin</code> directory.</p>
<p><strong>Solution for OS X 10.11 (El Capitan) and later:</strong> </p>
<ol>
<li>Install <a href="http://www.titanium.free.fr/onyx.html" rel="noreferrer">Onyx 3.1.3</a> app (Free analog of Disk Utility) </li>
<li>Choose 'Maintenance' -> 'Permissions' -> 'Execute'.
<a href="https://i.stack.imgur.com/GsdUN.png" rel="noreferrer"><img src="https://i.stack.imgur.com/GsdUN.png" alt="enter image description here"></a></li>
</ol>
<p><strong>Solution for older versions of OS X:</strong> </p>
<ul>
<li>Open 'Disk Utility' app -> Press 'Repair Disk Permissions'.</li>
</ul>
<p>It will set default permissions for the <code>/usr/bin</code> directory.<br>
If this step doesn't help try this:</p>
<ul>
<li>Delete <code>com.apple.terminal.plist</code> from the <code>~/Library/Preferences</code> folder;</li>
</ul> |
55,230,263 | Angular 7 : Injected service is undefined | <p>I tried to inject AccountService in the LoginService but it won't ,the accountService is undefined but in the other hand the authServiceProvider is defined . </p>
<p>Contrarily it injected perfectly in footerComponent.</p>
<p>So why the AccountService is injected perfectly in FooterComponent and it bugs in the LoginService.</p>
<p>I do not know where the problem came from . </p>
<pre><code>import { Injectable } from '@angular/core';
import { AccountService } from 'app/core/auth/account.service';
import { AuthServerProvider } from 'app/core/auth/auth-jwt.service';
@Injectable({ providedIn: 'root' })
export class LoginService {
constructor(public accountService: AccountService, private authServerProvider: AuthServerProvider) {
console.log(this.accountService); // is undefined
console.log(this.authServerProvider); // is defined
}
</code></pre>
<p>This is the AuthentificationService</p>
<pre><code>@Injectable({ providedIn: 'root' })
export class AuthServerProvider {
constructor(private http: HttpClient, private $localStorage: LocalStorageService, private $sessionStorage: SessionStorageService) {}
</code></pre>
<p>This is the AccountService</p>
<pre><code>@Injectable({ providedIn: 'root' })
export class AccountService {
private userIdentity: any;
private authenticated = false;
private authenticationState = new Subject<any>();
constructor(private languageService: JhiLanguageService, private sessionStorage: SessionStorageService, private http: HttpClient) {}
</code></pre>
<p>I tried to use AccountService in other component and it injected perfectly </p>
<pre><code>import { Component } from '@angular/core';
import { AccountService } from 'app/core';
@Component({
selector: 'jhi-footer',
templateUrl: './footer.component.html',
styleUrls: ['./footer.component.scss']
})
export class FooterComponent {
constructor( private accountService: AccountService) {
console.log(this.accountService); // It is defined
}
}
</code></pre>
<p>this is the app.module.ts</p>
<pre><code>import './vendor.ts';
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { NgbDatepickerConfig } from '@ng-bootstrap/ng-bootstrap';
import { Ng2Webstorage } from 'ngx-webstorage';
import { NgJhipsterModule } from 'ng-jhipster';
import { AuthInterceptor } from './blocks/interceptor/auth.interceptor';
import { AuthExpiredInterceptor } from './blocks/interceptor/auth-expired.interceptor';
import { ErrorHandlerInterceptor } from './blocks/interceptor/errorhandler.interceptor';
import { NotificationInterceptor } from './blocks/interceptor/notification.interceptor';
import { SharedModule } from 'app/shared';
import { CoreModule } from 'app/core';
import { AppRoutingModule } from './app-routing.module';
import { HomeModule } from './home/home.module';
import { AccountModule } from './account/account.module';
import { EntityModule } from './entities/entity.module';
import * as moment from 'moment';
// jhipster-needle-angular-add-module-import JHipster will add new module here
import { JhiMainComponent, NavbarComponent, FooterComponent, PageRibbonComponent, ActiveMenuDirective, ErrorComponent } from './layouts';
@NgModule({
imports: [
BrowserModule,
Ng2Webstorage.forRoot({ prefix: 'jhi', separator: '-' }),
NgJhipsterModule.forRoot({
// set below to true to make alerts look like toast
alertAsToast: false,
alertTimeout: 5000,
i18nEnabled: true,
defaultI18nLang: 'en'
}),
SharedModule.forRoot(),
CoreModule,
HomeModule,
AccountModule,
// jhipster-needle-angular-add-module JHipster will add new module here
EntityModule,
AppRoutingModule
],
declarations: [JhiMainComponent, NavbarComponent, ErrorComponent, PageRibbonComponent, ActiveMenuDirective, FooterComponent],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: AuthInterceptor,
multi: true
},
{
provide: HTTP_INTERCEPTORS,
useClass: AuthExpiredInterceptor,
multi: true
},
{
provide: HTTP_INTERCEPTORS,
useClass: ErrorHandlerInterceptor,
multi: true
},
{
provide: HTTP_INTERCEPTORS,
useClass: NotificationInterceptor,
multi: true
}
],
bootstrap: [JhiMainComponent]
})
export class AppModule {
constructor(private dpConfig: NgbDatepickerConfig) {
this.dpConfig.minDate = { year: moment().year() - 100, month: 1, day: 1 };
}
}
</code></pre>
<p>and this is the core.module .</p>
<pre><code>import { NgModule, LOCALE_ID } from '@angular/core';
import { DatePipe, registerLocaleData } from '@angular/common';
import { HttpClientModule } from '@angular/common/http';
import { Title } from '@angular/platform-browser';
import locale from '@angular/common/locales/en';
@NgModule({
imports: [HttpClientModule],
exports: [],
declarations: [],
providers: [
Title,
{
provide: LOCALE_ID,
useValue: 'en'
},
DatePipe
]
})
export class CoreModule {
constructor() {
registerLocaleData(locale);
}
}
</code></pre>
<p>Thanks in advance for your help.</p> | 55,231,138 | 4 | 8 | null | 2019-03-18 21:25:25.217 UTC | 3 | 2021-11-17 13:16:15.313 UTC | 2019-03-18 21:44:45.74 UTC | null | 6,375,501 | null | 6,375,501 | null | 1 | 34 | angular|typescript|ecmascript-6|dependency-injection|jhipster | 35,841 | <blockquote>
<p>You should always provide your service in the root injector unless
there is a case where you want the service to be available only if the
consumer imports a particular @NgModule.</p>
</blockquote>
<p>try to add your service you want to inject in <code>providers : [ ]</code> in your <code>core.module</code></p>
<pre><code>import { NgModule, LOCALE_ID } from '@angular/core';
import { DatePipe, registerLocaleData } from '@angular/common';
import { HttpClientModule } from '@angular/common/http';
import { Title } from '@angular/platform-browser';
import locale from '@angular/common/locales/en';
@NgModule({
imports: [HttpClientModule],
exports: [],
declarations: [],
providers: [
AccountService,
Title,
{
provide: LOCALE_ID,
useValue: 'en'
},
DatePipe
]
})
export class CoreModule {
constructor() {
registerLocaleData(locale);
}
}
</code></pre>
<p>and in your AccountService replace <code>@Injectable({ providedIn: 'root' })</code> with <code>@Injectable()</code></p>
<pre><code>@Injectable()
export class AccountService {
private userIdentity: any;
private authenticated = false;
private authenticationState = new Subject<any>();
constructor(private languageService: JhiLanguageService, private sessionStorage: SessionStorageService, private http: HttpClient) {}
</code></pre> |
27,361,565 | Why is JSON invalid if an integer begins with a leading zero? | <p>I'm importing some JSON files into my Parse.com project, and I keep getting the error "invalid key:value pair".</p>
<p>It states that there is an unexpected "8".</p>
<p>Here's an example of my JSON:</p>
<pre><code>}
"Manufacturer":"Manufacturer",
"Model":"THIS IS A STRING",
"Description":"",
"ItemNumber":"Number12345",
"UPC":083456789012,
"Cost":"$0.00",
"DealerPrice":" $0.00 ",
"MSRP":" $0.00 ",
}
</code></pre>
<p>If I update the JSON by either removing the <code>0</code> from <code>"UPC":083456789012,</code> or converting it to <code>"UPC":"083456789012",</code> it becomes valid.</p>
<p>Can JSON really not accept an integer that begins with <code>0</code>, or is there a way around the problem?</p> | 27,361,596 | 6 | 6 | null | 2014-12-08 15:45:39.473 UTC | 14 | 2019-07-06 11:17:25.477 UTC | 2018-12-19 15:43:56.737 UTC | null | 1,497,596 | null | 3,246,645 | null | 1 | 64 | json|parsing|object|zero|parseint | 69,108 | <p>A leading 0 indicates an octal number in JavaScript. An octal number cannot contain an 8; therefore, that number is invalid.
Moreover, JSON doesn't (officially) support octal numbers, so formally the JSON is invalid, even if the number would not contain an 8. Some parsers do support it though, which may lead to some confusion. Other parsers will recognize it as an invalid sequence and will throw an error, although the exact explanation they give may differ.</p>
<p><strong>Solution:</strong> If you have a number, don't ever store it with leading zeroes. If you have a value that needs to have a leading zero, don't treat it as a number, but as a string. Store it with quotes around it.</p>
<p>In this case, you've got a UPC which <a href="http://en.wikipedia.org/wiki/Universal_Product_Code" rel="noreferrer">needs to be 12 digits long</a> and may contain leading zeroes. I think the best way to store it is as a string.</p>
<p>It is debatable, though. If you treat it as a barcode, seeing the leading 0 as an integral part of it, then string makes sense. Other types of barcodes can even contain alphabetic characters. </p>
<p>On the other hand. A UPC is a number, and the fact that it's left-padded with zeroes to 12 digits could be seen as a display property. Actually, if you left-pad it to 13 digits by adding an extra 0, you've got an EAN code, because EAN is a superset of UPC. <br></p>
<p>If you have a monetary amount, you might display it as <code>€ 7.30</code>, while you store it as <code>7.3</code>, so it could also make sense to store a product code as a number.</p>
<p>But that decision is up to you. I can only advice you to use a string, which is my personal preference for these codes, and if you choose a number, then you'll have to remove the <code>0</code> to make it work.</p> |
21,809,904 | StyleBundle Index was outside the bounds of the array | <p>I want to include all files in directory like this:</p>
<pre><code>bundles.Add(new StyleBundle("~/Content/simpliq_css").Include(
"~/Content/simpliq/*.css"
));
</code></pre>
<p>But i got this error <code>Index was outside the bounds of the array</code></p>
<p>and red line is:</p>
<p><code>@Styles.Render("~/Content/simpliq_css")</code></p>
<pre><code>[IndexOutOfRangeException: Index was outside the bounds of the array.]
System.String.get_Chars(Int32 index) +0
Microsoft.Ajax.Utilities.CssParser.Append(Object obj, TokenType tokenType) +402
Microsoft.Ajax.Utilities.CssParser.AppendCurrent() +74
Microsoft.Ajax.Utilities.CssParser.ParseElementName() +321
Microsoft.Ajax.Utilities.CssParser.ParseSimpleSelector() +54
Microsoft.Ajax.Utilities.CssParser.ParseSelector() +555
Microsoft.Ajax.Utilities.CssParser.ParseRule() +165
Microsoft.Ajax.Utilities.CssParser.ParseStylesheet() +186
Microsoft.Ajax.Utilities.CssParser.Parse(String source) +946
Microsoft.Ajax.Utilities.Minifier.MinifyStyleSheet(String source, CssSettings settings, CodeSettings scriptSettings) +439
Microsoft.Ajax.Utilities.Minifier.MinifyStyleSheet(String source, CssSettings settings) +73
System.Web.Optimization.CssMinify.Process(BundleContext context, BundleResponse response) +302
System.Web.Optimization.Bundle.ApplyTransforms(BundleContext context, String bundleContent, IEnumerable`1 bundleFiles) +207
System.Web.Optimization.Bundle.GenerateBundleResponse(BundleContext context) +355
System.Web.Optimization.Bundle.GetBundleResponse(BundleContext context) +104
System.Web.Optimization.BundleResolver.GetBundleContents(String virtualPath) +254
System.Web.Optimization.AssetManager.EliminateDuplicatesAndResolveUrls(IEnumerable`1 refs) +435
System.Web.Optimization.AssetManager.DeterminePathsToRender(IEnumerable`1 assets) +1030
System.Web.Optimization.AssetManager.RenderExplicit(String tagFormat, String[] paths) +75
System.Web.Optimization.Styles.RenderFormat(String tagFormat, String[] paths) +293
System.Web.Optimization.Styles.Render(String[] paths) +51
ASP._Page_Areas_Admin_Views_Shared__Layout_cshtml.Execute() in f:\MyProjects\Fables\Fables\Fables.Web\Areas\Admin\Views\Shared\_Layout.cshtml:8
System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +271
System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +120
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +145
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer) +41
System.Web.WebPages.<>c__DisplayClass7.<RenderPageCore>b__6(TextWriter writer) +335
System.Web.WebPages.HelperResult.WriteTo(TextWriter writer) +42
System.Web.WebPages.WebPageExecutingBase.WriteTo(TextWriter writer, HelperResult content) +45
System.Web.WebPages.WebPageBase.Write(HelperResult result) +53
System.Web.WebPages.WebPageBase.RenderSurrounding(String partialViewName, Action`1 body) +178
System.Web.WebPages.WebPageBase.PopContext() +347
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +154
System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +695
System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +382
System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +431
System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +39
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +116
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +529
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +106
System.Web.Mvc.Async.<>c__DisplayClass28.<BeginInvokeAction>b__19() +321
System.Web.Mvc.Async.<>c__DisplayClass1e.<BeginInvokeAction>b__1b(IAsyncResult asyncResult) +185
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +42
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +133
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +40
System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +34
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +44
System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +39
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +62
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +39
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +39
System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__4(IAsyncResult asyncResult, ProcessRequestState innerState) +39
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +40
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9514928
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
</code></pre> | 21,815,357 | 6 | 4 | null | 2014-02-16 10:22:20.72 UTC | 5 | 2019-05-30 12:10:48.033 UTC | 2014-02-16 13:59:17.103 UTC | null | 2,524,304 | null | 2,524,304 | null | 1 | 42 | asp.net|asp.net-mvc | 24,929 | <p>Problem was in version of next packages:</p>
<p><img src="https://i.stack.imgur.com/uG6sg.jpg" alt="enter image description here"></p>
<p>You have to update it and problem will be solved.</p> |
21,641,435 | Error: No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient' | <p>I recently upgraded/updated Entity Framework in an old project from version 4 or 5 to version 6. Now I get this exception:</p>
<blockquote>
<p>An exception of type 'System.InvalidOperationException' occurred in
EntityFramework.dll but was not handled in user code</p>
<p>Additional information: No Entity Framework provider found for the
ADO.NET provider with invariant name 'System.Data.SqlClient'. Make
sure the provider is registered in the 'entityFramework' section of
the application config file. See
<a href="http://go.microsoft.com/fwlink/?LinkId=260882">http://go.microsoft.com/fwlink/?LinkId=260882</a> for more information.</p>
</blockquote>
<p>I googled the error and came across a couple of SO threads, but none of them contained a solution that works for me. This is what my App.config looks like:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
</code></pre>
<p>I already uninstalled Entity Framework from my project and re-installed it, deleted all the references to old EF files and re-installed, but nothing works for me. I keep getting this error.</p> | 21,654,364 | 13 | 5 | null | 2014-02-08 03:14:31.17 UTC | 12 | 2021-08-07 08:55:47.107 UTC | 2014-02-08 16:10:34.297 UTC | null | 854,791 | null | 854,791 | null | 1 | 48 | c#|.net|entity-framework|ado.net|entity-framework-6 | 116,081 | <p>Ok, this is pretty weird. I have a couple of projects: one is a UI project (an ASP.NET MVC project) and the others are projects for stuff like repositories. The repositories project had a reference to EF, but the UI project didn't (because it didn't need one, it just needed to reference the other projects). After I installed EF for the UI project as well, everything started working. This is why, it added this piece of code to my Web.config:</p>
<pre><code><entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</code></pre> |
17,470,691 | Remove old remote branches from Git | <p>When I use bash autocompletion in Git, it keeps showing me branches of old remotes that I don't have anymore. When I do a <code>git branch -la</code> it shows those old remotes and branches while a <code>git branch -l</code> won't. A <code>ls .git/refs/remotes/</code> also shows them. However, they are not present in my <em>.git/config</em> and neither are they shown when I run <code>git remote show</code>.</p>
<p>So how do I get rid of them because my autocomplete list is too long right now. </p>
<p>I have already tried:</p>
<pre><code>git reflog expire --expire=now --all
git gc --prune=now
rm .git/refs/remotes/theoldremote
git remote prune theoldremote
</code></pre>
<p>I'm also aware of the fact that I can just re-clone the repo but that's just cheating ;-)</p> | 17,471,862 | 6 | 3 | null | 2013-07-04 12:46:00.13 UTC | 28 | 2020-02-20 02:40:18.913 UTC | 2013-07-04 14:04:22.827 UTC | null | 679,913 | null | 679,913 | null | 1 | 88 | git | 39,086 | <p>Git does not delete the (local) remote-tracking branches automatically if the branch was deleted in the remote repository. Additionally, before V2.0.1 remote-tracking branches were in some cases not deleted when you removed the remote from your git config (see VonC's answer).</p>
<p>To delete stale remote-tracking branches (branches that were deleted in the remote repository) for one of your remote repositories, run</p>
<pre><code>git remote prune <remote>
</code></pre>
<p>To cite the man page or <code>git remote</code>:</p>
<blockquote>
<p>prune</p>
<p>Deletes all stale tracking branches under <name>. These stale branches have
already been removed from the remote repository referenced by <name>,
but are still locally available in "remotes/<name>".</p>
<p>With --dry-run option, report what branches will be pruned, but do
not actually prune them.</p>
</blockquote>
<p>However, from your question it seems you manually removed <code>.git/refs/remotes/theoldremote</code>, so Git no longer knows about the remote repository that the remote-tracking branches belonged to. That's not how you're supposed to do it.</p>
<p>The normal way to remove a remote repository is to run</p>
<pre><code>git remote rm <remote>
</code></pre>
<p>This will remove the remote from your <code>.git/config</code>, and will delete the remote-tracking branches.</p>
<p>If you just delete the directory under <code>.git/refs/remotes/</code>, the branches will remain behind. Then you will need to remove them manually: </p>
<pre><code>git branch -rd <remote>/<branchname>
</code></pre>
<p>You need option <code>-r</code> to delete a remote branch.</p> |
17,404,316 | The following untracked working tree files would be overwritten by merge, but I don't care | <p>On my branch I had some files in .gitignore</p>
<p>On a different branch those files are not.</p>
<p>I want to merge the different branch into mine, and I don't care if those files are no longer ignored or not.</p>
<p>Unfortunately I get this: </p>
<blockquote>
<p>The following untracked working tree files would be overwritten by merge</p>
</blockquote>
<p>How would I modify my pull command to overwrite those files, without me having to find, move or delete those files myself?</p> | 26,639,255 | 19 | 4 | null | 2013-07-01 12:16:32.603 UTC | 161 | 2022-09-08 12:26:58 UTC | 2016-12-06 12:40:48.333 UTC | null | 3,885,376 | null | 727,429 | null | 1 | 653 | git|merge|git-merge|git-fetch | 989,407 | <p>The problem is that you are not tracking the files locally but identical files are tracked remotely so in order to "pull" your system would be forced to overwrite the local files which are not version controlled. </p>
<p>Try running</p>
<pre><code>git add *
git stash
git pull
</code></pre>
<p>This will track all files, remove all of your local changes to those files, and then get the files from the server.</p> |
30,308,852 | Not enough data error : while doing Disqus SSO | <p>I am trying to integrate Disqus SSO in my site.</p>
<pre><code>var DISQUS_SECRET = "xyz";
var DISQUS_PUBLIC = "abc";
var disqus_developer = 1;
function disqusSignon() {
var disqusData = {
id: "{{ user.id }}",
username: "{{ user.username }}",
email: "{{ user.email }}"
};
var disqusStr = JSON.stringify(disqusData);
var timestamp = Math.round(+new Date() / 1000);
var message = window.btoa(disqusStr);
var result = CryptoJS.HmacSHA1(message + " " + timestamp, DISQUS_SECRET);
var hexsig = CryptoJS.enc.Hex.stringify(result);
return {
pubKey: DISQUS_PUBLIC,
auth: message + " " + hexsig + " " + timestamp
};
}
var data = disqusSignon();
function disqus_config(){
this.callbacks.afterRender = [function() {
this.page.remote_auth_s3 = data.auth;
this.page.api_key = data.pubKey;
}];
}
var disqus_config = function() {
this.page.remote_auth_s3 = data.auth;
this.page.api_key = data.pubKey;
}
var disqus_shortname = 'askpopulo';
/* * * DON'T EDIT BELOW THIS LINE * * */
(function() {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
</code></pre>
<p>Every thing is fine, the payload that is getting generated is also validated correctly on Disqus SSO debug tool. Still the user is not getting signed in using SSO.</p>
<p>And also this message is getting printed on the javascript console:</p>
<blockquote>
<p>It looks like there was a problem: Error: Not enough data {stack: (...), message: "Not enough data"}message: "Not enough data"stack: (...)get stack: function () { [native code] }arguments: nullcaller: nulllength: 0name: ""prototype: StackTraceGetter__proto__: function Empty() {}set stack: function () { [native code] }arguments: nullcaller: nulllength: 1name: ""prototype: StackTraceSetter__proto__: function Empty() {}<strong>proto</strong>: dr.DiscoveryApp.a.Model.extend.onComplete @ discovery.bundle.fce1a5edaced8a1898cef54c2d9fb2bf.js:2(anonymous function) @ common.bundle.91cd39decece4de79b12c1d2e99a09c8.js:9(anonymous function) @ common.bundle.91cd39decece4de79b12c1d2e99a09c8.js:9p @ common.bundle.91cd39decece4de79b12c1d2e99a09c8.js:9o @ common.bundle.91cd39decece4de79b12c1d2e99a09c8.js:9e @ common.bundle.91cd39decece4de79b12c1d2e99a09c8.js:9(anonymous function) @ common.bundle.91cd39decece4de79b12c1d2e99a09c8.js:9(anonymous function) @ common.bundle.91cd39decece4de79b12c1d2e99a09c8.js:9p @ common.bundle.91cd39decece4de79b12c1d2e99a09c8.js:9o @ common.bundle.91cd39decece4de79b12c1d2e99a09c8.js:9c @ common.bundle.91cd39decece4de79b12c1d2e99a09c8.js:9(anonymous function) @ common.bundle.91cd39decece4de79b12c1d2e99a09c8.js:9(anonymous function) @ common.bundle.91cd39decece4de79b12c1d2e99a09c8.js:9p @ common.bundle.91cd39decece4de79b12c1d2e99a09c8.js:9o @ common.bundle.91cd39decece4de79b12c1d2e99a09c8.js:9c @ common.bundle.91cd39decece4de79b12c1d2e99a09c8.js:9(anonymous function) @ common.bundle.91cd39decece4de79b12c1d2e99a09c8.js:9(anonymous function) @ common.bundle.91cd39decece4de79b12c1d2e99a09c8.js:9p @ common.bundle.91cd39decece4de79b12c1d2e99a09c8.j</p>
</blockquote> | 31,109,144 | 1 | 3 | null | 2015-05-18 16:53:00.967 UTC | 5 | 2015-06-29 06:31:47.703 UTC | 2015-06-03 15:24:05.653 UTC | null | 2,140,903 | null | 3,485,908 | null | 1 | 37 | javascript|jquery|disqus | 949 | <p>I think you should accept @Sainaen 's comment as answer. I am just elaborating on that as no one else has done that till now. The reference is <a href="https://disqus.com/home/channel/discussdisqus/discussion/channel-discussdisqus/javascript_error_discovery_bundle/" rel="nofollow noreferrer">Disqus Bug Report</a></p>
<blockquote>
<p>We checked with our team and these errors aren't a result of any
problem so you can safely ignore them. However, were considering
hiding them so they don't cause any annoyance. Thanks for reporting!</p>
</blockquote>
<p>I verified and the errors are still coming however they do not effect the system's working in any way whatsoever. This is more of an annoyance rather than an error. Still, it should be fixed because Disqus is too big an entity to ignore these silly warnings. What i would suggest is to mail to them the new stack trace along with any other details you think are important. even i would mail them and let's hope it gets removed. If not, then turn a blind eye towards that. Hope it helps.</p> |
36,727,482 | How to remove the "Go to live visual tree" / "Enable selection" / "Display layout adorners" overlay when debugging? | <p>How do I remove the box with the 3 icons when debugging?</p>
<p><a href="https://i.stack.imgur.com/rhlua.png"><img src="https://i.stack.imgur.com/rhlua.png" alt="enter image description here"></a></p> | 36,727,804 | 3 | 4 | null | 2016-04-19 19:17:04.21 UTC | 10 | 2021-11-30 20:03:13.89 UTC | 2016-04-19 19:27:26.84 UTC | null | 939,213 | null | 939,213 | null | 1 | 87 | c#|visual-studio|xaml|windows-runtime|win-universal-app | 22,460 | <p>Just simply uncheck <code>Tools -> Options -> Debugging -> General -> Enable UI Debugging Tools for XAML -> Show runtime tools in application</code>.</p>
<p><a href="https://i.stack.imgur.com/Ta3OB.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Ta3OB.png" alt="Screenshot"></a></p> |
26,346,647 | The database cannot be opened because it is version 782. This server supports version 706 and earlier. A downgrade path is not supported | <p>I have created a sample database using SQL Server 2014 Express and added it to my Windows Form solution. When double click on it to open I get this error. </p>
<blockquote>
<p>The database cannot be opened because it is version 782. This server
supports version 706 and earlier. A downgrade path is not supported</p>
</blockquote>
<p>I am using Visual Studio 2013. I really don't understand that I am using the two latest versions of Microsoft products and they are incompatible. Am I missing something? How can I open this database? </p>
<p><img src="https://i.stack.imgur.com/0pBjQ.png" alt="enter image description here"></p> | 27,220,592 | 6 | 4 | null | 2014-10-13 18:36:25.943 UTC | 22 | 2019-05-29 17:44:01.807 UTC | 2015-03-22 23:28:21.9 UTC | null | 15,168 | null | 1,996,435 | null | 1 | 85 | sql-server|visual-studio | 108,619 | <p>Try changing <kbd>Tools</kbd> > <kbd>Options</kbd> > <kbd>Database Tools</kbd> > <kbd>Data Connections</kbd> > <kbd>SQL Server Instance Name</kbd>. </p>
<p>The default for VS2013 is <code>(LocalDB)\v11.0</code>. </p>
<p>Changing to <code>(LocalDB)\MSSQLLocalDB</code>, for example, seems to work - no more version 782 error.</p> |
5,293,062 | MySQL INSERT/UPDATE on POINT column | <p>I'm trying to populate my DB with geographical places of my country. One of my tables have 4 fields: ID[PK], latitude. longitude ande geoPoint </p>
<pre><code>EDIT `SCDBs`.`Punto_Geografico`;
SET @lat = 18.469692;
SET @lon = -63.93212;
SET @g = 'POINT(@lat @lon)';
UPDATE Punto_Geografico SET latitude = @lat, longitude =@lon, geoPoint =@g WHERE idpunto_geografico = 0;
</code></pre>
<p>im getting the following error:
Error Code: 1416
Cannot get geometry object from data you send to the GEOMETRY field</p>
<p>I'm pretty sure that 'geoPoint' field is a POINT field with a spatial index. Am i missing anything.14</p> | 5,293,091 | 3 | 0 | null | 2011-03-13 22:56:51.463 UTC | 5 | 2022-06-07 14:46:24.75 UTC | 2011-05-04 04:50:20.897 UTC | null | 135,152 | null | 652,201 | null | 1 | 11 | mysql|sql|geospatial|spatial|mysql-error-1416 | 40,298 | <p>Try doing it without assigning your values to server values. Especially if they contain function calls. MySQL treats the contents of the variables as plain text and won't see that there's a function call in there.</p>
<pre><code>UPDATE ... SET latitude=18, longitute=-63, geoPoint=POINT(18 -63) WHERE ...
</code></pre> |
4,952,825 | T4 Get Current Working Directory of Solution | <p>I am using T4 in Visual Studio 2010, and I want to iterate over the files in my solution, however I have found that T4 source generation works in a kind of a sandbox, and the current working directory is inside of the Visual Studio 10 directory in program files.</p>
<p>Is there a way to reference the solution the T4 file is in relativistically, so that it doesn't break the build, or works on some one else's box that doesn't have the same file structure etc?</p>
<p>Thanks </p> | 4,953,636 | 3 | 0 | null | 2011-02-10 02:37:05.83 UTC | 9 | 2017-09-03 11:52:57.4 UTC | 2015-12-04 17:55:11.967 UTC | null | 350,372 | null | 520 | null | 1 | 23 | c#|visual-studio|code-generation|t4 | 18,057 | <p>You must set the <code>hostspecific</code> attribute to true like so:</p>
<pre><code><#@ template language="C#" hostspecific="True" #>
</code></pre>
<p>The <a href="http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.texttemplating.itexttemplatingenginehost.aspx" rel="noreferrer"><code>ITextTemplatingEngineHost</code></a> interface will give you the information you need.</p>
<pre><code><#= this.Host.ResolveParameterValue("-", "-", "projects") #>
</code></pre>
<p>I don't believe there is a way to reference the solution, but you can get the path in which your <code>*.tt</code> file is and from there get other files.</p>
<p>To load a file from a location relative to the text template, you can use this:</p>
<pre><code>this.Host.ResolvePath("relative/path.txt")
</code></pre> |
43,277,715 | Create nuget package from dlls | <p>I want to create a NuGet package which adds multiple .dll files as references to my project.</p>
<p>I have a folder with 10 .dlls files in it. </p>
<p>When I install this via nuget, I want these files to be added to the project's references.</p> | 43,316,056 | 3 | 5 | null | 2017-04-07 12:06:39.117 UTC | 35 | 2021-12-15 06:47:02.77 UTC | 2017-11-13 21:36:46.487 UTC | null | 3,063,884 | null | 6,099,813 | null | 1 | 88 | visual-studio|nuget | 104,474 | <blockquote>
<p>I want to create a nuget package which adds multiple .dll as references to my project.</p>
</blockquote>
<p>I would like give you two solutions to achieve this:</p>
<p>First, Use <strong>NuGet Package Explorer</strong>:</p>
<ol>
<li>Download the <a href="https://github.com/NuGetPackageExplorer/NuGetPackageExplorer" rel="noreferrer">NuGet Package Explorer</a>.</li>
<li>Open the NuGet Package Explorer, select the create a new package.</li>
<li>Add a lib folder on the content tab, and add your dlls file</li>
<li>Save the package and install it to the project, check if it add references.</li>
</ol>
<p><a href="https://i.stack.imgur.com/wl1tm.png" rel="noreferrer"><img src="https://i.stack.imgur.com/wl1tm.png" alt="NuGet Package Explorer GUI" /></a></p>
<p>Second, Just as Lex Li mention, We could <strong>use .nuspec to pack up the assemblies</strong>:</p>
<ol>
<li><p>Download the <a href="https://dist.nuget.org/index.html" rel="noreferrer">nuget.exe</a>.</p>
</li>
<li><p>Create a new project.</p>
</li>
<li><p>Open a cmd and switch path to nuget.exe</p>
</li>
<li><p>Use command line: <code>nuget spec "PathOfProject\TestDemo.csproj"</code></p>
</li>
<li><p>Open the <code>TestDemo.csproj.nuspec</code> file and modify it and add the assemblies as file; below is my .nuspec file:</p>
<pre><code><?xml version="1.0"?>
<package>
<metadata>
<id>TestDemo</id>
<version>1.0.0</version>
<authors>Tester</authors>
<owners>Tester</owners>
<requireLicenseAcceptance>false</requireLicenseAcceptance>
<description>TestDemo</description>
<releaseNotes>Summary of changes made in this release of the package.</releaseNotes>
<copyright>Copyright 2017</copyright>
<tags>Tag1 Tag2</tags>
</metadata>
<files>
<file src="MultipleDll\*.*" target="lib\net461" />
</files>
</package>
</code></pre>
</li>
<li><p>Use pack command: <code>nuget pack TestDemo.csproj.nuspec</code></p>
</li>
<li><p>Open the TestDemo package by NuGet Package Explorer.</p>
</li>
</ol>
<p><a href="https://i.stack.imgur.com/mSUnx.png" rel="noreferrer"><img src="https://i.stack.imgur.com/mSUnx.png" alt="NuGet Package Explorer - built package output" /></a></p> |
61,979,940 | Lombok Private Constructor | <p>Is there any annotation available for Lombok private NoArgConstructor? Lombok <code>@NoArgConstructor</code> creates a public Constructor with no parameter. But I want private constructor annotation.</p> | 61,980,073 | 1 | 3 | null | 2020-05-23 23:41:32.81 UTC | 5 | 2020-05-24 00:04:56.303 UTC | null | null | null | null | 5,648,801 | null | 1 | 45 | java|lombok | 19,923 | <p>Use the <a href="https://projectlombok.org/api/lombok/NoArgsConstructor.html" rel="noreferrer">access level</a> element in the annotation. <code>@NoArgsConstructor(access = AccessLevel.PRIVATE)</code></p> |
9,549,729 | Vim: insert the same characters across multiple lines | <p>Sometimes I want to edit a certain visual block of text across multiple lines.</p>
<p>For example, I would take a text that looks like this:</p>
<pre><code>name
comment
phone
email
</code></pre>
<p>And make it look like this</p>
<pre><code>vendor_name
vendor_comment
vendor_phone
vendor_email
</code></pre>
<p>Currently the way I would do it now is...</p>
<ol>
<li>Select all 4 row lines of a block by pressing <kbd>V</kbd> and then <kbd>j</kbd> four times.</li>
<li>Indent with <kbd>></kbd>.</li>
<li>Go back one letter with <kbd>h</kbd>.</li>
<li>Go to block visual mode with <kbd>Ctrl</kbd><kbd>v</kbd>.</li>
<li>Select down four rows by pressing <kbd>j</kbd> four times. At this point you have selected a 4x1 visual blocks of whitespace (four rows and one column).</li>
<li>Press <kbd>C</kbd>. Notice this pretty much indented to the left by one column.</li>
<li>Type out a <code>" vendor_"</code> without the quote. Notice the extra space we had to put back.</li>
<li>Press <kbd>Esc</kbd>. This is one of the very few times I use <kbd>Esc</kbd> to get out of insert mode. <kbd>Ctrl</kbd><kbd>c</kbd> would only edit the first line.</li>
<li>Repeat step 1.</li>
<li>Indent the other way with <kbd><</kbd>.</li>
</ol>
<p>I don't need to indent if there is at least one column of whitespace before the words. I wouldn't need the whitespace if I didn't have to clear the visual block with <kbd>c</kbd>.</p>
<p>But if I have to clear, then is there a way to do what I performed above without creating the needed whitespace with indentation?</p>
<p>Also why does editing multiple lines at once only work by exiting out of insert mode with <kbd>Esc</kbd> over <kbd>Ctrl</kbd><kbd>c</kbd>?</p>
<hr/>
<p>Here is a more complicated example:</p>
<pre><code>name = models.CharField( max_length = 135 )
comment = models.TextField( blank = True )
phone = models.CharField( max_length = 135, blank = True )
email = models.EmailField( blank = True )
</code></pre>
<p>to</p>
<pre><code>name = models.whatever.CharField( max_length = 135 )
comment = models.whatever.TextField( blank = True )
phone = models.whatever.CharField( max_length = 135, blank = True )
email = models.whatever.EmailField( blank = True )
</code></pre>
<p>In this example I would perform the vertical visual block over the <code>.</code>, and then reinsert it back during insert mode, i.e., type <code>.whatever.</code>. Hopefully now you can see the drawback to this method. I am limited to only selecting a column of text <strong>that are all the same in a vertical position</strong>.</p> | 9,549,765 | 15 | 5 | null | 2012-03-03 20:44:45.593 UTC | 239 | 2022-03-02 01:26:37.763 UTC | 2020-01-18 17:24:08.583 UTC | null | 63,550 | null | 1,150,923 | null | 1 | 407 | vim | 232,218 | <ol>
<li>Move the cursor to the <code>n</code> in <code>name</code>.</li>
<li>Enter visual block mode (<kbd>Ctrl</kbd><kbd>v</kbd>).</li>
<li>Press <kbd>j</kbd> three times (or <kbd>3j</kbd>) to jump down by 3 lines; <kbd>G</kbd> (capital g) to jump to the last line</li>
<li>Press <kbd><code>I</code></kbd> (capital i).</li>
<li>Type in <code>vendor_</code>. Note: It will only update the screen in the <em><strong>first</strong></em> line - until <kbd>Esc</kbd> is pressed (6.), at which point all lines will be updated.</li>
<li>Press <kbd>Esc</kbd>.</li>
</ol>
<p><img src="https://i.stack.imgur.com/T1WBi.gif" alt="mini-screencast demonstrating the method" /></p>
<p>An uppercase <code>I</code> must be used rather than a lowercase <code>i</code>, because the lowercase <code>i</code> is interpreted as the start of a <a href="http://vimhelp.appspot.com/motion.txt.html#text-objects" rel="noreferrer">text object</a>, which is rather useful on its own, e.g. for selecting inside a tag block (<a href="http://vimhelp.appspot.com/motion.txt.html#it" rel="noreferrer"><code>it</code></a>):</p>
<p><img src="https://i.stack.imgur.com/nlwsZ.gif" alt="mini-screencast showing the usefulness of the 'it' text object" /></p> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.