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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
10,032,461 | Git keeps asking me for my ssh key passphrase | <p>I created keys as instructed in the github tutorial, registered them with github, and tried using ssh-agent explicitly — yet git continues to ask me for my passphrase every time I try to do a pull or a push.</p>
<p>What could be the cause?</p> | 10,032,655 | 21 | 1 | null | 2012-04-05 16:33:49.18 UTC | 270 | 2022-07-08 02:35:57.847 UTC | 2021-04-14 13:12:50.717 UTC | null | 3,840,170 | null | 486,057 | null | 1 | 748 | git|ssh-agent | 348,585 | <p>Once you have started the SSH agent with:</p>
<pre><code>eval $(ssh-agent)
</code></pre>
<p>Do either:</p>
<ol>
<li><p>To add your private key to it:</p>
<pre><code> ssh-add
</code></pre>
<p>This will ask you your passphrase just once, and then you should be allowed to push, provided that you uploaded the public key to Github.</p>
</li>
<li><p>To add and save your key permanently on <strong>macOS</strong>:</p>
<pre><code> ssh-add -K
</code></pre>
<p>This will persist it after you close and re-open it by storing it in user's keychain.</p>
<p>If you see a warning about <code>deprecated</code> flags, try the new variant:</p>
<pre><code> ssh-add --apple-use-keychain
</code></pre>
</li>
<li><p>To add and save your key permanently on <strong>Ubuntu</strong> (or equivalent):</p>
<pre><code> ssh-add ~/.ssh/id_rsa
</code></pre>
</li>
</ol> |
8,149,569 | scan a directory to find files in c | <p>I'm trying to create a function in c which scans all my path C: \ temp (Windows) to search for a file that I pass (eg test.txt) and each time it finds one return the path to steps another function to write something in the bottom of this file.
I managed to do the function that writes to the file but can not figure out how to do that scans the folder and pass the address of the file found.</p> | 8,149,604 | 3 | 1 | null | 2011-11-16 09:46:54.8 UTC | 6 | 2018-11-07 08:12:05.613 UTC | 2015-02-12 12:00:59.913 UTC | null | 927,408 | null | 1,035,523 | null | 1 | 7 | c|directory|find | 63,057 | <pre><code>#include <unistd.h>
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
#include <stdlib.h>
void printdir(char *dir, int depth)
{
DIR *dp;
struct dirent *entry;
struct stat statbuf;
if((dp = opendir(dir)) == NULL) {
fprintf(stderr,"cannot open directory: %s\n", dir);
return;
}
chdir(dir);
while((entry = readdir(dp)) != NULL) {
lstat(entry->d_name,&statbuf);
if(S_ISDIR(statbuf.st_mode)) {
/* Found a directory, but ignore . and .. */
if(strcmp(".",entry->d_name) == 0 ||
strcmp("..",entry->d_name) == 0)
continue;
printf("%*s%s/\n",depth,"",entry->d_name);
/* Recurse at a new indent level */
printdir(entry->d_name,depth+4);
}
else printf("%*s%s\n",depth,"",entry->d_name);
}
chdir("..");
closedir(dp);
}
int main()
{
printf("Directory scan of /home:\n");
printdir("/home",0);
printf("done.\n");
exit(0);
}
</code></pre> |
7,931,182 | Reliably detect if the script is executing in a web worker | <p>I am currently writing a little library in JavaScript to help me delegate to a web-worker some heavy computation .</p>
<p>For some reasons (mainly for the ability to debug in the UI thread and then run the same code in a worker) I'd like to detect if the script is currently running in a worker or in the UI thread.</p>
<p>I'm not a seasoned JavaScript developper and I would like to ensure that the following function will reliably detect if I'm in a worker or not :</p>
<pre><code>function testenv() {
try{
if (importScripts) {
postMessage("I think I'm in a worker actually.");
}
} catch (e) {
if (e instanceof ReferenceError) {
console.log("I'm the UI thread.");
} else {
throw e;
}
}
}
</code></pre>
<p>So, does it ?</p> | 11,979,803 | 3 | 0 | null | 2011-10-28 15:12:04.01 UTC | 8 | 2014-05-12 22:07:16.507 UTC | 2011-10-28 15:32:38.533 UTC | null | 110,742 | null | 110,742 | null | 1 | 21 | javascript|web-worker | 16,504 | <p>As noted there is an answer in <a href="https://stackoverflow.com/questions/7507638/is-there-a-standard-mechanism-for-detecting-if-a-javascript-is-executing-as-a-we">another thread</a> which says to check for the presence of a document object on the window. I wanted to however make a modification to your code to avoid doing a try/catch block which <a href="http://www.youtube.com/watch?v=UJPdhx5zTaw&feature=player_detailpage#t=1602s" rel="nofollow noreferrer">slows execution of JS in Chrome</a> and likely in other browsers as well.</p>
<p>EDIT: I made an error previously in assuming there was a window object in the global scope. I usually add</p>
<pre><code>//This is likely SharedWorkerContext or DedicatedWorkerContext
window=this;
</code></pre>
<p>to the top of my worker loader script this allows all functions that use window feature detection to not blow up. Then you may use the function below.</p>
<pre><code>function testEnv() {
if (window.document === undefined) {
postMessage("I'm fairly confident I'm a webworker");
} else {
console.log("I'm fairly confident I'm in the renderer thread");
}
}
</code></pre>
<p>Alternatively without the window assignment as long as its at top level scope.</p>
<pre><code>var self = this;
function() {
if(self.document === undefined) {
postMessage("I'm fairly confident I'm a webworker");
} else {
console.log("I'm fairly confident I'm in the renderer thread");
}
}
</code></pre> |
11,629,475 | Microsoft SQL Server 2008 Management Studio - Connect/Server/Instance Issue | <p>firstly i recently installed this program as I’m working on a project to create a database to use in Microsoft visual studio.</p>
<p>This is the first time I’m using the program, so I’m having a few problems setting it up. I can't connect to a server because presumably i don't have one. I typed in my machine name to create a default/localhost server using windows authentication but i received an error.</p>
<p>Error: </p>
<blockquote>
<p>TITLE: Connect to Server</p>
<p>A network-related or instance-specific error occurred while
establishing a connection to SQL Server. The server was not found or
was not accessible. Verify that the instance name is correct and that
SQL Server is configured to allow remote connections. (provider: Named
Pipes Provider, error: 40 - Could not open a connection to SQL Server)
(Microsoft SQL Server, Error: 2)</p>
</blockquote>
<p>Could someone guide me on how i can setup up a local host to connect and thus be able to create my database. Also I’d like to know afterwards how i can create a server (ftp) to connect into and create my database there allowing me to view this on my laptop or a different machine.</p>
<p>Btw i have looked on Google for this, but I’m getting a bit confused, because I’m unsure what I’m searching for. If anyone can shed some light on my problem i would be greatly appreciated.</p>
<p>Thanks.</p> | 11,631,267 | 9 | 3 | null | 2012-07-24 11:02:00.003 UTC | 3 | 2016-08-01 12:02:32.72 UTC | null | null | null | null | 1,548,432 | null | 1 | 7 | sql-server-2008 | 57,935 | <ol>
<li>Does Your server name looks like : "localhost ( or IP of Your server
)"\"server name", E.G : localhost\SQLEXPRESS</li>
<li>Open application on Start -> -> Configuration Tools -> SQL Server Configuration Manager </li>
<li>Check, if MSSQL Server Service was started in :Sql Server Configuration Manager -> SQL Server Services. If not, right click on service and choose Start</li>
<li>Check on Configuration Manager on "SQL Server Network Configuration" does "TCP\IP" protocol is enabled and has "Listen All" enabled</li>
<li>Check, do You have firewall on port 1433</li>
</ol>
<p>If that doesn't help, write a message</p> |
11,609,188 | Initializing a 2D-array with zero in JAVA | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/2154251/any-shortcut-to-initialize-all-array-elements-to-zero">Any shortcut to initialize all array elements to zero?</a> </p>
</blockquote>
<p>How to Initializing a normal 2D array with zeros(all shells should have zero stored) without using that old looping method that takes lots of time .My code wants something that should take very less time but via looping method my time limit exceeds.</p> | 11,609,214 | 1 | 5 | null | 2012-07-23 08:48:40.237 UTC | 1 | 2018-12-13 10:14:47.73 UTC | 2017-05-23 11:46:41.443 UTC | null | -1 | null | 1,221,631 | null | 1 | 7 | java|arrays|time | 40,632 | <p>The important thing to realise here is that if you're storing primitives then the <a href="http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html" rel="nofollow noreferrer">default value is zero</a> (scroll down to the <em>Default Values</em> section). This applies to array initialisation as well as simple variable initialisation, and consequently you don't have to initialise the array contents explicitly to zero.</p>
<p>If you have to reset an existing structure, however, then you'd have to loop through the structure, and you may be better off initialising a new instance of your array structure. </p>
<p>Note that if you're creating an array or arrays, obviously you have to initialise the first array with the contained array.</p> |
11,772,493 | How to Pass a value via href - PHP | <p>Am passing a value using href tag</p>
<p>In first page Href tag used as</p>
<pre><code>echo "<a href=view_exp.php?compna=",$compname,">$compname</a>";
</code></pre>
<p>In the Second page used </p>
<pre><code>$compname = $_GET['compna'];
</code></pre>
<p>To receive the Compna values are pass but only the first word is passed remaining words are skipped.</p>
<p>Compname as " Chiti Technologies Ltd "
When I pass the value I receive onlt "Chiti" </p> | 11,772,568 | 5 | 0 | null | 2012-08-02 06:58:54.427 UTC | null | 2015-02-23 11:51:40.98 UTC | 2015-02-23 11:51:40.98 UTC | null | 696,364 | null | 1,557,247 | null | 1 | 8 | php|href | 58,623 | <p>The reason you're only getting the first word of the company name is that the company name contains blanks. You need to encode the name.</p>
<pre><code>echo "<a href=view_exp.php?compna=",urlencode($compname),">$compname</a>";
</code></pre> |
11,712,535 | Mac Mountain Lion send notification from CLI app | <p>How can I send a notification to the notification center from a command line app? My attemps so far compile and run, but don't succeed in notifying me.</p>
<p>Example</p>
<pre><code>#import <Cocoa/Cocoa.h>
int main(int argc, const char * argv[]) {
NSLog(@"Running notifications");
NSUserNotification *note = [[NSUserNotification alloc] init];
[note setTitle:@"Test"];
[note setInformativeText:@"Woot"];
NSUserNotificationCenter *center = [NSUserNotificationCenter defaultUserNotificationCenter];
[center scheduleNotification: note];
return 0;
}
</code></pre>
<p>I then compile like:</p>
<pre><code>clang -framework cocoa /tmp/Notes.m
</code></pre>
<p>and I get </p>
<pre><code> 2012-07-29 16:08:35.642 a.out[2430:707] Running notifications
</code></pre>
<p>as output, but no notification :(</p>
<p>Is codesigning a factor in this?</p> | 14,698,543 | 5 | 3 | null | 2012-07-29 20:09:40.787 UTC | 9 | 2018-03-04 03:33:32.61 UTC | 2012-07-30 01:21:19.527 UTC | null | 701,368 | null | 701,368 | null | 1 | 13 | objective-c|cocoa|nsnotificationcenter|osx-mountain-lion|nsusernotification | 3,931 | <p>I found that <code>NSUserNotificationCenter</code> works when <code>[[NSBundle mainBundle] bundleIdentifier]</code> returns the proper identifier. So, I wrote some swizzling code that you can find at <a href="https://github.com/norio-nomura/usernotification" rel="noreferrer">https://github.com/norio-nomura/usernotification</a></p>
<p>It can send an <code>NSUserNotification</code> without an Application Bundle.</p> |
11,590,482 | Do GCM registration id's expire? | <p>I know that C2DM registrations expire, and you are supposed to periodically refresh the registration ID. Is this the case with GCM? by looking at the following code on the Android GCM guide (shown below), it seems like you only do it once and don't need to refresh, but I dont see that explicitly written anywhere, so I just wanted to check. </p>
<pre><code>final String regId = GCMRegistrar.getRegistrationId(this);
if (regId.equals("")) {
GCMRegistrar.register(this, SENDER_ID);
} else {
Log.v(TAG, "Already registered");
}
</code></pre> | 11,590,536 | 2 | 1 | null | 2012-07-21 07:54:36.49 UTC | 17 | 2015-10-15 14:35:10.663 UTC | null | null | null | null | 936,981 | null | 1 | 43 | android|android-notifications|google-cloud-messaging | 36,654 | <p><strong>EDIT: THIS ANSWER IS WAY OUT OF DATE, I HAVE NO IDEA WHAT THE CURRENT BEHAVIOR IS</strong></p>
<hr>
<p>I found the answer myself. You don't explicitly need to re-register all the time, <a href="http://developer.android.com/google/gcm/client.html#sample-register" rel="noreferrer">just once according to the example in the docs</a>. </p>
<p>Also, <em>unlike previous versions of GCM and C2DM</em>, Google itself <strong>does not</strong> refresh the registration itself now: once you have the registration id from the initial registration you are good to go, <strong>except</strong> for one case: you do still need to re-register when the user upgrades to a new version (this case is also handled in the example in the link above): </p>
<blockquote>
<p>When an application is updated, it should invalidate its existing
registration ID, as it is not guaranteed to work with the new version.
Because there is no lifecycle method called when the application is
updated, the best way to achieve this validation is by storing the
current application version when a registration ID is stored.</p>
</blockquote> |
11,805,103 | How can I setup webstorm to automatically add semi-colons to javascript functions, methods, etc | <p>When I write Javascript, I use semi-colons. However when I write in webstorm/phpstorm, it auto completes braces and brackets, but doesn't auto-add a semicolon. I know that isn't required per the standards, etc., but that's the way that I code - and I'm not alone, many people code this way.</p>
<p>Example:</p>
<pre><code>var data = $.ajax({});
</code></pre>
<p>Normally, webstorm/phpstorm will do this, and leave the cursor inside the curly braces:</p>
<pre><code>var data = $.ajax({})
</code></pre>
<p>All in the world that I want is to not have to add the semicolon manually and have it just auto-complete as I noted in my first example.</p> | 11,805,404 | 13 | 2 | null | 2012-08-04 01:09:24.12 UTC | 12 | 2021-12-21 02:48:07.823 UTC | 2019-03-24 11:10:06.763 UTC | null | 10,607,772 | null | 1,286,630 | null | 1 | 67 | javascript|phpstorm|webstorm | 28,304 | <p>There is no way to insert it automatically, you need to use the <strong>Complete Statement</strong> action (<kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>Enter</kbd>).</p>
<p>You also need to check that Settings (Preferences on macOS) | Editor | Code Style | JavaScript | Punctuation | <strong>Use</strong> semicolon to terminate statements option is enabled.</p> |
3,963,457 | How do I select a 1 as a bit in a sql-server view? | <p>I want to create a view in which I select something like the following:</p>
<pre><code>select id, name, 1 as active
from users
</code></pre>
<p>However, I want the active field, which I am creating in the select statement (it doesn't exist in the table), to be a bit field. Is there a way to do this?</p> | 3,963,471 | 4 | 0 | null | 2010-10-18 21:14:24.967 UTC | 1 | 2010-10-18 21:49:35.287 UTC | null | null | null | null | 174,718 | null | 1 | 48 | sql|sql-server-2000 | 45,357 | <p>You can use the CONVERT operator.</p>
<pre><code>SELECT id, name, CONVERT(bit, 1) AS active
FROM users
</code></pre>
<p>CAST or CONVERT will work.</p> |
3,944,170 | Haskell and State | <p>Haskell is a pure functional programming language.</p>
<p>My question is:
<strong>What are the advantages and disadvantages of using Haskell to solve problems involving lots of state, for example GUI programming or game programming?</strong></p>
<p>Also a secondary question: what methods are there to handle state in a functional way?</p>
<p>Thanks in advance.</p> | 3,944,510 | 5 | 9 | null | 2010-10-15 16:26:26.233 UTC | 10 | 2011-10-14 16:40:01.45 UTC | 2011-04-23 22:47:33.627 UTC | null | 83,805 | null | 70,365 | null | 1 | 14 | user-interface|haskell|state|monads | 3,909 | <p>I'm going to answer your second question first. There are actually many ways to handle mutable state in Haskell (and other FP languages). First of all, Haskell does support mutable state in IO, through <code>IORef</code> and <code>mvar</code> constructs. Using these will feel very familiar to programmers from imperative languages. There are also specialized versions such as <code>STRef</code> and <code>TMVar</code>, as well as mutable arrays, pointers, and various other mutable data. The biggest drawback is that these are generally only available within IO or a more specialized monad.</p>
<p>The most common way to simulate state in a functional language is explicitly passing state as a function argument and returned value. For example:</p>
<pre><code>randomGen :: Seed -> (Int, Seed)
</code></pre>
<p>Here <code>randomGen</code> takes a seed parameter and returns a new seed. Every time you call it, you need to keep track of the seed for the next iteration. This technique is always available for state passing, but it quickly gets tedious.</p>
<p>Probably the most common Haskell approach is to use a monad to encapsulate this state passing. We can replace <code>randomGen</code> with this:</p>
<pre><code>-- a Random monad is simply a Seed value as state
type Random a = State Seed a
randomGen2 :: Random Int
randomGen2 = do
seed <- get
let (x,seed') = randomGen seed
put seed'
return x
</code></pre>
<p>Now any functions which need a PRNG can run within the Random monad to request them as needed. You just need to provide an initial state and the computation.</p>
<pre><code>runRandomComputation :: Random a -> Seed -> a
runRandomComputation = evalState
</code></pre>
<p>(note there are functions which considerably shorten the definition of randomGen2; I chose the most explicit version).</p>
<p>If your random computation also needs access to <code>IO</code>, then you use the monad transformer version of State, <code>StateT</code>.</p>
<p>Of special note is the <code>ST</code> monad, which essentially provides a mechanism to encapsulate IO-specific mutations away from the rest of IO. The ST monad provides STRefs, which are a mutable reference to data, and also mutable arrays. Using ST, it's possible to define things like this:</p>
<pre><code>randomList :: Seed -> [Int]
</code></pre>
<p>where [Int] is an infinite list of random numbers (it'll cycle eventually depending on your PSRG) from the starting seed you give it.</p>
<p>Finally, there's <a href="http://www.haskell.org/haskellwiki/Functional_Reactive_Programming" rel="noreferrer">Functional Reactive Programming</a>. Probably the current most prominent libraries for this are <a href="http://www.haskell.org/haskellwiki/Yampa" rel="noreferrer">Yampa</a> and <a href="http://www.haskell.org/haskellwiki/Reactive" rel="noreferrer">Reactive</a>, but the others are worth looking at also. There are several approaches to mutable state within the various implementations of FRP; from my slight use of them they often seem similar in concept to a signalling framework as in QT or Gtk+ (e.g. adding listeners for events).</p>
<p>Now, for the first question. For me, the biggest advantage is that mutable state is separated from other code at the type level. This means that code can't accidentally modify state unless it's explicitly mentioned in the type signature. It also gives very good control of read-only state versus mutable state (Reader monad vs. State monad). I find it very useful to structure my code in this way, and it's useful to be able to tell just from the type signature if a function could be mutating state unexpectedly.</p>
<p>I personally don't really have any reservations about using mutable state in Haskell. The biggest difficulty is that it can be tedious to add state to something that didn't need it previously, but the same thing would be tedious in other languages I've used for similar tasks (C#, Python).</p> |
3,802,054 | Run Logback in Debug | <p>I've recently switched from log4j to logback and am wondering if there is an easy way to run logback in debug mode, similar to log4j's <code>log4j.debug</code> property. I need to see where it is picking up my <code>logback.xml</code> from.</p>
<p>The docs mention using a <code>StatusPrinter</code> to print out logback's internal status, but that would require code changes.</p> | 3,802,093 | 6 | 0 | null | 2010-09-27 08:12:26.04 UTC | 4 | 2022-05-05 02:13:02.693 UTC | null | null | null | null | 7,412 | null | 1 | 53 | java|logging|logback | 50,257 | <p><strong>[EDIT]</strong></p>
<p>This has been fixed in Logback 1.0.4. You can now use <code>-Dlogback.debug=true</code> to enable debugging of the logback setup.</p>
<p>-- Old Answer --</p>
<p>Unfortunately, there is no way to enable debugging via a System property. You have to use <code><configuration debug="true"></code> in the <code>logback.xml</code>. Please submit a feature request.</p> |
3,741,147 | Android Development: How To Use onKeyUp? | <p>I'm new to Android development and I can't seem to find a good guide on how to use an <code>onKeyUp</code> listener.</p>
<p>In my app, I have a big <code>EditText</code>, when someone presses and releases a key in that <code>EditText</code> I want to call a function that will perform regular expressions in that <code>EditText</code>.</p>
<p>I don't know how I'd use the onKeyUp. Could someone please show me how?</p> | 7,210,068 | 7 | 0 | null | 2010-09-18 09:47:47.43 UTC | 2 | 2021-03-01 21:57:11.777 UTC | 2013-10-10 10:55:12.713 UTC | null | 1,318,946 | null | 427,234 | null | 1 | 20 | java|android|onkeyup | 47,321 | <p>The very right way is to use TextWatcher class.</p>
<pre><code>EditText tv_filter = (EditText) findViewById(R.id.filter);
TextWatcher fieldValidatorTextWatcher = new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (filterLongEnough()) {
populateList();
}
}
private boolean filterLongEnough() {
return tv_filter.getText().toString().trim().length() > 2;
}
};
tv_filter.addTextChangedListener(fieldValidatorTextWatcher);
</code></pre> |
3,736,516 | Best way to read, modify, and write XML | <p>My plan is to read in an XML document using my C# program, search for particular entries which I'd like to change, and then write out the modified document. However, I've become unstuck because it's hard to differentiate between elements, whether they start or end using XmlTextReader which I'm using to read in the file. I could do with a bit of advice to put me on the right track.</p>
<p>The document is a HTML document, so as you can imagine, it's quite complicated.</p>
<p>I'd like to search for an element id within the HTML document, so for example look for this and change the src;</p>
<pre><code><img border="0" src="bigpicture.png" width="248" height="36" alt="" id="lookforthis" />
</code></pre> | 3,736,648 | 8 | 0 | null | 2010-09-17 15:04:04.667 UTC | 5 | 2017-11-07 17:10:34.32 UTC | 2010-09-17 15:47:34.227 UTC | null | 148,423 | null | 271,200 | null | 1 | 17 | c#|xml | 81,949 | <p>If it's actually valid XML, and will easily fit in memory, I'd choose <a href="http://msdn.microsoft.com/en-us/library/bb387098.aspx" rel="noreferrer">LINQ to XML</a> (<code>XDocument</code>, <code>XElement</code> etc) every time. It's by far the nicest XML API I've used. It's easy to form queries, and easy to construct new elements too.</p>
<p>You can use XPath where that's appropriate, or the built-in axis methods (<code>Elements()</code>, <code>Descendants()</code>, <code>Attributes()</code> etc). If you could let us know what specific bits you're having a hard time with, I'd be happy to help work out how to express them in LINQ to XML.</p>
<p>If, on the other hand, this is HTML which <em>isn't</em> valid XML, you'll have a much harder time - because XML APIs generalyl expect to work with valid XML documents. You could use <a href="http://tidy.sourceforge.net/" rel="noreferrer">HTMLTidy</a> first of course, but that <em>may</em> have undesirable effects.</p>
<p>For your specific example:</p>
<pre><code>XDocument doc = XDocument.Load("file.xml");
foreach (var img in doc.Descendants("img"))
{
// src will be null if the attribute is missing
string src = (string) img.Attribute("src");
img.SetAttributeValue("src", src + "with-changes");
}
</code></pre> |
3,906,831 | How do I generate memoized recursive functions in Clojure? | <p>I'm trying to write a function that returns a memoized recursive function in Clojure, but I'm having trouble making the recursive function see its own memoized bindings. Is this because there is no var created? Also, why can't I use memoize on the local binding created with let?</p>
<p>This slightly unusual Fibonacci sequence maker that starts at a particular number is an example of what I wish I could do:</p>
<pre><code>(defn make-fibo [y]
(memoize (fn fib [x] (if (< x 2)
y
(+ (fib (- x 1))
(fib (- x 2)))))))
(let [f (make-fibo 1)]
(f 35)) ;; SLOW, not actually memoized
</code></pre>
<p>Using <code>with-local-vars</code> seems like the right approach, but it doesn't work for me either. I guess I can't close over vars?</p>
<pre><code>(defn make-fibo [y]
(with-local-vars [fib (fn [x] (if (< x 2)
y
(+ (@fib (- x 1))
(@fib (- x 2)))))]
(memoize fib)))
(let [f (make-fibo 1)]
(f 35)) ;; Var null/null is unbound!?!
</code></pre>
<p>I could of course manually write a macro that creates a closed-over atom and manage the memoization myself, but I was hoping to do this without such hackery. </p> | 3,908,020 | 8 | 1 | null | 2010-10-11 13:51:01.21 UTC | 8 | 2019-09-01 07:50:55.2 UTC | 2010-10-11 13:57:32.46 UTC | null | 316,182 | null | 316,182 | null | 1 | 38 | recursion|clojure|scope|closures|memoization | 4,891 | <p>This seems to work:</p>
<pre><code>(defn make-fibo [y]
(with-local-vars
[fib (memoize
(fn [x]
(if (< x 2)
y
(+ (fib (- x 2)) (fib (dec x))))))]
(.bindRoot fib @fib)
@fib))
</code></pre>
<p><code>with-local-vars</code> only provides thread-local bindings for the newly created Vars, which are popped once execution leaves the <code>with-local-vars</code> form; hence the need for <code>.bindRoot</code>.</p> |
3,819,247 | GridView Hide Column by code | <p>I want to hide ID column in my GridView, I knew the code </p>
<pre><code>GridView1.Columns[0].Visible = false;
</code></pre>
<p>but the surprise was that my count property for my <code>GridView</code> columns is 0 !!! while I can see data in the <code>GridView</code>, so any ideas?</p>
<p>Thank you,</p>
<p>Update:</p>
<p>here is the complete code for the method which populate the <code>GridView</code></p>
<pre><code>public DataSet GetAllPatients()
{
SqlConnection connection = new SqlConnection(this.ConnectionString);
String sql = "SELECT [ID],[Name],[Age],[Phone],[MedicalHistory],[Medication],[Diagnoses] FROM [dbo].[AwadyClinc_PatientTbl]order by ID desc";
SqlCommand command = new SqlCommand(sql, connection);
SqlDataAdapter da = new SqlDataAdapter(command);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
</code></pre> | 3,819,831 | 13 | 5 | null | 2010-09-29 06:29:32.333 UTC | 11 | 2018-03-26 07:13:06.997 UTC | 2016-07-14 11:22:38.747 UTC | null | 3,894,854 | null | 181,761 | null | 1 | 45 | c#|asp.net | 299,481 | <p><code>GridView.Columns.Count</code> will always be 0 when your GridView has its <code>AutoGenerateColumns</code> property set to <code>true</code> (default is <code>true</code>).</p>
<p>You can explicitly declare your columns and set the <code>AutoGenerateColumns</code> property to <code>false</code>, or you can use this in your codebehind:</p>
<p><code>GridView.Rows[0].Cells.Count</code> </p>
<p>to get the column count once your GridView data has been bound, or this: </p>
<pre><code>protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
e.Row.Cells[index].Visible = false;
}
</code></pre>
<p>to set a column invisible using your GridView's <code>RowDataBound</code> event.</p> |
7,735,315 | Rails route to username instead of id | <p>I am trying to change the rails routes from /users/1 to /username. I currently set this up so it works for the actions of showing and editing. The actual issue is that when I go to update the user by using:</p>
<pre><code><%= form_for @user do |f|%>
</code></pre>
<p>It never updates, because the update action is routed to /users/:id. Is there any way to route this so that it works for /username? (which is the route that is rendering in my forms as the action). I've been scratching my head over this one for a while now.</p>
<p>EDIT:</p>
<p>The issue isn't routing to username, that it working correctly. The issue is that the form routes to /username for update, however the update route for users is still /users/:id instead of :/id.</p>
<p>I tried updating my routes to this, but to no avail:</p>
<pre><code>match '/:id', :to => "users#show", :as => :user
match '/:id', :to => "users#update", :as => :user, :via => :put
match '/:id', :to => "users#destroy", :as => :user, :via => :delete
</code></pre>
<p>EDIT:</p>
<p>Doh! This fixed the issue:</p>
<pre><code>match '/:id', :to => "users#show", :as => :user, :via => :get
</code></pre> | 7,735,324 | 4 | 0 | null | 2011-10-12 04:36:27.083 UTC | 10 | 2011-10-12 05:27:37.337 UTC | 2011-10-12 05:27:37.337 UTC | null | 949,270 | null | 949,270 | null | 1 | 23 | ruby-on-rails|ruby | 10,925 | <p>In your user model:</p>
<pre><code>def to_param
username
end
</code></pre>
<p>The <code>to_param</code> method on ActiveRecord objects uses, by default, just the ID of the object. By putting this code in your model, you're overwriting the ActiveRecord default, so when you link to a User, it will use the <code>username</code> for the parameter instead of <code>id</code>.</p> |
8,227,073 | Using NumberPicker Widget with Strings | <p>Is there a way to use the Android NumberPicker widget for choosing strings instead of integers?</p> | 13,590,660 | 5 | 0 | null | 2011-11-22 12:47:49.79 UTC | 29 | 2021-10-18 12:35:30.503 UTC | null | null | null | null | 810,372 | null | 1 | 106 | android | 61,066 | <pre><code>NumberPicker picker = new NumberPicker(this);
picker.setMinValue(0);
picker.setMaxValue(2);
picker.setDisplayedValues( new String[] { "Belgium", "France", "United Kingdom" } );
</code></pre> |
8,023,414 | How to convert a 128-bit integer to a decimal ascii string in C? | <p>I'm trying to convert a 128-bit unsigned integer stored as an array of 4 unsigned ints to the decimal string representation in C:</p>
<pre><code>unsigned int src[] = { 0x12345678, 0x90abcdef, 0xfedcba90, 0x8765421 };
printf("%s", some_func(src)); // gives "53072739890371098123344"
</code></pre>
<p>(The input and output examples above are completely fictional; I have no idea what that input would produce.)</p>
<p>If I was going to hex, binary or octal, this would be a simple matter of masks and bit shifts to peel of the least significant characters. However, it seems to me that I need to do base-10 division. Unfortunately, I can't remember how to do that across multiple ints, and the system I'm using doesn't support data types larger than 32-bits, so using a 128-bit type is not possible. Using a different language is also out, and I'd rather avoid a big number library just for this one operation.</p> | 8,023,862 | 8 | 10 | null | 2011-11-05 21:29:18.613 UTC | 8 | 2021-03-23 21:56:48.403 UTC | null | null | null | null | 20,744 | null | 1 | 17 | c|string|int|ascii | 13,829 | <p>Division is not necessary:</p>
<pre><code>#include <string.h>
#include <stdio.h>
typedef unsigned long uint32;
/* N[0] - contains least significant bits, N[3] - most significant */
char* Bin128ToDec(const uint32 N[4])
{
// log10(x) = log2(x) / log2(10) ~= log2(x) / 3.322
static char s[128 / 3 + 1 + 1];
uint32 n[4];
char* p = s;
int i;
memset(s, '0', sizeof(s) - 1);
s[sizeof(s) - 1] = '\0';
memcpy(n, N, sizeof(n));
for (i = 0; i < 128; i++)
{
int j, carry;
carry = (n[3] >= 0x80000000);
// Shift n[] left, doubling it
n[3] = ((n[3] << 1) & 0xFFFFFFFF) + (n[2] >= 0x80000000);
n[2] = ((n[2] << 1) & 0xFFFFFFFF) + (n[1] >= 0x80000000);
n[1] = ((n[1] << 1) & 0xFFFFFFFF) + (n[0] >= 0x80000000);
n[0] = ((n[0] << 1) & 0xFFFFFFFF);
// Add s[] to itself in decimal, doubling it
for (j = sizeof(s) - 2; j >= 0; j--)
{
s[j] += s[j] - '0' + carry;
carry = (s[j] > '9');
if (carry)
{
s[j] -= 10;
}
}
}
while ((p[0] == '0') && (p < &s[sizeof(s) - 2]))
{
p++;
}
return p;
}
int main(void)
{
static const uint32 testData[][4] =
{
{ 0, 0, 0, 0 },
{ 1048576, 0, 0, 0 },
{ 0xFFFFFFFF, 0, 0, 0 },
{ 0, 1, 0, 0 },
{ 0x12345678, 0x90abcdef, 0xfedcba90, 0x8765421 }
};
printf("%s\n", Bin128ToDec(testData[0]));
printf("%s\n", Bin128ToDec(testData[1]));
printf("%s\n", Bin128ToDec(testData[2]));
printf("%s\n", Bin128ToDec(testData[3]));
printf("%s\n", Bin128ToDec(testData[4]));
return 0;
}
</code></pre>
<p>Output:</p>
<pre><code>0
1048576
4294967295
4294967296
11248221411398543556294285637029484152
</code></pre> |
8,177,688 | How to Set Layout Background in Android UI | <p>I'm new to Android programming. I have a UI with some <code>TextView</code> and <code>Button</code> controls. How do I set a background behind those components? Lets call it <code>background.png</code>. </p> | 8,177,761 | 9 | 0 | null | 2011-11-18 04:14:51.363 UTC | 3 | 2015-12-10 16:23:13.937 UTC | 2011-11-18 05:08:10.643 UTC | null | 20,938 | null | 1,052,070 | null | 1 | 8 | java|android | 49,904 | <p>in your parent layout element, e.g. linearlayout or whatever, simply add <code>android:background="@drawable/background"</code> This will set the background of your layout, assuming you have the image in a /drawable folder.</p> |
8,308,695 | How to add Options Menu to Fragment in Android | <p>I am trying to add an item to the options menu from a group of fragments.</p>
<p>I have created a new <code>MenuFragment</code> class and extended this for the fragments I wish to include the menu item in. Here is the code:</p>
<p>Java:</p>
<pre><code>public class MenuFragment extends Fragment {
MenuItem fav;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
fav = menu.add("add");
fav.setIcon(R.drawable.btn_star_big_off);
}
}
</code></pre>
<p>Kotlin: </p>
<pre><code>class MenuFragment : Fragment {
lateinit var fav: MenuItem
override fun onCreate(savedInstanceState: Bundle) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
fav = menu.add("add");
fav.setIcon(R.drawable.btn_star_big_off);
}
}
</code></pre>
<p>For some reason the <code>onCreateOptionsMenu</code> appears not to run.</p> | 8,309,255 | 24 | 5 | null | 2011-11-29 09:48:13.83 UTC | 96 | 2022-08-23 16:39:43.07 UTC | 2020-04-04 15:19:45.3 UTC | null | 2,295,681 | null | 1,070,986 | null | 1 | 451 | android|android-fragments|android-optionsmenu | 330,360 | <p>Call the super method:</p>
<p>Java:</p>
<pre class="lang-java prettyprint-override"><code> @Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// TODO Add your menu entries here
super.onCreateOptionsMenu(menu, inflater);
}
</code></pre>
<p>Kotlin:</p>
<pre class="lang-kotlin prettyprint-override"><code> override fun void onCreate(savedInstanceState: Bundle) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
// TODO Add your menu entries here
super.onCreateOptionsMenu(menu, inflater)
}
</code></pre>
<p>Put log statements in the code to see if the method is not being called or if the menu is not being amended by your code.</p>
<p>Also ensure you are calling <code>setHasOptionsMenu(boolean)</code> in <code>onCreate(Bundle)</code> to notify the fragment that it should participate in options menu handling.</p> |
4,159,331 | Python - Speed up an A Star Pathfinding Algorithm | <p>I've coded my first slightly-complex algorithm, an implementation of the <a href="http://en.wikipedia.org/wiki/A*_search_algorithm" rel="noreferrer">A Star Pathfinding</a> algorithm. I followed some <a href="http://www.python.org/doc/essays/graphs.html" rel="noreferrer">Python.org advice</a> on implementing graphs so a dictionary contains all the nodes each node is linked too. Now, since this is all for a game, each node is really just a tile in a grid of nodes, hence how I'm working out the heuristic and my occasional reference to them.</p>
<p>Thanks to timeit I know that I can run this function successfully a little over one hundred times a second. Understandably this makes me a little uneasy, this is without any other 'game stuff' going on, like graphics or calculating game logic. So I'd love to see whether any of you can speed up my algorithm, I am completely unfamiliar with Cython or it's kin, I can't code a line of C.</p>
<p>Without any more rambling, here is my A Star function.</p>
<pre><code>def aStar(self, graph, current, end):
openList = []
closedList = []
path = []
def retracePath(c):
path.insert(0,c)
if c.parent == None:
return
retracePath(c.parent)
openList.append(current)
while len(openList) is not 0:
current = min(openList, key=lambda inst:inst.H)
if current == end:
return retracePath(current)
openList.remove(current)
closedList.append(current)
for tile in graph[current]:
if tile not in closedList:
tile.H = (abs(end.x-tile.x)+abs(end.y-tile.y))*10
if tile not in openList:
openList.append(tile)
tile.parent = current
return path
</code></pre> | 4,159,367 | 3 | 2 | null | 2010-11-11 21:14:12.563 UTC | 24 | 2014-06-17 17:22:04.67 UTC | null | null | null | null | 250,080 | null | 1 | 34 | python|algorithm|performance|a-star | 27,053 | <p>An easy optimization is to use sets instead of lists for the open and closed sets. </p>
<pre><code>openSet = set()
closedSet = set()
</code></pre>
<p>This will make all of the <code>in</code> and <code>not in</code> tests O(1) instead of O(<i>n</i>).</p> |
4,385,515 | Take diff of two vertical opened windows in Vim | <p>I've have two files opened. They are opened in vertical mode, next to next. Can I instantly diff these two files without leaving or closing Vim ?</p> | 4,386,234 | 4 | 0 | null | 2010-12-08 08:35:40.407 UTC | 32 | 2020-10-06 08:16:05.177 UTC | 2010-12-16 13:38:17.12 UTC | null | 513,198 | null | 462,233 | null | 1 | 119 | vim|diff|vimdiff | 23,385 | <p>To begin diffing on all visible windows:</p>
<pre><code>:windo diffthis
</code></pre>
<p>which executes <code>:diffthis</code> on each window.</p>
<p>To end diff mode:</p>
<pre><code>:diffoff!
</code></pre>
<p>(The <code>!</code> makes <code>diffoff</code> apply to all windows of the current tab - it'd be nice if <code>diffthis</code> had the same feature, but it doesn't.)</p> |
4,797,686 | Selecting all columns that start with XXX using a wildcard? | <p>I have several columns in my databases with similar names.
How do I select those based on the word they start with?
Here's an example table layout:
<img src="https://i.stack.imgur.com/8NW2X.png" alt="enter image description here" /></p>
<p>I tried selecting all info for a particular thing (food kind in this example) using</p>
<pre><code>$Food = "Vegetable";
mysql_query("SELECT `" . $Food . " %` FROM `Foods`");
</code></pre>
<p>but it didn't seem to work.</p>
<p>Any help would be appreciated :-)</p>
<p><strong>EDIT: Apparently this wasn't clear from my example, but I already know all column's first words. The columns are always the same and no 'food kinds' are ever added or deleted. The PHP variable is only there to determine which one of a couple of set kinds I need.</strong></p> | 4,797,725 | 5 | 3 | null | 2011-01-25 19:01:25.467 UTC | 2 | 2019-06-04 23:22:57.373 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 408,089 | null | 1 | 26 | php|mysql|select|wildcard | 71,942 | <p>There's no way to do exactly what you're trying to. You could do another query first to fetch all the column names, then process them in PHP and build the second query, but that's probably more complex than just writing out the names that you want.</p>
<p>Or is there a reason this query needs to be dynamic? Will the table's structure change often?</p> |
4,069,784 | Order by in Inner Join | <p>I am putting inner join in my query.I have got the result but didn't know that how the data is coming in output.Can anyone tell me that how the Inner join matching the data.Below I am showing a image.There are two table(One or Two Table).</p>
<p><img src="https://i.stack.imgur.com/IbzZm.png" alt="alt text"></p>
<p>According to me that first row it should be Mohit but output is different.Please tell me.</p>
<p>Thanks in advance.</p> | 4,069,818 | 6 | 0 | null | 2010-11-01 14:31:44.3 UTC | 4 | 2018-08-07 06:51:49.813 UTC | 2010-11-03 08:57:56.937 UTC | null | 55,159 | null | 214,651 | null | 1 | 21 | sql|sql-server|inner-join | 163,450 | <p>You have to sort it if you want the data to come back a certain way. When you say you are expecting "<code>Mohit</code>" to be the first row, I am assuming you say that because "<code>Mohit</code>" is the first row in the <code>[One]</code> table. However, when SQL Server joins tables, it doesn't necessarily join in the order you think.</p>
<p>If you want the first row from <code>[One]</code> to be returned, then try sorting by <code>[One].[ID]</code>. Alternatively, you can <code>order by</code> any other column.</p> |
4,050,907 | Python: OverflowError: math range error | <p>I get a Overflow error when i try this calculation, but i cant figure out why.</p>
<pre><code>1-math.exp(-4*1000000*-0.0641515994108)
</code></pre> | 4,050,933 | 6 | 1 | null | 2010-10-29 10:15:15.643 UTC | 7 | 2020-05-01 06:03:12.33 UTC | null | null | null | null | 490,332 | null | 1 | 38 | python|math|overflow | 128,928 | <p>The number you're asking math.exp to calculate has, in decimal, over 110,000 digits. That's slightly outside of the range of a double, so it causes an overflow.</p> |
4,652,958 | Is there a way to log every gui event in Delphi? | <p>The Delphi debugger is great for debugging linear code, where one function calls other functions in a predictable, linear manner, and we can step through the program line by line.</p>
<p>I find the debugger less useful when dealing with event driven gui code, where a single line of code can cause new events to be triggered, which may in turn trigger other events.
In this situation, the 'step through the code' approach doesn't let me see everything that is going on.</p>
<p>The way I usually solve this is to 1) guess which events might be part of the problem, then 2) add breakpoints or logging to each of those events.</p>
<p>The problem is that this approach is haphazard and time consuming.</p>
<p>Is there a switch I can flick in the debugger to say 'log all gui events'? Or is there some code I can add to trap events, something like</p>
<pre><code>procedure GuiEventCalled(ev:Event)
begin
log(ev);
ev.call();
end
</code></pre>
<p>The end result I'm looking for is something like this (for example):</p>
<pre><code>FieldA.KeyDown
FieldA.KeyPress
FieldA.OnChange
FieldA.OnExit
FieldB.OnEnter
</code></pre>
<p>This would take all the guesswork out of Delphi gui debugging.</p>
<p>I am using Delphi 2010</p>
<p>[EDIT]
A few answers suggested ways to intercept or log Windows messages. Others then pointed out that not all Delphi Events are Windows messages at all. I think it is these type of "Non Windows Message" Events that I was asking about; Events that are created by Delphi code. [/EDIT]</p>
<p>[EDIT2]
After reading all the information here, I had an idea to use RTTI to dynamically intercept TNotifyEvents and log them to the Event Log in the Debugging window. This includes OnEnter, OnExit, OnChange, OnClick, OnMouseEnter, OnMouseLeave events. After a bit of hacking I got it to work pretty well, at least for my use (it doesn't log Key events, but that could be added).
I've posted the code <a href="http://code.google.com/p/delphieventlogger/" rel="noreferrer">here</a></p>
<p>To use</p>
<ol>
<li>Download the EventInterceptor Unit and add it to your project</li>
<li>Add the EventInterceptor Unit to the Uses clause</li>
<li><p>Add this line somewhere in your code for each form you want to track. </p>
<p>AddEventInterceptors(MyForm);</p></li>
</ol>
<p>Open the debugger window and any events that are called will be logged to the Event Log</p>
<p>[/EDIT2]</p> | 4,998,874 | 7 | 1 | null | 2011-01-11 00:10:56.973 UTC | 9 | 2011-02-15 00:31:04.583 UTC | 2011-01-14 04:57:59.01 UTC | null | 348,610 | null | 348,610 | null | 1 | 15 | delphi | 3,374 | <p>Use the "delphieventlogger" Unit I wrote <a href="http://code.google.com/p/delphieventlogger/" rel="noreferrer">download here</a>. It's only one method call and is very easy to use. It logs all TNotifyEvents (e.g. OnChange, OnEnter, OnExit) to the Delphi Event Log in the debugger window.</p> |
4,171,111 | jsTree Open a branch | <p>I am using the JQuery plugin jsTree, <a href="http://www.jstree.com/" rel="noreferrer">http://www.jstree.com/</a>
I am able to expand the whole tree with the following method:</p>
<pre><code>$("#tree").jstree("open_all");
</code></pre>
<p>and also a specific node:</p>
<pre><code>$("#tree").jstree("open_node", $('#childNode'));
</code></pre>
<p>I am having difficulty opening a branch of the tree, open branch opens it fine but does not open its parent if it has one.</p>
<p>Has anyone successully done this with jsTree? Let me know if you need more info.</p>
<p>Thanks</p>
<p>Eef</p> | 4,195,157 | 8 | 0 | null | 2010-11-13 05:25:37.15 UTC | 7 | 2019-09-23 12:47:37.873 UTC | null | null | null | null | 30,786 | null | 1 | 22 | javascript|jquery|treeview|jstree | 63,568 | <p>You could use the binding</p>
<pre><code>$("#tree").bind("open_node.jstree", function (event, data) {
if((data.inst._get_parent(data.rslt.obj)).length) {
data.inst._get_parent(data.rslt.obj).open_node(this, false);
}
});
</code></pre> |
4,187,032 | Get list of data-* attributes using javascript / jQuery | <p>Given an arbitrary HTML element with zero or more <code>data-*</code> attributes, how can one retrieve a list of key-value pairs for the data.</p>
<p>E.g. given this:</p>
<pre><code><div id='prod' data-id='10' data-cat='toy' data-cid='42'>blah</div>
</code></pre>
<p>I would like to be able to programmatically retrieve this:</p>
<pre><code>{ "id":10, "cat":"toy", "cid":42 }
</code></pre>
<p>Using jQuery (v1.4.3), accessing the individual bits of data using <code>$.data()</code> is simple if the keys are known in advance, but it is not obvious how one can do so with arbitrary sets of data.</p>
<p>I'm looking for a 'simple' jQuery solution if one exists, but would not mind a lower level approach otherwise. I had a go at trying to to parse <code>$('#prod').attributes</code> but my lack of javascript-fu is letting me down.</p>
<h2>update</h2>
<p><a href="https://github.com/ubilabs/jquery-customdata" rel="noreferrer">customdata</a> does what I need. However, including a jQuery plugin just for a fraction of its functionality seemed like an overkill. </p>
<p>Eyeballing the source helped me fix my own code (and improved my javascript-fu).</p>
<p>Here's the solution I came up with:</p>
<pre><code>function getDataAttributes(node) {
var d = {},
re_dataAttr = /^data\-(.+)$/;
$.each(node.get(0).attributes, function(index, attr) {
if (re_dataAttr.test(attr.nodeName)) {
var key = attr.nodeName.match(re_dataAttr)[1];
d[key] = attr.nodeValue;
}
});
return d;
}
</code></pre>
<h2>update 2</h2>
<p>As demonstrated in the accepted answer, the solution is trivial with jQuery (>=1.4.4). <code>$('#prod').data()</code> would return the required data dict.</p> | 4,190,650 | 10 | 1 | null | 2010-11-15 17:19:32.287 UTC | 32 | 2021-01-13 08:28:06.25 UTC | 2016-03-04 16:57:23.93 UTC | null | 996,815 | null | 115,845 | null | 1 | 161 | javascript|jquery|html|attributes | 145,542 | <p>Actually, if you're working with jQuery, as of version <del>1.4.3</del> 1.4.4 (because of the bug as mentioned in the comments below), <code>data-*</code> attributes are supported through <a href="http://api.jquery.com/data/" rel="noreferrer"><code>.data()</code></a>: </p>
<blockquote>
<p>As of jQuery 1.4.3 HTML 5 <code>data-</code>
attributes will be automatically
pulled in to jQuery's data object.</p>
<p>Note that strings are left intact
while JavaScript values are converted
to their associated value (this
includes booleans, numbers, objects,
arrays, and null). The <code>data-</code>
attributes are pulled in the first
time the data property is accessed and
then are no longer accessed or mutated
(all data values are then stored
internally in jQuery).</p>
</blockquote>
<p>The <code>jQuery.fn.data</code> function will return all of the <code>data-</code> attribute inside an object as key-value pairs, with the key being the part of the attribute name after <code>data-</code> and the value being the value of that attribute after being converted following the rules stated above. </p>
<p>I've also created a simple demo if that doesn't convince you: <a href="http://jsfiddle.net/yijiang/WVfSg/" rel="noreferrer">http://jsfiddle.net/yijiang/WVfSg/</a></p> |
4,295,386 | How can I check if a value is a JSON object? | <p>My server side code returns a value which is a JSON object on success and a string 'false' on failure. Now how can I check whether the returned value is a JSON object?</p> | 4,295,670 | 13 | 9 | null | 2010-11-28 04:34:05.747 UTC | 21 | 2021-04-01 16:39:23.317 UTC | 2021-04-01 16:39:23.317 UTC | null | 9,193,372 | null | 78,297 | null | 1 | 112 | jquery|json|object | 225,317 | <p>jQuery.parseJSON() should return an object of type "object", if the string was JSON, so you only have to check the type with <code>typeof</code></p>
<pre><code>var response=jQuery.parseJSON('response from server');
if(typeof response =='object')
{
// It is JSON
}
else
{
if(response ===false)
{
// the response was a string "false", parseJSON will convert it to boolean false
}
else
{
// the response was something else
}
}
</code></pre> |
14,482,954 | WebSockets or an alternative with phonegap? | <p>How can I send low latency data to a server and back with phonegap?</p>
<p>Considering I don't have access to php files locally, and don't have experience with node.js or WebSockets I don't know which ones I should use.</p> | 14,483,835 | 4 | 0 | null | 2013-01-23 15:15:23.09 UTC | 10 | 2014-04-26 07:35:04.99 UTC | null | null | null | null | 1,296,178 | null | 1 | 8 | node.js|cordova|websocket | 17,648 | <p>WebSockets aren't natively supported by the browsers in Android or <a href="http://shazronatadobe.wordpress.com/2012/07/20/improvements-in-cordova-2-0-0-for-ios/" rel="nofollow noreferrer">older versions of Cordova under iOS</a>, which means you'll need to use a PhoneGap plugin if you want to use them on the client.</p>
<p>There's more information at: <a href="http://remysharp.com/2010/10/04/websockets-in-phonegap-projects/" rel="nofollow noreferrer">http://remysharp.com/2010/10/04/websockets-in-phonegap-projects/</a></p>
<p>However, I'm not sure (even with the plugin) how resilient WebSockets are likely to be when the device moves between network connections (WiFi -> 3G -> WiFi), so using a simple polling web service may be a more reliable option if your app needs to continue receiving data as your users move around.</p>
<p>If you need to receive data initiated by the server, consider using push notifications instead: both iOS (APN) and Android (C2DM) provide APIs to do this which make more efficient use of the battery than having your app poll your server constantly.</p> |
14,870,945 | node.js Event Loop Diagnostics | <p>Is it possible to peek at the event loop for diagnostics?</p>
<p>I would like to know how many events are currently waiting for execution (excluding setTimeout/interval).</p>
<p>Update: I'd like to do this from inside the running node process.</p> | 14,884,585 | 2 | 5 | null | 2013-02-14 08:52:22.623 UTC | 14 | 2013-09-19 06:55:09.713 UTC | 2013-02-14 09:47:47.85 UTC | null | 52,817 | null | 52,817 | null | 1 | 18 | node.js|event-loop | 3,222 | <p><em>Updated for nodejs 0.10 with setImmediate()</em></p>
<p>While I wasn't able to find the number of waiting events in the queue I found another health metric that might be useful:</p>
<pre><code>var ts=Date.now();
setImmediate(function()
{
var delay=Date.now()-ts;
});
</code></pre>
<p>delay will contain the milliseconds it took from queuing the event to executing it.</p>
<p>This also takes cpu intensive events into account (which would not be possible by just looking at the # of events).</p>
<p>The measurement itself will affect the event queue as well but this should have a much lower overhead than a full profiler.</p> |
14,412,677 | Using sass with Flask and jinja2 | <p>I would like to include a sass compiler in my Flask application. Is there a generally accepted way of doing this?</p> | 14,413,794 | 5 | 0 | null | 2013-01-19 08:50:43.817 UTC | 17 | 2022-08-15 07:35:55.853 UTC | 2013-09-06 15:48:30.127 UTC | null | 2,165,163 | null | 721,768 | null | 1 | 58 | python|flask|sass|jinja2 | 25,810 | <p><a href="http://elsdoerfer.name/docs/flask-assets/" rel="noreferrer">Flask-Assets</a> extension (which uses <a href="http://elsdoerfer.name/docs/webassets/" rel="noreferrer">webassets</a> library) can be used for that. Here's how to configure it to use <a href="http://pypi.python.org/pypi/pyScss" rel="noreferrer">pyScss</a> compiler (implemented in Python) for SCSS:</p>
<pre><code>from flask import Flask, render_template
from flask.ext.assets import Environment, Bundle
app = Flask(__name__)
assets = Environment(app)
assets.url = app.static_url_path
scss = Bundle('foo.scss', 'bar.scss', filters='pyscss', output='all.css')
assets.register('scss_all', scss)
</code></pre>
<p>And in the template include this:</p>
<pre><code>{% assets "scss_all" %}
<link rel=stylesheet type=text/css href="{{ ASSET_URL }}">
{% endassets %}
</code></pre>
<p>SCSS files will be compiled in debug mode as well.</p>
<p>pyScss only supports SCSS syntax, but there are other filters (<code>sass</code>, <code>scss</code> and <code>compass</code>) which use the original Ruby implementation.</p> |
2,636,958 | Create unmanaged c++ object in c# | <p>I have an unmanaged dll with a class "MyClass" in it.
Now is there a way to create an instance of this class in C# code? To call its constructor? I tried but the visual studio reports an error with a message that this memory area is corrupted or something.</p>
<p>Thanks in advance</p> | 2,637,085 | 3 | 4 | null | 2010-04-14 11:34:52.517 UTC | 11 | 2018-01-22 08:38:37.853 UTC | null | null | null | null | 234,396 | null | 1 | 15 | c#|.net|c++|unmanaged | 18,442 | <p>C# cannot create class instance exported from native Dll. You have two options:</p>
<ol>
<li><p>Create C++/CLI wrapper. This is .NET Class Library which can be added as Reference to any other .NET project. Internally, C++/CLI class works with unmanaged class, linking to native Dll by standard C++ rules. For .NET client, this C++/CLI class looks like .NET class.</p></li>
<li><p>Write C wrapper for C++ class, which can be used by .NET client with PInvoke. For example, over-simplified C++ class:</p></li>
</ol>
<pre>
class MyClass()
{
public:
MyClass(int n){data=n;}
~MyClass(){}
int GetData(){return data;}
private:
int data;
};
</pre>
<p>C API wrapper for this class:</p>
<pre>
void* CreateInstance()
{
MyClass* p = new MyClass();
return p;
}
void ReleaseInstance(void* pInstance)
{
MyClass* p = (MyClass*)pInstance;
delete p;
}
int GetData(void* pInstance)
{
MyClass* p = (MyClass*)pInstance;
return p->GetData();
}
// Write wrapper function for every MyClass public method.
// First parameter of every wrapper function should be class instance.
</pre>
<p>CreateInstance, ReleaseInstance and GetData may be declared in C# client using PInvoke, and called directly. void* parameter should be declared as IntPtr in PInvoke declaration.</p> |
2,709,087 | Turning a string into a Uri in Android | <p>I have a string, <code>'songchoice'</code>. I want it to become a 'Uri' so I can use with <code>MediaPlayer.create(context, Uri)</code></p>
<p>How can I convert songchoice to the Uri?</p> | 2,709,109 | 3 | 0 | null | 2010-04-25 17:10:28.643 UTC | 18 | 2021-05-05 07:31:13.053 UTC | 2019-01-20 23:28:16.68 UTC | null | 472,495 | null | 321,763 | null | 1 | 242 | java|android|uri | 158,880 | <pre><code>Uri myUri = Uri.parse("http://www.google.com");
</code></pre>
<p>Here's the doc <a href="http://developer.android.com/reference/android/net/Uri.html#parse%28java.lang.String%29" rel="noreferrer">http://developer.android.com/reference/android/net/Uri.html#parse%28java.lang.String%29</a></p> |
31,766,623 | Stream video content through Web API 2 | <p>I'm in the process of working out what the best way is going to be to do the following:</p>
<p>I have a bunch of CCTV footage files (MP4 files, ranging from 4MB-50MB in size), which I want to make available through a web portal. My first thought was to stream the file through Web API, so I found the link below:</p>
<p><a href="http://www.strathweb.com/2013/01/asynchronously-streaming-video-with-asp-net-web-api/" rel="noreferrer">http://www.strathweb.com/2013/01/asynchronously-streaming-video-with-asp-net-web-api/</a></p>
<p>After implementing a sample project, I realised that the example was based on Web API 1, and not Web API 2.1, which is what I'm using. After doing some more research, I got the code to compile with WebAPI 2.1. I then realised that if I want to do streaming I cannot use MP4 files, there is a fair amount of technical detail behind this, so here is the thread: </p>
<p><a href="https://stackoverflow.com/questions/21921790/best-approach-to-real-time-http-streaming-to-html5-video-client">Best approach to real time http streaming to HTML5 video client</a></p>
<p>It seems for this to work I need to encode my MP4 files to something like WebM, but that is going to take too much time. Icecast (<a href="http://icecast.org/" rel="noreferrer">http://icecast.org/</a>), which is a streaming server, but I haven't tried it out yet, again not sure if this is what I need to do.</p>
<p>Now that I think of it, I actually don't need live streaming, I just need to allow the client to play the video file through their browser, perhaps using HTML5 video element? The thing is, my application needs to work on IOS as well, so I reckon that means I cant even encode my MP4 to FLV and just use flash.</p>
<p>All I really need is to have all my video clips as thumbnails on a web page, and if the client clicks on one, it begins to play ASAP, without having to download the entire file. Think of the "Watch Trailer" feature on imdb.com. Simply just play a video file, thats really what I want. I don't need LIVE streaming, which is what I think WebM is for? Again, not sure.</p> | 33,634,614 | 2 | 1 | null | 2015-08-01 21:58:51.557 UTC | 14 | 2020-06-12 14:56:20.62 UTC | 2017-05-23 11:47:00.513 UTC | null | -1 | null | 128,782 | null | 1 | 19 | c#|asp.net-web-api|ffmpeg|video-streaming|html5-video | 26,633 | <p>Two things:</p>
<ol>
<li><p>Use a <a href="http://www.w3schools.com/tags/tag_video.asp" rel="nofollow noreferrer">video element</a> in your HTML (this works in browsers AND iOS):</p>
<pre><code><video src="http://yoursite.com/api/Media/GetVideo?videoId=42" />
</code></pre></li>
<li><p>Support <code>206 PARTIAL CONTENT</code> requests in you Web API code. This is <strong>crucial</strong> for both streaming and iOS support, and is mentioned in that thread you posted.</p></li>
</ol>
<p>Just follow this example:</p>
<p><a href="https://devblogs.microsoft.com/aspnet/asp-net-web-api-and-http-byte-range-support/" rel="nofollow noreferrer">https://devblogs.microsoft.com/aspnet/asp-net-web-api-and-http-byte-range-support/</a></p>
<p>In a nutshell:</p>
<pre><code>if (Request.Headers.Range != null)
{
// Return part of the video
HttpResponseMessage partialResponse = Request.CreateResponse(HttpStatusCode.PartialContent);
partialResponse.Content = new ByteRangeStreamContent(stream, Request.Headers.Range, mediaType);
return partialResponse;
}
else
{
// Return complete video
HttpResponseMessage fullResponse = Request.CreateResponse(HttpStatusCode.OK);
fullResponse.Content = new StreamContent(stream);
fullResponse.Content.Headers.ContentType = mediaType;
return fullResponse;
}
</code></pre> |
53,972,876 | How do I add a background image to flutter app? | <p>I am trying to add a Background image to my Flutter App, and I have gone through all similar questions on SO. The app m runs fine but the image does not appear.</p>
<p>here is my widget code:</p>
<pre><code> @override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
actions: <Widget>[
new IconButton(icon: const Icon(Icons.list), onPressed: _loadWeb)
],
),
body: new Stack(
children: <Widget>[
Container(
child: new DecoratedBox(
decoration: new BoxDecoration(
image: new DecorationImage(
image: new AssetImage("images/logo.png"),
fit: BoxFit.fill,
),
),
),
),
Center(
child: _authList(),
)
],
),
floatingActionButton: FloatingActionButton(
onPressed: getFile,
tooltip: 'Select file',
child: Icon(Icons.sd_storage),
), // This trailing comma makes auto-formatting nicer for build methods.
));
}
</code></pre>
<p>The app runs fine and the second widget on the stack, which is a listView works normally but the image does not show up.</p>
<p>Any ideas?</p> | 53,973,519 | 5 | 0 | null | 2018-12-29 19:50:10.153 UTC | 6 | 2020-10-07 12:25:02.427 UTC | null | null | null | null | 34,747 | null | 1 | 38 | dart|flutter | 82,226 | <p><code>Scaffold</code> doesn't support any concept of a background image. What you can do is give the <code>Scaffold</code> a transparent color and put it in a <code>Container</code> and use the <code>decoration</code> property to pull in the required background image. The app bar is also transparent. </p>
<pre><code>Widget build(BuildContext context) {
return MaterialApp(
title: 'Welcome to Flutter',
home: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage("images/logo.png"), fit: BoxFit.cover)),
child: Scaffold(
backgroundColor: Colors.transparent,
appBar: AppBar(
elevation: 0,
backgroundColor: Colors.transparent,
title: Text('My App'),
centerTitle: true,
leading: IconButton(
icon: Icon(
Icons.list,
color: Colors.white,
),
onPressed: () {}),
),
),
),
);
}
</code></pre> |
38,944,378 | Django: from django.urls import reverse; ImportError: No module named urls | <p>I am working through the DjangoProject tutorial with the polls app. As the tutorial states in part 4 I am trying to import 'reverse': <code>from django.urls import reverse</code> but getting the error:</p>
<blockquote>
<p>from django.urls import reverse
ImportError: No module named urls</p>
</blockquote>
<p>I have changed the <code>ROOT_URLCONF</code> to just '<code>urls</code>', however, it did not work either.</p>
<p>Any help is appreciated, Thank you.</p>
<p><strong>settings.py</strong></p>
<pre><code>import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '3jyaq2i8aii-0m=fqm#7h&ri2+!7x3-x2t(yv1jutwa9kc)t!e'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'polls.apps.PollsConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'mysite.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'mysite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.9/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/
STATIC_URL = '/static/'
</code></pre>
<p><strong>urls.py</strong> </p>
<pre><code>from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^polls/', include('polls.urls')),
]
</code></pre>
<p><strong>polls/views.py</strong></p>
<pre><code>from django.http import HttpResponse, HttpResponseRedirect
from .models import Question, Choice
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
context = {
'latest_question_list': latest_question_list,
}
return render(request, 'polls/index.html', context)
def detail(request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, 'polls/results.html', {'question' : question})
def results(request, questioin_id):
response = "you are looking at the results of question %s"
return HttpResponse(response % question_id)
def vote(request, question_id):
question = get_object_or_404(Question, pk=questioin_id)
try:
selected_choice = question.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
return render(request, 'polls/detail.html', {'question': question,
'error_message': "you didnt select a choice",
})
else:
selected_choice.votes += 1
selected_choice.save()
return HttpResponseRedirect(reverse('polls:results', args=
(question.id,)))
</code></pre>
<p><strong>polls/urls.py</strong></p>
<pre><code>from django.conf.urls import url
from . import views
app_name = 'polls'
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'),
url(r'^(?P<question_id>[0-9]+)/results/$', views.results, name='results'),
url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'),
]
</code></pre> | 38,944,415 | 1 | 0 | null | 2016-08-14 16:48:06.02 UTC | 2 | 2018-03-09 19:04:44.227 UTC | 2016-08-23 03:16:43.88 UTC | null | 6,280,781 | null | 6,531,255 | null | 1 | 31 | python|django|django-views | 51,616 | <p>You're on Django 1.9, you should do:</p>
<pre><code>from django.core.urlresolvers import reverse
</code></pre>
<p>Starting with version 1.10 (including Django 2.0) is where you get to do <a href="https://docs.djangoproject.com/en/1.10/ref/urlresolvers/" rel="noreferrer"><code>from django.urls import reverse</code></a></p> |
30,096,022 | Always 'Ad Hoc Code Signed' for Embedded Binary Signing Certificate | <p>I have two targets, the main target & an extension target. Now when I'm trying to archive the app, Xcode failed with the following error:</p>
<pre><code>error: Embedded binary is not signed with the same certificate as the parent app. Verify the embedded binary target's code sign settings match the parent app's.
Embedded Binary Signing Certificate: - (Ad Hoc Code Signed)
Parent App Signing Certificate: iPhone Distribution: ***. (EAA28CVMQM)
</code></pre>
<p>So I checked the <code>Build Settings - Code Signing</code> again and again to ensure <code>Embedded binary is signed with the same certificate as the parent app</code>, </p>
<p><img src="https://i.stack.imgur.com/INXL7.png" alt="enter image description here"></p>
<p><img src="https://i.stack.imgur.com/62CYh.png" alt="enter image description here"></p>
<p>Or settings like below :</p>
<p><img src="https://i.stack.imgur.com/eGEH2.png" alt="enter image description here"></p>
<p>They all failed into the same reason. No matter how I change the Code Signing settings, the <code>Embedded Binary Signing Certificate</code> is always <code>(Ad Hoc Code Signed)</code>.</p>
<p>Before this post, I've read these links:</p>
<p><a href="https://stackoverflow.com/questions/25927604/xcode6embedded-binary-is-not-signed-with-the-same-certificate-as-the-parent-app">Xcode6:Embedded binary is not signed with the same certificate as the parent app</a></p>
<p><a href="https://stackoverflow.com/questions/27273911/embedded-binary-is-not-signed-with-the-same-certificate-as-the-parent-app-yet-th">Embedded binary is not signed with the same certificate as the parent app yet they are identical</a></p>
<p><a href="http://aplus.rs/2014/embedded-binary-is-not-signed-with-the-same-certificate-as-the-parent-app/" rel="nofollow noreferrer">http://aplus.rs/2014/embedded-binary-is-not-signed-with-the-same-certificate-as-the-parent-app/</a></p>
<p><a href="https://developer.apple.com/library/ios/technotes/tn2407/_index.html#//apple_ref/doc/uid/DTS40014991-CH1-VALIDATION_ERRORS-EMBEDDED_BINARY_S_BUNDLE_IDENTIFIER_IS_NOT_PREFIXED_WITH_THE_PARENT_APP_S_BUNDLE_IDENTIFIER_" rel="nofollow noreferrer">https://developer.apple.com/library/ios/technotes/tn2407/_index.html#//apple_ref/doc/uid/DTS40014991-CH1-VALIDATION_ERRORS-EMBEDDED_BINARY_S_BUNDLE_IDENTIFIER_IS_NOT_PREFIXED_WITH_THE_PARENT_APP_S_BUNDLE_IDENTIFIER_</a></p>
<p>Thanks for any help.</p> | 30,120,228 | 5 | 0 | null | 2015-05-07 08:43:41.9 UTC | 13 | 2020-06-29 12:42:34.037 UTC | 2017-05-23 12:02:11.563 UTC | null | -1 | null | 889,538 | null | 1 | 12 | ios|xcode|code-signing|provisioning-profile|ios-extensions | 9,005 | <p>Believe it or not!!!!!!!!!!!!</p>
<p>It's the <code>Apple Worldwide Developer Relations Certification Authority</code>, if I choose <code>always trust</code>, Xcode archives failed. When I changed to <code>system defaults</code>, Xcode archives successfully.</p>
<p>Bloody h...</p> |
29,142,417 | 4D position from 1D index? | <p>I need to extract a 4D position from a 1D array. I can see how it goes for 2D and 3D but I'm having a hard time wrapping my head around the 4th dimension..</p>
<p>For 2D:</p>
<pre><code>int* array = new int[width * height];
int index = y * width + x;
int x = index / height
int y = index - x * height;
</code></pre>
<p>For 3D:</p>
<pre><code>int* array = new int[width * height * depth];
int index = z * width * height + y * width + z;
int x = index / (height * depth);
int y = index - (x * height * depth) / depth;
int z = index - (x * height * depth) - (y * depth);
</code></pre>
<p>For 4D ?</p>
<pre><code>int* array = new int[width * height * depth * duration];
int index = w * width * height * depth + z * width * height + y * width + w;
int x = index / (height * depth * duration);
int y = ??
</code></pre> | 29,148,148 | 1 | 0 | null | 2015-03-19 10:42:27.35 UTC | 9 | 2020-11-10 20:48:34.69 UTC | null | null | null | null | 1,537,817 | null | 1 | 8 | arrays|multidimensional-array|3d | 4,181 | <p>The indexing formula is given by the multiplication of any given dimension value with the product of all the previous dimensions.</p>
<pre><code>Index = xn ( D1 * ... * D{n-1} ) + x{n-1} ( D1 * ... * D{n-2} ) + ... + x2 * D1 + x1
</code></pre>
<p>So for 4D</p>
<pre><code>index = x + y * D1 + z * D1 * D2 + t * D1 * D2 * D3;
x = Index % D1;
y = ( ( Index - x ) / D1 ) % D2;
z = ( ( Index - y * D1 - x ) / (D1 * D2) ) % D3;
t = ( ( Index - z * D2 * D1 - y * D1 - x ) / (D1 * D2 * D3) ) % D4;
/* Technically the last modulus is not required,
since that division SHOULD be bounded by D4 anyways... */
</code></pre>
<p>The general formula being of the form</p>
<pre><code>xn = ( ( Index - Index( x1, ..., x{n-1} ) ) / Product( D1, ..., D{N-1} ) ) % Dn
</code></pre> |
22,943,658 | IllegalStateException: The application's PagerAdapter changed the adapter's content without calling PagerAdapter#notifyDataSetChanged | <p>I'm using the <code>ViewPager</code> example with <code>ActionBar</code> tabs taken from the Android documentation <a href="http://developer.android.com/reference/android/support/v4/view/ViewPager.html">here</a>.</p>
<p>Unfortunately, as soon as I call the <code>addTab</code> method, the application crashes with the following exception:</p>
<blockquote>
<p>IllegalStateException: The application's PagerAdapter changed the
adapter's content without calling PagerAdapter#notifyDataSetChanged!
Expected adapter item count 0, found 1.</p>
</blockquote>
<p>This is the <code>FragmentPagerAdapter</code> code:</p>
<pre><code>public static class TabsAdapter extends FragmentPagerAdapter
implements ActionBar.TabListener, ViewPager.OnPageChangeListener {
private final Context mContext;
private final ActionBar mActionBar;
private final ViewPager mViewPager;
private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();
static final class TabInfo {
private final Class<?> clss;
private final Bundle args;
TabInfo(Class<?> _class, Bundle _args) {
clss = _class;
args = _args;
}
}
public TabsAdapter(Activity activity, ViewPager pager) {
super(activity.getFragmentManager());
mContext = activity;
mActionBar = activity.getActionBar();
mViewPager = pager;
mViewPager.setAdapter(this);
mViewPager.setOnPageChangeListener(this);
}
public void addTab(ActionBar.Tab tab, Class<?> clss, Bundle args) {
TabInfo info = new TabInfo(clss, args);
tab.setTag(info);
tab.setTabListener(this);
mTabs.add(info);
mActionBar.addTab(tab);
notifyDataSetChanged();
}
@Override
public int getCount() {
return mTabs.size();
}
@Override
public Fragment getItem(int position) {
TabInfo info = mTabs.get(position);
return Fragment.instantiate(mContext, info.clss.getName(), info.args);
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
mActionBar.setSelectedNavigationItem(position);
}
@Override
public void onPageScrollStateChanged(int state) {
}
@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
Object tag = tab.getTag();
for (int i=0; i<mTabs.size(); i++) {
if (mTabs.get(i) == tag) {
mViewPager.setCurrentItem(i);
}
}
}
@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
}
}
</code></pre>
<p>I'm not modifying my adapter in any other part of my code and I'm calling the <code>addTab</code> method from the main thread, the <code>addTab</code> method ends with a call to <code>notifyDataSetChanged</code>. As the documentation recommends to do:</p>
<blockquote>
<p>PagerAdapter supports data set changes. Data set changes must occur on
the main thread and must end with a call to notifyDataSetChanged()
similar to AdapterView adapters derived from BaseAdapter.</p>
</blockquote> | 22,943,659 | 10 | 0 | null | 2014-04-08 17:02:59.87 UTC | 6 | 2020-10-27 07:54:41.367 UTC | null | null | null | null | 1,433,971 | null | 1 | 41 | android|android-viewpager|illegalstateexception|fragmentpageradapter | 61,529 | <p>I had a hard time making my <code>ViewPager</code> working. At the end, it seems that the example in the documentation is wrong.</p>
<p>The <code>addTab</code> method should be as follows:</p>
<pre><code>public void addTab(Tab tab, Class<?> clss, Bundle args) {
TabInfo info = new TabInfo(clss, args);
tab.setTag(info);
tab.setTabListener(this);
mTabs.add(info);
notifyDataSetChanged();
mActionBar.addTab(tab);
}
</code></pre>
<p>Notice the order of the last three operations. In the original example, <code>notifyDataSetChanged</code> was called after the <code>mActionBar.addTab</code> function.</p>
<p>Unfortunately, as soon as you call the <code>addTab</code> on the <code>ActionBar</code>, the first tab you add is automatically selected. Because of this, the <code>onTabSelected</code> event is fired and while trying to retrieve the page, it throws the <code>IllegalStateException</code> because it notices a discrepancy between the expected item count and the actual one.</p> |
20,905,350 | Latest 'pip' fails with "requires setuptools >= 0.8 for dist-info" | <p>Using the recent (1.5) version of <code>pip</code>, I get an error when attempting to update several packages. For example, <code>sudo pip install -U pytz</code> results in failure with:</p>
<pre><code>Wheel installs require setuptools >= 0.8 for dist-info support.
pip's wheel support requires setuptools >= 0.8 for dist-info support.
</code></pre>
<p>I don't understand this message <a href="https://stackoverflow.com/q/21063614/656912">(I have <code>setuptools</code> 2.1)</a> or what to do about it.</p>
<hr>
<p>Exception information from the log for this error:</p>
<pre><code>Exception information:
Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/pip/basecommand.py", line 122, in main
status = self.run(options, args)
File "/Library/Python/2.7/site-packages/pip/commands/install.py", line 230, in run
finder = self._build_package_finder(options, index_urls, session)
File "/Library/Python/2.7/site-packages/pip/commands/install.py", line 185, in _build_package_finder
session=session,
File "/Library/Python/2.7/site-packages/pip/index.py", line 50, in __init__
self.use_wheel = use_wheel
File "/Library/Python/2.7/site-packages/pip/index.py", line 89, in use_wheel
raise InstallationError("pip's wheel support requires setuptools >= 0.8 for dist-info support.")
InstallationError: pip's wheel support requires setuptools >= 0.8 for dist-info support.
</code></pre> | 20,906,394 | 2 | 0 | null | 2014-01-03 14:00:42.453 UTC | 26 | 2022-02-24 23:30:17.51 UTC | 2017-05-23 12:02:11.703 UTC | null | -1 | null | 656,912 | null | 1 | 83 | python|pip|setuptools|python-wheel | 33,631 | <p>This worked for me:</p>
<pre><code>sudo pip install setuptools --no-use-wheel --upgrade
</code></pre>
<p>Note it's usage of <code>sudo</code></p>
<p><strong>UPDATE</strong></p>
<p>On Windows you just need to execute <code>pip install setuptools --no-use-wheel --upgrade</code> as an administrator. In Unix/Linux, the <code>sudo</code> command is for elevating permissions.</p>
<p><strong>UPDATE 2</strong></p>
<p>This appears to have been fixed in 1.5.1.</p> |
38,533,338 | Comparator.comparing(...) of a nested field | <p>Suppose I have a domain model like this:</p>
<pre><code>class Lecture {
Course course;
... // getters
}
class Course {
Teacher teacher;
int studentSize;
... // getters
}
class Teacher {
int age;
... // getters
}
</code></pre>
<p>Now I can create a Teacher Comparator like this:</p>
<pre><code> return Comparator
.comparing(Teacher::getAge);
</code></pre>
<p>But how do I compare Lecture's on nested fields, like this?</p>
<pre><code> return Comparator
.comparing(Lecture::getCourse::getTeacher:getAge)
.thenComparing(Lecture::getCourse::getStudentSize);
</code></pre>
<p>I can't add a method <code>Lecture.getTeacherAge()</code> on the model.</p> | 38,533,383 | 4 | 2 | null | 2016-07-22 18:42:10.817 UTC | 7 | 2022-05-16 17:41:50.943 UTC | null | null | null | null | 472,109 | null | 1 | 38 | java|lambda|java-8|comparator | 35,250 | <p>You can't nest method references. You can use lambda expressions instead:</p>
<pre><code>return Comparator
.comparing(l->l.getCourse().getTeacher().getAge(), Comparator.reverseOrder())
.thenComparing(l->l.getCourse().getStudentSize());
</code></pre>
<hr>
<p>Without the need for reverse order it's even less verbose:</p>
<pre><code>return Comparator
.comparing(l->l.getCourse().getTeacher().getAge())
.thenComparing(l->l.getCourse().getStudentSize());
</code></pre>
<p>Note: in some cases you need to explicitly state the generic types. For example, the code below won't work without the <code><FlightAssignment, LocalDateTime></code> before <code>comparing(...)</code> in Java 8.</p>
<pre><code>flightAssignmentList.sort(Comparator
.<FlightAssignment, LocalDateTime>comparing(a -> a.getFlight().getDepartureUTCDateTime())
.thenComparing(a -> a.getFlight().getArrivalUTCDateTime())
.thenComparing(FlightAssignment::getId));
</code></pre>
<p>Newer java version have better auto type detection and might not require that.</p> |
38,057,526 | Export AWS configuration as CloudFormation template | <p>I´m using AWS CLI and CloudFormation, and I could not find any reference in the documentation.</p>
<p>Does anybody know if it´s possible to create a CloudFormation template from a current configuration.</p>
<p>Let´s say that I want to get a CloudFormation template from my current security group configuration.</p>
<p>Any idea if it´s possible to export that configuration as a template using CLI?</p> | 55,764,927 | 4 | 0 | null | 2016-06-27 15:12:51.82 UTC | 12 | 2022-07-05 13:42:46.06 UTC | 2021-10-13 21:34:36.587 UTC | null | 74,089 | null | 854,207 | null | 1 | 34 | amazon-web-services|amazon-cloudformation | 25,611 | <p>Based on our experience we found 3 possible ways to translate existing manually deployed (from Web Console UI) AWS infra to Cloudformation (CF).</p>
<ol>
<li><p>Using a new CloudFormation native introduced feature (since Nov 2019) that allows you to <a href="https://aws.amazon.com/blogs/aws/new-import-existing-resources-into-a-cloudformation-stack/" rel="nofollow noreferrer">Import existing resources into a CloudFormation stack</a></p>
</li>
<li><p>Using <code>aws cli</code> execute <code>$aws service_name_here describe</code> for each element that make up your stack eg for <strong>RDS Database Stack</strong>:</p>
</li>
</ol>
<ul>
<li>RDS Instance -> <code>Type: AWS::RDS::DBInstance</code>,</li>
<li>RDS (EC2) SG -> <code>Type: AWS::EC2::SecurityGroup</code>,</li>
<li>RDS Subnet Group -> <code>Type: AWS::RDS::DBSubnetGroup</code> and</li>
<li>RDS DB Param Group -> <code>Type: AWS::RDS::DBParameterGroup</code></li>
</ul>
<p><strong>And manually translate to CF</strong> based on the outputs obtained from the <code>aws cli</code> for each of the components. This approach usually requires more experience in both AWS and CF but the templates that you are creating can be structured and designed under good practices, fully parameterized (<code>Sub, Ref, Join, Fn::GetAtt:, Fn::ImportValue</code>), modular, applying <code>conditions</code> and in a 1st iteration the result would probably be close to the final state of the templates (interesting reference examples: <a href="https://github.com/widdix/aws-cf-templates/" rel="nofollow noreferrer">https://github.com/widdix/aws-cf-templates/</a>).</p>
<p><strong>Extra points! :)</strong></p>
<ol start="3">
<li>Some other new alternatives to export your current deployed AWS infra to Cloudformation / Terraform code:</li>
</ol>
<ul>
<li><a href="https://former2.com" rel="nofollow noreferrer">https://former2.com</a></li>
<li><a href="https://modules.tf" rel="nofollow noreferrer">https://modules.tf</a></li>
<li><a href="https://www.brainboard.co/" rel="nofollow noreferrer">https://www.brainboard.co/</a></li>
</ul>
<hr />
<p><strong>Related Article:</strong> <a href="https://medium.com/@exequiel.barrirero/aws-export-configuration-as-code-cloudformation-terraform-b1bca8949bca" rel="nofollow noreferrer">https://medium.com/@exequiel.barrirero/aws-export-configuration-as-code-cloudformation-terraform-b1bca8949bca</a></p> |
35,479,025 | Cross project management using service account | <p>I need a service account that can access multiple projects, but I have not been able to find a way to do this at all. It seems that a service account is always bound to a project.</p>
<p>Another option is to create a service account on the separate projects and then authenticate them using <code>gcloud auth activate-service-account --key-file SOME_FILE.json</code>, but the problem here is that it does not seem possible to automate the creation of service accounts.</p>
<p>So the question is then: Is it possible to create a cross project service account or to automate the creation of a service accounts? Even better would be if I could do both</p> | 35,558,464 | 3 | 0 | null | 2016-02-18 10:35:25.913 UTC | 13 | 2020-02-10 10:55:17.457 UTC | null | null | null | null | 1,226,744 | null | 1 | 60 | google-cloud-platform|gcloud | 38,267 | <p>You should be able to add a service account to another project:</p>
<ol>
<li><p>Create the first service account in project A in the Cloud Console. Activate it using <code>gcloud auth activate-service-account</code>.</p></li>
<li><p>In the Cloud Console, navigate to project B. Find the "IAM & admin" > "IAM" page. Click the "Add" button. In the "New members" field paste the name of the service account (it should look like a strange email address) and give it the appropriate role.</p></li>
<li><p>Run <code>gcloud</code> commands with <code>--project</code> set to project B. They should succeed (I just manually verified that this will work).</p></li>
</ol>
<p>Automatic creation of service accounts is something that we're hesitant to do until we can work through all of the security ramifications.</p> |
28,562,666 | How to move an existing job from one view to another in Jenkins? | <p>I want to move an existing job from one view to another but I can't find the way. Is the only way to copy the job and delete it from the other view? I would like to have the same name and for my experience Jenkins doesn't handle very well the renaming of jobs.</p> | 28,562,900 | 6 | 0 | null | 2015-02-17 13:27:44.857 UTC | 9 | 2019-07-02 07:30:32.44 UTC | null | null | null | null | 658,957 | null | 1 | 163 | jenkins | 86,822 | <p>you can simply do it by editing the view (link "Edit view" on left side) and check/uncheck checkboxes
<a href="https://i.stack.imgur.com/J1SxC.png" rel="noreferrer"><img src="https://i.stack.imgur.com/J1SxC.png" alt="enter image description here"></a></p> |
751,838 | Create an index on SQL view with UNION operators? Will it really improve performance? | <p>I am trying to create an index on the following view:</p>
<pre><code>SELECT 'Candidate' AS Source, CandidateID AS SourceId, LastName + ', ' + FirstName AS SourceName
FROM dbo.Candidates
UNION
SELECT 'Resource' AS Source, ResourceID AS SourceId, LastName + ', ' + FirstName AS SourceName
FROM dbo.Resources
UNION
SELECT 'Deal' AS Source, DealID AS SourceId, CONVERT(varchar, Number) + '-' + CONVERT(varchar, RevisionNumber) AS SourceName
FROM dbo.Deals
UNION
SELECT 'Job Order' AS Source, JobOrderID AS SourceId, CustomerNumber AS SourceName
FROM dbo.JobOrders
</code></pre>
<p>I am getting the following error:</p>
<pre><code>Msg 1939, Level 16, State 1, Line 2
Cannot create index on view '_Source' because the view is not schema bound.
</code></pre>
<p>I added WITH SCHEMABINDING to the CREATE and now get the following error:</p>
<pre><code>Msg 10116, Level 16, State 1, Line 2
Cannot create index on view 'DEALMAKER.dbo._Source' because it contains one or more UNION, INTERSECT, or EXCEPT operators. Consider creating a separate indexed view for each query that is an input to the UNION, INTERSECT, or EXCEPT operators of the original view.
</code></pre>
<p>My questions are:</p>
<p>How would I create an index on this view? Would creating separate indexed views <strong>really</strong> work? </p>
<p>Lastly, am I <strong>really</strong> going to see a performance improvement for any queries that may JOIN this view?</p>
<p>Thanks in advance!</p> | 751,848 | 2 | 1 | null | 2009-04-15 14:00:54.92 UTC | 3 | 2012-06-15 16:36:23.57 UTC | null | null | null | null | 1,768 | null | 1 | 18 | sql|sql-server|database|views | 40,022 | <p>You cannot create an index on a view that makes use of a union operator. Really no way around that, sorry!</p>
<p>I would imagine you've seen this, but check out this <a href="http://msdn.microsoft.com/en-us/library/ms191432.aspx" rel="noreferrer">MSDN page</a>. It gives the requirements for indexed views and explains what they are and how they work.</p>
<p>As to whether or not you'd see a performance benefit if you COULD index the view, that would depend entirely on the size of your tables. I would not expect any impact on creating separate indexed views, as I would assume that your tables are already indexed and you aren't doing any joining or logic in the view.</p> |
2,507,798 | Prevent TextView from wrapping in parent | <p>How do I prevent a TextView, or any visual object, from wrapping to the screen and instead have them chopped off the sides? Is there some XML attribute or code to do this or is it impossible to have anything overflow from the screen?</p>
<p>For example, you have this:</p>
<p><a href="https://i.stack.imgur.com/WsXuR.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/WsXuR.jpg" alt="text being wrapped"></a>
</p>
<p>But you really want this:</p>
<p><a href="https://i.stack.imgur.com/5xhKy.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/5xhKy.jpg" alt="text being cropped"></a>
</p>
<p>Any ideas?</p> | 2,507,873 | 5 | 0 | null | 2010-03-24 13:01:41.197 UTC | 10 | 2019-07-05 21:12:54.11 UTC | 2019-07-05 21:12:54.11 UTC | null | 4,751,173 | null | 80,428 | null | 1 | 43 | android|textview | 27,459 | <p>check out <code>android:maxLines="1"</code> and if you want to add ending <code>...</code> add also <code>android:ellipsize="end"</code></p>
<pre><code><TextView
android:id="@+id/name"
android:text="i want this to crop not wrap"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:maxLines="1"
android:ellipsize="end" />
</code></pre>
<p><code>android:singleLine="true"</code> was <a href="https://developer.android.com/reference/android/R.attr.html#singleLine" rel="noreferrer" title="Android Developers Documentation">deprecated in API Level 3</a>.</p> |
2,678,551 | When should space be encoded to plus (+) or %20? | <p>Sometimes the spaces get URL encoded to the <code>+</code> sign, and some other times to <code>%20</code>. What is the difference and why should this happen?</p> | 2,678,602 | 5 | 0 | null | 2010-04-20 20:55:31.867 UTC | 172 | 2021-11-19 14:59:50.56 UTC | 2021-11-19 14:48:23.227 UTC | null | 63,550 | null | 171,950 | null | 1 | 583 | urlencode | 316,326 | <p><code>+</code> means a space <em>only</em> in <code>application/x-www-form-urlencoded</code> content, such as the query part of a URL:</p>
<pre><code>http://www.example.com/path/foo+bar/path?query+name=query+value
</code></pre>
<p>In this URL, the parameter name is <code>query name</code> with a space and the value is <code>query value</code> with a space, but the folder name in the path is literally <code>foo+bar</code>, <em>not</em> <code>foo bar</code>.</p>
<p><code>%20</code> is a valid way to encode a space in either of these contexts. So if you need to URL-encode a string for inclusion in part of a URL, it is always safe to replace spaces with <code>%20</code> and pluses with <code>%2B</code>. This is what, e.g., <code>encodeURIComponent()</code> does in JavaScript. Unfortunately it's not what <a href="http://php.net/manual/en/function.urlencode.php" rel="noreferrer">urlencode</a> does in PHP (<a href="http://php.net/manual/en/function.rawurlencode.php" rel="noreferrer">rawurlencode</a> is safer).</p>
<h3>See Also</h3>
<p><a href="http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.1" rel="noreferrer">HTML 4.01 Specification application/x-www-form-urlencoded</a></p> |
3,001,888 | How do .gitignore exclusion rules actually work? | <p>I'm trying to solve a gitignore problem on a large directory structure, but to simplify my question I have reduced it to the following.</p>
<p>I have the following directory structure of two files (foo, bar) in a brand new git repository (no commits so far):</p>
<pre><code>a/b/c/foo
a/b/c/bar
</code></pre>
<p>Obviously, a 'git status -u' shows:</p>
<pre><code># Untracked files:
...
# a/b/c/bar
# a/b/c/foo
</code></pre>
<p>What I want to do is create a .gitignore file that ignores everything inside a/b/c but does not ignore the file 'foo'.</p>
<p>If I create a .gitignore thus:</p>
<pre><code>c/
</code></pre>
<p>Then a 'git status -u' shows both foo and bar as ignored:</p>
<pre><code># Untracked files:
...
# .gitignore
</code></pre>
<p>Which is as I expect.</p>
<p>Now if I add an exclusion rule for foo, thus:</p>
<pre><code>c/
!foo
</code></pre>
<p>According to the gitignore manpage, I'd expect this to to work. But it doesn't - it still ignores foo:</p>
<pre><code># Untracked files:
...
# .gitignore
</code></pre>
<p>This doesn't work either:</p>
<pre><code>c/
!a/b/c/foo
</code></pre>
<p>Neither does this:</p>
<pre><code>c/*
!foo
</code></pre>
<p>Gives:</p>
<pre><code># Untracked files:
...
# .gitignore
# a/b/c/bar
# a/b/c/foo
</code></pre>
<p>In that case, although foo is no longer ignored, bar is also not ignored.</p>
<p>The order of the rules in .gitignore doesn't seem to matter either.</p>
<p>This also doesn't do what I'd expect:</p>
<pre><code>a/b/c/
!a/b/c/foo
</code></pre>
<p>That one ignores both foo and bar.</p>
<p>One situation that does work is if I create the file a/b/c/.gitignore and put in there:</p>
<pre><code>*
!foo
</code></pre>
<p>But the problem with this is that eventually there will be other subdirectories under a/b/c and I don't want to have to put a separate .gitignore into every single one - I was hoping to create 'project-based' .gitignore files that can sit in the top directory of each project, and cover all the 'standard' subdirectory structure.</p>
<p>This also seems to be equivalent:</p>
<pre><code>a/b/c/*
!a/b/c/foo
</code></pre>
<p>This might be the closest thing to "working" that I can achieve, but the full relative paths and explicit exceptions need to be stated, which is going to be a pain if I have a lot of files of name 'foo' in different levels of the subdirectory tree.</p>
<p>Anyway, either I don't quite understand how exclusion rules work, or they don't work at all when directories (rather than wildcards) are ignored - by a rule ending in a /</p>
<p>Can anyone please shed some light on this?</p>
<p>Is there a way to make gitignore use something sensible like regular expressions instead of this clumsy shell-based syntax?</p>
<p>I'm using and observe this with git-1.6.6.1 on Cygwin/bash3 and git-1.7.1 on Ubuntu/bash3.</p> | 3,001,967 | 5 | 2 | null | 2010-06-08 22:46:52.953 UTC | 33 | 2019-07-01 14:38:31.607 UTC | 2019-07-01 14:38:31.607 UTC | null | 6,820,850 | null | 143,397 | null | 1 | 163 | git|gitignore | 85,811 | <pre>/a/b/c/*
!foo</pre>
<p>Seems to work for me (git 1.7.0.4 on Linux). The <code>*</code> is important as otherwise you're ignoring the directory itself (so git won't look inside) instead of the files within the directory (which allows for the exclusion).</p>
<p>Think of the exclusions as saying "but not this one" rather than "but include this" - "ignore this directory (<code>/a/b/c/</code>) but not this one (<code>foo</code>)" doesn't make much sense; "ignore all files in this directory (<code>/a/b/c/*</code>) but not this one (<code>foo</code>)" does. To quote the man page:</p>
<blockquote>
<p>An optional prefix ! which negates the pattern; any matching file excluded by a previous pattern will become included again.</p>
</blockquote>
<p>i.e., the <em>file</em> has to have been excluded already to be included again. Hope that sheds some light.</p> |
2,667,524 | Django query case-insensitive list match | <p>I have a list of names that I want to match case insensitive, is there a way to do it without using a loop like below?</p>
<pre><code>a = ['name1', 'name2', 'name3']
result = any([Name.objects.filter(name__iexact=name) for name in a])
</code></pre> | 2,667,582 | 8 | 0 | null | 2010-04-19 12:57:23.887 UTC | 7 | 2022-09-05 18:31:02.053 UTC | 2014-12-23 01:55:23.037 UTC | null | 359,284 | null | 294,103 | null | 1 | 49 | django|django-queryset | 22,839 | <p>Unfortunatley, there are <em>no</em> <code>__iin</code> field lookup. But there is a <a href="https://docs.djangoproject.com/en/3.0/ref/models/querysets/#iregex" rel="noreferrer"><code>iregex</code></a> that might be useful, like so:</p>
<pre><code>result = Name.objects.filter(name__iregex=r'(name1|name2|name3)')
</code></pre>
<p>or even:</p>
<pre><code>a = ['name1', 'name2', 'name3']
result = Name.objects.filter(name__iregex=r'(' + '|'.join(a) + ')')
</code></pre>
<p>Note that if a can contain characters that are special in a regex, you need to <a href="http://docs.python.org/2/library/re.html#re.escape" rel="noreferrer">escape</a> them properly.</p>
<p>NEWS: In Django 1.7+ it is possible to create your own lookups, so you can actually use <code>filter(name__iin=['name1', 'name2', 'name3'])</code> after proper initialization. See <a href="https://docs.djangoproject.com/en/3.0/ref/models/lookups/" rel="noreferrer">documentation reference for details</a>.</p> |
2,453,951 | C# Double - ToString() formatting with two decimal places but no rounding | <p>How do I format a <code>Double</code> to a <code>String</code> in C# so as to have only two decimal places? </p>
<p>If I use <code>String.Format("{0:0.00}%", myDoubleValue)</code> the number is then rounded and I want a simple truncate without any rounding. I also want the conversion to <code>String</code> to be culture sensitive.</p> | 2,453,982 | 15 | 3 | null | 2010-03-16 11:40:21.157 UTC | 27 | 2021-08-27 01:29:14.44 UTC | 2011-02-28 17:56:21 UTC | null | 103,385 | null | 1,360 | null | 1 | 194 | c#|string|double | 492,055 | <p>I use the following:</p>
<pre><code>double x = Math.Truncate(myDoubleValue * 100) / 100;
</code></pre>
<p>For instance:</p>
<p>If the number is 50.947563 and you use the following, the following will happen:</p>
<pre><code>- Math.Truncate(50.947563 * 100) / 100;
- Math.Truncate(5094.7563) / 100;
- 5094 / 100
- 50.94
</code></pre>
<p>And there's your answer truncated, now to format the string simply do the following:</p>
<pre><code>string s = string.Format("{0:N2}%", x); // No fear of rounding and takes the default number format
</code></pre> |
45,592,581 | Cannot debug in VS Code by attaching to Chrome | <p>I have default config in launch.json. The site runs on port 8080.</p>
<pre class="lang-json prettyprint-override"><code>{
"version": "0.2.0",
"configurations": [
{
"type": "chrome",
"request": "launch",
"name": "Launch Chrome against localhost",
"url": "http://localhost:8080",
"webRoot": "${workspaceRoot}"
},
{
"type": "chrome",
"request": "attach",
"name": "Attach to Chrome",
"port": 9222,
"webRoot": "${workspaceRoot}"
}
]
}
</code></pre>
<p><a href="https://i.stack.imgur.com/fn1qO.png" rel="noreferrer"><img src="https://i.stack.imgur.com/fn1qO.png" alt="enter image description here" /></a></p>
<p>However, when I click on the Debug button, I get this error:</p>
<blockquote>
<p>Cannot connect to the target: connect ECONNREFUSED 127.0.0.1:9222</p>
</blockquote>
<p><a href="https://i.stack.imgur.com/1HNWA.png" rel="noreferrer"><img src="https://i.stack.imgur.com/1HNWA.png" alt="enter image description here" /></a></p>
<p><strong>Question 1: Why does VS Code assign port 9222 when creating this json?</strong></p>
<p>What is so special about this port that MS decided to put it in this launch.json?</p>
<p><strong>Question 2: What do I need to change to make things work?</strong></p>
<p>The Launch debug always launches a new window.
I am asking <strong>specifically about Attach debug option</strong>, so that it will open in a new tab instead.</p> | 45,596,306 | 9 | 1 | null | 2017-08-09 13:47:48.04 UTC | 26 | 2022-07-18 20:11:33.397 UTC | 2020-11-26 00:48:29.107 UTC | null | 1,402,846 | null | 610,422 | null | 1 | 75 | visual-studio-code | 102,914 | <ol>
<li><p>You need to install Debugger for Chrome extension for this to work. Open extensions in VS Code and search for Debugger for Chrome</p></li>
<li><p>You need to run a web server on the URL specified in the first configuration (default to <a href="http://localhost:8080" rel="noreferrer">http://localhost:8080</a>). I use <code>serve</code> npm package that I installed globally. From my app folder I run <code>serve -p 8080</code></p></li>
<li><p>Select Launch Chrome against localhost option. It will launch the browser and you can set breakpoints in your code and the debugging should work.</p></li>
</ol>
<p>Regarding the second configuration (Attach to Chrome). There's nothing special about the port. In order to attach to Chrome you need to run Chrome with remote debugging enabled on port specified in the config. For example <code>chrome.exe --remote-debugging-port=9222</code>. I personally never use this options. Just follow the three steps above and you should be fine.</p> |
42,556,835 | Show values on top of bars in chart.js | <p>Please refer this Fiddle : <a href="https://jsfiddle.net/4mxhogmd/1/" rel="noreferrer">https://jsfiddle.net/4mxhogmd/1/</a></p>
<p>I am working on chart.js
If you see in fiddle, you will notice that value which is top on bar is not properly displayed in some cases(goes outside the canvas)
While research I came across this link <a href="https://stackoverflow.com/questions/31631354/how-to-display-data-values-on-chart-js">how to display data values on Chart.js</a></p>
<p>But here they used tooltip also for same cases to the text tweak inside of bars.
I don't want this.</p>
<pre><code>var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["2 Jan", "9 Jan", "16 Jan", "23 Jan", "30 Jan", "6 Feb", "13 Feb"],
datasets: [{
data: [6, 87, 56, 15, 88, 60, 12],
backgroundColor: "#4082c4"
}]
},
options: {
"hover": {
"animationDuration": 0
},
"animation": {
"duration": 1,
"onComplete": function () {
var chartInstance = this.chart,
ctx = chartInstance.ctx;
ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontSize, Chart.defaults.global.defaultFontStyle, Chart.defaults.global.defaultFontFamily);
ctx.textAlign = 'center';
ctx.textBaseline = 'bottom';
this.data.datasets.forEach(function (dataset, i) {
var meta = chartInstance.controller.getDatasetMeta(i);
meta.data.forEach(function (bar, index) {
var data = dataset.data[index];
ctx.fillText(data, bar._model.x, bar._model.y - 5);
});
});
}
},
legend: {
"display": false
},
tooltips: {
"enabled": false
},
scales: {
yAxes: [{
display: false,
gridLines: {
display : false
},
ticks: {
display: false,
beginAtZero:true
}
}],
xAxes: [{
gridLines: {
display : false
},
ticks: {
beginAtZero:true
}
}]
}
}
});
</code></pre>
<p>What I want is to show value on top only, for all cases.</p> | 42,558,204 | 8 | 1 | null | 2017-03-02 13:30:00.02 UTC | 22 | 2022-06-23 21:40:45.94 UTC | 2017-05-23 12:02:51.35 UTC | null | -1 | null | 3,916,831 | null | 1 | 43 | javascript|charts|chart.js | 133,376 | <p>I pulled out the data from being defined inside of myChart that way I could pull out the max value from the dataset. Then inside of the yAxes you can set the max ticks to be the max value + 10 from your data set. This ensures that the top bars in the graph will not go off the edge of the canvas and not display their value.</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>var ctx = document.getElementById("myChart");
debugger;
var data = {
labels: ["2 Jan", "9 Jan", "16 Jan", "23 Jan", "30 Jan", "6 Feb", "13 Feb"],
datasets: [{
data: [150, 87, 56, 50, 88, 60, 45],
backgroundColor: "#4082c4"
}]
}
var myChart = new Chart(ctx, {
type: 'bar',
data: data,
options: {
"hover": {
"animationDuration": 0
},
"animation": {
"duration": 1,
"onComplete": function() {
var chartInstance = this.chart,
ctx = chartInstance.ctx;
ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontSize, Chart.defaults.global.defaultFontStyle, Chart.defaults.global.defaultFontFamily);
ctx.textAlign = 'center';
ctx.textBaseline = 'bottom';
this.data.datasets.forEach(function(dataset, i) {
var meta = chartInstance.controller.getDatasetMeta(i);
meta.data.forEach(function(bar, index) {
var data = dataset.data[index];
ctx.fillText(data, bar._model.x, bar._model.y - 5);
});
});
}
},
legend: {
"display": false
},
tooltips: {
"enabled": false
},
scales: {
yAxes: [{
display: false,
gridLines: {
display: false
},
ticks: {
max: Math.max(...data.datasets[0].data) + 10,
display: false,
beginAtZero: true
}
}],
xAxes: [{
gridLines: {
display: false
},
ticks: {
beginAtZero: true
}
}]
}
}
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.bundle.js"></script>
<canvas id="myChart" width="100" height="100"></canvas></code></pre>
</div>
</div>
</p> |
10,311,413 | Storing application permissions in a database | <p>I'm developing an application for our company that eventually will have lots of ways of restricting users to particular sections/modules. While the application is still small, I'd like to move to a new method of storing permissions that, as the application grows, will remain easy to maintain and query.</p>
<p>Currently in our MySQL database we have a table called "user" which stores the user's ID, username and password. In a separate table called "user_acl" is the following:</p>
<pre><code>user_acl_id
acl_root
acl_news_read
acl_news_write
acl_news_modify
acl_reports_read
acl_reports_write
acl_reports_modify
acl_users_read
acl_users_write
acl_users_modify
</code></pre>
<p>We only have 3 modules at the minute, but over time more will be created and permissions for each will need to be added.</p>
<p>Rather than create a column for each permission, is there any other way or storing this information?</p> | 10,311,479 | 4 | 0 | null | 2012-04-25 07:43:26.097 UTC | 17 | 2021-05-17 19:04:11.047 UTC | null | null | null | null | 312,031 | null | 1 | 16 | php|mysql|arrays|permissions|store | 17,013 | <p>I would do it this way.</p>
<pre><code>table name: permission
columns: id, permission_name
</code></pre>
<p>and then I can assign multiple permissions to the user using a many to many relationship table</p>
<pre><code>table name: user_permission
columns: permission_id, user_id
</code></pre>
<p>This design will allow me to add as many permission as I want, and assign it to as many user as i want.</p>
<p>While the above design go with your requirement, I have my own method of implementing ACL in my application. I am posting it here.</p>
<p>My method of implementation of ACL goes like this:</p>
<ol>
<li>User will be assigned a role (Admin, guest, staff, public)</li>
<li>A role will have one or many permissions assigned to them (user_write, user_modify, report_read) etc.</li>
<li>Permission for the User will be inherited from the role to which he/she is</li>
<li>User can be assigned with manual permission apart from the permission inherited from role.</li>
</ol>
<p>To do this I have come up with the following database design.</p>
<pre><code>role
I store the role name here
+----------+
| Field |
+----------+
| id |
| role_name |
+----------+
permission:
I store the permission name and key here
Permission name is for displaying to user.
Permission key is for determining the permission.
+----------------+
| Field |
+----------------+
| id |
| permission_name |
| permission_key |
+----------------+
role_permission
I assign permission to role here
+---------------+
| Field |
+---------------+
| id |
| role_id |
| permission_id |
+---------------+
user_role
I assign role to the user here
+---------------+
| Field |
+---------------+
| id |
| user_id |
| role_id |
+---------------+
user_permission
I store the manual permission I may allow for the user here
+---------------+
| Field |
+---------------+
| id |
| user_id |
| permission_id |
+---------------+
</code></pre>
<p>This gives me more control over the ACL. I can allow superadmins to assign permission by themselves, and so on. As I said this is just to give you the idea.</p> |
5,913,424 | HG: Undo a commit from history | <p>I have a HG repository with revs 1, 2, 3, 4, 5 and 6. </p>
<p>When I committed rev 4, I unknowingly botched some changes in rev3 that I should not have. I did not notice this until rev 6 was already committed. </p>
<p>I need to undo changes in rev 4, but then re-apply all other changes after that. Basically undoing commit #4. How can I do that?</p> | 5,913,543 | 2 | 0 | null | 2011-05-06 15:15:07.643 UTC | 6 | 2018-02-22 10:21:57.54 UTC | null | null | null | null | 5,210 | null | 1 | 31 | mercurial|tortoisehg | 26,820 | <p>You want <a href="https://www.mercurial-scm.org/wiki/Backout" rel="noreferrer">hg backout</a></p>
<blockquote>
<p>Revert/undo the effect of an earlier <a href="https://www.mercurial-scm.org/wiki/ChangeSet" rel="noreferrer">changeset</a>...</p>
<p>Backout works by applying a changeset that's the opposite of the changeset to be backed out. That new changeset is committed to the <a href="https://www.mercurial-scm.org/wiki/Repository" rel="noreferrer">repository</a>, and eventually merged...</p>
</blockquote> |
19,545,370 | Android: how to hide ActionBar on certain activities | <p>I've developed a simple demo application with a splash screen a map and some regular screens.</p>
<p>I have an action bar at the top that contains a logo. It all looks fine on my phone (Galaxy s1 I9000 V2.3) but when i test it on Galaxy s2 v4 the action bar appears also in the splash screen and in the map screen.</p>
<p>The spalsh and map activity are not even inheriting from ActionBarActivity so how is that possible and how can i make it go away?</p>
<p>Manifest:</p>
<pre><code><application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:theme="@style/Theme.AppCompat.Light" >
<activity
android:name=".HomeActivity"
android:icon="@drawable/android_logo"
android:label=""
android:logo="@drawable/android_logo" >
<!--
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
-->
</activity>
<activity
android:name=".MapActivity"
android:label="" >
</activity>
<activity
android:name=".PackageActivity"
android:icon="@drawable/android_logo"
android:label=""
android:logo="@drawable/android_logo" >
</activity>
<activity
android:name=".SplashActivity"
android:label="" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</code></pre>
<p>MapActivity definition (it's a long one so i included just the definition):</p>
<pre><code>public class MapActivity extends FragmentActivity implements LocationListener
</code></pre>
<p>Splash Activity:</p>
<pre><code>import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
public class SplashActivity extends Activity{
private static final long SPLASH_DISPLAY_LENGTH = 2000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
new Handler().postDelayed(new Runnable(){
@Override
public void run() {
Intent mainIntent = new Intent(SplashActivity.this,HomeActivity.class);
SplashActivity.this.startActivity(mainIntent);
SplashActivity.this.finish();
}
}, SPLASH_DISPLAY_LENGTH);
}
}
</code></pre> | 19,545,450 | 20 | 0 | null | 2013-10-23 15:01:07.33 UTC | 35 | 2022-04-24 12:00:07.847 UTC | 2019-07-03 02:40:44.233 UTC | null | 2,581,314 | null | 812,303 | null | 1 | 125 | java|android|android-actionbar | 216,787 | <p>Apply the following in your Theme for the Activity in <code>AndroidManifest.xml</code>:</p>
<pre><code><activity android:name=".Activity"
android:label="@string/app_name"
android:theme="@android:style/Theme.NoTitleBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</code></pre> |
41,075,257 | Adding a wait-for-element while performing a SplashRequest in python Scrapy | <p>I am trying to scrape a few dynamic websites using Splash for Scrapy in python. However, I see that Splash fails to wait for the complete page to load in certain cases. A brute force way to tackle this problem was to add a large <code>wait</code> time (eg. 5 seconds in the below snippet). However, this is extremely inefficient and still fails to load certain data (sometimes it take longer than 5 seconds to load the content). Is there some sort of a wait-for-element condition that can be put through these requests?</p>
<pre><code>yield SplashRequest(
url,
self.parse,
args={'wait': 5},
'User-Agent':"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36",
}
)
</code></pre> | 41,098,381 | 3 | 0 | null | 2016-12-10 11:58:11.117 UTC | 8 | 2019-11-20 08:28:14.747 UTC | 2019-11-20 08:28:14.747 UTC | null | 939,364 | null | 3,810,057 | null | 1 | 15 | python|scrapy|wait|scrapy-splash|splash-js-render | 7,146 | <p>Yes, you can write a Lua script to do that. Something like that:</p>
<pre><code>function main(splash)
splash:set_user_agent(splash.args.ua)
assert(splash:go(splash.args.url))
-- requires Splash 2.3
while not splash:select('.my-element') do
splash:wait(0.1)
end
return {html=splash:html()}
end
</code></pre>
<p>Before Splash 2.3 you can use <code>splash:evaljs('!document.querySelector(".my-element")')</code> instead of <code>not splash:select('.my-element')</code>.</p>
<p>Save this script to a variable (<code>lua_script = """ ... """</code>). Then you can send a request like this:</p>
<pre><code>yield SplashRequest(
url,
self.parse,
endpoint='execute',
args={
'lua_source': lua_script,
'ua': "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36"
}
}
</code></pre>
<p>See scripting <a href="http://splash.readthedocs.io/en/stable/scripting-tutorial.html" rel="noreferrer">tutorial</a> and <a href="http://splash.readthedocs.io/en/stable/scripting-ref.html" rel="noreferrer">reference</a> for more details on how to write Splash Lua scripts.</p> |
47,132,158 | what happens after a broker is down in a cluster? | <p>Suppose a broker is down for long time, now what happens to the followers and leaders that this broker was containing?</p>
<ul>
<li><p>if broker was containing a leader and one of in-sync replica is chosen as leader, does it create another in-sync replica(in case we have specific replication factor)?</p></li>
<li><p>if broker was containing a follower, does it create another follower elsewhere in cluster?</p></li>
<li><p>now suppose broker awakens after long time, now do leaders and followers are restored as it left when it went down?</p></li>
</ul> | 47,135,485 | 1 | 0 | null | 2017-11-06 07:55:55.297 UTC | 11 | 2018-09-30 23:11:41.907 UTC | 2018-09-30 23:11:41.907 UTC | null | 2,308,683 | null | 8,837,757 | null | 1 | 15 | apache-kafka | 12,967 | <p>What happens when a broker is down depends on your configuration. It mostly depends on these configuration settings:</p>
<ul>
<li><code>min.insync.replicas</code></li>
<li><code>default.replication.factor</code></li>
<li><code>unclean.leader.election.enable</code></li>
</ul>
<p>Kafka does not create a new replica when a broker goes down.</p>
<p>If the offline broker was a leader, a new leader is elected from the replicas that are in-sync. If no replicas are in-sync it will only elect an out of sync replica if <code>unclean.leader.election.enable</code> is true, otherwise the partition will be offline.</p>
<p>If the offline broker was a follower, it will be marked a out of sync by the leader.</p>
<p>When restarting the broker, it will try to get back in sync. Once done, whether it stays a follower or becomes the leader depends if it is the prefered replica.</p>
<p>Finally if you know a broker will be offline for a long time and still require a replica, you can use the reassignment tool <code>kafka-reassign-partitions.sh</code> to move partitions to online brokers.</p> |
18,186,878 | invalid use of template name without an argument list | <p>I am facing a problem with my linked list class, I have created the interface and implementation files of the class, but when I build it, this error occurs: "invalid use of template name 'LinkedList' without an argument list".
here's my interface file:</p>
<pre><code>#ifndef LINKEDLIST_H
#define LINKEDLIST_H
template <typename T>
struct Node{
T info;
Node<T> *next;
};
template <typename T>
class LinkedList
{
Node<T> *start;
Node<T> *current;
public:
LinkedList();
~LinkedList();
};
#endif // LINKEDLIST_H
</code></pre>
<p>and this is my implementation code:</p>
<pre><code>#include "LinkedList.h"
LinkedList::LinkedList()
{
start = nullptr;
current = nullptr;
}
LinkedList::~LinkedList()
{
}
</code></pre> | 18,186,928 | 1 | 1 | null | 2013-08-12 12:22:34.407 UTC | 10 | 2017-03-05 14:00:56.723 UTC | 2017-03-05 14:00:56.723 UTC | null | 1,033,581 | null | 2,674,860 | null | 1 | 40 | c++|templates|data-structures|linked-list | 100,446 | <p>Write it like this:</p>
<pre><code>template<typename T>
LinkedList<T>::LinkedList()
{
start = nullptr;
current = nullptr;
}
</code></pre>
<p>And similarly for other member functions. But you'll run into another problem - declarations and definitions of a template <a href="https://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file">can't be separated</a> to different files.</p> |
46,885,008 | I just installed Angular Material and Angular Animations in my project and got these errors | <p>I just ran the code: <code>npm install --save @angular/material @angular/animations</code></p>
<p>This is my package.json</p>
<pre><code>{
"name": "cerpnew",
"version": "0.0.0",
"license": "MIT",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
"private": true,
"dependencies": {
"@angular/animations": "^4.4.6",
"@angular/common": "^4.2.4",
"@angular/compiler": "^4.2.4",
"@angular/core": "^4.2.4",
"@angular/forms": "^4.2.4",
"@angular/http": "^4.2.4",
"@angular/material": "^2.0.0-beta.12",
"@angular/platform-browser": "^4.2.4",
"@angular/platform-browser-dynamic": "^4.2.4",
"@angular/router": "^4.2.4",
"@types/angular-material": "^1.1.54",
"angular-2-dropdown-multiselect": "^1.6.0",
"angular-2-local-storage": "^1.0.1",
"bootstrap": "^3.3.7",
"bootstrap-select": "^1.12.4",
"core-js": "^2.4.1",
"jquery": "^3.2.1",
"ng-checkbox": "^1.0.2",
"ng2-bootstrap-modal": "^1.0.1",
"ng2-daterangepicker": "^2.0.10",
"react-datepicker": "^0.55.0",
"rxjs": "^5.4.2",
"select-picker": "^0.3.1",
"sweetalert": "^2.0.5",
"zone.js": "^0.8.14"
},
"devDependencies": {
"@angular/cli": "1.4.5",
"@angular/compiler-cli": "^4.2.4",
"@angular/language-service": "^4.2.4",
"@types/jasmine": "~2.5.53",
"@types/jasminewd2": "~2.0.2",
"@types/jquery": "^3.2.13",
"@types/node": "~6.0.60",
"codelyzer": "~3.2.0",
"jasmine-core": "~2.6.2",
"jasmine-spec-reporter": "~4.1.0",
"karma": "~1.7.0",
"karma-chrome-launcher": "~2.1.1",
"karma-cli": "~1.0.1",
"karma-coverage-istanbul-reporter": "^1.2.1",
"karma-jasmine": "~1.1.0",
"karma-jasmine-html-reporter": "^0.2.2",
"protractor": "~5.1.2",
"ts-node": "~3.2.0",
"tslint": "~5.7.0",
"typescript": "~2.3.3"
}
}
</code></pre>
<p>When running <code>ng serve</code> I get the following errors.</p>
<blockquote>
<p>ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/select/typings/select.d.ts
(9,32): Cannot find module '@angular/cdk/bidi'. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/core/typings/ripple/ripple-renderer.d.ts
(9,26): Cannot find module '@angular/ cdk/platform'. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/autocomplete/typings/autocomplete.d.ts
(10,44): Cannot find module '@angular/c dk/a11y'. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/autocomplete/typings/autocomplete-trigger.d.ts
(8,32): Cannot find module '@an gular/cdk/bidi'. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/autocomplete/typings/autocomplete-trigger.d.ts
(9,67): Cannot find module '@an gular/cdk/overlay'. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/button/typings/button.d.ts
(9,26): Cannot find module '@angular/cdk/platform'.</p>
<p>ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/button/typings/button.d.ts
(11,30): Cannot find module '@angular/cdk/a11y'. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/button-toggle/typings/button-toggle.d.ts
(11,30): Cannot find module '@angular /cdk/a11y'. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/button-toggle/typings/button-toggle.d.ts
(12,43): Cannot find module '@angular /cdk/collections'. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/checkbox/typings/checkbox.d.ts
(4,30): Cannot find module '@angular/cdk/a11y'.</p>
<p>ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/chips/typings/chip.d.ts
(8,33): Cannot find module '@angular/cdk/a11y'. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/chips/typings/chip-list.d.ts
(8,33): Cannot find module '@angular/cdk/a11y'. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/chips/typings/chip-list.d.ts
(9,32): Cannot find module '@angular/cdk/bidi'. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/chips/typings/chip-list.d.ts
(10,32): Cannot find module '@angular/cdk/collect ions'. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/dialog/typings/dialog-config.d.ts
(9,27): Cannot find module '@angular/cdk/bid i'. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/dialog/typings/dialog-container.d.ts
(10,86): Cannot find module '@angular/cdk /portal'. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/dialog/typings/dialog-container.d.ts
(11,34): Cannot find module '@angular/cdk /a11y'. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/dialog/typings/dialog-ref.d.ts
(8,28): Cannot find module '@angular/cdk/overla y'. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/dialog/typings/dialog.d.ts
(1,62): Cannot find module '@angular/cdk/overlay'. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/dialog/typings/dialog.d.ts
(2,31): Cannot find module '@angular/cdk/portal'. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/datepicker/typings/datepicker.d.ts
(8,32): Cannot find module '@angular/cdk/bi di'. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/datepicker/typings/datepicker.d.ts
(9,67): Cannot find module '@angular/cdk/ov erlay'. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/expansion/typings/accordion-item.d.ts
(9,43): Cannot find module '@angular/cdk /collections'. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/expansion/typings/expansion-panel.d.ts
(2,43): Cannot find module '@angular/cd k/collections'. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/expansion/typings/expansion-panel-header.d.ts
(1,30): Cannot find module '@ang ular/cdk/a11y'. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/grid-list/typings/grid-list.d.ts
(10,32): Cannot find module '@angular/cdk/bid i'. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/input/typings/autosize.d.ts
(9,26): Cannot find module '@angular/cdk/platform' . ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/input/typings/input.d.ts
(10,26): Cannot find module '@angular/cdk/platform'. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/list/typings/selection-list.d.ts
(8,50): Cannot find module '@angular/cdk/a11y '. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/list/typings/selection-list.d.ts
(9,32): Cannot find module '@angular/cdk/coll ections'. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/menu/typings/menu-item.d.ts
(8,33): Cannot find module '@angular/cdk/a11y'. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/menu/typings/menu-panel.d.ts
(10,27): Cannot find module '@angular/cdk/bidi'. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/menu/typings/menu-directive.d.ts
(9,27): Cannot find module '@angular/cdk/bidi '. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/menu/typings/menu-trigger.d.ts
(1,43): Cannot find module '@angular/cdk/bidi'.</p>
<p>ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/menu/typings/menu-trigger.d.ts
(2,67): Cannot find module '@angular/cdk/overla y'. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/progress-spinner/typings/progress-spinner.d.ts
(10,26): Cannot find module '@a ngular/cdk/platform'. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/radio/typings/radio.d.ts
(11,43): Cannot find module '@angular/cdk/collections '. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/radio/typings/radio.d.ts
(12,30): Cannot find module '@angular/cdk/a11y'. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/select/typings/select.d.ts
(8,44): Cannot find module '@angular/cdk/a11y'. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/core/typings/ripple/ripple.d.ts
(9,26): Cannot find module '@angular/cdk/platf orm'. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/select/typings/select.d.ts
(10,32): Cannot find module '@angular/cdk/collectio ns'. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/select/typings/select.d.ts
(11,109): Cannot find module '@angular/cdk/overlay' . ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/sidenav/typings/drawer.d.ts
(9,34): Cannot find module '@angular/cdk/a11y'. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/sidenav/typings/drawer.d.ts
(10,32): Cannot find module '@angular/cdk/bidi'. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/slide-toggle/typings/slide-toggle.d.ts
(9,26): Cannot find module '@angular/cd k/platform'. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/slide-toggle/typings/slide-toggle.d.ts
(12,30): Cannot find module '@angular/c dk/a11y'. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/slider/typings/slider.d.ts
(8,32): Cannot find module '@angular/cdk/bidi'. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/slider/typings/slider.d.ts
(12,30): Cannot find module '@angular/cdk/a11y'. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/snack-bar/typings/snack-bar-config.d.ts
(9,36): Cannot find module '@angular/c dk/a11y'. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/snack-bar/typings/snack-bar-config.d.ts
(10,27): Cannot find module '@angular/ cdk/bidi'. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/snack-bar/typings/snack-bar-container.d.ts
(10,70): Cannot find module '@angul ar/cdk/portal'. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/snack-bar/typings/snack-bar-ref.d.ts
(8,28): Cannot find module '@angular/cdk/ overlay'. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/snack-bar/typings/snack-bar.d.ts
(8,31): Cannot find module '@angular/cdk/a11y '. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/snack-bar/typings/snack-bar.d.ts
(9,25): Cannot find module '@angular/cdk/over lay'. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/snack-bar/typings/snack-bar.d.ts
(10,31): Cannot find module '@angular/cdk/por tal'. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/sort/typings/sort-header.d.ts
(9,30): Cannot find module '@angular/cdk/table'.</p>
<p>ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/stepper/typings/step-label.d.ts
(9,30): Cannot find module '@angular/cdk/stepp er'. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/stepper/typings/stepper.d.ts
(1,37): Cannot find module '@angular/cdk/stepper' . ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/stepper/typings/stepper-button.d.ts
(1,52): Cannot find module '@angular/cdk/s tepper'. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/stepper/typings/step-header.d.ts
(8,30): Cannot find module '@angular/cdk/a11y '. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/table/typings/cell.d.ts
(9,84): Cannot find module '@angular/cdk/table'. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/table/typings/table.d.ts
(1,26): Cannot find module '@angular/cdk/table'. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/table/typings/row.d.ts
(1,66): Cannot find module '@angular/cdk/table'. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/tabs/typings/tab-label.d.ts
(9,41): Cannot find module '@angular/cdk/portal'. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/tabs/typings/tab.d.ts
(8,32): Cannot find module '@angular/cdk/portal'. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/tabs/typings/tab-body.d.ts
(10,53): Cannot find module '@angular/cdk/portal'. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/tabs/typings/tab-body.d.ts
(11,43): Cannot find module '@angular/cdk/bidi'. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/tabs/typings/tab-header.d.ts
(8,43): Cannot find module '@angular/cdk/bidi'. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/tabs/typings/tab-header.d.ts
(13,31): Cannot find module '@angular/cdk/scrolli ng'. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/tabs/typings/tab-nav-bar/tab-nav-bar.d.ts
(8,32): Cannot find module '@angular /cdk/bidi'. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/tabs/typings/tab-nav-bar/tab-nav-bar.d.ts
(9,26): Cannot find module '@angular /cdk/platform'. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/tabs/typings/tab-nav-bar/tab-nav-bar.d.ts
(10,31): Cannot find module '@angula r/cdk/scrolling'. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/tooltip/typings/tooltip.d.ts
(9,31): Cannot find module '@angular/cdk/a11y'. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/tooltip/typings/tooltip.d.ts
(10,32): Cannot find module '@angular/cdk/bidi'. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/tooltip/typings/tooltip.d.ts
(11,156): Cannot find module '@angular/cdk/overla y'. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/tooltip/typings/tooltip.d.ts
(12,26): Cannot find module '@angular/cdk/platfor m'. ERROR in
E:/angular2/CERPNEW/node_modules/@angular/material/tooltip/typings/tooltip.d.ts
(13,34): Cannot find module '@angular/cdk/scrolli ng'. ERROR in Error:
Error encountered resolving symbol values statically. Could not
resolve @angular/cdk/observers relative to E:/angular2/CER
PNEW/node_modules/@angular/material/checkbox/typings/index.d.ts.,
resolving symbol MatCheckboxModule in
E:/angular2/CERPNEW/node_modules/@
angular/material/checkbox/typings/index.d.ts, resolving symbol
MatCheckboxModule in
E:/angular2/CERPNEW/node_modules/@angular/material/che
ckbox/typings/index.d.ts
at syntaxError (E:\angular2\CERPNEW\node_modules@angular\compiler\bundles\compiler.umd.js:1729:34)
at simplifyInContext (E:\angular2\CERPNEW\node_modules@angular\compiler\bundles\compiler.umd.js:25118:23)
at StaticReflector.simplify (E:\angular2\CERPNEW\node_modules@angular\compiler\bundles\compiler.umd.js:25130:13)
at StaticReflector.annotations (E:\angular2\CERPNEW\node_modules@angular\compiler\bundles\compiler.umd.js:24558:41)
at _getNgModuleMetadata (E:\angular2\CERPNEW\node_modules@angular\compiler-cli\src\ngtools_impl.js:138:31)
at _extractLazyRoutesFromStaticModule (E:\angular2\CERPNEW\node_modules@angular\compiler-cli\src\ngtools_impl.js:109:26)
at E:\angular2\CERPNEW\node_modules@angular\compiler-cli\src\ngtools_impl.js:129:27
at Array.reduce ()
at _extractLazyRoutesFromStaticModule (E:\angular2\CERPNEW\node_modules@angular\compiler-cli\src\ngtools_impl.js:128:10)
at Object.listLazyRoutesOfModule (E:\angular2\CERPNEW\node_modules@angular\compiler-cli\src\ngtools_impl.js:53:22)
at Function.NgTools_InternalApi_NG_2.listLazyRoutes (E:\angular2\CERPNEW\node_modules@angular\compiler-cli\src\ngtools_api.js:91:39)
at AotPlugin._getLazyRoutesFromNgtools (E:\angular2\CERPNEW\node_modules@ngtools\webpack\src\plugin.js:207:44)
at _donePromise.Promise.resolve.then.then.then.then.then (E:\angular2\CERPNEW\node_modules@ngtools\webpack\src\plugin.js:443:24)
at
at process._tickCallback (internal/process/next_tick.js:188:7)</p>
</blockquote> | 46,885,041 | 7 | 1 | null | 2017-10-23 08:33:28.427 UTC | 9 | 2022-07-15 11:35:57.413 UTC | 2022-07-15 11:35:57.413 UTC | null | 8,343,610 | null | 8,542,004 | null | 1 | 41 | angular|angular-material | 87,385 | <p>you should install neccessary <em>@angular/cdk</em> library to correct use of the newest @angular/material. </p>
<p>You can do this by command:</p>
<pre><code>npm install --save @angular/material @angular/cdk
</code></pre> |
8,952,476 | Detect if CGPoint within polygon | <p>I have a set of CGPoints which make up a polygon shape, how can I detect if a single CGPoint is inside or outside of the polygon?</p>
<p>Say, the shape was a triangle and the CGPoint was moving hoizontally, how could I detect when it crossed the triangle line?</p>
<p>I can use <code>CGRectContainsPoint</code> when the shape is a regular 4-sided shape but I can't see how I would do it with an odd shape.</p> | 8,952,499 | 4 | 0 | null | 2012-01-21 11:05:40.427 UTC | 9 | 2020-08-21 10:49:10.733 UTC | null | null | null | null | 290,796 | null | 1 | 21 | iphone|objective-c|ios|cocoa|quartz-graphics | 7,810 | <p>You can create a <code>CG(Mutable)PathRef</code> (or a <code>UIBezierPath</code> that wraps a <code>CGPathRef</code>) from your points and use the <a href="http://developer.apple.com/library/ios/documentation/graphicsimaging/Reference/CGPath/Reference/reference.html#//apple_ref/c/func/CGPathContainsPoint" rel="noreferrer"><code>CGPathContainsPoint</code></a> function to check if a point is inside that path. If you use <code>UIBezierPath</code>, you could also use the <code>containsPoint:</code> method.</p> |
55,306,893 | How to get current date and time in TypeScript | <p><strong>Summary</strong></p>
<p>I'm creating my first extension for VSCode in TypeScript, and want to create a new information message to display current date/time.</p>
<p><strong>What I've tried</strong></p>
<p>I've tried looking for some data/time keyword in the list of vscode key bindings. I've also tried looking for a function to get system date/time on Google only to come across solutions explaining data/time syntax and how to display a specific date/time but nothing to get the CURRENT data/time. I've also looked for it in vscode API documentation.</p>
<p><strong>Code part</strong></p>
<p>According to my understanding the code should be in <code>extension.ts</code> file in <code>activate</code> section where I register the command to implement <code>showInformationMessage</code> function call and send a string to it containing the date/time. So here is the code around the line where I store the current date/time:</p>
<pre class="lang-js prettyprint-override"><code>
let disposableShowTime = vscode.commands.registerCommand(
"extension.showTime",
() => {
// Display a message box to the user
let dateTime = "22 March, 2019 12:45PM"; // store current data/time instead
vscode.window.showInformationMessage("Current time: " + dateTime);
}
);
</code></pre>
<p><strong>Desired output</strong>: <code>[Current Date/Time]</code></p>
<p><strong>Actual output</strong>: <code>22 March, 2019 12:45PM</code></p> | 55,307,111 | 3 | 0 | null | 2019-03-22 19:50:10.203 UTC | 1 | 2021-04-30 07:22:38.89 UTC | 2019-12-16 07:21:04.463 UTC | null | 10,684,507 | null | 2,333,630 | null | 1 | 43 | typescript | 118,226 | <p>To retrieve the current system Date/Time in javaScript/TypeScript you need to create a new <code>Date</code> object using parameterless constructor, like this:</p>
<pre><code>let dateTime = new Date()
</code></pre> |
23,718,236 | python flask browsing through directory with files | <p>Is it possible to use flask to browse through a directory with files?</p>
<p>My code never seems to work correctly as weird appending between strings happens.</p>
<p>Also I don`t know how to implement a kind of check whether the path is a file or a folder.</p>
<p>Here is my Flask app.route:</p>
<pre><code>@app.route('/files', defaults={'folder': None,'sub_folder': None}, methods=['GET'])
@app.route('/files/<folder>', defaults={'sub_folder': None}, methods=['GET'])
@app.route('/files/<folder>/<sub_folder>', methods=['GET'])
def files(folder,sub_folder):
basedir = 'files/'
directory = ''
if folder != None:
directory = directory + '/' + folder
if sub_folder != None:
directory = directory + '/' + sub_folder
files = os.listdir(basedir + directory)
return render_template('files.html',files=files,directory=basedir + directory,currdir=directory)
</code></pre>
<p>and here is my html template, if anyone could give me some pointers it would be greatly appreciated!</p>
<pre><code><body>
<h2>Files {{ currdir }}</h2> </br>
{% for name in files: %}
<A HREF="{{ directory }}{{ name }}">{{ name }}</A> </br></br>
{% endfor %}
</body>s.html',files=files,directory=basedir + directory,currdir=directory)
</code></pre> | 23,724,948 | 3 | 0 | null | 2014-05-18 03:19:00.237 UTC | 11 | 2021-10-23 22:14:15.55 UTC | null | null | null | user2882307 | null | null | 1 | 20 | python|flask | 44,116 | <p>A <code>path</code> converter (<a href="http://flask.pocoo.org/docs/quickstart/#variable-rules" rel="noreferrer">docs</a> link) in the url structure is better than hardcoding all the different possible path structures.</p>
<p><code>os.path.exists</code> can be used to check if the path is valid and <code>os.path.isfile</code> and <code>os.path.isdir</code> for checking if the path is a file or a directory, respectively.</p>
<p>Endpoint:</p>
<pre><code>@app.route('/', defaults={'req_path': ''})
@app.route('/<path:req_path>')
def dir_listing(req_path):
BASE_DIR = '/Users/vivek/Desktop'
# Joining the base and the requested path
abs_path = os.path.join(BASE_DIR, req_path)
# Return 404 if path doesn't exist
if not os.path.exists(abs_path):
return abort(404)
# Check if path is a file and serve
if os.path.isfile(abs_path):
return send_file(abs_path)
# Show directory contents
files = os.listdir(abs_path)
return render_template('files.html', files=files)
</code></pre>
<p>Template (Now with directory browsing :) ):</p>
<pre><code><ul>
{% for file in files %}
<li>
<a href="{{ (request.path + '/' if request.path != '/' else '') + file }}">
{{ (request.path + '/' if request.path != '/' else '') + file }}
</a>
</li>
{% endfor %}
</ul>
</code></pre>
<p>Note: <code>abort</code> and <code>send_file</code> functions were imported from flask.</p> |
878,632 | Best Way to call external program in c# and parse output | <h3>Duplicate</h3>
<blockquote>
<p><a href="https://stackoverflow.com/questions/415620/redirect-console-output-to-textbox-in-separate-program-c">Redirect console output to textbox in separate program</a>
<a href="https://stackoverflow.com/questions/353601/capturing-nslookup-shell-output-with-c">Capturing nslookup shell output with C#</a></p>
</blockquote>
<p>I am looking to call an external program from within my c# code.</p>
<p>The program I am calling, lets say foo.exe returns about 12 lines of text.</p>
<p>I want to call the program and parse thru the output.</p>
<p>What is the most optimal way to do this ?</p>
<p>Code snippet also appreciated :)</p>
<p>Thank You very much.</p> | 878,660 | 1 | 1 | null | 2009-05-18 16:44:56.643 UTC | 12 | 2011-08-12 15:43:52.61 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | Tom | null | null | 1 | 25 | c#|.net | 54,902 | <pre><code>using System;
using System.Diagnostics;
public class RedirectingProcessOutput
{
public static void Main()
{
Process p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = "/c dir *.cs";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.Start();
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
Console.WriteLine("Output:");
Console.WriteLine(output);
}
}
</code></pre> |
19,704,950 | Load multiple certificates into PKCS12 with openssl | <p>I am trying to load multiple certificates using openssl into the PKCS12 format. The command is as follows:</p>
<pre><code>openssl pkcs12 -export -in cert1.arm -inkey cert1_private_key.pem -certfile cert2.arm -certfile cert3.arm -certfile RootCert.pem -name "Test" -out test.p12
</code></pre>
<p>Having parsed the generated PKCS12 file, only the last certificate has been included into the file:</p>
<pre><code>openssl pkcs12 -in test.p12 -info -nodes
</code></pre>
<p>I also tried to import them separately into the pkcs12 file while in all the attempts, only the last certificate was remained in the file.</p>
<p>Any idea where is the problem to solve it?</p> | 19,721,047 | 1 | 0 | null | 2013-10-31 11:13:30.413 UTC | 6 | 2017-01-11 01:23:33.063 UTC | 2014-12-01 12:32:35.113 UTC | null | 588,306 | null | 1,496,640 | null | 1 | 25 | openssl|x509certificate|pkcs#12 | 40,029 | <p>First, make sure all your certificates are in PEM format. Then, make a SINGLE file called "certs.pem" containing the rest of the certificates (cert2.arm, cert3.arm, and RootCert.pem). </p>
<p>Then use the command like this:</p>
<pre><code>openssl pkcs12 -export -in cert1.arm -inkey cert1_private_key.pem -certfile certs.pem -name "Test" -out test.p12
</code></pre>
<p>The <a href="https://www.openssl.org/docs/man1.0.1/apps/pkcs12.html" rel="noreferrer">openssl pkcs12</a> documentation explains the different options.</p> |
2,407,653 | jQuery AJAX type: 'GET', passing value problem | <p>I have a jQuery AJAX call with type:'GET' like this:</p>
<pre><code>$.ajax({type:'GET',url:'/createUser',data:"userId=12345&userName=test",
success:function(data){
alert('successful');
}
});
</code></pre>
<p>In my console output is:
GET:<a href="http://sample.com/createUser?userId=12345&userName=test" rel="nofollow noreferrer">http://sample.com/createUser?userId=12345&userName=test</a>
params: userId 12345
userName test</p>
<p>In my script i should get the value using $_GET['userId'] and $_GET['userName'] but i can't get the value passed in by ajax request using GET method.</p>
<p>Any ideas on how to do this?</p>
<p>thanks,</p> | 2,407,782 | 2 | 2 | null | 2010-03-09 08:49:29.213 UTC | 1 | 2012-06-07 14:15:49.147 UTC | 2010-03-09 09:15:06.887 UTC | null | 250,471 | null | 250,471 | null | 1 | 2 | php|jquery|ajax|get | 87,533 | <p>The only thing I can see wrong with the code (which no longer applies as the question has been edited (which suggests that the code has been rewritten for the question and might not accurately reflect the actual code in use)) is that the success function is in the wrong place.</p>
<p>You have:</p>
<pre><code>$.ajax(
{
type:'GET',
url:'/createUser',
data:"userId=12345&userName=test"
},
success: function(data){
alert('successful');
}
);
</code></pre>
<p>which should be:</p>
<pre><code>$.ajax(
{
type:'GET',
url:'/createUser',
data:"userId=12345&userName=test",
success: function(data){
alert('successful');
}
}
);
</code></pre>
<p>Despite this, your description of the console output suggests the data is being sent correctly. I'd try testing with this script to see what PHP actually returns (you can see the body of the response in the Firebug console):</p>
<pre><code><?php
header("Content-type: text/plain");
print_r($_REQUEST);
?>
</code></pre> |
33,203,689 | Switching on a generic type? | <p>Is it possible to switch on a generic type in Swift?</p>
<p>Here's an example of what I mean:</p>
<pre><code>func doSomething<T>(type: T.Type) {
switch type {
case String.Type:
// Do something
break;
case Int.Type:
// Do something
break;
default:
// Do something
break;
}
}
</code></pre>
<p>When trying to use the code above, I get the following errors:</p>
<pre class="lang-none prettyprint-override"><code>Binary operator '~=' cannot be applied to operands of type 'String.Type.Type' and 'T.Type'
Binary operator '~=' cannot be applied to operands of type 'Int.Type.Type' and 'T.Type'
</code></pre>
<p>Is there a way to switch on a type, or to achieve something similar? (calling a method with a generic and performing different actions depending on the type of the generic)</p> | 33,203,744 | 1 | 0 | null | 2015-10-18 21:52:18.273 UTC | 2 | 2015-10-18 22:05:17.53 UTC | null | null | null | null | 2,664,985 | null | 1 | 35 | swift|generics | 9,570 | <p>You need the <code>is</code> pattern:</p>
<pre><code>func doSomething<T>(type: T.Type) {
switch type {
case is String.Type:
print("It's a String")
case is Int.Type:
print("It's an Int")
default:
print("Wot?")
}
}
</code></pre>
<p>Note that the <code>break</code> statements are usually not needed, there is no
"default fallthrough" in Swift cases.</p> |
38,309,256 | Get column data by Column name and sheet name | <p>Is there a way to access all rows in a column in a specific sheet by using python xlrd. </p>
<p>e.g:</p>
<pre><code>workbook = xlrd.open_workbook('ESC data.xlsx', on_demand=True)
sheet = workbook.sheet['sheetname']
arrayofvalues = sheet['columnname']
</code></pre>
<p>Or do i have to create a dictionary by myself?</p>
<p>The excel is pretty big so i would love to avoid iterating over all the colnames/sheets </p> | 38,339,321 | 2 | 0 | null | 2016-07-11 14:17:44.037 UTC | 1 | 2016-07-12 21:40:30.243 UTC | null | null | null | null | 1,385,456 | null | 1 | 10 | python|excel|xlrd | 50,490 | <p>Yes, you are looking for the <code>col_values()</code> worksheet method. Instead of</p>
<pre><code>arrayofvalues = sheet['columnname']
</code></pre>
<p>you need to do</p>
<pre><code>arrayofvalues = sheet.col_values(columnindex)
</code></pre>
<p>where <code>columnindex</code> is the number of the column (counting from zero, so column A is index 0, column B is index 1, etc.). If you have a descriptive heading in the first row (or first few rows) you can give a second parameter that tells which row to start from (again, counting from zero). For example, if you have one header row, and thus want values starting in the second row, you could do</p>
<pre><code>arrayofvalues = sheet.col_values(columnindex, 1)
</code></pre>
<p>Please check out the <a href="https://github.com/python-excel/tutorial/raw/master/python-excel.pdf" rel="noreferrer">tutorial</a> for a reasonably readable discussion of the <code>xlrd</code> package. (The official <a href="http://xlrd.readthedocs.io/en/latest/" rel="noreferrer"><code>xlrd</code> documentation</a> is harder to read.)</p>
<p>Also note that (1) while you are free to use the name <code>arrayofvalues</code>, what you are really getting is a Python list, which technically isn't an array, and (2) the <code>on_demand</code> workbook parameter has no effect when working with .xlsx files, which means <code>xlrd</code> will attempt to load the entire workbook into memory regardless. (The <code>on_demand</code> feature works for .xls files.)</p> |
33,598,153 | Angular 2 - Whats the best way to store global variables like authentication token so all classes have access to them? | <p>Angular 2 question only:</p>
<p>Whats the best way to store global variables like authentication token or base url (environment settings) so that all classes can have access to them without loosing them on refresh?</p>
<p>So when I login I will give the user a auth token and normally store it in the $rootscope for angular 1.x.</p> | 33,603,587 | 4 | 1 | null | 2015-11-08 19:37:03.293 UTC | 10 | 2018-04-13 16:33:21.71 UTC | 2017-09-15 08:54:25.77 UTC | null | 5,765,795 | null | 1,590,389 | null | 1 | 19 | angular|typescript | 32,538 | <p>Well to create really global scope data you should register your class\object\value during the app bootstrapping as dependency parameter to the bootstrap function</p>
<p><code>bootstrap(MyApp,[MyGlobalService]);</code></p>
<p>This will register your service <code>MyGlobalService</code> (infact it can be a object or factory function or your own provider) at the root level. This dependency now can be injected into any component. </p>
<p>Unlike Angular1 there are multiple Injectors available for an Angular2 app, with one-to-one mapping between components and injectors. Each component has its own injector.</p>
<p>The Angular developer guide has some good example of such registrations. See the guide on <a href="https://angular.io/docs/ts/latest/guide/dependency-injection.html" rel="noreferrer">Dependency Injection</a>.</p>
<p>The other option has already been highlighted by @Yaniv. </p> |
22,964,272 | PostgreSQL Get a random datetime/timestamp between two datetime/timestamp | <p>The title is pretty much explicit, my question is if i get two dates with hour:</p>
<ul>
<li>01-10-2014 10:00:00</li>
<li>01-20-2014 20:00:00</li>
</ul>
<p>Is it possible to pick a random datetime between these two datetime ?</p>
<p>I tried with the random() function but i don't really get how to use it with datetime</p>
<p>Thanks</p>
<p>Matthiew</p> | 22,965,061 | 3 | 0 | null | 2014-04-09 13:35:46.823 UTC | 12 | 2018-09-22 18:14:13.61 UTC | null | null | null | null | 1,518,320 | null | 1 | 53 | sql|database|postgresql|datetime|timestamp | 36,880 | <p>You can do almost everything with the <a href="http://www.postgresql.org/docs/current/static/functions-datetime.html" rel="noreferrer">date/time operators</a>:</p>
<pre><code>select timestamp '2014-01-10 20:00:00' +
random() * (timestamp '2014-01-20 20:00:00' -
timestamp '2014-01-10 10:00:00')
</code></pre> |
1,822,047 | How to emit explicit interface implementation using reflection.emit? | <p>Observe the following simple source code:</p>
<pre><code>using System;
using System.Linq.Expressions;
using System.Reflection;
using System.Reflection.Emit;
namespace A
{
public static class Program
{
private const MethodAttributes ExplicitImplementation =
MethodAttributes.Private | MethodAttributes.Virtual | MethodAttributes.Final |
MethodAttributes.HideBySig | MethodAttributes.NewSlot;
private const MethodAttributes ImplicitImplementation =
MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig;
private static Type EmitMyIntfType(ModuleBuilder moduleBuilder)
{
var typeBuilder = moduleBuilder.DefineType("IMyInterface",
TypeAttributes.NotPublic | TypeAttributes.Interface | TypeAttributes.Abstract);
typeBuilder.DefineMethod("MyMethod", MethodAttributes.Assembly | MethodAttributes.Abstract |
MethodAttributes.Virtual | MethodAttributes.HideBySig | MethodAttributes.NewSlot,
typeof(void), new[] { typeof(int) });
return typeBuilder.CreateType();
}
public static void Main()
{
var assemblyName = new AssemblyName("DynamicTypesAssembly");
var assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave);
var moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName.Name, assemblyName.Name + ".dll", true);
var myIntfType = EmitMyIntfType(moduleBuilder);
var typeBuilder = moduleBuilder.DefineType("MyType",
TypeAttributes.Public | TypeAttributes.BeforeFieldInit | TypeAttributes.Serializable |
TypeAttributes.Sealed, typeof(object), new[] { myIntfType });
//var myMethodImpl = typeBuilder.DefineMethod("IMyInterface.MyMethod", ExplicitImplementation,
// null, new[] { typeof(int) });
var myMethodImpl = typeBuilder.DefineMethod("MyMethod", ImplicitImplementation,
null, new[] { typeof(int) });
var ilGenerator = myMethodImpl.GetILGenerator();
ilGenerator.Emit(OpCodes.Ret);
var type = typeBuilder.CreateType();
assemblyBuilder.Save("A.dll");
}
}
}
</code></pre>
<p>Below is the equivalent C# code obtained by decompiling the A.dll assembly using the Reflector:</p>
<pre><code>internal interface IMyInterface
{
void MyMethod(int);
}
[Serializable]
public sealed class MyType : IMyInterface
{
public override void MyMethod(int)
{
}
}
</code></pre>
<p>Now what if I wish the <code>MyType</code> type implement the <code>IMyInterface</code> interface explicitly?
So I take these lines:</p>
<pre><code>//var myMethodImpl = typeBuilder.DefineMethod("IMyInterface.MyMethod", ExplicitImplementation,
// null, new[] { typeof(int) });
var myMethodImpl = typeBuilder.DefineMethod("MyMethod", ImplicitImplementation,
null, new[] { typeof(int) });
</code></pre>
<p>and switch the comments to yield this code:</p>
<pre><code>var myMethodImpl = typeBuilder.DefineMethod("IMyInterface.MyMethod", ExplicitImplementation,
null, new[] { typeof(int) });
// var myMethodImpl = typeBuilder.DefineMethod("MyMethod", ImplicitImplementation,
// null, new[] { typeof(int) });
</code></pre>
<p>But now, the application fails to create the dynamic type. This line:</p>
<pre><code>var type = typeBuilder.CreateType();
</code></pre>
<p>throws the following exception:</p>
<pre><code>System.TypeLoadException was unhandled
Message="Method 'MyMethod' in type 'MyType' from assembly 'DynamicTypesAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' does not have an implementation."
Source="mscorlib"
TypeName="MyType"
StackTrace:
at System.Reflection.Emit.TypeBuilder._TermCreateClass(Int32 handle, Module module)
at System.Reflection.Emit.TypeBuilder.TermCreateClass(Int32 handle, Module module)
at System.Reflection.Emit.TypeBuilder.CreateTypeNoLock()
at System.Reflection.Emit.TypeBuilder.CreateType()
at A.Program.Main() in C:\Home\work\A\Program.cs:line 45
InnerException:
</code></pre>
<p>Can anyone show me what is wrong with my code?</p>
<p>Thanks.</p> | 1,822,169 | 1 | 0 | null | 2009-11-30 19:58:01.733 UTC | 7 | 2011-03-17 12:28:54.53 UTC | 2009-11-30 22:56:48.417 UTC | null | 2,351,099 | null | 80,002 | null | 1 | 29 | c#|.net|reflection|reflection.emit|explicit-implementation | 8,547 | <p>That seems duplicate to <a href="https://stackoverflow.com/questions/1773710/explicit-interface-implementation-and-reflection-emit">this question</a>...</p>
<p>Which <a href="http://msdn.microsoft.com/en-us/library/system.reflection.emit.typebuilder.definemethodoverride.aspx" rel="noreferrer">points to MSDN</a>:</p>
<blockquote>
<p>However, to provide a separate
implementation of I.M(), you must
define a method body and then use the
<code>DefineMethodOverride</code> method to
associate that method body with a
<code>MethodInfo</code> representing I.M(). The
name of the method body does not
matter.</p>
</blockquote>
<pre><code> // Build the method body for the explicit interface
// implementation. The name used for the method body
// can be anything. Here, it is the name of the method,
// qualified by the interface name.
//
MethodBuilder mbIM = tb.DefineMethod("I.M",
MethodAttributes.Private | MethodAttributes.HideBySig |
MethodAttributes.NewSlot | MethodAttributes.Virtual |
MethodAttributes.Final,
null,
Type.EmptyTypes);
ILGenerator il = mbIM.GetILGenerator();
il.Emit(OpCodes.Ldstr, "The I.M implementation of C");
il.Emit(OpCodes.Call, typeof(Console).GetMethod("WriteLine",
new Type[] { typeof(string) }));
il.Emit(OpCodes.Ret);
// DefineMethodOverride is used to associate the method
// body with the interface method that is being implemented.
//
tb.DefineMethodOverride(mbIM, typeof(I).GetMethod("M"));
</code></pre> |
19,208,901 | Best practice to authenticate 2 machines in a M2M environment | <p>I have multiple tiny Linux <em>embedded servers</em> on Beaglebone Black (could by a RaspberryPi, it makes no difference) that need to exchange information with a <em>main server</em> (hosted on the web). </p>
<p>Ideally, each system talks to each other by simple RESTful commands - for instance, the main server sends out new configurations to the embedded servers - and the servers send back data.
Commands could be also issued by a human user from the main server or directly to the embedded servers.</p>
<p><strong>What would it be the most "standard" way of authentication of each server against each other?</strong> I'm thinking OAuth, assuming that each machine has its own OAuth user - but I'm not sure if that is the correct pattern to follow.</p> | 21,623,530 | 2 | 0 | null | 2013-10-06 12:34:06.563 UTC | 11 | 2017-01-27 06:01:21.563 UTC | null | null | null | null | 273,567 | null | 1 | 19 | authentication|oauth | 13,358 | <blockquote>
<p>What would it be the most "standard" way of authentication of each server against each other? I'm thinking OAuth, assuming that each machine has its own OAuth user - but I'm not sure if that is the correct pattern to follow.</p>
</blockquote>
<p>Authenticating machines is no different than authenticating users. They are both security principals. In fact, Microsoft made machines a first-class citizen in Windows 2000. They can be a principal on securable objects like files and folders, just like regular users can.</p>
<p>(There is some hand waving since servers usually suffer from the Unattended Key Storage problem described by Gutmann in his <a href="http://www.cs.auckland.ac.nz/~pgut001/pubs/book.pdf" rel="noreferrer">Engineering Security</a> book).</p>
<p>I would use a private PKI (i.e., be my own Certification Authority) and utilize mutual authentication based on public/private key pairs like SSL/TLS. This has the added benefit of re-using a lot of infrastructure, so the HTTP/HTTPS/REST "just works" as it always has.</p>
<p>If you use a Private PKI, issue certificates for the machines that include the following key usage:</p>
<ul>
<li>Digital Signature (Key Usage)</li>
<li>Key Encipherment (Key Usage)</li>
<li>Key Agreement (Key Usage)</li>
<li>Web Client Authentication (Extended Key Usage)</li>
<li>Web Server Authentication (Extended Key Usage)</li>
</ul>
<p>Or, run a private PKI and only allow communications between servers using a VPN based on your PKI. You can still tunnel your RESTful requests, and no others will be able to establish a VPN to one of your servers. You get the IP filters for free.</p>
<p>Or use a Kerberos style protocol with a key distribution center. You'll need the entire Kerberos infrastructure, including a KDC. Set up secure channels based on the secrets proctored by the KDC.</p>
<p>Or, use a SSH-like system, public/private key pairs and sneaker-net to copy the peer's public keys to one another. Only allow connections from machines whose public keys you have.</p>
<p>I probably would not use an OAuth-like system. In the OAuth-like system, you're going to be both the Provider and Relying Party. In this case, you might as well be a CA and reuse everything from SSL/TLS.</p> |
27,370,768 | List all methods in COMobject | <p>Is it possible?</p>
<p>Something in the lines of :</p>
<pre><code>import win32com.client
ProgID = "someProgramID"
com_object = win32com.client.Dispatch(ProgID)
for methods in com_object:
print methods
</code></pre>
<p>I got the <code>com_object.__dict__</code>, which lists:</p>
<pre><code>[_oleobj_, _lazydata_, _olerepr_, _unicode_to_string_, _enum_, _username_, _mapCachedItems_, _builtMethods_]
</code></pre>
<p>Most are empty, except:</p>
<ul>
<li><code>_oleobj_</code> (PyIDispatch)</li>
<li><code>_lazydata_</code> (PyITypeInfo)</li>
<li><code>_olerepr_</code> (LazyDispatchItem instance)</li>
<li><code>_username_</code> (<code><unknown></code>)</li>
</ul>
<p>But I don't know how to access anything on those types.</p> | 27,371,403 | 3 | 0 | null | 2014-12-09 02:59:20.677 UTC | 10 | 2021-10-12 13:58:31.813 UTC | null | null | null | null | 3,014,930 | null | 1 | 16 | python|methods|win32com | 20,205 | <p>Just found how to get most of the methods:</p>
<p>Here's how:</p>
<pre><code>import win32com.client
import pythoncom
ProgID = "someProgramID"
com_object = win32com.client.Dispatch(ProgID)
for key in dir(com_object):
method = getattr(com_object,key)
if str(type(method)) == "<type 'instance'>":
print key
for sub_method in dir(method):
if not sub_method.startswith("_") and not "clsid" in sub_method.lower():
print "\t"+sub_method
else:
print "\t",method
</code></pre>
<p>Here's a exemple output with <code>ProgID = "Foobar2000.Application.0.7"</code></p>
<p>Output:</p>
<pre><code>Playlists
Add
GetSortedTracks
GetTracks
Item
Load
Move
Remove
Save
Name
foobar2000 v1.1.13
ApplicationPath
C:\Program Files (x86)\foobar2000\foobar2000.exe
MediaLibrary
GetSortedTracks
GetTracks
Rescan
Minimized
True
Playback
FormatTitle
FormatTitleEx
Next
Pause
Previous
Random
Seek
SeekRelative
Start
Stop
ProfilePath
file://C:\Users\user\AppData\Roaming\foobar2000
</code></pre> |
38,850,419 | How to create multi-color border with CSS? | <p>How to create multi-color border like image below?</p>
<p><a href="https://i.stack.imgur.com/kBXkA.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/kBXkA.jpg" alt="enter image description here"></a></p> | 38,850,580 | 4 | 3 | null | 2016-08-09 12:13:52.443 UTC | 20 | 2022-06-27 07:52:14.247 UTC | 2019-06-17 08:28:38.3 UTC | null | 8,620,333 | null | 1,897,577 | null | 1 | 35 | css|border|css-shapes | 54,191 | <p>You can do it with <code>:after</code> or <code>:before</code> psuedo element and css <code>linear-gradient</code> as shown below:</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>body {
background: #ccc;
}
.box {
text-align: center;
position: relative;
line-height: 100px;
background: #fff;
height: 100px;
width: 300px;
}
.box:after {
background: linear-gradient(to right, #bcbcbc 25%,#ffcd02 25%, #ffcd02 50%, #e84f47 50%, #e84f47 75%, #65c1ac 75%);
position: absolute;
content: '';
height: 4px;
right: 0;
left: 0;
top: 0;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box">Div</div></code></pre>
</div>
</div>
</p> |
34,631,300 | Why do I obtain this error when deploying app to Heroku? | <p>I am getting some kind of error when deploying my app to heroku using git hub. The problem is, I don't understand the heroku logs and the entailing errors. Here is the heroku log: </p>
<pre><code>Marcuss-MacBook-Pro:Weather-App marcushurney$ heroku logs
2016-01-05T14:37:27.798077+00:00 app[web.1]: npm ERR! Please include the following file with any support request:
2016-01-05T14:37:27.798377+00:00 app[web.1]: npm ERR! /app/npm-debug.log
2016-01-05T14:37:27.786949+00:00 app[web.1]: npm ERR! node v5.1.1
2016-01-05T14:37:27.786556+00:00 app[web.1]: npm ERR! argv "/app/.heroku/node/bin/node" "/app/.heroku/node/bin/npm" "start"
2016-01-05T14:37:27.787856+00:00 app[web.1]: npm ERR! npm v3.3.12
2016-01-05T14:37:28.776245+00:00 heroku[web.1]: Process exited with status 1
2016-01-05T14:37:28.789412+00:00 heroku[web.1]: State changed from starting to crashed
2016-01-05T17:27:16.684869+00:00 heroku[web.1]: State changed from crashed to starting
2016-01-05T17:27:17.853743+00:00 heroku[web.1]: Starting process with command `npm start`
2016-01-05T17:27:20.423495+00:00 app[web.1]: npm ERR! node v5.1.1
2016-01-05T17:27:20.423130+00:00 app[web.1]: npm ERR! argv "/app/.heroku/node/bin/node" "/app/.heroku/node/bin/npm" "start"
2016-01-05T17:27:20.424111+00:00 app[web.1]: npm ERR! npm v3.3.12
2016-01-05T17:27:20.425937+00:00 app[web.1]: npm ERR! missing script: start
2016-01-05T17:27:20.422441+00:00 app[web.1]: npm ERR! Linux 3.13.0-71-generic
2016-01-05T17:27:20.426242+00:00 app[web.1]: npm ERR!
2016-01-05T17:27:20.426432+00:00 app[web.1]: npm ERR! If you need help, you may report this error at:
2016-01-05T17:27:20.426634+00:00 app[web.1]: npm ERR! <https://github.com/npm/npm/issues>
</code></pre> | 34,637,534 | 7 | 0 | null | 2016-01-06 10:52:06.787 UTC | 14 | 2022-01-08 03:18:31.117 UTC | 2020-07-25 15:06:09.137 UTC | null | 13,884,549 | null | 5,264,835 | null | 1 | 29 | git|heroku|npm|npm-scripts|npm-start | 46,832 | <p>You have to inform heroku where to start : <code>missing script: start</code>. In your package.json, you should have something like <a href="https://devcenter.heroku.com/articles/nodejs-support#customizing-the-build-process" rel="noreferrer">this</a>: </p>
<pre><code>"scripts": {
"start": "node index.js"
}
</code></pre>
<p>Where <code>index.js</code> is your entry point.</p>
<p>As an <a href="https://devcenter.heroku.com/articles/nodejs-support#default-web-process-type" rel="noreferrer">alternative</a>, you can specify in <code>Procfile</code>:</p>
<pre><code>web: node index.js
</code></pre> |
24,451,684 | For Android Material support libraries, where can I find CardView and RecyclerView? | <p>I cannot find RecyclerView, Palette or CardView in the support libraries. Emulators responds with a "Class Not Found" error.</p>
<p>How can I fix an error like this?</p> | 24,451,685 | 1 | 0 | null | 2014-06-27 12:19:30.047 UTC | 9 | 2020-02-02 07:20:18.313 UTC | 2020-02-02 07:20:18.313 UTC | null | 6,782,707 | null | 742,188 | null | 1 | 27 | android|android-support-library | 18,125 | <p>You require these libraries in your build.gradle.</p>
<pre><code>compile 'com.android.support:cardview-v7:+'
compile 'com.android.support:recyclerview-v7:+'
compile 'com.android.support:palette-v7:+'
</code></pre>
<p>Source:
<a href="http://www.reddit.com/r/androiddev/comments/297xli/howto_use_the_v21_support_libs_on_older_versions/">http://www.reddit.com/r/androiddev/comments/297xli/howto_use_the_v21_support_libs_on_older_versions/</a></p> |
26,954,217 | How to implement first launch tutorial like Android Lollipop apps: Like Sheets, Slides app? | <p>I have Android 5.0 final build flashed in my Nexus 5. I noticed it has very beautiful, clean and elegant way of showing tutorial at first launch. Apps like "Sheets", "Slides" etc. </p>
<p>How can we implement that in our Android L compatible apps?</p>
<p>Also the app fades off the first launch screen and then shows the tutorial.</p>
<p><img src="https://i.stack.imgur.com/DqMcam.png" alt="Tutorial screen 1">
<img src="https://i.stack.imgur.com/djuf8m.png" alt="Initial screen which fades off and shows the tutorial"></p> | 33,204,139 | 7 | 1 | null | 2014-11-16 05:42:26.747 UTC | 44 | 2017-12-04 12:00:59.217 UTC | 2016-10-30 00:06:47.67 UTC | null | 4,583,267 | null | 3,011,841 | null | 1 | 54 | android|android-5.0-lollipop | 39,638 | <p>There is a pretty good library for emulating these first run tutorials:
<a href="https://github.com/PaoloRotolo/AppIntro" rel="noreferrer">https://github.com/PaoloRotolo/AppIntro</a></p>
<p><a href="https://i.stack.imgur.com/RXBtV.png" rel="noreferrer"><img src="https://i.stack.imgur.com/RXBtVm.png" alt="AppIntro example screenshot"></a></p>
<p><em>Click for larger image</em></p> |
53,984,725 | NetworkSecurityConfig: No Network Security Config specified, using platform default Error response code: 400 | <p>I'm trying to connect to either of these places and get the JSON data:-</p>
<pre><code>https://content.guardianapis.com/search?q=debate&tag=politics/politics&from-date=2014-01-01&api-key=test
https://content.guardianapis.com/search?q=debates&api-key=test
https://content.guardianapis.com/search?api-key=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx
</code></pre>
<p>All three I can get to via the browser, but when I try to access them via an android app I get the following errors:-</p>
<pre><code>NetworkSecurityConfig: No Network Security Config specified, using platform default
Error response code: 400
</code></pre>
<p>I've added this to manifest.xml:-</p>
<pre><code><uses-permission android:name="android.permission.INTERNET"/>
</code></pre>
<p>I also added this to the manifest.xml:-</p>
<pre><code>android:networkSecurityConfig="@xml/network_security_config"
</code></pre>
<p>And created res/xml/network_security_config.xml, which contains:-</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<domain-config>
<domain includeSubdomains="true">content.guardianapis.com</domain>>
</domain-config>
</code></pre>
<p>Which changes the error to:-</p>
<pre><code>D/NetworkSecurityConfig: Using Network Security Config from resource network_security_config debugBuild: true
Error response code: 400
</code></pre>
<p>I know it's missing:-</p>
<pre><code><trust-anchors>
<certificates src="@raw/my_ca"/>
</trust-anchors>
</code></pre>
<p>but I have no idea where or what the certificate would be or if it's needed.</p>
<p>Not really sure what is going on, any help would be appreciated.</p>
<p>IN ADDITION:-
I am able to connect fine and get the JSON from this URL:-</p>
<pre><code>https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&eventtype=earthquake&orderby=time&minmag=6&limit=10
</code></pre>
<p>All I get is this:-</p>
<pre><code>No Network Security Config specified, using platform default
</code></pre>
<p>Buy not error 400 and gets through with a 200 instead. So it makes me think there is something weird going on, but not sure where.</p> | 53,984,915 | 3 | 6 | null | 2018-12-31 07:24:24.573 UTC | 7 | 2021-07-20 12:30:50.097 UTC | 2020-08-11 04:25:21.017 UTC | null | 4,853,133 | null | 839,837 | null | 1 | 20 | java|android|asp.net-web-api|networking | 87,220 | <p>Try these solutions</p>
<blockquote>
<p><strong>Solution 1</strong>)</p>
</blockquote>
<p>Add the following attribute to the <code><application</code> tag in <code>AndroidManifest.xml</code>:</p>
<pre><code>android:usesCleartextTraffic="true"
</code></pre>
<blockquote>
<p><strong>Solution 2</strong>)</p>
</blockquote>
<p>Add <code>android:networkSecurityConfig="@xml/network_security_config"</code> to the <code><application</code> tag in <code>app/src/main/AndroidManifest.xml</code>:</p>
<pre><code><application
android:name=".ApplicationClass"
android:allowBackup="true"
android:hardwareAccelerated="false"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:largeHeap="true"
android:networkSecurityConfig="@xml/network_security_config"
android:supportsRtl="true"
android:theme="@style/AppTheme">
</code></pre>
<p>With a corresponding <code>network_security_config.xml</code> in <code>app/src/main/res/xml/</code>:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true" />
</network-security-config>
</code></pre>
<p><a href="https://i.stack.imgur.com/9Nhzi.png" rel="noreferrer"><img src="https://i.stack.imgur.com/9Nhzi.png" alt="enter image description here"></a></p>
<p>Refer this answer for more info:
<a href="https://stackoverflow.com/questions/53493077/files-are-not-downloading-on-android-pie-9-0-xiaomi-mi-a2-using-download-mange">Download Manger not working in Android Pie 9.0 (Xiaomi mi A2)</a></p> |
30,539,679 | Python: Read several json files from a folder | <p>I would like to know how to read several <code>json</code> files from a single folder (without specifying the files names, just that they are json files). </p>
<p>Also, it is possible to turn them into a <code>pandas</code> DataFrame?</p>
<p>Can you give me a basic example?</p> | 30,540,662 | 9 | 0 | null | 2015-05-29 21:54:33.457 UTC | 18 | 2022-06-07 07:05:16.487 UTC | 2015-05-29 22:16:02.59 UTC | null | 3,510,736 | null | 4,088,961 | null | 1 | 60 | python|json|pandas | 115,397 | <p>One option is listing all files in a directory with <a href="https://docs.python.org/2/library/os.html#os.listdir" rel="noreferrer">os.listdir</a> and then finding only those that end in '.json':</p>
<pre><code>import os, json
import pandas as pd
path_to_json = 'somedir/'
json_files = [pos_json for pos_json in os.listdir(path_to_json) if pos_json.endswith('.json')]
print(json_files) # for me this prints ['foo.json']
</code></pre>
<p>Now you can use pandas <a href="http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.from_dict.html" rel="noreferrer">DataFrame.from_dict</a> to read in the json (a python dictionary at this point) to a pandas dataframe:</p>
<pre><code>montreal_json = pd.DataFrame.from_dict(many_jsons[0])
print montreal_json['features'][0]['geometry']
</code></pre>
<p>Prints:</p>
<pre><code>{u'type': u'Point', u'coordinates': [-73.6051013, 45.5115944]}
</code></pre>
<p>In this case I had appended some jsons to a list <code>many_jsons</code>. The first json in my list is actually a <a href="http://geojson.org/" rel="noreferrer">geojson</a> with some geo data on Montreal. I'm familiar with the content already so I print out the 'geometry' which gives me the lon/lat of Montreal.</p>
<p>The following code sums up everything above:</p>
<pre><code>import os, json
import pandas as pd
# this finds our json files
path_to_json = 'json/'
json_files = [pos_json for pos_json in os.listdir(path_to_json) if pos_json.endswith('.json')]
# here I define my pandas Dataframe with the columns I want to get from the json
jsons_data = pd.DataFrame(columns=['country', 'city', 'long/lat'])
# we need both the json and an index number so use enumerate()
for index, js in enumerate(json_files):
with open(os.path.join(path_to_json, js)) as json_file:
json_text = json.load(json_file)
# here you need to know the layout of your json and each json has to have
# the same structure (obviously not the structure I have here)
country = json_text['features'][0]['properties']['country']
city = json_text['features'][0]['properties']['name']
lonlat = json_text['features'][0]['geometry']['coordinates']
# here I push a list of data into a pandas DataFrame at row given by 'index'
jsons_data.loc[index] = [country, city, lonlat]
# now that we have the pertinent json data in our DataFrame let's look at it
print(jsons_data)
</code></pre>
<p>for me this prints:</p>
<pre><code> country city long/lat
0 Canada Montreal city [-73.6051013, 45.5115944]
1 Canada Toronto [-79.3849008, 43.6529206]
</code></pre>
<p>It may be helpful to know that for this code I had two geojsons in a directory name 'json'. Each json had the following structure:</p>
<pre><code>{"features":
[{"properties":
{"osm_key":"boundary","extent":
[-73.9729016,45.7047897,-73.4734865,45.4100756],
"name":"Montreal city","state":"Quebec","osm_id":1634158,
"osm_type":"R","osm_value":"administrative","country":"Canada"},
"type":"Feature","geometry":
{"type":"Point","coordinates":
[-73.6051013,45.5115944]}}],
"type":"FeatureCollection"}
</code></pre> |
30,561,889 | readOGR() cannot open file | <pre><code>wmap <- readOGR(dsn="~/R/funwithR/data/ne_110m_land", layer="ne_110m_land")
</code></pre>
<p>This code is not loading the shape file and error is generated as</p>
<pre><code>Error in ogrInfo(dsn = dsn, layer = layer, encoding = encoding, use_iconv = use_iconv, :
Cannot open file
</code></pre>
<p>I am sure that the directory is correct one. At the end / is also not there and layer name is also correct.</p>
<p>Inside the ne_110m_land directory files I have are:</p>
<pre><code>ne_110m_land.dbf
ne_110m_land.prj
ne_110m_land.shp
ne_110m_land.shx
ne_110m_land.VERSION.txt
ne_110m_land.README.html
</code></pre> | 30,562,015 | 8 | 0 | null | 2015-05-31 19:41:04.75 UTC | 13 | 2021-09-12 17:00:38.87 UTC | 2018-12-16 09:22:16.983 UTC | null | 3,386,310 | null | 4,933,747 | null | 1 | 35 | r|gdal|rgdal|ogr | 83,928 | <p>You could have shown that you have the right path with:</p>
<pre><code>list.files('~/R/funwithR/data/ne_110m_land', pattern='\\.shp$')
file.exists('~/R/funwithR/data/ne_110m_land/ne_110m_land.shp')
</code></pre>
<p>perhaps try:</p>
<pre><code>readOGR(dsn=path.expand("~/R/funwithR/data/ne_110m_land"), layer="ne_110m_land")
</code></pre>
<p>or a simpler alternative that is wrapped around that:</p>
<pre><code>library(raster)
s <- shapefile("~/R/funwithR/data/ne_110m_land/ne_110m_land.shp")
</code></pre>
<p><strong>Update:</strong></p>
<p><code>rgdal</code> has changed a bit and you do not need to separate the path and layer anymore (at least for some formats). So you can do</p>
<pre><code>x <- readOGR("~/R/funwithR/data/ne_110m_land/ne_110m_land.shp")
</code></pre>
<p>(perhaps still using path.expand)</p>
<p>Also, if you are still using <code>readOGR</code> you are a bit behind the times. It is better to use <code>terra::vect</code> or <code>sf::st_read</code>.</p> |
43,815,995 | What is the difference between declarations and entryComponents | <p>I have this in my app.module.ts:</p>
<pre class="lang-js prettyprint-override"><code>import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { HttpModule, Http } from '@angular/http';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { EliteApi } from '../shared/shared';
import { MyApp } from './app.component';
import { MyTeams, Tournaments, TeamDetails, Teams, TeamHome, Standings } from '../pages/pages';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
@NgModule({
declarations: [
MyApp,
MyTeams,
TeamDetails,
Tournaments,
Teams,
TeamHome,
Standings
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp),
HttpModule
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
MyTeams,
TeamDetails,
Tournaments,
Teams,
TeamHome,
Standings
],
providers: [
HttpModule,
StatusBar,
SplashScreen,
{ provide: ErrorHandler, useClass: IonicErrorHandler },
EliteApi
]
})
export class AppModule { }
</code></pre>
<p>At the moment my <code>declarations</code> and <code>entryComponents</code> both are exactly the same. They contain all of the page/components that I built for my app. If I remove any entry from any of the properties I get error in angular2.</p>
<p>My question is if they are always the same then what is the need for these properties? I think I am definitely missing some point here. When would entryComponents and declaractions be different from one another?</p> | 43,816,056 | 6 | 0 | null | 2017-05-06 02:15:03.79 UTC | 15 | 2020-08-18 21:07:07.137 UTC | 2020-08-18 21:07:07.137 UTC | null | 6,595,016 | null | 6,034,347 | null | 1 | 75 | angular | 43,984 | <p>The <code>entryComponents</code> array is used to define <em>only</em> components that are not found in html and created dynamically with <code>ComponentFactoryResolver</code>. Angular needs this hint to find them and compile. All other components should just be listed in the declarations array.</p>
<p><a href="https://angular.io/guide/ngmodule-faq#what-is-an-entry-component" rel="noreferrer">Here's the documentation on angular site</a></p> |
43,825,440 | Importing nodejs `fs` with typescript when executing with ts-node? | <p>I'm trying to run the following code with <a href="https://github.com/TypeStrong/ts-node" rel="noreferrer">ts-node</a>.</p>
<pre><code>import { writeFileSync, readFileSync } from 'fs';
</code></pre>
<p>However I get:</p>
<pre><code>src/main/ts/create.ts (1,45): Cannot find module 'fs'. (2307)
</code></pre>
<p>What do I need to do in to allow typescript to import the fs module?</p> | 43,826,359 | 1 | 0 | null | 2017-05-06 21:12:52.637 UTC | 1 | 2017-05-06 23:30:10.597 UTC | null | null | null | null | 1,684,269 | null | 1 | 30 | node.js|typescript|typescript2.2|ts-node | 26,332 | <p>You need to run:</p>
<pre><code>$ npm install @types/node --save-dev
</code></pre>
<p>If you need additional information you can refer to the <a href="https://basarat.gitbooks.io/typescript/docs/quick/nodejs.html" rel="noreferrer">NodeJS QuickStart in the TypeScript Deep Dive by Basarat</a>.</p> |
1,072,964 | Names of Graph Traversal Algorithms | <p>What I'm looking for is a comprehensive list of graph traversal algorithms, with brief descriptions of their purpose, as a jump off point for researching them. So far I'm aware of:</p>
<ul>
<li>Dijkstra's - single-source shortest path</li>
<li>Kruskal's - finds a minimum spanning tree</li>
</ul>
<p>What are some other well-known ones? Please provide a brief description of each algorithm to each of your answers.</p> | 4,385,001 | 3 | 1 | null | 2009-07-02 07:25:30.563 UTC | 13 | 2012-06-07 10:43:51.697 UTC | 2009-07-02 08:32:48.68 UTC | null | 112,765 | null | 112,765 | null | 1 | 16 | algorithm|graph|graph-theory | 12,155 | <p>the well knowns are :</p>
<ul>
<li>Depth-first search <a href="http://en.wikipedia.org/wiki/Depth-first_search" rel="noreferrer">http://en.wikipedia.org/wiki/Depth-first_search</a></li>
<li>Breadth-first search <a href="http://en.wikipedia.org/wiki/Breadth-first_search" rel="noreferrer">http://en.wikipedia.org/wiki/Breadth-first_search</a></li>
<li>Prim's algorithm <a href="http://en.wikipedia.org/wiki/Prim%27s_algorithm" rel="noreferrer">http://en.wikipedia.org/wiki/Prim's_algorithm</a></li>
<li>Kruskal's algorithm <a href="http://en.wikipedia.org/wiki/Kruskal%27s_algorithm" rel="noreferrer">http://en.wikipedia.org/wiki/Kruskal's_algorithm</a></li>
<li>Bellman–Ford algorithm <a href="http://en.wikipedia.org/wiki/Bellman%E2%80%93Ford_algorithm" rel="noreferrer">http://en.wikipedia.org/wiki/Bellman%E2%80%93Ford_algorithm</a></li>
<li>Floyd–Warshall algorithm <a href="http://en.wikipedia.org/wiki/Floyd%E2%80%93Warshall_algorithm" rel="noreferrer">http://en.wikipedia.org/wiki/Floyd%E2%80%93Warshall_algorithm</a></li>
<li>Reverse-delete algorithm <a href="http://en.wikipedia.org/wiki/Reverse-Delete_algorithm" rel="noreferrer">http://en.wikipedia.org/wiki/Reverse-Delete_algorithm</a></li>
<li>Dijkstra's_algorithm <a href="http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm" rel="noreferrer">http://en.wikipedia.org/wiki/Dijkstra's_algorithm</a> </li>
</ul>
<p>network flow</p>
<ul>
<li>Ford–Fulkerson algorithm <a href="http://en.wikipedia.org/wiki/Ford%E2%80%93Fulkerson_algorithm" rel="noreferrer">http://en.wikipedia.org/wiki/Ford%E2%80%93Fulkerson_algorithm</a></li>
<li>Maximum Flow <a href="http://en.wikipedia.org/wiki/Maximum_flow_problem" rel="noreferrer">http://en.wikipedia.org/wiki/Maximum_flow_problem</a></li>
</ul> |
524,641 | How do I create my own ostream/streambuf? | <p>For educational purposes I want to create a ostream and stream buffer to do: </p>
<ol>
<li>fix endians when doing << myVar; </li>
<li>store in a deque container instead of using std:cout or writing to a file </li>
<li>log extra data, such as how many times I did <<, how many times I did .write, the amount of bytes I written and how many times I flush(). But I do not need all the info.</li>
</ol>
<p>I tried overloading but failed horribly. I tried overloading write by doing </p>
<pre><code>ostream& write( const char* s, streamsize n )
</code></pre>
<p>in my basic_stringstream2 class (I copied paste basic_stringstream into my cpp file and modified it) but the code kept using basic_ostream. I looked through code and it looks like I need to overload xsputn (which isn't mention on this page <a href="http://www.cplusplus.com/reference/iostream/ostream" rel="noreferrer">http://www.cplusplus.com/reference/iostream/ostream</a> ) but what else do I need to overload? and how do I construct my class (what does it need to inherit, etc)?</p> | 528,661 | 3 | 1 | null | 2009-02-07 21:45:04.903 UTC | 17 | 2017-11-01 13:55:19.647 UTC | 2011-12-20 08:08:22.713 UTC | null | 234,175 | user34537 | null | null | 1 | 25 | c++|ostream|streambuf | 27,039 | <p>The canonical approach consists in defining your own streambuf.
You should have a look at:</p>
<ul>
<li><a href="http://www.angelikalanger.com/Articles/Topics.html#CPP" rel="noreferrer">Angelika LAnger's articles</a> on IOStreams derivation</li>
<li><a href="http://gabisoft.free.fr/articles-en.html" rel="noreferrer">James Kanze's articles</a> on filtering streambufs</li>
<li><a href="http://www.boost.org/doc/libs/1_37_0/libs/iostreams/doc/index.html" rel="noreferrer">boost.iostream</a> for examples of application</li>
</ul> |
22,250,574 | HTML data-toggle="collapse" only collapse if it isn't already | <p>I want to collapse a div with a button if it is not collapsed already.
I have a button:</p>
<pre><code><button data-toggle="collapse" data-target="#aim" ...></button>
</code></pre>
<p>and my <code>div</code>:</p>
<pre><code><div id="#aim" class="collapse"></div>
</code></pre>
<p>I works great but if the <code>div</code> is already open the button close it.</p>
<p>Is there a chance to get collapse it when it isn't already?</p> | 22,284,157 | 3 | 0 | null | 2014-03-07 12:50:24.807 UTC | 1 | 2017-04-16 03:51:02.787 UTC | 2017-04-16 03:51:02.787 UTC | null | 1,033,581 | null | 2,543,819 | null | 1 | 6 | html|twitter-bootstrap|button | 44,483 | <p>Remove the <code>#</code> from your <code><div id="#aim" class="collapse"></code> and it should work. More info about bootstrap's data-toggle attribute can be found <a href="http://getbootstrap.com/javascript/#collapse" rel="nofollow">here</a>.</p>
<p>(Previous comment added as possible answer to help close this question).</p> |
6,485,908 | Basic Dual Contouring Theory | <p>I've been searching on google, but cannot find anything basic. In it's most basic form, how is dual contouring (for a voxel terrain) implememted? I know what it does, and why, but cannot understand how to do it. JS or C# (preferably) is good.Has anyone used Dual contouring before and can explain it briefly?</p> | 6,491,712 | 1 | 5 | null | 2011-06-26 18:31:45.517 UTC | 20 | 2020-02-15 20:23:59.793 UTC | 2011-06-27 06:31:48.373 UTC | null | 720,075 | null | 720,075 | null | 1 | 16 | c#|javascript|scripting|terrain|voxel | 13,202 | <p>Ok. So I got bored tonight and decided to give implementing dual contouring myself a shot. Like I said in the comments, all the relevant material is in section 2 of the following paper:</p>
<ul>
<li><del>Original Version: <a href="http://www.frankpetterson.com/publications/dualcontour/dualcontour.pdf" rel="nofollow noreferrer">http://www.frankpetterson.com/publications/dualcontour/dualcontour.pdf</a></del></li>
<li>Archived Version: <a href="https://web.archive.org/web/20170713094715if_/http://www.frankpetterson.com/publications/dualcontour/dualcontour.pdf" rel="nofollow noreferrer">https://web.archive.org/web/20170713094715if_/http://www.frankpetterson.com/publications/dualcontour/dualcontour.pdf</a></li>
</ul>
<p>In particular, the topology of the mesh is described in part 2.2 in the following section, quote:</p>
<blockquote>
<ol>
<li><p>For each cube that exhibits a sign change, generate a vertex positioned at the minimizer of the quadratic function of equation 1.</p></li>
<li><p>For each edge that exhibits a sign change, generate a quad connecting the minimizing vertices of the four cubes containing the edge.</p></li>
</ol>
</blockquote>
<p>That's all there is to it! You solve a linear least squares problem to get a vertex for each cube, then you connect adjacent vertices with quads. So using this basic idea, I wrote a dual contouring isosurface extractor in python using numpy (partly just to satisfy my own morbid curiosity on how it worked). Here is the code:</p>
<pre><code>import numpy as np
import numpy.linalg as la
import scipy.optimize as opt
import itertools as it
#Cardinal directions
dirs = [ [1,0,0], [0,1,0], [0,0,1] ]
#Vertices of cube
cube_verts = [ np.array([x, y, z])
for x in range(2)
for y in range(2)
for z in range(2) ]
#Edges of cube
cube_edges = [
[ k for (k,v) in enumerate(cube_verts) if v[i] == a and v[j] == b ]
for a in range(2)
for b in range(2)
for i in range(3)
for j in range(3) if i != j ]
#Use non-linear root finding to compute intersection point
def estimate_hermite(f, df, v0, v1):
t0 = opt.brentq(lambda t : f((1.-t)*v0 + t*v1), 0, 1)
x0 = (1.-t0)*v0 + t0*v1
return (x0, df(x0))
#Input:
# f = implicit function
# df = gradient of f
# nc = resolution
def dual_contour(f, df, nc):
#Compute vertices
dc_verts = []
vindex = {}
for x,y,z in it.product(range(nc), range(nc), range(nc)):
o = np.array([x,y,z])
#Get signs for cube
cube_signs = [ f(o+v)>0 for v in cube_verts ]
if all(cube_signs) or not any(cube_signs):
continue
#Estimate hermite data
h_data = [ estimate_hermite(f, df, o+cube_verts[e[0]], o+cube_verts[e[1]])
for e in cube_edges if cube_signs[e[0]] != cube_signs[e[1]] ]
#Solve qef to get vertex
A = [ n for p,n in h_data ]
b = [ np.dot(p,n) for p,n in h_data ]
v, residue, rank, s = la.lstsq(A, b)
#Throw out failed solutions
if la.norm(v-o) > 2:
continue
#Emit one vertex per every cube that crosses
vindex[ tuple(o) ] = len(dc_verts)
dc_verts.append(v)
#Construct faces
dc_faces = []
for x,y,z in it.product(range(nc), range(nc), range(nc)):
if not (x,y,z) in vindex:
continue
#Emit one face per each edge that crosses
o = np.array([x,y,z])
for i in range(3):
for j in range(i):
if tuple(o + dirs[i]) in vindex and tuple(o + dirs[j]) in vindex and tuple(o + dirs[i] + dirs[j]) in vindex:
dc_faces.append( [vindex[tuple(o)], vindex[tuple(o+dirs[i])], vindex[tuple(o+dirs[j])]] )
dc_faces.append( [vindex[tuple(o+dirs[i]+dirs[j])], vindex[tuple(o+dirs[j])], vindex[tuple(o+dirs[i])]] )
return dc_verts, dc_faces
</code></pre>
<p>It is not very fast because it uses the SciPy's generic non-linear root finding methods to find the edge points on the isosurface. However, it does seem to work reasonably well and in a fairly generic way. To test it, I ran it using the following test case (in the Mayavi2 visualization toolkit):</p>
<pre><code>import enthought.mayavi.mlab as mlab
center = np.array([16,16,16])
radius = 10
def test_f(x):
d = x-center
return np.dot(d,d) - radius**2
def test_df(x):
d = x-center
return d / sqrt(np.dot(d,d))
verts, tris = dual_contour(f, df, n)
mlab.triangular_mesh(
[ v[0] for v in verts ],
[ v[1] for v in verts ],
[ v[2] for v in verts ],
tris)
</code></pre>
<p>This defines a sphere as an implicit equation, and solves for the 0-isosurface by dual contouring. When I ran it in the toolkit, this was the result:</p>
<p><img src="https://i.stack.imgur.com/41J0M.png" alt="enter image description here"></p>
<p>In conclusion, it appears to be working.</p> |
41,718,376 | How to apply integration tests to a Flask RESTful API | <p><em>[As per <a href="https://stackoverflow.com/a/46369945/1021819">https://stackoverflow.com/a/46369945/1021819</a>, the title should refer to integration tests rather than unit tests]</em></p>
<p>Suppose I'd like to test the following Flask API (from <a href="http://flask-restful-cn.readthedocs.io/en/0.3.5/quickstart.html#a-minimal-api" rel="noreferrer">here</a>):</p>
<pre><code>import flask
import flask_restful
app = flask.Flask(__name__)
api = flask_restful.Api(app)
class HelloWorld(flask_restful.Resource):
def get(self):
return {'hello': 'world'}
api.add_resource(HelloWorld, '/')
if __name__ == "__main__":
app.run(debug=True)
</code></pre>
<p>Having saved this as <code>flaskapi.py</code> and run it, in the same directory I run the script <code>test_flaskapi.py</code>:</p>
<pre><code>import unittest
import flaskapi
import requests
class TestFlaskApiUsingRequests(unittest.TestCase):
def test_hello_world(self):
response = requests.get('http://localhost:5000')
self.assertEqual(response.json(), {'hello': 'world'})
class TestFlaskApi(unittest.TestCase):
def setUp(self):
self.app = flaskapi.app.test_client()
def test_hello_world(self):
response = self.app.get('/')
if __name__ == "__main__":
unittest.main()
</code></pre>
<p>Both the tests pass, but for the second test (defined in the <code>TestFlaskApi</code>) class I haven't yet figured out how to assert that the JSON response is as expected (namely, <code>{'hello': 'world'}</code>). This is because it is an instance of <code>flask.wrappers.Response</code> (which is probably essentially a Werkzeug Response object (cf. <a href="http://werkzeug.pocoo.org/docs/0.11/wrappers/" rel="noreferrer">http://werkzeug.pocoo.org/docs/0.11/wrappers/</a>)), and I haven't been able to find an equivalent of the <code>json()</code> method for <code>requests</code> <a href="http://docs.python-requests.org/en/master/api/#requests.Response" rel="noreferrer">Response</a> object.</p>
<p>How can I make assertions on the JSON content of the second <code>response</code>?</p> | 41,718,602 | 5 | 2 | null | 2017-01-18 11:34:07.653 UTC | 10 | 2021-08-11 14:09:53.1 UTC | 2020-12-24 20:55:45.017 UTC | null | 13,055,097 | null | 995,862 | null | 1 | 30 | python|flask|integration-testing|flask-restful|werkzeug | 36,000 | <p>I've found that I can get the JSON data by applying <code>json.loads()</code> to the output of the <code>get_data()</code> method:</p>
<pre><code>import unittest
import flaskapi
import requests
import json
import sys
class TestFlaskApiUsingRequests(unittest.TestCase):
def test_hello_world(self):
response = requests.get('http://localhost:5000')
self.assertEqual(response.json(), {'hello': 'world'})
class TestFlaskApi(unittest.TestCase):
def setUp(self):
self.app = flaskapi.app.test_client()
def test_hello_world(self):
response = self.app.get('/')
self.assertEqual(
json.loads(response.get_data().decode(sys.getdefaultencoding())),
{'hello': 'world'}
)
if __name__ == "__main__":
unittest.main()
</code></pre>
<p>Both tests pass as desired:</p>
<pre><code>..
----------------------------------------------------------------------
Ran 2 tests in 0.019s
OK
[Finished in 0.3s]
</code></pre> |
42,735,929 | How to delete a word in iTerm in mac os | <p>I am using iTerm as a terminal in my mac. I am not able to delete a word in command line for ex in command <code>cd /path/to/dir</code>, i want to delete just <code>path</code> word , then how can i do that in iTerm.</p>
<p>basically what is the shortcut to delete a word in iTerm. </p>
<p>I looked at <a href="https://apple.stackexchange.com/questions/154292/iterm-going-one-word-backwards-and-forwards">https://apple.stackexchange.com/questions/154292/iterm-going-one-word-backwards-and-forwards</a> and <code>fn+option+delete</code> is just deleting a single character, not the whole word.</p> | 42,736,566 | 4 | 2 | null | 2017-03-11 13:44:18.03 UTC | 12 | 2022-08-17 14:56:09.497 UTC | 2017-04-13 12:45:06.607 UTC | null | -1 | null | 4,296,092 | null | 1 | 47 | macos|shell|iterm | 14,528 | <p><kbd>esc</kbd>+<kbd>d</kbd> should work as a default.</p>
<p>Or you can add a <code>Send Escape Sequence</code> based keyboard mapping for <code>esc-d</code>:</p>
<p><a href="https://i.stack.imgur.com/Ftawu.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Ftawu.png" alt="enter image description here"></a></p> |
2,078,200 | Need approach to show tables using segmented control? | <p>Hi there I using a segmented control on a view. With the help of this segmented control I would like to display to different tables on my view, Suppose I have two segments in my table on tap of segment 1 I would like to display table 1 and on tap of segment 2 I would like to display table 2 my table 1 is a Plain table and table 2 is a grouped table, Apple is using approach to display differnt apps in differnt categories on app store but I am not sure how do I do that. Please suggest any approach or any code sample for the same will also appriciated.</p>
<p>Thanks
Sandy </p> | 2,078,253 | 2 | 0 | null | 2010-01-16 17:03:04.02 UTC | 14 | 2011-11-14 18:04:40.913 UTC | 2010-01-16 17:14:03.077 UTC | null | 100,848 | null | 188,517 | null | 1 | 11 | iphone|objective-c|uitableview | 12,531 | <p>We do this by having a single tableview, and then doing an if/case statement in each tableview callback method to return the right data based on which value is selected in the segmented control.</p>
<p>First, add the segmentedControl to the titleView, and set a callback function for when it is changed:</p>
<pre><code>- (void) addSegmentedControl {
NSArray * segmentItems = [NSArray arrayWithObjects: @"One", @"Two", nil];
segmentedControl = [[[UISegmentedControl alloc] initWithItems: segmentItems] retain];
segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;
segmentedControl.selectedSegmentIndex = 0;
[segmentedControl addTarget: self action: @selector(onSegmentedControlChanged:) forControlEvents: UIControlEventValueChanged];
self.navigationItem.titleView = segmentedControl;
}
</code></pre>
<p>Next, when the segmented control is changed, you need to load the data for the new segment, and reset the table view to show this data:</p>
<pre><code>- (void) onSegmentedControlChanged:(UISegmentedControl *) sender {
// lazy load data for a segment choice (write this based on your data)
[self loadSegmentData:segmentedControl.selectedSegmentIndex];
// reload data based on the new index
[self.tableView reloadData];
// reset the scrolling to the top of the table view
if ([self tableView:self.tableView numberOfRowsInSection:0] > 0) {
NSIndexPath *topIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.tableView scrollToRowAtIndexPath:topIndexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
}
}
</code></pre>
<p>Then in your tableView callbacks, you need to have logic per segment value to return the right thing. I'll show you one callback as an example, but implement the rest like this:</p>
<pre><code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"GenericCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[NSBundle mainBundle] loadNibNamed:@"GenericCell" owner:self options:nil] objectAtIndex: 0];
}
if (segmentedControl.selectedSegmentIndex == 0) {
cell.textLabel.text = @"One";
} else if (segmentedControl.selectedSegmentIndex == 1) {
cell.textLabel.text = @"Two";
}
return cell;
}
</code></pre>
<p>That's about it, hope it helps.</p> |
1,366,858 | jQuery Validation plugin custom method. Multiple parameters | <p>I'm trying to use a custom validator with jQuery Validation plugin.
However, I'm unsure how are you supposed to pass multiple arguments to a validation method?
I've tried using (2,3), curly braces and combinations, but I have failed.</p>
<p>This is the code - ???? marks the area I need info about:</p>
<pre><code>$(document).ready(function() {
jQuery.validator.addMethod("math", function(value, element, params) {
return this.optional(element) || value == params[0] + params[1];
}, jQuery.format("Please enter the correct value for {0} + {1}"));
$("#form_register").validate({
debug: true,
rules: {
inputEl: { required: true, math: ???? }
},
messages: {
inputEl: { required: "Required", math: "Incorrect result" }
}
});
});
</code></pre> | 1,366,872 | 2 | 0 | null | 2009-09-02 10:13:34.667 UTC | 5 | 2013-02-19 14:09:53.753 UTC | null | null | null | null | 145,893 | null | 1 | 30 | jquery|jquery-validate | 35,079 | <p>Javascript arrays:</p>
<pre><code>[value1,value2,value3]
</code></pre>
<p>SO your code might be:</p>
<pre><code>inputEl: { required: true, math: [2, 3 ,4 , 5] }
</code></pre> |
5,966,599 | Java Scanner String input | <p>I'm writing a program that uses an Event class, which has in it an instance of a calendar, and a description of type String. The method to create an event uses a Scanner to take in a month, day, year, hour, minute, and a description. The problem I'm having is that the Scanner.next() method only returns the first word before a space. So if the input is "My Birthday", the description of that instance of an Event is simply "My".</p>
<p>I did some research and found that people used Scanner.nextLine() for this issue, but when I try this, it just skips past where the input should go. Here is what a section of my code looks like:</p>
<pre><code>System.out.print("Please enter the event description: ");
String input = scan.nextLine();
e.setDescription(input);
System.out.println("Event description" + e.description);
e.time.set(year, month-1, day, hour, min);
addEvent(e);
System.out.println("Event: "+ e.time.getTime());
</code></pre>
<p>And this is the output I get:</p>
<pre><code>Please enter the event description: Event description
Event: Thu Mar 22 11:11:48 EDT 2012
</code></pre>
<p>It skips past the space to input the description String, and as a result, the description (which is initially set to a blank space - " "), is never changed.</p>
<p>How can I fix this?</p> | 5,966,775 | 5 | 4 | null | 2011-05-11 15:17:59.39 UTC | 7 | 2021-05-31 11:17:21.357 UTC | 2011-05-15 12:44:34.723 UTC | null | 21,234 | null | 748,950 | null | 1 | 20 | java|string|java.util.scanner | 286,122 | <p>When you read in the year month day hour minutes with something like nextInt() it leaves rest of the line in the parser/buffer (even if it is blank) so when you call nextLine() you are reading the rest of this first line.</p>
<p>I suggest you call scan.nextLine() before you print your next prompt to discard the rest of the line.</p> |
5,986,860 | function is not defined error in Python | <p>I am trying to define a basic function in python but I always get the following error when I run a simple test program;</p>
<pre><code>>>> pyth_test(1, 2)
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
pyth_test(1, 2)
NameError: name 'pyth_test' is not defined
</code></pre>
<p>Here is the code I am using for this function;</p>
<pre><code>def pyth_test (x1, x2):
print x1 + x2
</code></pre>
<p>UPDATE: I have the script called pyth.py open, and then I am typing in pyth_test(1,2) in the interpreter when it gives the error. </p>
<p>Thanks for the help. (I apologize for the basic question, I've never programmed before and am trying to learn Python as a hobby)</p>
<hr>
<pre><code>import sys
sys.path.append ('/Users/clanc/Documents/Development/')
import test
printline()
## (the function printline in the test.py file
##def printline():
## print "I am working"
</code></pre> | 5,986,866 | 5 | 2 | null | 2011-05-13 03:05:17.713 UTC | 4 | 2022-02-18 16:38:19.95 UTC | 2016-09-05 01:55:39.073 UTC | null | 3,750,257 | null | 751,698 | null | 1 | 48 | python|function | 273,420 | <p>Yes, but in what file is <code>pyth_test</code>'s definition declared in? Is it also located before it's called?</p>
<p>Edit:</p>
<p>To put it into perspective, create a file called <code>test.py</code> with the following contents:</p>
<pre><code>def pyth_test (x1, x2):
print x1 + x2
pyth_test(1,2)
</code></pre>
<p>Now run the following command:</p>
<pre><code>python test.py
</code></pre>
<p>You should see the output you desire. Now if you are in an interactive session, it should go like this:</p>
<pre><code>>>> def pyth_test (x1, x2):
... print x1 + x2
...
>>> pyth_test(1,2)
3
>>>
</code></pre>
<p>I hope this explains how the declaration works.</p>
<hr>
<p>To give you an idea of how the layout works, we'll create a few files. Create a new empty folder to keep things clean with the following:</p>
<p><strong><em>myfunction.py</em></strong></p>
<pre><code>def pyth_test (x1, x2):
print x1 + x2
</code></pre>
<p><strong><em>program.py</em></strong></p>
<pre><code>#!/usr/bin/python
# Our function is pulled in here
from myfunction import pyth_test
pyth_test(1,2)
</code></pre>
<p>Now if you run:</p>
<pre><code>python program.py
</code></pre>
<p>It will print out 3. Now to explain what went wrong, let's modify our program this way:</p>
<pre><code># Python: Huh? where's pyth_test?
# You say it's down there, but I haven't gotten there yet!
pyth_test(1,2)
# Our function is pulled in here
from myfunction import pyth_test
</code></pre>
<p>Now let's see what happens:</p>
<pre><code>$ python program.py
Traceback (most recent call last):
File "program.py", line 3, in <module>
pyth_test(1,2)
NameError: name 'pyth_test' is not defined
</code></pre>
<p>As noted, python cannot find the module for the reasons outlined above. For that reason, you should keep your declarations at top.</p>
<p>Now then, if we run the interactive python session:</p>
<pre><code>>>> from myfunction import pyth_test
>>> pyth_test(1,2)
3
</code></pre>
<p>The same process applies. Now, package importing isn't all that simple, so I recommend you look into how <a href="http://docs.python.org/tutorial/modules.html" rel="noreferrer">modules work with Python</a>. I hope this helps and good luck with your learnings!</p> |
6,116,960 | What do "module.exports" and "exports.methods" mean in NodeJS / Express? | <p>Looking at a random <a href="https://github.com/visionmedia/express/blob/master/lib/router/index.js">source file</a> of the <code>express</code> framework for <code>NodeJS</code>, there are two lines of the code that I do not understand (these lines of code are typical of almost all NodeJS files).</p>
<pre><code>/**
* Expose `Router` constructor.
*/
exports = module.exports = Router;
</code></pre>
<p>and</p>
<pre><code>/**
* Expose HTTP methods.
*/
var methods = exports.methods = require('./methods');
</code></pre>
<p>I understand that the <em>first piece of code</em> <strong>allows the rest of the functions in the file to be exposed to the NodeJS app</strong>, but I don't understand exactly <strong>how it works</strong>, or what the code in the line means. </p>
<blockquote>
<p>What do <code>exports</code> and <code>module.exports</code> actually mean?</p>
</blockquote>
<p>I believe the 2nd piece of code allows the functions in the file to access <code>methods</code>, but again, how exactly does it do this.</p>
<p>Basically, what are these magic words: <strong><code>module</code></strong> and <strong><code>exports</code></strong>?</p> | 6,117,479 | 5 | 0 | null | 2011-05-24 21:13:54.653 UTC | 33 | 2019-06-24 00:45:05.747 UTC | 2015-10-21 11:59:04.633 UTC | null | 3,924,118 | null | 527,749 | null | 1 | 57 | javascript|node.js|express|module|export | 42,686 | <p>To be more specific:</p>
<p><code>module</code> is the global scope variable inside a file.</p>
<p>So if you call <code>require("foo")</code> then :</p>
<pre><code>// foo.js
console.log(this === module); // true
</code></pre>
<p>It acts in the same way that <code>window</code> acts in the browser. </p>
<p>There is also another global object called <code>global</code> which you can write and read from in any file you want, but that involves mutating global scope and this is <strong>EVIL</strong></p>
<p><code>exports</code> is a variable that lives on <code>module.exports</code>. It's basically what you <em>export</em> when a file is required.</p>
<pre><code>// foo.js
module.exports = 42;
// main.js
console.log(require("foo") === 42); // true
</code></pre>
<p>There is a minor problem with <code>exports</code> on it's own. The _global scope context+ and <code>module</code> are <strong>not</strong> the same. (In the browser the global scope context and <code>window</code> are the same).</p>
<pre><code>// foo.js
var exports = {}; // creates a new local variable called exports, and conflicts with
// living on module.exports
exports = {}; // does the same as above
module.exports = {}; // just works because its the "correct" exports
// bar.js
exports.foo = 42; // this does not create a new exports variable so it just works
</code></pre>
<p><a href="https://stackoverflow.com/questions/5311334/what-is-the-purpose-of-nodejs-module-exports-and-how-do-you-use-it">Read more about exports</a></p> |
5,939,412 | php string function to get substring before the last occurrence of a character | <pre><code>$string = "Hello World Again".
echo strrchr($string , ' '); // Gets ' Again'
</code></pre>
<p>Now I want to get "Hello World" from the <code>$string</code> [The substring before the last occurrence of a space ' ' ]. How do I get it??</p> | 5,939,484 | 10 | 0 | null | 2011-05-09 15:56:31.2 UTC | 2 | 2021-06-04 10:33:21.887 UTC | null | null | null | null | 383,393 | null | 1 | 40 | php | 40,284 | <p>This is kind of a cheap way to do it, but you could split, pop, and then join to get it done:</p>
<pre><code>$string = 'Hello World Again';
$string = explode(' ', $string);
array_pop($string);
$string = implode(' ', $string);
</code></pre> |
5,818,423 | Set NOW() as Default Value for datetime datatype? | <p>I have two columns in table users namely <code>registerDate and lastVisitDate</code> which consist of datetime data type. I would like to do the following.</p>
<ol>
<li>Set registerDate defaults value to MySQL NOW()</li>
<li>Set lastVisitDate default value to <code>0000-00-00 00:00:00</code> Instead of null which it uses by default.</li>
</ol>
<p>Because the table already exists and has existing records, I would like to use Modify table. I've tried using the two piece of code below, but neither works. </p>
<pre><code>ALTER TABLE users MODIFY registerDate datetime DEFAULT NOW()
ALTER TABLE users MODIFY registerDate datetime DEFAULT CURRENT_TIMESTAMP;
</code></pre>
<p>It gives me Error : <code>ERROR 1067 (42000): Invalid default value for 'registerDate'</code></p>
<p>Is it possible for me to set the default datetime value to NOW() in MySQL?</p> | 5,818,452 | 13 | 4 | null | 2011-04-28 12:14:03.573 UTC | 36 | 2020-02-16 10:22:14.74 UTC | 2015-07-30 12:52:16.597 UTC | null | 4,320,665 | null | 396,476 | null | 1 | 214 | mysql|sql|datetime|mysql-error-1067 | 498,925 | <p>As of MySQL 5.6.5, you can use the <code>DATETIME</code> type with a dynamic default value:</p>
<pre><code>CREATE TABLE foo (
creation_time DATETIME DEFAULT CURRENT_TIMESTAMP,
modification_time DATETIME ON UPDATE CURRENT_TIMESTAMP
)
</code></pre>
<p>Or even combine both rules:</p>
<pre><code>modification_time DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
</code></pre>
<p>Reference:<br>
<a href="http://dev.mysql.com/doc/refman/5.7/en/timestamp-initialization.html" rel="noreferrer">http://dev.mysql.com/doc/refman/5.7/en/timestamp-initialization.html</a><br>
<a href="http://optimize-this.blogspot.com/2012/04/datetime-default-now-finally-available.html" rel="noreferrer">http://optimize-this.blogspot.com/2012/04/datetime-default-now-finally-available.html</a></p>
<p>Prior to 5.6.5, you need to use the <code>TIMESTAMP</code> data type, which automatically updates whenever the record is modified. Unfortunately, however, only one auto-updated <code>TIMESTAMP</code> field can exist per table.</p>
<pre><code>CREATE TABLE mytable (
mydate TIMESTAMP
)
</code></pre>
<p>See: <a href="http://dev.mysql.com/doc/refman/5.1/en/create-table.html" rel="noreferrer">http://dev.mysql.com/doc/refman/5.1/en/create-table.html</a></p>
<p>If you want to prevent MySQL from updating the timestamp value on <code>UPDATE</code> (so that it only triggers on <code>INSERT</code>) you can change the definition to:</p>
<pre><code>CREATE TABLE mytable (
mydate TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
</code></pre> |
5,736,398 | How to calculate the SVG Path for an arc (of a circle) | <p>Given a circle centered at (200,200), radius 25, how do I draw an arc from 270 degree to 135 degree and one that goes from 270 to 45 degree?</p>
<p>0 degree means it is right on the x-axis (the right side) (meaning it is 3 o' clock position)
270 degree means it is 12 o'clock position, and 90 means it is 6 o'clock position</p>
<p>More generally, what is a path for an arc for part of a circle with</p>
<pre><code>x, y, r, d1, d2, direction
</code></pre>
<p>meaning</p>
<pre><code>center (x,y), radius r, degree_start, degree_end, direction
</code></pre> | 18,473,154 | 14 | 0 | null | 2011-04-20 20:44:31.26 UTC | 131 | 2022-07-08 10:15:26.247 UTC | 2012-11-14 19:01:40.087 UTC | null | 164,966 | null | 325,418 | null | 1 | 234 | svg | 178,336 | <p>Expanding on @wdebeaum's great answer, here's a method for generating an arced path: </p>
<pre><code>function polarToCartesian(centerX, centerY, radius, angleInDegrees) {
var angleInRadians = (angleInDegrees-90) * Math.PI / 180.0;
return {
x: centerX + (radius * Math.cos(angleInRadians)),
y: centerY + (radius * Math.sin(angleInRadians))
};
}
function describeArc(x, y, radius, startAngle, endAngle){
var start = polarToCartesian(x, y, radius, endAngle);
var end = polarToCartesian(x, y, radius, startAngle);
var largeArcFlag = endAngle - startAngle <= 180 ? "0" : "1";
var d = [
"M", start.x, start.y,
"A", radius, radius, 0, largeArcFlag, 0, end.x, end.y
].join(" ");
return d;
}
</code></pre>
<p>to use</p>
<pre><code>document.getElementById("arc1").setAttribute("d", describeArc(200, 400, 100, 0, 180));
</code></pre>
<p>and in your html</p>
<pre><code><path id="arc1" fill="none" stroke="#446688" stroke-width="20" />
</code></pre>
<p><a href="http://jsbin.com/quhujowota/1/edit?html,js,output">Live demo</a></p> |
46,607,843 | Xcode 9 commit: Couldn't communicate with helper application | <p>I've recently updated to OSX Sierra (from El Capitan) and to Xcode 9. I removed all compatibility issues (like autolayout issues) and would like to commit to my local gitrep now.</p>
<p>the following error appears:</p>
<p><a href="https://i.stack.imgur.com/6kOII.png" rel="noreferrer"><img src="https://i.stack.imgur.com/6kOII.png" alt="enter image description here"></a></p>
<p>I thought it might be the same bug appeared in XCode 7 mentioned here:
<a href="https://stackoverflow.com/questions/14694662/xcode-and-git-source-control-the-working-copy-xxxxx-failed-to-commit-files">Xcode and Git Source Control : “The working copy XXXXX failed to commit files”</a></p>
<p><a href="https://i.stack.imgur.com/zOxxR.png" rel="noreferrer"><img src="https://i.stack.imgur.com/zOxxR.png" alt="enter image description here"></a></p>
<p>But it wasn't. I tried the solution mentioned above. Username and EMail are properly set. I did save everything, tried restarting the machine and a few other minor things. Nothing worked - i can't commit.</p>
<p>Any help appreciated.</p>
<p><strong>EDIT</strong></p>
<p>I got it to work by commiting manually and adding changes before with</p>
<pre><code>git commit -a -m "Fixes"
</code></pre>
<p>I will keep an eye on that if it happens again once i made more changes and report here if so.</p> | 46,947,162 | 5 | 1 | null | 2017-10-06 14:16:02.093 UTC | 5 | 2019-07-02 08:10:33.507 UTC | 2017-10-06 14:29:37.997 UTC | null | 4,591,992 | null | 4,591,992 | null | 1 | 34 | git|macos|git-commit|xcode9 | 18,288 | <p>The solution is to add changes once with a git command.
Use terminal and navigate to Xcode project folder. If you are in the right folder, this command:</p>
<pre><code>ls -al
</code></pre>
<p>will list a .git folder. Then you know you're at the right place. Then execute</p>
<pre><code>git commit -a -m "Commit title here"
</code></pre>
<p>After that commit via Xcode should work again. </p> |
44,689,474 | ERROR TypeError: Cannot read property 'length' of undefined | <p>There is an error in this part of my code</p>
<pre><code><img src="../../../assets/gms-logo.png" alt="logo" routerLink="/overview" alt="website icon">
</code></pre>
<p>But when I checked the assets folder, <code>gms-logo.png</code> is still there and in <code>angular-cli.json</code>, assets is also there. The path is also correct. </p>
<p>Recently though, I've been working on Search function. So my hypothesis is, </p>
<blockquote>
<p>Has the program started searching even if the user is still not focused on the input type? How do I fix this?</p>
</blockquote>
<p>Below is my html for Search and the showing of its suggestion segment</p>
<pre><code><input type="text" placeholder="Search" (keyup)="onSearch($event.target.value)">
<div class="suggestion" *ngIf="results.length > 0">
<div *ngFor="let result of results ">
<a href="" target="_blank">
{{ result.name }}
</a>
</div>
</div>
</code></pre>
<p>Below is my component</p>
<pre><code>results: Object;
onSearch(name) {
this.search
.searchEmployee(name)
.subscribe(
name => this.results = name,//alert(searchName),this.route.navigate(['/information/employees/']),
error => alert(error),
);
}
</code></pre> | 44,689,516 | 6 | 1 | null | 2017-06-22 03:06:42.57 UTC | 1 | 2020-03-19 10:47:50.927 UTC | 2017-06-22 03:14:06.997 UTC | null | 5,935,350 | null | 5,935,350 | null | 1 | 12 | angular|typeerror|angular-cli|google-developers-console|google-developer-tools | 99,963 | <p>You need to initialize your <code>results</code> variable as an array.</p>
<p>In your component, add:</p>
<pre><code>results = [];
</code></pre>
<p>Another option is to change your suggestion div's <code>*ngIf</code> statement to check if <code>results</code> is defined: </p>
<pre><code><div class="suggestion" *ngIf="results">
<div *ngFor="let result of results ">
<a href="" target="_blank">
{{ result.name }}
</a>
</div>
</div>
</code></pre> |
44,583,254 | ValueError: Input 0 is incompatible with layer lstm_13: expected ndim=3, found ndim=4 | <p>I am trying for multi-class classification and here are the details of my training input and output:</p>
<blockquote>
<p>train_input.shape= (1, 95000, 360) (95000 length input array with each
element being an array of 360 length)</p>
<p>train_output.shape = (1, 95000, 22) (22 Classes are there)</p>
</blockquote>
<pre><code>model = Sequential()
model.add(LSTM(22, input_shape=(1, 95000,360)))
model.add(Dense(22, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
print(model.summary())
model.fit(train_input, train_output, epochs=2, batch_size=500)
</code></pre>
<p>The error is:</p>
<blockquote>
<p>ValueError: Input 0 is incompatible with layer lstm_13: expected ndim=3, found ndim=4
in line:
model.add(LSTM(22, input_shape=(1, 95000,360)))</p>
</blockquote>
<p>Please help me out, I am not able to solve it through other answers.</p> | 44,583,919 | 5 | 1 | null | 2017-06-16 07:23:45.11 UTC | 8 | 2021-10-27 05:26:06.55 UTC | null | null | null | null | 5,697,891 | null | 1 | 34 | python|keras|lstm|recurrent-neural-network | 103,571 | <p>I solved the problem by making </p>
<blockquote>
<p>input size: (95000,360,1) and
output size: (95000,22)</p>
</blockquote>
<p>and changed the <strong>input shape to (360,1)</strong> in the code where model is defined:</p>
<pre><code>model = Sequential()
model.add(LSTM(22, input_shape=(360,1)))
model.add(Dense(22, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
print(model.summary())
model.fit(ml2_train_input, ml2_train_output_enc, epochs=2, batch_size=500)
</code></pre> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.