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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4,890,289 | How do I configure MSBuild to use a saved publishProfile for WebDeploy? | <p>I have used Visual Studio to create a publish profile. It saved that information to MyProject.Publish.xml, located in the root of my project directory. </p>
<p>I would like the MSBuild task that gets executed on my CI server to use that file as its base settings. Ideally, if I could override properties via command line parameters, that would rock.</p>
<p>Is this possible? If so, what is the syntax?</p>
<p>For example, I'm looking for something like: </p>
<pre><code>MSBuild MyProject.csproj /P:UsePublishProfile=True /P:UserName=deployUser /P:Password=MyPassword
</code></pre> | 8,664,145 | 1 | 1 | null | 2011-02-03 18:42:30.037 UTC | 15 | 2016-02-25 15:40:34.867 UTC | 2016-02-25 15:40:34.867 UTC | null | 1,185 | null | 3,085 | null | 1 | 32 | visual-studio-2010|msbuild|msdeploy|webdeploy | 27,606 | <p>I'm sorry to tell you that the publish.xml file which VS2010 uses was not designed to be used in this way. In fact it was not even designed to be checked-in/shared with others.</p>
<p>The logic for reading/writing those files are strictly contained inside Visual Studio and not available through MSBuild. <strong>So there is no straight forward way of doing this today.</strong> You have to pass in the individual property names/values when you call msbuild.exe. You can see a similar question that I answered at <a href="https://stackoverflow.com/questions/4041836/team-build-publish-locally-using-msdeploy">Team Build: Publish locally using MSDeploy</a> for more info.</p>
<h3>Note for VS 11 Developer Preview</h3>
<p>Just so you know we have addressed this in the up coming version of Visual Studio. You can see if by downloading the VS 11 developer preview. Now all the profiles are saved into their own files (under the PublishProfiles in the Properties node in Solution Explorer). They are now designed to be checked in and shared with team members. These files are now MSBuild files and you can customize them if you wish. In order to publish from the command line just pass DeployOnBuild=true and set PublishProfile to the name of the profile. For example:</p>
<pre><code>msbuild.exe MyProject.csproj /p:DeployOnBuild=true;PublishProfile=MyProfile
</code></pre> |
49,612,412 | Kubenetes: Is it possible to hit multiple pods with a single request in Kubernetes cluster | <p>I want to clear cache in all the pods in my Kubernetes namespace. I want to send one request to the end-point which will then send a HTTP call to all the pods in the namespace to clear cache. Currently, I can hit only one pod using Kubernetes and I do not have control over which pod would get hit.</p>
<p>Even though the load-balancer is set to RR, continuously hitting the pods(n number of times, where n is the total number of pods) doesn't help as some other requests can creep in.</p>
<p>The same issue was discussed here, but I couldn't find a solution for the implementation:
<a href="https://github.com/kubernetes/kubernetes/issues/18755" rel="noreferrer">https://github.com/kubernetes/kubernetes/issues/18755</a></p>
<p>I'm trying to implement the clearing cache part using Hazelcast, wherein I will store all the cache and Hazelcast automatically takes care of the cache update.</p>
<p>If there is an alternative approach for this problem, or a way to configure kubernetes to hit all end-points for some specific requests, sharing here would be a great help.</p> | 50,797,128 | 5 | 2 | null | 2018-04-02 13:38:35.073 UTC | 21 | 2021-06-15 11:31:40.497 UTC | 2018-12-26 17:56:24.37 UTC | null | 2,381,544 | null | 2,381,544 | null | 1 | 49 | docker|kubernetes|kubernetes-ingress | 21,732 | <p>Provided you got kubectl in your pod and have access to the api-server, you can get all endpoint adressess and pass them to curl:</p>
<pre><code>kubectl get endpoints <servicename> \
-o jsonpath="{.subsets[*].addresses[*].ip}" | xargs curl
</code></pre>
<p><strong>Alternative without kubectl in pod:</strong></p>
<p>the recommended way to access the api server from a pod is by using kubectl proxy: <a href="https://kubernetes.io/docs/tasks/access-application-cluster/access-cluster/#accessing-the-api-from-a-pod" rel="noreferrer">https://kubernetes.io/docs/tasks/access-application-cluster/access-cluster/#accessing-the-api-from-a-pod</a> this would of course add at least the same overhead. alternatively you could directly call the REST api, you'd have to provide the token manually.</p>
<pre><code>APISERVER=$(kubectl config view --minify | grep server | cut -f 2- -d ":" | tr -d " ")
TOKEN=$(kubectl describe secret $(kubectl get secrets \
| grep ^default | cut -f1 -d ' ') | grep -E '^token' | cut -f2 -d':' | tr -d " ")
</code></pre>
<p>if you provide the APISERVER and TOKEN variables, you don't need kubectl in your pod, this way you only need curl to access the api server and "jq" to parse the json output:</p>
<pre><code>curl $APISERVER/api/v1/namespaces/default/endpoints --silent \
--header "Authorization: Bearer $TOKEN" --insecure \
| jq -rM ".items[].subsets[].addresses[].ip" | xargs curl
</code></pre>
<p><strong>UPDATE (final version)</strong></p>
<p>APISERVER usually can be set to kubernetes.default.svc and the token should be available at /var/run/secrets/kubernetes.io/serviceaccount/token in the pod, so no need to provide anything manually:</p>
<pre><code>TOKEN=$(cat /var/run/secrets/kubernetes.io/serviceaccount/token); \
curl https://kubernetes.default.svc/api/v1/namespaces/default/endpoints --silent \
--header "Authorization: Bearer $TOKEN" --insecure \
| jq -rM ".items[].subsets[].addresses[].ip" | xargs curl
</code></pre>
<p>jq is available here: <a href="https://stedolan.github.io/jq/download/" rel="noreferrer">https://stedolan.github.io/jq/download/</a> (< 4 MiB, but worth it for easily parsing JSON)</p> |
24,543,101 | Create Subpage in html | <p>Let's say I have a website <a href="http://www.example.com" rel="nofollow noreferrer">http://www.example.com</a></p>
<p>How do I create more subpages to this page i.e.</p>
<p><a href="http://www.example.com/faq" rel="nofollow noreferrer">www.example.com/faq</a></p>
<p><a href="http://www.example.com/contact" rel="nofollow noreferrer">www.example.com/contact</a></p>
<p>etc.</p> | 24,543,154 | 3 | 2 | null | 2014-07-03 00:18:48.557 UTC | 9 | 2022-01-07 21:56:53.583 UTC | 2022-01-07 21:56:53.583 UTC | null | 6,458,245 | null | 3,799,689 | null | 1 | 11 | html|css|web|file-structure | 56,110 | <p>You'll need to create new HTML files called faq.html and contact.html for this instance. Then you can link to these pages with <code><a></code> tags.</p>
<p><strong>EDIT</strong><br>
After half a decade, this answer has started getting upvotes, while not being as complete as the longer answer here. Here are some more details:</p>
<p>When you create extra HTML files and visit them, you'll see that the URL also contains the <code>.html</code>-part. This is something most people don't want. Provided you're using a webserver (either local or with a third-party host), there are multiple ways to get rid of the extension — one of which doesn't require server-side scripts and has been documented in <a href="https://stackoverflow.com/questions/24543101/#comment38008703_24543154">Stephen's comment below</a>.</p>
<p>What you do, is you add <em>folders</em> with the appropiate names (<code>faq</code>, <code>contact</code>, etc.). Once you have the folders set up, all you have to do is put index files inside them (<code>index.html</code>). Those index files should contain the content for their respective parent folders.</p>
<p>In essence, this is repeating the process with which the root location of a website is created, but for subfolders. You see, oftentimes you start out with a root folder called <code>public_html</code>, in which there is a single index file. Webservers <strong>automatically serve index files</strong>:</p>
<pre class="lang-none prettyprint-override"><code>public_html/index.html -> example.com/index.html
-> example.com/
public_html/faq/index.html -> example.com/faq/index.html
-> example.com/faq/ ←
</code></pre>
<p>As you can see, when done, you can visit</p>
<pre class="lang-none prettyprint-override"><code>www.example.com/faq
</code></pre>
<p>Instead of</p>
<pre class="lang-none prettyprint-override"><code>www.example.com/faq/index.html
</code></pre>
<p>Just like how you can visit</p>
<pre class="lang-none prettyprint-override"><code>www.example.com
</code></pre>
<p>Instead of</p>
<pre class="lang-none prettyprint-override"><code>www.example.com/index.html
</code></pre>
<p>If you feel like you want more fine-grained control, you're better off using server-side scripts. Whatever server language you use, you are in total control over where people navigate and what they get to see, no matter what the request looks like.</p>
<p>If you're using an Apache server, you can take a look at what an <code>.htaccess</code> file is, though writing and debugging them is arduous IMO.</p> |
21,536,599 | What does percolator mean/do in elasticsearch? | <p>Even though I read the documentation for Elasticsearch to understand what a percolator is. I still have difficulty understanding what it means and where it is used in simple terms. Can anyone provide me with more details?</p> | 21,547,816 | 3 | 1 | null | 2014-02-03 20:02:14.737 UTC | 13 | 2021-09-16 15:39:57.61 UTC | null | null | null | null | 313,245 | null | 1 | 82 | java|lucene|elasticsearch|search-engine | 18,615 | <p>What you usually do is index documents and get them back by querying. What the percolator allows you to do in a nutshell is index your queries and percolate documents against the indexed queries to know which queries they match. It's also called reversed search, as what you do is the opposite to what you are used to.</p>
<p>There are different usecases for the percolator, the first one being any platform that stores users interests in order to send the right content to the right users as soon as it comes in. </p>
<p>For instance a user subscribes to a specific topic, and as soon as a new article for that topic comes in, a notification will be sent to the interested users. You can express the users interests as an elasticsearch query, using the <a href="http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl.html" rel="noreferrer">query DSL</a>, and you can register it in elasticsearch as it was a document. Every time a new article is issued, without needing to index it, you can percolate it to know which users are interested in it. At this point in time you know who needs to receive a notification containing the article link (sending the notification is not done by elasticsearch though). An additional step would also be to index the content itself but that is not required.</p>
<p>Have a look at <a href="https://speakerdeck.com/javanna/whats-new-in-percolator" rel="noreferrer">this presentation</a> to see other couple of usecases and other features available in combination with the percolator starting from elasticsearch 1.0.</p> |
9,131,055 | Is there any way to align text in message box in vb or vba? | <p>Is there any way to align text into the center in <code>msgbox</code> in VB or VBA? Does VB have any functionality to do the same?</p> | 9,132,675 | 4 | 0 | null | 2012-02-03 15:24:26.017 UTC | 1 | 2022-02-23 14:53:34.617 UTC | 2012-02-03 19:38:57.373 UTC | null | 3,043 | null | 404,348 | null | 1 | 6 | vba|vb6|vbscript|messagebox | 39,833 | <p>No. The <code>MsgBox()</code> function is simply a wrapper for the Windows <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms645505%28v=vs.85%29.aspx" rel="noreferrer"><code>MessageBox()</code></a> function and as such has no stylistic control over the dialog beyond the icon.</p>
<p>If you want to change it any further than this, you will need to create your own window and show that instead.</p>
<p>On Windows Vista+ you can use <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/bb787471%28v=vs.85%29.aspx" rel="noreferrer">TaskDialogs</a> that allow a lot more control.</p> |
9,562,218 | C: Multiple scanf's, when I enter in a value for one scanf it skips the second scanf | <p>I have this block of code (functions omitted as the logic is part of a homework assignment): </p>
<pre><code>#include <stdio.h>
int main()
{
char c = 'q';
int size;
printf("\nShape (l/s/t):");
scanf("%c",&c);
printf("Length:");
scanf("%d",&size);
while(c!='q')
{
switch(c)
{
case 'l': line(size); break;
case 's': square(size); break;
case 't': triangle(size); break;
}
printf("\nShape (l/s/t):");
scanf("%c",&c);
printf("\nLength:");
scanf("%d",&size);
}
return 0;
}
</code></pre>
<p>The first two Scanf's work great, no problem once we get into the while loop, I have a problem where, when you are supposed to be prompted to enter a new shape char, it instead jumps down to the <code>printf</code> of Length and waits to take input from there for a char, then later a decimal on the next iteration of the loop. </p>
<p>Preloop iteration: </p>
<p>Scanf: Shape. Works Great<br>
Scanf: Length. No Problem </p>
<p>Loop 1. </p>
<p>Scanf: Shape. Skips over this<br>
Scanf: length. Problem, this scanf maps to the shape char.</p>
<p>Loop 2<br>
Scanf: Shape. Skips over this<br>
Scanf: length. Problem, this scanf maps to the size int now. </p>
<p>Why is it doing this? </p> | 9,562,355 | 7 | 0 | null | 2012-03-05 05:54:24.3 UTC | 21 | 2018-03-25 05:18:16.687 UTC | 2014-10-03 14:40:29.203 UTC | null | 15,168 | null | 494,901 | null | 1 | 24 | c|scanf | 112,634 | <p><code>scanf("%c")</code> reads the newline character from the <kbd>ENTER</kbd> key.</p>
<p>When you type let's say <code>15</code>, you type a <code>1</code>, a <code>5</code> and then press the <kbd>ENTER</kbd> key. So there are now three characters in the input buffer. <code>scanf("%d")</code> reads the <code>1</code> and the <code>5</code>, interpreting them as the number <code>15</code>, but the newline character is still in the input buffer. The <code>scanf("%c")</code> will immediately read this newline character, and the program will then go on to the next <code>scanf("%d")</code>, and wait for you to enter a number.</p>
<p>The usual advice is to read entire lines of input with <code>fgets</code>, and interpret the content of each line in a separate step. A simpler solution to your immediate problem is to add a <code>getchar()</code> after each <code>scanf("%d")</code>.</p> |
9,183,368 | Symfony2 $user->setPassword() updates password as plain text [DataFixtures + FOSUserBundle] | <p>I'm trying to pre-populate a database with some User objects, but when I call <code>$user->setPassword('some-password');</code> and then save the user object, the string 'some-password' is stored directly in the database, instead of the hashed+salted password.</p>
<p>My DataFixture class:</p>
<pre><code>// Acme/SecurityBundle/DataFixtures/ORM/LoadUserData.php
<?php
namespace Acme\SecurityBundle\DataFixtures\ORM;
use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Acme\SecurityBundle\Entity\User;
class LoadUserData implements FixtureInterface
{
public function load(ObjectManager $manager)
{
$userAdmin = new User();
$userAdmin->setUsername('System');
$userAdmin->setEmail('[email protected]');
$userAdmin->setPassword('test');
$manager->persist($userAdmin);
$manager->flush();
}
}
</code></pre>
<p>And the relevant database output:</p>
<pre><code>id username email salt password
1 System [email protected] 3f92m2tqa2kg8cookg84s4sow80880g test
</code></pre> | 9,200,996 | 7 | 0 | null | 2012-02-07 20:29:12.537 UTC | 14 | 2016-12-22 03:58:38.62 UTC | 2012-02-07 22:29:29.42 UTC | null | 1,089,026 | null | 1,089,026 | null | 1 | 44 | php|doctrine|symfony|fosuserbundle | 39,094 | <p>Since you are using FOSUserBundle, you can use <code>UserManager</code> to do this. I would use this code (assuming you have <code>$this->container</code> set):</p>
<pre><code>public function load(ObjectManager $manager)
{
$userManager = $this->container->get('fos_user.user_manager');
$userAdmin = $userManager->createUser();
$userAdmin->setUsername('System');
$userAdmin->setEmail('[email protected]');
$userAdmin->setPlainPassword('test');
$userAdmin->setEnabled(true);
$userManager->updateUser($userAdmin, true);
}
</code></pre> |
9,471,380 | Create CSR using existing private key | <p>What I am trying to do is, create a CSR and with a private key that is password protected (the key). </p>
<p>In OpenSSL I can create a private key with a password like so: </p>
<pre><code>openssl genrsa -des3 -out privkey.pem 2048
</code></pre>
<p>Is there some way I can use the key I just created and generate a CSR using the key? </p>
<p>If not is there some way I can generate a CSR along with a PASSWORD PROTECTED private key? </p> | 9,471,775 | 1 | 0 | null | 2012-02-27 19:55:11.18 UTC | 12 | 2021-03-18 11:15:56.613 UTC | 2015-05-04 22:58:10.37 UTC | null | 608,639 | null | 1,181,079 | null | 1 | 49 | ssl|openssl|certificate | 93,788 | <p>This is the second example from <a href="https://www.openssl.org/docs/man1.1.1/man1/openssl-req.html#EXAMPLES" rel="noreferrer">the documentation of OpenSSL req</a>:</p>
<blockquote>
<p>Create a private key and then generate a certificate request from it:</p>
<pre><code>openssl genrsa -out key.pem 2048
openssl req -new -key key.pem -out req.pem
</code></pre>
</blockquote>
<p>Note that, if you do this directly with <code>req</code> (see 3rd example), if you don't use the <code>-nodes</code> option, your private key will also be encrypted:</p>
<blockquote>
<pre><code>openssl req -newkey rsa:2048 -keyout key.pem -out req.pem
</code></pre>
</blockquote>
<p>(Despite what the documentation says, it's not exactly the same as the second example, since it doesn't use <code>-des3</code>, but you would have done so anyway.)</p> |
9,114,503 | JSON for List of int | <p>I have a class</p>
<pre><code>public class ItemList
{
public long Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public List<int> ItemModList { get; set; }
}
</code></pre>
<p>how should i give the input JSON for list of int as it does not have a key to match its value</p>
<p>JSON</p>
<pre><code>{
"Id": "610",
"Name": "15",
"Description": "1.99",
"ItemModList": []
}
</code></pre>
<p>what should I write in the ItemModList</p> | 9,114,555 | 2 | 0 | null | 2012-02-02 14:59:08.67 UTC | 9 | 2022-09-13 08:11:09.197 UTC | null | null | null | null | 725,208 | null | 1 | 72 | json | 330,095 | <p>Assuming your ints are 0, 375, 668,5 and 6:</p>
<pre><code>{
"Id": "610",
"Name": "15",
"Description": "1.99",
"ItemModList": [
0,
375,
668,
5,
6
]
}
</code></pre>
<p>I suggest that you change "Id": "610" to "Id": 610 since it is a integer/long and not a string. You can read more about the JSON format and examples here <a href="http://json.org/" rel="noreferrer">http://json.org/</a></p> |
9,168,518 | How can I determine if a String is non-null and not only whitespace in Groovy? | <p>Groovy adds the <code>isAllWhitespace()</code> method to Strings, which is great, but there doesn't seem to be a <em>good</em> way of determining if a String has something other than <em>just</em> white space in it.</p>
<p>The best I've been able to come up with is:</p>
<pre><code>myString && !myString.allWhitespace
</code></pre>
<p>But that seems too verbose. This seems like such a common thing for validation that there <em>must</em> be a simpler way to determine this.</p> | 9,168,744 | 4 | 0 | null | 2012-02-06 22:50:11.033 UTC | 11 | 2022-04-29 11:58:29.08 UTC | 2013-12-11 15:45:56.35 UTC | null | 20,770 | null | 20,770 | null | 1 | 167 | string|groovy|whitespace | 240,554 | <p>Another option is</p>
<pre><code>if (myString?.trim()) {
...
}
</code></pre>
<p>(using <a href="https://groovy-lang.org/semantics.html#_strings" rel="noreferrer">Groovy Truth for Strings</a>)</p> |
30,240,181 | Can I apply animations to margins? | <p>I'm trying to animate in CSS3 margins, which <a href="http://css3.bradshawenterprises.com/transitions/" rel="noreferrer">this site</a> seems to say you can, but I can't get working. </p>
<p>I actually have 3 animations. 1 for a simple initial <code>fadeIn</code> on initial load, then the 2 others for the <code>margin</code> animation on click. I've also just tried <code>margin</code> instead of the top and bottom but still no sign of it working. </p>
<p>Click on a section to see animation toggle.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(".section").click(function() {
$(this).toggleClass("open");
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{
background: #f1f1f1;
}
.section{
display: block;
background: #fff;
border-bottom: 1px solid #f1f1f1;
animation: fadeIn .5s ease, margin-top .5s ease, margin-bottom .5s ease;
}
.section.open {
margin: 20px 0;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<div class="wrapper">
<div class="section">Some content</div>
<div class="section">Some content</div>
<div class="section">Some content</div>
<div class="section">Some content</div>
<div class="section">Some content</div>
<div class="section">Some content</div>
<div class="section">Some content</div>
</div></code></pre>
</div>
</div>
</p>
<p>Here is a JSFiddle: <a href="http://jsfiddle.net/ybh0thp9/3/" rel="noreferrer">http://jsfiddle.net/ybh0thp9/3/</a> </p> | 30,240,325 | 3 | 3 | null | 2015-05-14 14:41:00.203 UTC | 1 | 2021-04-07 18:00:55.377 UTC | 2019-06-24 21:11:36.757 UTC | null | 2,756,409 | null | 517,477 | null | 1 | 32 | html|css|css-animations | 74,493 | <p>You don't need keyframes for this: <a href="http://jsfiddle.net/BramVanroy/ybh0thp9/7/" rel="noreferrer">http://jsfiddle.net/BramVanroy/ybh0thp9/7/</a></p>
<pre><code>transition: margin 700ms;
</code></pre>
<p>You need to add the transition property to the base element that you wish to animate.</p>
<p>You also mentioned that you wanted opacity change, but I don't see how that's possible considering you only have a single element without children. I mean: you can't click on the element if it's hidden.</p>
<p>What you can do, though, is add opacity to the whole thing: <a href="http://jsfiddle.net/BramVanroy/ybh0thp9/9/" rel="noreferrer">http://jsfiddle.net/BramVanroy/ybh0thp9/9/</a></p>
<p>Or even prettier, with a transformation:</p>
<p><a href="http://jsfiddle.net/BramVanroy/ybh0thp9/10/" rel="noreferrer">http://jsfiddle.net/BramVanroy/ybh0thp9/10/</a></p>
<pre><code>.section {
margin: 0;
opacity: 0.7;
transform: scale(0.85);
transition: all 700ms;
}
.section.open {
margin: 20px 0;
opacity: 1;
transform: scale(1);
}
</code></pre>
<hr>
<p>Per comment, you want to fade in the elements on page load. We can do that by adding a class <code>init</code>.</p>
<p><a href="http://jsfiddle.net/BramVanroy/ybh0thp9/12/" rel="noreferrer">http://jsfiddle.net/BramVanroy/ybh0thp9/12/</a></p>
<pre><code>$(".section").addClass("init"); // JS
.section.init {opacity: 1;} // CSS
</code></pre>
<hr>
<p>With keyframes: <a href="http://jsfiddle.net/BramVanroy/ybh0thp9/14/" rel="noreferrer">http://jsfiddle.net/BramVanroy/ybh0thp9/14/</a></p>
<pre><code>@-webkit-keyframes fadeIn { from {opacity: 0; } to { opacity: 1; } }
@-moz-keyframes fadeIn { from {opacity: 0; } to { opacity: 1; } }
@keyframes fadeIn { from {opacity: 0; } to { opacity: 1; } }
-webkit-animation: fadeIn 1.5s ease;
-moz-animation: fadeIn 1.5s ease;
animation: fadeIn 1.5s ease;
</code></pre> |
10,341,685 | HTML/Javascript Access EXIF data before file upload | <p>I am trying to extract <strong>EXIF</strong> data from a image(jpeg) which has been dragged into the browser or has been selected via a html file input element.</p>
<p>I managed to preview the image within the browser using <code>FileReader and FileReader.readAsDataURL</code>
as described <a href="https://developer.mozilla.org/en/DOM/FileReader" rel="nofollow noreferrer">here</a>.</p>
<p>and I found a <a href="http://blog.nihilogic.dk/2008/05/reading-exif-data-with-javascript.html" rel="nofollow noreferrer">EXIF library</a> which allows to extract the EXIF data of an image via javascript. But for me it only works if I use it with normal <code>img</code> tags which load their content over a URL.</p>
<p>I also found <a href="https://stackoverflow.com/questions/5784459/javascript-can-i-read-exif-data-from-a-file-upload-input">this question</a> on StackOverflow where the accepted answer states that it is just not possible. </p>
<p>But I am pretty sure that it can be realized because <a href="http://500px.com" rel="nofollow noreferrer">500px.com</a> extracts the EXIF data immediately after a file is added for upload and before the upload has been finished. </p>
<p>Some ideas how it should be possible to extract the EXIF data from the base64 encoded image I get from the FileReader?</p> | 10,346,298 | 3 | 1 | null | 2012-04-26 21:28:10.617 UTC | 9 | 2017-04-26 15:14:12.683 UTC | 2017-04-26 15:14:12.683 UTC | null | 1,033,581 | null | 1,000,569 | null | 1 | 15 | javascript|jquery|html|file-upload|exif | 26,394 | <p>I finally found a client side solution for the problem:</p>
<ol>
<li>Read the file using the <code>FileReader</code> and the method <code>.readAsBinaryString</code></li>
<li>Then wrap that binary string into a BinaryFile object which is already included in the <a href="https://github.com/exif-js/exif-js" rel="nofollow">EXIF Library</a></li>
<li>Finally call <code>EXIF.readFromBinaryFile(binaryFileObject);</code></li>
</ol>
<p>and its done :)</p> |
7,174,635 | Does protobuf-net have built-in compression for serialization? | <p>I was doing some comparison between <code>BinaryFormatter</code> and protobuf-net serializer and was quite pleased with what I <a href="http://theburningmonk.com/2011/08/performance-test-binaryformatter-vs-protobuf-net/" rel="noreferrer">found</a>, but what was strange is that protobuf-net managed to serialize the objects into a smaller byte array than what I would get if I just wrote the value of every property into an array of bytes without any metadata.</p>
<p>I know protobuf-net supports string interning if you set <code>AsReference</code> to <code>true</code>, but I'm not doing that in this case, so does protobuf-net provide some compression by default?</p>
<p>Here's some code you can run to see for yourself:</p>
<pre class="lang-cs prettyprint-override"><code>var simpleObject = new SimpleObject
{
Id = 10,
Name = "Yan",
Address = "Planet Earth",
Scores = Enumerable.Range(1, 10).ToList()
};
using (var memStream = new MemoryStream())
{
var binaryWriter = new BinaryWriter(memStream);
// 4 bytes for int
binaryWriter.Write(simpleObject.Id);
// 3 bytes + 1 more for string termination
binaryWriter.Write(simpleObject.Name);
// 12 bytes + 1 more for string termination
binaryWriter.Write(simpleObject.Address);
// 40 bytes for 10 ints
simpleObject.Scores.ForEach(binaryWriter.Write);
// 61 bytes, which is what I expect
Console.WriteLine("BinaryWriter wrote [{0}] bytes",
memStream.ToArray().Count());
}
using (var memStream = new MemoryStream())
{
ProtoBuf.Serializer.Serialize(memStream, simpleObject);
// 41 bytes!
Console.WriteLine("Protobuf serialize wrote [{0}] bytes",
memStream.ToArray().Count());
}
</code></pre>
<p>EDIT: forgot to add, the <code>SimpleObject</code> class looks like this:</p>
<pre class="lang-cs prettyprint-override"><code>[Serializable]
[DataContract]
public class SimpleObject
{
[DataMember(Order = 1)]
public int Id { get; set; }
[DataMember(Order = 2)]
public string Name { get; set; }
[DataMember(Order = 3)]
public string Address { get; set; }
[DataMember(Order = 4)]
public List<int> Scores { get; set; }
}
</code></pre> | 7,181,908 | 2 | 0 | null | 2011-08-24 11:22:43.53 UTC | 7 | 2020-09-12 00:12:35.73 UTC | 2019-07-29 11:10:10.91 UTC | null | 247,623 | null | 55,074 | null | 1 | 30 | serialization|protobuf-net|binary-serialization | 30,684 | <p>No it does not; there is no "compression" as such specified in the protobuf spec; however, it does (by default) use "varint encoding" - a variable-length encoding for integer data that means small values use less space; so 0-127 take 1 byte plus the header. Note that varint <em>by itself</em> goes pretty loopy for negative numbers, so "zigzag" encoding is also supported which allows small <em>magnitude</em> numbers to be small (basically, it interleaves positive and negative pairs).</p>
<p>Actually, in your case for <code>Scores</code> you should also look at "packed" encoding, which requires either <code>[ProtoMember(4, IsPacked = true)]</code> or the equivalent via <code>TypeModel</code> in v2 (v2 supports either approach). This avoids the overhead of a header per value, by writing a single header and the <em>combined</em> length. "Packed" can be used with varint/zigzag. There are also fixed-length encodings for scenarios where you <em>know</em> the values are likely large and unpredictable.</p>
<p>Note also: but if your data has lots of text you may benefit from additionally running it through gzip or deflate; if it <em>doesn't</em>, then both gzip and deflate could cause it to get bigger.</p>
<p>An overview of the wire format <a href="https://developers.google.com/protocol-buffers/docs/encoding" rel="noreferrer">is here</a>; it isn't very tricky to understand, and may help you plan how best to further optimize.</p> |
19,198,029 | get present year value to string | <p>I need to get the present year value in string so I did:</p>
<pre><code>Calendar now = Calendar.getInstance();
DateFormat date = new SimpleDateFormat("yyyy");
String year = date.format(now);
</code></pre>
<p>It works on ubuntu but it's not working on windows 7. </p>
<p>Do you know why?
Is there a safer way to do that?</p>
<p>Thanks</p> | 19,198,045 | 10 | 1 | null | 2013-10-05 12:53:02.04 UTC | 0 | 2017-08-17 06:40:46.74 UTC | null | null | null | null | 1,535,655 | null | 1 | 7 | java|calendar|operating-system|date-format | 60,319 | <p>You can simple get the year from <code>Calendar</code> instance using <a href="http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#get%28int%29"><code>Calendar#get(int field)</code></a> method:</p>
<pre><code>Calendar now = Calendar.getInstance();
int year = now.get(Calendar.YEAR);
String yearInString = String.valueOf(year);
</code></pre> |
37,644,199 | Pandas Convert Timestamp Column to Datetime | <p>Given the following data frame and necessary wrangling:</p>
<pre><code>import pandas as pd
df=pd.DataFrame({'A':['a','b','c'],
'dates':['2015-08-31 00:00:00','2015-08-24 00:00:00','2015-08-25 00:00:00']})
df.dates=df.dates.astype(str)
df['dates'] = pd.to_datetime(df.dates.str.split(',\s*').str[0])
set(df['dates'])
</code></pre>
<p>I end up with:</p>
<pre><code>{Timestamp('2015-08-24 00:00:00'),
Timestamp('2015-08-25 00:00:00'),
Timestamp('2015-08-31 00:00:00')}
</code></pre>
<p>I need to convert the time stamps back to datetime (really, just date) format.</p>
<p>I've tried this based on the answer to <a href="https://stackoverflow.com/questions/22825349/converting-between-datetime-and-pandas-timestamp-objects">this post</a>:</p>
<pre><code>df['dates'].to_pydatetime()
</code></pre>
<p>But that returns:</p>
<pre><code>AttributeError: 'Series' object has no attribute 'to_pydatetime'
</code></pre>
<p>In my real data, the data type is: <code><M8[ns]</code></p> | 37,646,554 | 6 | 2 | null | 2016-06-05 16:28:54.743 UTC | 1 | 2022-08-07 16:56:07.15 UTC | 2019-08-17 16:34:02.417 UTC | null | 1,839,439 | null | 4,392,566 | null | 1 | 12 | python-3.x|datetime|timestamp | 39,536 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.date.html" rel="noreferrer"><code>dt.date</code></a> to return a <code>datetime.date</code> object:</p>
<pre><code>In [3]:
set(df['dates'].dt.date)
Out[3]:
{datetime.date(2015, 8, 24),
datetime.date(2015, 8, 25),
datetime.date(2015, 8, 31)}
</code></pre> |
21,104,476 | What does the "r" in pythons re.compile(r' pattern flags') mean? | <p>I am reading through <a href="http://docs.python.org/2/library/re.html">http://docs.python.org/2/library/re.html</a>. According to this the "r" in pythons re.compile(<strong>r</strong>' pattern flags') refers the raw string notation :</p>
<blockquote>
<p>The solution is to use Python’s raw string notation for regular
expression patterns; backslashes are not handled in any special way in
a string literal prefixed with 'r'. So r"\n" is a two-character string
containing '\' and 'n', while "\n" is a one-character string
containing a newline. Usually patterns will be expressed in Python
code using this raw string notation.</p>
</blockquote>
<p>Would it be fair to say then that:</p>
<p>re.compile(<strong>r</strong> pattern) means that "pattern" is a regex while, re.compile(pattern) means that "pattern" is an exact match? </p> | 21,104,539 | 3 | 2 | null | 2014-01-14 01:18:28.503 UTC | 22 | 2020-08-17 05:37:00.673 UTC | null | null | null | null | 1,592,380 | null | 1 | 34 | python|regex | 40,049 | <p>As <code>@PauloBu</code> stated, the <code>r</code> string prefix is not specifically related to regex's, but to strings generally in Python.</p>
<p>Normal strings use the backslash character as an escape character for special characters (like newlines):</p>
<pre><code>>>> print('this is \n a test')
this is
a test
</code></pre>
<p>The <code>r</code> prefix tells the interpreter not to do this:</p>
<pre><code>>>> print(r'this is \n a test')
this is \n a test
>>>
</code></pre>
<p>This is important in regular expressions, as you need the backslash to make it to the <code>re</code> module intact - in particular, <code>\b</code> matches empty string specifically at the start and end of a word. <code>re</code> expects the string <code>\b</code>, however normal string interpretation <code>'\b'</code> is converted to the ASCII backspace character, so you need to either explicitly escape the backslash (<code>'\\b'</code>), or tell python it is a raw string (<code>r'\b'</code>).</p>
<pre><code>>>> import re
>>> re.findall('\b', 'test') # the backslash gets consumed by the python string interpreter
[]
>>> re.findall('\\b', 'test') # backslash is explicitly escaped and is passed through to re module
['', '']
>>> re.findall(r'\b', 'test') # often this syntax is easier
['', '']
</code></pre> |
18,515,647 | Strange Bitmap using 1 Mb of Heap | <p>Out of curiosity, I just recently tested my Android App for Memory Leaks, using the <strong>Eclipse Memory Analyzer.</strong></p>
<p>I came across a strange Bitmap with the size of <strong>512 x 512 pixels using up about 1 Megabyte</strong> of my devices heap memory.</p>
<p><img src="https://i.stack.imgur.com/WSRNa.png" alt="enter image description here"></p>
<p>I checked my drawables folder and could not find a bitmap of that size (512 x 512).</p>
<p>I started googling and came across this question, where a user explains how to get the actual Image behind a "memory leak" reference in the Memory Analyzer: </p>
<p><strong><a href="https://stackoverflow.com/questions/12709603/mat-eclipse-memory-analyzer-how-to-view-bitmaps-from-memory-dump/12709604#12709604">MAT (Eclipse Memory Analyzer) - how to view bitmaps from memory dump</a></strong></p>
<p>I followed the tutorial and with the help of GIMP, I extracted the following Image:</p>
<p><img src="https://i.stack.imgur.com/Ea6uI.png" alt="enter image description here"></p>
<p>So my questions are:</p>
<ul>
<li>What is that?</li>
<li>What is it doing in my applications heap?</li>
<li>How do I get rid of it?</li>
<li>Does anyone else have the same bitmap in his heap?</li>
</ul>
<p>Notes:</p>
<ul>
<li>In my drawables folder is no Bitmap looking like that</li>
<li>The largest Bitmap my app uses is 140 x 140 pixels</li>
<li>I have a feeling that this Bitmap somehow comes from the system</li>
<li>The Bitmap is in heap right after app start - without any user interaction</li>
<li>I am debugging on a HTC One S, Android 4.1 Cyanogen Mod (Screen 540 x 960)</li>
<li>I am not using external Libraries</li>
</ul>
<p><strong>Update</strong>: </p>
<p>With the help of <a href="https://stackoverflow.com/users/690952/selvin">Selvin's</a> suggestion and my personal felling that this could be a System-issue, I tested two other apps of mine.</p>
<blockquote>
<p><strong>Both of the apps I tested also showed the same Bitmap in the Memory Analyzer with exactly the same amount of bytes consumed:</strong></p>
</blockquote>
<p><img src="https://i.stack.imgur.com/Aazck.png" alt="enter image description here"></p>
<p>Furthermore, I was able to find out that:</p>
<blockquote>
<p><strong>The source of the Bitmap is always associated with the LAUNCHER Activity of the app.</strong></p>
</blockquote>
<p>So what to do about that?
Is there a way to get rid of it?</p>
<p>Since I do memory-intensive operations in my app, I'd like to have as much heap available as possible.</p> | 18,643,245 | 1 | 5 | null | 2013-08-29 15:55:20.407 UTC | 8 | 2021-10-15 22:19:21.407 UTC | 2021-10-15 22:19:21.407 UTC | null | 5,459,839 | null | 1,590,502 | null | 1 | 14 | android|memory-management|bitmap|heap-memory|eclipse-memory-analyzer | 1,527 | <p>The default window background used by Android is a 512x512 image (the blueish-dark gradient you see with the dark theme or the gray-white gradient with the light theme). On capable devices, this image is replaced with a procedural gradient as of Android 4.2.</p>
<p>Note that this bitmap is normally loaded in Zygote and shared by all the apps. It might show up in heap dumps if the dump doesn't exclude Zygote-allocated objects.</p>
<p>Here are the two 512x512 backgrounds I'm talking about if you're interested:</p>
<p><a href="https://github.com/android/platform_frameworks_base/blob/jb-mr0-release/core/res/res/drawable-nodpi/background_holo_dark.png" rel="noreferrer">https://github.com/android/platform_frameworks_base/blob/jb-mr0-release/core/res/res/drawable-nodpi/background_holo_dark.png</a></p>
<p><a href="https://github.com/android/platform_frameworks_base/blob/jb-mr0-release/core/res/res/drawable-nodpi/background_holo_light.png" rel="noreferrer">https://github.com/android/platform_frameworks_base/blob/jb-mr0-release/core/res/res/drawable-nodpi/background_holo_light.png</a></p> |
8,767,727 | transcode and segment with ffmpeg | <p>It appears that ffmpeg now has a segmenter in it, or at least there is a command line option</p>
<p>-f segment </p>
<p>in the documentation. </p>
<p>Does this mean I can use ffmpeg to realtime-transcode a video into h.264 and deliver segmented IOS compatible .m3u8 streams using ffmpeg alone? if so, what would a command to transcode an arbitrary video file to a segmented h.264 aac 640 x 480 stream ios compatible stream?</p> | 10,047,372 | 2 | 1 | null | 2012-01-07 05:53:44.827 UTC | 27 | 2013-05-22 20:44:21.727 UTC | null | null | null | null | 820,085 | null | 1 | 27 | ffmpeg|http-live-streaming | 55,892 | <p>Absolutely - you can use <strong>-f segment</strong> to chop video into pieces and serve it to iOS devices. ffmpeg will create segment files .ts and you can serve those with any web server.</p>
<p><strong>Working example</strong> (with disabled sound) - ffmpeg version N-39494-g41a097a:</p>
<pre><code>./ffmpeg -v 9 -loglevel 99 -re -i sourcefile.avi -an \
-c:v libx264 -b:v 128k -vpre ipod320 \
-flags -global_header -map 0 -f segment -segment_time 4 \
-segment_list test.m3u8 -segment_format mpegts stream%05d.ts
</code></pre>
<p><strong>Tips:</strong></p>
<ul>
<li>make sure you compile ffmpeg from most recent <a href="/questions/tagged/git" class="post-tag" title="show questions tagged 'git'" rel="tag">git</a> repository</li>
<li>compile with libx264 codec</li>
<li>-map 0 is needed</li>
</ul>
<p>How I compiled FFMPEG - with extra rtmp support to get feeds from <a href="/questions/tagged/flash-media-server" class="post-tag" title="show questions tagged 'flash-media-server'" rel="tag">flash-media-server</a></p>
<pre><code>export PKG_CONFIG_PATH="/usr/lib/pkgconfig/:../rtmpdump-2.3/librtmp"
./configure --enable-librtmp --enable-libx264 \
--libdir='../x264/:/usr/local/lib:../rtmpdump-2.3' \
--enable-gpl --enable-pthreads --enable-libvpx \
--disable-ffplay --disable-ffserver --disable-shared --enable-debug
</code></pre> |
965,601 | How to detect left click anywhere on the document using jQuery? | <p>I have this right now:</p>
<pre><code>$(document).click(function(e) { alert('clicked'); });
</code></pre>
<p>In Firefox, this event is firing when I left-click OR right-click. I only want it to fire when I left-click.</p>
<p>Does attaching a click handler to the document work differently than attaching it to other elements? For other elements, it only seems to fire on left clicks.</p>
<p>Is there a way to detect <em>only</em> left clicks besides looking at e.button, which is browser-dependent?</p>
<p>Thanks</p> | 965,646 | 4 | 0 | null | 2009-06-08 15:49:26.16 UTC | null | 2014-02-11 22:00:43.743 UTC | null | null | null | null | 2,749 | null | 1 | 14 | javascript|jquery | 50,840 | <p>Try</p>
<pre><code>$(document).click(function(e) {
// Check for left button
if (e.button == 0) {
alert('clicked');
}
});
</code></pre>
<p>However, there seems to be some confusion as to whether IE returns 1 or 0 as left click, you may need to test this :)</p>
<p>Further reading here: <a href="http://www.barneyb.com/barneyblog/2009/04/09/jquery-live-click-gotcha/" rel="noreferrer">jQuery Gotcha</a></p>
<p><strong>EDIT</strong>: missed the bit where you asked not to use <code>e.button</code>. Sorry!</p>
<p>However, the example <a href="http://barneyb.com/r/jquery_live_button.cfm" rel="noreferrer">here</a> returns the same ID regardless of looking at it in FF or IE, and uses e.button. could possibly have updated the jQuery framework? The other answer is that older versions of IE return a different value, which would be a pain. Unfortunately I only have IE 7/8 here to test against.</p> |
1,535 | Reducing duplicate error handling code in C#? | <p>I've never been completely happy with the way exception handling works, there's a lot exceptions and try/catch brings to the table (stack unwinding, etc.), but it seems to break a lot of the OO model in the process.</p>
<p>Anyway, here's the problem:</p>
<p>Let's say you have some class which wraps or includes networked file IO operations (e.g. reading and writing to some file at some particular UNC path somewhere). For various reasons you don't want those IO operations to fail, so if you detect that they fail you retry them and you keep retrying them until they succeed or you reach a timeout. I already have a convenient RetryTimer class which I can instantiate and use to sleep the current thread between retries and determine when the timeout period has elapsed, etc.</p>
<p>The problem is that you have a bunch of IO operations in several methods of this class, and you need to wrap each of them in try-catch / retry logic.</p>
<p>Here's an example code snippet:</p>
<pre><code>RetryTimer fileIORetryTimer = new RetryTimer(TimeSpan.FromHours(10));
bool success = false;
while (!success)
{
try
{
// do some file IO which may succeed or fail
success = true;
}
catch (IOException e)
{
if (fileIORetryTimer.HasExceededRetryTimeout)
{
throw e;
}
fileIORetryTimer.SleepUntilNextRetry();
}
}
</code></pre>
<p>So, how do you avoid duplicating most of this code for every file IO operation throughout the class? My solution was to use anonymous delegate blocks and a single method in the class which executed the delegate block passed to it. This allowed me to do things like this in other methods:</p>
<pre><code>this.RetryFileIO( delegate()
{
// some code block
} );
</code></pre>
<p>I like this somewhat, but it leaves a lot to be desired. I'd like to hear how other people would solve this sort of problem.</p> | 2,047 | 4 | 2 | null | 2008-08-04 19:21:48.53 UTC | 4 | 2020-12-16 01:54:30.937 UTC | null | null | null | null | 332 | null | 1 | 40 | c#|exception|error-handling | 2,460 | <p>This looks like an excellent opportunity to have a look at Aspect Oriented Programming. Here is a good article on <a href="https://docs.microsoft.com/en-us/archive/blogs/simonince/aspect-oriented-interception" rel="nofollow noreferrer">AOP in .NET</a>. The general idea is that you'd extract the cross-functional concern (i.e. Retry for x hours) into a separate class and then you'd annotate any methods that need to modify their behaviour in that way. Here's how it might look (with a nice extension method on Int32)</p>
<pre><code>[RetryFor( 10.Hours() )]
public void DeleteArchive()
{
//.. code to just delete the archive
}
</code></pre> |
178,712 | How to find out if a column exists in a DataRow? | <p>I am reading an XML file into a DataSet and need to get the data out of the DataSet. Since it is a user-editable config file the fields may or may not be there. To handle missing fields well I'd like to make sure each column in the DataRow exists and is not DBNull. </p>
<p>I already check for DBNull but I don't know how to make sure the column exists without having it throw an exception or using a function that loops over all the column names. What is the best method to do this?</p> | 178,766 | 4 | 0 | null | 2008-10-07 14:30:09.427 UTC | 8 | 2022-07-08 21:40:27.15 UTC | 2022-07-08 21:40:27.15 UTC | null | 3,345,644 | null | 21,186 | null | 1 | 61 | .net|vb.net|ado.net|dataset|datarow | 111,527 | <p>DataRow's are nice in the way that they have their underlying table linked to them. With the underlying table you can verify that a specific row has a specific column in it.</p>
<pre><code> If DataRow.Table.Columns.Contains("column") Then
MsgBox("YAY")
End If
</code></pre> |
54,433,183 | TypeScript interface signature for the onClick event in ReactJS | <p>The official <a href="https://reactjs.org/tutorial/tutorial.html" rel="noreferrer">reactjs.org</a> website contains an excellent introductory tutorial.</p>
<p>The tutorial snippets are written in JavaScript and I am trying to convert these to TypeScript.</p>
<p>I have managed to get the code working but have a question about using interfaces.</p>
<p>What should the correct "function signature" be for the onClick callback.</p>
<p><strong><em>Is there a way to replace the 'any' keyword in the IProps_Square interface with an explicit function signature ?</em></strong></p>
<p>Any help or suggestions would be really appreciated, many thanks Russell</p>
<p><strong>index.html</strong></p>
<pre><code><!DOCTYPE html>
<html lang="en">
<body>
<div id="reactjs-tutorial"></div>
</body>
</html>
</code></pre>
<p><strong>index.tsx</strong></p>
<pre><code>import * as React from 'react';
import * as ReactDOM from 'react-dom';
interface IProps_Square {
message: string,
onClick: any,
}
class Square extends React.Component < IProps_Square > {
render() {
return (
<button onClick={this.props.onClick}>
{this.props.message}
</button>
);
}
}
class Game extends React.Component {
render() {
return (
<Square
message = { 'click this' }
onClick = { () => alert('hello') }
/>
);
}
}
ReactDOM.render(
<Game />,
document.getElementById('reactjs-tutorial')
);
</code></pre> | 61,341,154 | 4 | 2 | null | 2019-01-30 04:00:34.67 UTC | 11 | 2022-04-14 11:56:18.553 UTC | null | null | null | null | 9,075,515 | null | 1 | 55 | javascript|reactjs|typescript | 104,499 | <p>The <em>interface</em> with props should be</p>
<pre class="lang-js prettyprint-override"><code>interface IProps_Square {
message: string;
onClick: React.MouseEventHandler<HTMLButtonElement>;
}
</code></pre>
<p>Notice also that if you use semicolons, the interface items separator is a semicolon, not a comma.</p> |
45,353,619 | Angular4 Application running issues in IE11 | <p>I am building a Angular4 project using Angular CLI (1.1.2). It runs perfectly in Chrome (Version 59.0.3071.115) and firefox(54.0.1) but when I tried to use IE11 (Verison 11.0.9600.18738) nothings shows up and when I open the develper mode in IE, it shows me the following Error:</p>
<pre><code>SCRIPT5022: Exception thrown and not caught
File: polyfills.bundle.js, Line: 829, Column: 34
</code></pre>
<p>And the detailed Error message is following:</p>
<p><a href="https://i.stack.imgur.com/O2L2B.png" rel="noreferrer"><img src="https://i.stack.imgur.com/O2L2B.png" alt="enter image description here"></a></p>
<p>Anyone knows how to solve this problem?</p>
<p>Thanks!</p> | 45,354,411 | 3 | 2 | null | 2017-07-27 14:23:42.883 UTC | 14 | 2019-10-22 04:27:35.333 UTC | null | null | null | null | 5,802,031 | null | 1 | 73 | angular|internet-explorer|angular-cli|compatibility|polyfills | 39,727 | <p>The default polyfills.ts file is commented and need to uncomment lines of code and run npm install the corresponding module. Then it will compatible with the IE11</p> |
60,754,297 | Docker Compose failed to build - Filesharing has been cancelled | <p>I've ran into an issue with Docker Desktop, currently im running the edge version as a user on Stackoverflow. Before I got the drive not shared for unknown reason error which was "solved" by installing edge version: <a href="https://stackoverflow.com/questions/59555010/docker-for-windows-drive-sharing-failed-for-an-unknown-reason">Docker for Windows: Drive sharing failed for an unknown reason</a></p>
<p>Now that this was installed im getting this new error which prevents some containers from being built. These containers have all been tested and works on several other systems. Currently 3 out of 4 containers are not built and they all produce the same error as below:</p>
<pre><code>ERROR: for db Cannot create container for service db: status code not OK but 500: {"Message":"Unhandled exception: Filesharing has been cancelled"}
Encountered errors while bringing up the project.
</code></pre>
<p>full error:</p>
<pre><code>Creating imt2291-part2_www_1 ...
Creating imt2291-part2_phpmyadmin_1 ... done
Creating imt2291-part2_db_1 ...
Creating imt2291-part2_test_1 ... error
Creating imt2291-part2_www_1 ... error
ERROR: for imt2291-part2_test_1 Cannot create container for service test: status code not OK but 500: {"Message":"Unhandled exception: Filesharing has been cancelled"}
ERROR: for imt2291-part2_www_1 Cannot create container for service www: status Creating imt2291-part2_db_1 ... error
lled"}
ERROR: for imt2291-part2_db_1 Cannot create container for service db: status code not OK but 500: {"Message":"Unhandled exception: Filesharing has been cancelled"}
ERROR: for test Cannot create container for service test: status code not OK but 500: {"Message":"Unhandled exception: Filesharing has been cancelled"}
ERROR: for www Cannot create container for service www: status code not OK but 500: {"Message":"Unhandled exception: Filesharing has been cancelled"}
ERROR: for db Cannot create container for service db: status code not OK but 500: {"Message":"Unhandled exception: Filesharing has been cancelled"}
Encountered errors while bringing up the project.
</code></pre>
<p>Has anyone encountered this issue before and found a fix?</p> | 60,814,428 | 5 | 1 | null | 2020-03-19 09:31:43.407 UTC | 12 | 2022-06-01 19:55:17.283 UTC | null | null | null | null | 11,179,805 | null | 1 | 112 | windows|docker|docker-compose|docker-desktop | 56,033 | <p>You need to update File Sharing configuration in your Docker for Windows app (there is a new security hardening in 2.2.0.0 which has agressive defaults). Add all folders you need and then restart Docker for Windows. </p>
<p><a href="https://i.stack.imgur.com/LnntP.png" rel="noreferrer"><img src="https://i.stack.imgur.com/LnntP.png" alt="example"></a></p> |
50,714,469 | Recursively iterate through all subdirectories using pathlib | <p>How can I use <a href="https://docs.python.org/3/library/pathlib.html" rel="noreferrer">pathlib</a> to recursively iterate over all subdirectories of a given directory?</p>
<pre><code>p = Path('docs')
for child in p.iterdir(): child
</code></pre>
<p>only seems to iterate over the immediate children of a given directory.</p>
<p>I know this is possible with <code>os.walk()</code> or <code>glob</code>, but I want to use pathlib because I like working with the path objects.</p> | 50,714,580 | 5 | 0 | null | 2018-06-06 07:22:47.15 UTC | 9 | 2021-05-29 07:49:56.237 UTC | 2018-06-06 07:30:01.68 UTC | null | 1,934,212 | null | 1,934,212 | null | 1 | 127 | python|python-3.x|pathlib | 66,752 | <p>You can use the <a href="https://docs.python.org/3/library/pathlib.html#pathlib.Path.glob" rel="noreferrer"><code>glob</code></a> method of a <code>Path</code> object:</p>
<pre><code>p = Path('docs')
for i in p.glob('**/*'):
print(i.name)
</code></pre> |
31,082,098 | Why would I use divergent functions? | <p>Reading through the Rust book, I came across <a href="https://doc.rust-lang.org/stable/book/first-edition/functions.html#diverging-functions" rel="noreferrer">an interesting topic — divergent functions</a>:</p>
<blockquote>
<p>Rust has some special syntax for ‘diverging functions’, which are
functions that do not return:</p>
<pre><code>fn diverges() -> ! {
panic!("This function never returns!");
}
</code></pre>
</blockquote>
<blockquote>
<p>A diverging function can be used as any type:</p>
<pre><code>let x: i32 = diverges();
let x: String = diverges();
</code></pre>
</blockquote>
<p>What would be the use cases of a divergent function? The book says that </p>
<blockquote>
<p><code>panic!()</code> causes the current thread of execution to crash with the
given message. Because this function will cause a crash, it will never
return, and so it has the type <code>!</code></p>
</blockquote>
<p>That makes sense, but I can't think of where else a divergent function would be of use and it seems <em>very</em> localized to just <code>panic!</code>. I know there must be some useful scenarios out there for why they introduced divergent functions. Where would I likely see divergent functions in Rust?</p> | 31,082,459 | 3 | 0 | null | 2015-06-26 21:02:21.357 UTC | 1 | 2022-03-08 04:18:54.307 UTC | 2017-10-11 14:13:24.143 UTC | null | 155,423 | null | 1,409,312 | null | 1 | 34 | rust | 3,208 | <p>It has several uses. It can be used for functions which are designed to panic or exit the program. <code>panic!()</code> itself is one such function, but it can also be applied to functions which wrap <code>panic!()</code>, such as printing out more detailed error information and then panicking.</p>
<p>It can also be used for functions that never return. If a function goes into an infinite loop, such as the main loop of a server, and thus never returns, it could be defined this way.</p>
<p>Another possible use would be a wrapper around the Unix <a href="http://pubs.opengroup.org/onlinepubs/009695399/functions/exec.html" rel="noreferrer"><code>exec</code> family of functions</a>, in which the current process is replaced with the one being executed.</p>
<p>It is useful to have such a type because it is compatible with all other types. In order to be type safe, Rust has to ensure that all branches of a <code>match</code> or <code>if</code> statement return the same type. But if there are some branches that are unreachable or indicate an error, you need some way to throw an error that will unify with the type returned by the other branches. Because <code>!</code> unifies with all types, it can be used in any such case.</p>
<p>There is an <a href="https://github.com/canndrew/rfcs/blob/89e727e3b3da92295a7ab986b942de696d249091/text/0000-disjoins.md" rel="noreferrer">interesting RFC</a> (and <a href="https://github.com/rust-lang/rfcs/pull/1154" rel="noreferrer">discussion</a>) at the moment that argues (in part) for <a href="https://github.com/canndrew/rfcs/blob/89e727e3b3da92295a7ab986b942de696d249091/text/0000-disjoins.md#the--type" rel="noreferrer">expanding the places where <code>!</code> can be used</a>, arguing that it should be treated as a full fledged type like <code>()</code> is; <code>!</code> being a type with no values that unifies with all other types, while <code>()</code> being a distinct type with a single value. I'm not sure I agree with the full RFC, but the discussion of treating <code>!</code> as a full-fledged type is interesting and I think could be proposed separately from the rest of the RFC.</p>
<p><strong>Update</strong>: Since I wrote the above, the part of the RFC about promoting <code>!</code> to a full fledged type was <a href="https://github.com/rust-lang/rfcs/pull/1216" rel="noreferrer">split into a separate RFC and merged</a>, and is <a href="https://github.com/rust-lang/rust/issues/35121" rel="noreferrer">in the process of being implemented</a> (currently available in nightly builds behind a feature gate). As a full-fledged type, it can be used in more contexts, such as in <code>Result<T, !></code> indicating a result that can never fail, or <code>Result<!, E></code> as one that can never succeed. These are useful in generic contexts; if you have some trait that requires a method to return a result, but for that particular implementation it can only possibly succeed, you don't need to fill in some dummy error type.</p> |
35,453,953 | How to change Options menu dots color? | <p>I want to change Options menu's dots color to white. I tried to add image for this but dose not work. How to do this?</p>
<p><a href="https://i.stack.imgur.com/uP6sq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uP6sq.png" alt="enter image description here" /></a></p>
<p>menu xml :</p>
<pre><code> <menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.example.siddhi.timetablelayout.Main2Activity">
<item android:id="@+id/action_settings" android:title="@string/action_settings"
android:orderInCategory="100" app:showAsAction="never"
android:icon="@drawable/ic_more_vert_white_48dp"/>
</menu>
</code></pre> | 35,454,669 | 2 | 0 | null | 2016-02-17 10:24:47.58 UTC | 10 | 2022-07-16 10:56:49.14 UTC | 2022-07-16 10:56:49.14 UTC | null | 6,296,561 | null | 5,855,723 | null | 1 | 50 | android|colors|menu | 53,891 | <p>Put it in your <code>style.xml</code> in <code>AppTheme</code>:</p>
<pre><code><!-- android:textColorSecondary is the color of the menu overflow icon (three vertical dots) -->
<item name="android:textColorSecondary">@color/white</item>
</code></pre> |
25,827,368 | Swift webview: How to call correctly swift code from javascript? | <p>I'm trying to make my javascript interact with swift code but unfortunately i didn't succeed. </p>
<p>For the moment, i just tried to change the headers colors and display a message like you will see in the code below.</p>
<p>Here's my (<strong>index.html</strong>) code:</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta charset="UTF-8">
</head>
<body>
<h1>WebView Test</h1>
<script type="text/javascript" src="main.js"></script>
</body>
</html>
</code></pre>
<p>Here's my (<strong>main.js -JavaScript</strong>) code:</p>
<pre><code>function callNativeApp () {
try {
webkit.messageHandlers.callbackHandler.postMessage("Send from JavaScript");
} catch(err) {
console.log('error');
}
}
setTimeout(function () {
callNativeApp();
}, 5000);
function redHeader() {
document.querySelector('h1').style.color = "red";
}
</code></pre>
<p>Here's my (<strong>ViewController.swift</strong>) code:</p>
<pre><code>import UIKit
import WebKit
class ViewController: UIViewController, WKScriptMessageHandler {
@IBOutlet var containerView : UIView! = nil
var webView: WKWebView?
override func loadView() {
super.loadView()
var contentController = WKUserContentController();
var userScript = WKUserScript(
source: "redHeader()",
injectionTime: WKUserScriptInjectionTime.AtDocumentEnd,
forMainFrameOnly: true
)
contentController.addUserScript(userScript)
contentController.addScriptMessageHandler(
self,
name: "callbackHandler"
)
var config = WKWebViewConfiguration()
config.userContentController = contentController
self.webView = WKWebView()
self.view = self.webView!
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var url = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("index", ofType: "html")!)
var req = NSURLRequest(URL: url)
self.webView!.loadRequest(req)
}
func userContentController(userContentController: WKUserContentController!,didReceiveScriptMessage message: WKScriptMessage!) {
if(message.name == "callbackHandler") {
println("JavaScript is sending a message \(message.body)")
} }
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
</code></pre> | 25,830,317 | 2 | 1 | null | 2014-09-13 20:27:06.473 UTC | 20 | 2015-12-21 16:43:17.043 UTC | null | null | null | null | 3,740,543 | null | 1 | 25 | javascript|ios|xcode|swift | 25,210 | <p>You have everything set up properly, but you aren't giving your <code>WKWebViewConfiguration</code> instance to the <code>WKWebView</code>. Since the configuration has the details of the Javascript/Swift bridge, you can't talk back and forth.</p>
<pre><code>override func loadView() {
// ...
var config = WKWebViewConfiguration()
config.userContentController = contentController
self.webView = WKWebView(frame: self.view.frame, configuration: config)
self.view = self.webView!
}
</code></pre> |
25,795,131 | Do buffered channels maintain order? | <p>In Go, do buffered channels have any order guarantee?</p>
<p>For example:
you have two goroutines A & B that share a channel. A pushes data onto the channel while B reads from it. Are you guranted that B will read data In the same order that A put it into the channel?</p>
<p>I understand that if there are multiple producers or consumers the order may be non-deterministic, but I'm specifically asking about having just 1 producer and 1 consumer.</p> | 25,795,236 | 1 | 1 | null | 2014-09-11 18:57:34.24 UTC | 8 | 2020-06-04 05:10:54.66 UTC | 2019-02-11 07:05:23.303 UTC | user6169399 | 13,860 | null | 140,848 | null | 1 | 15 | go|channel | 9,344 | <blockquote>
<p>"Are you guaranteed that B will read data In the same order that A put it into the channel?" </p>
</blockquote>
<p>Yes. The order of data is guaranteed.<br>
But the <em>delivery</em> is guaranteed only for unbuffered channels, <em>not</em> buffered.<br>
(see second section of this answer)</p>
<hr>
<p>You can see the idea of channels illustrated in "<a href="https://www.ardanlabs.com/blog/2014/02/the-nature-of-channels-in-go.html" rel="noreferrer">The Nature Of Channels In Go</a>" from <strong><a href="https://twitter.com/goinggodotnet" rel="noreferrer">William Kennedy</a></strong> (Feb. 2014): it shows how the order or read/write is respected.<br>
See also <a href="https://golang.org/doc/effective_go.html#channels" rel="noreferrer">Channels</a>:</p>
<blockquote>
<p>Receivers always block until there is data to receive. </p>
<ul>
<li>If the channel is unbuffered, the sender blocks until the receiver has received the value. </li>
<li>If the channel has a buffer, the sender blocks only until the value has been copied to the buffer; if the buffer is full, this means waiting until some receiver has retrieved a value.</li>
</ul>
</blockquote>
<h2>Unbuffered Channels</h2>
<p><a href="https://i.stack.imgur.com/7lO5e.png" rel="noreferrer"><img src="https://i.stack.imgur.com/7lO5e.png" alt="https://www.ardanlabs.com/images/goinggo/Screen+Shot+2014-02-16+at+10.10.54+AM.png"></a></p>
<h2>Buffered Channel</h2>
<p><a href="https://i.stack.imgur.com/l0ddx.png" rel="noreferrer"><img src="https://i.stack.imgur.com/l0ddx.png" alt="https://www.ardanlabs.com/images/goinggo/Screen+Shot+2014-02-17+at+8.38.15+AM.png"></a></p>
<p><sup>Image source: <a href="https://www.ardanlabs.com/blog/2014/02/the-nature-of-channels-in-go.html" rel="noreferrer">Ardan labs - William Kennedy</a></sup></p>
<hr>
<p>The same William Kennedy details the <strong>Guarantee Of Delivery</strong> aspect in "<strong><a href="https://www.ardanlabs.com/blog/2017/10/the-behavior-of-channels.html" rel="noreferrer">The Behavior Of Channels</a></strong>" (Oct 2017)</p>
<blockquote>
<p>Do I need a guarantee that the signal sent by a particular goroutine has been received?</p>
</blockquote>
<p><a href="https://i.stack.imgur.com/dTEM1.png" rel="noreferrer"><img src="https://i.stack.imgur.com/dTEM1.png" alt="https://www.ardanlabs.com/images/goinggo/86_signaling_with_data.png"></a></p>
<p><sup>Image source: Again, <a href="https://www.ardanlabs.com/blog/2017/10/the-behavior-of-channels.html" rel="noreferrer">Ardan labs - William Kennedy</a></sup></p>
<blockquote>
<p>The three channel options are Unbuffered, Buffered >1 or Buffered =1.</p>
<ul>
<li><p><strong>Guarantee</strong></p>
<ul>
<li>An <strong>Unbuffered</strong> channel gives you a <strong>Guarantee</strong> that a signal being sent has been received.
<ul>
<li>Because the <strong>Receive of the signal Happens Before the Send</strong> of the signal completes.</li>
</ul></li>
</ul></li>
<li><p><strong>No Guarantee</strong></p>
<ul>
<li>A <strong>Buffered</strong> channel of <strong>size >1</strong> gives you <strong>No Guarantee</strong> that a signal being sent has been received.
<ul>
<li>Because the <strong>Send</strong> of the signal <strong>Happens Before the Receive</strong> of the signal completes.</li>
</ul></li>
</ul></li>
<li><p><strong>Delayed Guarantee</strong></p>
<ul>
<li>A <strong>Buffered</strong> channel of <strong>size =1</strong> gives you a <strong>Delayed Guarantee</strong>. It can guarantee that the previous signal that was sent has been received.
<ul>
<li>Because the <strong>Receive of the First Signal, Happens Before the Send of the Second Signal</strong> completes.</li>
</ul></li>
</ul></li>
</ul>
</blockquote> |
25,739,957 | How to reboot android device emulator in Genymotion | <p>How can i test my application after reboot(BOOT COMPLETED) using Genymotion I am using nexus 4 as device</p>
<pre><code><receiver android:name="com.template.SampleBootReceiver"
android:enabled="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
</code></pre> | 25,745,972 | 6 | 2 | null | 2014-09-09 08:30:42.397 UTC | 5 | 2017-03-19 21:19:27.3 UTC | 2014-09-09 08:43:12.77 UTC | null | 3,247,356 | null | 3,926,701 | null | 1 | 13 | android|android-emulator|genymotion | 67,905 | <p>You can use the command line with <code>adb reboot</code>. It should restart your device.</p>
<p>To use adb you need to be inside the adb binary's folder. ie, <code><android SDK>/platform-tools/</code> or <code><genymotion folder>/tools/</code> if the android SDK is not installed. You can also these folders to your path to access it from anywhere.</p> |
30,452,318 | How to handle empty response in Spring RestTemplate | <p>My Authorization service returs a http 204 on success and a http 401 on failure but no responseBody. I'm not able to consume this with the RestTemplate client. It fails attempting to serialize the response. The error from Jackson suggest that i turn on FAIL_ON_EMPTY_BEANS in the serializer, but how do set this in restTemplate</p>
<p><strong>The client consuming the rest api</strong></p>
<pre><code>@SuppressWarnings("rawtypes")
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
RestTemplate restTemplate = new RestTemplate();
System.out.println("\n\n\n\n ============API REQUEST INTERCEPTOR=============== \n\n\n\n\n");
if(StringUtils.isBlank(request.getHeader(AuthenticationKeys.AUTHENTICATIONTOKEN.name().toLowerCase()))){
//TODO AUTHORIZE TOKEN
ResponseEntity<AuthenticationResponse> authenticateResponse = restTemplate.getForEntity(authenticateUrl, AuthenticationResponse.class);
if(authenticateResponse.getStatusCode().is2xxSuccessful()){
//TODO SET THE TOKEN IN THE CONTEXT
return true;
}else{
//TODO DO SOME ERROR HANDLING
return false;
}
}else{
AuthorizationRequest authorizationRequest = new AuthorizationRequest();
authorizationRequest.setToken("TESTNG");
ResponseEntity<Object> authorizationResponse = restTemplate.postForEntity(authorizeUrl, request, Object.class);
if(authorizationResponse.getStatusCode().is2xxSuccessful()){
return true;
}else{
//TODO DO SOME ERROR HANDLING
if(authorizationResponse.getStatusCode().equals(HttpStatus.UNAUTHORIZED)){
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Oops! access to this API is not authorized to you.");
}
return false;
}
}
</code></pre>
<p><strong>The rest service</strong> </p>
<pre><code>@RequestMapping(value="/authorize", method = RequestMethod.POST)
void authorize(@RequestBody @Valid AuthorizationRequest request, HttpServletResponse response){
if(request.getToken().equals("TESTING")){
response.setStatus(HttpServletResponse.SC_NO_CONTENT);
}else{
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}
}
}
</code></pre>
<p><strong>The exception</strong></p>
<pre><code>Caused by: com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class org.apache.catalina.connector.CoyoteInputStream and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) ) (through reference chain: org.apache.shiro.web.servlet.ShiroHttpServletRequest["request"]->org.apache.catalina.connector.RequestFacade["inputStream"])
at com.fasterxml.jackson.databind.ser.impl.UnknownSerializer.failForEmpty(UnknownSerializer.java:59) ~[jackson-databind-2.5.0.jar:2.5.0]
at com.fasterxml.jackson.databind.ser.impl.UnknownSerializer.serialize(UnknownSerializer.java:26) ~[jackson-databind-2.5.0.jar:2.5.0]
at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:575) ~[jackson-databind-2.5.0.jar:2.5.0]
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:663) ~[jackson-databind-2.5.0.jar:2.5.0]
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:156) ~[jackson-databind-2.5.0.jar:2.5.0]
at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:575) ~[jackson-databind-2.5.0.jar:2.5.0]
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:663) ~[jackson-databind-2.5.0.jar:2.5.0]
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:156) ~[jackson-databind-2.5.0.jar:2.5.0]
at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:129) ~[jackson-databind-2.5.0.jar:2.5.0]
at com.fasterxml.jackson.databind.ObjectMapper.writeValue(ObjectMapper.java:2238) ~[jackson-databind-2.5.0.jar:2.5.0]
at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.writeInternal(AbstractJackson2HttpMessageConverter.java:231) ~[spring-web-4.1.4.RELEASE.jar:4.1.4.RELEASE]
... 52 more
</code></pre>
<p><strong>The Attempted Fix</strong></p>
<pre><code>RestTemplate restTemplate = new RestTemplate();
List<HttpMessageConverter<?>> converters = restTemplate.getMessageConverters();
for(HttpMessageConverter<?> converter : converters){
if(converter instanceof MappingJackson2HttpMessageConverter){
((MappingJackson2HttpMessageConverter) converter).getObjectMapper().configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
}
}
</code></pre>
<p><strong>The next error</strong></p>
<pre><code>org.springframework.http.converter.HttpMessageNotWritableException: Could not write content: getInputStream() has already been called for this request (through reference chain: org.apache.shiro.web.servlet.ShiroHttpServletRequest["request"]->org.apache.catalina.connector.RequestFacade["reader"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: getInputStream() has already been called for this request (through reference chain: org.apache.shiro.web.servlet.ShiroHttpServletRequest["request"]->org.apache.catalina.connector.RequestFacade["reader"])
at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.writeInternal(AbstractJackson2HttpMessageConverter.java:238) ~[spring-web-4.1.4.RELEASE.jar:4.1.4.RELEASE]
at org.springframework.http.converter.AbstractHttpMessageConverter.write(AbstractHttpMessageConverter.java:208) ~[spring-web-4.1.4.RELEASE.jar:4.1.4.RELEASE]
at org.springframework.web.client.RestTemplate$HttpEntityRequestCallback.doWithRequest(RestTemplate.java:777) ~[spring-web-4.1.4.RELEASE.jar:4.1.4.RELEASE]
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:566) ~[spring-web-4.1.4.RELEASE.jar:4.1.4.RELEASE]
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:529) ~[spring-web-4.1.4.RELEASE.jar:4.1.4.RELEASE]
at org.springframework.web.client.RestTemplate.postForEntity(RestTemplate.java:356) ~[spring-web-4.1.4.RELEASE.jar:4.1.4.RELEASE]
at mordeth.orchestration.interceptor.ApiRequestInterceptor.preHandle(ApiRequestInterceptor.java:120) ~[ApiRequestInterceptor.class:?]
at org.springframework.web.servlet.HandlerExecutionChain.applyPreHandle(HandlerExecutionChain.java:134) ~[spring-webmvc-4.1.4.RELEASE.jar:4.1.4.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938) [spring-webmvc-4.1.4.RELEASE.jar:4.1.4.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877) [spring-webmvc-4.1.4.RELEASE.jar:4.1.4.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966) [spring-webmvc-4.1.4.RELEASE.jar:4.1.4.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:868) [spring-webmvc-4.1.4.RELEASE.jar:4.1.4.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:646) [servlet-api.jar:?]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842) [spring-webmvc-4.1.4.RELEASE.jar:4.1.4.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727) [servlet-api.jar:?]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303) [catalina.jar:7.0.57]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) [catalina.jar:7.0.57]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) [tomcat7-websocket.jar:7.0.57]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) [catalina.jar:7.0.57]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) [catalina.jar:7.0.57]
at mordeth.orchestration.controller.CorsFilter.doFilterInternal(CorsFilter.java:21) [CorsFilter.class:?]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.1.4.RELEASE.jar:4.1.4.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) [catalina.jar:7.0.57]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) [catalina.jar:7.0.57]
at org.apache.shiro.web.servlet.AbstractShiroFilter.executeChain(AbstractShiroFilter.java:449) [shiro-web-1.2.0.jar:1.2.0]
at org.apache.shiro.web.servlet.AbstractShiroFilter$1.call(AbstractShiroFilter.java:365) [shiro-web-1.2.0.jar:1.2.0]
at org.apache.shiro.subject.support.SubjectCallable.doCall(SubjectCallable.java:90) [shiro-core-1.2.0.jar:1.2.0]
at org.apache.shiro.subject.support.SubjectCallable.call(SubjectCallable.java:83) [shiro-core-1.2.0.jar:1.2.0]
at org.apache.shiro.subject.support.DelegatingSubject.execute(DelegatingSubject.java:380) [shiro-core-1.2.0.jar:1.2.0]
at org.apache.shiro.web.servlet.AbstractShiroFilter.doFilterInternal(AbstractShiroFilter.java:362) [shiro-web-1.2.0.jar:1.2.0]
at org.apache.shiro.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:125) [shiro-web-1.2.0.jar:1.2.0]
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344) [spring-web-4.1.4.RELEASE.jar:4.1.4.RELEASE]
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261) [spring-web-4.1.4.RELEASE.jar:4.1.4.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) [catalina.jar:7.0.57]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) [catalina.jar:7.0.57]
at org.apache.logging.log4j.web.Log4jServletFilter.doFilter(Log4jServletFilter.java:67) [log4j-web-2.0.jar:2.0]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) [catalina.jar:7.0.57]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) [catalina.jar:7.0.57]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220) [catalina.jar:7.0.57]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122) [catalina.jar:7.0.57]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503) [catalina.jar:7.0.57]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170) [catalina.jar:7.0.57]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103) [catalina.jar:7.0.57]
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950) [catalina.jar:7.0.57]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116) [catalina.jar:7.0.57]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421) [catalina.jar:7.0.57]
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070) [tomcat-coyote.jar:7.0.57]
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611) [tomcat-coyote.jar:7.0.57]
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:314) [tomcat-coyote.jar:7.0.57]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) [?:1.7.0_71]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [?:1.7.0_71]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-coyote.jar:7.0.57]
at java.lang.Thread.run(Thread.java:745) [?:1.7.0_71]
Caused by: com.fasterxml.jackson.databind.JsonMappingException: getInputStream() has already been called for this request (through reference chain: org.apache.shiro.web.servlet.ShiroHttpServletRequest["request"]->org.apache.catalina.connector.RequestFacade["reader"])
at com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:210) ~[jackson-databind-2.5.0.jar:2.5.0]
at com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:177) ~[jackson-databind-2.5.0.jar:2.5.0]
at com.fasterxml.jackson.databind.ser.std.StdSerializer.wrapAndThrow(StdSerializer.java:190) ~[jackson-databind-2.5.0.jar:2.5.0]
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:671) ~[jackson-databind-2.5.0.jar:2.5.0]
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:156) ~[jackson-databind-2.5.0.jar:2.5.0]
at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:575) ~[jackson-databind-2.5.0.jar:2.5.0]
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:663) ~[jackson-databind-2.5.0.jar:2.5.0]
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:156) ~[jackson-databind-2.5.0.jar:2.5.0]
at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:129) ~[jackson-databind-2.5.0.jar:2.5.0]
at com.fasterxml.jackson.databind.ObjectMapper.writeValue(ObjectMapper.java:2238) ~[jackson-databind-2.5.0.jar:2.5.0]
at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.writeInternal(AbstractJackson2HttpMessageConverter.java:231) ~[spring-web-4.1.4.RELEASE.jar:4.1.4.RELEASE]
... 52 more
Caused by: java.lang.IllegalStateException: getInputStream() has already been called for this request
at org.apache.catalina.connector.Request.getReader(Request.java:1239) ~[catalina.jar:7.0.57]
at org.apache.catalina.connector.RequestFacade.getReader(RequestFacade.java:505) ~[catalina.jar:7.0.57]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.7.0_71]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) ~[?:1.7.0_71]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.7.0_71]
at java.lang.reflect.Method.invoke(Method.java:606) ~[?:1.7.0_71]
at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:536) ~[jackson-databind-2.5.0.jar:2.5.0]
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:663) ~[jackson-databind-2.5.0.jar:2.5.0]
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:156) ~[jackson-databind-2.5.0.jar:2.5.0]
at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:575) ~[jackson-databind-2.5.0.jar:2.5.0]
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:663) ~[jackson-databind-2.5.0.jar:2.5.0]
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:156) ~[jackson-databind-2.5.0.jar:2.5.0]
at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:129) ~[jackson-databind-2.5.0.jar:2.5.0]
at com.fasterxml.jackson.databind.ObjectMapper.writeValue(ObjectMapper.java:2238) ~[jackson-databind-2.5.0.jar:2.5.0]
at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.writeInternal(AbstractJackson2HttpMessageConverter.java:231) ~[spring-web-4.1.4.RELEASE.jar:4.1.4.RELEASE]
... 52 more
</code></pre> | 30,455,956 | 1 | 2 | null | 2015-05-26 07:35:05.86 UTC | 7 | 2015-05-26 18:54:14.927 UTC | 2015-05-26 09:24:42.813 UTC | null | 2,535,987 | null | 2,535,987 | null | 1 | 46 | spring|rest|jackson|resttemplate | 82,689 | <p>Use String instead of AuthenticationResponse. If you get an empty response, the String value will be empty. </p>
<pre><code>ResponseEntity<String> authenticateResponse = restTemplate.getForEntity(authenticateUrl, String.class);
</code></pre>
<p>UPDATE:
Check this <a href="https://jira.spring.io/browse/SPR-8572" rel="noreferrer">link</a>. I think this will fix your issue.</p>
<pre><code>ResponseEntity<Void> response = restTemplate.getForEntity(authenticateUrl,Void.class);
Void body = response.getBody();
</code></pre> |
29,643,352 | Converting Hex to RGB value in Python | <p>Working off Jeremy's response here: <a href="https://stackoverflow.com/questions/214359/converting-hex-color-to-rgb-and-vice-versa">Converting hex color to RGB and vice-versa</a> I was able to get a python program to convert preset colour hex codes (example #B4FBB8), however from an end-user perspective we can't ask people to edit code & run from there. How can one prompt the user to enter a hex value and then have it spit out a RGB value from there? </p>
<p>Here's the code I have thus far:</p>
<pre><code>def hex_to_rgb(value):
value = value.lstrip('#')
lv = len(value)
return tuple(int(value[i:i + lv // 3], 16) for i in range(0, lv, lv // 3))
def rgb_to_hex(rgb):
return '#%02x%02x%02x' % rgb
hex_to_rgb("#ffffff") # ==> (255, 255, 255)
hex_to_rgb("#ffffffffffff") # ==> (65535, 65535, 65535)
rgb_to_hex((255, 255, 255)) # ==> '#ffffff'
rgb_to_hex((65535, 65535, 65535)) # ==> '#ffffffffffff'
print('Please enter your colour hex')
hex == input("")
print('Calculating...')
print(hex_to_rgb(hex()))
</code></pre>
<p>Using the line <code>print(hex_to_rgb('#B4FBB8'))</code> I'm able to get it to spit out the correct RGB value which is (180, 251, 184)</p>
<p>It's probably super simple - I'm still pretty rough with Python. </p> | 29,643,643 | 12 | 1 | null | 2015-04-15 06:47:59.633 UTC | 25 | 2022-04-26 22:38:51.26 UTC | 2017-05-23 12:34:23.59 UTC | null | -1 | null | 3,924,370 | null | 1 | 123 | python|colors|rgb | 137,035 | <p>I believe that this does what you are looking for:</p>
<pre><code>h = input('Enter hex: ').lstrip('#')
print('RGB =', tuple(int(h[i:i+2], 16) for i in (0, 2, 4)))
</code></pre>
<p>(The above was written for Python 3)</p>
<p>Sample run:</p>
<pre><code>Enter hex: #B4FBB8
RGB = (180, 251, 184)
</code></pre>
<h3>Writing to a file</h3>
<p>To write to a file with handle <code>fhandle</code> while preserving the formatting:</p>
<pre><code>fhandle.write('RGB = {}'.format( tuple(int(h[i:i+2], 16) for i in (0, 2, 4)) ))
</code></pre> |
26,767,591 | pygame.error: video system not initialized | <p>I am getting this error whenever I attempt to execute my <code>pygame</code> code:
<code>pygame.error: video system not initialized</code></p>
<pre class="lang-py prettyprint-override"><code>from sys import exit
import pygame
from pygame.locals import *
black = 0, 0, 0
white = 255, 255, 255
red = 255, 0, 0
green = 0, 255, 0
blue = 0, 0, 255
screen = screen_width, screen_height = 600, 400
clock = pygame.time.Clock()
pygame.display.set_caption("Physics")
def game_loop():
fps_cap = 120
running = True
while running:
clock.tick(fps_cap)
for event in pygame.event.get(): # error is here
if event.type == pygame.QUIT:
running = False
screen.fill(white)
pygame.display.flip()
pygame.quit()
exit()
game_loop()
#!/usr/bin/env python
</code></pre> | 26,767,644 | 11 | 1 | null | 2014-11-05 21:36:08.423 UTC | 2 | 2022-09-24 17:45:03.717 UTC | 2021-12-17 21:37:31.357 UTC | null | 15,611,749 | null | 4,062,174 | null | 1 | 14 | python|pygame | 107,963 | <p>You haven't called <a href="http://www.pygame.org/docs/ref/pygame.html#pygame.init" rel="noreferrer"><code>pygame.init()</code></a> anywhere.</p>
<p>See the <a href="https://www.pygame.org/docs/tut/PygameIntro.html" rel="noreferrer">basic Intro tutorial</a>, or the specific <a href="http://www.pygame.org/docs/tut/ImportInit.html" rel="noreferrer">Import and Initialize</a> tutorial, which explains:</p>
<blockquote>
<p>Before you can do much with pygame, you will need to initialize it. The most common way to do this is just make one call.</p>
</blockquote>
<pre><code>pygame.init()
</code></pre>
<blockquote>
<p>This will attempt to initialize all the pygame modules for you. Not all pygame modules need to be initialized, but this will automatically initialize the ones that do. You can also easily initialize each pygame module by hand. For example to only initialize the font module you would just call.</p>
</blockquote>
<p>In your particular case, it's probably <a href="http://www.pygame.org/docs/ref/display.html#pygame.display.init" rel="noreferrer"><code>pygame.display</code></a> that's complaining that you called either its <code>set_caption</code> or its <code>flip</code> without calling its <code>init</code> first. But really, as the tutorial says, it's better to just <code>init</code> everything at the top than to try to figure out exactly what needs to be initialized when.</p> |
20,120,833 | How do I refer to a typedef in a header file? | <p>I have a source file where a typedef struct is defined:</p>
<pre><code>typedef struct node {
char *key;
char *value;
struct node *next;
} *Node;
</code></pre>
<p>In this module, there are some functions that operate on a Node and have Node as return type. What am I supposed to write in the header file for this typedef?</p>
<p>Is it correct to write just</p>
<pre><code>typedef *Node;
</code></pre>
<p>in the header? </p> | 20,120,917 | 2 | 1 | null | 2013-11-21 12:18:55.86 UTC | 4 | 2013-11-21 12:30:59.953 UTC | null | null | null | null | 1,221,132 | null | 1 | 11 | c|header|typedef | 43,953 | <p>You can use:</p>
<pre><code>typedef struct node * Node;
</code></pre>
<p>But I would advise against hiding the pointer in type declaration. It is more informative to have that information in variable declaration.</p>
<p><strong>module.c:</strong></p>
<pre><code>#include "module.h"
struct node {
char *key;
char *value;
struct node *next;
};
</code></pre>
<p><strong>module.h:</strong></p>
<pre><code>typedef struct node Node;
</code></pre>
<p><strong>variable declaration for pointer somewhere:</strong></p>
<pre><code>#include "module.h"
Node * myNode; // We don't need to know the whole type when declaring pointer
</code></pre> |
20,149,796 | MemoryCache Thread Safety, Is Locking Necessary? | <p>For starters let me just throw it out there that I know the code below is not thread safe (correction: might be). What I am struggling with is finding an implementation that is and one that I can actually get to fail under test. I am refactoring a large WCF project right now that needs some (mostly) static data cached and its populated from a SQL database. It needs to expire and "refresh" at least once a day which is why I am using MemoryCache.</p>
<p>I know that the code below should not be thread safe but I cannot get it to fail under heavy load and to complicate matters a google search shows implementations both ways (with and without locks combined with debates whether or not they are necessary.</p>
<p>Could someone with knowledge of MemoryCache in a multi threaded environment let me definitively know whether or not I need to lock where appropriate so that a call to remove (which will seldom be called but its a requirement) will not throw during retrieval/repopulation.</p>
<pre><code>public class MemoryCacheService : IMemoryCacheService
{
private const string PunctuationMapCacheKey = "punctuationMaps";
private static readonly ObjectCache Cache;
private readonly IAdoNet _adoNet;
static MemoryCacheService()
{
Cache = MemoryCache.Default;
}
public MemoryCacheService(IAdoNet adoNet)
{
_adoNet = adoNet;
}
public void ClearPunctuationMaps()
{
Cache.Remove(PunctuationMapCacheKey);
}
public IEnumerable GetPunctuationMaps()
{
if (Cache.Contains(PunctuationMapCacheKey))
{
return (IEnumerable) Cache.Get(PunctuationMapCacheKey);
}
var punctuationMaps = GetPunctuationMappings();
if (punctuationMaps == null)
{
throw new ApplicationException("Unable to retrieve punctuation mappings from the database.");
}
if (punctuationMaps.Cast<IPunctuationMapDto>().Any(p => p.UntaggedValue == null || p.TaggedValue == null))
{
throw new ApplicationException("Null values detected in Untagged or Tagged punctuation mappings.");
}
// Store data in the cache
var cacheItemPolicy = new CacheItemPolicy
{
AbsoluteExpiration = DateTime.Now.AddDays(1.0)
};
Cache.AddOrGetExisting(PunctuationMapCacheKey, punctuationMaps, cacheItemPolicy);
return punctuationMaps;
}
//Go oldschool ADO.NET to break the dependency on the entity framework and need to inject the database handler to populate cache
private IEnumerable GetPunctuationMappings()
{
var table = _adoNet.ExecuteSelectCommand("SELECT [id], [TaggedValue],[UntaggedValue] FROM [dbo].[PunctuationMapper]", CommandType.Text);
if (table != null && table.Rows.Count != 0)
{
return AutoMapper.Mapper.DynamicMap<IDataReader, IEnumerable<PunctuationMapDto>>(table.CreateDataReader());
}
return null;
}
}
</code></pre> | 20,150,112 | 7 | 2 | null | 2013-11-22 16:30:26.75 UTC | 22 | 2019-08-29 12:38:33.023 UTC | 2013-11-22 19:49:36.627 UTC | null | 2,062,622 | null | 2,062,622 | null | 1 | 110 | c#|multithreading|wcf|memorycache | 87,077 | <p>The default MS-provided <code>MemoryCache</code> is entirely thread safe. Any custom implementation that derives from <code>MemoryCache</code> may not be thread safe. If you're using plain <code>MemoryCache</code> out of the box, it is thread safe. Browse the source code of my open source distributed caching solution to see how I use it (MemCache.cs):</p>
<p><a href="https://github.com/haneytron/dache/blob/master/Dache.CacheHost/Storage/MemCache.cs" rel="noreferrer">https://github.com/haneytron/dache/blob/master/Dache.CacheHost/Storage/MemCache.cs</a></p> |
14,700,998 | How to print value from pl/sql cursor? | <p>I've tried the following code for printing each or some detail based on the value I get from the cursor but I can't, can anybody help me?</p>
<pre><code>set serveroutput on
declare
d_id number;
temp_tab VARRAY;
cursor c1 is select * from(select d.department_ID, `enter code here`d.department_name,count(d.department_name) cnt from employees e,departments d where e.department_id=d.department_id group by d.department_ID, d.department_name) where cnt>=5;
begin
open c1;
for i in c1
loop
select e.first_name,d.department_id,d.department_name into temp_tab from employees e,departments d where d.department_id=i.department_ID;
end loop;
close c1;
end;
</code></pre> | 14,701,332 | 2 | 0 | null | 2013-02-05 05:50:50.987 UTC | null | 2013-02-05 11:09:47.85 UTC | 2013-02-05 06:05:25.47 UTC | null | 1,433,298 | null | 1,859,477 | null | 1 | 1 | plsql|oracle11g | 39,943 | <p>Yes.If you want to print ant element value.Then select the element value into the variable.</p>
<p>Then use below one to print the element value :</p>
<pre><code>dbms_output.put_line('Variable value= ' || Variable_name );
</code></pre>
<p>In your code you are using the collection varaiable and fetching value into collection.
Then to print objects elements:</p>
<pre><code>dbms_output.put_line('First Name :'||object_name.first_name);
</code></pre>
<p>If you are using the record variable in PLSQL.Then use the below method:then declare the record type variable then fetch into that variable then display variable.column,</p>
<pre><code>DECLARE
TYPE t_name IS RECORD(
first_name employees.first_name%TYPE,
last_name employees.last_name%TYPE
);
r_name t_name; -- name record
n_emp_id employees.employee_id%TYPE := 200;
BEGIN
SELECT first_name,
last_name
INTO r_name
FROM employees
WHERE employee_id = n_emp_id;
-- print out the employee's name
DBMS_OUTPUT.PUT_LINE(r_name.first_name || ',' || r_name.last_name );
END;
</code></pre> |
7,504,680 | How to write a DQL select statement to search some, but not all the entities in a single table inheritance table | <p>So I have 3 entities within one table. I need to be able to search 2 out of the 3 entities in one select statement, but I'm not sure how to do this.</p> | 7,506,698 | 3 | 0 | null | 2011-09-21 18:21:09.95 UTC | 9 | 2019-09-05 20:52:22.203 UTC | 2017-07-19 11:22:54.31 UTC | null | 4,074,148 | null | 581,851 | null | 1 | 13 | doctrine-orm | 9,154 | <p>Use the <code>INSTANCE OF</code> operator in your dql query like this (where <code>User</code> is your base class):</p>
<pre><code>$em->createQuery('
SELECT u
FROM Entity\User u
WHERE (u INSTANCE OF Entity\Manager OR u INSTANCE OF Entity\Customer)
');
</code></pre>
<p>Doctrine translates this in the sql query in a <code>WHERE user.type = '...'</code> condition.</p>
<p>See <a href="https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/dql-doctrine-query-language.html" rel="nofollow noreferrer">here</a> for more details on the dql query syntax.</p> |
7,603,446 | VIM Insert PHPdoc automatically | <p>Is there a way to insert PHPDoc in VIM using a command or key combination?</p>
<p>For example, I have a class:</p>
<pre><code>class MyClass
{
public function __construct() { }
public function __destruct() { }
/* command here to insert PHP doc */
public function abc() { }
}
</code></pre>
<p>I would like to insert something like:</p>
<pre><code>/**
* method()
*
* description
*
* @access
* @author
* @param type $varname description
* @return type description
* @copyright
* @version
*/
</code></pre>
<p>And then I can full out the rest manually. Thank you</p> | 8,950,400 | 3 | 4 | null | 2011-09-29 21:12:54.99 UTC | 11 | 2013-05-15 15:08:15.433 UTC | null | null | null | null | 923,348 | null | 1 | 17 | vim|phpdoc | 9,864 | <p>This can be done pretty effectively with the lightweight <a href="http://www.vim.org/scripts/script.php?script_id=1355" rel="noreferrer">phpDocumentor plugin</a>. </p>
<p><strong>Edit</strong> <a href="http://www.vim.org/scripts/script.php?script_id=2980" rel="noreferrer">Here's a modified version</a> with more recent development.</p>
<p><strong>Edit</strong> <a href="https://github.com/tobyS/pdv" rel="noreferrer">Here's version 2 of the phpDocumentor plugin</a>. It is more recent than the above two links.</p>
<p>Install the plugin into your <code>$VIMFILES/plugin</code> directory and add this to your .vimrc:</p>
<pre><code>" PHP documenter script bound to Control-P
autocmd FileType php inoremap <C-p> <ESC>:call PhpDocSingle()<CR>i
autocmd FileType php nnoremap <C-p> :call PhpDocSingle()<CR>
autocmd FileType php vnoremap <C-p> :call PhpDocRange()<CR>
</code></pre>
<p>The above binds phpDocumentor to <kbd>Ctrl</kbd><kbd>p</kbd> in insert, normal, and visual modes. Place your cursor on a class, function, or variable definition, press <kbd>Ctrl</kbd><kbd>p</kbd>, and the plugin will attempt to form a doc block based on the definition.</p>
<h3>Example function doc block:</h3>
<pre><code>/**
* testDocBlock
*
* @param mixed $param1
* @param mixed $param2
* @static
* @access public
* @return boolean
*/
public static function testDocBlock($param1, $param2) {
// Pressed Ctl-p while cursor was on the function definition line above...
}
</code></pre>
<h3>Example class doc block</h3>
<p>Copyright, version, author, etc are included by default in a class doc block. You can modify the plugin to include your own default values for these:</p>
<pre><code>/**
* TestClass
*
* @package
* @version $id$
* @copyright
* @author Michael <[email protected]>
* @license
*/
class TestClass {
}
</code></pre>
<h3>Full abstract class example:</h3>
<pre><code><?php
/**
* TestClass
*
* @abstract
* @package
* @version $id$
* @copyright
* @author Michael <[email protected]>
* @license
*/
abstract class TestClass {
/**
* publicProp
*
* @var string
* @access public
*/
public $publicProp;
/**
* privateProp
*
* @var string
* @access private
*/
private $privateProp;
/**
* testDocBlock
*
* @param string $param1
* @param string $param2
* @static
* @access public
* @return boolean
*/
public static function testDocBlock($param1, $param2) {
// code here...
}
}
?>
</code></pre> |
7,647,042 | Sharing global javascript variable of a page with an iframe within that page | <p>I have an scenario where in I have a page, which have <code><script></code> tag and some global javascript variables within that. I also have an iframe within that page and I want to have access of global javascript variables of the page in iframe.</p>
<p>Is it possible?, if yes, how can i do that?</p> | 7,647,123 | 3 | 1 | null | 2011-10-04 11:15:10.407 UTC | 16 | 2018-08-20 01:23:20.797 UTC | null | null | null | null | 810,176 | null | 1 | 55 | javascript|iframe | 71,568 | <p>Easily by calling parent.your_var_name in your iframe's script.</p>
<p>One condition: both pages (main and iframe's) have to be on the same domain.</p>
<p>main page:</p>
<pre><code><script>
var my_var = 'hello world!';
</script>
</code></pre>
<p>iframe</p>
<pre><code><script>
function some_fn(){
alert(parent.my_var); //helo world!
}
</script>
</code></pre> |
7,288,669 | Jquery $('#div').show().delay(5000).hide(); doesn't work | <p>I'm trying to show a div thats set to <code>display: none;</code> for 5 seconds with</p>
<pre><code>$('#div').show().delay(5000).hide();
</code></pre>
<p>but it deson't work, it just goes straight to hide()</p>
<p>Can any of you help me?</p> | 7,288,701 | 4 | 0 | null | 2011-09-02 20:01:25.043 UTC | 15 | 2011-09-02 20:10:09.143 UTC | 2011-09-02 20:03:41.963 UTC | null | 764,846 | null | 497,415 | null | 1 | 58 | javascript|jquery|css | 81,168 | <p>Do it like this:</p>
<pre><code>$('#div').show(0).delay(5000).hide(0);
</code></pre>
<p>By passing in numbers to <code>.show()</code> and <code>.hide()</code>, jQuery will take those methods into its internal <em>fx queue</em> (even if the number is zero). Since <code>.delay()</code> only works within a queue, you need that little workaround.</p>
<p>example: <a href="http://jsfiddle.net/zceKN/">http://jsfiddle.net/zceKN/</a></p> |
24,282,550 | No non-missing arguments warning when using min or max in reshape2 | <p>I get the following warning when I use min or max in the dcast function from the reshape2 package. What is it telling me? I can't find anything that explains the warning message and I'm a bit confused about why I get it when I use max but not when I use mean or other aggregate functions.</p>
<blockquote>
<p>Warning message:<br>In .fun(.value[0], ...) : no non-missing arguments to min; returning Inf</p>
</blockquote>
<p>Here's a reproducible example:</p>
<pre><code>data(iris)
library(reshape2)
molten.iris <- melt(iris,id.var="Species")
summary(molten.iris)
str(molten.iris)
#------------------------------------------------------------
# Both return warning:
dcast(data=molten.iris,Species~variable,value.var="value",fun.aggregate=min)
dcast(data=molten.iris,Species~variable,value.var="value",fun.aggregate=max)
# Length looks fine though
dcast(data=molten.iris,Species~variable,value.var="value",fun.aggregate=length)
#------------------------------------------------------------
# No warning messages here:
aggregate(value ~ Species + variable, FUN=min, data=molten.iris)
aggregate(value ~ Species + variable, FUN=max, data=molten.iris)
#------------------------------------------------------------
# Or here:
library(plyr)
ddply(molten.iris,c("Species","variable"),function(df){
data.frame(
"min"=min(df$value),
"max"=max(df$value)
)
})
#------------------------------------------------------------
</code></pre> | 24,328,604 | 1 | 1 | null | 2014-06-18 09:57:13.81 UTC | 7 | 2018-11-27 05:38:20.263 UTC | null | null | null | null | 1,409,652 | null | 1 | 50 | r|aggregate-functions|reshape2 | 90,695 | <p>You get this warning because the min/max are applied to numeric of length 0 argument.</p>
<p>This reproduces the warning.</p>
<pre><code>min(numeric(0))
[1] Inf
Warning message:
In min(numeric(0)) : no non-missing arguments to min; returning Inf
</code></pre>
<p>Note that for <code>mean</code> you don't get the warning :</p>
<pre><code>mean(numeric(0))
[1] NaN
</code></pre>
<p>It is just a warning that don't have any effect in the computation. You can suppress it using <code>suppressWarnings</code>:</p>
<pre><code> suppressWarnings(dcast(data=molten.iris,
Species~variable,value.var="value",
fun.aggregate=min))
</code></pre>
<h2>EDIT</h2>
<p>Above I am just answering the question: What's the meaning of the warning ? and why we have this min/max and not with mean function. The question why <code>dcast</code> is applying the aggregate function to a vector of length 0, it is just a BUG and you should contact the package maintainer. I think the error comes from <code>plyr::vaggregate</code> function used internally by <code>dcast</code>,</p>
<pre><code>plyr::vaggregate(1:3,1:3,min)
Error in .fun(.value[0], ...) :
(converted from warning) no non-missing arguments to min; returning Inf
</code></pre>
<p>Specially this line of code:</p>
<pre><code>plyr::vaggregate
function (.value, .group, .fun, ..., .default = NULL, .n = nlevels(.group))
{
### some lines
....
### Here I don't understand the meaning of .value[0]
### since vector in R starts from 1 not zeros!!!
if (is.null(.default)) {
.default <- .fun(.value[0], ...)
}
## the rest of the function
.....
}
</code></pre> |
24,309,526 | How to change the docker image installation directory? | <p>From what I can tell, docker images are installed to <code>/var/lib/docker</code> as they are pulled. Is there a way to change this location, such as to a mounted volume like <code>/mnt</code>?</p> | 24,312,133 | 19 | 2 | null | 2014-06-19 14:49:02.847 UTC | 109 | 2021-11-11 06:02:45.83 UTC | 2014-11-20 20:18:17.303 UTC | null | 209,050 | null | 91,144 | null | 1 | 253 | docker | 193,072 | <p>With recent versions of Docker, you would set the value of the <code>data-root</code> parameter to your custom path, in <code>/etc/docker/daemon.json</code>
(according to <a href="https://docs.docker.com/engine/reference/commandline/dockerd/#daemon-configuration-file" rel="noreferrer">https://docs.docker.com/engine/reference/commandline/dockerd/#daemon-configuration-file</a>).</p>
<p>With older versions, you can change Docker's storage base directory (where container and images go) using the <code>-g</code>option when starting the Docker daemon. (check <code>docker --help</code>).
You can have this setting applied automatically when Docker starts by adding it to <strong>/etc/default/docker</strong></p> |
21,890,338 | When should one use RxJava Observable and when simple Callback on Android? | <p>I'm working on networking for my app. So I decided to try out Square's <a href="https://github.com/square/retrofit" rel="noreferrer">Retrofit</a>. I see that they support simple <code>Callback</code></p>
<pre><code>@GET("/user/{id}/photo")
void getUserPhoto(@Path("id") int id, Callback<Photo> cb);
</code></pre>
<p>and RxJava's <code>Observable</code></p>
<pre><code>@GET("/user/{id}/photo")
Observable<Photo> getUserPhoto(@Path("id") int id);
</code></pre>
<p>Both look pretty similar at first glance, but when it gets to implementation it gets interesting...</p>
<p>While with simple callback implementation would look similar to this:</p>
<pre><code>api.getUserPhoto(photoId, new Callback<Photo>() {
@Override
public void onSuccess() {
}
});
</code></pre>
<p>which is quite simple and straightforward. And with <code>Observable</code> it quickly gets verbose and quite complicated.</p>
<pre><code>public Observable<Photo> getUserPhoto(final int photoId) {
return Observable.create(new Observable.OnSubscribeFunc<Photo>() {
@Override
public Subscription onSubscribe(Observer<? super Photo> observer) {
try {
observer.onNext(api.getUserPhoto(photoId));
observer.onCompleted();
} catch (Exception e) {
observer.onError(e);
}
return Subscriptions.empty();
}
}).subscribeOn(Schedulers.threadPoolForIO());
}
</code></pre>
<p>And that is not it. You still have to do something like this:</p>
<pre><code>Observable.from(photoIdArray)
.mapMany(new Func1<String, Observable<Photo>>() {
@Override
public Observable<Photo> call(Integer s) {
return getUserPhoto(s);
}
})
.subscribeOn(Schedulers.threadPoolForIO())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<Photo>() {
@Override
public void call(Photo photo) {
//save photo?
}
});
</code></pre>
<p>Am I missing something here? Or is this a wrong case to use <code>Observable</code>s?
When would/should one prefer <code>Observable</code> over simple Callback?</p>
<h2>Update</h2>
<p>Using retrofit is much simpler than example above as @Niels showed in his answer or in Jake Wharton's example project <a href="https://github.com/JakeWharton/u2020" rel="noreferrer">U2020</a>. But essentially the question stays the same - when should one use one way or the other?</p> | 29,918,329 | 9 | 3 | null | 2014-02-19 19:25:04.543 UTC | 187 | 2022-08-18 07:09:01.92 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 385,219 | null | 1 | 268 | android|retrofit|rx-java | 95,058 | <p>For simple networking stuff, the advantages of RxJava over Callback is very limited. The simple getUserPhoto example:</p>
<p><strong>RxJava:</strong></p>
<pre><code>api.getUserPhoto(photoId)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<Photo>() {
@Override
public void call(Photo photo) {
// do some stuff with your photo
}
});
</code></pre>
<p><strong>Callback:</strong></p>
<pre><code>api.getUserPhoto(photoId, new Callback<Photo>() {
@Override
public void onSuccess(Photo photo, Response response) {
}
});
</code></pre>
<p>The RxJava variant is not much better than the Callback variant. For now, let's ignore the error handling.
Let's take a list of photos:</p>
<p><strong>RxJava:</strong></p>
<pre><code>api.getUserPhotos(userId)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.flatMap(new Func1<List<Photo>, Observable<Photo>>() {
@Override
public Observable<Photo> call(List<Photo> photos) {
return Observable.from(photos);
}
})
.filter(new Func1<Photo, Boolean>() {
@Override
public Boolean call(Photo photo) {
return photo.isPNG();
}
})
.subscribe(
new Action1<Photo>() {
@Override
public void call(Photo photo) {
list.add(photo)
}
});
</code></pre>
<p><strong>Callback:</strong></p>
<pre><code>api.getUserPhotos(userId, new Callback<List<Photo>>() {
@Override
public void onSuccess(List<Photo> photos, Response response) {
List<Photo> filteredPhotos = new ArrayList<Photo>();
for(Photo photo: photos) {
if(photo.isPNG()) {
filteredList.add(photo);
}
}
}
});
</code></pre>
<p>Now, the RxJava variant still isn't smaller, although with Lambdas it would be getter closer to the Callback variant.
Furthermore, if you have access to the JSON feed, it would be kind of weird to retrieve all photos when you're only displaying the PNGs. Just adjust the feed to it only displays PNGs.</p>
<p><em>First conclusion</em> </p>
<p>It doesn't make your codebase smaller when you're loading a simple JSON that you prepared to be in the right format.</p>
<p>Now, let's make things a bit more interesting. Let's say you not only want to retrieve the userPhoto, but you have an Instagram-clone, and you want to retrieve 2 JSONs:
1. getUserDetails()
2. getUserPhotos()</p>
<p>You want to load these two JSONs in parallel, and when both are loaded, the page should be displayed.
The callback variant will become a bit more difficult: you have to create 2 callbacks, store the data in the activity, and if all the data is loaded, display the page:</p>
<p><strong>Callback:</strong></p>
<pre><code>api.getUserDetails(userId, new Callback<UserDetails>() {
@Override
public void onSuccess(UserDetails details, Response response) {
this.details = details;
if(this.photos != null) {
displayPage();
}
}
});
api.getUserPhotos(userId, new Callback<List<Photo>>() {
@Override
public void onSuccess(List<Photo> photos, Response response) {
this.photos = photos;
if(this.details != null) {
displayPage();
}
}
});
</code></pre>
<p><strong>RxJava:</strong></p>
<pre><code>private class Combined {
UserDetails details;
List<Photo> photos;
}
Observable.zip(api.getUserDetails(userId), api.getUserPhotos(userId), new Func2<UserDetails, List<Photo>, Combined>() {
@Override
public Combined call(UserDetails details, List<Photo> photos) {
Combined r = new Combined();
r.details = details;
r.photos = photos;
return r;
}
}).subscribe(new Action1<Combined>() {
@Override
public void call(Combined combined) {
}
});
</code></pre>
<p>We are getting somewhere! The code of RxJava is now as big as the callback option. The RxJava code is more robust;
Think of what would happen if we needed a third JSON to be loaded (like the latest Videos)? The RxJava would only need a tiny adjustment, while the Callback variant needs to be adjusted in multiple places (on each callback we need to check if all data is retrieved).</p>
<p>Another example; we want to create an autocomplete field, which loads data using Retrofit.
We don't want to do a webcall every time an EditText has a TextChangedEvent. When typing fast, only the last element should trigger the call.
On RxJava we can use the debounce operator:</p>
<pre><code>inputObservable.debounce(1, TimeUnit.SECONDS).subscribe(new Action1<String>() {
@Override
public void call(String s) {
// use Retrofit to create autocompletedata
}
});
</code></pre>
<p>I won't create the Callback variant but you will understand this is much more work.</p>
<p>Conclusion:
RxJava is exceptionally good when data is sent as a stream. The Retrofit Observable pushes all elements on the stream at the same time.
This isn't particularly useful in itself compared to Callback. But when there are multiple elements pushed on the stream and different times, and you need to do timing-related stuff, RxJava makes the code a lot more maintainable.</p> |
1,432,213 | Copy file on a network shared drive | <p>I have a network shared drive ("\serveur\folder") on which I would like to copy file.
I can write on the drive with a specific user ("user"/"pass").
How can I access the shared drived with write privilege using C#?</p> | 1,432,259 | 4 | 0 | null | 2009-09-16 10:41:29.79 UTC | 23 | 2020-03-20 10:48:50.923 UTC | 2013-07-22 16:27:07.573 UTC | null | 1,677,912 | null | 118,125 | null | 1 | 24 | c#|authentication|network-drive | 92,728 | <p>Untested code, but it will be similiar to:</p>
<pre><code>AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
// http://pinvoke.net/default.aspx/advapi32/LogonUser.html
IntPtr token;
LogonUser("username", "domain", "password", LogonType.LOGON32_LOGON_BATCH, LogonProvider.LOGON32_PROVIDER_DEFAULT);
WindowsIdentity identity = new WindowsIdentity(token);
WindowsImpersonationContext context = identity.Impersonate();
try
{
File.Copy(@"c:\temp\MyFile.txt", @"\\server\folder\Myfile.txt", true);
}
finally
{
context.Undo();
}
</code></pre> |
1,641,507 | Detect browser support for cross-domain XMLHttpRequests? | <p>I'm working on some Javascript that makes use of Firefox 3.5's ability to perform cross-domain XMLHttpRequests… But I'd like to fail gracefully if they aren't supported.</p>
<p>Apart from actually making a cross-domain request, is there any way to detect a browser's support for them?</p> | 7,616,755 | 4 | 0 | null | 2009-10-29 03:46:28.073 UTC | 12 | 2013-08-06 09:33:54.123 UTC | null | null | null | null | 71,522 | null | 1 | 43 | javascript|xmlhttprequest|cross-domain | 15,846 | <p>For future reference, full CORS feature detection should look something like this:</p>
<pre><code>//Detect browser support for CORS
if ('withCredentials' in new XMLHttpRequest()) {
/* supports cross-domain requests */
document.write("CORS supported (XHR)");
}
else if(typeof XDomainRequest !== "undefined"){
//Use IE-specific "CORS" code with XDR
document.write("CORS supported (XDR)");
}else{
//Time to retreat with a fallback or polyfill
document.write("No CORS Support!");
}
</code></pre>
<p>You can <a href="http://jsbin.com/ohugih/8/edit">try this test live using JSBin</a> and see the proper response in IE, Firefox, Chrome, Safari, and Opera. </p>
<p>There are some edge cases in non-browser environments that <em>do support</em> cross-domain XHR but not XHR2/CORS. This test does not account for those situations.</p> |
1,773,985 | How do I modify an array while I am iterating over it in Ruby? | <p>I'm just learning Ruby so apologies if this is too newbie for around here, but I can't work this out from the pickaxe book (probably just not reading carefully enough).
Anyway, if I have an array like so:</p>
<pre><code>arr = [1,2,3,4,5]
</code></pre>
<p>...and I want to, say, multiply each value in the array by 3, I have worked out that doing the following:</p>
<pre><code>arr.each {|item| item *= 3}
</code></pre>
<p>...will not get me what I want (and I understand why, I'm not modifying the array itself).</p>
<p>What I don't get is how to modify the original array from inside the code block after the iterator. I'm sure this is very easy.</p> | 1,773,995 | 4 | 0 | null | 2009-11-21 00:07:20.043 UTC | 13 | 2021-11-26 02:49:36.9 UTC | 2012-02-28 21:08:57.603 UTC | null | 590,783 | null | 215,895 | null | 1 | 92 | ruby|arrays|iteration | 71,803 | <p>Use <code>map</code> to create a new array from the old one:</p>
<pre><code>arr2 = arr.map {|item| item * 3}
</code></pre>
<p>Use <code>map!</code> to modify the array in place:</p>
<pre><code>arr.map! {|item| item * 3}
</code></pre>
<p>See it working online: <a href="http://ideone.com/SVhrK" rel="noreferrer">ideone</a></p> |
1,869,753 | Maximum size for a SQL Server Query? IN clause? Is there a Better Approach | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/1069415/t-sql-where-col-in">T-SQL WHERE col IN (…)</a> </p>
</blockquote>
<p>What is the maximum size for a SQL Server query? (# of characters)</p>
<p>Max size for an IN clause? I think I saw something about Oracle having a 1000 item limit but you could get around this with ANDing 2 INs together. Similar issue in SQL Server?</p>
<p><strong>UPDATE</strong>
So what would be the best approach if I need to take say 1000 GUIDs from another system (Non Relational Database) and do a "JOIN in code' against the SQL Server? Is it to submit the list of 1000 GUIDs to an IN clause?
Or is there another technique that works more efficiently?</p>
<p>I haven't tested this but I wonder if I could submit the GUIDs as an XML doc. For example </p>
<pre><code><guids>
<guid>809674df-1c22-46eb-bf9a-33dc78beb44a</guid>
<guid>257f537f-9c6b-4f14-a90c-ee613b4287f3</guid>
</guids>
</code></pre>
<p>and then do some kind of XQuery JOIN against the Doc and the Table. Less efficient than 1000 item IN clause?</p> | 1,869,810 | 4 | 3 | null | 2009-12-08 20:52:11.227 UTC | 27 | 2012-08-31 14:39:12 UTC | 2017-05-23 12:10:32.503 UTC | null | -1 | null | 36,590 | null | 1 | 103 | sql|sql-server|tsql|limits | 214,406 | <p>Every SQL batch has to fit in the <a href="http://msdn.microsoft.com/en-us/library/ms143432.aspx" rel="noreferrer">Batch Size Limit</a>: 65,536 * Network Packet Size.</p>
<p>Other than that, your query is limited by runtime conditions. It will usually run out of stack size because x IN (a,b,c) is nothing but x=a OR x=b OR x=c which creates an expression tree similar to x=a OR (x=b OR (x=c)), so it gets very deep with a large number of OR. SQL 7 would hit a SO <a href="http://support.microsoft.com/kb/288095" rel="noreferrer">at about 10k values in the IN</a>, but nowdays stacks are much deeper (because of x64), so it can go pretty deep.</p>
<p><strong>Update</strong></p>
<p>You already found Erland's article on the topic of passing lists/arrays to SQL Server. With SQL 2008 you also have <a href="http://msdn.microsoft.com/en-us/library/bb675163.aspx" rel="noreferrer">Table Valued Parameters</a> which allow you to pass an entire DataTable as a single table type parameter and join on it. </p>
<p>XML and XPath is another viable solution:</p>
<pre><code>SELECT ...
FROM Table
JOIN (
SELECT x.value(N'.',N'uniqueidentifier') as guid
FROM @values.nodes(N'/guids/guid') t(x)) as guids
ON Table.guid = guids.guid;
</code></pre> |
42,798,967 | How to subtract strings in python | <p>Basically, if I have a string <code>'AJ'</code> and another string <code>'AJYF'</code>, I would like to be able to write <code>'AJYF'-'AJ'</code> and get <code>'YF'</code>.</p>
<p>I tried this but got a syntax error.</p>
<p>Just on a side note the subtractor will always will be shorter than the string it is subtracted from. Also, the subtractor will always be like the string it is subtracted from. For instance, if I have 'GTYF' and I want to subtract a string of length 3 from it, that string has to be 'GTY'.</p>
<p>If it is possible, the full function I am trying to do is convert a string to a list based on how long each item in the list is supposed to be. Is there any way of doing that?</p> | 42,799,036 | 5 | 13 | null | 2017-03-15 00:19:24.14 UTC | 5 | 2022-09-01 06:16:15.827 UTC | 2021-06-18 11:32:48.807 UTC | null | 792,066 | null | 7,454,274 | null | 1 | 38 | python | 111,887 | <p>Easy Solution is:</p>
<pre><code>>>> string1 = 'AJYF'
>>> string2 = 'AJ'
>>> if string2 in string1:
... string1.replace(string2,'')
'YF'
>>>
</code></pre> |
49,527,483 | Are infinite std::chrono::duration objects legal? | <p>Is it legal to make and use <code>std::chrono::duration<double></code>'s with an infinity as the contained value, like so?</p>
<pre><code>std::chrono::duration<double>{ std::numeric_limits<double>::infinity() };
</code></pre>
<p>Will it behave 'like I expect', keeping an infinite value when adding or subtracting with other durations?</p>
<p>I've dug through cppreference but the only thing I've found discussing the question is the page on <code>duration_cast</code> noting that:</p>
<blockquote>
<p>Casting from a floating-point duration to an integer duration is subject to undefined behavior when the floating-point value is NaN, infinity, or too large to be representable by the target's integer type. Otherwise, casting to an integer duration is subject to truncation as with any static_cast to an integer type.</p>
</blockquote>
<p>which seems to imply that it's legal, but only in a backhanded sort of way.</p>
<p>(I'm using the type to represent a "Please wake me up in X seconds" way, and positive infinity is a useful sentinel to represent "I really don't care when I wake up")</p> | 49,528,712 | 2 | 5 | null | 2018-03-28 06:24:24.64 UTC | 3 | 2018-03-28 07:56:25.9 UTC | 2018-03-28 06:29:43.337 UTC | null | 440,558 | null | 5,557,309 | null | 1 | 29 | c++|c++11|language-lawyer|chrono | 3,915 | <p>The value <code>infinity</code> for <code>std::chrono::duration<double></code> will behave as you expect with arithmetic operators.</p>
<h3><code>std::chrono::duration<double></code> is perfectly fine</h3>
<p><a href="http://eel.is/c++draft/time.duration" rel="noreferrer">[time.duration]</a> defines the conditions existing on <code>Rep</code> for <code>template<class Rep> std::chrono::duration</code> and <code>double</code> is explicitly allowed (per <a href="http://eel.is/c++draft/time.duration#2.sentence-1" rel="noreferrer">[time.duration]/2</a>), no special value disallowed:</p>
<blockquote>
<p><code>Rep</code> shall be an arithmetic type or a class emulating an arithmetic type. </p>
</blockquote>
<h3><code>std::numeric_limits<double>::infinity()</code> is perfectly fine</h3>
<p><a href="http://eel.is/c++draft/time.duration.arithmetic" rel="noreferrer">[time.duration.arithmetic]</a> and <a href="http://eel.is/c++draft/time.duration.nonmember" rel="noreferrer">[time.duration.nonmemberdefine]</a> define the behaviour of the arithmetic operators on <code>duration</code>. For each <code>operator♦</code> and given two <code>duration</code> objects <code>A</code> and <code>B</code> holding the <code>double</code> values <code>a</code> and <code>b</code>, <code>A♦B</code> effects as <code>a♦b</code> would. For instance for <code>+</code>:</p>
<blockquote>
<p>In the function descriptions that follow, <code>CD</code> represents the return type of the function. <code>CR(A, B)</code> represents <code>common_type_t<A, B></code>.</p>
<pre><code>template<class Rep1, class Period1, class Rep2, class Period2>
constexpr common_type_t<duration<Rep1, Period1>, duration<Rep2, Period2>>
operator+(const duration<Rep1, Period1>& lhs, const duration<Rep2, Period2>& rhs);
</code></pre>
<p><em>Returns: <code>CD(CD(lhs).count() + CD(rhs).count())</code>.</em></p>
</blockquote>
<p>This explicitly means that the following will behave as expected:</p>
<pre><code>const double infinity = std::numeric_limits<double>::infinity();
std::chrono::duration<double> inf{ infinity };
std::chrono::duration<double> one{ 1.0 };
inf + one; // as if std::chrono::duration<double>{ infinity + 1.0 };
</code></pre> |
10,470,742 | Define 'valid mp3 chunk' for decodeAudioData (WebAudio API) | <p>I'm trying to use decodeAudioData to decode and play back an initial portion of a larger mp3 file, in javascript. My first, crude, approach was slicing a number of bytes off the beginning of the mp3 and feeding them to decodeAudioData. Not surprisingly this fails.</p>
<p>After some digging it seems that decodeAudioData is only able to work with 'valid mp3 chunks' as documented by <a href="https://stackoverflow.com/users/218471/fair-dinkum-thinkum">Fair Dinkum Thinkum</a>, <a href="https://stackoverflow.com/questions/8759842/how-to-stream-mp3-data-via-websockets-with-node-js-and-socket-io">here</a>.</p>
<p>However there is no clarification about the structure of a valid mp3 chunk (the author of the aforementioned doesn't go into this). I am aware of the various mp3 splitters that exist out there but i'd like to approach this programmatically. (I'm trying to implement a kind of 'poor man's streaming' using nodejs on the server side).</p>
<p>So, would splitting on mp3 frame headers be enough or do I need to do more? (perhaps 'closing' every chunk by appending some data at the end?) How about the 'byte reservoir'? Would this cause problems? For the record, I'm currently working with 128kbps cbr mp3s. Would this simplify the process in any way?</p>
<p>Any info on what decodeAudioData expects as vaild data would be appreciated.</p>
<p>Thank you.</p>
<p>PS: I realise that this is perhaps a request for clarification on Fair Dinkum Thinkum's <a href="https://stackoverflow.com/questions/8759842/how-to-stream-mp3-data-via-websockets-with-node-js-and-socket-io">post</a> but my low reputation is keeping me from posting a comment. So I can't see how else to do it but with a new question. Thanks again.</p> | 13,315,068 | 2 | 2 | null | 2012-05-06 13:06:04.68 UTC | 11 | 2022-02-16 08:10:09.57 UTC | 2017-05-23 11:48:29.607 UTC | null | -1 | null | 612,262 | null | 1 | 13 | javascript|mp3|web-audio-api | 7,052 | <p>After more experimentation with decodeAudioData (on Chrome) this is what I've found:</p>
<ul>
<li>Any <em>initial</em> mp3 chunk will be successfully decoded as long as it is split on an mp3 frame boundary. Finding that boundary may not always be trivial (e.g. involve parsing mp3 headers) as even constant bitrate mp3s don't always contain constant-size frames. For example, 128kbps mp3 files contain 417-byte frames as well as 418-byte frames. (some frames contain an extra byte as padding).</li>
<li>An arbitrary mp3 chunk is <em>not</em> guaranteed to be decodable even if split on exact frame boundaries on 'both sides'. Some chunks of this sort can be decoded but others cause decodeAudioData to throw an error. I'm guessing this has to do with <a href="http://wiki.hydrogenaudio.org/index.php?title=Bit_reservoir" rel="noreferrer">mp3 bit reservoir</a> which creates a dependency between mp3 frames.</li>
</ul> |
10,430,043 | Difference between "char" and "String" in Java | <p>I am reading a book for Java that I am trying to learn, and I have a question. I can't understand what is the difference between the variable type <code>char</code> and <code>String</code>. For example, there is a difference between <code>int</code> and <code>short</code>, the bytes at the memory and the area of numbers that they have.</p>
<p>But what is the difference between <code>char</code> and <code>String</code>? except that <code>char</code> use (') and "String" (").</p>
<p>PS: It is my first "real" programming language. (At school I learned a fake-language for the purpose of the programming lesson.)</p> | 10,430,082 | 14 | 2 | null | 2012-05-03 11:02:54.793 UTC | 37 | 2020-11-24 19:39:23.787 UTC | 2017-02-16 16:23:39.937 UTC | null | 5,738,837 | null | 1,181,992 | null | 1 | 60 | java|string|char | 298,779 | <p><code>char</code> is one character. <code>String</code> is zero or more characters.</p>
<p><code>char</code> is a primitive type. <code>String</code> is a class.</p>
<pre><code>char c = 'a';
String s = "Hi!";
</code></pre>
<p>Note the single quotes for <code>char</code>, and double quotes for <code>String</code>. </p> |
28,413,756 | ASP.NET 5 add WCF service reference | <p>In Visual Studio 2015 Preview (Pre Release), how can I add a service reference for a <code>WCF</code> service? </p> | 28,440,491 | 6 | 2 | null | 2015-02-09 15:53:23.403 UTC | 11 | 2021-07-23 16:12:31.587 UTC | 2015-05-22 18:52:44.353 UTC | null | 998,328 | null | 1,221,847 | null | 1 | 28 | c#|asp.net|wcf|asp.net-core|visual-studio-2015 | 36,535 | <p>Currently, this is a fairly involved process as the tooling does not seem to support much in the way of generating WCF client code or automatically map from config files. Also, as dotnetstep has pointed out, the ASP.NET team has not ported <code>System.ServiceModel</code> to 5 yet (or provided an alternative for WCF clients <em>yet</em>). Nonetheless, we can use a code-based approach to create a client proxy and use <a href="https://msdn.microsoft.com/en-us/library/aa347733%28v=vs.110%29.aspx" rel="noreferrer"><code>svcutil</code></a> to generate our service reference classes.</p>
<h2>Solution Prerequisites</h2>
<p>For this example, I will assume you are locally hosting a service at <a href="http://localhost:5000/MapService.svc" rel="noreferrer">http://localhost:5000/MapService.svc</a> that implements an <code>IMapService</code> contract. Also, we will call the project that is going to contain the service proxy <code>MapClient</code>.</p>
<p>Your <code>project.json</code> should look something like:</p>
<pre class="lang-json prettyprint-override"><code>{
"commands": {
"run": "run"
},
"frameworks": {
"dnx451": {
"dependencies": {
"Microsoft.AspNet.Mvc": "6.0.0-beta2"
},
"frameworkAssemblies": {
"System.ServiceModel": "4.0.0.0"
}
}
}
}
</code></pre>
<h2>Generate the Service Reference Classes</h2>
<p>First, let's create a folder, <code>Service References</code>, in the <code>MapClient</code> project.</p>
<p>Next, open up <em>Developer Command Prompt for VS2015</em> and navigate to your <code>MapClient</code> project directory:</p>
<pre><code>cd "C:\Users\youraccount\Documents\Visual Studio 2015\Projects\MapClient\src\MapClient"
</code></pre>
<p>Make sure <code>MapService</code> is running and run the following command:</p>
<pre><code>svcutil /language:cs /out:"Service References\MapServiceReference.cs" http://localhost:5000/MapService.svc
</code></pre>
<p>That should generate two files, <code>output.config</code> and <code>MapServiceReference.cs</code>. </p>
<h2>Create a code-based client proxy</h2>
<p>Since there is no way to <em>automagically</em> map endpoint and binding configuration from a config file to your <code>ClientBase</code> currently in ASP.NET 5, the <code>output.config</code> isn't of much use to us. You can remove it.</p>
<p>Instead, let's create a client proxy in the code:</p>
<pre class="lang-cs prettyprint-override"><code>using System.ServiceModel;
namespace TestWCFReference
{
public class Program
{
public void Main(string[] args)
{
var endpointUrl = "http://localhost:5000/MapService.svc";
BasicHttpBinding binding = new BasicHttpBinding();
EndpointAddress endpoint = new EndpointAddress(endpointUrl);
ChannelFactory<IMapService> channelFactory = new ChannelFactory<IMapService>(binding, endpoint);
IMapService clientProxy = channelFactory.CreateChannel();
var map = clientProxy.GetMap();
channelFactory.Close();
}
}
}
</code></pre>
<p>Now you can use the <code>clientProxy</code> instance to access any Operation Contract in <code>IMapService</code>.</p>
<p>As a sidenote, it would probably be better architecture to create a key:value config file that stores your binding and endpoint configuration and use the <a href="https://github.com/aspnet/Configuration/blob/dev/src/Microsoft.Framework.ConfigurationModel/Configuration.cs" rel="noreferrer"><code>Microsoft.Framework.ConfigurationModel.Configuration</code></a> object to populate your <code>ChannelFactory</code> so you can keep your service configuration out of your code, but hopefully this example will get you started.</p> |
36,609,998 | Angular 2 and TypeScript Promises | <p>I'm trying to use the <code>routerCanDeactivate</code> function for a component in my app. The simple way to use it is as follows: </p>
<pre><code>routerCanDeactivate() {
return confirm('Are you sure you want to leave this screen?');
}
</code></pre>
<p>My only issue with this is that it's ugly. It just uses a browser generated confirm prompt. I really want to use a custom modal, like a Bootstrap modal. I have the Bootstrap modal returning a true or false value based on the button they click. The <code>routerCanDeactivate</code> I'm implementing can accept a true/false value or a promise that resolves to true/false. </p>
<p>Here is the code for the component that has the <code>routerCanDeactivate</code> method:</p>
<pre><code>export class MyComponent implements CanDeactivate {
private promise: Promise<boolean>;
routerCanDeactivate() {
$('#modal').modal('show');
return this.promise;
}
handleRespone(res: boolean) {
if(res) {
this.promise.resolve(res);
} else {
this.promise.reject(res);
}
}
}
</code></pre>
<p>When my TypeScript files compile, I get the following errors in the terminal: </p>
<pre><code>error TS2339: Property 'resolve' does not exist on type 'Promise<boolean>'.
error TS2339: Property 'reject' does not exist on type 'Promise<boolean>'.
</code></pre>
<p>When I try to leave the component, the modal starts, but then the component deactivates and doesn't wait for the promise to resolve. </p>
<p>My issue is trying to work out the Promise so that the <code>routerCanDeactivate</code> method waits for the promise to resolve. Is there a reason why there is an error saying that there is no <code>'resolve'</code> property on <code>Promise<boolean></code>? If I can work that part out, what must I return in the <code>routerCanDeactivate</code> method so that it waits for the resolution/rejection of the promise?</p>
<p>For reference, <a href="https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/es6-promise/es6-promise.d.ts">here is the DefinitelyTyped Promise definition</a>. There is clearly a resolve and reject function on there.</p>
<p>Thanks for your help.</p>
<p><strong>UPDATE</strong></p>
<p>Here is the updated file, with the Promise being initialized:</p>
<pre><code>private promise: Promise<boolean> = new Promise(
( resolve: (res: boolean)=> void, reject: (res: boolean)=> void) => {
const res: boolean = false;
resolve(res);
}
);
</code></pre>
<p>and the <code>handleResponse</code> function: </p>
<pre><code>handleResponse(res: boolean) {
console.log('res: ', res);
this.promise.then(res => {
console.log('res: ', res);
});
}
</code></pre>
<p>It still doesn't work correctly, but the modal shows up and waits for the response. When you say yes leave, it stays on the component. Also, the first <code>res</code> that is logged is the correct value returned from the component, but the one inside <code>.then</code> function is not the same as the one passed in to the <code>handleResponse</code> function.</p>
<p><strong><em>More Updates</em></strong></p>
<p>After doing some more reading, it appears that in the <code>promise</code> declaration, it sets the <code>resolve</code> value, and the <code>promise</code> has that value no matter what. So even though later on I call the <code>.then</code> method, it doesn't change the value of the <code>promise</code> and I can't make it true and switch components. Is there a way to make the <code>promise</code> not have a default value and that it has to wait until the its <code>.then</code> method is invoked?</p>
<p>Updated functions:</p>
<pre><code>private promise: Promise<boolean> = new Promise((resolve, reject) => resolve(false) );
handleResponse(res: any) {
this.promise.then(val => {
val = res;
});
}
</code></pre>
<p>Thanks again for the help.</p>
<p><strong><em>Last Update</em></strong></p>
<p>After looking at many suggestions, I decided to create a <code>Deferred</code> class. It's worked pretty well, but when I do the <code>deferred.reject(anyType)</code>, I get an error in the console of:</p>
<pre><code>EXCEPTION: Error: Uncaught (in promise): null
</code></pre>
<p>This same thing happens when I pass in <code>null</code>, a <code>string</code>, or a <code>boolean</code>. Trying to provide a <code>catch</code> function in the <code>Deferred</code> class didn't work.</p>
<p><strong><em>Deferred Class</em></strong></p>
<pre><code>export class Deferred<T> {
promise: Promise<T>;
resolve: (value?: T | PromiseLike<T>) => void;
reject: (reason?: any) => void;
constructor() {
this.promise = new Promise<T>((resolve, reject) => {
this.resolve = resolve;
this.reject = reject;
});
}
}
</code></pre> | 36,611,901 | 5 | 7 | null | 2016-04-13 21:35:01.207 UTC | 6 | 2017-05-25 04:52:49.33 UTC | 2016-04-14 16:05:37.39 UTC | null | 2,242,564 | null | 2,242,564 | null | 1 | 27 | typescript|angular | 71,707 | <p>I'm not familiar with the bootstrap modal api, but I'd expect there to be a way to bind to a close event somehow when creating it.</p>
<pre><code>export class MyComponent implements CanDeactivate {
routerCanDeactivate(): Promise<boolean> {
let $modal = $('#modal').modal();
return new Promise<boolean>((resolve, reject) => {
$modal.on("hidden.bs.modal", result => {
resolve(result.ok);
});
$modal.modal("show");
});
}
}
</code></pre>
<p>You're trying to use the <code>Promise</code> like <code>Deferred</code>. If you want that kind of API, write yourself a <code>Deferred</code> class.</p>
<pre><code>class Deferred<T> {
promise: Promise<T>;
resolve: (value?: T | PromiseLike<T>) => void;
reject: (reason?: any) => void;
constructor() {
this.promise = new Promise<T>((resolve, reject) => {
this.resolve = resolve;
this.reject = reject;
});
}
}
export class MyComponent implements CanDeactivate {
private deferred = new Deferred<boolean>();
routerCanDeactivate(): Promise<boolean> {
$("#modal").modal("show");
return this.deferred.promise;
}
handleRespone(res: boolean): void {
if (res) {
this.deferred.resolve(res);
} else {
this.deferred.reject(res);
}
}
}
</code></pre> |
7,642,000 | downto vs. to in VHDL | <p>I'm not sure I understand the difference between 'downto' vs. 'to' in vhdl.</p>
<p>I've seen some online explanations, but I still don't think I understand. Can anyone lay it out for me?</p> | 7,642,026 | 7 | 0 | null | 2011-10-04 00:03:19.29 UTC | 4 | 2019-03-01 15:35:27.703 UTC | null | null | null | null | 690,469 | null | 1 | 20 | vhdl | 67,458 | <p>One goes up, one goes down:</p>
<pre><code>-- gives 0, 1, 2, 3:
for i in 0 to 3 loop
-- gives 3, 2, 1, 0:
for i in 3 downto 0 loop
</code></pre> |
7,046,539 | if (device == iPad), if (device == iPhone) | <p>So I have a universal app and I'm setting up the content size of a <code>UIScrollView</code>. Obviously the content size is going to be different on iPhones and iPads. How can I set a certain size for iPads and another size for iPhones and iPod touches?</p> | 7,046,605 | 7 | 1 | null | 2011-08-12 21:32:11.993 UTC | 6 | 2017-07-07 11:41:19.807 UTC | null | null | null | null | 516,833 | null | 1 | 30 | objective-c|ios|xcode|uiscrollview | 25,634 | <pre><code>if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
{
// The device is an iPad running iOS 3.2 or later.
}
else
{
// The device is an iPhone or iPod touch.
}
</code></pre> |
7,451,070 | Calling a PHP function by onclick event | <p>I am trying to call a function by "onclick" event of the button.
When I do that it shows error message.
Can anybody help me out on this so that when I click on the button it should call the function and execute it.</p>
<p><strong>My PHP code is:</strong></p>
<pre><code><?php
function hello() {
echo "Hello";
}
echo "<input type='button' name='Release' onclick= hello(); value='Click to Release'>";
?>
</code></pre>
<p>What is wrong with this code?</p> | 7,451,081 | 9 | 2 | null | 2011-09-16 22:39:51.683 UTC | 6 | 2021-08-28 00:06:15.653 UTC | 2021-08-21 16:15:29.277 UTC | null | 16,316,260 | user946103 | null | null | 1 | 6 | php|function | 196,425 | <p>First quote your JavaScript:</p>
<pre><code>onclick="hello();"
</code></pre>
<p>Also you can't call a PHP function from JavaScript;
you need:</p>
<pre><code><script type="text/javascript">
function hello()
{
alert ("hello");
}
</script>
</code></pre> |
7,031,126 | Switching between GCC and Clang/LLVM using CMake | <p>I have a number of projects built using CMake and I'd like to be able to easily switch between using GCC or Clang/LLVM to compile them. I believe (please correct me if I'm mistaken!) that to use Clang I need to set the following:</p>
<pre><code> SET (CMAKE_C_COMPILER "/usr/bin/clang")
SET (CMAKE_C_FLAGS "-Wall -std=c99")
SET (CMAKE_C_FLAGS_DEBUG "-g")
SET (CMAKE_C_FLAGS_MINSIZEREL "-Os -DNDEBUG")
SET (CMAKE_C_FLAGS_RELEASE "-O4 -DNDEBUG")
SET (CMAKE_C_FLAGS_RELWITHDEBINFO "-O2 -g")
SET (CMAKE_CXX_COMPILER "/usr/bin/clang++")
SET (CMAKE_CXX_FLAGS "-Wall")
SET (CMAKE_CXX_FLAGS_DEBUG "-g")
SET (CMAKE_CXX_FLAGS_MINSIZEREL "-Os -DNDEBUG")
SET (CMAKE_CXX_FLAGS_RELEASE "-O4 -DNDEBUG")
SET (CMAKE_CXX_FLAGS_RELWITHDEBINFO "-O2 -g")
SET (CMAKE_AR "/usr/bin/llvm-ar")
SET (CMAKE_LINKER "/usr/bin/llvm-ld")
SET (CMAKE_NM "/usr/bin/llvm-nm")
SET (CMAKE_OBJDUMP "/usr/bin/llvm-objdump")
SET (CMAKE_RANLIB "/usr/bin/llvm-ranlib")
</code></pre>
<p>Is there an easy way of switching between these and the default GCC variables, preferably as a system-wide change rather than project specific (i.e. not just adding them into a project's CMakeLists.txt)?</p>
<p>Also, is it necessary to use the <code>llvm-*</code> programs rather than the system defaults when compiling using clang instead of gcc? What's the difference?</p> | 7,032,021 | 11 | 0 | null | 2011-08-11 18:42:06.09 UTC | 194 | 2022-08-05 08:47:57.787 UTC | null | null | null | null | 222,454 | null | 1 | 318 | cmake|llvm|clang | 311,069 | <p>CMake honors the environment variables <code>CC</code> and <code>CXX</code> upon detecting the C and C++ compiler to use:</p>
<pre><code>$ export CC=/usr/bin/clang
$ export CXX=/usr/bin/clang++
$ cmake ..
-- The C compiler identification is Clang
-- The CXX compiler identification is Clang
</code></pre>
<p>The compiler specific flags can be overridden by putting them into a make override file and pointing the <a href="https://cmake.org/cmake/help/latest/variable/CMAKE_USER_MAKE_RULES_OVERRIDE.html" rel="nofollow noreferrer"><code>CMAKE_USER_MAKE_RULES_OVERRIDE</code></a> variable to it. Create a file <code>~/ClangOverrides.txt</code> with the following contents:</p>
<pre><code>SET (CMAKE_C_FLAGS_INIT "-Wall -std=c99")
SET (CMAKE_C_FLAGS_DEBUG_INIT "-g")
SET (CMAKE_C_FLAGS_MINSIZEREL_INIT "-Os -DNDEBUG")
SET (CMAKE_C_FLAGS_RELEASE_INIT "-O3 -DNDEBUG")
SET (CMAKE_C_FLAGS_RELWITHDEBINFO_INIT "-O2 -g")
SET (CMAKE_CXX_FLAGS_INIT "-Wall")
SET (CMAKE_CXX_FLAGS_DEBUG_INIT "-g")
SET (CMAKE_CXX_FLAGS_MINSIZEREL_INIT "-Os -DNDEBUG")
SET (CMAKE_CXX_FLAGS_RELEASE_INIT "-O3 -DNDEBUG")
SET (CMAKE_CXX_FLAGS_RELWITHDEBINFO_INIT "-O2 -g")
</code></pre>
<p>The suffix <code>_INIT</code> will make CMake initialize the corresponding <code>*_FLAGS</code> variable with the given value. Then invoke <code>cmake</code> in the following way:</p>
<pre><code>$ cmake -DCMAKE_USER_MAKE_RULES_OVERRIDE=~/ClangOverrides.txt ..
</code></pre>
<p>Finally to force the use of the LLVM binutils, set the internal variable <code>_CMAKE_TOOLCHAIN_PREFIX</code>. This variable is honored by the <code>CMakeFindBinUtils</code> module:</p>
<pre><code>$ cmake -D_CMAKE_TOOLCHAIN_PREFIX=llvm- ..
</code></pre>
<p>Setting <code>_CMAKE_TOOLCHAIN_LOCATION</code> is no longer necessary for CMake version 3.9 or newer.</p>
<p>Putting this all together you can write a shell wrapper which sets up the environment variables <code>CC</code> and <code>CXX</code> and then invokes <code>cmake</code> with the mentioned variable overrides.</p>
<p>Also see this <a href="https://gitlab.kitware.com/cmake/community/-/wikis/FAQ#make-override-files" rel="nofollow noreferrer">CMake FAQ</a> on make override files.</p> |
7,591,064 | How do Java programs run without defining the main method? | <p>I was looking through some Java source and noticed that the <code>main</code> method wasn't defined.</p>
<p>How does Java compile source code without knowing where to start?</p> | 7,591,085 | 13 | 0 | null | 2011-09-29 00:05:12.553 UTC | 3 | 2021-10-24 16:22:14.613 UTC | 2011-09-29 00:10:04.343 UTC | null | 596,068 | null | 950,669 | null | 1 | 10 | java|methods|program-entry-point | 46,712 | <p>The <code>main</code> method is only used when the Java Virtual Machine is executing your code. Code cannot be executed without a <code>main</code> method but it can still be compiled.</p>
<p>When compiling code, you usually specify a set of files on the command line e.g.</p>
<pre><code>javac MyClass1.java MyClass2.java
</code></pre>
<p>The Java compiler (<code>javac</code>) examines each class you passed to it and compiles it into a .class file.</p>
<p>One reason Java source code may be missing a <code>main</code> method is because it is designed to be used as a library, instead of being executed.</p>
<p>Something you may find interesting: although the source code compiled by the Java compiler does not need a <code>main</code> method, the <a href="http://hg.openjdk.java.net/jdk7/jdk7/langtools/file/ce654f4ecfd8/src/share/classes/com/sun/tools/javac/Main.java">source code for the Java compiler itself</a> does have a <code>main</code> method.</p> |
7,130,619 | Bold words in a string of strings.xml in Android | <p>I have a long text in one of the strings at strings.xml. I want to make bold and change the color of some words in that text.</p>
<p>How can I do it?</p> | 7,130,661 | 13 | 1 | null | 2011-08-20 08:15:52.533 UTC | 19 | 2022-08-15 11:43:28.42 UTC | 2019-02-09 10:46:32.08 UTC | null | 8,621,930 | null | 890,775 | null | 1 | 155 | java|android|xml | 160,523 | <p>You could basically use html tags in your string resource like: </p>
<pre><code><resource>
<string name="styled_welcome_message">We are <b><i>so</i></b> glad to see you.</string>
</resources>
</code></pre>
<p>And use Html.fromHtml or use spannable, check the link I posted. </p>
<p>Old similar question: <a href="https://stackoverflow.com/questions/1529068/is-it-possible-to-have-multiple-styles-inside-a-textview">Is it possible to have multiple styles inside a TextView?</a></p> |
14,026,777 | Making music programmatically on iPhone? | <p>I'm totally naive when it comes to audio and music on the iPhone, or on any platform in general. </p>
<p>Say I wanted to make a simple piano app - <em>is it possible to generate the sounds for each key programmatically?</em> </p>
<p>Or <em>would I have to provide say a .wav file for every possible sound?</em> </p>
<p>I'm wondering how programs like GarageBand are able to provide such diverse sounds - could it be that they have a file for every possible sound? </p>
<p>Or <em>is there a way to dynamically generate those kinds of sounds?</em></p>
<p><strong>Edit</strong>: I found <a href="http://www.hollance.com/2010/12/sound-synthesis-on-the-iphone/" rel="nofollow">this most excellent article</a> describing exactly what I want to do, and the guy even has a sample project with a small piano with all sounds being generated programmatically.</p> | 14,027,872 | 2 | 0 | null | 2012-12-25 00:34:45.73 UTC | 11 | 2012-12-25 18:13:30.757 UTC | 2012-12-25 18:13:30.757 UTC | null | 458,960 | null | 458,960 | null | 1 | 16 | iphone|ios|cocoa-touch|audio | 1,475 | <p>You can generate tones programmatically, as described in this <a href="http://www.cocoawithlove.com/2010/10/ios-tone-generator-introduction-to.html?m=1" rel="nofollow noreferrer">tutorial</a>. The example here shows you how to generate a pure sine wave using audio units.</p>
<p>Due to Fourier's theorem, any (periodic) continuous function can be expressed as the sum of sine functions of different amplitudes and phases. Using this, you can mix a few of these functions to simulate the sound of an instrument. However, this requires a lot of research and a deep understanding of wave mechanics and calculus, so it's not a trivial task.</p> |
29,200,635 | Convert float to string with precision & number of decimal digits specified? | <p>How do you convert a float to a string in C++ while specifying the precision & number of decimal digits? </p>
<p>For example: <code>3.14159265359 -> "3.14"</code></p> | 29,200,671 | 6 | 3 | null | 2015-03-22 22:30:08.403 UTC | 21 | 2021-05-27 15:41:29.13 UTC | 2018-11-28 22:22:08.22 UTC | null | 395,461 | null | 395,461 | null | 1 | 112 | c++|string|floating-point | 184,613 | <p>A typical way would be to use <code>stringstream</code>:</p>
<pre><code>#include <iomanip>
#include <sstream>
double pi = 3.14159265359;
std::stringstream stream;
stream << std::fixed << std::setprecision(2) << pi;
std::string s = stream.str();
</code></pre>
<p>See <a href="http://www.cplusplus.com/reference/ios/fixed/" rel="noreferrer">fixed</a></p>
<blockquote>
<p><strong>Use fixed floating-point notation</strong></p>
<p>Sets the <code>floatfield</code> format flag for the <em>str</em> stream to <code>fixed</code>.</p>
<p>When <code>floatfield</code> is set to <code>fixed</code>, floating-point values are written using fixed-point notation: the value is represented with exactly as many digits in the decimal part as specified by the <em>precision field</em> (<code>precision</code>) and with no exponent part.</p>
</blockquote>
<p>and <a href="http://www.cplusplus.com/reference/iomanip/setprecision/" rel="noreferrer">setprecision</a>.</p>
<hr>
<p>For <strong>conversions of technical purpose</strong>, like storing data in XML or JSON file, C++17 defines <a href="https://en.cppreference.com/w/cpp/utility/to_chars" rel="noreferrer">to_chars</a> family of functions.</p>
<p>Assuming a compliant compiler (which we lack at the time of writing),
something like this can be considered:</p>
<pre><code>#include <array>
#include <charconv>
double pi = 3.14159265359;
std::array<char, 128> buffer;
auto [ptr, ec] = std::to_chars(buffer.data(), buffer.data() + buffer.size(), pi,
std::chars_format::fixed, 2);
if (ec == std::errc{}) {
std::string s(buffer.data(), ptr);
// ....
}
else {
// error handling
}
</code></pre> |
9,419,570 | Could not find stored procedure, however can execute it | <p>I am new to SQL Server and created my very first stored procedure. It executes fine and I can locate it under 'Programmability', 'Stored Procedures' so I pop open a new query and type in the following statements:</p>
<pre><code>use name_of_database
exec name_of_stored_procedure 'value'
</code></pre>
<p>However before executing the stored procedure, the name of the stored procedure is underlined in red noting it cannot be found, so I run the query:</p>
<pre><code>select * from INFORMATION_SCHEMA.ROUTINES where ROUTINE_NAME = 'name_of_stored_procedure'
</code></pre>
<p>Nada. It returns nothing.</p>
<p>However if I go ahead and execute the stored procedure, it works fine.</p>
<p>What am I doing wrong?</p> | 9,419,632 | 6 | 1 | null | 2012-02-23 19:09:46.9 UTC | null | 2020-02-20 20:31:23.227 UTC | 2012-02-23 22:19:49.687 UTC | null | 61,305 | null | 700,543 | null | 1 | 10 | sql-server-2008 | 48,310 | <p>For SSMS you just need to clear the Intellisense cache (Ctrl + Shift + R). Then the red squiggly line will disappear and Intellisense will help you out with that.</p>
<p>If you can view your Stored Proc under Programmability -> Stored Procedures in your object explorer, then you will be able to view it through your <code>select * from information_schema.routines ...</code> query. Check your database context, as well as the rest of the query. Take out the <code>where</code> clause and look through the whole result set.</p> |
9,334,187 | Management of strings in structs | <p>I know that strings have variable length, therefore they need variable space in memory to be stored. When we define a string item in a <code>struct</code>, the <code>struct</code>'s size would then be variable in length. </p>
<p>Older languages managed this by using fixed-length strings. However, there is no way to define fixed-length strings in C#, and C# manages normal strings in <code>struct</code>s pretty good. </p>
<p>This becomes more weird when we define an array of such <code>struct</code>s, or simply an array of strings. As result of any change (decrease/increase) in length of one string, all forward <code>struct</code>s must be shifted. </p>
<p>How does C# handle variable-length strings in structs?</p> | 9,334,231 | 5 | 1 | null | 2012-02-17 19:30:06.69 UTC | 2 | 2020-01-07 04:15:30.44 UTC | 2019-09-26 13:03:10.937 UTC | null | 1,704,458 | null | 587,820 | null | 1 | 32 | c#|string|struct | 21,687 | <p>The string itself is not stored in the struct. Instead a reference to the string is stored in the struct, so the struct size never changes. </p>
<p><code>string</code> is not a value type; .NET strings are <em>interned</em>, which means that each unique string is stored in a look-up table in memory.</p> |
19,433,630 | How to use 'User' as foreign key in Django 1.5 | <p>I have made a custom profile model which looks like this:</p>
<pre><code>from django.db import models
from django.contrib.auth.models import User
class UserProfile(models.Model):
user = models.ForeignKey('User', unique=True)
name = models.CharField(max_length=30)
occupation = models.CharField(max_length=50)
city = models.CharField(max_length=30)
province = models.CharField(max_length=50)
sex = models.CharField(max_length=1)
</code></pre>
<p>But when I run <code>manage.py syncdb</code>, I get:</p>
<blockquote>
<p>myapp.userprofile: 'user' has a relation with model User, which has
either not been installed or is abstract.</p>
</blockquote>
<p>I also tried:</p>
<pre><code>from django.contrib.auth.models import BaseUserManager, AbstractUser
</code></pre>
<p>But it gives the same error. Where I'm wrong and how to fix this?</p> | 19,433,703 | 2 | 3 | null | 2013-10-17 17:44:25.613 UTC | 13 | 2022-03-26 17:28:49.407 UTC | 2022-03-26 17:28:49.407 UTC | null | 8,172,439 | null | 727,695 | null | 1 | 51 | python|python-3.x|django|foreign-keys|django-users | 54,378 | <p>Change this:</p>
<pre><code>user = models.ForeignKey('User', unique=True)
</code></pre>
<p>to this:</p>
<pre><code>user = models.ForeignKey(User, unique=True)
</code></pre> |
24,481,399 | How to set Master address for Spark examples from command line | <p><strong>NOTE:</strong> <em>They author is looking for answers to set the Spark Master when running Spark examples that involves <strong>no</strong> changes to the source code, but rather only options that can be done from the command-line if at all possible.</em></p>
<p>Let us consider the run() method of the BinaryClassification example:</p>
<pre><code> def run(params: Params) {
val conf = new SparkConf().setAppName(s"BinaryClassification with $params")
val sc = new SparkContext(conf)
</code></pre>
<p>Notice that the SparkConf did not provide any means to configure the SparkMaster.</p>
<p>When running this program from Intellij with the following arguments:</p>
<pre><code>--algorithm LR --regType L2 --regParam 1.0 data/mllib/sample_binary_classification_data.txt
</code></pre>
<p>the following error occurs:</p>
<pre><code>Exception in thread "main" org.apache.spark.SparkException: A master URL must be set
in your configuration
at org.apache.spark.SparkContext.<init>(SparkContext.scala:166)
at org.apache.spark.examples.mllib.BinaryClassification$.run(BinaryClassification.scala:105)
</code></pre>
<p>I have also tried adding in the Spark Master url anyways (though the code seems NOT to support it ..)</p>
<pre><code> spark://10.213.39.125:17088 --algorithm LR --regType L2 --regParam 1.0
data/mllib/sample_binary_classification_data.txt
</code></pre>
<p>and</p>
<pre><code>--algorithm LR --regType L2 --regParam 1.0 spark://10.213.39.125:17088
data/mllib/sample_binary_classification_data.txt
</code></pre>
<p>Both do not work with error:</p>
<pre><code>Error: Unknown argument 'data/mllib/sample_binary_classification_data.txt'
</code></pre>
<p>For reference here is the options parsing - which does nothing with SparkMaster:</p>
<pre><code>val parser = new OptionParser[Params]("BinaryClassification") {
head("BinaryClassification: an example app for binary classification.")
opt[Int]("numIterations")
.text("number of iterations")
.action((x, c) => c.copy(numIterations = x))
opt[Double]("stepSize")
.text(s"initial step size, default: ${defaultParams.stepSize}")
.action((x, c) => c.copy(stepSize = x))
opt[String]("algorithm")
.text(s"algorithm (${Algorithm.values.mkString(",")}), " +
s"default: ${defaultParams.algorithm}")
.action((x, c) => c.copy(algorithm = Algorithm.withName(x)))
opt[String]("regType")
.text(s"regularization type (${RegType.values.mkString(",")}), " +
s"default: ${defaultParams.regType}")
.action((x, c) => c.copy(regType = RegType.withName(x)))
opt[Double]("regParam")
.text(s"regularization parameter, default: ${defaultParams.regParam}")
arg[String]("<input>")
.required()
.text("input paths to labeled examples in LIBSVM format")
.action((x, c) => c.copy(input = x))
</code></pre>
<p>So .. yes .. I could go ahead and modify the source code. But I suspect instead I am missing an <em>available</em> tuning knob to make this work that does not involve modifying the source code.</p> | 24,481,688 | 5 | 2 | null | 2014-06-30 00:06:46.163 UTC | 11 | 2018-04-15 00:49:25.687 UTC | 2017-01-12 08:52:19.01 UTC | null | 1,056,563 | null | 1,056,563 | null | 1 | 35 | intellij-idea|apache-spark | 53,439 | <p>You can set the Spark master from the command-line by adding the JVM parameter:</p>
<pre><code>-Dspark.master=spark://myhost:7077
</code></pre> |
24,466,366 | Mongoose - RangeError: Maximum Call Stack Size Exceeded | <p>I am trying to bulk insert documents into MongoDB (so bypassing Mongoose and using the native driver instead as Mongoose doesn't support bulk insert of an array of documents). The reason I'm doing this is to improve the speed of writing.</p>
<p>I am receiving the error "RangeError: Maximum Call Stack Size Exceeded" at console.log(err) in the code below: </p>
<pre><code>function _fillResponses(globalSurvey, optionsToSelectRegular, optionsToSelectPiped, responseIds, callback) {
Response.find({'_id': {$in: responseIds}}).exec(function(err, responses) {
if (err) { return callback(err); }
if (globalSurvey.questions.length) {
responses.forEach(function(response) {
console.log("Filling response: " + response._id);
response.answers = [];
globalAnswers = {};
globalSurvey.questions.forEach(function(question) {
ans = _getAnswer(question, optionsToSelectRegular, optionsToSelectPiped, response);
globalAnswers[question._id] = ans;
response.answers.push(ans);
});
});
Response.collection.insert(responses, function(err, responsesResult) {
console.log(err);
callback()
});
} else {
callback();
}
});
}
</code></pre>
<p>So similar to: <a href="https://stackoverflow.com/questions/24356859/mongoose-maximum-call-stack-size-exceeded">https://stackoverflow.com/questions/24356859/mongoose-maximum-call-stack-size-exceeded</a></p>
<p>Perhaps it's something about the format of the responses array that Mongoose returns that means I can't directly insert using MongoDB natively? I've tried .toJSON() on each response but no luck.</p>
<p>I still get the error even with a very small amount of data but looping through and calling the Mongoose save on each document individually works fine.</p>
<p>EDIT: I think it is related to this issue: <a href="http://howtosjava.blogspot.com.au/2012/05/nodejs-mongoose-rangeerror-maximum-call.html" rel="noreferrer">http://howtosjava.blogspot.com.au/2012/05/nodejs-mongoose-rangeerror-maximum-call.html</a></p>
<p>My schema for responses is: </p>
<pre><code>var ResponseSchema = new Schema({
user: {
type: Schema.ObjectId,
ref: 'User'
},
randomUUID: String,
status: String,
submitted: Date,
initialEmailId: String,
survey: String,
answers: [AnswerSchema]
});
</code></pre>
<p>So, answers are a sub-document within responses. Not sure how to fix it though....</p> | 25,275,825 | 8 | 3 | null | 2014-06-28 11:32:23.297 UTC | 9 | 2022-06-23 22:11:11.55 UTC | 2017-05-23 12:26:23.547 UTC | null | -1 | null | 2,897,345 | null | 1 | 32 | javascript|node.js|mongodb|mongoose | 31,990 | <p>I was having this same issue and I started digging through the mongoose source code (version 3.8.14). Eventually it led me to this line within </p>
<ul>
<li>mongoose/node_modules/mongodb/lib/mongodb/collection/core.js -> <em>insert</em>(...) -> <em>insertWithWriteCommands</em>(...) -> </li>
<li><p>mongoose/node_modules/mongodb/lib/mongodb/collection/batch/ordered.js -> <em>bulk.insert(docs[i])</em> -> <em>addToOperationsList(...)</em> -> <em>bson.calculateObjectSize(document, false);</em></p>
<p>var bsonSize = bson.calculateObjectSize(document, false);</p></li>
</ul>
<p>Apparently, this calls BSON.calculateObjectSize, which calls calculateObjectSize which then infinitely recurses. I wasn't able to dig that far in to what caused it, but figured that it may have something to do with the mongoose wrapper binding functions to the Schema. Since I was inserting raw data into mongoDB, once I decided to change the bulk insert in mongoose to a standard javascript object, the problem went away and bulk inserts happened correctly. You might be able to do something similar.</p>
<p>Essentially, my code went from</p>
<pre><code>//EDIT: mongoose.model needs lowercase 'm' for getter method
var myModel = mongoose.model('MyCollection');
var toInsert = myModel();
var array = [toInsert];
myModel.collection.insert(array, {}, function(err, docs) {});
</code></pre>
<p>to </p>
<pre><code>//EDIT: mongoose.model needs lowercase 'm' for getter method
var myModel = mongoose.model('MyCollection');
var toInsert = { //stuff in here
name: 'john',
date: new Date()
};
var array = [toInsert];
myModel.collection.insert(array, {}, function(err, docs) {});
</code></pre> |
411,396 | How to use javascript onclick on a DIV tag to toggle visibility of a section that contains clickable links? | <p>Hi I've got a DIV section that has only its title visible initially. What I would like to achieve is that when the visitor clicks anywhere on the area of <code>toggle_section</code> the <code>toggle_stuff</code> div toggles between visible/hidden.</p>
<pre><code><div id="toggle_section"
onclick="javascript: new Effect.toggle('toggle_stuff', 'slide');">
<div id="toggle_title">Some title</div>
<div id="toggle_stuff">
some content stuff
<a href="/foo.php">Some link</a>
</div>
</div>
</code></pre>
<p>However, the way it is set-up right now, if I have any <code><a></code> link within the <code>toggle_section</code>, clicking that link will also execute the onclick event.</p>
<p>Then my question is what would be the best way to set this type of behavior?</p> | 411,488 | 5 | 0 | null | 2009-01-04 17:59:02.493 UTC | 2 | 2012-10-24 16:37:22.63 UTC | 2011-12-27 22:34:27.087 UTC | null | 938,089 | Miroslav Solanka | 47,193 | null | 1 | 8 | javascript|css|prototypejs|scriptaculous | 71,722 | <p>The most simple solution is to <strong>add an extra onclick handler to the link</strong> within your DIV which stops event propagation:</p>
<pre><code><div id="toggle_section"
onclick="javascript: new Effect.toggle('toggle_stuff', 'slide');">
<div id="toggle_title">Some title</div>
<div id="toggle_stuff">
some content stuff
<a href="/foo.php"
onclick="Event.stop(event);"
>Some link</a>
</div>
</div>
</code></pre>
<p>The above example uses Prototype's <a href="http://www.prototypejs.org/api/event/stop" rel="noreferrer"><code>Event.stop()</code></a> function in order to facilitate a cross browser event propagation stop.</p>
<p>As you use the inline <code>onclick()</code> handler, most (if not all) browser will traverse the event in the bubbling phase first (which is what you want).</p>
<p>A good guide to understanding the actual reasons behind this behaviour and the differences between <em>event capturing</em> and <em>event bubbling</em> can be found at the excellent <a href="http://www.quirksmode.org/js/events_order.html" rel="noreferrer">Quirksmode.</a></p> |
744,013 | How to cancel the execution of a method? | <p>Consider i execute a method 'Method1' in C#.
Once the execution goes into the method i check few condition and if any of them is false, then the execution of Method1 should be stopped. how can i do this, i.e can the execution of a method when certain conditions are met.?</p>
<p>but my code is something like this,</p>
<pre><code>int Method1()
{
switch(exp)
{
case 1:
if(condition)
//do the following. **
else
//Stop executing the method.**
break;
case2:
...
}
}
</code></pre> | 744,024 | 5 | 1 | null | 2009-04-13 14:18:47.297 UTC | 5 | 2017-11-02 15:44:43.883 UTC | 2017-11-02 15:44:43.883 UTC | null | 2,735,344 | null | 73,137 | null | 1 | 14 | c# | 61,799 | <p>Use the <code>return</code> statement.</p>
<pre><code>if(!condition1) return;
if(!condition2) return;
// body...
</code></pre> |
967,646 | Monitor when an exe is launched | <p>I have some services that an application needs running in order for some of the app's features to work. I would like to enable the option to only start the external Windows services to initialize after the application is launched. (as opposed to having them start automatically with the machine and take up memory when the application is not needed)</p>
<p>I do not have access to the exe's code to implement this, so ideally I would like to write a C# .Net Windows service that would monitor when an exe is launched.</p>
<p>What I've found so far is the System.IO.FileSystemEventHandler. This component only handles changed, created, deleted, and renamed event types. I don't expect that a file system component would be the ideal place to find what I'm looking for, but don't know where else to go.</p>
<p>Maybe I'm not searching with the right keywords, but I have not yet found anything extremely helpful on Google or here on stackoverflow.com.</p>
<p>The solution would be required to run on XP, Vista, and Win 7 when it comes...</p>
<p>Thanks in advance for any pointers.</p> | 967,668 | 5 | 1 | null | 2009-06-09 00:22:57.25 UTC | 18 | 2013-05-01 20:32:20.637 UTC | null | null | null | user119522 | null | null | 1 | 23 | c#|.net|windows-services|monitoring | 13,700 | <p>From <a href="http://social.msdn.microsoft.com/Forums/en-US/netfxbcl/thread/46f52ad5-2f97-4ad8-b95c-9e06705428bd?wa=wsignin1.0" rel="noreferrer">this article</a>, you can use WMI (the <code>System.Management</code> namespace) in your service to watch for process start events.</p>
<pre><code> void WaitForProcess()
{
ManagementEventWatcher startWatch = new ManagementEventWatcher(
new WqlEventQuery("SELECT * FROM Win32_ProcessStartTrace"));
startWatch.EventArrived
+= new EventArrivedEventHandler(startWatch_EventArrived);
startWatch.Start();
ManagementEventWatcher stopWatch = new ManagementEventWatcher(
new WqlEventQuery("SELECT * FROM Win32_ProcessStopTrace"));
stopWatch.EventArrived
+= new EventArrivedEventHandler(stopWatch_EventArrived);
stopWatch.Start();
}
static void stopWatch_EventArrived(object sender, EventArrivedEventArgs e) {
stopWatch.Stop();
Console.WriteLine("Process stopped: {0}"
, e.NewEvent.Properties["ProcessName"].Value);
}
static void startWatch_EventArrived(object sender, EventArrivedEventArgs e) {
startWatch.Stop();
Console.WriteLine("Process started: {0}"
, e.NewEvent.Properties["ProcessName"].Value);
}
}
</code></pre>
<p>WMI allows for fairly sophisticated queries; you can modify the queries here to trigger your event handler only when your watched app launches, or on other criteria. <a href="http://www.dreamincode.net/forums/showtopic42934.htm" rel="noreferrer">Here's a quick introduction</a>, from a C# perspective.</p> |
786,661 | Using ASPNet_Regiis to encrypt custom configuration section - can you do it? | <p>I have a web application with a custom configuration section. That section contains information I'ld like to encrypt (was hoping to use ASPNet_RegIIS rather than do it myself).</p>
<p>Web.Config:</p>
<pre><code><?xml version="1.0"?>
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
<configSections>
<section name="MyCustomSection"
type="MyNamespace.MyCustomSectionHandler, MyAssembly"/>
</configSections>
<configProtectedData>
<providers>
<clear />
<add name="DataProtectionConfigurationProvider"
type="System.Configuration.RsaProtectedConfigurationProvider, System.Configuration, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a,
processorArchitecture=MSIL"
keyContainerName="MyKeyContainer"
useMachineContainer="true" />
</providers>
</configProtectedData>
<MyCustomSection>
<blah name="blah1">
<blahChild name="blah1Child1" />
</blah>
</MyCustomSection>
</code></pre>
<p>The configuration handler works great before trying to encrypt it. When I try to encrypt it with: </p>
<blockquote>
<p>aspnet_regiis -pef "MyCustomSection"
c:\inetpub\wwwroot\MyWebsite -prov
DataProtectionConfigurationProvider</p>
</blockquote>
<p>I get an error:</p>
<blockquote>
<p>Encrypting configuration section... An
error occurred creating the
configuration section handler for
MyCustomSection: Could not load file
or assembly 'MyAssembly' or one of its
dependencies. The system cannot find
the file specified.
(c:\inetpub\wwwroot\MyWebsite\web.config
line 5)</p>
</blockquote>
<p>I have tried with/without the provider configured. With/without section groups. With/Without having started the website before hand. I've tried temporarily putting my assembly in the GAC for the registration. I also tried my log4net section just to try something that wasn't mine, with no luck. I've run the command prompt as Administrator. Any ideas? Or can ASPNet_RegIIS just not be used for custom sections?</p>
<p>One final shot after viewing <a href="http://msdn.microsoft.com/en-us/library/system.configuration.iconfigurationsectionhandler.aspx" rel="noreferrer">MSDN</a> was changing my handler to inherit from ConfigurationSection rather than implementing IConfigurationSectionHandler since it was technically deprecated in 2.0 (hoping it was something regarding aspnet_regiis version). No luck there either.</p>
<p>Any ideas let me know. Thanks!</p> | 6,363,620 | 5 | 2 | null | 2009-04-24 16:39:16.79 UTC | 14 | 2013-07-19 12:16:38.15 UTC | null | null | null | null | 1,907 | null | 1 | 36 | asp.net|encryption|web-config|aspnet-regiis.exe|system.configuration | 15,231 | <p><code>aspnet_regiis</code> must be able to bind the assembly. The normal .net binding rules apply. </p>
<p>I get around this by creating directory called <code>aspnet_regiis_bin</code> in the same directory as <code>aspnet_regiis.exe</code> and an <code>aspnet_regiis.exe.config</code> file with <code>aspnet_regiis_bin</code> as a private path like this:</p>
<pre><code><configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<probing privatePath="aspnet_regiis_bin"/>
</assemblyBinding>
</runtime>
</configuration>
</code></pre>
<p>I then copy the assemblies that define the custom configuration sections into <code>aspnet_regiis_bin</code> so that <code>aspnet_regiis</code> can find them.</p>
<p>This procedure doesn't require the assemblies to be strong named or in the GAC but does require messing around in the framework directories.</p> |
715,550 | Best way to encode tuples with json | <p>In python I have a dictionary that maps tuples to a list of tuples. e.g. </p>
<p><code>{(1,2): [(2,3),(1,7)]}</code></p>
<p>I want to be able to encode this data use it with javascript, so I looked into json but it appears keys must be strings so my tuple does not work as a key.</p>
<p>Is the best way to handle this is encode it as "1,2" and then parse it into something I want on the javascript? Or is there a more clever way to handle this.</p> | 715,601 | 5 | 0 | null | 2009-04-03 20:14:25.057 UTC | 5 | 2014-03-31 13:33:28.153 UTC | null | null | null | f4hy | 86,887 | null | 1 | 48 | python|json | 80,246 | <p>You might consider saying</p>
<pre><code>{"[1,2]": [(2,3),(1,7)]}
</code></pre>
<p>and then when you need to get the value out, you can just parse the keys themselves as JSON objects, which all modern browsers can do with the built-in <code>JSON.parse</code> method (I'm using <code>jQuery.each</code> to iterate here but you could use anything):</p>
<pre><code>var myjson = JSON.parse('{"[1,2]": [[2,3],[1,7]]}');
$.each(myjson, function(keystr,val){
var key = JSON.parse(keystr);
// do something with key and val
});
</code></pre>
<p>On the other hand, you might want to just structure your object differently, e.g.</p>
<pre><code>{1: {2: [(2,3),(1,7)]}}
</code></pre>
<p>so that instead of saying</p>
<pre><code>myjson[1,2] // doesn't work
</code></pre>
<p>which is invalid Javascript syntax, you could say</p>
<pre><code>myjson[1][2] // returns [[2,3],[1,7]]
</code></pre> |
218,150 | Which built-in .NET exceptions can I throw from my application? | <p>If I need to throw an exception from within my application which of the built-in .NET exception classes can I use? Are they all fair game? When should I derive my own?</p> | 218,182 | 5 | 1 | null | 2008-10-20 11:51:38.603 UTC | 17 | 2015-04-23 11:38:29.063 UTC | 2013-12-05 04:23:37.033 UTC | null | 707,111 | Si Keep | 1,127,460 | null | 1 | 71 | c#|.net|exception | 12,600 | <p>See <a href="http://msdn.microsoft.com/en-us/library/ms173163.aspx" rel="noreferrer">Creating and Throwing Exceptions</a>.</p>
<p>On throwing built-in exceptions, it says:</p>
<blockquote>
<p>Do not throw System.Exception, System.SystemException, System.NullReferenceException, or System.IndexOutOfRangeException intentionally from your own source code.</p>
</blockquote>
<p>and</p>
<blockquote>
<p>Do Not Throw General Exceptions </p>
<p>If you throw a general exception type, such as Exception or SystemException in a library or framework, it forces consumers to catch all exceptions, including unknown exceptions that they do not know how to handle. </p>
<p>Instead, either throw a more derived type that already exists in the framework, or create your own type that derives from Exception."</p>
</blockquote>
<p>This <a href="http://blogs.msdn.com/fxcop/archive/2007/01/22/faq-what-exception-should-i-throw-instead-of-the-reserved-exceptions-found-by-donotraisereservedexceptiontypes.aspx" rel="noreferrer">blog entry</a> also has some useful guidelines.</p>
<p>Also, FxCop code analysis defines a list of "do not raise exceptions" as <a href="http://msdn.microsoft.com/en-us/library/ms182338.aspx" rel="noreferrer">described here</a>. It recommends:</p>
<blockquote>
<p>The following exception types are too general to provide sufficient information to the user: </p>
<ul>
<li>System.Exception </li>
<li>System.ApplicationException </li>
<li>System.SystemException</li>
</ul>
<p>The following exception types are reserved and should be thrown only by the common language runtime: </p>
<ul>
<li>System.ExecutionEngineException </li>
<li>System.IndexOutOfRangeException </li>
<li>System.NullReferenceException </li>
<li>System.OutOfMemoryException</li>
</ul>
</blockquote>
<p>So in theory you can raise any other framework exception type, providing you clearly understand the intent of the exception as described by Microsoft (see MSDN documentation).</p>
<p>Note, these are "guidelines" and as some others have said, there is debate around System.IndexOutOfRangeException (ie many developers throw this exception).</p> |
770,523 | Escaping Strings in JavaScript | <p>Does JavaScript have a built-in function like PHP's <code>addslashes</code> (or <code>addcslashes</code>) function to add backslashes to characters that need escaping in a string?</p>
<p>For example, this:</p>
<blockquote>
<p>This is a demo string with
'single-quotes' and "double-quotes".</p>
</blockquote>
<p>...would become:</p>
<blockquote>
<p>This is a demo string with
\'single-quotes\' and
\"double-quotes\".</p>
</blockquote> | 770,533 | 5 | 6 | null | 2009-04-20 23:50:45.863 UTC | 28 | 2020-12-30 13:23:49.3 UTC | 2012-06-16 17:32:45.3 UTC | null | 387,076 | null | 48,492 | null | 1 | 75 | javascript|string|escaping|quotes|backslash | 151,111 | <p><a href="http://locutus.io/php/strings/addslashes/" rel="noreferrer">http://locutus.io/php/strings/addslashes/</a></p>
<pre><code>function addslashes( str ) {
return (str + '').replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');
}
</code></pre> |
916,169 | Cannot use identity column key generation with <union-subclass> ( TABLE_PER_CLASS ) | <p><strong>com.something.SuperClass:</strong></p>
<pre><code>@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class SuperClass implements Serializable {
private static final long serialVersionUID = -695503064509648117L;
long confirmationCode;
@Id
@GeneratedValue(strategy = GenerationType.AUTO) // Causes exception!!!
public long getConfirmationCode() {
return confirmationCode;
}
public void setConfirmationCode(long confirmationCode) {
this.confirmationCode = confirmationCode;
}
}
</code></pre>
<p><strong>com.something.SubClass:</strong></p>
<pre><code>@Entity
public abstract class Subclass extends SuperClass {
private static final long serialVersionUID = 8623159397061057722L;
String name;
@Column(nullable = false)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
</code></pre>
<p><strong>Gives me this exception:</strong></p>
<pre><code>Caused by: org.hibernate.MappingException: Cannot use identity column key
generation with <union-subclass> mapping for: com.something.SuperClass
</code></pre>
<p>What's the best and most convenient way for me to generate the ID's? <em>I do not want to change my inheritance strategy.</em></p> | 923,523 | 5 | 0 | null | 2009-05-27 14:49:01.083 UTC | 26 | 2018-10-20 10:32:48.987 UTC | 2017-11-17 08:41:30.463 UTC | null | 100,297 | user14070 | null | null | 1 | 107 | hibernate|inheritance|jpa|class-table-inheritance | 57,966 | <p>The problem here is that you mix "table-per-class" inheritance and <code>GenerationType.Auto</code>.
Consider an identity column in MsSQL. It is column based. In a "table-per-class" strategy you use one table per class and each one has an ID. </p>
<p>Try:</p>
<p><code>@GeneratedValue(strategy = GenerationType.TABLE)</code></p> |
1,336,661 | Simple(r) ORM for PHP | <p>What is the <strong>simplest</strong> ORM implementation around for PHP? I'm looking for something <strong>really simple and light</strong> (in terms of LOC, since speed it's not crucial I don't need caches and what not), <strong>preferably a single file or class package</strong> that doesn't depends on XML or other configuration files and it's easy to deploy.</p>
<p>Reading other similar questions <a href="http://www.schizofreend.nl/pork.dbobject/" rel="nofollow noreferrer">Pork.dbObject</a> (which by the way is developed by one of SO users) was the closest I could find so far, and I'm interested in knowing if there are any other ORM implementations that might be <strong>lighter than this one</strong>.</p> | 1,358,099 | 6 | 0 | null | 2009-08-26 18:34:20.947 UTC | 9 | 2012-12-23 21:34:26.977 UTC | 2012-12-23 21:34:26.977 UTC | null | 168,868 | null | 89,771 | null | 1 | 10 | php|orm | 7,070 | <p>Doctrine and Propel are good, but can't say they are "simplest".
Here two alternatives - <a href="http://www.phpactiverecord.org/" rel="nofollow noreferrer">PHP Active Record</a> , <a href="http://www.outlet-orm.org/site/" rel="nofollow noreferrer">Outlet PHP ORM</a></p>
<p>Hope one of them helps</p> |
361,500 | initializing std::string from char* without copy | <p>I have a situation where I need to process large (many GB's) amounts of data as such:</p>
<ol>
<li>build a large string by appending many smaller (C char*) strings</li>
<li>trim the string</li>
<li>convert the string into a C++ const std::string for processing (read only)</li>
<li>repeat</li>
</ol>
<p>The data in each iteration are independent.</p>
<p>My question is, I'd like to minimise (if possible eliminate) heap allocated memory usage, as it at the moment is my largest performance problem.</p>
<p>Is there a way to convert a C string (char*) into a stl C++ string (std::string) without requiring std::string to internally alloc/copy the data?</p>
<p>Alternatively, could I use stringstreams or something similar to re-use a large buffer?</p>
<p><strong>Edit:</strong> Thanks for the answers, for clarity, I think a revised question would be:</p>
<p><em>How can I build (via multiple appends) a stl C++ string efficiently. And if performing this action in a loop, where each loop is totally independant, how can I re-use thisallocated space.</em></p> | 361,597 | 6 | 0 | null | 2008-12-12 00:11:01.99 UTC | 8 | 2016-11-30 18:01:51.58 UTC | 2008-12-12 02:52:41.303 UTC | Akusete | 40,175 | Akusete | 40,175 | null | 1 | 51 | c++|string|memory-management|stl | 30,949 | <p>Is it at all possible to use a C++ string in step 1? If you use <code>string::reserve(size_t)</code>, you can allocate a large enough buffer to prevent multiple heap allocations while appending the smaller strings, and then you can just use that same C++ string throughout all of the remaining steps.</p>
<p>See <a href="http://en.cppreference.com/w/cpp/string/basic_string/reserve" rel="noreferrer">this link</a> for more information on the <code>reserve</code> function.</p> |
679,000 | How to check if a database exists in SQL Server? | <p>What is the ideal way to check if a database exists on a SQL Server using TSQL? It seems multiple approaches to implement this.</p> | 679,038 | 6 | 0 | null | 2009-03-24 19:56:11.41 UTC | 31 | 2022-05-01 21:48:44.01 UTC | null | null | null | Ray Vega | 4,872 | null | 1 | 313 | sql-server|database|tsql | 329,614 | <p>From a Microsoft's script:</p>
<pre><code>DECLARE @dbname nvarchar(128)
SET @dbname = N'Senna'
IF (EXISTS (SELECT name
FROM master.dbo.databases
WHERE ('[' + name + ']' = @dbname
OR name = @dbname)))
</code></pre> |
385,367 | What requests do browsers' "F5" and "Ctrl + F5" refreshes generate? | <p>Is there a standard for what actions <kbd>F5</kbd> and <kbd>Ctrl</kbd>+<kbd>F5</kbd> trigger in web browsers?</p>
<p>I once did experiment in IE6 and Firefox 2.x. The <kbd>F5</kbd> refresh would trigger a HTTP request sent to the server with an <code>If-Modified-Since</code> header, while <kbd>Ctrl</kbd>+<kbd>F5</kbd> would not have such a header. In my understanding, <kbd>F5</kbd> will try to utilize cached content as much as possible, while <kbd>Ctrl</kbd>+<kbd>F5</kbd> is intended to abandon all cached content and just retrieve all content from the servers again.</p>
<p>But today, I noticed that in some of the latest browsers (Chrome, IE8) it doesn't work in this way anymore. Both <kbd>F5</kbd> and <kbd>Ctrl</kbd>+<kbd>F5</kbd> send the <code>If-Modified-Since</code> header.</p>
<p>So how is this supposed to work, or (if there is no standard) how do the major browsers differ in how they implement these refresh features?</p> | 385,384 | 6 | 4 | null | 2008-12-22 02:00:08.72 UTC | 181 | 2021-07-16 20:00:18.867 UTC | 2021-07-16 19:59:53.497 UTC | saua | 7,487,335 | Morgan Cheng | 26,349 | null | 1 | 411 | http|browser|caching|cross-browser|refresh | 604,322 | <p>Generally speaking:</p>
<p><kbd>F5</kbd> may give you the same page even if the content is changed, because it may load the page from cache. But <kbd>Ctrl</kbd>+<kbd>F5</kbd> forces a cache refresh, and will guarantee that if the content is changed, you will get the new content.</p> |
32,270,758 | Why doesn't C++ support strongly typed ellipsis? | <p>Can someone please explain to me why C++, at least to my knowledge, doesn't implement a strongly typed ellipsis function, something to the effect of:</p>
<pre><code>void foo(double ...) {
// Do Something
}
</code></pre>
<p>Meaning that, in plain speak: 'The user can pass a variable number of terms to the foo function, however, all of the terms must be doubles'</p> | 32,273,471 | 8 | 14 | null | 2015-08-28 12:10:20.807 UTC | 8 | 2015-08-28 21:16:05.113 UTC | 2015-08-28 17:41:57.727 UTC | null | 2,310,866 | null | 1,834,057 | null | 1 | 28 | c++|variadic-functions|ellipsis | 8,130 | <p>Historically, the ellipsis syntax <code>...</code> comes from C.</p>
<p>This complicated beast was used to power <code>printf</code>-like functions and is to be used with <code>va_list</code>, <code>va_start</code> etc...</p>
<p>As you noted, it is not typesafe; but then C is far from being typesafe, what with its implicit conversions from and to <code>void*</code> for any pointer types, its implicit truncation of integrals/floating point values, etc...</p>
<p>Because C++ was to be as close as possible as a superset of C, it inherited the ellipsis from C.</p>
<hr>
<p>Since its inception, C++ practices evolved, and there has been a strong push toward stronger typing.</p>
<p>In C++11, this culminated in:</p>
<ul>
<li>initializer lists, a short-hand syntax for a variable number of values of a given type: <code>foo({1, 2, 3, 4, 5})</code></li>
<li>variadic templates, which are a beast of their own and allow writing a type-safe <code>printf</code> for example</li>
</ul>
<p>Variadic templates actually reuse the ellipsis <code>...</code> in their syntax, to denote <em>packs</em> of types or values and as an unpack operator:</p>
<pre><code>void print(std::ostream&) {}
template <typename T, typename... Args>
void print(std::ostream& out, T const& t, Args const&... args) {
print(out << t, args...); // recursive, unless there are no args left
// (in that case, it calls the first overload
// instead of recursing.)
}
</code></pre>
<p>Note the 3 different uses of <code>...</code>:</p>
<ul>
<li><code>typename...</code> to declare a variadic type</li>
<li><code>Args const&...</code> to declare a pack of arguments</li>
<li><code>args...</code> to unpack the pack in an expression</li>
</ul> |
38,021,661 | Copy multiple files from s3 bucket | <p>I am having trouble downloading multiple files from AWS S3 buckets to my local machine. </p>
<p>I have all the filenames that I want to download and I do not want others. How can I do that ? Is there any kind of loop in aws-cli I can do some iteration ?</p>
<p>There are couple hundreds files I need to download so that it seems not possible to use one single command that takes all filenames as arguments. </p> | 38,026,133 | 8 | 3 | null | 2016-06-24 20:32:19.863 UTC | 12 | 2021-11-24 10:19:24.243 UTC | null | null | null | null | 6,003,407 | null | 1 | 55 | amazon-web-services|amazon-s3|aws-cli | 92,263 | <p>There is a bash script which can read all the filenames from a file <code>filename.txt</code>. </p>
<pre><code>#!/bin/bash
set -e
while read line
do
aws s3 cp s3://bucket-name/$line dest-path/
done <filename.txt
</code></pre> |
37,956,272 | NS_ASSUME_NONNULL_BEGIN Macro | <p>I am following an online tutorial from team tree house and one of the steps is to create an NSManagedObject subclass for my data model. </p>
<p>When I did that the code automatically generated a class and set of macros at the beginning and and the end:</p>
<p><strong>NS_ASSUME_NONNULL_BEGIN</strong></p>
<p><strong>NS_ASSUME_NONNULL_END</strong></p>
<p>I was searching online but I could not find any documentation about what these guys are doing here. By the way they were defined in the header <strong>NSObjCRuntime.h</strong></p>
<p>Any ideas what purpose they serve?</p> | 37,956,475 | 1 | 3 | null | 2016-06-21 23:38:10.533 UTC | 8 | 2017-06-14 00:22:10.277 UTC | 2017-06-14 00:22:10.277 UTC | null | 15,168 | user5412293 | null | null | 1 | 58 | ios|objective-c|xcode | 31,225 | <p>It's a convenience macro to save you typing <strong>nonnull</strong> in your headers. From the <em>Swift</em> blog detailing how new safety features have been incorporated back in <em>Objective-C</em>:</p>
<blockquote>
<p>To ease adoption of the new annotations, you can mark certain regions
of your Objective-C header files as audited for nullability. Within
these regions, any simple pointer type will be assumed to be nonnull.</p>
</blockquote>
<p>See Nullability and Objective-C - <a href="https://developer.apple.com/swift/blog/?id=25" rel="noreferrer">https://developer.apple.com/swift/blog/?id=25</a> </p> |
46,634,876 | How can I change a readonly property in TypeScript? | <p>I want to be able to make <code>readonly</code> properties (not getters) for users of my class, but I need to update them internally; is there a way to do this and allow to be changed internally? (and make sure TypeScript blocks most attempts to change the value)</p>
<p><em>(In my case it's a game engine and getters/setters [functions in general] are a bad option)</em></p> | 46,634,877 | 6 | 6 | null | 2017-10-08 18:55:10.75 UTC | 9 | 2019-11-17 19:31:32.17 UTC | 2017-10-10 17:05:43.84 UTC | null | 1,236,397 | null | 1,236,397 | null | 1 | 32 | typescript | 76,176 | <p>There are actually 3 ways I know of. If you have a class like this:</p>
<pre><code>class GraphNode {
readonly _parent: GraphNode;
add(newNode: GraphNode) { /* ...etc... */ }
}
var node = new GraphNode();
</code></pre>
<p>In the <code>add()</code> function you could do either:</p>
<ol>
<li><p><code>newNode[<any>'_parent'] = this;</code> - Works, but BAD IDEA. Refactoring will break this. </p>
<p><strong>Update:</strong> Seems <code>newNode['_parent'] = this;</code> will work just fine now without <code><any></code> in newer versions of TypeScript, but refactoring will still break it.</p></li>
<li><code>(<{_parent: GraphNode}>newNode)._parent = this;</code> - Better than 1 (not the best), and although refactoring breaks it, at least the compiler will tell you this time (since the type conversion will fail).</li>
<li><p>BEST: Create an INTERNAL interface (used by yourself only):</p>
<pre><code>interface IGraphObjectInternal { _parent: GraphNode; }
class GraphNode implements IGraphObjectInternal {
readonly _parent: GraphNode;
add(newNode: GraphNode) { /* ...etc... */ }
}
</code></pre>
<p>Now you can just do <code>(<IGraphObjectInternal>newNode)._parent = this;</code> and refactoring will also work. The only caveat is that if you export your class from a namespace (the only reason to use an internal interface IMO) you'll have to export the interface as well. For this reason, I sometimes will use #2 to completely lock down internals where there's only one place using it (and not advertise to the world), but usually #3 if I need to have many properties to work with referenced in many other locations (in case I need to refactor things).</p></li>
</ol>
<p>You may notice I didn't talk about getters/setters. While it is possible to use only a getter and no setter, then update a private variable, TypeScript does not protect you! I can easily do <code>object['_privateOrProtectedMember'] = whatever</code> and it will work. It does not work for the <code>readonly</code> modifier (which was in the question). Using the <code>readonly</code> modifier better locks down my properties (as far as working within the TypeScript compiler is concerned), and because JavaScript doesn't have a <code>readonly</code> modifier, I can use various methods to update them with workarounds on the JavaScript side (i.e. at runtime). ;)</p>
<p><strong>Warning:</strong> As I said, this only works within TypeScript. In JavaScript people can still modify your properties (unless you use getters only with non-exposed properties).</p>
<h1>Update</h1>
<p>Since typescript 2.8 you can now remove the readonly modifiers:</p>
<pre><code>type Writeable<T> = { -readonly [P in keyof T]: T[P] };
</code></pre>
<p>and also the <em>optional</em> modifier:</p>
<pre><code>type Writeable<T> = { -readonly [P in keyof T]-?: T[P] };
</code></pre>
<p>More here: <a href="https://github.com/Microsoft/TypeScript/wiki/What%27s-new-in-TypeScript#improved-control-over-mapped-type-modifiers" rel="noreferrer">Improved control over mapped type modifiers</a></p> |
33,188,077 | Sum of Column Values in Table - Rdlc report | <p>I have a Table in Rdlc report with 6 Columns and a dataset. A dll is added ( referenced ) to the Report, named RepHlpr.dll. This dll have a shared function <em>GetPar</em> which calculates and gets data from other databases. Column <em>Amount</em> is working fine and getting data as per the expression, As : <br> </p>
<p><a href="https://i.stack.imgur.com/fqhQU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fqhQU.png" alt="Expression Value of Column"></a></p>
<p>While getting Sum of <em>Copper</em> and <em>HP</em>, Everything Works fine because these column gets values from dataset.
<br>I am getting problem to get Sum of Values of <em>Amount</em>. I have tried Expressions :</p>
<pre><code>=Sum(Textbox44.Value)
=Sum(ReportItems!Textbox44.Value)
=Sum(Table1.Textbox44.Value)
</code></pre>
<p><a href="https://i.stack.imgur.com/cB1Wk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cB1Wk.png" alt="Sum Of Amount Column"></a></p>
<p><Br>
But Its showing Error : Textbox48 ( in which above expression is coded ) uses an aggregate function on a report item. Aggregate functions can be used only on report items contained in page headers and footers. <br>
<strong>Is there any way to get Sum of Column <em>Amount</em> ?</strong></p> | 33,188,462 | 2 | 3 | null | 2015-10-17 15:05:48.737 UTC | null | 2018-03-19 10:50:39.79 UTC | 2015-10-17 15:39:55.313 UTC | null | 3,542,539 | null | 3,542,539 | null | 1 | 3 | c#|.net|vb.net|winforms|rdlc | 46,314 | <p>You can apply Sum on your formula of that textbox instead of trying to apply it on the value of textbox:</p>
<pre><code>=Sum(Code.YourMethod(Fields!Filed1.Value, Fields!Filed2, otherParam), "YourDataSetName")
</code></pre>
<p>For example if name of your report data set is <code>"DataSet1"</code></p>
<pre><code>Sum(RepHlpr.RepHlpr.GetPar("Amt", Fields!hp.Value, Fields!make.Value), "DataSet1")
</code></pre>
<p><strong>Example</strong></p>
<p>I created a <code>Code</code> function:</p>
<pre><code>Public Function Multiply(ByVal value As Integer, factor As Integer) As Integer
Return value * factor
End Function
</code></pre>
<p>Then I set expression for my extra column that is not data bound:</p>
<pre><code>=Code.Multiply(Fields!Price.Value, 2)
</code></pre>
<p>Then I added a <code>TextBox</code> and set its <code>Sum</code> expression based on my custom column expression:</p>
<pre><code>=Sum(Code.Multiply(Fields!Price.Value, 2), "DataSet1")
</code></pre>
<p>And here is the screenshot:</p>
<p><a href="https://i.stack.imgur.com/lSVL1.png" rel="noreferrer"><img src="https://i.stack.imgur.com/lSVL1.png" alt="enter image description here"></a></p> |
23,176,284 | Difference between PrincipalSearcher and DirectorySearcher | <p>I see Active Directory examples that use <code>PrincipalSearcher</code> and other examples that do the same thing but use <code>DirectorySearcher</code>. What is the difference between these two examples? </p>
<p>Example using <code>PrincipalSearcher</code></p>
<pre><code>PrincipalContext context = new PrincipalContext(ContextType.Domain);
PrincipalSearcher search = new PrincipalSearcher(new UserPrincipal(context));
foreach( UserPrincipal user in search.FindAll() )
{
if( null != user )
Console.WriteLine(user.DistinguishedName);
}
</code></pre>
<p>Example using <code>DirectorySearcher</code></p>
<pre><code>DirectorySearcher search = new DirectorySearcher("(&(objectClass=user)(objectCategory=person))");
search.PageSize = 1000;
foreach( SearchResult result in search.FindAll() )
{
DirectoryEntry user = result.GetDirectoryEntry();
if( null != user )
Console.WriteLine(user.Properties["distinguishedName"].Value.ToString());
}
</code></pre> | 26,321,067 | 4 | 3 | null | 2014-04-19 22:26:40.963 UTC | 29 | 2021-08-22 03:16:00.047 UTC | 2017-09-18 11:32:53.073 UTC | null | 24,995 | null | 1,017,257 | null | 1 | 45 | c#|active-directory|directoryservices | 27,718 | <p>I've spent a lot of time analyzing the differences between these two. Here's what I've learned. </p>
<ul>
<li><p><code>DirectorySearcher</code> comes from the <code>System.DirectoryServices</code> namespace. </p></li>
<li><p><code>PrincipalSearcher</code> comes from the <code>System.DirectoryServices.AccountManagement</code> namespace, which is built on top of <code>System.DirectoryServices</code>. <code>PrincipalSearcher</code> internally uses <code>DirectorySearcher</code>. </p></li>
<li><p>The <code>AccountManagement</code> namespace (i.e. <code>PrincipalSearcher</code>) was designed to simplify management of User, Group, and Computer objects (i.e. Principals). In theory, it's usage should be easier to understand, and produce fewer lines of code. Though in my practice so far, it seems to heavily depend on what you're doing. </p></li>
<li><p><code>DirectorySearcher</code> is more low-level and can deal with more than just User, Group and Computer objects. </p></li>
<li><p>For general usage, when you're working with basic attributes and only a few objects, <code>PrincipalSearcher</code> will result in fewer lines of code and faster run time. </p></li>
<li><p>The advantage seems to disappear the more advanced the tasks you're doing become. For instance if you're expecting more than few hundred results, you'll have to get the underlying <code>DirectorySearcher</code> and set the <code>PageSize</code> </p>
<pre><code>DirectorySearcher ds = search.GetUnderlyingSearcher() as DirectorySearcher;
if( ds != null )
ds.PageSize = 1000;
</code></pre></li>
<li><p><code>DirectorySearcher</code> can be significantly faster than <code>PrincipalSearcher</code> if you make use of <code>PropertiesToLoad</code>. </p></li>
<li><p><code>DirectorySearcher</code> and like classes can work with all objects in AD, whereas <code>PrincipalSearcher</code> is much more limited. For example, you can not modify an Organizational Unit using <code>PrincipalSearcher</code> and like classes. </p></li>
</ul>
<p>Here is a chart I made to analyze using <code>PrincipalSearcher</code>, <code>DirectorySearcher</code> without using <code>PropertiesToLoad</code>, and <code>DirectorySearcher</code> with using <code>PropertiesToLoad</code>. All tests... </p>
<ul>
<li>Use a <code>PageSize</code> of <code>1000</code></li>
<li>Query a total of 4,278 user objects </li>
<li>Specify the following criteria
<ul>
<li><code>objectClass=user</code></li>
<li><code>objectCategory=person</code></li>
<li>Not a scheduling resource (i.e. <code>!msExchResourceMetaData=ResourceType:Room</code>)</li>
<li>Enabled (i.e. <code>!userAccountControl:1.2.840.113556.1.4.803:=2</code>) </li>
</ul></li>
</ul>
<p><img src="https://i.stack.imgur.com/pKs0x.png" alt="DirectorySearcher vs. PrincipalSearcher Performance Chart"></p>
<p><br /></p>
<h3>Code For Each Test</h3>
<hr>
<p><strong>Using <code>PrincipalSearcher</code></strong></p>
<pre><code>[DirectoryRdnPrefix("CN")]
[DirectoryObjectClass("Person")]
public class UserPrincipalEx: UserPrincipal
{
private AdvancedFiltersEx _advancedFilters;
public UserPrincipalEx( PrincipalContext context ): base(context)
{
this.ExtensionSet("objectCategory","User");
}
public new AdvancedFiltersEx AdvancedSearchFilter
{
get {
if( null == _advancedFilters )
_advancedFilters = new AdvancedFiltersEx(this);
return _advancedFilters;
}
}
}
public class AdvancedFiltersEx: AdvancedFilters
{
public AdvancedFiltersEx( Principal principal ):
base(principal) { }
public void Person()
{
this.AdvancedFilterSet("objectCategory", "person", typeof(string), MatchType.Equals);
this.AdvancedFilterSet("msExchResourceMetaData", "ResourceType:Room", typeof(string), MatchType.NotEquals);
}
}
//...
for( int i = 0; i < 10; i++ )
{
uint count = 0;
Stopwatch timer = Stopwatch.StartNew();
PrincipalContext context = new PrincipalContext(ContextType.Domain);
UserPrincipalEx filter = new UserPrincipalEx(context);
filter.Enabled = true;
filter.AdvancedSearchFilter.Person();
PrincipalSearcher search = new PrincipalSearcher(filter);
DirectorySearcher ds = search.GetUnderlyingSearcher() as DirectorySearcher;
if( ds != null )
ds.PageSize = 1000;
foreach( UserPrincipalEx result in search.FindAll() )
{
string canonicalName = result.CanonicalName;
count++;
}
timer.Stop();
Console.WriteLine("{0}, {1} ms", count, timer.ElapsedMilliseconds);
}
</code></pre>
<p><br /></p>
<p><strong>Using <code>DirectorySearcher</code></strong></p>
<pre><code>for( int i = 0; i < 10; i++ )
{
uint count = 0;
string queryString = "(&(objectClass=user)(objectCategory=person)(!msExchResourceMetaData=ResourceType:Room)(!userAccountControl:1.2.840.113556.1.4.803:=2))";
Stopwatch timer = Stopwatch.StartNew();
DirectoryEntry entry = new DirectoryEntry();
DirectorySearcher search = new DirectorySearcher(entry,queryString);
search.PageSize = 1000;
foreach( SearchResult result in search.FindAll() )
{
DirectoryEntry user = result.GetDirectoryEntry();
if( user != null )
{
user.RefreshCache(new string[]{"canonicalName"});
string canonicalName = user.Properties["canonicalName"].Value.ToString();
count++;
}
}
timer.Stop();
Console.WriteLine("{0}, {1} ms", count, timer.ElapsedMilliseconds);
}
</code></pre>
<p><br /></p>
<p><strong>Using <code>DirectorySearcher</code> with <code>PropertiesToLoad</code></strong> </p>
<p>Same as "Using <code>DirectorySearcher</code> but add this line</p>
<pre><code>search.PropertiesToLoad.AddRange(new string[] { "canonicalName" });
</code></pre>
<p>After </p>
<pre><code>search.PageSize = 1000;
</code></pre> |
1,528,834 | What can a single developer learn from Scrum? | <p>Let's say that a developer is interested in learning Scrum, but nobody else on the team is interested. I realize that Scrum is made for teams, and the process would have to be modified to fit a single person.</p>
<p>Is there any benefit to be gained by the developer trying Scrum, even if the team doesn't? If so, how would the process be modified to suit the situation?</p> | 1,528,857 | 5 | 2 | null | 2009-10-07 00:13:39.407 UTC | 9 | 2011-12-09 19:02:24.66 UTC | 2011-12-09 19:02:24.66 UTC | null | 3,043 | null | 108,105 | null | 1 | 12 | agile|scrum | 2,255 | <p>I think there's benefit to be gained by any method that helps you develop goals, tasks, keep on top of work and deliver something often.</p>
<p>Your individual work-products would gain the same advantages that teams gain with scrum:</p>
<ul>
<li>You'd get something <em>done</em> every {Sprint Iteration Period Here}, something you can hand off and say "This is now ready".</li>
<li>Your estimation technique will start to improve with reflection and retrospectives</li>
<li>You'll start to plan your day and make commitments to yourself about getting things done, so again your estimation of your capacity will increase</li>
<li>Retrospectives will formalize improvement of your personal work process. You'll start actively improving, removing and adapting to suit you and your individual needs.</li>
</ul>
<p>You wouldn't be able to rely on other team members to help out, which is a bit annoying, and you wouldn't have a product owner, Scrum master or a backlog to pick tasks from. You may not even be in a position to make decisions on what to work on next. But I think the formal discipline and reflection is helpful for all craft practitioners, at all levels, alone or in groups. </p>
<p>And who knows, you might even inspire your team to Scrum it up once they see what great results you're getting.</p> |
2,032,361 | what's polymorphic type in C++? | <p>I found in one article saying "static_cast is used for non-polymorphic type casting and dynamic_cast is used for polymorphic type casting". I understand that int and double are not polymorphic types. </p>
<p>However, I also found that static_cast can be used between base class and derived class. What does polymorphic type here mean? Some people says polymorphic type means the base class with virtual function. Is that right? Is this the only situation? What else? Can anybody could elaborate this for me more?</p> | 2,032,368 | 5 | 0 | null | 2010-01-09 04:39:00.227 UTC | 9 | 2015-09-06 21:55:14.143 UTC | null | null | null | null | 233,254 | null | 1 | 36 | c++ | 20,343 | <p>First of all, the article is not completely correct. <em>dynamic_cast</em> checks the type of an object and may fail, <em>static_cast</em> does not check and largely requires the programmer to know what they're doing (though it will issue compile errors for some egregious mistakes), but <strong>they may <em>both</em> be used in polymorphic situations</strong>. (<em>dynamic_cast</em> has the additional requirement that at least one of the involved types has a virtual method.)</p>
<p>Polymorphism in C++, in a nutshell, is <strong>using objects through a separately-defined interface</strong>. That interface is the base class, and it is almost always only useful to do this when it has virtual methods.</p>
<p>However, it's rare-but-possible to have polymorphism without any virtual methods; often this is a sign of either bad design or having to meet external requirements, and because of that, there's no way to give a good example that will fit here. ("You'll know when to use it when you see it," is, unfortunately, the best advice I can give you here.)</p>
<p>Polymorphism example:</p>
<pre><code>struct Animal {
virtual ~Animal() {}
virtual void speak() = 0;
};
struct Cat : Animal {
virtual void speak() { std::cout << "meow\n"; }
};
struct Dog : Animal {
virtual void speak() { std::cout << "wouf\n"; }
};
struct Programmer : Animal {
virtual void speak() {
std::clog << "I refuse to participate in this trite example.\n";
}
};
</code></pre>
<p>Exercising the above classes slightly—also see my <a href="https://stackoverflow.com/questions/1832003/instantiating-classes-by-name-with-factory-pattern/1837665#1837665">generic factory example</a>:</p>
<pre><code>std::auto_ptr<Animal> new_animal(std::string const& name) {
if (name == "cat") return std::auto_ptr<Animal>(new Cat());
if (name == "dog") return std::auto_ptr<Animal>(new Dog());
if (name == "human") return std::auto_ptr<Animal>(new Programmer());
throw std::logic_error("unknown animal type");
}
int main(int argc, char** argv) try {
std::auto_ptr<Animal> p = new_animal(argc > 1 ? argv[1] : "human");
p->speak();
return 0;
}
catch (std::exception& e) {
std::clog << "error: " << e.what() << std::endl;
return 1;
}
</code></pre>
<p>It's also possible to <a href="https://stackoverflow.com/questions/1041521/does-cs-file-have-an-object-oriented-interface">use polymorphism without inheritance</a>, as it's really a design <em>technique</em> or <em>style</em>. (I refuse to use the buzzword <em>pattern</em> here... :P)</p> |
2,308,479 | Simple Java HTTPS server | <p>I need to set up a really lightweight HTTPS server for a Java application. It's a simulator that's being used in our development labs to simulate the HTTPS connections accepted by a piece of equipment in the wild. Because it's purely a lightweight development tool and isn't used in production in any way at all, I'm quite happy to bypass certifications and as much negotiation as I can.</p>
<p>I'm planning on using the <code>HttpsServer</code> class in Java 6 SE but I'm struggling to get it working. As a test client, I'm using <code>wget</code> from the cygwin command line (<code>wget https://[address]:[port]</code>) but <code>wget</code> reports that it was "Unable to establish SSL connection".</p>
<p>If I run <code>wget</code> with the <code>-d</code> option for debugging it tells me "SSL handshake failed".</p>
<p>I've spent 30 minutes googling this and everything seems to just point back to the fairly useless Java 6 documentation that describes the methods but doesn't actually talk about how to get the darn thing talking or provide any example code at all.</p>
<p>Can anyone nudge me in the right direction?</p> | 2,323,188 | 5 | 0 | null | 2010-02-22 02:31:36.033 UTC | 28 | 2021-01-20 01:57:53.47 UTC | 2019-06-23 11:37:47.407 UTC | null | 775,954 | null | 826 | null | 1 | 53 | java|ssl|https|java-6 | 88,295 | <p>What I eventually used was this:</p>
<pre><code>try {
// Set up the socket address
InetSocketAddress address = new InetSocketAddress(InetAddress.getLocalHost(), config.getHttpsPort());
// Initialise the HTTPS server
HttpsServer httpsServer = HttpsServer.create(address, 0);
SSLContext sslContext = SSLContext.getInstance("TLS");
// Initialise the keystore
char[] password = "simulator".toCharArray();
KeyStore ks = KeyStore.getInstance("JKS");
FileInputStream fis = new FileInputStream("lig.keystore");
ks.load(fis, password);
// Set up the key manager factory
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, password);
// Set up the trust manager factory
TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
tmf.init(ks);
// Set up the HTTPS context and parameters
sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
httpsServer.setHttpsConfigurator(new HttpsConfigurator(sslContext) {
public void configure(HttpsParameters params) {
try {
// Initialise the SSL context
SSLContext c = SSLContext.getDefault();
SSLEngine engine = c.createSSLEngine();
params.setNeedClientAuth(false);
params.setCipherSuites(engine.getEnabledCipherSuites());
params.setProtocols(engine.getEnabledProtocols());
// Get the default parameters
SSLParameters defaultSSLParameters = c.getDefaultSSLParameters();
params.setSSLParameters(defaultSSLParameters);
} catch (Exception ex) {
ILogger log = new LoggerFactory().getLogger();
log.exception(ex);
log.error("Failed to create HTTPS port");
}
}
});
LigServer server = new LigServer(httpsServer);
joinableThreadList.add(server.getJoinableThread());
} catch (Exception exception) {
log.exception(exception);
log.error("Failed to create HTTPS server on port " + config.getHttpsPort() + " of localhost");
}
</code></pre>
<p>To generate a keystore:</p>
<pre><code>$ keytool -genkeypair -keyalg RSA -alias self_signed -keypass simulator \
-keystore lig.keystore -storepass simulator
</code></pre>
<p>See also <a href="https://download.oracle.com/javase/tutorial/security/toolsign/step3.html" rel="noreferrer">here</a>.</p>
<p>Potentially storepass and keypass might be different, in which case the <code>ks.load</code> and <code>kmf.init</code> must use storepass and keypass, respectively.</p> |
2,167,811 | Unit Testing ASP.NET DataAnnotations validation | <p>I am using DataAnnotations for my model validation i.e.</p>
<pre><code>[Required(ErrorMessage="Please enter a name")]
public string Name { get; set; }
</code></pre>
<p>In my controller, I am checking the value of ModelState. This is correctly returning false for invalid model data posted from my view.</p>
<p>However, when executing the unit test of my controller action, ModelState always returns true:</p>
<pre><code>[TestMethod]
public void Submitting_Empty_Shipping_Details_Displays_Default_View_With_Error()
{
// Arrange
CartController controller = new CartController(null, null);
Cart cart = new Cart();
cart.AddItem(new Product(), 1);
// Act
var result = controller.CheckOut(cart, new ShippingDetails() { Name = "" });
// Assert
Assert.IsTrue(string.IsNullOrEmpty(result.ViewName));
Assert.IsFalse(result.ViewData.ModelState.IsValid);
}
</code></pre>
<p>Do I need to do anything extra to set up the model validation in my tests?</p> | 2,167,852 | 5 | 0 | null | 2010-01-30 12:03:47.333 UTC | 25 | 2022-03-23 20:18:47.163 UTC | 2022-03-23 20:18:47.163 UTC | null | 4,294,399 | null | 231,216 | null | 1 | 84 | asp.net|asp.net-mvc|data-annotations | 37,947 | <p>Validation will be performed by the <code>ModelBinder</code>. In the example, you construct the <code>ShippingDetails</code> yourself, which will skip the <code>ModelBinder</code> and thus, validation entirely. Note the difference between input validation and model validation. Input validation is to make sure the user provided some data, given he had the chance to do so. If you provide a form without the associated field, the associated validator won't be invoked.</p>
<p>There have been changes in MVC2 on model validation vs. input validation, so the exact behaviour depends on the version you are using. See <a href="http://bradwilson.typepad.com/blog/2010/01/input-validation-vs-model-validation-in-aspnet-mvc.html" rel="noreferrer">http://bradwilson.typepad.com/blog/2010/01/input-validation-vs-model-validation-in-aspnet-mvc.html</a> for details on this regarding both MVC and MVC 2.</p>
<p>[EDIT] I guess the cleanest solution to this is to call <code>UpdateModel</code> on the Controller manually when testing by providing a custom mock <code>ValueProvider</code>. That should fire validation and set the <code>ModelState</code> correctly. </p> |
1,357,960 | Qt jpg image display | <p>I want to display .jpg image in an Qt UI. I checked it online and found <a href="http://qt-project.org/doc/qt-4.8/widgets-imageviewer.html" rel="noreferrer">http://qt-project.org/doc/qt-4.8/widgets-imageviewer.html</a>. I thought Graphics View will do the same, and also it has codec to display video. How to display images using Graphics View? I went through the libraries, but because I am a totally newbie in Qt, I can't find a clue to start with. Can you direct me to some resources/examples on how to load and display images in Qt?</p>
<p>Thanks.</p> | 1,360,907 | 7 | 0 | null | 2009-08-31 15:17:21.967 UTC | 20 | 2020-02-11 18:47:10.083 UTC | 2013-11-16 20:36:47.92 UTC | null | 89,435 | null | 90,765 | null | 1 | 58 | image|qt|graphics|video|view | 169,877 | <pre><code>#include ...
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QGraphicsScene scene;
QGraphicsView view(&scene);
QGraphicsPixmapItem item(QPixmap("c:\\test.png"));
scene.addItem(&item);
view.show();
return a.exec();
}
</code></pre>
<p>This should work. :) List of supported formats can be <a href="http://qt-project.org/doc/qt-5.0/qtgui/qpixmap.html#reading-and-writing-image-files" rel="noreferrer">found here</a></p> |
1,445,919 | How to enable wire logging for a java HttpURLConnection traffic? | <p>I've used <a href="http://hc.apache.org/httpclient-3.x/index.html" rel="noreferrer">Jakarta commons HttpClient</a> in another project and I would like the same <a href="http://hc.apache.org/httpclient-3.x/logging.html" rel="noreferrer">wire logging</a> output but using the "standard" HttpUrlConnection.</p>
<p>I've used <a href="http://www.fiddler2.com/fiddler2/" rel="noreferrer">Fiddler</a> as a proxy but I would like to log the traffic directly from java.</p>
<p>Capturing what goes by the connection input and output streams is not enough because the HTTP headers are written and consumed by the HttpUrlConnection class, so I will not be able to log the headers.</p> | 2,272,332 | 8 | 0 | null | 2009-09-18 17:38:03.827 UTC | 11 | 2019-01-23 09:37:06.22 UTC | 2014-06-09 08:15:02.99 UTC | null | 603,516 | null | 34,009 | null | 1 | 53 | java|http|logging|httpurlconnection | 70,996 | <p>I've been able to log all SSL traffic implementing my own <a href="http://java.sun.com/javase/6/docs/api/javax/net/ssl/SSLSocketFactory.html" rel="noreferrer">SSLSocketFactory</a> on top of the default one. </p>
<p>This worked for me because all of our connections are using HTTPS and we can set the socket factory with the method <a href="http://java.sun.com/javase/6/docs/api/javax/net/ssl/HttpsURLConnection.html#setSSLSocketFactory(javax.net.ssl.SSLSocketFactory)" rel="noreferrer">HttpsURLConnection.setSSLSocketFactory</a>. </p>
<p>A more complete solution that enables monitoring on all sockets can be found at <a href="http://www.javaspecialists.eu/archive/Issue169.html" rel="noreferrer">http://www.javaspecialists.eu/archive/Issue169.html</a>
Thanks to <a href="https://stackoverflow.com/users/8946">Lawrence Dol</a> for pointing in the right direction of using <a href="http://java.sun.com/javase/6/docs/api/java/net/Socket.html#setSocketImplFactory(java.net.SocketImplFactory)" rel="noreferrer">Socket.setSocketImplFactory</a></p>
<p>Here is my not ready for production code:</p>
<pre><code>public class WireLogSSLSocketFactory extends SSLSocketFactory {
private SSLSocketFactory delegate;
public WireLogSSLSocketFactory(SSLSocketFactory sf0) {
this.delegate = sf0;
}
public Socket createSocket(Socket s, String host, int port,
boolean autoClose) throws IOException {
return new WireLogSocket((SSLSocket) delegate.createSocket(s, host, port, autoClose));
}
/*
...
*/
private static class WireLogSocket extends SSLSocket {
private SSLSocket delegate;
public WireLogSocket(SSLSocket s) {
this.delegate = s;
}
public OutputStream getOutputStream() throws IOException {
return new LoggingOutputStream(delegate.getOutputStream());
}
/*
...
*/
private static class LoggingOutputStream extends FilterOutputStream {
private static final Logger logger = Logger.getLogger(WireLogSocket.LoggingOutputStream.class);
//I'm using a fixed charset because my app always uses the same.
private static final String CHARSET = "ISO-8859-1";
private StringBuffer sb = new StringBuffer();
public LoggingOutputStream(OutputStream out) {
super(out);
}
public void write(byte[] b, int off, int len)
throws IOException {
sb.append(new String(b, off, len, CHARSET));
logger.info("\n" + sb.toString());
out.write(b, off, len);
}
public void write(int b) throws IOException {
sb.append(b);
logger.info("\n" + sb.toString());
out.write(b);
}
public void close() throws IOException {
logger.info("\n" + sb.toString());
super.close();
}
}
}
}
</code></pre> |
1,851,181 | Why should #ifdef be avoided in .c files? | <p>A programmer I respect said that in C code, <code>#if</code> and <code>#ifdef</code> should be avoided at all costs, except possibly in header files. Why would it be considered bad programming practice to use <code>#ifdef</code> in a .c file?</p> | 1,851,183 | 11 | 0 | null | 2009-12-05 05:06:44.133 UTC | 18 | 2021-01-13 09:58:21.277 UTC | null | null | null | null | 41,661 | null | 1 | 32 | c|conditional-compilation | 12,348 | <p>Hard to maintain. Better use interfaces to abstract platform specific code than abusing conditional compilation by scattering <code>#ifdef</code>s all over your implementation.</p>
<p>E.g.</p>
<pre><code>void foo() {
#ifdef WIN32
// do Windows stuff
#else
// do Posix stuff
#endif
// do general stuff
}
</code></pre>
<p>Is not nice. Instead have files <code>foo_w32.c</code> and <code>foo_psx.c</code> with</p>
<p>foo_w32.c:</p>
<pre><code>void foo() {
// windows implementation
}
</code></pre>
<p>foo_psx.c:</p>
<pre><code>void foo() {
// posix implementation
}
</code></pre>
<p>foo.h:</p>
<pre><code>void foo(); // common interface
</code></pre>
<p>Then have 2 makefiles<sup>1</sup>: <code>Makefile.win</code>, <code>Makefile.psx</code>, with each compiling the appropriate <code>.c</code> file and linking against the right object.</p>
<p>Minor amendment:</p>
<p>If <code>foo()</code>'s implementation depends on some code that appears in all platforms, E.g. <code>common_stuff()</code><sup>2</sup>, simply call that in your <code>foo()</code> implementations.</p>
<p>E.g.</p>
<p>common.h:</p>
<pre><code>void common_stuff(); // May be implemented in common.c, or maybe has multiple
// implementations in common_{A, B, ...} for platforms
// { A, B, ... }. Irrelevant.
</code></pre>
<p>foo_{w32, psx}.c:</p>
<pre><code>void foo() { // Win32/Posix implementation
// Stuff
...
if (bar) {
common_stuff();
}
}
</code></pre>
<p>While you may be repeating a function call to <code>common_stuff()</code>, you can't parameterize your definition of <code>foo()</code> per platform unless it follows a very specific pattern. Generally, platform differences require completely different implementations and don't follow such patterns.</p>
<hr>
<ol>
<li>Makefiles are used here illustratively. Your build system may not use <code>make</code> at all, such as if you use Visual Studio, CMake, Scons, etc.</li>
<li>Even if <code>common_stuff()</code> actually has multiple implementations, varying per platform.</li>
</ol> |
1,538,676 | Uppercasing First Letter of Words Using SED | <p>How do you replace the first letter of a word into Capital letter,
e.g.</p>
<pre><code>Trouble me
Gold rush brides
</code></pre>
<p>into </p>
<pre><code>Trouble Me
Gold Rush Brides
</code></pre> | 1,538,818 | 11 | 1 | null | 2009-10-08 15:50:33.143 UTC | 15 | 2022-09-13 01:21:42.233 UTC | 2021-04-09 21:31:45.513 UTC | null | 1,783,588 | null | 67,405 | null | 1 | 54 | linux|bash|unix|awk|sed | 56,733 | <p>This line should do it:</p>
<pre><code>sed -e "s/\b\(.\)/\u\1/g"
</code></pre> |
1,483,732 | SET NOCOUNT ON usage | <p>Inspired by <a href="https://stackoverflow.com/questions/1483383/is-this-stored-procedure-thread-safe-or-whatever-the-equiv-is-on-sql-server">this question</a> where there are differing views on SET NOCOUNT...</p>
<blockquote>
<p>Should we use SET NOCOUNT ON for SQL Server? If not, why not?</p>
</blockquote>
<p><strong>What it does</strong> Edit 6, on 22 Jul 2011</p>
<p>It suppresses the "xx rows affected" message after any DML. This is a resultset and when sent, the client must process it. It's tiny, but measurable (see answers below)</p>
<p>For triggers etc, the client will receive multiple "xx rows affected" and this causes all manner of errors for some ORMs, MS Access, JPA etc (see edits below)</p>
<p><strong>Background:</strong></p>
<p>General accepted best practice (I thought until this question) is to use <code>SET NOCOUNT ON</code> in triggers and stored procedures in SQL Server. We use it everywhere and a quick google shows plenty of SQL Server MVPs agreeing too.</p>
<p>MSDN says this can break a <a href="http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldataadapter.aspx" rel="noreferrer">.net SQLDataAdapter</a>.</p>
<p>Now, this means to me that the SQLDataAdapter is limited to utterly simply CRUD processing because it expects the "n rows affected" message to match. So, I can't use:</p>
<ul>
<li>IF EXISTS to avoid duplicates (no rows affected message) <em>Note: use with caution</em></li>
<li>WHERE NOT EXISTS (less rows then expected</li>
<li>Filter out trivial updates (eg no data actually changes)</li>
<li>Do any table access before (such as logging)</li>
<li>Hide complexity or denormlisation</li>
<li>etc</li>
</ul>
<p>In the question marc_s (who knows his SQL stuff) says do not use it. This differs to what I think (and I regard myself as somewhat competent at SQL too).</p>
<p>It's possible I'm missing something (feel free to point out the obvious), but what do you folks out there think?</p>
<p>Note: it's been years since I saw this error because I don't use SQLDataAdapter nowadays.</p>
<p><strong>Edits after comments and questions:</strong></p>
<p>Edit: More thoughts...</p>
<p>We have multiple clients: one may use a C# SQLDataAdaptor, another may use nHibernate from Java. These can be affected in different ways with <code>SET NOCOUNT ON</code>.</p>
<p>If you regard stored procs as methods, then it's bad form (anti-pattern) to assume some internal processing works a certain way for your own purposes.</p>
<p>Edit 2: a <a href="https://stackoverflow.com/questions/1354362">trigger breaking nHibernate question</a>, where <code>SET NOCOUNT ON</code> can not be set</p>
<p>(and no, it's not a duplicate of <a href="https://stackoverflow.com/questions/995589/set-nocount-off-or-return-rowcount">this</a>)</p>
<p>Edit 3: Yet more info, thanks to my MVP colleague</p>
<ul>
<li><a href="http://support.microsoft.com/?scid=kb%3Ben-us%3B240882&x=4&y=9" rel="noreferrer">KB 240882</a>, issue causing disconnects on SQL 2000 and earlier</li>
<li><a href="http://sqlmag.com/sql-server-2000/seeing-believing" rel="noreferrer">Demo of performance gain</a> </li>
</ul>
<p>Edit 4: 13 May 2011</p>
<p><a href="https://stackoverflow.com/q/5880413/27535">Breaks Linq 2 SQL too when not specified?</a></p>
<p>Edit 5: 14 Jun 2011</p>
<p>Breaks JPA, stored proc with table variables: <a href="https://stackoverflow.com/q/6344631/27535">Does JPA 2.0 support SQL Server table variables?</a></p>
<p>Edit 6: 15 Aug 2011</p>
<p>The SSMS "Edit rows" data grid requires SET NOCOUNT ON: <a href="https://stackoverflow.com/q/7067329/27535">Update trigger with GROUP BY</a></p>
<p>Edit 7: 07 Mar 2013</p>
<p>More in depth details from @RemusRusanu:<br> <a href="https://stackoverflow.com/questions/1915405/does-set-nocount-on-really-make-that-much-of-a-performance-difference/1918085#1918085">Does SET NOCOUNT ON really make that much of a performance difference</a></p> | 1,547,539 | 17 | 7 | 2013-06-07 08:07:07.217 UTC | 2009-09-27 14:52:29.403 UTC | 123 | 2020-09-02 10:07:09.237 UTC | 2017-05-23 11:47:26.613 UTC | null | -1 | null | 27,535 | null | 1 | 354 | sql|sql-server|tsql|ado.net|concurrency | 306,641 | <p>Ok now I've done my research, here is the deal:</p>
<p>In TDS protocol, <code>SET NOCOUNT ON</code> only saves <a href="https://msdn.microsoft.com/en-us/library/dd340553.aspx" rel="noreferrer">9-bytes per query</a> while the text "SET NOCOUNT ON" itself is a whopping 14 bytes. I used to think that <code>123 row(s) affected</code> was returned from server in plain text in a separate network packet but that's not the case. It's in fact a small structure called <code>DONE_IN_PROC</code> embedded in the response. It's not a separate network packet so no roundtrips are wasted.</p>
<p>I think you can stick to default counting behavior almost always without worrying about the performance. There are some cases though, where calculating the number of rows beforehand would impact the performance, such as a forward-only cursor. In that case NOCOUNT might be a necessity. Other than that, there is absolutely no need to follow "use NOCOUNT wherever possible" motto.</p>
<p>Here is a very detailed analysis about insignificance of <code>SET NOCOUNT</code> setting: <a href="http://daleburnett.com/2014/01/everything-ever-wanted-know-set-nocount/" rel="noreferrer">http://daleburnett.com/2014/01/everything-ever-wanted-know-set-nocount/</a></p> |
1,582,285 | How to remove elements from a generic list while iterating over it? | <p>I am looking for a better <strong><em>pattern</em></strong> for working with a list of elements which each need processed and then depending on the outcome are removed from the list. </p>
<p>You can't use <code>.Remove(element)</code> inside a <code>foreach (var element in X)</code> (because it results in <code>Collection was modified; enumeration operation may not execute.</code> exception)... you also can't use <code>for (int i = 0; i < elements.Count(); i++)</code> and <code>.RemoveAt(i)</code> because it disrupts your current position in the collection relative to <code>i</code>.</p>
<p>Is there an elegant way to do this?</p> | 1,582,317 | 28 | 0 | null | 2009-10-17 14:12:35.363 UTC | 109 | 2022-04-06 09:37:42.713 UTC | 2017-01-16 12:23:29.943 UTC | null | 3,682,162 | null | 191,693 | null | 1 | 553 | c#|list|loops|generics|key-value | 497,350 | <p>Iterate your list in reverse with a for loop:</p>
<pre><code>for (int i = safePendingList.Count - 1; i >= 0; i--)
{
// some code
// safePendingList.RemoveAt(i);
}
</code></pre>
<p>Example:</p>
<pre><code>var list = new List<int>(Enumerable.Range(1, 10));
for (int i = list.Count - 1; i >= 0; i--)
{
if (list[i] > 5)
list.RemoveAt(i);
}
list.ForEach(i => Console.WriteLine(i));
</code></pre>
<p>Alternately, you can use the <a href="http://msdn.microsoft.com/en-us/library/wdka673a.aspx" rel="noreferrer">RemoveAll method</a> with a predicate to test against:</p>
<pre><code>safePendingList.RemoveAll(item => item.Value == someValue);
</code></pre>
<p>Here's a simplified example to demonstrate:</p>
<pre><code>var list = new List<int>(Enumerable.Range(1, 10));
Console.WriteLine("Before:");
list.ForEach(i => Console.WriteLine(i));
list.RemoveAll(i => i > 5);
Console.WriteLine("After:");
list.ForEach(i => Console.WriteLine(i));
</code></pre> |
18,200,035 | How do you convert a String to a float or int? | <p>In an Arduino program I'm working on the GPS sends the coordinates to the arduino through USB. Because of this, the incoming coordinates are stored as Strings. Is there any way to convert the GPS coordinates to a float or int? </p>
<p>I've tried <code>int gpslong = atoi(curLongitude)</code> and <code>float gpslong = atof(curLongitude)</code>, but they both cause Arduino to give an error:</p>
<pre><code>error: cannot convert 'String' to 'const char*' for argument '1' to 'int atoi(const char*)'
</code></pre>
<p>Does anyone have any suggestions?</p> | 18,200,065 | 5 | 0 | null | 2013-08-13 03:07:19.6 UTC | 2 | 2017-07-18 23:30:03.367 UTC | 2013-08-13 03:24:58.973 UTC | null | 1,204,143 | null | 2,677,031 | null | 1 | 15 | arduino | 78,339 | <p>You can get an <code>int</code> from a <code>String</code> by just calling <a href="http://arduino.cc/en/Reference/StringToInt" rel="noreferrer"><code>toInt</code></a> on the <code>String</code> object (e.g. <code>curLongitude.toInt()</code>).</p>
<p>If you want a <code>float</code>, you can use <code>atof</code> in conjunction with the <a href="http://arduino.cc/en/Reference/StringToCharArray" rel="noreferrer"><code>toCharArray</code></a> method:</p>
<pre><code>char floatbuf[32]; // make this at least big enough for the whole string
curLongitude.toCharArray(floatbuf, sizeof(floatbuf));
float f = atof(floatbuf);
</code></pre> |
18,157,322 | Find the sum of all the primes below two million. Project euler, C | <p>So, everything seems to be working nicely, but the program doesn't give me the correct answer. Mine is 142,915,960,832, whereas it should be 142,913,828,922. The differece is 2,131,910 (if I still can subtract numbers on paper haha) and I have no idea where did I get those two millions. Could anyone help me?</p>
<pre><code>#include <stdio.h>
#include <math.h>
#define BELOW 2000000
int isaprime (int num);
int main (void) {
int i;
float sum = 0;
for (i = 2; i < BELOW; i++) {
if (isaprime(i) == 1) {
sum = sum + i;
printf ("\n%d\t%.1f", i, sum);
}
}
getch();
return 0;
}
int isaprime (int num) {
int i;
for (i = 2; i <= sqrt(num); i++) {
if (num % i == 0) {
return 0;
}
else {
;
}
}
return 1;
}
</code></pre> | 18,157,441 | 9 | 22 | null | 2013-08-09 23:58:28.963 UTC | 2 | 2019-01-17 18:21:07.127 UTC | 2015-01-22 16:41:51.897 UTC | user2555451 | null | null | 2,476,330 | null | 1 | 7 | c | 46,718 | <p>Using <a href="http://en.wikipedia.org/wiki/Single_precision_floating-point_format" rel="noreferrer"><code>float</code></a> as the <code>sum</code> is the problem. The largest integer <code>k</code> such that all integers from <code>[-k, k]</code> are <em>exactly</em> representable in 32-bit float is 2^24<sup>1</sup>; after that you will start losing precision in some integers. Since your sum is outside that range that, by an absurd margin, you lose precision and all bets are off.</p>
<p>You need to change to a larger type like <code>long</code> (assuming it's 64-bits on your machine). Make the change, and you'll get right answer (as I did with you code):</p>
<pre><code>[ec2-user@ip-10-196-190-10 ~]$ cat -n euler.c
1 #include <stdio.h>
2 #include <math.h>
3
4 #define BELOW 2000000
5
6 int isaprime (int num);
7
8 int main (void) {
9
10 int i;
11 long sum = 0;
12
13 for (i = 2; i < BELOW; i++) {
14
15 if (isaprime(i) == 1) {
16 sum = sum + i;
17 }
18 }
19 printf("sum: %ld\n", sum);
20
21 return 0;
22 }
23
24 int isaprime (int num) {
25
26 int i;
27
28 for (i = 2; i <= sqrt(num); i++) {
29 if (num % i == 0) {
30 return 0;
31 }
32 else {
33 ;
34 }
35 }
36
37 return 1;
38 }
[ec2-user@ip-10-196-190-10 ~]$ gcc euler.c -lm
[ec2-user@ip-10-196-190-10 ~]$ ./a.out
sum: 142913828922
</code></pre>
<p><sup>1</sup>: 23 explicit bits in the mantissa plus one hidden bit.</p> |
6,648,260 | What does "upvalue" mean in Mathematica and when to use them? | <p>To me, <code>g /: f[g[x_]] := h[x]</code> is just verbose equivalent of <code>f[g[x_]] := h[x]</code>. Can you raise an example that you have to use <code>/:</code>?</p> | 6,650,884 | 3 | 3 | null | 2011-07-11 09:37:30.54 UTC | 17 | 2020-01-13 19:38:38.4 UTC | null | null | null | null | 667,027 | null | 1 | 23 | wolfram-mathematica | 3,625 | <p>Actually, <code>g /: f[g[x_]] := h[x]</code> is not equivalent to <code>f[g[x_]] := h[x]</code>. The latter associates the definition with <code>f</code>, while <a href="http://reference.wolfram.com/mathematica/ref/TagSet.html?q=TagSet&lang=en" rel="nofollow noreferrer"><code>TagSet</code></a> (<code>/:</code>) and <a href="http://reference.wolfram.com/mathematica/ref/UpSet.html?q=UpSet&lang=en" rel="nofollow noreferrer"><code>UpSet</code></a> (<code>^=</code> and its <a href="http://reference.wolfram.com/mathematica/ref/UpSetDelayed.html?q=UpSetDelayed&lang=en" rel="nofollow noreferrer">delayed version</a>, <code>^:=</code>) associate the definition with <code>g</code>. This is a crucial difference and can be illustrated by a simple example. Let's say you want to have a set of variables that obey modulo 5 addition, i.e. 6 + 7 mod 5 = 3. So, we want anything with <code>Head</code> <code>mod</code> to behave correctly. Initially, we'd think that </p>
<pre><code>a_mod + b_mod := mod@Mod[a + b, 5]
</code></pre>
<p>would work. But, it generates the error</p>
<pre><code>SetDelayed::write : Tag Plus in a_mod + b_mod is Protected.
</code></pre>
<p>We could remove <code>Unprotect</code> <code>Plus</code> and our definition would then work, but this may cause problems with other definitions and as <code>Plus</code> accumulates more definitions, it would slow down. Alternatively, we can associate the addition property with the <code>mod</code> object itself via <code>TagSet</code> </p>
<pre><code>mod /: mod[a_] + mod[b_] := mod @ Mod[a + b, 5]
</code></pre>
<p>or <code>UpSetDelayed</code></p>
<pre><code>mod[a_] + mod[b_] ^:= mod @ Mod[a + b, 5]
</code></pre>
<p>Setting an <a href="http://reference.wolfram.com/mathematica/ref/UpValues.html?q=UpValues&lang=en" rel="nofollow noreferrer">upvalue</a> is somewhat more correct from a conceptual point of view since <code>mod</code> is the one with the different property. </p>
<p>There are a couple of issues to be aware of. First, the upvalue mechanism can only scan one level deep, i.e. <code>Plus[a_mod, b_mod]</code> is fine, but <code>Exp[Plus[a_mod, b_mod]]</code> will throw an error. This may require you to get creative with an intermediate type. Secondly, from a coding perspective <code>UpSetDelayed</code> is easier to write, but occasionally there is some ambiguity as to which <code>Head</code> is the upvalue associated with. <code>TagSet</code> handles that by explicitly naming the appropriate <code>Head</code>, and in general, it is what I tend to prefer over <code>UpSet</code>.</p>
<p>Some of Mathematica's operators do not have any behavior associated with them, so they're not protected. For these operators, you can define functions as you wish. For instance, I've defined </p>
<pre><code>a_ \[CircleTimes] b_ := KroneckerProduct[a,b]
a_ \[CircleTimes] b_ \[CircleTimes] c__ := a \[CircleTimes] ( b \[CircleTimes] c )
</code></pre>
<p>and</p>
<pre><code>a_ \[CirclePlus] b__ := BlockDiagonal[{a,b}]
</code></pre>
<p>to provide convenient shorthand notations for matrix operations that I use a lot.</p>
<p>My example above was a little contrived, but there are a number of times <code>UpValues</code> have come in handy. For example, I found that I needed a symbolic form for the complex roots of unity that behaved appropriately under multiplication and exponentiation. </p>
<p><strong>Example</strong>: A straightforward and useful example is marking a <code>Symbol</code> as Real: </p>
<pre><code>makeReal[a__Symbol] := (
# /: Element[#, Reals] := True;
# /: Im[#] := 0;
# /: Re[#] := #;
# /: Abs[#] := Sign[#] #;
# /: Arg[#] := Piecewise[{{0, Sign[#] >= 0}, {Pi, Sign[#] < 0}}]
) & /@ List[a]
</code></pre>
<p>Note the use of <code>TagSet</code> as <code>Element[ a, Reals ] ^:= True</code> would be ambiguous. What would the rule be attached to <code>a</code> or <code>Reals</code>? Also, if we wanted a positive real number, we could set <code>Arg[#]:=0</code> which allows <code>Simplify</code> to behave as expected, e.g. <code>Simplify[Sqrt[a^2]] == a</code>. </p> |
6,574,636 | Serializing Map<Date, String> with Jackson | <p>I want to serialize a Map with Jackson.
The Date should be serialized as a timestamp, like all my other dates.</p>
<p>The following code renders the keys in the form "Tue Mar 11 00:00:00 CET 1952" (which is Date.toString()) instead of the timestamp.</p>
<pre><code>Map<Date, String> myMap = new HashMap<Date, String>();
...
ObjectMapper.writeValue(myMap)
</code></pre>
<p>I assume this is because of type erasure and jackson doesn't know at runtime that the key is a Date. But I didn't find a way to pass a TypeReference to any writeValue method.</p>
<p>Is there a simple way to achieve my desired behaviour or are all keys always rendered as Strings by jackson?</p>
<p>Thanks for any hint.</p> | 6,574,980 | 3 | 1 | null | 2011-07-04 17:51:07.1 UTC | 11 | 2019-06-25 19:12:29.123 UTC | null | null | null | null | 321,388 | null | 1 | 37 | generics|serialization|jackson|type-erasure | 31,321 | <p>The default map key serializer is <code>StdKeySerializer</code>, and it simply does this.</p>
<pre><code>String keyStr = (value.getClass() == String.class) ? ((String) value) : value.toString();
jgen.writeFieldName(keyStr);
</code></pre>
<p>You could make use of <a href="https://fasterxml.github.io/jackson-databind/javadoc/2.9/com/fasterxml/jackson/databind/module/SimpleModule.html" rel="noreferrer">the SimpleModule feature</a>, and specify a custom key serializer, using the <code>addKeySerializer</code> method.</p>
<hr>
<p>And here's how that could be done.</p>
<pre class="lang-java prettyprint-override"><code>import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.Version;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.ObjectWriter;
import org.codehaus.jackson.map.SerializerProvider;
import org.codehaus.jackson.map.module.SimpleModule;
import org.codehaus.jackson.map.type.MapType;
import org.codehaus.jackson.map.type.TypeFactory;
public class CustomKeySerializerDemo
{
public static void main(String[] args) throws Exception
{
Map<Date, String> myMap = new HashMap<Date, String>();
myMap.put(new Date(), "now");
Thread.sleep(100);
myMap.put(new Date(), "later");
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writeValueAsString(myMap));
// {"Mon Jul 04 11:38:36 MST 2011":"now","Mon Jul 04 11:38:36 MST 2011":"later"}
SimpleModule module =
new SimpleModule("MyMapKeySerializerModule",
new Version(1, 0, 0, null));
module.addKeySerializer(Date.class, new DateAsTimestampSerializer());
MapType myMapType = TypeFactory.defaultInstance().constructMapType(HashMap.class, Date.class, String.class);
ObjectWriter writer = new ObjectMapper().withModule(module).typedWriter(myMapType);
System.out.println(writer.writeValueAsString(myMap));
// {"1309806289240":"later","1309806289140":"now"}
}
}
class DateAsTimestampSerializer extends JsonSerializer<Date>
{
@Override
public void serialize(Date value, JsonGenerator jgen, SerializerProvider provider)
throws IOException, JsonProcessingException
{
jgen.writeFieldName(String.valueOf(value.getTime()));
}
}
</code></pre>
<hr>
<p>Update for the latest Jackson (2.0.4):</p>
<pre class="lang-java prettyprint-override"><code>import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.type.MapType;
import com.fasterxml.jackson.databind.type.TypeFactory;
public class CustomKeySerializerDemo
{
public static void main(String[] args) throws Exception
{
Map<Date, String> myMap = new HashMap<Date, String>();
myMap.put(new Date(), "now");
Thread.sleep(100);
myMap.put(new Date(), "later");
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writeValueAsString(myMap));
// {"2012-07-13T21:14:09.499+0000":"now","2012-07-13T21:14:09.599+0000":"later"}
SimpleModule module = new SimpleModule();
module.addKeySerializer(Date.class, new DateAsTimestampSerializer());
MapType myMapType = TypeFactory.defaultInstance().constructMapType(HashMap.class, Date.class, String.class);
ObjectWriter writer = new ObjectMapper().registerModule(module).writerWithType(myMapType);
System.out.println(writer.writeValueAsString(myMap));
// {"1342214049499":"now","1342214049599":"later"}
}
}
class DateAsTimestampSerializer extends JsonSerializer<Date>
{
@Override
public void serialize(Date value, JsonGenerator jgen, SerializerProvider provider)
throws IOException, JsonProcessingException
{
jgen.writeFieldName(String.valueOf(value.getTime()));
}
}
</code></pre> |
6,487,885 | Generating data dictionary for SQL Server database | <p>I am trying to generate a data dictionary for a table in my database. </p>
<p>Ideally I would like to export the column names, data type, restrictions and extended property descriptions. </p>
<p>How can this be achieved?</p> | 6,487,925 | 4 | 0 | null | 2011-06-27 01:37:52.51 UTC | 4 | 2022-07-22 06:22:13.003 UTC | 2011-09-13 16:16:00.09 UTC | null | 23,199 | null | 788,522 | null | 1 | 9 | sql-server|sql-server-2008|data-dictionary | 38,367 | <p>You can get at this via a combination of <code>SELECT * FROM INFORMATION_SCHEMA.COLUMNS</code> and using <a href="http://msdn.microsoft.com/en-us/library/ms179853.aspx" rel="noreferrer"><code>fn_listextendedproperty</code></a>.</p> |
6,638,517 | Make a form's background transparent | <p>How I make a background transparent on my form? Is it possible in C#?</p>
<p>Thanks in advance!</p> | 6,638,537 | 4 | 0 | null | 2011-07-10 01:07:15.363 UTC | 3 | 2019-02-20 08:21:47.717 UTC | 2011-07-10 18:37:50.527 UTC | null | 707,111 | null | 447,979 | null | 1 | 14 | c#|.net|winforms|background | 60,473 | <p>You can set the <code>BackColor</code> of your form to an uncommon color (say <code>Color.Magenta</code>) then set the form's <code>TransparencyKey</code> property to the same color. Then, set the <code>FormBorderStyle</code> to <code>None</code>.</p>
<p>Of course, that's just the quick and easy solution. The edges of controls are ugly, you have to keep changing the background color of new controls you add (if they're Buttons or something like that) and a whole host of other problems.</p>
<p>It really depends what you want to achieve. What is it? If you want to make a widget sort of thing, there are much better ways. If you need rounded corners or a custom background, there are much better ways. So please provide some more information if <code>TransparencyKey</code> isn't quite what you had in mind.</p> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.