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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
22,160,888 | What is the difference between crtbegin.o, crtbeginT.o and crtbeginS.o? | <p>I'm trying to link directly using <code>ld</code> to isolate a build problem.</p>
<p>When I include <code>/usr/lib/gcc/x86_64-linux-gnu/4.7/libstdc++.so</code>, I get a few issues:</p>
<pre><code>ac-aaa.o: In function `__static_initialization_and_destruction_0':
/usr/include/c++/4.7/iostream:75: undefined reference to `__dso_handle'
ac-callback.o: In function `__static_initialization_and_destruction_0':
/usr/include/c++/4.7/iostream:75: undefined reference to `__dso_handle'
...
</code></pre>
<p>Searching for <code>__dso_handle</code>:</p>
<pre><code>$ grep __dso_handle /usr/lib/gcc/x86_64-linux-gnu/4.7/*
Binary file /usr/lib/gcc/x86_64-linux-gnu/4.7/cc1plus matches
Binary file /usr/lib/gcc/x86_64-linux-gnu/4.7/crtbegin.o matches
Binary file /usr/lib/gcc/x86_64-linux-gnu/4.7/crtbeginS.o matches
Binary file /usr/lib/gcc/x86_64-linux-gnu/4.7/crtbeginT.o matches
</code></pre>
<p>What is the difference between <code>crtbegin.o</code>, <code>crtbeginT.o</code> and <code>crtbeginS.o</code>?</p> | 27,786,892 | 1 | 1 | null | 2014-03-04 01:06:17.267 UTC | 10 | 2015-05-07 23:52:56.167 UTC | 2015-05-07 23:52:56.167 UTC | null | 608,639 | null | 608,639 | null | 1 | 15 | c++|linux|linker|ld|crt | 10,492 | <p>You will find nice explanation here: <a href="http://dev.gentoo.org/~vapier/crt.txt" rel="noreferrer">http://dev.gentoo.org/~vapier/crt.txt</a></p>
<p>I will quote it following, in case that URL disappears.</p>
<hr>
<h2>Mini FAQ about the misc libc/gcc crt files.</h2>
<pre><code>Some definitions:
PIC - position independent code (-fPIC)
PIE - position independent executable (-fPIE -pie)
crt - C runtime
crt0.o crt1.o etc...
Some systems use crt0.o, while some use crt1.o (and a few even use crt2.o
or higher). Most likely due to a transitionary phase that some targets
went through. The specific number is otherwise entirely arbitrary -- look
at the internal gcc port code to figure out what your target expects. All
that matters is that whatever gcc has encoded, your C library better use
the same name.
This object is expected to contain the _start symbol which takes care of
bootstrapping the initial execution of the program. What exactly that
entails is highly libc dependent and as such, the object is provided by
the C library and cannot be mixed with other ones.
On uClibc/glibc systems, this object initializes very early ABI requirements
(like the stack or frame pointer), setting up the argc/argv/env values, and
then passing pointers to the init/fini/main funcs to the internal libc main
which in turn does more general bootstrapping before finally calling the real
main function.
glibc ports call this file 'start.S' while uClibc ports call this crt0.S or
crt1.S (depending on what their gcc expects).
crti.o
Defines the function prologs for the .init and .fini sections (with the _init
and _fini symbols respectively). This way they can be called directly. These
symbols also trigger the linker to generate DT_INIT/DT_FINI dynamic ELF tags.
These are to support the old style constructor/destructor system where all
.init/.fini sections get concatenated at link time. Not to be confused with
newer prioritized constructor/destructor .init_array/.fini_array sections and
DT_INIT_ARRAY/DT_FINI_ARRAY ELF tags.
glibc ports used to call this 'initfini.c', but now use 'crti.S'. uClibc
also uses 'crti.S'.
crtn.o
Defines the function epilogs for the .init/.fini sections. See crti.o.
glibc ports used to call this 'initfini.c', but now use 'crtn.S'. uClibc
also uses 'crtn.S'.
Scrt1.o
Used in place of crt1.o when generating PIEs.
gcrt1.o
Used in place of crt1.o when generating code with profiling information.
Compile with -pg. Produces output suitable for the gprof util.
Mcrt1.o
Like gcrt1.o, but is used with the prof utility. glibc installs this as
a dummy file as it's useless on linux systems.
crtbegin.o
GCC uses this to find the start of the constructors.
crtbeginS.o
Used in place of crtbegin.o when generating shared objects/PIEs.
crtbeginT.o
Used in place of crtbegin.o when generating static executables.
crtend.o
GCC uses this to find the start of the destructors.
crtendS.o
Used in place of crtend.o when generating shared objects/PIEs.
General linking order:
crt1.o crti.o crtbegin.o [-L paths] [user objects] [gcc libs] [C libs] [gcc libs] crtend.o crtn.o
More references:
http://gcc.gnu.org/onlinedocs/gccint/Initialization.html
</code></pre> |
37,536,687 | What is the relation between docker0 and eth0? | <p>I know by default docker creates a virtual bridge <code>docker0</code>, and all container network are linked to <code>docker0</code>.</p>
<p><img src="https://www.linuxjournal.com/files/linuxjournal.com/ufiles/imagecache/large-550px-centered/u1002061/11833f1.png" alt=""></p>
<p>As illustrated above:</p>
<ul>
<li>container <code>eth0</code> is paired with <code>vethXXX</code></li>
<li><code>vethXXX</code> is linked to <code>docker0</code> same as a machine linked to switch</li>
</ul>
<p>But what is the relation between <code>docker0</code> and host <code>eth0</code>?
More specifically:</p>
<ol>
<li><strong>When a packet flows from container to docker0, how does it know it will be forwarded to eth0, and then to the outside world?</strong></li>
<li><strong>When an external packet arrives to eth0, why it is forwarded to docker0 then container? instead of processing it or drop it?</strong></li>
</ol>
<p>Question 2 can be a little confusing, I will keep it there and explained a little more:</p>
<ul>
<li>It is a return packet that initialed by container(in question 1): since the outside does not know container network, the packet is sent to host <code>eth0</code>. How it is forwarded to container? I mean, there must be some place to store the information, how can I check it?</li>
</ul>
<p>Thanks in advance!</p>
<hr>
<p>After reading the answer and official network articles, I find the following diagram more accurate that <code>docker0</code> and <code>eth0</code> has no direct link,instead they can forward packets:</p>
<p><a href="http://dockerone.com/uploads/article/20150527/e84946a8e9df0ac6d109c35786ac4833.png" rel="noreferrer">http://dockerone.com/uploads/article/20150527/e84946a8e9df0ac6d109c35786ac4833.png</a></p> | 37,538,317 | 2 | 2 | null | 2016-05-31 04:11:06.663 UTC | 22 | 2020-10-16 02:48:55.797 UTC | 2017-02-08 15:10:20.313 UTC | null | -1 | null | 1,925,083 | null | 1 | 46 | networking|docker | 33,435 | <p>There is no direct link between the default <code>docker0</code> bridge and the hosts ethernet devices. If you use the <code>--net=host</code> option for a container then the hosts network stack will be available in the container.</p>
<blockquote>
<p>When a packet flows from container to docker0, how does it know it will be forwarded to eth0, and then to the outside world?</p>
</blockquote>
<p>The <code>docker0</code> bridge has the <code>.1</code> address of the Docker network assigned to it, this is usually something around a 172.17 or 172.18.</p>
<pre><code>$ ip address show dev docker0
8: docker0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default
link/ether 02:42:03:47:33:c1 brd ff:ff:ff:ff:ff:ff
inet 172.17.0.1/16 scope global docker0
valid_lft forever preferred_lft forever
</code></pre>
<p>Containers are assigned a veth interface which is attached to the <code>docker0</code> bridge.</p>
<pre><code>$ bridge link
10: vethcece7e5 state UP @(null): <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 master docker0 state forwarding priority 32 cost 2
</code></pre>
<p>Containers created on the default Docker network receive the <code>.1</code> address as their default route.</p>
<pre><code>$ docker run busybox ip route show
default via 172.17.0.1 dev eth0
172.17.0.0/16 dev eth0 src 172.17.0.3
</code></pre>
<p>Docker uses NAT MASQUERADE for outbound traffic from there and it will follow the standard outbound routing on the host, which may or may not involve <code>eth0</code>.</p>
<pre><code>$ iptables -t nat -vnL POSTROUTING
Chain POSTROUTING (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target prot opt in out source destination
0 0 MASQUERADE all -- * !docker0 172.17.0.0/16 0.0.0.0/0
</code></pre>
<p>iptables handles the connection tracking and return traffic.</p>
<blockquote>
<p>When an external packet arrives to eth0, why it is forwarded to docker0 then container? instead of processing it or drop it?</p>
</blockquote>
<p>If you are asking about the return path for outbound traffic from the container, see iptables above as the <code>MASQUERADE</code> will map the connection back through.</p>
<p>If you mean new inbound traffic, Packets are not forwarded into a container by default. The standard way to achieve this is to setup <a href="https://docs.docker.com/engine/reference/run/#expose-incoming-ports" rel="noreferrer">a port mapping</a>. Docker launches a daemon that listens on the host on port X and forwards to the container on port Y.</p>
<p>I'm not sure why NAT wasn't used for inbound traffic as well. I've run into some issues trying to map large numbers of ports into containers which led to <a href="https://github.com/jpetazzo/pipework#connect-a-container-to-a-local-physical-interface" rel="noreferrer">mapping real world interfaces</a> completely into containers.</p> |
20,381,976 | REST API DESIGN - Getting a resource through REST with different parameters but same url pattern | <p>I have a question related to REST URL design. I found some relevant posts here <a href="https://stackoverflow.com/questions/16273390/different-restful-representations-of-the-same-resource">Different RESTful representations of the same resource</a> and here <a href="https://stackoverflow.com/questions/11104466/restful-url-to-get-resource-by-different-fields">RESTful url to GET resource by different fields</a> but the responses are not quite clear on what the best practices are and why. Here's an example.</p>
<p>I have REST URLs for representing "users" resource. I can GET a user with an id or with an email address but the URL representation remains the same for both. Going through a lot of blogs and books I see that people have been doing this in many different ways. For example</p>
<p>read this practice in a book and somewhere on stackoverflow (I can't seem to find the link again)</p>
<pre><code>GET /users/id={id}
GET /users/email={email}
</code></pre>
<p>read this practice on a lot of blogs</p>
<pre><code>GET /users/{id}
GET /users/email/{email}
</code></pre>
<p>Query params are normally used for filtering the results of the resources represented by the URL, but I have seen this practice being used as well</p>
<pre><code>GET /users?id={id}
GET /users?email={email}
</code></pre>
<p>My question is, out of all these practices, which one would make the most sense to developers consuming the APIs and why? I believe there are no rules set in stone when it comes to REST URL designs and naming conventions, but I just wanted to know which route I should take to help developers better understand the APIs.</p> | 20,386,425 | 3 | 1 | null | 2013-12-04 17:29:56.49 UTC | 45 | 2022-04-04 07:16:50.127 UTC | 2022-03-16 23:11:41.093 UTC | null | 7,487,335 | null | 3,066,911 | null | 1 | 125 | rest|url|jax-rs|url-scheme|url-pattern | 88,674 | <p>In my experience, <code>GET /users/{id} GET /users/email/{email}</code> is the most common approach. I would also expect the methods to return a 404 Not Found if a user doesn't exist with the provided <code>id</code> or <code>email</code>. I wouldn't be surprised to see <code>GET /users/id/{id}</code>, either (though in my opinion, it is redundant).</p>
<h2>Comments on the other approaches</h2>
<ol>
<li><code>GET /users/id={id} GET /users/email={email}</code>
<ul>
<li>I don't think I've seen this, and if I did see it, it would be very confusing. It's almost like it's trying to imitate query parameters with path parameters.</li>
</ul></li>
<li><code>GET /users?id={id} GET /users?email={email}</code>
<ul>
<li>I think you hit the nail on the head when you mentioned using query parameters for filtering.</li>
<li>Would it ever make sense to call this resource with <em>both</em> an <code>id</code> and an <code>email</code> (e.g. <code>GET /users?id={id}&email={email}</code>)? If not, I wouldn't use a single resource method like this.</li>
<li>I would expect this method for retrieving a <em>list</em> of users with optional query parameters for filtering, but I would not expect <code>id</code>, <code>email</code> or any unique identifier to be among the parameters. For example: <code>GET /users?status=BANNED</code> might return a list of banned users.</li>
</ul></li>
</ol>
<p><sub>Check out <a href="https://stackoverflow.com/a/4028874/1671856">this answer</a> from a related question.</sub></p> |
20,646,171 | Can I use TypeScript overloads when using fat arrow syntax for class methods? | <p>I've converted some classes from the conventional form:</p>
<pre><code>class TestOverloads {
private status = "blah";
public doStuff(selector: JQuery);
public doStuff(selector: string);
public doStuff(selector: any) {
alert(this.status);
}
}
</code></pre>
<p>to use arrow function expressions instead:</p>
<pre><code>class TestOverloads2 {
private status = "blah";
public doStuff = (selector: any) => {
alert(this.status);
}
}
</code></pre>
<p>so as to avoid scoping problems when the class methods are used in a callback (see <a href="https://stackoverflow.com/questions/20627138/typescript-this-scoping-issue-when-called-in-jquery-callback">here</a> for background).</p>
<p>I can't work out how to recreate my overloaded function signatures though. How would I write my overloads when using the fat arrow?</p> | 20,646,788 | 2 | 1 | null | 2013-12-17 22:39:24.923 UTC | 3 | 2015-04-20 08:35:24.963 UTC | 2017-05-23 10:31:02.393 UTC | null | -1 | null | 45,031 | null | 1 | 29 | typescript|arrow-functions | 5,619 | <p>You can write an inline type literal for the call signatures the function supports:</p>
<pre><code>class TestOverloads2 {
private status = "blah";
public doStuff: {
(selector: JQuery): void;
(selector: string): void;
} = (selector: any) => {
alert(this.status);
}
}
</code></pre>
<p>That's sort of hideous, so you might want to extract it into an interface instead: </p>
<pre><code>interface SelectByJQueryOrString {
(selector: JQuery): void;
(selector: string): void;
}
class TestOverloads3 {
private status = "blah";
public doStuff: SelectByJQueryOrString = (selector: any) => {
alert(this.status);
}
}
</code></pre> |
32,467,408 | http://localhost/undefined 404 (Not Found) | <p>I was not clear in my problem description. Let me try again.</p>
<p>NB. This is a problem common to my production, staging, and development sites (not just to my delevlopment site as the commenters seem to have thought).</p>
<p>NB. This problem occurs bowsing with Chrome and not with Firefox.</p>
<p>The problem occurs at the site home page: <a href="http://www.example.com" rel="noreferrer">http://www.example.com</a> (or with "/index.php appended"). The page loads successfully, but the Console pannel of Chrome's Developer Tools shows a 404 error. The message reads "GET <a href="http://www.example/undefined" rel="noreferrer">http://www.example/undefined</a> 404 (Not Found)". It always shows the error as occuring at "(index):1" which is the DOCTYPE line. Whatever is generating the problem, it is not that.</p>
<p>The page is loading fine, I just get this odd message in the Developers Tools Console. (I probably wasn't clear about that in the original problem description.) Firfox's console shows no such error.</p>
<p>I want to track down what is generating this error. In particular, I would like to find where Chrome is getting the "undefined" url. My guess (but only a guess) is that one of my many Javascript files is genrating a URL from an undefined variable. Chrome's location of the problem, "(index):1", is wrong. I would appreciate any ideas as to how to get a more useful error message out of Chrome: the name of the file where the URL was found would help. If I can do this without having set breakpoints in all my Javascript files one by one, that would be particularly nice. :-)</p>
<p>The original question with URL's removed (I'm limited in the number of links I'm allowed with a reputation < 10) follows. You may not want to read it as people have been confused by it.</p>
<blockquote>
<p>We have rather complex Drupal website. When going to the homepage,
the Chrome (Version 45.0.2454.85 m) Console shows me an error: "[URL
removed] 404 (Not Found) (index):1". (I'm using the development site
on my local computer because minification is turned off there.)<br>
Okay, I think, I know what to do about that: Go find the offending
spot in whatever file, scratch my head a few times, get a brilliant
idea, and fix the problem. One little difficulty: the problem is
surely <strong>not</strong> occurring at index, line 1 (which I assume is what
"(index):1" means). The "undefined" in the error message suggests but
does not prove that the offender is one of our about a dozen
JavaScript files. Presumably some variable somewhere is undefined.
So how do I get Chrome to cough up the location where the offense is
occurring? It is not giving me any undefined value JavaScript errors,
just a 404 on [URL removed]/undefined . Thanks in advance for any
ideas.</p>
<p>Edit: I forgot to add that Firefox is showing no such error.</p>
</blockquote> | 36,964,874 | 5 | 4 | null | 2015-09-08 21:18:51.537 UTC | 3 | 2021-01-15 06:40:42.657 UTC | 2015-09-16 22:37:22.08 UTC | null | 3,250,335 | null | 3,250,335 | null | 1 | 18 | javascript|google-chrome|http-status-code-404|undefined | 54,463 | <p>I found where this issue could appear from.</p>
<ol>
<li>Make sure that all the generated CSS (styles) that set a background-image or the like, where there's an url() actually point somewhere; if it doesn't point anywhere the error will set to the .html DOCTYPE.</li>
<li>Check the src of your image tags; make sure that they are not set by JavaScript to undefined.</li>
<li>Also check the src of your script files, even when it'd be much rarer in that case to happen.</li>
</ol>
<p>So yes it's awful that it actually doesn't point where the actual error is but in fact has to be with a lookup resource that it isn't able to find; we probably don't even want it to search. Eg. when the element is invisible and we don't set any image; but we still pass undefined it'll search for undefined and it'll not give you any hint of in which part of the tree the error is.</p>
<p>Since your page is too complex to know where it is, or if this is even the problem you are facing; this is the most I can tell; the only reason I could find it too quick was because of react dev tools told me right away of my render properties and the fact that the component was quite small.</p> |
34,854,806 | Ansible: Permission denied (publickey, password) | <p>I'm not able to connect to a host in Ansible. This is the error:</p>
<blockquote>
<p>192.168.1.12 | UNREACHABLE! => {
"changed": false,
"msg": "ERROR! SSH encountered an unknown error during the connection. We recommend you re-run the command using -vvvv, which
will enable SSH debugging output to help diagnose the issue",
"unreachable": true }</p>
</blockquote>
<p>This is my <code>hosts</code> file:</p>
<pre><code>[test]
192.168.1.12
</code></pre>
<p>And this is the ad-hoc instruction:</p>
<pre><code>ansible all -m ping
</code></pre>
<p>I'm able to connect via raw <code>ssh</code>.</p> | 34,857,236 | 5 | 3 | null | 2016-01-18 12:28:15.677 UTC | 3 | 2019-09-11 09:28:01.37 UTC | 2016-01-18 13:03:02.7 UTC | null | 3,026,283 | null | 3,026,283 | null | 1 | 5 | ssh|ansible | 42,102 | <p>By default Ansible try to use SSH keys. It seems that you have wrong keys. Try to use Password authentication. </p>
<p><code>ansible all -m ping --ask-pass --ask-sudo-pass</code></p>
<p>I Hope it helps.</p> |
39,825,634 | How override ASP.NET Core Identity's password policy | <p>By default, ASP.NET Core Identity's password policy require at least one special character, one uppercase letter, one number, ...</p>
<p>How can I change this restrictions ? </p>
<p>There is nothing about that in the documentation (<a href="https://docs.asp.net/en/latest/security/authentication/identity.html" rel="noreferrer">https://docs.asp.net/en/latest/security/authentication/identity.html</a>)</p>
<p>I try to override the Identity's User Manager but I don't see which method manages the password policy.</p>
<pre><code>public class ApplicationUserManager : UserManager<ApplicationUser>
{
public ApplicationUserManager(
DbContextOptions<SecurityDbContext> options,
IServiceProvider services,
IHttpContextAccessor contextAccessor,
ILogger<UserManager<ApplicationUser>> logger)
: base(
new UserStore<ApplicationUser>(new SecurityDbContext(contextAccessor)),
new CustomOptions(),
new PasswordHasher<ApplicationUser>(),
new UserValidator<ApplicationUser>[] { new UserValidator<ApplicationUser>() },
new PasswordValidator[] { new PasswordValidator() },
new UpperInvariantLookupNormalizer(),
new IdentityErrorDescriber(),
services,
logger
// , contextAccessor
)
{
}
public class PasswordValidator : IPasswordValidator<ApplicationUser>
{
public Task<IdentityResult> ValidateAsync(UserManager<ApplicationUser> manager, ApplicationUser user, string password)
{
return Task.Run(() =>
{
if (password.Length >= 4) return IdentityResult.Success;
else { return IdentityResult.Failed(new IdentityError { Code = "SHORTPASSWORD", Description = "Password too short" }); }
});
}
}
public class CustomOptions : IOptions<IdentityOptions>
{
public IdentityOptions Value { get; private set; }
public CustomOptions()
{
Value = new IdentityOptions
{
ClaimsIdentity = new ClaimsIdentityOptions(),
Cookies = new IdentityCookieOptions(),
Lockout = new LockoutOptions(),
Password = null,
User = new UserOptions(),
SignIn = new SignInOptions(),
Tokens = new TokenOptions()
};
}
}
}
</code></pre>
<p>I add this user manager dependency in startup's class :</p>
<pre><code>services.AddScoped<ApplicationUserManager>();
</code></pre>
<p>But when I'm using ApplicationUserManager in controllers, I have the error :
An unhandled exception occurred while processing the request.</p>
<p><em>InvalidOperationException: Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContextOptions`1[SecurityDbContext]' while attempting to activate 'ApplicationUserManager'.</em></p>
<p><strong>EDIT:</strong> User's management works when I use the ASP.NET Core Identity's default classes, so it's not a database problem, or something like this</p>
<p><strong>EDIT 2 : I found the solution, you have just to configure Identity in the startup's class. My answer gives some details.</strong></p> | 39,826,998 | 5 | 1 | null | 2016-10-03 06:27:49.433 UTC | 17 | 2021-04-06 09:21:52.557 UTC | 2018-03-14 13:51:40.907 UTC | null | 542,251 | null | 4,428,633 | null | 1 | 66 | c#|asp.net-core-mvc|asp.net-identity|asp.net-core-identity | 42,651 | <p>It's sooooo simple in the end ...</p>
<p>No need to override any class, you have just to configure the identity settings in your startup class, like this :</p>
<pre><code>services.Configure<IdentityOptions>(options =>
{
options.Password.RequireDigit = false;
options.Password.RequiredLength = 5;
options.Password.RequireLowercase = true;
options.Password.RequireNonLetterOrDigit = true;
options.Password.RequireUppercase = false;
});
</code></pre>
<p>Or you can configure identity when you add it :</p>
<pre><code>services.AddIdentity<ApplicationUser, IdentityRole>(options=> {
options.Password.RequireDigit = false;
options.Password.RequiredLength = 4;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireUppercase = false;
options.Password.RequireLowercase = false;
})
.AddEntityFrameworkStores<SecurityDbContext>()
.AddDefaultTokenProviders();
</code></pre>
<p>AS.NET Core is definitively good stuff ...</p> |
39,136,625 | Service Worker Registration Failed | <p>I am currently working on service worker to handle push notification in browser. Currently I am having this "SW registration failed error":</p>
<blockquote>
<p>SW registration failed with error SecurityError: Failed to register a ServiceWorker: The URL protocol of the current origin ('null') is not supported.</p>
</blockquote>
<p>Check <code>client1.html</code> and <code>service-worker.js</code> file below:</p>
<p><strong>service-worker.js</strong></p>
<pre class="lang-js prettyprint-override"><code>console.log('Started', self);
self.addEventListener('install', function(event) {
self.skipWaiting();
console.log('Installed', event);
});
self.addEventListener('activate', function(event) {
console.log('Activated', event);
});
self.addEventListener('push', function(event) {
console.log('Push message received', event);
});
</code></pre>
<p><strong>client1.html</strong></p>
<pre class="lang-html prettyprint-override"><code><!doctype html>
<html>
<head>
<title>Client 1</title>
</head>
<body>
<script>
if('serviceWorker' in navigator){
// Register service worker
navigator.serviceWorker.register('service-worker.js').then(function(reg){
console.log("SW registration succeeded. Scope is "+reg.scope);
}).catch(function(err){
console.error("SW registration failed with error "+err);
});
}
</script>
</body>
</html>
</code></pre>
<p>Can anyone help with this issue?</p> | 39,136,817 | 5 | 5 | null | 2016-08-25 04:17:07.717 UTC | 2 | 2022-02-25 21:53:43.52 UTC | 2020-01-04 04:48:20.897 UTC | null | 1,366,033 | null | 4,670,317 | null | 1 | 33 | javascript|browser|service-worker|web-push | 106,477 | <p><strong>Solved:</strong>
First thing is service worker only works in secure mode either in https or localhost.
It doesnot work in local resources like file:// or http.</p>
<p>and second issue was during registration.</p>
<pre><code>navigator.serviceWorkerContainer
.register('service-worker.js')
.then(function(reg){
</code></pre> |
26,612,404 | Spring map GET request parameters to POJO automatically | <p>I have method in my REST controller that contains a lot of parameters. For example:</p>
<pre><code>@RequestMapping(value = "/getItem", method = RequestMethod.GET)
public ServiceRequest<List<SomeModel>> getClaimStatuses(
@RequestParam(value = "param1", required = true) List<String> param1,
@RequestParam(value = "param2", required = false) String param2,
@RequestParam(value = "param3", required = false) List<String> param3,
@RequestParam(value = "param4", required = false) List<String> param4,
@RequestParam(value = "param5", required = false) List<String> param5) {
// ......
}
</code></pre>
<p>and I would like to map all GET request parameters to a POJO object like:</p>
<pre><code>public class RequestParamsModel {
public RequestParamsModel() {
}
public List<String> param1;
public String param2;
public List<String> param3;
public String param4;
public String param5;
}
</code></pre>
<p>I need something like we can do using @RequestBody in REST Controller.</p>
<p><strong>Is it possible to do in Spring 3.x ?</strong></p>
<p>Thanks!</p> | 26,612,778 | 2 | 1 | null | 2014-10-28 15:37:13.297 UTC | 6 | 2019-01-18 07:22:19.887 UTC | 2017-01-22 11:49:36.28 UTC | null | 2,809,449 | null | 1,001,120 | null | 1 | 22 | java|spring|spring-mvc | 39,864 | <p>Possible and easy, make sure that your bean has proper accessors for the fields. You can add proper validation per property, just make sure that you have the proper jars in place. In terms of code it would be something like</p>
<pre><code>import javax.validation.constraints.NotNull;
public class RequestParamsModel {
public RequestParamsModel() {}
private List<String> param1;
private String param2;
private List<String> param3;
private String param4;
private String param5;
@NotNull
public List<String> getParam1() {
return param1;
}
// ...
}
</code></pre>
<p>The controller method would be:</p>
<pre><code>import javax.validation.Valid;
@RequestMapping(value = "/getItem", method = RequestMethod.GET)
public ServiceRequest<List<SomeModel>> getClaimStatuses(@Valid RequestParamsModel model) {
// ...
}
</code></pre>
<p>And the request, something like:</p>
<pre><code>/getItem?param1=list1,list2&param2=ok
</code></pre> |
19,965,838 | port 8080 is already in use and no process using 8080 has been listed | <p>I am trying to start Tomcat from Eclipse, but a problem occured: </p>
<blockquote>
<p>Port 8080 required by Tomcat v6.0 Server at localhost is already in use. The server may already be running in another process, or a system process may be using the port. To start this server you will need to stop the other process or change the port number(s).</p>
</blockquote>
<p>I tried to list processes connected to this port using command on Windows: </p>
<pre><code>netstat -aon
</code></pre>
<p>But on the listing there is no process with <code>PID = 8080</code>. I also tried: </p>
<pre><code>netstat -aon | find "8080"
</code></pre>
<p>But it also didn't find anything. Can anyone help me? </p> | 19,965,872 | 5 | 1 | null | 2013-11-13 22:33:13.5 UTC | 3 | 2022-01-26 07:34:25.09 UTC | 2017-11-26 09:21:07.587 UTC | null | 2,352,344 | null | 1,934,872 | null | 1 | 28 | java|eclipse|tomcat | 143,811 | <p>PID is the process ID - not the port number. You need to look for an entry with ":8080" at the end of the address/port part (the second column). Then you can look at the PID and use Task Manager to work out which process is involved... or run <code>netstat -abn</code> which will show the process names (but must be run under an administrator account).</p>
<p>Having said that, I <em>would</em> expect the <code>find "8080"</code> to find it...</p>
<p>Another thing to do is just visit <code>http://localhost:8080</code> - on that port, chances are it's a web server of some description.</p> |
6,549,787 | Getting started with secure AWS CloudFront streaming with Python | <p>I have created a S3 bucket, uploaded a video, created a streaming distribution in CloudFront. Tested it with a static HTML player and it works. I have created a keypair through the account settings. I have the private key file sitting on my desktop at the moment. That's where I am.</p>
<p>My aim is to get to a point where my Django/Python site creates secure URLs and people can't access the videos unless they've come from one of my pages. The problem is I'm allergic to the way Amazon have laid things out and I'm just getting more and more confused.</p>
<p>I realise this isn't going to be the best question on StackOverflow but I'm certain I can't be the only fool out here that can't make heads or tails out of how to set up a secure CloudFront/S3 situation. I would really appreciate your help and am willing (once two days has passed) give a 500pt bounty to the best answer.</p>
<p>I have several questions that, once answered, should fit into one explanation of how to accomplish what I'm after:</p>
<ul>
<li><p>In the documentation (there's an example in the next point) there's lots of XML lying around telling me I need to <code>POST</code> things to various places. Is there an online console for doing this? Or do I literally have to force this up via cURL (et al)?</p></li>
<li><p>How do I create a Origin Access Identity for CloudFront and bind it to my distribution? I've read <a href="http://docs.amazonwebservices.com/AmazonCloudFront/latest/DeveloperGuide/index.html?SecuringContent_S3.html#CreateOriginAccessIdentity">this document</a> but, per the first point, don't know what to do with it. How does my keypair fit into this?</p></li>
<li><p>Once that's done, how do I limit the S3 bucket to only allow people to download things through that identity? If this is another XML jobby rather than clicking around the web UI, please tell me where and how I'm supposed to get this into my account.</p></li>
<li><p>In Python, what's the easiest way of generating an expiring URL for a file. I have <code>boto</code> installed but I don't see how to get a file from a streaming distribution.</p></li>
<li><p>Are there are any applications or scripts that can take the difficulty of setting this garb up? I use Ubuntu (Linux) but I have XP in a VM if it's Windows-only. I've already looked at CloudBerry S3 Explorer Pro - but it makes about as much sense as the online UI.</p></li>
</ul> | 6,590,986 | 2 | 2 | null | 2011-07-01 15:10:28.95 UTC | 31 | 2016-03-15 12:11:22.457 UTC | null | null | null | null | 12,870 | null | 1 | 42 | python|amazon-s3|amazon-web-services|amazon-cloudfront | 17,706 | <p>You're right, it takes a lot of API work to get this set up. I hope they get it in the AWS Console soon!</p>
<p><strong>UPDATE: I have submitted this code to boto - as of boto v2.1 (released 2011-10-27) this gets much easier. For boto < 2.1, use the instructions here. For boto 2.1 or greater, get the updated instructions on my blog: <a href="http://www.secretmike.com/2011/10/aws-cloudfront-secure-streaming.html" rel="noreferrer">http://www.secretmike.com/2011/10/aws-cloudfront-secure-streaming.html</a> Once boto v2.1 gets packaged by more distros I'll update the answer here.</strong></p>
<p>To accomplish what you want you need to perform the following steps which I will detail below:</p>
<ol>
<li>Create your s3 bucket and upload some objects (you've already done this)</li>
<li>Create a Cloudfront "Origin Access Identity" (basically an AWS account to allow cloudfront to access your s3 bucket)</li>
<li>Modify the ACLs on your objects so that only your Cloudfront Origin Access Identity is allowed to read them (this prevents people from bypassing Cloudfront and going direct to s3)</li>
<li>Create a cloudfront distribution with basic URLs and one which requires signed URLs</li>
<li>Test that you can download objects from basic cloudfront distribution but not from s3 or the signed cloudfront distribution</li>
<li>Create a key pair for signing URLs</li>
<li>Generate some URLs using Python</li>
<li>Test that the signed URLs work</li>
</ol>
<hr>
<p><strong>1 - Create Bucket and upload object</strong></p>
<p>The easiest way to do this is through the AWS Console but for completeness I'll show how using boto. Boto code is shown here:</p>
<pre><code>import boto
#credentials stored in environment AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY
s3 = boto.connect_s3()
#bucket name MUST follow dns guidelines
new_bucket_name = "stream.example.com"
bucket = s3.create_bucket(new_bucket_name)
object_name = "video.mp4"
key = bucket.new_key(object_name)
key.set_contents_from_filename(object_name)
</code></pre>
<p><strong>2 - Create a Cloudfront "Origin Access Identity"</strong></p>
<p>For now, this step can only be performed using the API. Boto code is here:</p>
<pre><code>import boto
#credentials stored in environment AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY
cf = boto.connect_cloudfront()
oai = cf.create_origin_access_identity(comment='New identity for secure videos')
#We need the following two values for later steps:
print("Origin Access Identity ID: %s" % oai.id)
print("Origin Access Identity S3CanonicalUserId: %s" % oai.s3_user_id)
</code></pre>
<p><strong>3 - Modify the ACLs on your objects</strong></p>
<p>Now that we've got our special S3 user account (the S3CanonicalUserId we created above) we need to give it access to our s3 objects. We can do this easily using the AWS Console by opening the object's (not the bucket's!) Permissions tab, click the "Add more permissions" button, and pasting the very long S3CanonicalUserId we got above into the "Grantee" field of a new. Make sure you give the new permission "Open/Download" rights.</p>
<p>You can also do this in code using the following boto script:</p>
<pre><code>import boto
#credentials stored in environment AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY
s3 = boto.connect_s3()
bucket_name = "stream.example.com"
bucket = s3.get_bucket(bucket_name)
object_name = "video.mp4"
key = bucket.get_key(object_name)
#Now add read permission to our new s3 account
s3_canonical_user_id = "<your S3CanonicalUserID from above>"
key.add_user_grant("READ", s3_canonical_user_id)
</code></pre>
<p><strong>4 - Create a cloudfront distribution</strong></p>
<p>Note that custom origins and private distributions are not fully supported in boto until version 2.0 which has not been formally released at time of writing. The code below pulls out some code from the boto 2.0 branch and hacks it together to get it going but it's not pretty. The 2.0 branch handles this much more elegantly - definitely use that if possible!</p>
<pre><code>import boto
from boto.cloudfront.distribution import DistributionConfig
from boto.cloudfront.exception import CloudFrontServerError
import re
def get_domain_from_xml(xml):
results = re.findall("<DomainName>([^<]+)</DomainName>", xml)
return results[0]
#custom class to hack this until boto v2.0 is released
class HackedStreamingDistributionConfig(DistributionConfig):
def __init__(self, connection=None, origin='', enabled=False,
caller_reference='', cnames=None, comment='',
trusted_signers=None):
DistributionConfig.__init__(self, connection=connection,
origin=origin, enabled=enabled,
caller_reference=caller_reference,
cnames=cnames, comment=comment,
trusted_signers=trusted_signers)
#override the to_xml() function
def to_xml(self):
s = '<?xml version="1.0" encoding="UTF-8"?>\n'
s += '<StreamingDistributionConfig xmlns="http://cloudfront.amazonaws.com/doc/2010-07-15/">\n'
s += ' <S3Origin>\n'
s += ' <DNSName>%s</DNSName>\n' % self.origin
if self.origin_access_identity:
val = self.origin_access_identity
s += ' <OriginAccessIdentity>origin-access-identity/cloudfront/%s</OriginAccessIdentity>\n' % val
s += ' </S3Origin>\n'
s += ' <CallerReference>%s</CallerReference>\n' % self.caller_reference
for cname in self.cnames:
s += ' <CNAME>%s</CNAME>\n' % cname
if self.comment:
s += ' <Comment>%s</Comment>\n' % self.comment
s += ' <Enabled>'
if self.enabled:
s += 'true'
else:
s += 'false'
s += '</Enabled>\n'
if self.trusted_signers:
s += '<TrustedSigners>\n'
for signer in self.trusted_signers:
if signer == 'Self':
s += ' <Self/>\n'
else:
s += ' <AwsAccountNumber>%s</AwsAccountNumber>\n' % signer
s += '</TrustedSigners>\n'
if self.logging:
s += '<Logging>\n'
s += ' <Bucket>%s</Bucket>\n' % self.logging.bucket
s += ' <Prefix>%s</Prefix>\n' % self.logging.prefix
s += '</Logging>\n'
s += '</StreamingDistributionConfig>\n'
return s
def create(self):
response = self.connection.make_request('POST',
'/%s/%s' % ("2010-11-01", "streaming-distribution"),
{'Content-Type' : 'text/xml'},
data=self.to_xml())
body = response.read()
if response.status == 201:
return body
else:
raise CloudFrontServerError(response.status, response.reason, body)
cf = boto.connect_cloudfront()
s3_dns_name = "stream.example.com.s3.amazonaws.com"
comment = "example streaming distribution"
oai = "<OAI ID from step 2 above like E23KRHS6GDUF5L>"
#Create a distribution that does NOT need signed URLS
hsd = HackedStreamingDistributionConfig(connection=cf, origin=s3_dns_name, comment=comment, enabled=True)
hsd.origin_access_identity = oai
basic_dist = hsd.create()
print("Distribution with basic URLs: %s" % get_domain_from_xml(basic_dist))
#Create a distribution that DOES need signed URLS
hsd = HackedStreamingDistributionConfig(connection=cf, origin=s3_dns_name, comment=comment, enabled=True)
hsd.origin_access_identity = oai
#Add some required signers (Self means your own account)
hsd.trusted_signers = ['Self']
signed_dist = hsd.create()
print("Distribution with signed URLs: %s" % get_domain_from_xml(signed_dist))
</code></pre>
<p><strong>5 - Test that you can download objects from cloudfront but not from s3</strong></p>
<p>You should now be able to verify:</p>
<ul>
<li>stream.example.com.s3.amazonaws.com/video.mp4 - should give AccessDenied</li>
<li>signed_distribution.cloudfront.net/video.mp4 - should give MissingKey (because the URL is not signed)</li>
<li>basic_distribution.cloudfront.net/video.mp4 - should work fine</li>
</ul>
<p>The tests will have to be adjusted to work with your stream player, but the basic idea is that only the basic cloudfront url should work.</p>
<p><strong>6 - Create a keypair for CloudFront</strong></p>
<p>I think the only way to do this is through Amazon's web site. Go into your AWS "Account" page and click on the "Security Credentials" link. Click on the "Key Pairs" tab then click "Create a New Key Pair". This will generate a new key pair for you and automatically download a private key file (pk-xxxxxxxxx.pem). Keep the key file safe and private. Also note down the "Key Pair ID" from amazon as we will need it in the next step.</p>
<p><strong>7 - Generate some URLs in Python</strong></p>
<p>As of boto version 2.0 there does not seem to be any support for generating signed CloudFront URLs. Python does not include RSA encryption routines in the standard library so we will have to use an additional library. I've used M2Crypto in this example.</p>
<p>For a non-streaming distribution, you must use the full cloudfront URL as the resource, however for streaming we only use the object name of the video file. See the code below for a full example of generating a URL which only lasts for 5 minutes.</p>
<p>This code is based loosely on the PHP example code provided by Amazon in the CloudFront documentation.</p>
<pre><code>from M2Crypto import EVP
import base64
import time
def aws_url_base64_encode(msg):
msg_base64 = base64.b64encode(msg)
msg_base64 = msg_base64.replace('+', '-')
msg_base64 = msg_base64.replace('=', '_')
msg_base64 = msg_base64.replace('/', '~')
return msg_base64
def sign_string(message, priv_key_string):
key = EVP.load_key_string(priv_key_string)
key.reset_context(md='sha1')
key.sign_init()
key.sign_update(str(message))
signature = key.sign_final()
return signature
def create_url(url, encoded_signature, key_pair_id, expires):
signed_url = "%(url)s?Expires=%(expires)s&Signature=%(encoded_signature)s&Key-Pair-Id=%(key_pair_id)s" % {
'url':url,
'expires':expires,
'encoded_signature':encoded_signature,
'key_pair_id':key_pair_id,
}
return signed_url
def get_canned_policy_url(url, priv_key_string, key_pair_id, expires):
#we manually construct this policy string to ensure formatting matches signature
canned_policy = '{"Statement":[{"Resource":"%(url)s","Condition":{"DateLessThan":{"AWS:EpochTime":%(expires)s}}}]}' % {'url':url, 'expires':expires}
#now base64 encode it (must be URL safe)
encoded_policy = aws_url_base64_encode(canned_policy)
#sign the non-encoded policy
signature = sign_string(canned_policy, priv_key_string)
#now base64 encode the signature (URL safe as well)
encoded_signature = aws_url_base64_encode(signature)
#combine these into a full url
signed_url = create_url(url, encoded_signature, key_pair_id, expires);
return signed_url
def encode_query_param(resource):
enc = resource
enc = enc.replace('?', '%3F')
enc = enc.replace('=', '%3D')
enc = enc.replace('&', '%26')
return enc
#Set parameters for URL
key_pair_id = "APKAIAZCZRKVIO4BQ" #from the AWS accounts page
priv_key_file = "cloudfront-pk.pem" #your private keypair file
resource = 'video.mp4' #your resource (just object name for streaming videos)
expires = int(time.time()) + 300 #5 min
#Create the signed URL
priv_key_string = open(priv_key_file).read()
signed_url = get_canned_policy_url(resource, priv_key_string, key_pair_id, expires)
#Flash player doesn't like query params so encode them
enc_url = encode_query_param(signed_url)
print(enc_url)
</code></pre>
<p><strong>8 - Try out the URLs</strong></p>
<p>Hopefully you should now have a working URL which looks something like this:</p>
<pre><code>video.mp4%3FExpires%3D1309979985%26Signature%3DMUNF7pw1689FhMeSN6JzQmWNVxcaIE9mk1x~KOudJky7anTuX0oAgL~1GW-ON6Zh5NFLBoocX3fUhmC9FusAHtJUzWyJVZLzYT9iLyoyfWMsm2ylCDBqpy5IynFbi8CUajd~CjYdxZBWpxTsPO3yIFNJI~R2AFpWx8qp3fs38Yw_%26Key-Pair-Id%3DAPKAIAZRKVIO4BQ
</code></pre>
<p>Put this into your js and you should have something which looks like this (from the PHP example in Amazon's CloudFront documentation):</p>
<pre><code>var so_canned = new SWFObject('http://location.domname.com/~jvngkhow/player.swf','mpl','640','360','9');
so_canned.addParam('allowfullscreen','true');
so_canned.addParam('allowscriptaccess','always');
so_canned.addParam('wmode','opaque');
so_canned.addVariable('file','video.mp4%3FExpires%3D1309979985%26Signature%3DMUNF7pw1689FhMeSN6JzQmWNVxcaIE9mk1x~KOudJky7anTuX0oAgL~1GW-ON6Zh5NFLBoocX3fUhmC9FusAHtJUzWyJVZLzYT9iLyoyfWMsm2ylCDBqpy5IynFbi8CUajd~CjYdxZBWpxTsPO3yIFNJI~R2AFpWx8qp3fs38Yw_%26Key-Pair-Id%3DAPKAIAZRKVIO4BQ');
so_canned.addVariable('streamer','rtmp://s3nzpoyjpct.cloudfront.net/cfx/st');
so_canned.write('canned');
</code></pre>
<hr>
<p><strong>Summary</strong></p>
<p>As you can see, not very easy! boto v2 will help a lot setting up the distribution. I will find out if it's possible to get some URL generation code in there as well to improve this great library!</p> |
7,448,944 | Determining a website's 'root' location | <p>I need some help with concepts and terminology regarding website 'root' urls and directories.</p>
<p>Is it possible to determine a website's root, or is that an arbitrary idea, and only the actual server's root can be established?</p>
<p>Let's say I'm writing a PHP plugin that that will be used by different websites in different locations, but needs to determine what the website's base directory is. Using PHP, I will always be able to determine the DOCUMENT_ROOT and SERVER_NAME, that is, the absolute URL and absolute directory path of the server (or virtual server). But I can't know if the website itself is 'installed' at the root directory or in a sub directory. If the website was in a subdirectory, I would need the user to explicitly set an "sub-path" variable. Correct?</p> | 7,449,035 | 4 | 2 | null | 2011-09-16 18:33:04.307 UTC | 3 | 2015-05-08 11:29:11.573 UTC | 2011-09-16 19:18:31.957 UTC | null | 165,673 | null | 165,673 | null | 1 | 6 | php|path|document-root|base-url | 55,345 | <p>Answer to question 1: Yes you need a variable which explicitly sets the root path of the website. It can be done with an htaccess file at the root of each website containing the following line :</p>
<pre><code>SetEnv APP_ROOT_PATH /path/to/app
</code></pre>
<p><a href="http://httpd.apache.org/docs/2.0/mod/mod_env.html" rel="noreferrer">http://httpd.apache.org/docs/2.0/mod/mod_env.html</a></p>
<p>And you can access it anywhere in your php script by using :</p>
<pre><code><?php $appRootPath = getenv('APP_ROOT_PATH'); ?>
</code></pre>
<p><a href="http://php.net/manual/en/function.getenv.php" rel="noreferrer">http://php.net/manual/en/function.getenv.php</a></p> |
7,551,635 | Eclipse: How to get TODOs from SQL and XML files in tasks | <p>In Java files I can write TODO comments and they show up in the Tasks window.</p>
<pre><code>// TODO: Do something about this
</code></pre>
<p>However, when I write TODO comments in for example SQL scripts and XML files, they don't show up. Is there a way I can get them to do that? For example:</p>
<pre><code>-- TODO: Fix this SQL query
<!-- TODO: Fix this XML -->
</code></pre> | 7,553,917 | 4 | 0 | null | 2011-09-26 07:04:35.467 UTC | 3 | 2017-04-10 12:33:08.177 UTC | null | null | null | null | 39,321 | null | 1 | 29 | sql|xml|eclipse|comments|todo | 5,662 | <p>Check your main Preference dialog for Task Tags pages. Type "task" into the search box in the upper left of the dialog to help you find relevant pages. For XML files, I know that that feature is off by default.</p> |
2,182,596 | Remove first character from a string if it is a comma | <p>I need to setup a function in javascript to remove the first character of a string but only if it is a comma <code>,</code>. I've found the <code>substr</code> function but this will remove anything regardless of what it is. </p>
<p>My current code is</p>
<pre><code>text.value = newvalue.substr(1);
</code></pre> | 2,182,602 | 4 | 2 | null | 2010-02-02 08:07:29.603 UTC | 9 | 2017-11-10 16:03:13.003 UTC | 2016-06-21 18:30:15.827 UTC | null | 445,131 | null | 216,790 | null | 1 | 49 | javascript|regex|string | 66,099 | <pre><code>text.value = newvalue.replace(/^,/, '');
</code></pre>
<p>Edit: Tested and true. This is just <em>one</em> way to do it, though.</p> |
10,761,894 | Does Chrome have a built-in Call Stack? | <p>From Visual Studio, I'm accustomed to a call stack showing up at any breakpoint. Does Chrome have a call stack feature where I can see what functions preceded my breakpoint?</p>
<p>If not, is there a substitute (3rd party solution that works with Chrome?) that developers use to see what functions led to a breakpoint?</p>
<p>Edit: to be clear, I was expecting the call stack to appear within the javascript console in Chrome.</p> | 10,762,279 | 3 | 2 | null | 2012-05-25 22:08:47.493 UTC | 8 | 2018-04-30 07:18:17.643 UTC | 2012-05-25 23:00:10.637 UTC | null | 327,547 | null | 327,547 | null | 1 | 44 | javascript|google-chrome|browser|google-chrome-devtools|callstack | 38,798 | <p>I don't know what version of Chrome you're using. I'm using Chromium 17 and the Javascript debugger looks like this when hitting a breakpoint (emphasis mine):
<img src="https://i.stack.imgur.com/CJhtG.png" alt="Chromium call stack"></p> |
36,294,109 | How to check if a Promise is pending | <p>I have this situation in which I would like to know what the status is of a promise. Below, the function <code>start</code> only calls <code>someTest</code> if it is not running anymore (Promise is not pending). The <code>start</code> function can be called many times, but if its called while the tests are still running, its not going to wait and returns just <code>false</code></p>
<pre><code>class RunTest {
start() {
retVal = false;
if (!this.promise) {
this.promise = this.someTest();
retVal = true;
}
if ( /* if promise is resolved/rejected or not pending */ ) {
this.promise = this.someTest();
retVal = true;
}
return retVal;
}
someTest() {
return new Promise((resolve, reject) => {
// some tests go inhere
});
}
}
</code></pre>
<p>I cannot find a way to simply check the status of a promise. Something like <code>this.promise.isPending</code> would be nice :) Any help would be appreciated!</p> | 36,294,256 | 2 | 7 | null | 2016-03-29 20:04:42.61 UTC | 11 | 2016-03-29 21:15:43.317 UTC | 2016-03-29 20:18:39.547 UTC | null | 3,887,516 | null | 419,425 | null | 1 | 61 | javascript|promise|ecmascript-6|es6-promise | 86,864 | <p>You can attach a <code>then</code> handler that sets a <code>done</code> flag on the promise (or the <code>RunTest</code> instance if you prefer), and test that:</p>
<pre><code> if (!this.promise) {
this.promise = this.someTest();
this.promise.catch(() => {}).then(() => { this.promise.done = true; });
retVal = true;
}
if ( this.promise.done ) {
this.promise = this.someTest();
this.promise.catch(() => {}).then(() => { this.promise.done = true; });
retVal = true;
}
</code></pre>
<p>Notice the empty <code>catch()</code> handler, it's crucial in order to have the handler called regardless of the outcome of the promise.
You probably want to wrap that in a function though to keep the code DRY.</p> |
7,526,971 | How to redirect both stdout and stderr to a file | <p>I am running a bash script that creates a log file for the execution of the command</p>
<p>I use the following</p>
<pre><code>Command1 >> log_file
Command2 >> log_file
</code></pre>
<p>This only sends the standard output and not the standard error which appears on the terminal.</p> | 7,526,988 | 5 | 0 | null | 2011-09-23 09:35:45.347 UTC | 84 | 2021-12-15 12:48:19.763 UTC | 2021-12-15 12:48:19.763 UTC | null | 418,150 | null | 525,376 | null | 1 | 349 | bash|stdout|io-redirection|stderr | 255,066 | <p>If you want to log to the same file:</p>
<pre><code>command1 >> log_file 2>&1
</code></pre>
<p>If you want different files:</p>
<pre><code>command1 >> log_file 2>> err_file
</code></pre> |
7,411,717 | Why do package names often begin with "com" | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/2125293/java-packages-com-and-org">Java packages com and org</a> </p>
</blockquote>
<p>I am a java developer. Nowadays I am learning struts and when reading a tutorial a curiosity intruded in my mind regarding </p>
<pre><code>package com.something.something;
</code></pre>
<p>I know it is a very simple package declaration but what about</p>
<pre><code>package **com**.something.something;
</code></pre>
<p>This package name fragment often comes in many commercial distributions. Now I want to know what does it mean? Please clarify it.</p>
<p>Thanks and sorry if I couldn't clarify it...</p> | 7,411,742 | 6 | 6 | null | 2011-09-14 05:36:25.003 UTC | 10 | 2018-12-24 18:59:48.913 UTC | 2018-12-24 18:59:48.913 UTC | null | 3,160,529 | null | 934,418 | null | 1 | 46 | java|package | 109,602 | <p>It's just a namespace definition to avoid collision of class names. The <code>com.domain.package.Class</code> is an established Java convention wherein the namespace is qualified with the company domain in reverse.</p> |
7,172,784 | How do I POST JSON data with cURL? | <p>I use Ubuntu and installed <a href="https://en.wikipedia.org/wiki/CURL" rel="noreferrer">cURL</a> on it. I want to test my Spring REST application with cURL. I wrote my POST code at the Java side. However, I want to test it with cURL. I am trying to post a JSON data. Example data is like this:</p>
<pre><code>{"value":"30","type":"Tip 3","targetModule":"Target 3","configurationGroup":null,"name":"Configuration Deneme 3","description":null,"identity":"Configuration Deneme 3","version":0,"systemId":3,"active":true}
</code></pre>
<p>I use this command:</p>
<pre><code>curl -i \
-H "Accept: application/json" \
-H "X-HTTP-Method-Override: PUT" \
-X POST -d "value":"30","type":"Tip 3","targetModule":"Target 3","configurationGroup":null,"name":"Configuration Deneme 3","description":null,"identity":"Configuration Deneme 3","version":0,"systemId":3,"active":true \
http://localhost:8080/xx/xxx/xxxx
</code></pre>
<p>It returns this error:</p>
<pre><code>HTTP/1.1 415 Unsupported Media Type
Server: Apache-Coyote/1.1
Content-Type: text/html;charset=utf-8
Content-Length: 1051
Date: Wed, 24 Aug 2011 08:50:17 GMT
</code></pre>
<p>The error description is this:</p>
<blockquote>
<p><em>The server refused this request because the request entity is in a format not supported by the requested resource for the requested method ().</em></p>
</blockquote>
<p>Tomcat log:
"POST /ui/webapp/conf/clear HTTP/1.1" 415 1051</p>
<p>What is the right format of the cURL command?</p>
<p>This is my Java side <code>PUT</code> code (I have tested GET and DELETE and they work):</p>
<pre><code>@RequestMapping(method = RequestMethod.PUT)
public Configuration updateConfiguration(HttpServletResponse response, @RequestBody Configuration configuration) { //consider @Valid tag
configuration.setName("PUT worked");
//todo If error occurs response.sendError(HttpServletResponse.SC_NOT_FOUND);
return configuration;
}
</code></pre> | 7,173,011 | 28 | 2 | null | 2011-08-24 08:51:11.793 UTC | 807 | 2022-04-22 17:24:40.167 UTC | 2020-01-14 00:25:00.933 UTC | null | 5,780,109 | null | 453,596 | null | 1 | 3,564 | json|rest|spring-mvc|curl|http-headers | 3,879,707 | <p>You need to set your content-type to application/json. But <a href="https://curl.haxx.se/docs/manpage.html#-d" rel="noreferrer"><code>-d</code></a> (or <code>--data</code>) sends the Content-Type <code>application/x-www-form-urlencoded</code>, which is not accepted on Spring's side.</p>
<p>Looking at the <a href="https://curl.haxx.se/docs/manpage.html" rel="noreferrer">curl man page</a>, I think you can use <a href="https://curl.haxx.se/docs/manpage.html#-H" rel="noreferrer"><code>-H</code></a> (or <code>--header</code>):</p>
<pre><code>-H "Content-Type: application/json"
</code></pre>
<p>Full example:</p>
<pre><code>curl --header "Content-Type: application/json" \
--request POST \
--data '{"username":"xyz","password":"xyz"}' \
http://localhost:3000/api/login
</code></pre>
<p>(<code>-H</code> is short for <code>--header</code>, <code>-d</code> for <code>--data</code>)</p>
<p>Note that <code>-request POST</code> is <em>optional</em> if you use <code>-d</code>, as the <code>-d</code> flag implies a POST request.</p>
<hr />
<p>On Windows, things are slightly different. See the comment thread.</p> |
14,088,714 | Regular expression for name field in javascript validation | <p>i need a regular expression in javascript validation.
Regular expression for name field that will accept alphabets and only space character between words and total characters in the field should be in between 2 and 30. i.e., the field should accept min 2 chars and max of 30 chars</p> | 14,088,769 | 3 | 3 | null | 2012-12-30 06:09:11.9 UTC | 4 | 2020-09-07 06:57:38.667 UTC | 2018-11-09 15:07:27.753 UTC | null | 4,969,058 | null | 1,179,752 | null | 1 | 7 | javascript | 102,574 | <pre><code>function validate(id) {
var regex = /^[a-zA-Z ]{2,30}$/;
var ctrl = document.getElemetnById(id);
return regex.test(ctrl.value);
}
</code></pre> |
13,837,258 | What is an appropriate data type to store a timezone? | <p>I'm thinking of simply using a string in the format "+hh:mm" (or "-hh:mm"). Is this both necessary and sufficient?</p>
<p>Note: I don't need to store the date or the time, just the timezone.</p> | 13,838,848 | 5 | 0 | null | 2012-12-12 10:04:05.17 UTC | 7 | 2019-05-27 07:30:37.057 UTC | null | null | null | null | 331,393 | null | 1 | 37 | postgresql|datetime|timezone|sqldatatypes | 22,676 | <p>Unfortunately PostgreSQL doesn't offer a time zone data type, so you should probably use <code>text</code>.</p>
<p><code>interval</code> seems like a logical option at first glance, and it <em>is</em> appropriate for some uses. However, it fails to consider daylight savings time, nor does it consider the fact that different regions in the same UTC offset have different DST rules. </p>
<p>There is not a 1:1 mapping from UTC offset back to time zone.</p>
<p>For example, the time zone for <code>Australia/Sydney</code> (New South Wales) is <code>UTC+10</code> (<code>EST</code>), or <code>UTC+11</code> (<code>EDT</code>) during daylight savings time. Yes, that's the same acronym <code>EST</code> that the USA uses; time zone acronyms are non-unique in the tzdata database, which is why Pg has the <code>timezone_abbreviations</code> setting. Worse, Brisbane (Queensland) is at almost the same longditude and is in <code>UTC+10 EST</code> ... but doesn't have daylight savings, so sometime it's at a <code>-1</code> offset to New South Wales during NSW's DST.</p>
<p>(<em>Update</em>: More recently Australia adopted an <code>A</code> prefix, so it uses <code>AEST</code> as its eastern states TZ acronym, but <code>EST</code> and <code>WST</code> remain in common use).</p>
<p>Confusing much?</p>
<p>If all you need to store is a <em>UTC offset</em> then an <code>interval</code> is appropriate. If you want to store a <em>time zone</em>, store it as <code>text</code>. It's a pain to validate and to convert to a time zone offset at the moment, but at least it copes with DST.</p> |
14,323,872 | Using forked package import in Go | <p>Suppose you have a repository at <code>github.com/someone/repo</code> and you fork it to <code>github.com/you/repo</code>. You want to use your fork instead of the main repo, so you do a</p>
<pre><code>go get github.com/you/repo
</code></pre>
<p>Now all the import paths in this repo will be "broken", meaning, if there are multiple packages in the repository that reference each other via absolute URLs, they will reference the source, not the fork.</p>
<p>Is there a better way as cloning it manually into the right path?</p>
<pre><code>git clone [email protected]:you/repo.git $GOPATH/src/github.com/someone/repo
</code></pre> | 56,792,766 | 12 | 9 | null | 2013-01-14 17:53:51.24 UTC | 46 | 2022-05-20 11:36:33.297 UTC | 2013-01-14 21:44:02.99 UTC | user187676 | null | user187676 | null | null | 1 | 133 | go | 34,147 | <p>If you are using <a href="https://github.com/golang/go/wiki/Modules" rel="noreferrer">go modules</a>. You could use <a href="https://github.com/golang/go/wiki/Modules#when-should-i-use-the-replace-directive" rel="noreferrer"><code>replace</code></a> directive</p>
<blockquote>
<p>The <code>replace</code> directive allows you to supply another import path that might
be another module located in VCS (GitHub or elsewhere), or on your
local filesystem with a relative or absolute file path. The new import
path from the <code>replace</code> directive is used without needing to update the
import paths in the actual source code.</p>
</blockquote>
<p>So you could do below in your go.mod file</p>
<pre><code>module some-project
go 1.12
require (
github.com/someone/repo v1.20.0
)
replace github.com/someone/repo => github.com/you/repo v3.2.1
</code></pre>
<p>where <code>v3.2.1</code> is tag on your repo. Also can be done through CLI</p>
<pre><code>go mod edit -replace="github.com/someone/[email protected]=github.com/you/[email protected]"
</code></pre> |
29,250,016 | Gulp Watch only run once | <p>I'm using this Gulp Watch sample: <a href="https://github.com/floatdrop/gulp-watch/blob/master/docs/readme.md#starting-tasks-on-events">https://github.com/floatdrop/gulp-watch/blob/master/docs/readme.md#starting-tasks-on-events</a>.</p>
<pre><code>var gulp = require('gulp');
var watch = require('gulp-watch');
var batch = require('gulp-batch');
gulp.task('build', function () { console.log('Working!'); });
gulp.task('watch', function () {
watch('**/*.js', batch(function () {
gulp.start('build');
}));
});
</code></pre>
<p>When I run it on my Windows 8 machine, it only runs the first time I change a file:</p>
<pre><code>C:\test>gulp watch
[08:40:21] Using gulpfile C:\test\gulpfile.js
[08:40:21] Starting 'watch'...
[08:40:21] Finished 'watch' after 2.69 ms
[08:40:31] Starting 'build'...
Working!
[08:40:31] Finished 'build' after 261 µs
</code></pre>
<p>Next time nothing happens. Why?</p> | 29,345,447 | 5 | 3 | null | 2015-03-25 07:45:16.073 UTC | 4 | 2022-03-29 14:14:40.29 UTC | null | null | null | null | 617,413 | null | 1 | 31 | gulp|gulp-watch | 14,596 | <p>If you read the documentation closely, you see the following phrase:</p>
<blockquote>
<p>You can pass plain callback, that will be called on every event <strong>or wrap it in gulp-batch to run it <em>once</em></strong></p>
</blockquote>
<p>So, that's basically the deal with <code>gulp-batch</code>. To constantly watch it, just remove the batch call:</p>
<pre><code>gulp.task('build', function (done) {
console.log('Working!');
done();
});
gulp.task('watch', function () {
watch('app/*.js', function () {
gulp.start('build');
});
});
</code></pre>
<p>(and add the 'done' callback to <code>build</code> to let Gulp know when you're finished).</p>
<p>Btw... I'm not sure, but I think <code>gulp-watch</code> is meant to not only watch files, but also directly returning a vinyl object. So actually using the built-in <code>gulp.watch</code> should have the same effect:</p>
<pre><code>gulp.task('watch', function () {
gulp.watch('app/**/*.js', ['build']);
});
</code></pre> |
65,559,153 | Is Kotlin Flow's Collect is only internal kotlinx.coroutines API? | <p>Taking the direct example from <a href="https://kotlinlang.org/docs/reference/coroutines/flow.html#flows-are-cold" rel="noreferrer">https://kotlinlang.org/docs/reference/coroutines/flow.html#flows-are-cold</a></p>
<pre><code>fun simple(): Flow<Int> = flow {
println("Flow started")
for (i in 1..3) {
delay(100)
emit(i)
}
}
fun main() = runBlocking<Unit> {
println("Calling simple function...")
val flow = simple()
println("Calling collect...")
flow.collect { value -> println(value) }
println("Calling collect again...")
flow.collect { value -> println(value) }
}
</code></pre>
<p>I got the error on <code>collect</code>.</p>
<pre><code>This is an internal kotlinx.coroutines API that should not be used from outside of kotlinx.coroutines. No compatibility guarantees are provided.It is recommended to report your use-case of internal API to kotlinx.coroutines issue tracker, so stable API could be provided instead
</code></pre>
<p>When I add <code>@InternalCoroutinesApi</code></p>
<pre><code>@InternalCoroutinesApi
fun main() = runBlocking<Unit> {
println("Calling simple function...")
val flow = simple()
println("Calling collect...")
flow.collect { value -> println(value) }
println("Calling collect again...")
flow.collect { value -> println(value) }
}
</code></pre>
<p>I get an error in the <code>collect</code>'s lambda (function of <code>value -> println(value</code>) as below</p>
<pre><code>Type mismatch.
Required:
FlowCollector<Int>
Found:
([ERROR : ]) → Unit
Cannot infer a type for this parameter. Please specify it explicitly.
</code></pre>
<p>I am using Kotlin version 1.4.21.</p>
<pre><code> implementation "org.jetbrains.kotlin:kotlin-stdlib:1.4.2"
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.4.2'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.4.1'
testImplementation 'org.jetbrains.kotlinx:kotlinx-coroutines-test:1.4.2'
</code></pre>
<p>Did I do anything wrong that I cannot compile the example code in Android Studio?</p> | 65,560,100 | 6 | 3 | null | 2021-01-04 07:38:32.5 UTC | 11 | 2022-07-04 10:47:12.487 UTC | null | null | null | null | 3,286,489 | null | 1 | 67 | kotlin|kotlin-flow | 11,036 | <p>The answer is, NO, <code>collect</code> is not only internal kotlinx.coroutines API. The error message is misleading.</p>
<p>As per @ir42's comment, <code>add import kotlinx.coroutines.flow.collect </code> solve the problem.</p>
<p><strong>Additional info, why I didn't pick <code>collectLatest</code> as the answer</strong></p>
<p><code>collect</code> and <code>collectLatest</code> is different.</p>
<p>Using this example</p>
<pre><code>fun simple(): Flow<Int> = flow { // flow builder
for (i in 1..3) {
delay(100) // pretend we are doing something useful here
emit(i) // emit next value
}
}
fun main() = runBlocking<Unit> {
// Launch a concurrent coroutine to check if the main thread is blocked
launch {
for (k in 1..3) {
println("I'm not blocked $k")
delay(100)
}
}
// Collect the flow
simple().collect { value -> println(value) }
}
</code></pre>
<p>Collect will produce</p>
<pre><code>I'm not blocked 1
1
I'm not blocked 2
2
I'm not blocked 3
3
</code></pre>
<p>as per <a href="https://kotlinlang.org/docs/reference/coroutines/flow.html" rel="noreferrer">https://kotlinlang.org/docs/reference/coroutines/flow.html</a></p>
<p>But <code>collectLatest</code></p>
<pre><code>fun simple(): Flow<Int> = flow { // flow builder
for (i in 1..3) {
delay(100) // pretend we are doing something useful here
emit(i) // emit next value
}
}
fun main() = runBlocking<Unit> {
// Launch a concurrent coroutine to check if the main thread is blocked
launch {
for (k in 1..3) {
println("I'm not blocked $k")
delay(100)
}
}
// Collect the flow
simple().collectLatest { value -> println(value) }
}
</code></pre>
<p>will produce</p>
<pre><code>I'm not blocked 1
I'm not blocked 2
1
I'm not blocked 3
2
</code></pre> |
52,339,221 | Rails - Gem Error while installing pg (1.1.3), and Bundler cannot continue | <p>I am still fairly new to Rails. I am trying to push to Heroku and I am getting errors.</p>
<p>The first error is when I run a Bundle Install I get this error message:</p>
<blockquote>
<p>"An error occurred while installing pg (1.1.3), and Bundler cannot continue.
Make sure that <code>gem install pg -v '1.1.3'</code> succeeds before bundling."</p>
</blockquote>
<p>I have tried to run this command</p>
<pre><code>gem install pg -v '1.1.3'
</code></pre>
<p>But it fails and gives me this error message:</p>
<blockquote>
<p>"ERROR: Error installing pg:
ERROR: Failed to build gem native extension."</p>
</blockquote>
<p>Does anyone have a solution to this?</p> | 52,342,295 | 8 | 6 | null | 2018-09-14 21:08:40.82 UTC | 3 | 2022-01-07 22:50:11.98 UTC | 2021-02-19 10:04:36.45 UTC | null | 12,340,179 | null | 10,316,768 | null | 1 | 32 | ruby-on-rails | 40,338 | <p>try instaling with pg-config like this:<br>
<code>gem install pg -v 1.1.3 -- --with-pg-config=/usr/pgsql-9.X/bin/pg_config</code>. </p>
<p>In pg-config path mention the posgtres version installed in you're system. </p> |
24,471,954 | How to use dequeueReusableCellWithIdentifier in Swift? | <p>If I uncomment</p>
<pre><code>tableView(tableView: UITableView?, cellForRowAtIndexPath indexPath: NSIndexPath?)
</code></pre>
<p>I get an error on the line</p>
<pre><code>let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
</code></pre>
<p>that says <code>UITableView? does not have a member named 'dequeueReusableCellWithIdentifier'</code></p>
<p>If I unwrap the tableview then the error goes away, but in Objective-C we would normally check whether or not the cell exists, and if it does not we create a new one. In Swift, since the boilerplate provided uses the <code>let</code> keyword and unwraps an optional, we can't reassign it if it's nil.</p>
<p>What's the proper way to use dequeueReusableCellWithIdentifier in Swift?</p> | 24,493,429 | 5 | 2 | null | 2014-06-28 23:50:22.943 UTC | 5 | 2017-12-12 05:33:24.053 UTC | 2015-03-18 05:14:10.56 UTC | null | 947,934 | null | 1,370,927 | null | 1 | 24 | ios|uitableview|swift | 65,196 | <p>You can implicitly unwrap the parameters to the method and also cast the result of <code>dequeueReusableCellWithIdentifier</code> to give the following succinct code:</p>
<pre><code>func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("CellIdentifier", forIndexPath: indexPath) as UITableViewCell
//configure your cell
return cell
}
</code></pre> |
24,510,108 | Compare only day and month with date field in mysql | <p>How to compare only day and month with date field in mysql?
For example, I've a date in one table: <code>2014-07-10</code></p>
<p>Similarly, another date <code>2000-07-10</code> in another table.
I want to compare only day and month is equal on date field.</p>
<p>I tried this format. But I can't get the answer</p>
<pre><code>select *
from table
where STR_TO_DATE(field,'%m-%d') = STR_TO_DATE('2000-07-10','%m-%d')
and id = "1"
</code></pre> | 24,510,301 | 4 | 2 | null | 2014-07-01 12:18:30.897 UTC | 7 | 2018-06-25 16:39:50.717 UTC | 2018-06-25 16:39:50.717 UTC | null | 8,156,265 | null | 3,259,677 | null | 1 | 14 | mysql|sql|date|select | 54,523 | <p>Use DATE_FORMAT instead:</p>
<pre><code>SELECT DATE_FORMAT('2000-07-10','%m-%d')
</code></pre>
<p>yields</p>
<pre><code>07-10
</code></pre>
<p>Here's your query re-written with <code>DATE_FORMAT()</code>:</p>
<pre><code>SELECT *
FROM table
WHERE DATE_FORMAT(field, '%m-%d') = DATE_FORMAT('2000-07-10', '%m-%d')
AND id = "1"
</code></pre> |
563,225 | Code linting for Objective C | <p>Are there any code linting tools for ObjectiveC? </p> | 563,259 | 5 | 0 | null | 2009-02-18 22:57:28.293 UTC | 11 | 2019-05-24 10:22:16.603 UTC | 2009-02-18 23:14:14.947 UTC | epatel | 842 | DasBoot | 66,344 | null | 1 | 18 | objective-c|static-analysis | 5,873 | <p>Have a look at the <a href="https://clang.llvm.org/docs/UsersManual.html#controlling-static-analyzer-diagnostics" rel="noreferrer"><strong>LLVM/Clang Static Analyzer</strong></a></p>
<p>The LLVM/Clang static analyzer is a standalone tool that find bugs in C and Objective-C programs and it is very early in development.</p>
<p>A static analyzer based on <strong>clang</strong>. The goal of the Clang project is to create a new C, C++, Objective C and Objective C++ front-end for the LLVM compiler.</p>
<h2>Edit</h2>
<p>Clang has now been integrated into Xcode and can easily be run as a menu option "Build & Analyse"</p>
<p><img src="https://clang-analyzer.llvm.org/images/analyzer_xcode.png" alt="alt text" /></p> |
29,645 | Set up PowerShell Script for Automatic Execution | <p>I have a few lines of PowerShell code that I would like to use as an automated script. The way I would like it to be able to work is to be able to call it using one of the following options:</p>
<ol>
<li>One command line that opens PowerShell, executes script and closes PowerShell (this would be used for a global build-routine)</li>
<li>A file that I can double-click to run the above (I would use this method when manually testing components of my build process)</li>
</ol>
<p>I have been going through PowerShell documentation online, and although I can find lots of scripts, I have been unable to find instructions on how to do what I need. Thanks for the help.</p> | 29,649 | 5 | 0 | null | 2008-08-27 07:00:43.093 UTC | 10 | 2016-11-15 13:48:52.427 UTC | 2008-08-27 07:05:47.043 UTC | Yaakov Ellis | 51 | Yaakov Ellis | 51 | null | 1 | 20 | command-line|powershell|scripting | 64,693 | <p>Save your script as a .ps1 file and launch it using powershell.exe, like this:</p>
<pre><code>powershell.exe .\foo.ps1
</code></pre>
<p>Make sure you specify the full path to the script, and make sure you have set your execution policy level to at least "RemoteSigned" so that unsigned local scripts can be run.</p> |
165,495 | Detecting Mouse clicks in windows using python | <p>How can I detect mouse clicks regardless of the window the mouse is in?</p>
<p>Perferabliy in python, but if someone can explain it in any langauge I might be able to figure it out.</p>
<p>I found this on microsoft's site:
<a href="http://msdn.microsoft.com/en-us/library/ms645533(VS.85).aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/ms645533(VS.85).aspx</a></p>
<p>But I don't see how I can detect or pick up the notifications listed.</p>
<p>Tried using pygame's pygame.mouse.get_pos() function as follows:</p>
<pre><code>import pygame
pygame.init()
while True:
print pygame.mouse.get_pos()
</code></pre>
<p>This just returns 0,0.
I'm not familiar with pygame, is something missing?</p>
<p>In anycase I'd prefer a method without the need to install a 3rd party module.
(other than pywin32 <a href="http://sourceforge.net/projects/pywin32/" rel="noreferrer">http://sourceforge.net/projects/pywin32/</a> )</p> | 168,996 | 5 | 2 | null | 2008-10-03 02:51:44.47 UTC | 17 | 2017-10-06 00:24:34.81 UTC | 2008-10-03 07:47:06.833 UTC | monkut | 24,718 | null | 24,718 | null | 1 | 24 | python|windows|mouse | 82,003 | <p>The only way to detect mouse events outside your program is to install a Windows hook using <a href="http://msdn.microsoft.com/en-us/library/ms644990(VS.85).aspx" rel="noreferrer">SetWindowsHookEx</a>. The <a href="http://www.cs.unc.edu/Research/assist/developer.shtml" rel="noreferrer">pyHook</a> module encapsulates the nitty-gritty details. Here's a sample that will print the location of every mouse click:</p>
<pre><code>import pyHook
import pythoncom
def onclick(event):
print event.Position
return True
hm = pyHook.HookManager()
hm.SubscribeMouseAllButtonsDown(onclick)
hm.HookMouse()
pythoncom.PumpMessages()
hm.UnhookMouse()
</code></pre>
<p>You can check the <strong>example.py</strong> script that is installed with the module for more info about the <strong>event</strong> parameter.</p>
<p>pyHook might be tricky to use in a pure Python script, because it requires an active message pump. From the <a href="https://web.archive.org/web/20100501173949/http://mindtrove.info/articles/monitoring-global-input-with-pyhook/" rel="noreferrer">tutorial</a>:</p>
<blockquote>
<p>Any application that wishes to receive
notifications of global input events
must have a Windows message pump. The
easiest way to get one of these is to
use the PumpMessages method in the
Win32 Extensions package for Python.
[...] When run, this program just sits
idle and waits for Windows events. If
you are using a GUI toolkit (e.g.
wxPython), this loop is unnecessary
since the toolkit provides its own.</p>
</blockquote> |
873,432 | NetBeans PHP code completion for own code | <p>Recently I started using <a href="https://download.netbeans.org/netbeans/6.7/beta/" rel="nofollow noreferrer">NetBeans 6.7 beta</a> for PHP development instead of <a href="https://macromates.com/" rel="nofollow noreferrer">Textmate</a> and <a href="https://web.archive.org/web/20190331020751/https://www.bluestatic.org/software/macgdbp/" rel="nofollow noreferrer">MacGDBp</a>. I am rather amazed with it's feature set and most everything worked out of the box, or was easily configured to my liking.</p>
<p>I am having an issue with the code completion features though; they work for built-in functions, <a href="https://www.php.net/spl" rel="nofollow noreferrer" title="Standard PHP Library">SPL</a> and some of my code, but not all of my code, specifically, it never works for any methods in my classes, regardless of PHPDoc comments.</p>
<p>I can't seem to find any decent questions, let alone answers about this specific subject anywhere. It looks like everybody else who has problems with the code completion just hasn't enabled the auto-popup feature.</p>
<p><strong>So the big question is:</strong></p>
<p>Is there <em>any way</em> to influence the code completion cache, or something I have to add to my code to make it work? I'd really like to have code completion for the methods I write.</p>
<p><strong>PS</strong>: I have tried several older versions of netbeans, they all exhibit the same problem.</p>
<p><strong>edit</strong>: I've put a .zip up of my current test project. <a href="http://develop.theredhead.nl/~kris/stackoverflow/develop.theredhead.nl.zip" rel="nofollow noreferrer">get it here</a>. It's a very young project, think a day and a half.</p>
<p><strong>edit2</strong>: Below is a screenshot of what i'm looking at. As you can see, it fails to complete pretty much anything, nor does it see the PHPDoc documentation.</p>
<p><a href="https://i.stack.imgur.com/ubVyA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ubVyA.png" alt="alt text"></a><br>
</p> | 874,778 | 5 | 3 | null | 2009-05-16 22:12:14.11 UTC | 9 | 2019-07-19 14:46:12.773 UTC | 2019-07-19 14:46:12.773 UTC | null | 4,751,173 | null | 18,565 | null | 1 | 26 | netbeans|code-completion | 21,292 | <p>I've tried opening your project, and the completion seems to be working just fine for me.</p>
<p>The only thing I can think of is to try to delete your entire NB cache, which should be located in <code>$HOME/.netbeans/$VERSION/var/cache/</code>. This is a wild guess</p>
<p><strong>Create a backup first</strong>, I didn't try this!</p>
<p>If that fails, maybe you should try creating a new project, maybe that will kick NB in the butt.</p>
<p>Note that in NB 7.2 beta, the cache has moved to $HOME/.cache/netbeans/$VERSION.</p> |
983,716 | asp.net dropdownlist - add blank line before db values | <p>On my page I have a <code>DropDownList</code> which I populate with database values from an <code>SqlDataSource</code> (see code below).</p>
<p>How can I add my own text or a blank line before the values?</p>
<pre><code><asp:DropDownList ID="drpClient" runat="server" Width="200px"
AutoPostBack="True" DataSourceID="dsClients" DataTextField="name"
DataValueField="client_id">
</asp:DropDownList>
<asp:SqlDataSource ID="dsClients" runat="server"
ConnectionString="my_connection_string"
ProviderName="System.Data.SqlClient"
SelectCommand="SELECT [client_id], [name] FROM [clients]">
</asp:SqlDataSource>
</code></pre>
<p>Thanks.</p>
<p>P.S. Do you recommend using a <code>SqlDataSource</code> or is it better to populate another way?</p> | 983,773 | 5 | 1 | null | 2009-06-11 21:12:11.543 UTC | 8 | 2015-09-22 12:27:21.3 UTC | 2015-06-15 16:11:26.833 UTC | null | 1,678,392 | null | 115,983 | null | 1 | 31 | asp.net|drop-down-menu|sqldatasource|dropdownbox | 66,411 | <p>You can simply add a <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listitem.aspx" rel="noreferrer">ListItem</a> inside the DropDownList Markup. All the values from the DataSource will be appended after that.</p>
<pre><code><asp:DropDownList ID="drpClient" runat="server" Width="200px"
AutoPostBack="True" DataSourceID="dsClients" DataTextField="name"
DataValueField="client_id" AppendDataBoundItems="true">
<asp:ListItem>-- pick one --</asp:ListItem>
</asp:DropDownList>
</code></pre> |
32,227,482 | RecyclerView Swipe with a view below it | <p>I have been doing some research and I have yet to find an example or implementation that allows you to put a view (Example Image Below) underneath the RecyclerView when you swipe. Does anyone have any example or an idea of how this would be implemented <strong>WITHOUT</strong> using a library.</p>
<p>Here is how I am implementing the swipe to dismiss. </p>
<pre><code>ItemTouchHelper.SimpleCallback simpleItemTouchCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
@Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
return false;
}
@Override
public int getSwipeDirs(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
return super.getSwipeDirs(recyclerView, viewHolder);
}
@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
if (viewHolder instanceof ViewDividers) {
Log.e("DIRECTION", direction + "");
}
}
};
new ItemTouchHelper(simpleItemTouchCallback).attachToRecyclerView(recycler);
</code></pre>
<p>Here is the example of Google's Inbox:
<a href="https://i.stack.imgur.com/3TNRq.png" rel="noreferrer"><img src="https://i.stack.imgur.com/3TNRq.png" alt="enter image description here"></a></p> | 32,274,612 | 6 | 8 | null | 2015-08-26 13:05:40.857 UTC | 27 | 2020-03-26 16:05:04.217 UTC | null | null | null | null | 3,904,085 | null | 1 | 47 | android|android-recyclerview | 43,777 | <p>My understanding of how this is done is that one would put two views in the xml that would be displayed per line in your recyclerview.</p>
<p>So for example, this would be my adapter:</p>
<pre><code>public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
public static class ExampleViewHolder extends RecyclerView.ViewHolder {
public TextView background;
public TextView foreground;
public ExampleViewHolder(View v) {
super(v);
background = (TextView) v.findViewById(R.id.background);
foreground = (TextView) v.findViewById(R.id.foreground);
}
@Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
if (holder instanceof ExampleViewHolder) {
((ExampleViewHolder) holder).background.setBackgroundColor(); // do your manipulation of background and foreground here.
}
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.example, parent, false);
return new ExampleViewHolder(v);
}
}
}
</code></pre>
<p>Each line in the recyclerview is pulling the xml layout from R.layout.example. Therefore, to create a view underneath, you can just use relativelayout or framelayout to create the views on top of one another:</p>
<pre><code><RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/background"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/foreground"/>
</RelativeLayout>
</code></pre>
<p>Then if you do not want to use a library for the swipe, you can copy this class from google and subsequently modified by Bruno Romeu Nunes:</p>
<p><a href="https://github.com/heruoxin/Clip-Stack/blob/master/app/src/main/java/com/catchingnow/tinyclipboardmanager/SwipeableRecyclerViewTouchListener.java">https://github.com/heruoxin/Clip-Stack/blob/master/app/src/main/java/com/catchingnow/tinyclipboardmanager/SwipeableRecyclerViewTouchListener.java</a></p>
<p>The class will require you to create a swipe listener:</p>
<pre><code>swipeTouchListener =
new SwipeableRecyclerViewTouchListener(mRecyclerView,
new SwipeableRecyclerViewTouchListener.SwipeListener() {
@Override
public boolean canSwipe(int position) {
if (position == totalPost.size() - 1 && !connected) {
return false;
}
return true;
}
@Override
public void onDismissedBySwipeLeft(RecyclerView recyclerView, int[] reverseSortedPositions) {
for (int position : reverseSortedPositions) {
//change some data if you swipe left
}
myAdapter.notifyDataSetChanged();
}
@Override
public void onDismissedBySwipeRight(RecyclerView recyclerView, int[] reverseSortedPositions) {
for (int position : reverseSortedPositions) {
//change some data if you swipe right
}
myAdapter.notifyDataSetChanged();
}
});
</code></pre>
<p>Then simply link it with your recyclerview:</p>
<pre><code> mRecyclerView.addOnItemTouchListener(swipeTouchListener);
</code></pre> |
32,227,360 | Multi module project analysis with SonarQube | <p><code>SonarQube Server 5.1.2, Sonar-Runner 2.4</code></p>
<p>As provide in <a href="http://docs.sonarqube.org/display/SONAR/Analyzing+with+SonarQube+Runner#AnalyzingwithSonarQubeRunner-Multi-moduleProject" rel="noreferrer">Multi-moduleProject</a> i have created a project structure as </p>
<pre><code>Accounts
|
->invoice
|
->src
->receipt
|
->src
->sonar.properties
</code></pre>
<p>File:sonar.properties</p>
<pre><code>sonar.projectKey=org.mycompany.acc
sonar.projectName=Account
sonar.projectVersion=1.0
sonar.sources=src
sonar.modules=invoice,receipt
invoice.sonar.projectName=Invoice
receipt.sonar.projectName=Receipt
</code></pre>
<p>When execute with above configuration in sonar-runner i encountered with error "src" folder is missing in "Account" directory, hope this configuration is same as the conf available in that link. As per the understanding if the configuration is fine then the Invoice and Receipt will be listed as <strong>sub project</strong> under Account Project, so what are the changes are required in above configuration to achieve multi module / project under one project.</p>
<p><strong>ERROR</strong></p>
<p><code>ERROR: Error during Sonar runner execution
ERROR: Unable to execute Sonar
ERROR: Caused by: The folder 'src' does not exist for 'org.mycompany.acc' (base
directory = C:\Users\xyz\Accounts\.)
ERROR:
ERROR: To see the full stack trace of the errors, re-run SonarQube Runner with t
he -e switch.
ERROR: Re-run SonarQube Runner using the -X switch to enable full debug logging.</code></p> | 37,447,378 | 3 | 8 | null | 2015-08-26 13:00:11.623 UTC | 8 | 2022-06-21 14:40:38.847 UTC | 2015-08-27 09:24:45.897 UTC | null | 2,047,363 | null | 2,047,363 | null | 1 | 11 | sonarqube|sonar-runner|sonarqube5.1 | 38,095 | <p>try this:</p>
<pre><code>sonar.projectKey=org.mycompany.acc
sonar.projectName=Account
sonar.projectVersion=1.0
sonar.sources=src # try to remove this by the way if you don't have suchdirectory under root folder of project
sonar.modules=invoice,receipt
invoice.sonar.projectName=Invoice
invoice.sonar.sources=invoice/src
receipt.sonar.projectName=Receipt
receipt.sonar.sources=receipt/src
</code></pre> |
35,536,011 | Is there a declarative way to transform Array to Dictionary? | <p>I want to get from this array of strings</p>
<pre><code>let entries = ["x=5", "y=7", "z=10"]
</code></pre>
<p>to this</p>
<pre><code>let keyValuePairs = ["x" : "5", "y" : "7", "z" : "10"]
</code></pre>
<p>I tried to use <code>map</code> but the problem seems to be that a key - value pair in a dictionary is not a distinct type, it's just in my mind, but not in the Dictionary type so I couldn't really provide a transform function because there is nothing to transform to. Plus <code>map</code> return an array so it's a no go.</p>
<p>Any ideas?</p> | 35,546,528 | 8 | 2 | null | 2016-02-21 12:18:44.703 UTC | 6 | 2017-11-29 22:03:09.343 UTC | null | null | null | null | 788,100 | null | 1 | 31 | swift|declarative | 18,114 | <p><strong>Swift 4</strong></p>
<p>As alluded to by fl034, this can be simplified some with Swift 4 where an error checked version looks like:</p>
<pre><code>let foo = entries
.map { $0.components(separatedBy: "=") }
.reduce(into: [String:Int64]()) { dict, pair in
if pair.count == 2, let value = Int64(pair[1]) {
dict[pair[0]] = value
}
}
</code></pre>
<p>Even simpler if you don't want the values as Ints:</p>
<pre><code>let foo = entries
.map { $0.components(separatedBy: "=") }
.reduce(into: [String:String]()) { dict, pair in
if pair.count == 2 {
dict[pair[0]] = pair[1]
}
}
</code></pre>
<p><strong>Older TL;DR</strong></p>
<p>Minus error checking, it looks pretty much like:</p>
<pre><code>let foo = entries.map({ $0.componentsSeparatedByString("=") })
.reduce([String:Int]()) { acc, comps in
var ret = acc
ret[comps[0]] = Int(comps[1])
return ret
}
</code></pre>
<p>Use map to turn the <code>[String]</code> into a split up <code>[[String]]</code> and then build the dictionary of <code>[String:Int]</code> from that using reduce.</p>
<p>Or, by adding an extension to <code>Dictionary</code>:</p>
<pre><code>extension Dictionary {
init(elements:[(Key, Value)]) {
self.init()
for (key, value) in elements {
updateValue(value, forKey: key)
}
}
}
</code></pre>
<p>(Quite a useful extension btw, you can use it for a lot of map/filter operations on Dictionaries, really kind of a shame it doesn't exist by default)</p>
<p>It becomes even simpler:</p>
<pre><code>let dict = Dictionary(elements: entries
.map({ $0.componentsSeparatedByString("=") })
.map({ ($0[0], Int($0[1])!)})
)
</code></pre>
<p>Of course, you can also combine the two map calls, but I prefer to break up the individual transforms.</p>
<p>If you want to add some error checking, <code>flatMap</code> can be used instead of <code>map</code>:</p>
<pre><code>let dict2 = [String:Int](elements: entries
.map({ $0.componentsSeparatedByString("=") })
.flatMap({
if $0.count == 2, let value = Int($0[1]) {
return ($0[0], value)
} else {
return nil
}})
)
</code></pre>
<p>Again, if you want, you can obviously merge the <code>map</code> into the <code>flatMap</code> or split them for simplicity.</p>
<pre><code>let dict2 = [String:Int](elements: entries.flatMap {
let parts = $0.componentsSeparatedByString("=")
if parts.count == 2, let value = Int(parts[1]) {
return (parts[0], value)
} else {
return nil
}}
)
</code></pre> |
44,232,366 | How do I build a JSON file with webpack? | <p>I'd like to assemble a <code>manifest.json</code> file, as used by Chrome extensions, in a "smarter," programmatic sort of way. I'm using npm for my dependency resolution, and its <code>package.json</code> includes some shared fields with the <code>manifest.json</code> file, including "name," "description," and "version."</p>
<p>Is there a way to define something like a partial <code>manifest.json</code> file which includes all the Chrome-specific stuff, but fill in shared values where appropriate? I've found that this is pretty straightforward in Gulp:</p>
<pre><code>var gulp = require('gulp');
var fs = require('fs');
var jeditor = require('gulp-json-editor');
gulp.task('manifest', function() {
var pkg = JSON.parse(fs.readFileSync('./package.json'));
gulp.src('./manifest.json')
.pipe(jeditor({
'name': pkg.name,
'description': pkg.description,
'version': pkg.version,
'author': pkg.author,
'homepage_url': pkg.homepage,
}))
.pipe(gulp.dest("./dist"));
});
</code></pre>
<p>Even if there's some npm package out there designed for this purpose, can someone explain to me how something like this might be done generally? I know Webpack 2 has a built-in json loader, but I'm not clear how it would be used in a case like this.</p> | 44,249,538 | 6 | 2 | null | 2017-05-28 21:52:57.633 UTC | 8 | 2020-06-05 23:44:52.34 UTC | 2017-05-29 19:51:39.623 UTC | null | 2,141,391 | null | 2,141,391 | null | 1 | 39 | javascript|npm|webpack | 22,132 | <p>Credit to Sean Larkin from the Webpack project for reaching out to me and helping me figure out how to get this done. I needed to create a custom loader to handle reading the existing <code>manifest.json</code> and adding my fields of interest to it.</p>
<pre><code>// File: src/manifest-loader.js
const fs = require('fs');
// A loader to transform a partial manifest.json file into a complete
// manifest.json file by adding entries from an NPM package.json.
module.exports = function(source) {
const pkg = JSON.parse(fs.readFileSync('./package.json'));
const merged = Object.assign({}, JSON.parse(source), {
'name': pkg.name,
'description': pkg.description,
'version': pkg.version,
'author': pkg.author,
'homepage_url': pkg.homepage,
});
const mergedJson = JSON.stringify(merged);
// In Webpack, loaders ultimately produce JavaScript. In order to produce
// another file type (like JSON), it needs to be emitted separately.
this.emitFile('manifest.json', mergedJson);
// Return the processed JSON to be used by the next item in the loader chain.
return mergedJson;
};
</code></pre>
<p>Then configure webpack to use my custom <code>manifest-loader</code>.</p>
<pre><code>// File: webpack.config.js
const path = require('path');
module.exports = {
// Tell Webpack where to find our custom loader (in the "src" directory).
resolveLoader: {
modules: [path.resolve(__dirname, "src"), "node_modules"]
},
// The path to the incomplete manifest.json file.
entry: "./manifest.json",
output: {
// Where the newly built manifest.json will go.
path: path.resolve(__dirname, 'dist'),
// This file probably won't actually be used by anything.
filename: "manifest.js",
},
module: {
rules: [
{
// Only apply these loaders to manifest.json.
test: /manifest.json$/,
// Loaders are applied in reverse order.
use: [
// Second: JSON -> JS
"json-loader",
// First: partial manifest.json -> complete manifest.json
"manifest-loader",
]
}
]
}
};
</code></pre>
<p>The result, when running Webpack, is a <code>dist/</code> directory containing <code>manifest.js</code> and <code>manifest.json</code>, with <code>manifest.json</code> containing everything from the original, top-level <code>manifest.json</code> plus the additional info from <code>package.json</code>. The extra <code>manifest.js</code> is a script that exposes the contents of <code>manifest.json</code> to any other JavaScript in the project that wants it. This is probably not too useful, but a Chrome extension might conceivably want to <code>require</code> this in a script somewhere to expose some of this information in a friendly way.</p> |
18,004,033 | Insert Multiple Rows Into Temp Table With SQL Server 2012 | <p>These StackOverflow questions <a href="https://stackoverflow.com/questions/452859/inserting-multiple-rows-in-a-single-sql-query">here</a>, <a href="https://stackoverflow.com/questions/2676493/insert-multiple-rows-into-temp-table-with-one-command-in-sql2005">here</a>, and <a href="https://stackoverflow.com/questions/2624713/how-do-i-insert-multiple-rows-without-repeating-the-insert-into-dbo-blah-part">here</a> all say the same thing, but I can't get it to run in SSMS or SQLFiddle</p>
<pre class="lang-sql prettyprint-override"><code>CREATE TABLE #Names
(
Name1 VARCHAR(100),
Name2 VARCHAR(100)
)
INSERT INTO #Names
(Name1, Name2)
VALUES
('Matt', 'Matthew'),
('Matt', 'Marshal'),
('Matt', 'Mattison')
</code></pre>
<p>When I execute this is SSMS, the insert fails with the following message on the first line after <code>VALUES</code></p>
<blockquote>
<p>Msg 102, Level 15, State 1, Line 10<br>
Incorrect syntax near ','.</p>
</blockquote>
<p>This <a href="http://sqlfiddle.com/#!18/32d8f/1" rel="noreferrer"><strong>Fiddle</strong></a> runs without the <code>#</code> sign, and the schema executes successfully when the table name is <code>#Names</code>, but I get the following message when I try to select * from the table </p>
<blockquote>
<p>Invalid object name '#NAMES'.: SELECT * FROM #NAMES</p>
</blockquote>
<p>Does SQL Server 2012 support multiple inserts?</p>
<hr>
<p><strong>Update</strong>: Apparently accessing a 2005 server on SSMS 2012....</p>
<pre class="lang-sql prettyprint-override"><code>SELECT @@VERSION --Returns: Microsoft SQL Server 2005
</code></pre> | 18,004,229 | 2 | 2 | null | 2013-08-01 20:36:48.107 UTC | 3 | 2018-08-17 14:59:29.927 UTC | 2018-08-17 14:59:29.927 UTC | null | 1,366,033 | null | 1,366,033 | null | 1 | 18 | sql|sql-server-2012|bulkinsert | 131,527 | <p>Yes, SQL Server <strong>2012</strong> supports multiple inserts - that feature was introduced in SQL Server <strong>2008</strong>.</p>
<p>That makes me wonder if you have Management Studio 2012, but you're really connected to a SQL Server <strong>2005</strong> instance ...</p>
<p>What version of the SQL Server <strong>engine</strong> do you get from <code>SELECT @@VERSION</code> ??</p> |
17,768,814 | ngRoute set base url for all routes | <p>Is it possible to add a <strong>base url</strong> to all routes in an <em>AngularJS</em> app? Essentially changing its location on the server (kind of, if that makes sense... so it would be accessed not via <code>/</code> but via <code>/something/</code>).</p>
<p>To add some context, I am trying to place an existing <em>Angular</em> app behind some authentication such that the app would now be accessed at address say <code>http://mysite/secure</code> after successful login.</p>
<p>The problem is if I was to load the app at <code>http://mysite/secure</code> it works fine (the server will obviously serve up the correct page), but clicking any link would result in a page reload and route to <code>http://mysite/#newpage</code> instead of <code>http://mysite/secure/#newpage</code>.</p>
<p>Without adding <code>/secure/</code> to all of the routes and link element is this possible? Cheers, sorry if that is not worded well.</p> | 17,768,999 | 2 | 1 | null | 2013-07-21 03:38:06.64 UTC | 5 | 2018-09-05 12:54:17.987 UTC | 2018-09-05 12:54:17.987 UTC | null | 717,267 | null | 1,481,403 | null | 1 | 52 | angularjs | 57,575 | <p>Setting the <code><base></code> HTML5 tag might help. From the documentation <a href="http://docs.angularjs.org/guide/$location" rel="noreferrer">here</a>:</p>
<blockquote>
<p><strong>Relative links</strong></p>
<p>Be sure to check all relative links, images, scripts etc. You must either specify the url base in the head of your main html file (<code><base href="/my-base"></code>) or you must use absolute urls (starting with /) everywhere because relative urls will be resolved to absolute urls using the initial absolute url of the document, which is often different from the root of the application.</p>
<p>Running Angular apps with the History API enabled from document root is strongly encouraged as it takes care of all relative link issues.</p>
</blockquote> |
2,209,159 | Disconnect signals for models and reconnect in django | <p>I need make a save with a model but i need disconnect some receivers of the signals before save it.</p>
<p>I mean,</p>
<p>I have a model:</p>
<pre><code>class MyModel(models.Model):
...
def pre_save_model(sender, instance, **kwargs):
...
pre_save.connect(pre_save_model, sender=MyModel)
</code></pre>
<p>and in another place in the code i need something like:</p>
<pre><code>a = MyModel()
...
disconnect_signals_for_model(a)
a.save()
...
reconnect_signals_for_model(a)
</code></pre>
<p>Because i need in this case, save the model without execute the function pre_save_model.</p> | 26,245,339 | 5 | 0 | null | 2010-02-05 17:45:31.507 UTC | 8 | 2020-09-28 13:09:49.897 UTC | null | null | null | null | 150,647 | null | 1 | 35 | django|django-signals | 19,666 | <p>For a clean and reusable solution, you can use a context manager:</p>
<pre><code>class temp_disconnect_signal():
""" Temporarily disconnect a model from a signal """
def __init__(self, signal, receiver, sender, dispatch_uid=None):
self.signal = signal
self.receiver = receiver
self.sender = sender
self.dispatch_uid = dispatch_uid
def __enter__(self):
self.signal.disconnect(
receiver=self.receiver,
sender=self.sender,
dispatch_uid=self.dispatch_uid,
weak=False
)
def __exit__(self, type, value, traceback):
self.signal.connect(
receiver=self.receiver,
sender=self.sender,
dispatch_uid=self.dispatch_uid,
weak=False
)
</code></pre>
<p>Now, you can do something like the following:</p>
<pre><code>from django.db.models import signals
from your_app.signals import some_receiver_func
from your_app.models import SomeModel
...
kwargs = {
'signal': signals.post_save,
'receiver': some_receiver_func,
'sender': SomeModel,
'dispatch_uid': "optional_uid"
}
with temp_disconnect_signal(**kwargs):
SomeModel.objects.create(
name='Woohoo',
slug='look_mom_no_signals',
)
</code></pre>
<p><em>Note: If your signal handler uses a <code>dispatch_uid</code>, you <strong>MUST</strong> use the <code>dispatch_uid</code> arg.</em></p> |
1,367,322 | What are all the escape characters? | <p>I know some of the escape characters in Java, e.g.</p>
<pre><code>\n : Newline
\r : Carriage return
\t : Tab
\\ : Backslash
...
</code></pre>
<p>Is there a complete list somewhere?</p> | 1,367,339 | 5 | 3 | null | 2009-09-02 12:10:46.38 UTC | 59 | 2022-07-22 14:38:17.273 UTC | 2017-09-20 09:16:31.697 UTC | null | 1,685,157 | null | 974 | null | 1 | 135 | java|string|escaping | 568,148 | <p>You can find the full list <a href="http://docs.oracle.com/javase/tutorial/java/data/characters.html" rel="nofollow noreferrer">here</a>.</p>
<ul>
<li><code>\t</code> Insert a tab in the text at this point.</li>
<li><code>\b</code> Insert a backspace in the text at this point.</li>
<li><code>\n</code> Insert a newline in the text at this point.</li>
<li><code>\r</code> Insert a carriage return in the text at this point.</li>
<li><code>\f</code> Insert a formfeed in the text at this point.</li>
<li><code>\s</code> Insert a space in the text at this point.</li>
<li><code>\'</code> Insert a single quote character in the text at this point.</li>
<li><code>\"</code> Insert a double quote character in the text at this point.</li>
<li><code>\\</code> Insert a backslash character in the text at this point.</li>
</ul> |
1,947,717 | How to implement speech recognition and text-to-speech in C++? | <p>I want to know about various techniques to do speech recognition and text to speech conversion.
Also please let me know about any resources like links, tutorials ,ebooks etc. on it.</p>
<p>Which is the most efficient technique to achieve it ?</p> | 1,951,015 | 6 | 0 | null | 2009-12-22 17:00:56.54 UTC | 10 | 2010-05-27 12:07:19.73 UTC | 2009-12-23 06:00:14.65 UTC | null | 303,986 | null | 303,986 | null | 1 | 12 | c++|speech-recognition | 12,065 | <p>I'm going to answer the part about speech recognition (since I don't know much about text-to-speech):</p>
<p><a href="https://rads.stackoverflow.com/amzn/click/com/0262100665" rel="noreferrer" rel="nofollow noreferrer">http://ecx.images-amazon.com/images/I/4190SZC61CL._BO2,204,203,200_PIsitb-sticker-arrow-click,TopRight,35,-76_AA240_SH20_OU01_.jpg</a></p>
<p>This book, "Statistical Methods for Speech Recognition" is a classic that explains the mathematical foundations of statistical speech recognition, written by the founder of that area, Frederick Jelinek.</p>
<p>The most important concept you have to know is <a href="http://en.wikipedia.org/wiki/Hidden_Markov_model" rel="noreferrer">Hidden Markov Models</a>. People have been using them in speech recognition for decades. A recent approach uses <a href="http://en.wikipedia.org/wiki/Conditional_random_field" rel="noreferrer">Conditional Random Fields</a>, see the <a href="http://research.microsoft.com/en-us/um/people/gzweig/Pubs/scarf_asru09.pdf" rel="noreferrer">paper (PDF)</a> and the associated software toolkit <a href="http://research.microsoft.com/en-us/people/gzweig/" rel="noreferrer">SCARF</a>.</p>
<p>It is fairly hard to write your own speech recognizer. It's an active research area with several scientific conferences, e.g. <a href="http://www.asru2009.org/" rel="noreferrer">ASRU</a>, <a href="http://www.interspeech2009.org/" rel="noreferrer">Interspeech</a>, <a href="http://www.icassp2010.com/" rel="noreferrer">ICASSP</a>.</p> |
1,771,176 | IE8 non-compatibility mode, image with max-width and height:auto | <p>I have an image with this markup</p>
<pre><code><img src="wedding_00.jpg" width="900" height="600" />
</code></pre>
<p>And I am using CSS to downsize it to 600px width, like so:</p>
<pre><code>img {
max-width:600px;
height:auto;
}
</code></pre>
<p>Can anyone explain why this method works in Compatibility mode, but not in standard mode? Is there a way I can modify my CSS so that it will work in standard mode?</p>
<p>I realize that if I strip out the </p>
<pre><code>width="900" height="600"
</code></pre>
<p>that it solves the problem, but that is not an option I have.</p> | 1,771,221 | 6 | 0 | null | 2009-11-20 15:23:15.473 UTC | 10 | 2013-05-02 15:05:47.633 UTC | 2011-07-14 17:19:36.317 UTC | null | 208,770 | null | 208,770 | null | 1 | 32 | internet-explorer-8|css|compatibility-mode | 48,059 | <p>I'm not sure of the root cause but if you add</p>
<pre><code>width: auto;
</code></pre>
<p>then it works.</p> |
1,763,099 | Techniques to reduce data harvesting from AJAX/JSON services | <p>I was wondering if anyone had come across any techniques to reduce the chances of data exposed through JSON type services on the server (intended to supply AJAX functions) from being harvested by external agents.</p>
<p>It seems to me that the problem is not so difficult if you had say a Flash client consuming the data. Then you could send encrypted data to the client, which would know how to decrypt it. The same method seems impossible with AJAX though, due to the open nature of the Javascript source.</p>
<p>Has anybody implemented a clever technique here?</p>
<p>Whatever the method, it should still allow a genuine AJAX function to consume the data.</p>
<p>Note that I'm not really talking about protecting 'sensitive' information here, the odd record leaking out is not a problem. Rather I am thinking about stopping a situation where the whole DB is hoovered up by bots (either in one go, or gradually over time).</p>
<p>Thanks.</p> | 1,780,799 | 7 | 0 | null | 2009-11-19 12:54:41.8 UTC | 9 | 2010-07-17 16:13:04.377 UTC | 2010-07-17 16:13:04.377 UTC | null | 14,343 | null | 324,381 | null | 1 | 12 | ajax|security|web-services|json | 2,422 | <p>First, I would like to clear on this:</p>
<blockquote>
<p>It seems to me that the problem is not
so difficult if you had say a Flash
client consuming the data. Then you
could send encrypted data to the
client, which would know how to
decrypt it. The same method seems
impossible with AJAX though, due to
the open nature of the Javascrip
source.</p>
</blockquote>
<p>It will be pretty obvious the information is being sent encrypted to the flash client & it won't be that hard for the attacker to find out from your flash compiled program what's being used for this - replicate & get all that data. </p>
<p>If the data does happens to have the value you are thinking, you can count on the above.</p>
<p><strong>If this is public information, embrace that & don't combat it - instead find ways to capitalize on it.</strong></p>
<p>If this is information that you are only exposing to a set of users, make sure you have the corresponding authentication / secure communication. Track usage as others have said, and have measures that act on it,</p> |
1,974,491 | Remove blank line in Eclipse | <p>How can I remove lines that only contain spaces when using Eclipse Find/Replace prompt. I checked the "Regular Expression" check box, and tried the following, neither of which worked.</p>
<pre><code>^[:space:]*$
</code></pre>
<p>and</p>
<pre><code>^\s*$
</code></pre> | 1,974,583 | 7 | 0 | null | 2009-12-29 12:50:08.59 UTC | 23 | 2018-05-15 14:08:16.63 UTC | null | null | null | null | 131,640 | null | 1 | 36 | eclipse | 33,808 | <p>Find: <code>^\s*\n</code></p>
<p>Replace with: (empty)</p> |
1,407,638 | git merge: Removing files I want to keep! | <p>How can you merge two branches in git, retaining <em>necessary</em> files from a branch?</p>
<p>When merging two branches, if a file was deleted in one branch and not in another, the file is ultimately deleted.</p>
<p>For example:</p>
<ul>
<li>A file exists in master when you make a new branch</li>
<li>you remove the file from master since we don't need it (yet)</li>
<li>you make changes in the branch to add a feature, <em>which relies on the file existing</em></li>
<li><em>you make bug fixes in master</em> (cannot be discarded)</li>
<li>you merge some day, and the file is gone!</li>
</ul>
<hr>
<p>How to Reproduce:</p>
<ol>
<li><p>Create a git repo with one file.</p>
<pre><code>git init
echo "test" > test.txt
git add .
git commit -m "initial commit"
</code></pre></li>
<li><p>Create a branch</p>
<pre><code>git branch branchA
</code></pre></li>
<li><p>Delete the file in master</p>
<pre><code>git rm test.txt
git commit -m "removed file from master"
</code></pre></li>
<li><p>Make ANY changes in branchA that don't touch the deleted file (it has to be unchanged to avoid Conflict)</p>
<pre><code>git checkout branchA
touch something.txt
git add .
git commit -m "some branch changes"
</code></pre></li>
</ol>
<p>From here, any way I've found to merge these two branches, the test.txt file is deleted. Assuming we were <em>relying on the file</em> for <code>branchA</code>, this is a big problem.</p>
<hr>
<p><strong>Failing examples:</strong></p>
<p>Merge 1</p>
<pre><code>git checkout branchA
git merge master
ls test.txt
</code></pre>
<p>Merge 2</p>
<pre><code>git checkout master
git merge branchA
ls test.txt
</code></pre>
<p>Rebase 1</p>
<pre><code>git checkout branchA
git rebase master
ls test.txt
</code></pre> | 1,407,694 | 7 | 1 | null | 2009-09-10 20:47:54.69 UTC | 26 | 2021-10-14 21:24:27.023 UTC | 2009-09-10 21:30:46.037 UTC | null | 10,161 | null | 10,161 | null | 1 | 82 | git|merge|branch | 74,570 | <p>This is an interesting issue. Because you deleted the file after <code>BranchA</code> was created, and then are merging <code>master</code> into <code>BranchA</code>, I'm not sure how Git would be able to realize there is a conflict.</p>
<p>After the bad merge you can undo, and then re-merge, but add back the file:</p>
<pre><code>git checkout HEAD@{1} .
git merge --no-commit master
git checkout master test.txt
git add test.txt
git commit
</code></pre> |
2,035,061 | Select tableview row programmatically | <p>How do I programmatically select a <code>UITableView</code> row so that </p>
<pre><code>- (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath
</code></pre>
<p>gets executed? <code>selectRowAtIndexPath</code> will only highlight the row. </p> | 2,035,171 | 7 | 1 | null | 2010-01-09 21:39:24.953 UTC | 24 | 2020-01-05 10:04:01.427 UTC | 2014-05-14 15:29:54.053 UTC | null | 1,141,395 | null | 40,106 | null | 1 | 141 | iphone|objective-c|cocoa-touch|uitableview | 130,989 | <p>From <a href="https://developer.apple.com/documentation/uikit/uitableview/1614875-selectrowatindexpath?language=objc" rel="noreferrer">reference documentation:</a></p>
<blockquote>
<p>Calling this method does not cause the delegate to receive a <code>tableView:willSelectRowAtIndexPath:</code> or <code>tableView:didSelectRowAtIndexPath:</code> message, nor does it send <code>UITableViewSelectionDidChangeNotification</code> notifications to observers.</p>
</blockquote>
<p>What I would do is:</p>
<pre><code>- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[self doSomethingWithRowAtIndexPath:indexPath];
}
</code></pre>
<p>And then, from where you wanted to call selectRowAtIndexPath, you instead call doSomethingWithRowAtIndexPath. On top of that, you can additionally also call selectRowAtIndexPath if you want the UI feedback to happen.</p> |
2,217,928 | How do I write a regular expression that excludes rather than matches, e.g., not (this|string)? | <p>I am stumped trying to create an Emacs regular-expression that excludes groups. <code>[^]</code> excludes individual characters in a set, but I want to exclude specific <em>sequences</em> of characters: something like <code>[^(not|this)]</code>, so that strings containing "not" or "this" are not matched.</p>
<p>In principle, I could write <code>([^n][^o][^t]|[^...])</code>, but is there another way that's cleaner?</p> | 2,218,072 | 8 | 3 | null | 2010-02-07 19:16:42.253 UTC | 6 | 2021-04-06 14:48:47.587 UTC | 2017-03-13 18:30:52.383 UTC | null | 1,905,949 | null | 206,328 | null | 1 | 33 | regex|emacs|elisp|regex-negation|regex-group | 32,809 | <p>First of all: <code>[^n][^o][^t]</code> is not a solution. This would also exclude words like <code>nil</code> (<code>[^n]</code> does not match), <code>bob</code> (<code>[^o]</code> does not match) or <code>cat</code> (<code>[^t]</code> does not match).</p>
<p>But it is possible to build a regular expression with basic syntax that does match strings that neither contain <code>not</code> nor <code>this</code>:</p>
<pre><code>^([^nt]|n($|[^o]|o($|[^t]))|t($|[^h]|h($|[^i]|i($|[^s]))))*$
</code></pre>
<p>The pattern of this regular expression is to allow any character that is not the first character of the words or only prefixes of the words but not the whole words.</p> |
2,273,330 | Restore the state of std::cout after manipulating it | <p>Suppose I have a code like this:</p>
<pre><code>void printHex(std::ostream& x){
x<<std::hex<<123;
}
..
int main(){
std::cout<<100; // prints 100 base 10
printHex(std::cout); //prints 123 in hex
std::cout<<73; //problem! prints 73 in hex..
}
</code></pre>
<p>My question is if there is any way to 'restore' the state of <code>cout</code> to its original one after returning from the function? (Somewhat like <code>std::boolalpha</code> and <code>std::noboolalpha</code>..) ?</p>
<p>Thanks.</p> | 2,273,352 | 9 | 6 | null | 2010-02-16 13:53:21.943 UTC | 35 | 2022-09-04 07:50:54.917 UTC | 2019-09-17 07:38:49.603 UTC | null | 9,254,404 | null | 227,884 | null | 1 | 139 | c++|iostream | 54,251 | <p>you need to <code>#include <iostream></code> or <code>#include <ios></code> then when required:</p>
<pre><code>std::ios_base::fmtflags f( cout.flags() );
//Your code here...
cout.flags( f );
</code></pre>
<p>You can put these at the beginning and end of your function, or check out <a href="https://stackoverflow.com/a/43771309/921224">this answer</a> on how to use this with <a href="https://stackoverflow.com/questions/2321511/what-is-meant-by-resource-acquisition-is-initialization-raii">RAII</a>.</p> |
2,251,714 | Set title background color | <p>In my android application I want the standard/basic title bar to change color.</p>
<p>To change the text color you have <code>setTitleColor(int color)</code>, is there a way to change the background color of the bar?</p> | 2,285,722 | 13 | 2 | null | 2010-02-12 12:21:57.727 UTC | 76 | 2020-06-05 23:39:02.417 UTC | 2012-07-27 19:35:27.457 UTC | null | 950,912 | null | 174,868 | null | 1 | 107 | android|title|titlebar | 212,746 | <p>This <a href="http://www.anddev.org/my_own_titlebar_backbutton_like_on_the_iphone-t4591.html" rel="noreferrer">thread</a> will get you started with building your own title bar in a xml file and using it in your activities</p>
<p><strong>Edit</strong></p>
<p>Here is a brief summary of the content of the link above - This is <strong>just</strong> to set the color of the text and the background of the title bar - no resizing, no buttons, just the simpliest sample </p>
<p><em>res/layout/mytitle.xml</em> - This is the view that will represent the title bar</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/myTitle"
android:text="This is my new title"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:textColor="@color/titletextcolor"
/>
</code></pre>
<p><em>res/values/themes.xml</em> - We want to keep the default android theme and just need to change the background color of the title background. So we create a theme that inherits the default theme and set the background style to our own style.</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="customTheme" parent="android:Theme">
<item name="android:windowTitleBackgroundStyle">@style/WindowTitleBackground</item>
</style>
</resources>
</code></pre>
<p><em>res/values/styles.xml</em> - This is where we set the theme to use the color we want for the title background</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="WindowTitleBackground">
<item name="android:background">@color/titlebackgroundcolor</item>
</style>
</resources>
</code></pre>
<p><em>res/values/colors.xml</em> - Set here the color you want</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="titlebackgroundcolor">#3232CD</color>
<color name="titletextcolor">#FFFF00</color>
</resources>
</code></pre>
<p>In the <em>AndroidMANIFEST.xml</em>, set the theme attribute either in the application (for the whole application) or in the activity (only this activity) tags</p>
<pre><code><activity android:name=".CustomTitleBar" android:theme="@style/customTheme" ...
</code></pre>
<p><em>From the Activity (called CustomTitleBar) :</em></p>
<pre><code>@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.main);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.mytitle);
}
</code></pre> |
1,595,498 | A difference in style: IDictionary vs Dictionary | <p>I have a friend who's just getting into .NET development after developing in Java for ages and, after looking at some of his code I notice that he's doing the following quite often:</p>
<pre><code>IDictionary<string, MyClass> dictionary = new Dictionary<string, MyClass>();
</code></pre>
<p>He's declaring dictionary as the Interface rather than the Class. Typically I would do the following:</p>
<pre><code>Dictionary<string, MyClass> dictionary = new Dictionary<string, MyClass>();
</code></pre>
<p>I'd only use the IDictionary interface when it's needed (say, for example to pass the dictionary to a method that accepts an IDictionary interface).</p>
<p>My question is: are there any merits to his way of doing things? Is this a common practice in Java?</p> | 1,595,519 | 14 | 5 | null | 2009-10-20 15:31:40.257 UTC | 21 | 2019-08-11 11:48:28.52 UTC | null | null | null | null | 100,142 | null | 1 | 84 | c#|java|.net|interface | 74,263 | <p>If IDictionary is a "more generic" type than Dictionary then it makes sense to use the more generic type in declaring variables. That way you don't have to care as much about the implementing class assigned to the variable and you can change the type easily in the future without having to change a lot of following code. For example, in Java it's often considered better to do</p>
<pre><code>List<Integer> intList=new LinkedList<Integer>();
</code></pre>
<p>than it is to do</p>
<pre><code>LinkedList<Integer> intList=new LinkedList<Integer>();
</code></pre>
<p>That way I'm sure all following code treats the list as a List and not a LinkedList, making it easy in the future to switch out LinkedList for Vector or any other class which implements List. I'd say this is common to Java and good programming in general.</p> |
1,724,381 | Explaining why "Just add another column to the DB" is a bad idea, to non programmers | <p>I have sales people and bean counters who are trying to sell customizations to clients, which is fine. But when a complex change request comes in that I send back a large estimate for, they get confused. Often they come back at me with "Why can't you just add another column?" which by another, they mean a dozen or so custom columns PER client.</p>
<p>So far all I can come back with is "We are trying to keep the database well normalized" which means nothing to them. I tell them I can create a system of tables that allows each client to define their own set of custom fields, but of course that takes more time and money than "just adding a few columns". And of course they want to have their cake and eat it too.</p>
<p>So how can I make them understand?</p> | 1,724,458 | 15 | 11 | null | 2009-11-12 18:32:45.507 UTC | 21 | 2011-10-11 18:41:40.297 UTC | 2010-03-23 14:35:45.523 UTC | null | 55,164 | null | 55,164 | null | 1 | 53 | sql|database|architecture|communication|normalization | 2,825 | <p>The best way I've found is to show how you can create a new <em>feature</em> out of what they're asking for that you couldn't add with just a couple customized columns. Features are better than customizations, especially when you can charge someone for it. </p>
<p>Try to make a good business case for your side before you get into the technical stuff.</p> |
42,088,294 | react native conditional rendering | <p>I am trying to use an inline if statement to check if a piece of data exists and if it does to display it. this code is currently sitting in my render, return block.</p>
<p>the problem I am having is that using this, the content is no longer being rendered</p>
<pre><code>{(() => {
if (this.props.data.size) {
<Text style={styles.headerLabel}>Sizes</Text>
{(this.props.data.size||[]).map((section,i) => (
<AddToCartRow key={i} data={section} productName={this.props.data.name} value={Config.priceToPriceWithCurrency(section.price)} />
))}
}
})()}
</code></pre> | 42,091,904 | 4 | 4 | null | 2017-02-07 11:09:11.82 UTC | 3 | 2022-03-29 18:47:21.693 UTC | null | null | null | null | 1,448,378 | null | 1 | 16 | if-statement|react-native|conditional|render | 41,552 | <pre><code>render(){
return(
<View>
{this.state.error && <Text style={{ color: 'red' }}>{this.state.errorMessage}</Text>}
<Text>Hello World!</Text>
</View>
);
}
</code></pre>
<p>There you go.</p> |
6,581,190 | Check if one of variables is set to None | <p>I recently had to implement a small check for any variables that might have not been initialized (and their default value is <code>None</code>). I came up with this:</p>
<pre><code>if None in (var1, var2, var3):
error_out()
</code></pre>
<p>While, in my eyes, bordering on beautiful, I was wondering - is this a good way to do it? Is this <strong>the</strong> way to do it? Are there any cases in which this would produce some unexpected results?</p> | 6,581,475 | 3 | 3 | null | 2011-07-05 10:25:50.333 UTC | 4 | 2015-11-18 10:21:39.087 UTC | null | null | null | null | 320,475 | null | 1 | 36 | python | 21,425 | <p>First things first: your code is valid, readable, concise... so it might not be <strong>the</strong> way to do it (idioms evolves with time and new language features) but it certainly is <strong>one of</strong> the way to do it in a pythonic way.</p>
<p>Secondly, just two observations:</p>
<p><strong>The standard way to generate errors in python is to <a href="http://docs.python.org/tutorial/errors.html" rel="noreferrer">raise Exceptions</a></strong>. You can of course wrap your exception-raising within a function, but since it's quite unusual I was just wondering if you chose this design for some specific reason. Since you can write your own Exception class, even boilerplate code like logging an error message to file could go within the class itself rather than in the wrapping function.</p>
<p>The way you wrote your test is such that <strong>you won't be able to assign <code>None</code> as a value to your variables</strong>. This might be not a problem now, but might limit your flexibility in the future. An alternative way to check for initialisation could be to simply <strong>not</strong> declare an initial value for the variable in question and then do something along the lines of:</p>
<pre><code>try:
self.variable_name
except NameError:
# here the code that runs if the variable hasn't been initialised
finally:
# [optional] here the code that should run in either case
</code></pre> |
6,408,596 | IntelliJ IDEA: How can I create an exception breakpoint that stops on all exceptions *except for* ClassNotFoundException? | <p>I'd like to run my test suite in the debugger and break on any unexpected exception, but the Java classloaders throw lots of ClassNotFoundExceptions during normal operation. </p>
<p>So it would be nice if I could create an exception breakpoint that ignores ClassNotFoundExceptions and stops on everything else.</p> | 8,968,448 | 3 | 1 | null | 2011-06-20 08:32:16.403 UTC | 5 | 2016-10-13 15:39:23.977 UTC | 2011-06-20 08:36:52.693 UTC | null | 587,884 | null | 55,870 | null | 1 | 38 | java|debugging|exception-handling|intellij-idea | 16,139 | <p>This answer is almost the same as that of Mindas, but the details were enough for me to ignore his suggestion the first time around, and bother the Intellij support guys/girls (thanks Serge and Eugene):</p>
<ul>
<li>Open the 'Breakpoints' window and go to the 'Exception Breakpoints' tab</li>
<li>Highlight and activate the 'Any exception' breakpoint</li>
<li><p>Activate only the 'Condition' Condition and type in the following:</p>
<pre><code>!(this instanceof java.lang.ClassNotFoundException)
</code></pre></li>
</ul>
<p>IDEA will remove 'java.lang' immediately (version 11.01), but it is required for this solution to work. If you don't use that, you will get a ClassNotFound popup box (irony oh irony).</p>
<p>I did find out that a lot of 'standard' libraries throw exceptions in their normal flow of operations. When you successfully ignore the ClassNotFoundException's, you will find that others suddenly appear. Nothing is ever easy.</p> |
6,837,392 | How to save the registers on x86_64 for an interrupt service routine? | <p>I am looking at some old code from a school project, and in trying to compile it on my laptop I ran into some problems. It was originally written for an old 32 bit version of gcc. Anyway I was trying to convert some of the assembly over to 64 bit compatible code and hit a few snags.</p>
<p>Here is the original code:</p>
<pre><code>pusha
pushl %ds
pushl %es
pushl %fs
pushl %gs
pushl %ss
</code></pre>
<p><code>pusha</code> is not valid in 64 bit mode. So what would be the proper way to do this in x86_64 assembly while in 64 bit mode?</p>
<p>There has got to be a reason why <code>pusha</code> is not valid in 64 bit mode, so I have a feeling manually pushing all the registers may not be a good idea.</p> | 6,857,368 | 4 | 0 | null | 2011-07-26 22:30:42.663 UTC | 7 | 2022-05-29 18:48:05.677 UTC | 2022-05-29 18:48:05.677 UTC | null | 224,132 | null | 65,928 | null | 1 | 29 | assembly|x86-64|cpu-registers|interrupt-handling|isr | 30,502 | <p>Learn from existing code that does this kind of thing. For example:</p>
<ul>
<li>Linux (search for <code>SAVE_ARGS_IRQ</code>): <a href="https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/arch/x86/kernel/entry_64.S?id=6c3176a21652e506ca7efb8fa37a651a3c513bb5" rel="nofollow noreferrer">entry_64.S</a></li>
<li>OpenSolaris (search for <code>INTR_PUSH</code>): <a href="https://hg.java.net/hg/solaris~on-src/file/tip/usr/src/uts/intel/amd64/sys/privregs.h" rel="nofollow noreferrer">privregs.h</a></li>
<li>FreeBSD (search for <code>IDT_VEC</code>): <a href="http://www.freebsd.org/cgi/cvsweb.cgi/src/sys/amd64/amd64/exception.S" rel="nofollow noreferrer">exception.S</a> (similar is <a href="http://cvsweb.netbsd.org/bsdweb.cgi/src/sys/arch/amd64/amd64/vector.S" rel="nofollow noreferrer">vector.S</a> in NetBSD)</li>
</ul>
<p>In fact, "manually pushing" the regs is the only way on AMD64 since <code>PUSHA</code> doesn't exist there. AMD64 isn't unique in this aspect - most non-x86 CPUs do require register-by-register saves/restores as well at some point.</p>
<p>But if you inspect the referenced sourcecode closely you'll find that not all interrupt handlers require to save/restore the entire register set, so there is room for optimizations.</p> |
6,491,627 | Prevent table row onclick event to fire when clicking button inside the row | <p>I have a table row with ONCLICK event (that toggles additional data below). Inside one of the row cells I have a button (when clicked is performing an AJAX action).
When I click on the button - the Row's onclick event also fires and what happens is that the additional data appears before the AJAX call completes (which is a bad behavior for me).
Any ideas how can I solve this elegantly? (without identifying and coding it into the row's onclick code)
Thanks </p> | 6,491,721 | 4 | 0 | null | 2011-06-27 10:40:42.333 UTC | 9 | 2021-04-01 21:38:23.333 UTC | null | null | null | null | 414,410 | null | 1 | 35 | javascript|html|dom | 24,116 | <p>Add an <code>event.stopPropagation();</code> to your buttons <code>click</code> handler. For more information, have a look <a href="https://developer.mozilla.org/en/DOM/event.stopPropagation" rel="noreferrer">here</a>.</p> |
36,012,616 | Working with SQL views in Entity Framework Core | <p>For example, I have such model:</p>
<pre><code>public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
public BlogImage BlogImage { get; set; }
}
public class BlogImage
{
public int BlogImageId { get; set; }
public byte[] Image { get; set; }
public string Caption { get; set; }
public int BlogId { get; set; }
public Blog Blog { get; set; }
}
</code></pre>
<p>I want to return in <strong>ImageView</strong> view <strong>Url</strong> and <strong>Image</strong>. </p>
<p>Where do I need to create and define that SQL view? </p> | 52,170,144 | 7 | 4 | null | 2016-03-15 13:24:30.853 UTC | 15 | 2021-06-23 06:00:09.97 UTC | 2020-06-10 08:26:22.2 UTC | null | 5,170,364 | null | 5,717,094 | null | 1 | 72 | c#|entity-framework|entity-framework-core|sql-view | 135,597 | <p>In <strong>Entity Framework Core 2.1</strong> we can use <a href="https://docs.microsoft.com/en-us/ef/core/modeling/query-types" rel="noreferrer">Query Types</a> as Yuriy N suggested.</p>
<p>A more detailed article on how to use them can be found <a href="https://msdn.microsoft.com/magazine/mt847184" rel="noreferrer">here</a> </p>
<p>The most straight forward approach according to the article's examples would be:</p>
<p>1.We have for example the following entity Models to manage publications</p>
<pre><code>public class Magazine
{
public int MagazineId { get; set; }
public string Name { get; set; }
public string Publisher { get; set; }
public List<Article> Articles { get; set; }
}
public class Article
{
public int ArticleId { get; set; }
public string Title { get; set; }
public int MagazineId { get; set; }
public DateTime PublishDate { get; set; }
public Author Author { get; set; }
public int AuthorId { get; set; }
}
public class Author
{
public int AuthorId { get; set; }
public string Name { get; set; }
public List<Article> Articles { get; set; }
}
</code></pre>
<p>2.We have a view called AuthorArticleCounts, defined to return the name and number of articles an author has written</p>
<pre><code>SELECT
a.AuthorName,
Count(r.ArticleId) as ArticleCount
from Authors a
JOIN Articles r on r.AuthorId = a.AuthorId
GROUP BY a.AuthorName
</code></pre>
<p>3.We go and create a model to be used for the View</p>
<pre><code>public class AuthorArticleCount
{
public string AuthorName { get; private set; }
public int ArticleCount { get; private set; }
}
</code></pre>
<p>4.We create after that a DbQuery property in my DbContext to consume the view results inside the Model</p>
<pre><code>public DbQuery<AuthorArticleCount> AuthorArticleCounts{get;set;}
</code></pre>
<p>4.1. You might need to override OnModelCreating() and set up the View especially if you have different view name than your Class.</p>
<pre><code>protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Query<AuthorArticleCount>().ToView("AuthorArticleCount");
}
</code></pre>
<p>5.Finally we can easily get the results of the View like this.</p>
<pre><code>var results=_context.AuthorArticleCounts.ToList();
</code></pre>
<p><strong>UPDATE</strong>
According to ssougnez's comment</p>
<blockquote>
<p>It's worth noting that DbQuery won't be/is not supported anymore in EF
Core 3.0. <strong>See <a href="https://docs.microsoft.com/en-us/ef/core/modeling/keyless-entity-types" rel="noreferrer">here</a></strong></p>
</blockquote> |
57,005,230 | Custom modal transitions in SwiftUI | <p>I'm trying to recreate the iOS 11/12 App Store with <strong>SwiftUI</strong>.
Let's imagine the "story" is the view displayed when tapping on the card.</p>
<p>I've done the cards, but the problem I'm having now is how to do the animation done to display the "story".</p>
<p>As I'm not good at explaining, here you have a gif:</p>
<p><a href="https://raw.githubusercontent.com/PaoloCuscela/Cards/master/Images/DetailView.gif" rel="noreferrer">Gif 1</a>
<a href="https://drive.google.com/file/d/1Q-D4HEDCaV6GP_9Pdkb48S9x4wlG1K5t/view?usp=sharing" rel="noreferrer">Gif 2</a></p>
<p>I've thought of making the whole card a PresentationLink, but the "story" is displayed as a modal, so it doesn't cover the whole screen and doesn't do the animation I want.</p>
<p>The most similar thing would be NavigationLink, but that then obliges me to add a NavigationView, and the card is displayed like another page.</p>
<p>I actually do not care whether its a PresentationLink or NavigationLink or whatever as long as it does the animation and displays the "story".</p>
<p>Thanks in advance.</p>
<p>My code:</p>
<p><strong>Card.swift</strong></p>
<pre><code>struct Card: View {
var icon: UIImage = UIImage(named: "flappy")!
var cardTitle: String = "Welcome to \nCards!"
var cardSubtitle: String = ""
var itemTitle: String = "Flappy Bird"
var itemSubtitle: String = "Flap That!"
var cardCategory: String = ""
var textColor: UIColor = UIColor.white
var background: String = ""
var titleColor: Color = .black
var backgroundColor: Color = .white
var body: some View {
VStack {
if background != "" {
Image(background)
.resizable()
.frame(width: 380, height: 400)
.cornerRadius(20)
} else {
RoundedRectangle(cornerRadius: 20)
.frame(width: 400, height: 400)
.foregroundColor(backgroundColor)
}
VStack {
HStack {
VStack(alignment: .leading) {
if cardCategory != "" {
Text(verbatim: cardCategory.uppercased())
.font(.headline)
.fontWeight(.heavy)
.opacity(0.3)
.foregroundColor(titleColor)
//.opacity(1)
}
HStack {
Text(verbatim: cardTitle)
.font(.largeTitle)
.fontWeight(.heavy)
.lineLimit(3)
.foregroundColor(titleColor)
}
}
Spacer()
}.offset(y: -390)
.padding(.bottom, -390)
HStack {
if cardSubtitle != "" {
Text(verbatim: cardSubtitle)
.font(.system(size: 17))
.foregroundColor(titleColor)
}
Spacer()
}
.offset(y: -50)
.padding(.bottom, -50)
}
.padding(.leading)
}.padding(.leading).padding(.trailing)
}
}
</code></pre>
<p>So </p>
<pre><code>Card(cardSubtitle: "Welcome to this library I made :p", cardCategory: "CONNECT", background: "flBackground", titleColor: .white)
</code></pre>
<p>displays:
<a href="https://i.stack.imgur.com/T8deD.png" rel="noreferrer"><img src="https://i.stack.imgur.com/T8deD.png" alt="Card 1"></a></p> | 57,701,274 | 2 | 4 | null | 2019-07-12 10:35:04.203 UTC | 13 | 2021-09-29 08:04:18.513 UTC | 2019-07-12 14:35:26.733 UTC | null | 9,647,800 | null | 9,647,800 | null | 1 | 18 | ios|swift|swiftui | 9,458 | <p>SwiftUI doesn't do custom modal transitions right now, so we have to use a workaround.</p>
<p>One method that I could think of is to do the presentation yourself using a <code>ZStack</code>. The source frame could be obtained using a <code>GeometryReader</code>. Then, the destination shape could be controlled using frame and position modifiers.</p>
<p>In the beginning, the destination will be set to exactly match position and size of the source. Then immediately afterwards, the destination will be set to fullscreen size in an animation block.</p>
<pre><code>struct ContentView: View {
@State var isPresenting = false
@State var isFullscreen = false
@State var sourceRect: CGRect? = nil
var body: some View {
ZStack {
GeometryReader { proxy in
Button(action: {
self.isFullscreen = false
self.isPresenting = true
self.sourceRect = proxy.frame(in: .global)
}) { ... }
}
if isPresenting {
GeometryReader { proxy in
ModalView()
.frame(
width: self.isFullscreen ? nil : self.sourceRect?.width ?? nil,
height: self.isFullscreen ? nil : self.sourceRect?.height ?? nil)
.position(
self.isFullscreen ? proxy.frame(in: .global).center :
self.sourceRect?.center ?? proxy.frame(in: .global).center)
.onAppear {
withAnimation {
self.isFullscreen = true
}
}
}
}
}
.edgesIgnoringSafeArea(.all)
}
}
extension CGRect {
var center : CGPoint {
return CGPoint(x:self.midX, y:self.midY)
}
}
</code></pre> |
18,254,104 | How do I create a table based on another table | <p>I want to create a table based on the definition of another table.</p>
<p>I'm coming from oracle and I'd normally do this:</p>
<pre><code> CREATE TABLE schema.newtable AS SELECT * FROM schema.oldtable;
</code></pre>
<p>I can't seem to be able to do this in SQL Server 2008.</p> | 18,254,116 | 2 | 0 | null | 2013-08-15 13:48:14.3 UTC | 17 | 2013-08-15 14:29:44.357 UTC | 2013-08-15 14:29:44.357 UTC | null | 61,305 | null | 1,654,555 | null | 1 | 47 | sql-server|sql-server-2008|create-table | 236,445 | <p>There is no such syntax in SQL Server, though <code>CREATE TABLE AS ... SELECT</code> does exist in PDW. In SQL Server you can use this query to create an empty table:</p>
<pre><code>SELECT * INTO schema.newtable FROM schema.oldtable WHERE 1 = 0;
</code></pre>
<p>(If you want to make a copy of the table <em>including</em> all of the data, then leave out the <code>WHERE</code> clause.)</p>
<p>Note that this creates the same column structure (including an IDENTITY column if one exists) but it does not copy any indexes, constraints, triggers, etc.</p> |
15,715,574 | Can I calculate and use element height with SASS \ Compass | <p>I use sass and compass in my RoR project. I need to assign to the <code>top</code> CSS property of an element the value, which is element height divide by -2. Can I do it with SASS \ Compass?</p> | 15,717,408 | 4 | 0 | null | 2013-03-30 06:10:39.04 UTC | 0 | 2019-10-30 21:06:24.7 UTC | null | null | null | null | 764,182 | null | 1 | 11 | css|sass|compass-sass | 64,657 | <p>You seem to have got the <a href="https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem">XY problem</a>. You have a task to solve, and instead of asking us about the task, you ask about a solution that you tried and already found inappropriate.</p>
<p>Why do you want to apply the <code>top</code> property equal to half of element's height and negated? Because you want to <strong>move an absolutely positioned element half its height up</strong>. This is the original task.</p>
<p>There's a simple solution to achieve that, and SASS is not even necessary! (Actually, as long as you don't know element's height, SASS can't provide more help than CSS.)</p>
<p>We'll need an extra wrapper:
</p>
<pre><code><div class=container>
<div class=elements-wrapper>
<div class=element>
</div>
</div>
</div>
</code></pre>
<p>To push the element up for 50% of its height, do two simple steps:</p>
<p>1) Push its wrapper up fully out of the container:
</p>
<pre><code>.elements-wrapper {
position: absolute;
bottom: 100%; }
</code></pre>
<p>2) Now pull the element down for 50% of its height:</p>
<pre><code>.element {
margin-bottom: -50%; }
</code></pre>
<p>That's it!</p>
<p>When you do <code>margin-bottom: -50%</code>, you actually pull the element 50% down of its <em>wrapper's</em> height. But the wrapper's height it equal to the element's height!</p>
<p>Don't forget to apply <code>position: relative</code> to the container, otherwise <code>position: absolute</code> will relative to the window, not the container.</p>
<p>Here's a <strong>demo</strong> with well-commented code: <a href="http://jsbin.com/uwunal/4/edit" rel="noreferrer">http://jsbin.com/uwunal/4/edit</a></p>
<h2>UPD 2013-04-16</h2>
<p>I've just realised that this is a phony.</p>
<p>In CSS the percentages of top and bottom margins refer to the <strong>width</strong> of the container. So the above example only works because the container is square.</p> |
19,054,625 | Changing back button in iOS 7 disables swipe to navigate back | <p>I have an iOS 7 app where I am setting a custom back button like this:</p>
<pre><code> UIImage *backButtonImage = [UIImage imageNamed:@"back-button"];
UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
[backButton setImage:backButtonImage forState:UIControlStateNormal];
backButton.frame = CGRectMake(0, 0, 20, 20);
[backButton addTarget:self
action:@selector(popViewController)
forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *backBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
viewController.navigationItem.leftBarButtonItem = backBarButtonItem;
</code></pre>
<p>But this disables the iOS 7 "swipe left to right" gesture to navigate to the previous controller. Does anyone know how I can set a custom button and still keep this gesture enabled?</p>
<p>EDIT:
I tried to set the viewController.navigationItem.backBarButtonItem instead, but this doesn't seem to show my custom image.</p> | 19,076,323 | 14 | 2 | null | 2013-09-27 15:31:01.713 UTC | 58 | 2018-11-29 07:49:12.623 UTC | 2013-10-28 18:46:30.827 UTC | null | 813,137 | null | 1,199,792 | null | 1 | 81 | ios|uinavigationcontroller|ios7|uibarbuttonitem|uiviewanimation | 51,591 | <p><strong>IMPORTANT:</strong>
This is a hack. I would recommend taking a look at this <a href="https://stackoverflow.com/a/20330647/605197">answer</a>.</p>
<p>Calling the following line after assigning the <code>leftBarButtonItem</code> worked for me:</p>
<pre><code>self.navigationController.interactivePopGestureRecognizer.delegate = self;
</code></pre>
<p><strong>Edit:</strong>
This does not work if called in <code>init</code> methods. It should be called in <code>viewDidLoad</code> or similar methods.</p> |
16,278,977 | GCM how to unregister a device with GCM and 3rd party server | <p>I've an app that uses GCM push notifications. It works fine and my device registers and receives push messages. </p>
<p>If i uninstall the app from my device i no longer receive the messages as you would expect. The TextBox in which you send messages on the server is still there after i un-install the app, which i'd also expect.</p>
<p>I've looked at the documentation regarding unregistering and you can do it manually or automatically. </p>
<pre><code>The end user uninstalls the application.
The 3rd-party server sends a message to GCM server.
The GCM server sends the message to the device.
The GCM client receives the message and queries Package Manager about whether there are broadcast receivers configured to receive it, which returns false.
The GCM client informs the GCM server that the application was uninstalled.
The GCM server marks the registration ID for deletion.
The 3rd-party server sends a message to GCM.
The GCM returns a NotRegistered error message to the 3rd-party server.
The 3rd-party deletes the registration ID.
</code></pre>
<p>I don't understand the next to last statement in the above list.</p>
<pre><code>The GCM returns a NotRegistered error message to the 3rd-party server.
</code></pre>
<p>How is this acheived? </p>
<p>Also if the app is uninstalled from the device, how can it do the statement below? Is there an app lifecycle method that execute as an app is removed from a device? If there is, is this the place where code is placed that informs GCM server of the uninstall and the calls a php script on the 3rd party server that removes the regID from the DB?</p>
<pre><code>The GCM client informs the GCM server that the application was uninstalled.
</code></pre>
<p>thanks in advance,</p>
<p>Matt</p>
<pre><code>[edit1]
static void unregister(final Context context, final String regId) {
Log.i(TAG, "unregistering device (regId = " + regId + ")");
String serverUrl = SERVER_URL + "/unregister.php";
Map<String, String> params = new HashMap<String, String>();
params.put("regId", regId);
try {
post(serverUrl, params);
GCMRegistrar.setRegisteredOnServer(context, false);
String message = context.getString(R.string.server_unregistered);
CommonUtilities.displayMessage(context, message);
} catch (IOException e) {
// At this point the device is unregistered from GCM, but still
// registered in the server.
// We could try to unregister again, but it is not necessary:
// if the server tries to send a message to the device, it will get
// a "NotRegistered" error message and should unregister the device.
String message = context.getString(R.string.server_unregister_error,
e.getMessage());
CommonUtilities.displayMessage(context, message);
}
}
</code></pre>
<p>[EDIT2]
The unregister code below is for unregistering the device on the 3rd party server after deleting the app from the phone. The code is in addition to the tutorial below.</p>
<p><a href="http://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/">tutorial</a></p>
<p>send_messages.php</p>
<pre><code><?php
if (isset($_GET["regId"]) && isset($_GET["message"])) {
$regId = $_GET["regId"];
$message = $_GET["message"];
$strRegID = strval($regId);
include_once './GCM.php';
include_once './db_functions.php';
$gcm = new GCM();
$registatoin_ids = array($regId);
$message = array("price" => $message);
$result = $gcm->send_notification($registatoin_ids, $message);
$db = new db_Functions();
if (strcasecmp ( strval($result) , 'NotRegistered' )) {
$db->deleteUser($strRegID);
}
}
?>
</code></pre>
<p>db_functions.php</p>
<pre><code>public function deleteUser($regid) {
$strRegID = strval($regid);
$serverName = "LOCALHOST\SQLEXPRESS";
$uid = "gcm";
$pwd = "gcm";
$databaseName = "gcm";
$connectionInfo = array( "UID"=>$uid, "PWD"=>$pwd, "Database"=>$databaseName);
$db = sqlsrv_connect($serverName,$connectionInfo) or die("Unable to connect to server");
$query = "DELETE FROM gcmUser2 WHERE gcuRegID = '$regid'";
$result = sqlsrv_query($db, $query);
}
</code></pre> | 16,279,189 | 1 | 0 | null | 2013-04-29 12:45:25.387 UTC | 8 | 2013-09-26 14:27:43.627 UTC | 2013-04-30 10:19:16.187 UTC | null | 532,462 | null | 532,462 | null | 1 | 11 | android|push-notification|google-cloud-messaging | 10,313 | <p>When the GCM server attempts to send the message to the device after the app has been uninstalled, the GCM client detects that this app is not longer installed on the device. You don't do it in your application code. The GCM client component of the Android OS does it.</p>
<p>The next time to try to send a message to the app on the device that uninstalled it, the GCM server will already know it has been uninstalled, and send you the <code>NotRegistered</code> error.</p>
<p>There is no lifecycle method called when the app is removed from the device. If there was, you wouldn't need the sequence of events you quoted above in order for the GCM server and the 3rd party server to detect that the app was uninstalled (since you could have used such a method to both unregister your app from the GCM server and to let the 3rd party server know the app was uninstalled from that device).</p> |
719,020 | Is there an async version of DirectoryInfo.GetFiles / Directory.GetDirectories in dotNet? | <p>Is there an asynchronous version of DirectoryInfo.GetFiles / Directory.GetDirectories in dotNet? I'd like to use them in an F# async block, and it'd be nice to have a version that can be called with AsyncCallbacks. </p>
<p>Problem is I'm trying to suck in a bunch of directories, probably on SMB mounts over slow network connections, and I don't want a bunch of thread pool threads sitting around waiting for network reads when they could be doing other work.</p> | 719,044 | 7 | 0 | null | 2009-04-05 14:40:19.07 UTC | 11 | 2016-10-31 15:37:24.553 UTC | 2009-04-05 15:11:52.63 UTC | Noldorin | 44,389 | null | 73,046 | null | 1 | 54 | .net|f#|asynchronous|directoryinfo|async-workflow | 28,040 | <p>No, I don't think there is. The pool thread approach is probably the most pragmatic. Alternatively, I guess you could drop down to P/Invoke - but that would be a <em>lot</em> more work.</p> |
231,229 | How to generate a Makefile with source in sub-directories using just one makefile | <p>I have source in a bunch of subdirectories like:</p>
<pre><code>src/widgets/apple.cpp
src/widgets/knob.cpp
src/tests/blend.cpp
src/ui/flash.cpp
</code></pre>
<p>In the root of the project I want to generate a single Makefile using a rule like:</p>
<pre><code>%.o: %.cpp
$(CC) -c $<
build/test.exe: build/widgets/apple.o build/widgets/knob.o build/tests/blend.o src/ui/flash.o
$(LD) build/widgets/apple.o .... build/ui/flash.o -o build/test.exe
</code></pre>
<p>When I try this it does not find a rule for build/widgets/apple.o. Can I change something so that the %.o: %.cpp is used when it needs to make build/widgets/apple.o ?</p> | 231,418 | 7 | 0 | null | 2008-10-23 19:56:32.307 UTC | 47 | 2016-04-26 16:59:03.777 UTC | null | null | null | James Dean | 7,743 | null | 1 | 66 | makefile | 148,302 | <p>The reason is that your rule</p>
<pre><code>%.o: %.cpp
...
</code></pre>
<p>expects the .cpp file to reside in the same directory as the .o your building. Since test.exe in your case depends on build/widgets/apple.o (etc), make is expecting apple.cpp to be build/widgets/apple.cpp.</p>
<p>You can use VPATH to resolve this:</p>
<pre><code>VPATH = src/widgets
BUILDDIR = build/widgets
$(BUILDDIR)/%.o: %.cpp
...
</code></pre>
<p>When attempting to build "build/widgets/apple.o", make will search for apple.cpp <strong>in VPATH</strong>. Note that the build rule has to use special variables in order to access the actual filename make finds:</p>
<pre><code>$(BUILDDIR)/%.o: %.cpp
$(CC) $< -o $@
</code></pre>
<p>Where "$<" expands to the path where make located the first dependency.</p>
<p>Also note that this will build all the .o files in build/widgets. If you want to build the binaries in different directories, you can do something like</p>
<pre><code>build/widgets/%.o: %.cpp
....
build/ui/%.o: %.cpp
....
build/tests/%.o: %.cpp
....
</code></pre>
<p>I would recommend that you use "<a href="http://www.gnu.org/software/make/manual/make.html#Canned-Recipes" rel="noreferrer">canned command sequences</a>" in order to avoid repeating the actual compiler build rule:</p>
<pre><code>define cc-command
$(CC) $(CFLAGS) $< -o $@
endef
</code></pre>
<p>You can then have multiple rules like this:</p>
<pre><code>build1/foo.o build1/bar.o: %.o: %.cpp
$(cc-command)
build2/frotz.o build2/fie.o: %.o: %.cpp
$(cc-command)
</code></pre> |
680,498 | How can I make a WPF Expander Stretch? | <p>The <code>Expander</code> control in WPF does not stretch to fill all the available space. Is there any solutions in XAML for this?</p> | 680,512 | 8 | 0 | null | 2009-03-25 07:04:37.747 UTC | 6 | 2019-07-25 14:36:31.603 UTC | 2013-09-11 02:10:48.797 UTC | null | 305,637 | Ngm | 46,279 | null | 1 | 32 | c#|wpf|expander|stretch | 37,438 | <p>All you need to do is this:</p>
<pre><code><Expander>
<Expander.Header>
<TextBlock
Text="I am header text..."
Background="Blue"
Width="{Binding
RelativeSource={RelativeSource
Mode=FindAncestor,
AncestorType={x:Type Expander}},
Path=ActualWidth}"
/>
</Expander.Header>
<TextBlock Background="Red">
I am some content...
</TextBlock>
</Expander>
</code></pre>
<p><a href="http://joshsmithonwpf.wordpress.com/2007/02/24/stretching-content-in-an-expander-header/" rel="noreferrer">http://joshsmithonwpf.wordpress.com/2007/02/24/stretching-content-in-an-expander-header/</a></p> |
1,325,388 | How to find out why renameTo() failed? | <p>I am using WinXP. I use java to generate a list of files. The file will be created as abc.txt.temp at first, and after completing the generation, it will be renamed to abc.txt.</p>
<p>However, when i generating the files, some of the files failed to be renamed. It happen randomly.</p>
<p>Is there anyway to find out the reason why it failed?</p>
<pre class="lang-java prettyprint-override"><code>int maxRetries = 60;
logger.debug("retry");
while (maxRetries-- > 0)
{
if (isSuccess = file.renameTo(file2))
{
break;
}
try
{
logger.debug("retry " + maxRetries);
Thread.sleep(1000);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//file.renameTo(file2);
Thread.currentThread().getThreadGroup().getParent().list();
</code></pre>
<p>And the result:</p>
<pre class="lang-none prettyprint-override"><code>[DEBUG][2009-08-25 08:57:52,386] - retry 1
[DEBUG][2009-08-25 08:57:53,386] - retry 0
java.lang.ThreadGroup[name=system,maxpri=10]
Thread[Reference Handler,10,system]
Thread[Finalizer,8,system]
Thread[Signal Dispatcher,9,system]
Thread[Attach Listener,5,system]
java.lang.ThreadGroup[name=main,maxpri=10]
Thread[main,5,main]
Thread[log4j mail appender,5,main]
[DEBUG][2009-08-25 08:57:54,386] - isSuccess:false
</code></pre>
<p>I would like to know a systematic approach to figure out the reason. Thanks.</p> | 1,325,458 | 8 | 4 | null | 2009-08-25 00:00:06.63 UTC | 5 | 2021-03-02 18:16:20.123 UTC | 2017-12-18 17:44:12.4 UTC | null | 4,551,041 | null | 125,470 | null | 1 | 32 | java|file|file-io|file-rename | 60,939 | <p>It's possible that the reason that renaming failed is that the file is still open. Even if you are closing the file, it could be held open because of (for example):</p>
<ol>
<li>A file handle is inherited by a subprocess of your process</li>
<li>An anti-virus program is scanning the file for viruses, and so has it open</li>
<li>An indexer (such as Google Desktop or the Windows indexing service) has the file open</li>
</ol>
<p>To help find out what is keeping the file open, use tools such as <a href="http://technet.microsoft.com/en-us/sysinternals/bb896642.aspx" rel="noreferrer">FileMon</a> and <a href="http://technet.microsoft.com/en-us/sysinternals/bb896655.aspx" rel="noreferrer">Handle</a>.</p>
<p><strong>Update:</strong> A tool such as Unlocker may not help, if the file is only held open for a very short time (as would be the case for an anti-virus scan). However, if javaw.exe is shown as having the file open, that's your problem right there.</p> |
420,703 | How do I add multiple arguments to my custom template filter in a django template? | <h2>Here's my custom filter:</h2>
<pre><code>from django import template
register = template.Library()
@register.filter
def replace(value, cherche, remplacement):
return value.replace(cherche, remplacement)
</code></pre>
<h2>and here are the ways I tried using it in my template file that resulted in an error:</h2>
<pre><code>{{ attr.name|replace:"_"," " }}
{{ attr.name|replace:"_" " " }}
{{ attr.name|replace:"_":" " }}
{{ attr.name|replace:"cherche='_', remplacement=' '" }}
</code></pre>
<p>I looked into <a href="http://docs.djangoproject.com/en/dev/howto/custom-template-tags/" rel="noreferrer">django's docs</a> and <a href="http://www.djangobook.com/en/beta/chapter10/" rel="noreferrer">book</a> but only found example using a single argument... is it even possible?</p> | 423,060 | 9 | 0 | null | 2009-01-07 15:21:36.443 UTC | 27 | 2021-02-18 05:21:12.35 UTC | null | null | null | Bernard Chhun | 48,500 | null | 1 | 104 | django|django-templates | 103,608 | <p>It is possible and fairly simple.</p>
<p>Django only allows one argument to your filter, but there's no reason you can't put all your arguments into a single string using a comma to separate them.</p>
<p>So for example, if you want a filter that checks if variable X is in the list [1,2,3,4] you will want a template filter that looks like this:</p>
<pre><code>{% if X|is_in:"1,2,3,4" %}
</code></pre>
<p>Now we can create your templatetag like this:</p>
<pre><code>from django.template import Library
register = Library()
def is_in(var, args):
if args is None:
return False
arg_list = [arg.strip() for arg in args.split(',')]
return var in arg_list
register.filter(is_in)
</code></pre>
<p>The line that creates arg_list is a generator expression that splits the args string on all the commas and calls .strip() to remove any leading and trailing spaces.</p>
<p>If, for example, the 3rd argument is an int then just do:</p>
<pre><code>arg_list[2] = int(arg_list[2])
</code></pre>
<p>Or if all of them are ints do:</p>
<pre><code>arg_list = [int(arg) for arg in args.split(',')]
</code></pre>
<p>EDIT: now to specifically answer your question by using key,value pairs as parameters, you can use the same class Django uses to parse query strings out of URL's, which then also has the benefit of handling character encoding properly according to your settings.py.</p>
<p>So, as with query strings, each parameter is separated by '&':</p>
<pre><code>{{ attr.name|replace:"cherche=_&remplacement= " }}
</code></pre>
<p>Then your replace function will now look like this:</p>
<pre><code>from django import template
from django.http import QueryDict
register = template.Library()
@register.filter
def replace(value, args):
qs = QueryDict(args)
if qs.has_key('cherche') and qs.has_key('remplacement'):
return value.replace(qs['cherche'], qs['remplacement'])
else:
return value
</code></pre>
<p>You could speed this up some at the risk of doing some incorrect replacements:</p>
<pre><code>qs = QueryDict(args)
return value.replace(qs.get('cherche',''), qs.get('remplacement',''))
</code></pre> |
1,055,134 | How to centrally align a float: left ul/li navigation menu with css? | <p>So I have the following CSS in place to display a horizontal navigation bar using:</p>
<pre><code>.navigation ul {
list-style: none;
padding: 0;
margin: 0;
}
.navigation li {
float: left;
margin: 0 1.15em;
/* margin: 0 auto;*/
}
.navigation {
/* width: auto;*/
/* margin: 0 auto;*/
text-align: center;
}
</code></pre>
<p>My question is: how do I align the navigation bar centrally above the title?</p> | 1,055,140 | 10 | 1 | null | 2009-06-28 15:48:48.553 UTC | 7 | 2017-10-05 07:34:28.667 UTC | 2015-05-30 12:42:38.83 UTC | null | 2,202,537 | null | 52,116 | null | 1 | 26 | html|css|css-float | 98,762 | <p>Give your .navigation ul a width and use margin:0 auto;</p>
<pre><code>.navigation ul
{
list-style: none;
padding: 0;
width: 400px;
margin: 0 auto;
}
</code></pre> |
214,359 | Converting hex color to RGB and vice-versa | <p>What is the most efficient way to do this?</p> | 214,386 | 10 | 1 | null | 2008-10-18 01:33:52.253 UTC | 23 | 2022-08-31 13:14:48.693 UTC | 2011-11-23 20:45:47.577 UTC | Jeremy Cantrell | 2,683 | orlandu63 | 23,107 | null | 1 | 51 | colors|hex|rgb | 70,608 | <p>Real answer: Depends on what kind of hexadecimal color value you are looking for (e.g. 565, 555, 888, 8888, etc), the amount of alpha bits, the actual color distribution (rgb vs bgr...) and a ton of other variables.</p>
<p>Here's a generic algorithm for most RGB values using C++ templates (straight from ScummVM).</p>
<pre><code>template<class T>
uint32 RGBToColor(uint8 r, uint8 g, uint8 b) {
return T::kAlphaMask |
(((r << T::kRedShift) >> (8 - T::kRedBits)) & T::kRedMask) |
(((g << T::kGreenShift) >> (8 - T::kGreenBits)) & T::kGreenMask) |
(((b << T::kBlueShift) >> (8 - T::kBlueBits)) & T::kBlueMask);
}
</code></pre>
<p>Here's a sample color struct for 565 (the standard format for 16 bit colors):</p>
<pre><code>template<>
struct ColorMasks<565> {
enum {
highBits = 0xF7DEF7DE,
lowBits = 0x08210821,
qhighBits = 0xE79CE79C,
qlowBits = 0x18631863,
kBytesPerPixel = 2,
kAlphaBits = 0,
kRedBits = 5,
kGreenBits = 6,
kBlueBits = 5,
kAlphaShift = kRedBits+kGreenBits+kBlueBits,
kRedShift = kGreenBits+kBlueBits,
kGreenShift = kBlueBits,
kBlueShift = 0,
kAlphaMask = ((1 << kAlphaBits) - 1) << kAlphaShift,
kRedMask = ((1 << kRedBits) - 1) << kRedShift,
kGreenMask = ((1 << kGreenBits) - 1) << kGreenShift,
kBlueMask = ((1 << kBlueBits) - 1) << kBlueShift,
kRedBlueMask = kRedMask | kBlueMask
};
};
</code></pre> |
49,912 | Best .NET memory and performance profiler? | <p>We are using <a href="http://en.wikipedia.org/wiki/JetBrains" rel="nofollow noreferrer">JetBrains</a>' <a href="http://en.wikipedia.org/wiki/DotTrace" rel="nofollow noreferrer">dotTrace</a>. What other profiling tools can be recommended that are better for profiling C# <a href="http://en.wikipedia.org/wiki/Windows_Forms" rel="nofollow noreferrer">Windows Forms</a> applications?</p> | 49,943 | 11 | 1 | null | 2008-09-08 15:14:00.28 UTC | 19 | 2017-09-05 19:13:58.67 UTC | 2017-09-05 19:13:58.67 UTC | Erik van Brakel | 63,550 | null | 4,653 | null | 1 | 56 | c#|.net|profiling|profiler | 40,659 | <p>No. I have tried pretty much every .NET profiler on the market (ANTS, vTune, OptimizeIt, DevPartner, YourKit), and in my opinion dotTrace is the best of the lot. It is one of only two profilers I have used (the other being YourKit) that has low enough overhead to handle a highly CPU-intensive application.</p>
<p>If and only if your application is relatively light, I could recommend <a href="http://www.red-gate.com/products/ants_profiler/index.htm" rel="noreferrer">ANTS Profiler</a>. Its line-by-line stats are sometimes quite useful, but they come at a price in profiling efficiency.</p> |
949,433 | Why are these constructs using pre and post-increment undefined behavior? | <pre><code>#include <stdio.h>
int main(void)
{
int i = 0;
i = i++ + ++i;
printf("%d\n", i); // 3
i = 1;
i = (i++);
printf("%d\n", i); // 2 Should be 1, no ?
volatile int u = 0;
u = u++ + ++u;
printf("%d\n", u); // 1
u = 1;
u = (u++);
printf("%d\n", u); // 2 Should also be one, no ?
register int v = 0;
v = v++ + ++v;
printf("%d\n", v); // 3 (Should be the same as u ?)
int w = 0;
printf("%d %d\n", ++w, w); // shouldn't this print 1 1
int x[2] = { 5, 8 }, y = 0;
x[y] = y ++;
printf("%d %d\n", x[0], x[1]); // shouldn't this print 0 8? or 5 0?
}
</code></pre> | 949,443 | 14 | 18 | null | 2009-06-04 09:17:52.267 UTC | 333 | 2022-01-29 13:19:57.95 UTC | 2019-08-17 07:31:59.623 UTC | null | 918,959 | null | 44,988 | null | 1 | 888 | c|increment|undefined-behavior|operator-precedence|sequence-points | 93,558 | <p>C has the concept of undefined behavior, i.e. some language constructs are syntactically valid but you can't predict the behavior when the code is run.</p>
<p>As far as I know, the standard doesn't explicitly say <em>why</em> the concept of undefined behavior exists. In my mind, it's simply because the language designers wanted there to be some leeway in the semantics, instead of i.e. requiring that all implementations handle integer overflow in the exact same way, which would very likely impose serious performance costs, they just left the behavior undefined so that if you write code that causes integer overflow, anything can happen.</p>
<p>So, with that in mind, why are these "issues"? The language clearly says that certain things lead to <a href="http://en.wikipedia.org/wiki/Undefined_behavior" rel="noreferrer">undefined behavior</a>. There is no problem, there is no "should" involved. If the undefined behavior changes when one of the involved variables is declared <code>volatile</code>, that doesn't prove or change anything. It is <em>undefined</em>; you cannot reason about the behavior.</p>
<p>Your most interesting-looking example, the one with</p>
<pre><code>u = (u++);
</code></pre>
<p>is a text-book example of undefined behavior (see Wikipedia's entry on <a href="http://en.wikipedia.org/wiki/Sequence_point" rel="noreferrer">sequence points</a>).</p> |
1,223,710 | We have to use C "for performance reasons" | <p>In this age of many languages, there seems to be a great language for just about every task and I find myself professionally struggling against a mantra of "<em>nothing but C is fast</em>", where fast is really intended to mean "fast enough". I work with very rational open-minded people, who like to compare numbers, and all I have are thoughts and opinions. Could you help me find my way past subjective opinions and into the "real world"?</p>
<p>Would you help me find research as to what if any other languages could be used for embedded and (Linux) systems programming? I very well could be pushing a false hypothesis and would greatly appreciate research to show me this. Could you please link or include good numbers so as to help keep the "that's just his/her opinion" comments to a minimum.</p>
<hr>
<p>So these are my particular requirements</p>
<ul>
<li>memory is not a serious constraint</li>
<li>portability is not a serious concern</li>
<li>this is not a real time system</li>
</ul> | 1,224,901 | 19 | 11 | 2009-08-04 21:42:49.533 UTC | 2009-08-03 17:57:54.053 UTC | 15 | 2018-07-13 15:25:50.097 UTC | 2017-08-29 19:34:37.55 UTC | null | 3,924,118 | null | 90,801 | null | 1 | 23 | c|linux|embedded|systems-programming | 9,449 | <p>"Nothing but C is fast [enough]" is an early optimisation and wrong for all the reasons that early optimisations are wrong. If your system has enough complexity that something other than C is desirable, then there will be parts of the system that must be "fast enough" and parts with lighter constraints. If writing your code, for example, in Python will get the project finished faster, with fewer bugs, then you can follow up with some C or assembly code to speed up the time-critical parts.</p>
<p>Even if it turns out that the entire code must be written in C or assembly to meet the performance requirements, prototyping in a language like Python can have real benefits. You can take your working Python prototype and gradually replace parts with C code until you reach the necessary performance.</p>
<p>So, use the tools that let you get the development work done most correctly and most quickly, then use real data to determine where you need to optimize. It could be that C is the most appropriate tool to start with sometimes, but certainly not always, even in embedded systems.</p> |
521,171 | A Java collection of value pairs? (tuples?) | <p>I like how Java has a Map where you can define the types of each entry in the map, for example <code><String, Integer></code>. </p>
<p>What I'm looking for is a type of collection where each element in the collection is a pair of values. Each value in the pair can have its own type (like the String and Integer example above), which is defined at declaration time. </p>
<p>The collection will maintain its given order and will not treat one of the values as a unique key (as in a map). </p>
<p>Essentially I want to be able to define an ARRAY of type <code><String,Integer></code> or any other 2 types. </p>
<p>I realize that I can make a class with nothing but the 2 variables in it, but that seems overly verbose. </p>
<p>I also realize that I could use a 2D array, but because of the different types I need to use, I'd have to make them arrays of OBJECT, and then I'd have to cast all the time. </p>
<p>I only need to store pairs in the collection, so I only need two values per entry. Does something like this exist without going the class route? Thanks!</p> | 521,235 | 21 | 3 | null | 2009-02-06 17:07:53.98 UTC | 114 | 2022-06-03 15:02:59.143 UTC | 2009-02-06 17:18:23.99 UTC | toolkit | 3,295 | null | 60,006 | null | 1 | 412 | java | 587,507 | <p>The Pair class is one of those "gimme" generics examples that is easy enough to write on your own. For example, off the top of my head:</p>
<pre><code>public class Pair<L,R> {
private final L left;
private final R right;
public Pair(L left, R right) {
assert left != null;
assert right != null;
this.left = left;
this.right = right;
}
public L getLeft() { return left; }
public R getRight() { return right; }
@Override
public int hashCode() { return left.hashCode() ^ right.hashCode(); }
@Override
public boolean equals(Object o) {
if (!(o instanceof Pair)) return false;
Pair pairo = (Pair) o;
return this.left.equals(pairo.getLeft()) &&
this.right.equals(pairo.getRight());
}
}
</code></pre>
<p>And yes, this exists in multiple places on the Net, with varying degrees of completeness and feature. (My example above is intended to be immutable.)</p> |
635,483 | What is the best way to implement nested dictionaries? | <p>I have a data structure which essentially amounts to a nested dictionary. Let's say it looks like this:</p>
<pre><code>{'new jersey': {'mercer county': {'plumbers': 3,
'programmers': 81},
'middlesex county': {'programmers': 81,
'salesmen': 62}},
'new york': {'queens county': {'plumbers': 9,
'salesmen': 36}}}
</code></pre>
<p>Now, maintaining and creating this is pretty painful; every time I have a new state/county/profession I have to create the lower layer dictionaries via obnoxious try/catch blocks. Moreover, I have to create annoying nested iterators if I want to go over all the values. </p>
<p>I could also use tuples as keys, like such:</p>
<pre><code>{('new jersey', 'mercer county', 'plumbers'): 3,
('new jersey', 'mercer county', 'programmers'): 81,
('new jersey', 'middlesex county', 'programmers'): 81,
('new jersey', 'middlesex county', 'salesmen'): 62,
('new york', 'queens county', 'plumbers'): 9,
('new york', 'queens county', 'salesmen'): 36}
</code></pre>
<p>This makes iterating over the values very simple and natural, but it is more syntactically painful to do things like aggregations and looking at subsets of the dictionary (e.g. if I just want to go state-by-state).</p>
<p>Basically, sometimes I want to think of a nested dictionary as a flat dictionary, and sometimes I want to think of it indeed as a complex hierarchy. I could wrap this all in a class, but it seems like someone might have done this already. Alternatively, it seems like there might be some really elegant syntactical constructions to do this. </p>
<p>How could I do this better?</p>
<p>Addendum: I'm aware of <code>setdefault()</code> but it doesn't really make for clean syntax. Also, each sub-dictionary you create still needs to have <code>setdefault()</code> manually set.</p> | 19,829,714 | 21 | 0 | null | 2009-03-11 17:09:21.56 UTC | 168 | 2020-09-16 00:06:39.067 UTC | 2016-12-01 01:32:12.763 UTC | Rich B | 355,230 | YGA | 54,873 | null | 1 | 224 | python|data-structures|dictionary|mapping|autovivification | 117,839 | <blockquote>
<h2>What is the best way to implement nested dictionaries in Python?</h2>
</blockquote>
<p>This is a bad idea, don't do it. Instead, use a regular dictionary and use <code>dict.setdefault</code> where apropos, so when keys are missing under normal usage you get the expected <code>KeyError</code>. If you insist on getting this behavior, here's how to shoot yourself in the foot:</p>
<p>Implement <code>__missing__</code> on a <code>dict</code> subclass to set and return a new instance.</p>
<p>This approach has been available <a href="http://docs.python.org/2/library/stdtypes.html#dict" rel="noreferrer">(and documented)</a> since Python 2.5, and (particularly valuable to me) <strong>it pretty prints just like a normal dict</strong>, instead of the ugly printing of an autovivified defaultdict:</p>
<pre><code>class Vividict(dict):
def __missing__(self, key):
value = self[key] = type(self)() # retain local pointer to value
return value # faster to return than dict lookup
</code></pre>
<p>(Note <code>self[key]</code> is on the left-hand side of assignment, so there's no recursion here.)</p>
<p>and say you have some data:</p>
<pre><code>data = {('new jersey', 'mercer county', 'plumbers'): 3,
('new jersey', 'mercer county', 'programmers'): 81,
('new jersey', 'middlesex county', 'programmers'): 81,
('new jersey', 'middlesex county', 'salesmen'): 62,
('new york', 'queens county', 'plumbers'): 9,
('new york', 'queens county', 'salesmen'): 36}
</code></pre>
<p>Here's our usage code:</p>
<pre><code>vividict = Vividict()
for (state, county, occupation), number in data.items():
vividict[state][county][occupation] = number
</code></pre>
<p>And now:</p>
<pre><code>>>> import pprint
>>> pprint.pprint(vividict, width=40)
{'new jersey': {'mercer county': {'plumbers': 3,
'programmers': 81},
'middlesex county': {'programmers': 81,
'salesmen': 62}},
'new york': {'queens county': {'plumbers': 9,
'salesmen': 36}}}
</code></pre>
<h2>Criticism</h2>
<p>A criticism of this type of container is that if the user misspells a key, our code could fail silently:</p>
<pre><code>>>> vividict['new york']['queens counyt']
{}
</code></pre>
<p>And additionally now we'd have a misspelled county in our data:</p>
<pre><code>>>> pprint.pprint(vividict, width=40)
{'new jersey': {'mercer county': {'plumbers': 3,
'programmers': 81},
'middlesex county': {'programmers': 81,
'salesmen': 62}},
'new york': {'queens county': {'plumbers': 9,
'salesmen': 36},
'queens counyt': {}}}
</code></pre>
<h1>Explanation:</h1>
<p>We're just providing another nested instance of our class <code>Vividict</code> whenever a key is accessed but missing. (Returning the value assignment is useful because it avoids us additionally calling the getter on the dict, and unfortunately, we can't return it as it is being set.)</p>
<p>Note, these are the same semantics as the most upvoted answer but in half the lines of code - nosklo's implementation:</p>
<blockquote>
<pre><code>class AutoVivification(dict):
"""Implementation of perl's autovivification feature."""
def __getitem__(self, item):
try:
return dict.__getitem__(self, item)
except KeyError:
value = self[item] = type(self)()
return value
</code></pre>
</blockquote>
<h2>Demonstration of Usage</h2>
<p>Below is just an example of how this dict could be easily used to create a nested dict structure on the fly. This can quickly create a hierarchical tree structure as deeply as you might want to go.</p>
<pre><code>import pprint
class Vividict(dict):
def __missing__(self, key):
value = self[key] = type(self)()
return value
d = Vividict()
d['foo']['bar']
d['foo']['baz']
d['fizz']['buzz']
d['primary']['secondary']['tertiary']['quaternary']
pprint.pprint(d)
</code></pre>
<p>Which outputs:</p>
<pre><code>{'fizz': {'buzz': {}},
'foo': {'bar': {}, 'baz': {}},
'primary': {'secondary': {'tertiary': {'quaternary': {}}}}}
</code></pre>
<p>And as the last line shows, it pretty prints beautifully and in order for manual inspection. But if you want to visually inspect your data, implementing <code>__missing__</code> to set a new instance of its class to the key and return it is a far better solution.</p>
<h1>Other alternatives, for contrast:</h1>
<h2><code>dict.setdefault</code></h2>
<p>Although the asker thinks this isn't clean, I find it preferable to the <code>Vividict</code> myself.</p>
<pre><code>d = {} # or dict()
for (state, county, occupation), number in data.items():
d.setdefault(state, {}).setdefault(county, {})[occupation] = number
</code></pre>
<p>and now:</p>
<pre><code>>>> pprint.pprint(d, width=40)
{'new jersey': {'mercer county': {'plumbers': 3,
'programmers': 81},
'middlesex county': {'programmers': 81,
'salesmen': 62}},
'new york': {'queens county': {'plumbers': 9,
'salesmen': 36}}}
</code></pre>
<p>A misspelling would fail noisily, and not clutter our data with bad information:</p>
<pre><code>>>> d['new york']['queens counyt']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'queens counyt'
</code></pre>
<p>Additionally, I think setdefault works great when used in loops and you don't know what you're going to get for keys, but repetitive usage becomes quite burdensome, and I don't think anyone would want to keep up the following:</p>
<pre><code>d = dict()
d.setdefault('foo', {}).setdefault('bar', {})
d.setdefault('foo', {}).setdefault('baz', {})
d.setdefault('fizz', {}).setdefault('buzz', {})
d.setdefault('primary', {}).setdefault('secondary', {}).setdefault('tertiary', {}).setdefault('quaternary', {})
</code></pre>
<p>Another criticism is that setdefault requires a new instance whether it is used or not. However, Python (or at least CPython) is rather smart about handling unused and unreferenced new instances, for example, it reuses the location in memory:</p>
<pre><code>>>> id({}), id({}), id({})
(523575344, 523575344, 523575344)
</code></pre>
<h2>An auto-vivified defaultdict</h2>
<p>This is a neat looking implementation, and usage in a script that you're not inspecting the data on would be as useful as implementing <code>__missing__</code>:</p>
<pre><code>from collections import defaultdict
def vivdict():
return defaultdict(vivdict)
</code></pre>
<p>But if you need to inspect your data, the results of an auto-vivified defaultdict populated with data in the same way looks like this:</p>
<pre><code>>>> d = vivdict(); d['foo']['bar']; d['foo']['baz']; d['fizz']['buzz']; d['primary']['secondary']['tertiary']['quaternary']; import pprint;
>>> pprint.pprint(d)
defaultdict(<function vivdict at 0x17B01870>, {'foo': defaultdict(<function vivdict
at 0x17B01870>, {'baz': defaultdict(<function vivdict at 0x17B01870>, {}), 'bar':
defaultdict(<function vivdict at 0x17B01870>, {})}), 'primary': defaultdict(<function
vivdict at 0x17B01870>, {'secondary': defaultdict(<function vivdict at 0x17B01870>,
{'tertiary': defaultdict(<function vivdict at 0x17B01870>, {'quaternary': defaultdict(
<function vivdict at 0x17B01870>, {})})})}), 'fizz': defaultdict(<function vivdict at
0x17B01870>, {'buzz': defaultdict(<function vivdict at 0x17B01870>, {})})})
</code></pre>
<p>This output is quite inelegant, and the results are quite unreadable. The solution typically given is to recursively convert back to a dict for manual inspection. This non-trivial solution is left as an exercise for the reader.</p>
<h1>Performance</h1>
<p>Finally, let's look at performance. I'm subtracting the costs of instantiation.</p>
<pre><code>>>> import timeit
>>> min(timeit.repeat(lambda: {}.setdefault('foo', {}))) - min(timeit.repeat(lambda: {}))
0.13612580299377441
>>> min(timeit.repeat(lambda: vivdict()['foo'])) - min(timeit.repeat(lambda: vivdict()))
0.2936999797821045
>>> min(timeit.repeat(lambda: Vividict()['foo'])) - min(timeit.repeat(lambda: Vividict()))
0.5354437828063965
>>> min(timeit.repeat(lambda: AutoVivification()['foo'])) - min(timeit.repeat(lambda: AutoVivification()))
2.138362169265747
</code></pre>
<p>Based on performance, <code>dict.setdefault</code> works the best. I'd highly recommend it for production code, in cases where you care about execution speed.</p>
<p>If you need this for interactive use (in an IPython notebook, perhaps) then performance doesn't really matter - in which case, I'd go with Vividict for readability of the output. Compared to the AutoVivification object (which uses <code>__getitem__</code> instead of <code>__missing__</code>, which was made for this purpose) it is far superior.</p>
<h1>Conclusion</h1>
<p>Implementing <code>__missing__</code> on a subclassed <code>dict</code> to set and return a new instance is slightly more difficult than alternatives but has the benefits of</p>
<ul>
<li>easy instantiation</li>
<li>easy data population</li>
<li>easy data viewing</li>
</ul>
<p>and because it is less complicated and more performant than modifying <code>__getitem__</code>, it should be preferred to that method.</p>
<p>Nevertheless, it has drawbacks:</p>
<ul>
<li>Bad lookups will fail silently.</li>
<li>The bad lookup will remain in the dictionary.</li>
</ul>
<p>Thus I personally prefer <code>setdefault</code> to the other solutions, and have in every situation where I have needed this sort of behavior.</p> |
6,778,360 | What's the difference between Shared Worker and Worker in HTML5? | <p>After reading this blog post: <a href="http://www.sitepoint.com/javascript-shared-web-workers-html5/" rel="noreferrer">http://www.sitepoint.com/javascript-shared-web-workers-html5/</a></p>
<p>I don't get it. What's the difference between a <code>Worker</code> and a <code>SharedWorker</code>?</p> | 6,778,480 | 5 | 1 | null | 2011-07-21 15:12:17.123 UTC | 15 | 2020-06-20 14:48:14 UTC | 2011-07-21 15:19:54.897 UTC | null | 213,269 | null | 283,055 | null | 1 | 62 | javascript|html|web-worker | 21,928 | <p>Very basic distinction: a <code>Worker</code> can only be accessed from the script that created it, a <code>SharedWorker</code> can be accessed by any script that comes from the same domain.</p> |
6,419,393 | Is this design of Spring singleton beans thread safe? | <p>Consider the following Spring Service class. The spring scope defined is Singleton. The two service beans auto-wired as fields in the class below have similar structure - they too are composed of fields which are either of the following </p>
<ul>
<li>Spring beans themselves</li>
<li>stateless classes</li>
<li>immutable classes</li>
</ul>
<p>and so on. This pattern is overall used in the application design.</p>
<pre><code>@Service
public class DocumentService {
private final DocumentGenerationService documentGenerationService;
private final DocumentPublishService documentPublishService;
@Autowired
public DocumentService (DocumentGenerationService documentGenerationService,
DocumentPublishService documentPublishService) {
this.documentGenerationService = documentGenerationService;
this.documentPublishService = documentPublishService;
}
... methods follow
</code></pre>
<p>Is it correct to say that the DocumentService class is immutable since it's not possible to mutate any of its two fields (which are spring beans that can be initialized only once by the container itself)?</p>
<p>In any case, can the DocumentService bean as defined above be considered thread-safe? And if this design is followed the application as a whole is thread-safe too?</p> | 6,514,044 | 6 | 0 | null | 2011-06-21 01:24:34.75 UTC | 9 | 2014-03-19 16:51:09.077 UTC | 2011-06-21 01:29:04.923 UTC | null | 37,213 | null | 487,244 | null | 1 | 24 | java|multithreading|spring|concurrency|singleton | 15,844 | <blockquote>
<p><em>Is it correct to say that the DocumentService class is immutable since it's not possible to mutate any of its two fields (which are spring beans that can be initialized only once by the container itself)?</em></p>
</blockquote>
<p>According to the <a href="http://en.wikipedia.org/wiki/Immutable_object" rel="noreferrer">definition of immutability</a>, and formally speaking, this class is <strong>NOT immutable</strong>.</p>
<p>An object is immutable if it is not possible to change the state of the object, and the state of <code>documentGenerationService</code> and <code>documentPublishService</code> <strong>is part of the state of the class</strong> <code>DocumentService</code>.</p>
<p>And, as a result, <em>if the class has <strong>always</strong> the same state, it behaves <strong>always</strong> the same way</em>. In other words, there is no way to change the behaviour of an immutable object because the behaviour of an object depends only in its state, and in an immutable object, this state never changes (examples of immutable objects are Strings and Integers).</p>
<p>Note that in the definition of immutability we find an exception where "<em>an object is considered immutable even if some [...] attributes change but the object's state</em> [and, therefore, behaviour] <em>appears to be unchanging [...]</em>", but in this case (with the information provided) a change in the state of the references could definitely change the behaviour of the class (since we don't have any control on their own internal state).</p>
<p>There is a <strong><a href="http://download.oracle.com/javase/tutorial/essential/concurrency/imstrat.html" rel="noreferrer">strategy</a></strong> to make a class immutable. You already follow some of its guidelines, but in case you wished to do it immutable (I think it is not the case) you would need some others like make <strong>"defensive copy"</strong> of the arguments that you receive in the constructor and <strong>avoid subclasses overriding methods</strong>.</p>
<p>This <a href="http://www.javapractices.com/topic/TopicAction.do?Id=29" rel="noreferrer">link</a> is also interesting.</p>
<p>Nevertheless, <em>you should not</em> make Spring beans immutable, since it is not the way to use the programming model that Spring offers. So, in this case, it is "good" that the class is not immutable.</p>
<blockquote>
<p><em>In any case, can the DocumentService bean as defined above be considered thread-safe?</em></p>
</blockquote>
<p>As declared here, this class <strong>IS thread safe</strong>. Many threads can safely access this class without any race condition arising. We cannot say the same about the fields it contains, but this class is thread-safe. This works just the same way as "thread-safe list": it can contain "no thread-safe" objects, but still be a "thread-safe list".</p>
<blockquote>
<p><em>And if this design is followed the application as a whole is thread-safe too?</em></p>
</blockquote>
<p>If all the classes of your system are thread-safe (i.e. not a single race condition appears anywhere) you could <em>informally</em> say that the application is thread safe.</p> |
6,728,329 | ' ', hexadecimal value 0x1F, is an invalid character. Line 1, position 1 | <p>I am trying to read a xml file from the web and parse it out using XDocument. It normally works fine but sometimes it gives me this error for day:</p>
<pre><code> **' ', hexadecimal value 0x1F, is an invalid character. Line 1, position 1**
</code></pre>
<p>I have tried some solutions from Google but they aren't working for VS 2010 Express Windows Phone 7.</p>
<p>There is a solution which replace the 0x1F character to string.empty but my code return a stream which doesn't have replace method.</p>
<pre><code>s = s.Replace(Convert.ToString((byte)0x1F), string.Empty);
</code></pre>
<p>Here is my code:</p>
<pre><code> void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
using (var reader = new StreamReader(e.Result))
{
int[] counter = { 1 };
string s = reader.ReadToEnd();
Stream str = e.Result;
// s = s.Replace(Convert.ToString((byte)0x1F), string.Empty);
// byte[] str = Convert.FromBase64String(s);
// Stream memStream = new MemoryStream(str);
str.Position = 0;
XDocument xdoc = XDocument.Load(str);
var data = from query in xdoc.Descendants("user")
select new mobion
{
index = counter[0]++,
avlink = (string)query.Element("user_info").Element("avlink"),
nickname = (string)query.Element("user_info").Element("nickname"),
track = (string)query.Element("track"),
artist = (string)query.Element("artist"),
};
listBox.ItemsSource = data;
}
}
</code></pre>
<p>XML file:
<a href="http://music.mobion.vn/api/v1/music/userstop?devid=" rel="noreferrer">http://music.mobion.vn/api/v1/music/userstop?devid=</a></p> | 6,732,007 | 9 | 3 | null | 2011-07-18 03:16:44.203 UTC | 1 | 2018-12-12 14:49:17.16 UTC | 2015-09-01 17:21:12.67 UTC | null | 1,832,942 | null | 1,994,957 | null | 1 | 19 | encoding|linq-to-xml|windows-phone | 64,098 | <p>Consider using <a href="http://msdn.microsoft.com/en-us/library/7c5fyk1k.aspx" rel="nofollow">System.Web.HttpUtility.HtmlDecode</a> if you're decoding content read from the web.</p> |
7,011,071 | Detect 32-bit or 64-bit of Windows | <p>I want to detect whether the current Windows OS is 32-bit or 64-bit. How to achieve it using C++? I don't want processor type I want OS's bit type. This is because you can install 32-bit OS on 64-bit processor.</p> | 7,011,144 | 14 | 3 | null | 2011-08-10 12:53:29.897 UTC | 4 | 2021-12-05 18:24:53.087 UTC | 2014-07-11 09:30:09.36 UTC | null | 472,434 | null | 324,041 | null | 1 | 50 | c++|windows|32bit-64bit | 57,212 | <p>The function to call is <a href="http://msdn.microsoft.com/en-us/library/ms684139(v=vs.85).aspx" rel="nofollow noreferrer"><code>IsWow64Process</code></a> or <a href="https://docs.microsoft.com/en-gb/windows/desktop/api/wow64apiset/nf-wow64apiset-iswow64process2" rel="nofollow noreferrer"><code>IsWow64Process2</code></a>. It tells your 32-bit application if it is running on a 64 bit Windows.</p>
<p>If the program is compiled for 64 bits, it will already know.</p> |
6,480,462 | How to pre-populate the sms body text via an html link | <p>How to use an html link to open the sms app with a pre-filled body?</p>
<p>Everything I have read seems to indicate that sms:18005555555?body=bodyTextHere</p>
<p>Should work, but on the iPhone, this doesn't work. If I take out the ?body=bodyTextHere, and just use sms:phonenumber, it works.</p>
<p>I have seen several instances where QR codes do this through a safari link. How are they able to pre-populate the body text?</p> | 19,126,326 | 23 | 4 | null | 2011-06-25 20:55:24.093 UTC | 73 | 2022-05-24 19:01:19.323 UTC | 2017-08-11 13:12:37.497 UTC | null | 1,000,551 | null | 97,789 | null | 1 | 138 | html|ios|hyperlink|sms | 221,980 | <p>It turns out this is 100% possible, though a little hacky. </p>
<p>If you want it to work on Android you need to use this format:</p>
<p><code><a href="sms:/* phone number here */?body=/* body text here */">Link</a></code></p>
<p>If you want it to work on iOS, you need this:</p>
<p><code><a href="sms:/* phone number here */;body=/* body text here */">Link</a></code></p>
<p>Live demo here: <a href="http://bradorego.com/test/sms.html">http://bradorego.com/test/sms.html</a> (note the "Phone and ?body" and "Phone and ;body" should autofill both the to: field and the body text. View the source for more info)</p>
<p><strong>UPDATE:</strong></p>
<p>Apparently iOS8 had to go and change things on us, so thanks to some of the other commenters/responders, there's a new style for iOS:</p>
<p><code><a href="sms:/* phone number here */&body=/* body text here */">Link</a></code></p>
<p>(phone number is optional)</p> |
42,508,323 | JUnit for both try and catch block coverage | <p>I am trying to write a JUnit for below code but I am not getting any idea how to cover the code which is written in catch block statement. Please can any one write a sample JUnit for below code.</p>
<p>Here I don't want to cover any exception, but want to cover the lines of code written in the catch block using Mockito. </p>
<pre><code>public Product getProductLookUpData() {
Product product = null;
try{
// Try to get value from cacheable method
product = productCacheDao.getProductLookUpData();
.....//statements
} catch (Exception ex) {
// getting value from db
product = productDao.getIpacMetricCodeLookUpData();
....//statements
}
return product;
}
</code></pre> | 42,508,376 | 3 | 6 | null | 2017-02-28 12:04:42.363 UTC | 5 | 2018-05-16 10:06:54.233 UTC | 2018-05-16 10:06:54.233 UTC | null | 5,109,709 | null | 6,747,865 | null | 1 | 6 | java|junit | 68,347 | <p>You can <a href="http://site.mockito.org/" rel="noreferrer">mock</a> both <code>productCacheDao</code> and <code>productDao</code> and check how many times those methods were invoked in your test cases. And you can simulate exception throwing with those mock objects, like this:</p>
<pre><code>when(mockObject.method(any())).thenThrow(new IllegalStateException());
</code></pre>
<p>So, for your case I would do something like this:</p>
<pre><code>import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import static org.mockito.Mockito.*;
public class ProductTest {
private static final Product CACHED_PRODUCT = new Product("some parameters for cached product");
private static final Product DB_PRODUCT = new Product("some parameters for DB product");
private ProductService service;
private ProductDao productDaoMock;
private ProductCacheDao productCacheDaoMock;
@Before
public void setup() {
service = new ProductService();
productDaoMock = mock(ProdoctDao.class);
service.setProductDao(productDaoMock);
productCacheDaoMock = mock(ProdoctCacheDao.class);
service.setProductCacheDao(productCacheDaoMock);
}
@Test
public void testCache() {
when(productCacheDaoMock.getProductLookUpData(any())).thenReturn(CACHED_PRODUCT);
final Product product = service.getProductLookUpData();
Assert.assertEquals(CACHED_PRODUCT, product);
verify(productCacheDaoMock, times(1)).getProductLookUpData(any());
verify(productDaoMock, never()).getIpacMetricCodeLookUpData(any());
}
@Test
public void testDB() {
when(productCacheDaoMock.getProductLookUpData(any())).thenThrow(new IllegalStateException());
when(productDaoMock.getIpacMetricCodeLookUpData(any())).thenReturn(DB_PRODUCT);
final Product product = service.getProductLookUpData();
Assert.assertEquals(DB_PRODUCT, product);
verify(productCacheDaoMock, times(1)).getProductLookUpData(any());
verify(productDaoMock, times(1)).getIpacMetricCodeLookUpData(any());
}
}
</code></pre> |
41,515,134 | Discord Bot Can't Get Channel by Name | <p>I have been making a discord bot and wanted to make it send a message to a specific "Welcome" channel. Unfortunately, I have been unable to do so. I tried this.</p>
<pre><code>const welcomeChannel = bot.channels.get("name", "welcome")
welcomeChannel.sendMessage("Welcome\n"+member.user.username);
</code></pre>
<p>However in this "welcomeChannel is undefined".</p>
<p>Edit:</p>
<p>I tried using </p>
<pre><code>const welcomeChannel = bot.channels.get("id", "18NUMBERIDHERE")
welcomeChannel.sendMessage("Welcome\n"+member.user.username);
</code></pre>
<p>but this is still undefined, strangely</p> | 41,515,544 | 4 | 1 | null | 2017-01-06 22:08:14.87 UTC | 2 | 2022-02-21 15:58:03.43 UTC | 2020-09-05 18:52:05.477 UTC | null | 1,970,470 | null | 6,274,988 | null | 1 | 17 | javascript|discord|discord.js|bots | 96,221 | <p>You should use the channnel id instead of it's name.</p>
<p>How to get the channel id of a channel:</p>
<ol>
<li><p>Open up your Discord Settings</p>
</li>
<li><p>Go to <code>Advanced</code></p>
</li>
<li><p>Tick <code>Developer Mode</code> (And close the Discord settings)</p>
</li>
<li><p>Right click on your desired channel</p>
</li>
<li><p>Now there's an option <code>Copy ID</code> to copy the channel id</p>
</li>
</ol>
<p>Also checkout the <a href="https://discord.js.org/#/docs/main/stable/class/Guild?scrollTo=setChannelPositions" rel="nofollow noreferrer">discord.js documentation</a> for (channel) collections</p>
<hr />
<p>Furthermore your approach won't work because <code>.get</code> wants a channel id (see the linked documentation above). In case you <strong>REALLY</strong> want to get an channel by its name, use <code>.find</code> instead for that.<br />
This is however a really bad idea in case your bot runs on more than one server since channel names can now occur multiple times.</p> |
15,641,346 | Defining aliases in Cygwin under Windows | <p>I am trying to define some aliases in cygwin, but with no success. I am doing so like this at the end of the <code>.bashrc</code> file.</p>
<pre><code>alias foo='pwd'
</code></pre>
<p>I have tried to add this line in a <code>.bashrc</code> file in both inside the <code>home</code> folder of cygwin and in the home folder for the Windows user I am on <code>C:\Users\Nuno\</code>. In both cases I have just appended this line to a copy of the <code>/etc/skel/.bashrc</code> file. In either cases, it didn't work.</p>
<p>I had this working before. I had to reinstall Cygwin and ever since it never worked properly again. I have removed all files (or at least think so, when doing the reinstallation). I have also noticed that in the first install (when it was working) cygwin already was creating .bash files in the <code>home</code> folder. Now, it doesn't.</p>
<p>I am on a machine running Windows 7.</p>
<p><strong>EDIT</strong>: My cygwin home folder is set to the Windows home folder <code>C:\Users\Nuno\</code>. I have placed what I think is a valid <code>.bashrc</code> file there, but it still doesn't work. </p>
<p>Thanks in advance.</p> | 15,648,240 | 8 | 7 | null | 2013-03-26 15:45:39.397 UTC | 1 | 2020-12-17 10:14:29.123 UTC | 2013-03-26 15:56:15.753 UTC | null | 161,746 | null | 161,746 | null | 1 | 16 | cygwin | 38,657 | <p>As me_and already explained what's going on I just want to add a workaround should you for whatever reason not be able or willing to remove Windows' HOME environment variable.</p>
<p>Normally the shortcut for Cygwin executes</p>
<pre><code>C:\cygwin\bin\mintty.exe -i /Cygwin-Terminal.ico -
</code></pre>
<p>Instead you can create a batchfile with the following content and start that:</p>
<pre><code>@echo off
set HOME=
start C:\cygwin\bin\mintty.exe -i /Cygwin-Terminal.ico -
</code></pre>
<p>That will start a a Cygwin windows whose home directory settings are not overridden by a Windows environment variable.</p> |
15,558,202 | how to resize Image in java? | <p>Hello I have a QR code Image , and I want to resize it , when I try to resize it to a small image using this code , I always get a blury image , and the QR code is no longer valid when I scan it , but it works fine when I resize to a big sized images with the same code :</p>
<pre><code>public BufferedImage getScaledInstance(BufferedImage img,
int targetWidth,
int targetHeight,
Object hint,
boolean higherQuality)
{
int type = (img.getTransparency() == Transparency.OPAQUE) ?
BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB;
BufferedImage ret = (BufferedImage)img;
int w, h;
if (higherQuality) {
// Use multi-step technique: start with original size, then
// scale down in multiple passes with drawImage()
// until the target size is reached
w = img.getWidth();
h = img.getHeight();
} else {
// Use one-step technique: scale directly from original
// size to target size with a single drawImage() call
w = targetWidth;
h = targetHeight;
}
do {
if (higherQuality && w > targetWidth) {
w /= 2;
if (w < targetWidth) {
w = targetWidth;
}
}
if (higherQuality && h > targetHeight) {
h /= 2;
if (h < targetHeight) {
h = targetHeight;
}
}
BufferedImage tmp = new BufferedImage(w, h, type);
Graphics2D g2 = tmp.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, hint);
// g2.setRenderingHint(RenderingHints.KEY_DITHERING, hint);
g2.drawImage(ret, 0, 0, w, h, null);
g2.dispose();
ret = tmp;
} while (w != targetWidth || h != targetHeight);
return ret;
}
</code></pre>
<p>what is the problem , I don't exactly understand , please give me at least a hint , thank you </p> | 15,558,330 | 7 | 2 | null | 2013-03-21 21:11:19.327 UTC | 7 | 2016-11-17 21:35:32.58 UTC | null | null | null | null | 948,647 | null | 1 | 18 | java|image|qr-code | 101,366 | <p>I use affine transformation to achieve this task, here is my code, hope it helps</p>
<pre><code>/**
* scale image
*
* @param sbi image to scale
* @param imageType type of image
* @param dWidth width of destination image
* @param dHeight height of destination image
* @param fWidth x-factor for transformation / scaling
* @param fHeight y-factor for transformation / scaling
* @return scaled image
*/
public static BufferedImage scale(BufferedImage sbi, int imageType, int dWidth, int dHeight, double fWidth, double fHeight) {
BufferedImage dbi = null;
if(sbi != null) {
dbi = new BufferedImage(dWidth, dHeight, imageType);
Graphics2D g = dbi.createGraphics();
AffineTransform at = AffineTransform.getScaleInstance(fWidth, fHeight);
g.drawRenderedImage(sbi, at);
}
return dbi;
}
</code></pre> |
15,547,383 | Comparing Two objects using Assert.AreEqual() | <p>I 'm writing test cases for the first time in visual studio c# i have a method that returns a list of objects and i want to compare it with another list of objects by using the <code>Assert.AreEqual()</code> method.</p>
<p>I tried doing this but the assertion fails even if the two objects are identical.</p>
<p>I wanted to know if this method, the two parameters are comparing references or the content of the object,</p>
<p>Do I have to overload the <code>==</code> operator to make this work?</p> | 15,547,824 | 5 | 1 | null | 2013-03-21 12:21:21.193 UTC | 4 | 2018-05-16 09:41:43.28 UTC | 2013-05-08 12:54:50.93 UTC | null | 367,456 | null | 2,010,194 | null | 1 | 34 | c#|unit-testing|object|compare|xunit | 80,409 | <p>If you are using <code>NUnit</code> this is what the documentation says</p>
<blockquote>
<p>Starting with version 2.2, special provision is also made for
comparing single-dimensioned arrays. Two arrays will be treated as
equal by Assert.AreEqual if they are the same length and each of the
corresponding elements is equal. Note: Multi-dimensioned arrays,
nested arrays (arrays of arrays) and other collection types such as
ArrayList are not currently supported.</p>
</blockquote>
<p>In general if you are comparing two objects and you want to have value based equality you must override the <code>Equals</code> method.</p>
<p>To achieve what you are looking for try something like this:</p>
<pre><code>class Person
{
public string Firstname {get; set;}
public string Lastname {get; set;}
public override bool Equals(object other)
{
var toCompareWith = other as Person;
if (toCompareWith == null)
return false;
return this.Firstname == toCompareWith.Firstname &&
this.Lastname == toCompareWith.Lastname;
}
}
</code></pre>
<p>and in your unit test:</p>
<pre><code>Assert.AreEqual(expectedList.ToArray(), actualList.ToArray());
</code></pre> |
15,958,446 | SourceTree App says uncommitted changes even for newly-cloned repository - what could be wrong? | <p>A remote git repository <strong>is just cloned</strong> to a local box using <a href="http://www.atlassian.com/software/sourcetree/overview" rel="noreferrer">Atlassian SourceTree</a>. Even no files have really been modified in the work tree, Atlassian lists a bunch of files right away under "Uncommitted changes". Each file shows same line count both as removed and added, and this count equals to the total count of lines in the file. This would somehow give a hint that we're hitting some kind of line ending problem.</p>
<p>However, the repository's <code>.gitattribute</code> contains</p>
<pre><code># Set default behaviour, in case users don't have core.autocrlf set.
* text=auto
</code></pre>
<p>that per GitHub article <a href="https://help.github.com/articles/dealing-with-line-endings" rel="noreferrer">Dealing with Line Endings</a> should make explicitly <code>core.autocrlf</code> true for the repository. However also <code>~/.gitconfig</code> contains <code>autocrlf = true</code>.</p>
<p>If the modified files are tried to be "reverted" back to previous commit, there is no effect. Same files are still seen as uncommitted.</p>
<p>The repository has been cloned into multiple locations and ensured that no files have been in the same path, to make sure that SourceTree or git do not remember old files.</p>
<p>The repository is collaborated with Windows, Linux and OSX boxes. This problem appears only in OSX.</p>
<p>What could still be wrong in the SourceTree/repository/git setup?</p>
<hr>
<p>Update #1, 20. Apr 2013</p>
<p>As there is still something wrong, here are partial outputs of <code>git config --list</code>.</p>
<p>From SourceTree console (OSX)</p>
<pre><code>core.excludesfile=/Users/User/.gitignore_global
core.autocrlf=input
difftool.sourcetree.cmd=opendiff "$LOCAL" "$REMOTE"
difftool.sourcetree.path=
mergetool.sourcetree.cmd=/Applications/SourceTree.app/Contents/Resources/opendiff-w.sh "$LOCAL" "$REMOTE" -ancestor "$BASE" -merge "$MERGED"
mergetool.sourcetree.trustexitcode=true
core.repositoryformatversion=0
core.filemode=true
core.bare=false
core.logallrefupdates=true
core.ignorecase=true
core.autocrlf=true
</code></pre>
<p>Here is corresponding output from Windows side:</p>
<pre><code>core.symlinks=false
core.autocrlf=false
color.diff=auto
color.status=auto
color.branch=auto
color.interactive=true
pack.packsizelimit=2g
help.format=html
http.sslcainfo=/bin/curl-ca-bundle.crt
sendemail.smtpserver=/bin/msmtp.exe
diff.astextplain.textconv=astextplain
rebase.autosquash=true
http.proxy=
core.autocrlf=true
core.repositoryformatversion=0
core.filemode=false
core.bare=false
core.logallrefupdates=true
core.symlinks=false
core.ignorecase=true
core.hidedotfiles=dotGitOnly
core.eol=native
core.autocrlf=true
</code></pre>
<p>And full <code>.gitattributes</code> for the repository in question</p>
<pre><code># Set default behaviour, in case users don't have core.autocrlf set.
* text=auto
*.php text
*.twig text
*.js text
*.html text diff=html
*.css text
*.xml text
*.txt text
*.sh text eol=lf
console text
*.png binary
*.jpg binary
*.gif binary
*.ico binary
*.xslx binary
</code></pre> | 15,967,109 | 5 | 5 | null | 2013-04-11 20:39:28.233 UTC | 18 | 2016-01-15 14:28:54.413 UTC | 2013-04-20 15:16:36.667 UTC | null | 769,144 | null | 769,144 | null | 1 | 40 | git|end-of-line|atlassian-sourcetree | 41,588 | <p>I'm one of the SourceTree developers (I develop the Mac version of the product, actually), so hopefully I can be of some help.</p>
<p>Windows machines convert CRLF to LF when committing and LF to CRLF when checking out. <code>autocrlf</code> makes sure everything is LF within the repository. The option <code>text = auto</code> is the one we're interested in though as it <a href="https://www.kernel.org/pub/software/scm/git/docs/gitattributes.html" rel="noreferrer">says in the docs</a>:</p>
<blockquote>
<p>When text is set to "auto", the path is marked for automatic end-of-line normalization. If git decides that the content is text, its line endings are normalized to LF on checkin.</p>
</blockquote>
<p>So you see on checkin it will say "Hey, I need to normalise these line-endings because they're not in LF format, but in CRLF." and thus modifies your working copy to do the work it's expected to do. Usually on Mac/Linux you wouldn't need to normalise because everything is in LF, but Git will do a check because you might've checked out from a repository that was previously developed on Windows, or perhaps in an editor that was using CRLF instead of LF.</p>
<p>So in short, you'd probably want to re-commit all of those files as they should be in LF format, but also make sure <code>autocrlf = true</code> (edit, always to true!) in your Windows repository as it says in the docs:</p>
<blockquote>
<p>If you simply want to have CRLF line endings in your working directory regardless of the repository you are working with, you can set the config variable "core.autocrlf" without changing any attributes.</p>
</blockquote>
<p>Although imagine that previous quote was when setting <code>autocrlf</code> for a specific repository as well as globally.</p>
<p>Hopefully that's of some help, if not, feel free to ask more questions!</p>
<hr>
<p>Here's a good SO post re: line endings: <a href="https://stackoverflow.com/questions/2825428/why-should-i-use-core-autocrlf-true-in-git">Why should I use core.autocrlf=true in Git?</a></p>
<hr>
<p><strong>EDIT</strong></p>
<p>Based on the above answer we need to make sure of a few things here.</p>
<ul>
<li>That you've set the relevant git options in your <code>.git/config</code></li>
<li>If you want to keep CRLF line endings then set <code>autocrlf=true</code></li>
<li>If, when checking out your repository, you don't want your line endings to be automatically converted (causing all your files to be in the "modified" state immediately) then set the <code>text</code> option to <code>unset</code>. Add this option if a global git config has it set to a value you don't want.</li>
<li>If you're working on both Windows and Mac for a project then it's best you have <code>text=auto</code> and make sure LF is used across the board. This is why problems like this creep in; because your git config's differ or because the initial project/git setup on Windows assumes CRLF when your Mac assumes LF.</li>
</ul> |
15,559,041 | Maven Multi Module benefits over simple dependency | <p>I have some years of experience with maven projects, even with multi modules ones (which has made me <em>hate</em> the multi modules feature of maven (so the disclaimer is now done)) and even if I really like maven there is something I cannot get a clear answer about : </p>
<p><strong>What is a typical usecase of a multi module maven project ? What is the added value of such a structure compared to simple dependencies and parent pom ?</strong></p>
<p>I have seen a lot of configuration of multi module projects but all of them could have clearly been addressed by creating a simple structure of dependency library living their own life as deliverables (even with a parent pom, as a separate deliverable : factorising depedencies and configuration) and I haven't found any usecase where I can clearly see an added value of the multi module structure. </p>
<p>I have always found that this kind of structure brings an overkilling complexity with no real benefit : where am I missing something ? (to be truly honest, I can get that some <code>ear</code> can benefit from this kind of structure but except from that particular usecase, any other real use and benefit ?)</p> | 15,559,536 | 5 | 0 | null | 2013-03-21 22:01:29.67 UTC | 16 | 2021-05-25 15:04:08.047 UTC | 2020-10-08 18:13:56.753 UTC | user166390 | 213,269 | null | 1,263,543 | null | 1 | 51 | maven|dependency-management|maven-module | 14,283 | <p>Here's a real life case.</p>
<p>I have a multi-module project (and to your rant... I haven't seen any complications with it.) The end result is a webapp but I have different modules for api, impl, and webapp.</p>
<p>12 months after creating the project I find that I have to integrate with Amazon S3 using a stand-alone process run from a jar. I add a new module which depends on api/impl and write my code for the integration in the new module. I use the assembly plugin (or something like it) to create a runnable jar and now I have a war I can deploy in tomcat and a process I can deploy on another server. I have no web classes in my S3 integration process and I have no Amazon dependencies in my webapp but I can share all the stuff in api and impl.</p>
<p>3 months after that we decide to create a REST webapp. We want to do it as a separate app instead of just new URL mappings in the existing webapp. Simple. One more module, another webapp created as the result of the maven build with no special tinkering. Business logic is shared easily between webapp and rest-webapp and I can deploy them as needed.</p> |
15,949,324 | Jquery set radio button checked, using id and class selectors | <p>Is it possible to set a radio button to checked using jquery - by a class and an id?</p>
<p>For example:</p>
<pre><code>$('input:radio[class=test1 id=test2]).attr('checked', true);
</code></pre>
<p>I only seem to be able to set it by id OR class but not by both.</p> | 15,949,355 | 1 | 0 | null | 2013-04-11 12:54:17.77 UTC | 9 | 2016-05-12 11:25:15.787 UTC | 2016-05-12 11:25:15.787 UTC | user2261248 | null | null | 2,269,829 | null | 1 | 58 | jquery|button|checked | 202,098 | <blockquote>
<p><em>"...by a class and a div."</em></p>
</blockquote>
<p>I assume when you say "div" you mean "id"? Try this:</p>
<pre><code>$('#test2.test1').prop('checked', true);
</code></pre>
<p>No need to muck about with your <code>[attributename=value]</code> style selectors because <a href="http://api.jquery.com/id-selector/" rel="noreferrer">id has its own format</a> as does <a href="http://api.jquery.com/class-selector/" rel="noreferrer">class</a>, and they're easily combined although given that id is supposed to be unique it should be enough on its own unless your meaning is "select that element only if it currently has the specified class".</p>
<p>Or more generally to select an input where you want to specify a <a href="http://api.jquery.com/multiple-attribute-selector/" rel="noreferrer">multiple attribute selector</a>:</p>
<pre><code>$('input:radio[class=test1][id=test2]').prop('checked', true);
</code></pre>
<p>That is, list each attribute with its own square brackets.</p>
<p>Note that unless you have a pretty old version of jQuery you should use <a href="http://api.jquery.com/prop/" rel="noreferrer"><code>.prop()</code></a> rather than <code>.attr()</code> for this purpose.</p> |
15,578,935 | Proper way of casting pointer types | <p>Considering the <a href="http://blogs.msdn.com/b/oldnewthing/archive/2005/05/19/420038.aspx" rel="noreferrer">following code</a> (and the fact that <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/aa366887%28v=vs.85%29.aspx" rel="noreferrer"><code>VirtualAlloc()</code> returns a <code>void*</code></a>):</p>
<pre><code>BYTE* pbNext = reinterpret_cast<BYTE*>(
VirtualAlloc(NULL, cbAlloc, MEM_COMMIT, PAGE_READWRITE));
</code></pre>
<p>why is <code>reinterpret_cast</code> chosen instead of <code>static_cast</code>?</p>
<p>I used to think that <code>reinterpret_cast</code> is OK for e.g. casting pointers to and from integer types (like e.g. <code>DWORD_PTR</code>), but to cast from a <code>void*</code> to a <code>BYTE*</code>, isn't <code>static_cast</code> OK?</p>
<p>Are there any (subtle?) differences in this particular case, or are they just both valid pointer casts?</p>
<p>Does the C++ standard have a preference for this case, suggesting a way instead of the other?</p> | 15,579,008 | 3 | 3 | null | 2013-03-22 20:01:46.093 UTC | 15 | 2018-12-14 16:01:21.46 UTC | null | null | null | null | 1,629,821 | null | 1 | 67 | c++|pointers|casting|reinterpret-cast|static-cast | 85,800 | <p>For <strong>convertible pointers to fundamental types</strong> both casts have the same meaning; so you are correct that <code>static_cast</code> is okay.</p>
<p>When converting between some pointer types, <em>it's possible that the specific memory address held in the pointer needs to change</em>.</p>
<p>That's where the two casts differ. <code>static_cast</code> will make the appropriate adjustment. <code>reinterpret_cast</code> will not.</p>
<p>For that reason, it's a good general rule to <code>static_cast</code> between pointer types unless you <strong>know</strong> that <code>reinterpret_cast</code> is desired. </p> |
51,112,963 | How to Configure Firebase Firestore settings with Flutter | <p>I'm evaluating the <a href="https://pub.dartlang.org/packages/cloud_firestore" rel="noreferrer">Firestore Plugin for Flutter</a>.</p>
<p>This snippet works as expected, it inserts a record into firestore when the floating button in pressed:</p>
<pre><code>import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
Firestore firestore;
_MyHomePageState() {
firestore = Firestore.instance;
}
void _addBoard() {
setState(() {
_counter++;
firestore.collection("boards").document().setData({ 'name': 'mote_$_counter', 'descr': 'long descr $_counter' });
});
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: new Center(
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Text(
'You have pushed the button this many times:',
),
new Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
],
),
),
floatingActionButton: new FloatingActionButton(
onPressed: _addBoard,
child: new Icon(Icons.add),
),
}
}
</code></pre>
<p>Running with <code>flutter run</code> the console show the warning:</p>
<pre><code>W/Firestore(31567): (0.6.6-dev) [Firestore]: The behavior for java.util.Date objects stored in Firestore is going to change AND YOUR APP MAY BREAK.
W/Firestore(31567): To hide this warning and ensure your app does not break, you need to add the following code to your app before calling any other Cloud Firestore methods:
W/Firestore(31567):
W/Firestore(31567): FirebaseFirestore firestore = FirebaseFirestore.getInstance();
W/Firestore(31567): FirebaseFirestoreSettings settings = new FirebaseFirestoreSettings.Builder()
W/Firestore(31567): .setTimestampsInSnapshotsEnabled(true)
W/Firestore(31567): .build();
W/Firestore(31567): firestore.setFirestoreSettings(settings);
W/Firestore(31567):
W/Firestore(31567): With this change, timestamps stored in Cloud Firestore will be read back as com.google.firebase.Timestamp objects instead of as system java.util.Date objects. So you will also need to update code expecting a java.util.Date to instead expect a Timest
</code></pre>
<p>There is a way to configure the FirebaseFirestore instance and thus fix this issue with date settings?</p> | 52,885,939 | 2 | 2 | null | 2018-06-30 07:59:24.787 UTC | 9 | 2021-04-29 12:03:54.68 UTC | null | null | null | null | 3,356,777 | null | 1 | 11 | google-cloud-firestore|flutter | 5,731 | <p>it should be resolved in version 0.8.2.</p>
<p>See <a href="https://github.com/flutter/plugins/blob/master/packages/cloud_firestore/example/" rel="nofollow noreferrer">example</a> of how to use settings.</p> |
10,760,326 | How to merge two multi-line blocks of text in Vim? | <p>I’d like to merge two blocks of lines in Vim, i.e., take lines <em>k</em> through <em>l</em> and append them to lines <em>m</em> through <em>n</em>. If you prefer a pseudocode explanation: <code>[line[k+i] + line[m+i] for i in range(min(l-k, n-m)+1)]</code>.</p>
<p>For example,</p>
<pre><code>abc
def
...
123
45
...
</code></pre>
<p>should become</p>
<pre><code>abc123
def45
</code></pre>
<p>Is there a nice way to do this without copying and pasting manually line by line?</p> | 10,760,494 | 9 | 3 | null | 2012-05-25 19:30:08.177 UTC | 121 | 2022-06-14 06:23:36.7 UTC | 2020-09-29 02:24:48.68 UTC | null | 254,635 | null | 298,479 | null | 1 | 327 | vim | 80,906 | <p>You can certainly do all this with a single copy/paste (using block-mode selection), but I'm guessing that's not what you want.</p>
<p>If you want to do this with just <a href="http://en.wikipedia.org/wiki/Ex_%28text_editor%29">Ex</a> commands</p>
<pre><code>:5,8del | let l=split(@") | 1,4s/$/\=remove(l,0)/
</code></pre>
<p>will transform</p>
<pre><code>work it
make it
do it
makes us
harder
better
faster
stronger
~
</code></pre>
<p>into</p>
<pre><code>work it harder
make it better
do it faster
makes us stronger
~
</code></pre>
<hr>
<p><strong>UPDATE:</strong> An answer with this many upvotes deserves a more thorough explanation.</p>
<p>In Vim, you can use the pipe character (<code>|</code>) to chain multiple Ex commands, so the above is equivalent to</p>
<pre><code>:5,8del
:let l=split(@")
:1,4s/$/\=remove(l,0)/
</code></pre>
<p>Many Ex commands accept a range of lines as a prefix argument - in the above case the <code>5,8</code> before the <code>del</code> and the <code>1,4</code> before the <code>s///</code> specify which lines the commands operate on.</p>
<p><code>del</code> deletes the given lines. It can take a register argument, but when one is not given, it dumps the lines to the unnamed register, <code>@"</code>, just like deleting in normal mode does. <code>let l=split(@")</code> then splits the deleted lines into a list, using the default delimiter: whitespace. To work properly on input that had whitespace in the deleted lines, like:</p>
<pre><code>more than
hour
our
never
ever
after
work is
over
~
</code></pre>
<p>we'd need to specify a different delimiter, to prevent "work is" from being split into two list elements: <code>let l=split(@","\n")</code>.</p>
<p>Finally, in the substitution <code>s/$/\=remove(l,0)/</code>, we replace the end of each line (<code>$</code>) with the value of the expression <code>remove(l,0)</code>. <code>remove(l,0)</code> alters the list <code>l</code>, deleting and returning its first element. This lets us replace the deleted lines in the order in which we read them. We could instead replace the deleted lines in reverse order by using <code>remove(l,-1)</code>.</p> |
10,834,393 | PHP: How to get all possible combinations of 1D array? | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/1256117/algorithm-that-will-take-numbers-or-words-and-find-all-possible-combinations">algorithm that will take numbers or words and find all possible combinations</a><br>
<a href="https://stackoverflow.com/questions/1679605/combinations-dispositions-and-permutations-in-php">Combinations, Dispositions and Permutations in PHP</a> </p>
</blockquote>
<p>I've read/tried alot of the suggested answers on SO, which none of them solves the problem</p>
<pre><code>$array = array('Alpha', 'Beta', 'Gamma');
</code></pre>
<p>How to get all possible combinations?</p>
<p>Expected output:</p>
<pre><code>array('Alpha',
'Beta',
'Gamma',
'Alpha Beta',
'Alpha Gamma',
'Beta Alpha',
'Beta Gamma',
'Gamma Alpha',
'Gamma Beta',
'Alpha Beta Gamma',
'Alpha Gamma Beta',
'Beta Alpha Gamma',
'Beta Gamma Alpha',
'Gamma Alpha Beta',
'Gamma Beta Alpha')
</code></pre>
<p>Note: The answer I'm looking for should include <em>all combinations and all different arrangements</em>. For example: <strong>'Alpha Beta'</strong> and <strong>'Beta Alpha'</strong> are 2 different strings and both should be in the output array.</p>
<p>Thanks in advance</p> | 10,835,795 | 1 | 7 | null | 2012-05-31 13:14:55.15 UTC | 9 | 2019-12-02 18:28:30.297 UTC | 2017-05-23 12:09:55.29 UTC | null | -1 | null | 134,824 | null | 1 | 35 | php|combinations | 32,293 | <p>I believe your professor will be happier with this solution:</p>
<pre><code><?php
$array = array('Alpha', 'Beta', 'Gamma', 'Sigma');
function depth_picker($arr, $temp_string, &$collect) {
if ($temp_string != "")
$collect []= $temp_string;
for ($i=0, $iMax = sizeof($arr); $i < $iMax; $i++) {
$arrcopy = $arr;
$elem = array_splice($arrcopy, $i, 1); // removes and returns the i'th element
if (sizeof($arrcopy) > 0) {
depth_picker($arrcopy, $temp_string ." " . $elem[0], $collect);
} else {
$collect []= $temp_string. " " . $elem[0];
}
}
}
$collect = array();
depth_picker($array, "", $collect);
print_r($collect);
?>
</code></pre>
<p>This solves it:</p>
<pre><code>Array
(
[0] => Alpha
[1] => Alpha Beta
[2] => Alpha Beta Gamma
[3] => Alpha Beta Gamma Sigma
[4] => Alpha Beta Sigma
[5] => Alpha Beta Sigma Gamma
[6] => Alpha Gamma
[7] => Alpha Gamma Beta
[8] => Alpha Gamma Beta Sigma
[9] => Alpha Gamma Sigma
[10] => Alpha Gamma Sigma Beta
[11] => Alpha Sigma
[12] => Alpha Sigma Beta
[13] => Alpha Sigma Beta Gamma
[14] => Alpha Sigma Gamma
[15] => Alpha Sigma Gamma Beta
[16] => Beta
[17] => Beta Alpha
[18] => Beta Alpha Gamma
[19] => Beta Alpha Gamma Sigma
[20] => Beta Alpha Sigma
[21] => Beta Alpha Sigma Gamma
[22] => Beta Gamma
[23] => Beta Gamma Alpha
[24] => Beta Gamma Alpha Sigma
[25] => Beta Gamma Sigma
[26] => Beta Gamma Sigma Alpha
[27] => Beta Sigma
[28] => Beta Sigma Alpha
[29] => Beta Sigma Alpha Gamma
[30] => Beta Sigma Gamma
[31] => Beta Sigma Gamma Alpha
[32] => Gamma
[33] => Gamma Alpha
[34] => Gamma Alpha Beta
[35] => Gamma Alpha Beta Sigma
[36] => Gamma Alpha Sigma
[37] => Gamma Alpha Sigma Beta
[38] => Gamma Beta
[39] => Gamma Beta Alpha
[40] => Gamma Beta Alpha Sigma
[41] => Gamma Beta Sigma
[42] => Gamma Beta Sigma Alpha
[43] => Gamma Sigma
[44] => Gamma Sigma Alpha
[45] => Gamma Sigma Alpha Beta
[46] => Gamma Sigma Beta
[47] => Gamma Sigma Beta Alpha
[48] => Sigma
[49] => Sigma Alpha
[50] => Sigma Alpha Beta
[51] => Sigma Alpha Beta Gamma
[52] => Sigma Alpha Gamma
[53] => Sigma Alpha Gamma Beta
[54] => Sigma Beta
[55] => Sigma Beta Alpha
[56] => Sigma Beta Alpha Gamma
[57] => Sigma Beta Gamma
[58] => Sigma Beta Gamma Alpha
[59] => Sigma Gamma
[60] => Sigma Gamma Alpha
[61] => Sigma Gamma Alpha Beta
[62] => Sigma Gamma Beta
[63] => Sigma Gamma Beta Alpha
)
</code></pre> |
33,443,918 | 403 Forbidden on nginx/1.4.6 (Ubuntu) - Laravel | <p>I keep getting <code>403 Forbidden</code></p>
<p><a href="https://i.stack.imgur.com/pEXD5.png" rel="noreferrer"><img src="https://i.stack.imgur.com/pEXD5.png" alt="enter image description here"></a></p>
<hr>
<p>My settings:</p>
<p><code>/etc/nginx/sites-available/default</code></p>
<p><strong>default</strong></p>
<pre><code>server {
listen 80;
root home/laravel-app/;
index index.php index.html index.htm;
server_name example.com;
location / {
try_files $uri $uri/ /index.html;
}
error_page 404 /404.html;
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/www;
}
# pass the PHP scripts to FastCGI server listening on the php-fpm socket
location ~ \.php$ {
try_files $uri =404;
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
</code></pre>
<hr>
<p><strong>Update</strong></p>
<p>I followed this instruction : <a href="https://www.digitalocean.com/community/tutorials/how-to-install-linux-nginx-mysql-php-lemp-stack-on-ubuntu-12-04" rel="noreferrer">here</a> </p>
<hr>
<p>Any hints/suggestions on this will be a huge help ! </p> | 33,547,989 | 3 | 7 | null | 2015-10-30 19:53:55.973 UTC | 3 | 2019-09-12 08:49:29.71 UTC | 2015-11-05 14:36:43.367 UTC | null | 4,480,164 | null | 4,480,164 | null | 1 | 24 | php|laravel|nginx|ubuntu-12.04|laravel-5.1 | 41,762 | <p>You need to specify an absolute path for your <code>root</code> directive. Nginx uses the directory set at compile time using the --prefix switch. By default this is <code>/usr/local/nginx</code>.</p>
<p>What this means is that your root, which is currently set to root <code>home/laravel-app/</code> causes nginx to look for files at <code>/usr/local/nginx/home/laravel-app/</code> which presumably isn't where your files are.</p>
<p>If you set your <code>root</code> directive to an absolute path such as <code>/var/www/laravel-app/public/</code> nginx will find the files.</p>
<p>Similarly you'll note that I added <code>/public/</code> to the path above. This is because Laravel stores it's <code>index.php</code> file there. If you were to just point at <code>/laravel-app/</code> there's no index file and it'd give you a 403.</p> |
22,542,834 | How to use Regular Expressions (Regex) in Microsoft Excel both in-cell and loops | <p>How can I use regular expressions in Excel and take advantage of Excel's powerful grid-like setup for data manipulation?</p>
<ul>
<li>In-cell function to return a matched pattern or replaced value in a string.</li>
<li>Sub to loop through a column of data and extract matches to adjacent cells.</li>
<li>What setup is necessary?</li>
<li>What are Excel's special characters for Regular expressions?</li>
</ul>
<hr>
<p>I understand Regex is not ideal for many situations (<a href="https://stackoverflow.com/a/4098123/2521004">To use or not to use regular expressions?</a>) since excel can use <code>Left</code>, <code>Mid</code>, <code>Right</code>, <code>Instr</code> type commands for similar manipulations. </p> | 22,542,835 | 9 | 3 | null | 2014-03-20 19:09:13.197 UTC | 483 | 2022-09-17 18:45:33.52 UTC | 2019-05-24 15:01:53.507 UTC | null | 2,190,175 | null | 2,521,004 | null | 1 | 719 | regex|excel|vba | 1,180,525 | <p><a href="http://en.wikipedia.org/wiki/Regular_expressions" rel="noreferrer">Regular expressions</a> are used for Pattern Matching.</p>
<p>To use in Excel follow these steps:</p>
<p><strong>Step 1</strong>: Add VBA reference to "Microsoft VBScript Regular Expressions 5.5"</p>
<ul>
<li>Select "Developer" tab (<a href="http://msdn.microsoft.com/en-us/library/bb608625.aspx" rel="noreferrer">I don't have this tab what do I do?</a>)</li>
<li>Select "Visual Basic" icon from 'Code' ribbon section</li>
<li>In "Microsoft Visual Basic for Applications" window select "Tools" from the top menu.</li>
<li>Select "References"</li>
<li>Check the box next to "Microsoft VBScript Regular Expressions 5.5" to include in your workbook.</li>
<li>Click "OK"</li>
</ul>
<p><strong>Step 2</strong>: Define your pattern</p>
<p><em>Basic definitions:</em></p>
<p><code>-</code> Range.</p>
<ul>
<li>E.g. <code>a-z</code> matches an lower case letters from a to z</li>
<li>E.g. <code>0-5</code> matches any number from 0 to 5</li>
</ul>
<p><code>[]</code> Match exactly one of the objects inside these brackets.</p>
<ul>
<li>E.g. <code>[a]</code> matches the letter a</li>
<li>E.g. <code>[abc]</code> matches a single letter which can be a, b or c</li>
<li>E.g. <code>[a-z]</code> matches any single lower case letter of the alphabet.</li>
</ul>
<p><code>()</code> Groups different matches for return purposes. See examples below.</p>
<p><code>{}</code> Multiplier for repeated copies of pattern defined before it.</p>
<ul>
<li>E.g. <code>[a]{2}</code> matches two consecutive lower case letter a: <code>aa</code></li>
<li>E.g. <code>[a]{1,3}</code> matches at least one and up to three lower case letter <code>a</code>, <code>aa</code>, <code>aaa</code></li>
</ul>
<p><code>+</code> Match at least one, or more, of the pattern defined before it.</p>
<ul>
<li>E.g. <code>a+</code> will match consecutive a's <code>a</code>, <code>aa</code>, <code>aaa</code>, and so on</li>
</ul>
<p><code>?</code> Match zero or one of the pattern defined before it.</p>
<ul>
<li>E.g. Pattern may or may not be present but can only be matched one time.</li>
<li>E.g. <code>[a-z]?</code> matches empty string or any single lower case letter.</li>
</ul>
<p><code>*</code> Match zero or more of the pattern defined before it.</p>
<ul>
<li>E.g. Wildcard for pattern that may or may not be present.</li>
<li>E.g. <code>[a-z]*</code> matches empty string or string of lower case letters.</li>
</ul>
<p><code>.</code> Matches any character except newline <code>\n</code></p>
<ul>
<li>E.g. <code>a.</code> Matches a two character string starting with a and ending with anything except <code>\n</code></li>
</ul>
<p><code>|</code> OR operator</p>
<ul>
<li>E.g. <code>a|b</code> means either <code>a</code> or <code>b</code> can be matched.</li>
<li>E.g. <code>red|white|orange</code> matches exactly one of the colors.</li>
</ul>
<p><code>^</code> NOT operator</p>
<ul>
<li>E.g. <code>[^0-9]</code> character can not contain a number</li>
<li>E.g. <code>[^aA]</code> character can not be lower case <code>a</code> or upper case <code>A</code></li>
</ul>
<p><code>\</code> Escapes special character that follows (overrides above behavior)</p>
<ul>
<li>E.g. <code>\.</code>, <code>\\</code>, <code>\(</code>, <code>\?</code>, <code>\$</code>, <code>\^</code></li>
</ul>
<hr />
<p><em>Anchoring Patterns:</em></p>
<p><code>^</code> Match must occur at start of string</p>
<ul>
<li>E.g. <code>^a</code> First character must be lower case letter <code>a</code></li>
<li>E.g. <code>^[0-9]</code> First character must be a number.</li>
</ul>
<p><code>$</code> Match must occur at end of string</p>
<ul>
<li>E.g. <code>a$</code> Last character must be lower case letter <code>a</code></li>
</ul>
<hr />
<p><em>Precedence table:</em></p>
<pre><code>Order Name Representation
1 Parentheses ( )
2 Multipliers ? + * {m,n} {m, n}?
3 Sequence & Anchors abc ^ $
4 Alternation |
</code></pre>
<hr />
<p><em>Predefined Character Abbreviations:</em></p>
<pre><code>abr same as meaning
\d [0-9] Any single digit
\D [^0-9] Any single character that's not a digit
\w [a-zA-Z0-9_] Any word character
\W [^a-zA-Z0-9_] Any non-word character
\s [ \r\t\n\f] Any space character
\S [^ \r\t\n\f] Any non-space character
\n [\n] New line
</code></pre>
<hr />
<p><strong>Example 1</strong>: <em>Run as macro</em></p>
<p>The following example macro looks at the value in cell <code>A1</code> to see if the first 1 or 2 characters are digits. If so, they are removed and the rest of the string is displayed. If not, then a box appears telling you that no match is found. Cell <code>A1</code> values of <code>12abc</code> will return <code>abc</code>, value of <code>1abc</code> will return <code>abc</code>, value of <code>abc123</code> will return "Not Matched" because the digits were not at the start of the string.</p>
<pre><code>Private Sub simpleRegex()
Dim strPattern As String: strPattern = "^[0-9]{1,2}"
Dim strReplace As String: strReplace = ""
Dim regEx As New RegExp
Dim strInput As String
Dim Myrange As Range
Set Myrange = ActiveSheet.Range("A1")
If strPattern <> "" Then
strInput = Myrange.Value
With regEx
.Global = True
.MultiLine = True
.IgnoreCase = False
.Pattern = strPattern
End With
If regEx.Test(strInput) Then
MsgBox (regEx.Replace(strInput, strReplace))
Else
MsgBox ("Not matched")
End If
End If
End Sub
</code></pre>
<hr />
<p><strong>Example 2</strong>: <em>Run as an in-cell function</em></p>
<p>This example is the same as example 1 but is setup to run as an in-cell function. To use, change the code to this:</p>
<pre><code>Function simpleCellRegex(Myrange As Range) As String
Dim regEx As New RegExp
Dim strPattern As String
Dim strInput As String
Dim strReplace As String
Dim strOutput As String
strPattern = "^[0-9]{1,3}"
If strPattern <> "" Then
strInput = Myrange.Value
strReplace = ""
With regEx
.Global = True
.MultiLine = True
.IgnoreCase = False
.Pattern = strPattern
End With
If regEx.test(strInput) Then
simpleCellRegex = regEx.Replace(strInput, strReplace)
Else
simpleCellRegex = "Not matched"
End If
End If
End Function
</code></pre>
<p>Place your strings ("12abc") in cell <code>A1</code>. Enter this formula <code>=simpleCellRegex(A1)</code> in cell <code>B1</code> and the result will be "abc".</p>
<p><img src="https://i.stack.imgur.com/q3RRC.png" alt="results image" /></p>
<hr />
<p><strong>Example 3</strong>: <em>Loop Through Range</em></p>
<p>This example is the same as example 1 but loops through a range of cells.</p>
<pre><code>Private Sub simpleRegex()
Dim strPattern As String: strPattern = "^[0-9]{1,2}"
Dim strReplace As String: strReplace = ""
Dim regEx As New RegExp
Dim strInput As String
Dim Myrange As Range
Set Myrange = ActiveSheet.Range("A1:A5")
For Each cell In Myrange
If strPattern <> "" Then
strInput = cell.Value
With regEx
.Global = True
.MultiLine = True
.IgnoreCase = False
.Pattern = strPattern
End With
If regEx.Test(strInput) Then
MsgBox (regEx.Replace(strInput, strReplace))
Else
MsgBox ("Not matched")
End If
End If
Next
End Sub
</code></pre>
<hr />
<p><strong>Example 4</strong>: Splitting apart different patterns</p>
<p>This example loops through a range (<code>A1</code>, <code>A2</code> & <code>A3</code>) and looks for a string starting with three digits followed by a single alpha character and then 4 numeric digits. The output splits apart the pattern matches into adjacent cells by using the <code>()</code>. <code>$1</code> represents the first pattern matched within the first set of <code>()</code>.</p>
<pre><code>Private Sub splitUpRegexPattern()
Dim regEx As New RegExp
Dim strPattern As String
Dim strInput As String
Dim Myrange As Range
Set Myrange = ActiveSheet.Range("A1:A3")
For Each C In Myrange
strPattern = "(^[0-9]{3})([a-zA-Z])([0-9]{4})"
If strPattern <> "" Then
strInput = C.Value
With regEx
.Global = True
.MultiLine = True
.IgnoreCase = False
.Pattern = strPattern
End With
If regEx.test(strInput) Then
C.Offset(0, 1) = regEx.Replace(strInput, "$1")
C.Offset(0, 2) = regEx.Replace(strInput, "$2")
C.Offset(0, 3) = regEx.Replace(strInput, "$3")
Else
C.Offset(0, 1) = "(Not matched)"
End If
End If
Next
End Sub
</code></pre>
<p>Results:</p>
<p><img src="https://i.stack.imgur.com/9eCZ5.png" alt="results image" /></p>
<hr />
<p><strong>Additional Pattern Examples</strong></p>
<pre class="lang-none prettyprint-override"><code>String Regex Pattern Explanation
a1aaa [a-zA-Z][0-9][a-zA-Z]{3} Single alpha, single digit, three alpha characters
a1aaa [a-zA-Z]?[0-9][a-zA-Z]{3} May or may not have preceding alpha character
a1aaa [a-zA-Z][0-9][a-zA-Z]{0,3} Single alpha, single digit, 0 to 3 alpha characters
a1aaa [a-zA-Z][0-9][a-zA-Z]* Single alpha, single digit, followed by any number of alpha characters
</i8> \<\/[a-zA-Z][0-9]\> Exact non-word character except any single alpha followed by any single digit
</code></pre> |
13,758,482 | How to implement 3d secure payment securely | <p>I'm wondering what's the best way of accepting payments from credit cards that require <a href="http://en.wikipedia.org/wiki/3-D_Secure" rel="noreferrer">3-D Secure</a> verification. Currently the checkout flow is like this:</p>
<ol>
<li>Customer submits payment</li>
<li>Payment gateway returns an error stating that the card requires 3-D secure code processing. Returns the ACS URL in the response</li>
<li>I redirect user to the issuing bank's verification site and I pass a callback URL for the ACS to redirect after completion of verification</li>
<li>Customer enters verification code and ACS redirects to the callback URL with an authorization token indicating successful verification</li>
<li>To complete the process, I have to resubmit the original request with the authorization token to the payment gateway</li>
</ol>
<p>My problem is in the final step. As I need to resubmit the original request (which contains the credit card information of the customer), I need to store it somewhere temporarily so I can retrieve it when the callback URL is called. Is there an alternative to this? </p>
<p>I'm thinking of trying an iframe solution: The original form is never closed and I display the verification process in an iframe. When the process completes, i.e. the callback url is called, I hide the iframe and update the original form with the needed values and resubmit. Has anyone tried this technique before?</p>
<hr> | 13,762,496 | 3 | 0 | null | 2012-12-07 07:06:22.573 UTC | 11 | 2015-12-03 22:15:43.913 UTC | null | null | null | null | 72,356 | null | 1 | 15 | security|credit-card|3d-secure | 14,339 | <p>As you might already noticed in article you linked, presenting bank's page in iframe is a preferred option. Although if you read in further, it presents other security features, specifically in regard to phishing protection. Because your client won't know to whom is he really sending his password. </p>
<p>But going back to your proposition, if you present it in iframe or popup window, you would be able to store the original form on your base page and then resubmit it with received authentication token. It's a very good idea because you would not need to do any PCI compliance stuff. So not only it's easier for you it is recommended :).</p> |
13,425,425 | How to customize startup of WPF application? | <p>When a new WPF Application project is created, <code>MainWindow.xaml</code>, <code>App.xaml</code> and their corresponding code behind classes are automatically generated. In the <code>App.xaml</code> there is an attribute that defines which window is going to be run initially and by the default it's <code>StartupUri="MainWindow.xaml"</code></p>
<p>I have created a new <code>Dispatcher</code> class in the same project. At startup, I want the instance of that class <code>Dispatcher</code> to be constructed and then one of its method to run. That method would actually create and show the <code>MainWindow</code> window. So how do I modify the <code>App.xaml</code> or <code>App.xaml.cs</code> in order to make it happen? Or, if it cannot be done by <code>App</code>, how should I implement it? Thanks.</p> | 13,425,695 | 3 | 0 | null | 2012-11-16 22:33:50.55 UTC | 7 | 2022-04-13 08:38:11.7 UTC | 2012-11-16 22:42:36.943 UTC | null | 119,093 | null | 119,093 | null | 1 | 31 | wpf|startup | 46,168 | <p>You can remove the <code>StartupUri</code> attribute from the App.xaml.</p>
<p>Then, by creating an override for <code>OnStartup()</code> in the App.xaml.cs, you can create your new instance of your <code>Dispatcher</code> class.</p>
<p>Here's what my quick app.xaml.cs implementation looks like:</p>
<pre><code>public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
new MyClassIWantToInstantiate();
}
}
}
</code></pre>
<p><strong>Update</strong></p>
<p>I recently discovered <a href="https://stackoverflow.com/a/3896209/23074">this workaround</a> for a bug if you use this method to customize app startup and suddenly none of the Application-level resources can be found.</p> |
13,594,507 | What does it mean to have an index to scalar variable error? python | <pre><code>import numpy as np
with open('matrix.txt', 'r') as f:
x = []
for line in f:
x.append(map(int, line.split()))
f.close()
a = array(x)
l, v = eig(a)
exponent = array(exp(l))
L = identity(len(l))
for i in xrange(len(l)):
L[i][i] = exponent[0][i]
print L
</code></pre>
<ol>
<li><p>My code opens up a text file containing a matrix:<br />
<code>1 2</code><br />
<code>3 4</code><br />
and places it in list <code>x</code> as integers.</p>
</li>
<li><p>The list <code>x</code> is then converted into an array <code>a</code>.</p>
</li>
<li><p>The eigenvalues of <code>a</code> are placed in <code>l</code> and the eigenvectors are placed in <code>v</code>.</p>
</li>
<li><p>I then want to take the exp(a) and place it in another array <code>exponent</code>.</p>
</li>
<li><p>Then I create an identity matrix <code>L</code> of whatever length <code>l</code> is.</p>
</li>
<li><p>My for loop is supposed to take the values of <code>exponent</code> and replace the 1's across the diagonal of the identity matrix but I get an error saying</p>
<blockquote>
<p><code>invalid index to scalar variable</code>.</p>
</blockquote>
</li>
</ol>
<p>What is wrong with my code?</p> | 13,594,564 | 3 | 1 | null | 2012-11-27 22:42:22.327 UTC | 2 | 2020-04-07 19:46:56.52 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 1,855,428 | null | 1 | 36 | python | 159,264 | <p><code>exponent</code> is a 1D array. This means that <code>exponent[0]</code> is a scalar, and <code>exponent[0][i]</code> is trying to access it as if it were an array.</p>
<p>Did you mean to say:</p>
<pre><code>L = identity(len(l))
for i in xrange(len(l)):
L[i][i] = exponent[i]
</code></pre>
<p>or even</p>
<pre><code>L = diag(exponent)
</code></pre>
<p>?</p> |
13,238,203 | Automatic Migrations for ASP.NET SimpleMembershipProvider | <p>So I tried to use automatic migrations with my new MVC 4 Project but somehow it isn't working. I <a href="http://blog.longle.net/2012/09/25/seeding-users-and-roles-with-mvc4-simplemembershipprovider-simpleroleprovider-ef5-codefirst-and-custom-user-properties/">followed this blog post</a> step by step.</p>
<p>I've added the changes to the <code>UserProfile</code> account model (the <code>NotaryCode</code> field): </p>
<pre><code>[Table("UserProfile")]
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
public int NotaryCode { get; set; }
}
</code></pre>
<p>Then I wrote on the package manager console <code>enable-migrations</code> and a Configuration class appeared (inherits from <code>DbMigrationsConfiguration<Web.Models.UsersContext></code>) then I fill the class as:</p>
<pre><code>public Configuration()
{
AutomaticMigrationsEnabled = true;
}
protected override void Seed(Atomic.Vesper.Cloud.Web.Models.UsersContext context)
{
WebSecurity.InitializeDatabaseConnection(
"DefaultConnection",
"UserProfile",
"UserId",
"UserName", autoCreateTables: true);
if (!Roles.RoleExists("Atomic"))
Roles.CreateRole("Atomic");
if (!Roles.RoleExists("Protocolista"))
Roles.CreateRole("Protocolista");
if (!Roles.RoleExists("Cliente"))
Roles.CreateRole("Cliente");
string adminUser = "randolf";
if (!WebSecurity.UserExists(adminUser))
WebSecurity.CreateUserAndAccount(
adminUser,
"12345",
new { NotaryCode = -1 });
if (!Roles.GetRolesForUser(adminUser).Contains("Atomic"))
Roles.AddUsersToRoles(new[] { adminUser }, new[] { "Atomic" });
}
</code></pre>
<p>And then I tried to run <code>update-database -verbose</code> but this doesn't work. I mean, this is the output:</p>
<p><strong>There is already an object named 'UserProfile' in the database.</strong></p>
<pre><code>PM> update-database -verbose
Using StartUp project 'Web'.
Using NuGet project 'Web'.
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
Target database is: 'VesperCloud' (DataSource: .\SQLSERVER, Provider: System.Data.SqlClient, Origin: Configuration).
No pending code-based migrations.
Applying automatic migration: 201211051825098_AutomaticMigration.
CREATE TABLE [dbo].[UserProfile] (
[UserId] [int] NOT NULL IDENTITY,
[UserName] [nvarchar](max),
[NotaryCode] [int] NOT NULL,
CONSTRAINT [PK_dbo.UserProfile] PRIMARY KEY ([UserId])
)
System.Data.SqlClient.SqlException (0x80131904): There is already an object named 'UserProfile' in the database.
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at System.Data.Entity.Migrations.DbMigrator.ExecuteSql(DbTransaction transaction, MigrationStatement migrationStatement)
at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.ExecuteSql(DbTransaction transaction, MigrationStatement migrationStatement)
at System.Data.Entity.Migrations.DbMigrator.ExecuteStatements(IEnumerable`1 migrationStatements)
at System.Data.Entity.Migrations.Infrastructure.MigratorBase.ExecuteStatements(IEnumerable`1 migrationStatements)
at System.Data.Entity.Migrations.DbMigrator.ExecuteOperations(String migrationId, XDocument targetModel, IEnumerable`1 operations, Boolean downgrading, Boolean auto)
at System.Data.Entity.Migrations.DbMigrator.AutoMigrate(String migrationId, XDocument sourceModel, XDocument targetModel, Boolean downgrading)
at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.AutoMigrate(String migrationId, XDocument sourceModel, XDocument targetModel, Boolean downgrading)
at System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)
at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)
at System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration)
at System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update(String targetMigration)
at System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.RunCore()
at System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.Run()
ClientConnectionId:a7da0ddb-bccf-490f-bc1e-ecd2eb4eab04
**There is already an object named 'UserProfile' in the database.**
</code></pre>
<p>I know the object exists. I mean, I'm try to use automatic-migrations to, precisely, modify and run without recreating manually the DB. But somehow this isn't working.</p>
<p>I look the MSDN documentation and found the property:</p>
<pre><code>AutomaticMigrationDataLossAllowed = true;
</code></pre>
<p>But setting it to true doesn't change anything. I guess I'm missing something but somehow doesn't find what. Any idea?</p> | 13,304,855 | 3 | 1 | null | 2012-11-05 18:36:16.897 UTC | 34 | 2015-09-20 10:54:39.033 UTC | 2013-05-28 12:03:50.44 UTC | null | 1,790,982 | null | 744,484 | null | 1 | 43 | asp.net-mvc-4|entity-framework-5|entity-framework-migrations | 39,521 | <p><code>update-database -verbose</code> doesn't work because your model has been changed after your data table already existed.</p>
<p>First, make sure there are no changes to the UserProfile class. Then, run: </p>
<p><code>Add-Migration InitialMigrations -IgnoreChanges</code></p>
<p>This should generate a blank "InitialMigration" file. Now, add any desired changes to the UserProfile class. Once changes are added, run the update command again:</p>
<p><code>update-database -verbose</code></p>
<p>Now the automatic migration will be applied and the table will be altered with your changes.</p> |
24,369,197 | How to add static text inside an input form | <p>How can I put this static text in an input form?</p>
<p>It's there all the time.</p>
<p><img src="https://i.stack.imgur.com/Xxsnr.jpg" alt="Enter image description here"></p>
<p>This is my code:</p>
<pre><code><label for="subdomain">Subdomain:</label>
<input type="text" placeholder="ExampleDomain" id="subdomain"/>
</code></pre> | 24,369,498 | 8 | 4 | null | 2014-06-23 15:02:06.72 UTC | 6 | 2022-05-15 18:32:39.763 UTC | 2019-07-09 22:52:35.567 UTC | null | 63,550 | null | 2,715,378 | null | 1 | 13 | html|css|forms|input | 122,125 | <h3>HTML</h3>
<pre><code><label for="subdomain">Subdomain:</label>
<input type="text" placeholder="ExampleDomain" id="subdomain" />
<input type="text" id="subdomaintwo" value=".domain.com" disabled/>
</code></pre>
<h3>CSS</h3>
<pre><code>input[type="text"]#subdomaintwo{
-webkit-appearance: none!important;
color: red;
text-align: right;
width: 75px;
border: 1px solid gray;
border-left: 0px;
margin: 0 0 0 -7px;
background: white;
}
input[type="text"]#subdomain{
-webkit-appearance: none!important;
border: 1px solid gray;
border-right: 0px;
outline: none;
}
</code></pre>
<p><a href="https://jsfiddle.net/aeLn6rt8/" rel="nofollow noreferrer">JS Fiddle for this</a></p> |
3,369,993 | How to set a console application window to be the top most window (C#)? | <p>How do i set a console application to be the top most window. I am building the console application in .NET (i am using C# and maybe even pinvokes to unmanaged code is ok).</p>
<p>I thought that i could have my console application derive from Form class</p>
<pre><code>class MyConsoleApp : Form {
public MyConsoleApp() {
this.TopLevel = true;
this.TopMost = true;
this.CenterToScreen();
}
public void DoSomething() {
//....
}
public static void Main() {
MyConsoleApp consoleApp = new MyConsoleApp();
consoleApp.DoSomething();
}
}
</code></pre>
<p>However this doesn't work. I am not sure if the properties set on the windows form is applicable to the console UI.</p> | 3,370,052 | 2 | 0 | null | 2010-07-30 08:56:53.113 UTC | 9 | 2020-11-11 19:15:24.547 UTC | null | null | null | null | 184,774 | null | 1 | 8 | c#|window|console-application | 11,698 | <p>You can P/Invoke <code>SetWindowPos</code> from the Windows API:</p>
<pre><code>using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
class Program
{
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool SetWindowPos(
IntPtr hWnd,
IntPtr hWndInsertAfter,
int x,
int y,
int cx,
int cy,
int uFlags);
private const int HWND_TOPMOST = -1;
private const int SWP_NOMOVE = 0x0002;
private const int SWP_NOSIZE = 0x0001;
static void Main(string[] args)
{
IntPtr hWnd = Process.GetCurrentProcess().MainWindowHandle;
SetWindowPos(hWnd,
new IntPtr(HWND_TOPMOST),
0, 0, 0, 0,
SWP_NOMOVE | SWP_NOSIZE);
Console.ReadKey();
}
}
</code></pre> |
3,368,942 | Grouped string aggregation / LISTAGG for SQL Server | <p>I'm sure this has been asked but I can't quite find the right search terms. </p>
<p>Given a schema like this:</p>
<pre><code>| CarMakeID | CarMake
------------------------
| 1 | SuperCars
| 2 | MehCars
| CarMakeID | CarModelID | CarModel
-----------------------------------------
| 1 | 1 | Zoom
| 2 | 1 | Wow
| 3 | 1 | Awesome
| 4 | 2 | Mediocrity
| 5 | 2 | YoureSettling
</code></pre>
<p>I want to produce a dataset like this:</p>
<pre><code>| CarMakeID | CarMake | CarModels
---------------------------------------------
| 1 | SuperCars | Zoom, Wow, Awesome
| 2 | MehCars | Mediocrity, YoureSettling
</code></pre>
<p>What do I do in place of 'AGG' for strings in SQL Server in the following style query?</p>
<pre><code>SELECT *,
(SELECT AGG(CarModel)
FROM CarModels model
WHERE model.CarMakeID = make.CarMakeID
GROUP BY make.CarMakeID) as CarMakes
FROM CarMakes make
</code></pre> | 3,368,974 | 2 | 0 | null | 2010-07-30 05:44:18.007 UTC | 7 | 2017-05-08 22:01:21.327 UTC | null | null | null | null | 364 | null | 1 | 18 | sql|sql-server|aggregate-functions | 48,993 | <p><a href="http://www.simple-talk.com/sql/t-sql-programming/concatenating-row-values-in-transact-sql/" rel="nofollow noreferrer">http://www.simple-talk.com/sql/t-sql-programming/concatenating-row-values-in-transact-sql/</a></p>
<blockquote>
<p>It is an interesting problem in Transact SQL, for which there are a number of solutions and considerable debate. How do you go about producing a summary result in which a distinguishing column from each row in each particular category is listed in a 'aggregate' column? A simple, and intuitive way of displaying data is surprisingly difficult to achieve. Anith Sen gives a summary of different ways, and offers words of caution over the one you choose...</p>
</blockquote> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.