qid
int64 4
8.14M
| question
stringlengths 20
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list | input
stringlengths 12
45k
| output
stringlengths 2
31.8k
|
---|---|---|---|---|---|---|
195,991 |
<p>For explanation imagine a simple address. Written in a HTML paragraph with line breaks it would like this:</p>
<pre><code>Street: Example Street 1
City: Vienna
Zip Code: 1010
Country: Austria
</code></pre>
<p>Most of the time that's completely okay, but sometimes I have to achieve the following output:</p>
<pre><code>Street: Example Street 1
City: Vienna
Zip Code: 1010
Country: Austria
</code></pre>
<p>My thoughts so far:</p>
<ol>
<li>Should be valid XHTML and work or degrade gracefully in all major browsers</li>
<li>Using tags in a semantically correct way is strongly preferred</li>
<li>Because of point two: I hope there's a better solution than tables</li>
<li>The problem is not limited to addresses - would be useful in other situation too</li>
</ol>
<p>How do you achieve this output (using HTML and/or CSS)?</p>
|
[
{
"answer_id": 196004,
"author": "Henrik Paul",
"author_id": 2238,
"author_profile": "https://Stackoverflow.com/users/2238",
"pm_score": 2,
"selected": false,
"text": "<p>Tables are the way to go.</p>\n"
},
{
"answer_id": 196007,
"author": "Kornel",
"author_id": 27009,
"author_profile": "https://Stackoverflow.com/users/27009",
"pm_score": 4,
"selected": false,
"text": "<p>I think you've taken \"tables are bad\" concept to the extreme. </p>\n\n<ul>\n<li>Tables used purely for layout (when other element would be more semantic) are bad.</li>\n<li>Tables for tabular data are good. They were intended for that purpose!</li>\n</ul>\n\n<p>What you've got fits very nicely into concept of rows and columns, with headers (<code><th></code>) and data (<code><td></code>) – based on semantics, not only layout.</p>\n\n<p>If you want to make it more explicit that it's an address, then use <a href=\"http://microformats.org/wiki/adr\" rel=\"noreferrer\">adr Microformat</a> or add a <code><caption></code>.</p>\n\n<p>Wrong approaches:</p>\n\n<ul>\n<li><code><dl></code>: \"1010\" is not a definition of \"Zip Code\". The other way round it makes a bit more sense, but the relationship is just as clear with <code><th></code> → <code><td></code>, it doesn't rely on CSS, and will look perfect regearless of user's font size.<br>\nIf you use <code><th></code> will be perfectly rendered <em>even in lynx</em>! Address in <code><dl></code> without CSS trick will look weird.</li>\n<li>HTML's <code><address></code> element may not be appropriate for this, because it is intended <em>only</em> for page author's/maintainer's contact information. It also allows inline content only, so you would lose structure of the address.</li>\n</ul>\n"
},
{
"answer_id": 196030,
"author": "Eevee",
"author_id": 17875,
"author_profile": "https://Stackoverflow.com/users/17875",
"pm_score": 4,
"selected": true,
"text": "<p>I find that definition lists make much more sense than tables here. Float the <code>dt</code> to the left with a specific width and have it clear on the left. If either the label or the data are going to wrap, you'll have to do some post-element-float-clearing trickery to make this work, but it doesn't sound like you'll need that. (I think it's worth it, anyway; plus, do it once and you'll never have to do it again.)</p>\n\n<p>You can even use <code>:after</code> to add the colons automatically, if you don't mind brushing off IE6.</p>\n"
},
{
"answer_id": 196067,
"author": "Herb Caudill",
"author_id": 239663,
"author_profile": "https://Stackoverflow.com/users/239663",
"pm_score": -1,
"selected": false,
"text": "<p>No need for tables (not that tables would be really inappropriate in this setting). I do this kind of thing all the time. </p>\n\n<pre><code><div class=DetailsRow>\n <div class=DetailsLabel>Street</div>\n <div class=DetailsContent>123 Main Street</div>\n</div>\n<div class=DetailsRow>\n <div class=DetailsLabel>City</div>\n <div class=DetailsContent>Vienna</div>\n</div>\n ...etc\n</code></pre>\n\n<p>and</p>\n\n<pre><code>div.DetailsRow\n{\nclear:both;\n}\n\ndiv.DetailsLabel\n{\nfloat:left;\nwidth:100px;\ncolor:gray;\n}\n\ndiv.DetailsContent\n{\nfloat:left;\nwidth:400px;\n}\n</code></pre>\n"
},
{
"answer_id": 196133,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 2,
"selected": false,
"text": "<p>Don't listen to the people saying that this is tabular data. Just because something has been presented in rows, it doesn't make it a table!</p>\n\n<p>This is a great situation to use the <code>dl</code>, <code>dt</code> and <code>dd</code> tags. It's a <em>bit</em> of a stretch from what they're originally intended for, but it's still much more meaningful than a table, spans or divs.</p>\n\n<pre><code><dl>\n <dt>Street</dt>\n <dd>Example Street 1</dd>\n <dt>City</dt>\n <dd>Vienna</dd>\n <dt>Zip Code</dt>\n <dd>1010</dd>\n <dt>Country</dt>\n <dd>Austria</dd>\n</dl>\n</code></pre>\n\n<p>And the CSS:</p>\n\n<pre><code>dt {\n width: 150px;\n float: left;\n clear: left\n}\ndd {\n float: left;\n}\n</code></pre>\n\n<p>That's fairly basic CSS - it probably won't hold up to a lot of situations (eg: two <code>dd</code>'s in a row, a really long <code>dt</code>), but it's a start. Look at the <code>inline-block</code> property for the <code>dt</code>, and perhaps instead of using <code>float</code>ing, you could set a <code>left-margin</code> of <code>150px</code> on the <code>dd</code>.</p>\n"
},
{
"answer_id": 198704,
"author": "SpoonMeiser",
"author_id": 1577190,
"author_profile": "https://Stackoverflow.com/users/1577190",
"pm_score": 0,
"selected": false,
"text": "<p>As others have mentioned, floated elements are the way to go here.</p>\n\n<p>This would be my solution:</p>\n\n<pre><code><p class=\"details\">\n <span class=\"label\">Street:</span>\n Some Street or other.\n <br />\n\n <span class=\"label\">City:</span>\n A City.\n <br />\n</p>\n</code></pre>\n\n<p>With CSS that looks like this:</p>\n\n<pre><code>p.details {\n padding-left: 200px;\n}\n\np.details span.label {\n float: left;\n clear: left;\n width: 200px;\n margin-left: -200px;\n}\n</code></pre>\n\n<p>Because the main text isn't floating, this avoid any issues where that text is long and needs to wrap; it stops the floating element becoming to wide and then floating below the label. This means that no special cases are needed for when this text is multi-line either, say, if you wanted to have a multi-line address.</p>\n\n<p>Similarly, this method also works if the label data needs to wrap over multiple lines, since the next label clears the previous float.</p>\n\n<p>Having the line breaks in there means it also degrades nicely and looks like you would expect when not using CSS.</p>\n\n<p>This method works very well for laying out forms, where <code><label></code> elements are used instead of the spans, and the paragraphs can be selected in the CSS as any paragraph that is the child of a <code><form></code>.</p>\n"
},
{
"answer_id": 3335348,
"author": "panzi",
"author_id": 277767,
"author_profile": "https://Stackoverflow.com/users/277767",
"pm_score": -1,
"selected": false,
"text": "<p>Or you can throw away all sanity (and semantics) and recreate tables using CSS (tested in Firefox and Chrome):</p>\n\n<pre><code><html>\n<head>\n<title>abusing divs</title>\n<style type=\"text/css\">\ndiv.details {\n display: table;\n}\ndiv.details > div {\n display: table-row;\n}\ndiv.details > div > div {\n display: table-cell;\n padding-left: 0.25em;\n padding-right: 0.25em;\n}\n</style>\n</head>\n<body>\n<div class=\"details\">\n <div>\n <div>Street</div>\n <div>123 Main Street</div>\n </div>\n <div>\n <div>City</div>\n <div>Vienna</div>\n </div>\n <div>\n <div>This is a very very loooong label</div>\n <div>...</div>\n </div>\n</div>\n</body>\n</html>\n</code></pre>\n\n<p>Just kidding.</p>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195991",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20467/"
] |
For explanation imagine a simple address. Written in a HTML paragraph with line breaks it would like this:
```
Street: Example Street 1
City: Vienna
Zip Code: 1010
Country: Austria
```
Most of the time that's completely okay, but sometimes I have to achieve the following output:
```
Street: Example Street 1
City: Vienna
Zip Code: 1010
Country: Austria
```
My thoughts so far:
1. Should be valid XHTML and work or degrade gracefully in all major browsers
2. Using tags in a semantically correct way is strongly preferred
3. Because of point two: I hope there's a better solution than tables
4. The problem is not limited to addresses - would be useful in other situation too
How do you achieve this output (using HTML and/or CSS)?
|
I find that definition lists make much more sense than tables here. Float the `dt` to the left with a specific width and have it clear on the left. If either the label or the data are going to wrap, you'll have to do some post-element-float-clearing trickery to make this work, but it doesn't sound like you'll need that. (I think it's worth it, anyway; plus, do it once and you'll never have to do it again.)
You can even use `:after` to add the colons automatically, if you don't mind brushing off IE6.
|
196,017 |
<p>I'd like to generate unique random numbers between 0 and 1000 that never repeat (i.e. 6 doesn't show up twice), but that doesn't resort to something like an O(N) search of previous values to do it. Is this possible?</p>
|
[
{
"answer_id": 196022,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 6,
"selected": false,
"text": "<p>You can do this:</p>\n\n<ol>\n<li>Create a list, 0..1000.</li>\n<li>Shuffle the list. (See <a href=\"http://en.wikipedia.org/wiki/Fisher-Yates_shuffle\" rel=\"noreferrer\">Fisher-Yates shuffle</a> for a good way to do this.)</li>\n<li>Return numbers in order from the shuffled list.</li>\n</ol>\n\n<p>So this doesn't require a search of old values each time, but it still requires O(N) for the initial shuffle. But as Nils pointed out in comments, this is amortised O(1).</p>\n"
},
{
"answer_id": 196024,
"author": "Toon Krijthe",
"author_id": 18061,
"author_profile": "https://Stackoverflow.com/users/18061",
"pm_score": 1,
"selected": false,
"text": "<p>Another posibility:</p>\n\n<p>You can use an array of flags. And take the next one when it;s already chosen.</p>\n\n<p>But, beware after 1000 calls, the function will never end so you must make a safeguard.</p>\n"
},
{
"answer_id": 196065,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 9,
"selected": true,
"text": "<p>Initialize an array of 1001 integers with the values 0-1000 and set a variable, max, to the current max index of the array (starting with 1000). Pick a random number, r, between 0 and max, swap the number at the position r with the number at position max and return the number now at position max. Decrement max by 1 and continue. When max is 0, set max back to the size of the array - 1 and start again without the need to reinitialize the array.</p>\n\n<p><strong>Update:</strong>\nAlthough I came up with this method on my own when I answered the question, after some research I realize this is a modified version of <a href=\"http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle\" rel=\"noreferrer\">Fisher-Yates</a> known as Durstenfeld-Fisher-Yates or Knuth-Fisher-Yates. Since the description may be a little difficult to follow, I have provided an example below (using 11 elements instead of 1001):</p>\n\n<p>Array starts off with 11 elements initialized to array[n] = n, max starts off at 10:</p>\n\n<pre><code>+--+--+--+--+--+--+--+--+--+--+--+\n| 0| 1| 2| 3| 4| 5| 6| 7| 8| 9|10|\n+--+--+--+--+--+--+--+--+--+--+--+\n ^\n max \n</code></pre>\n\n<p>At each iteration, a random number r is selected between 0 and max, array[r] and array[max] are swapped, the new array[max] is returned, and max is decremented:</p>\n\n<pre><code>max = 10, r = 3\n +--------------------+\n v v\n+--+--+--+--+--+--+--+--+--+--+--+\n| 0| 1| 2|10| 4| 5| 6| 7| 8| 9| 3|\n+--+--+--+--+--+--+--+--+--+--+--+\n\nmax = 9, r = 7\n +-----+\n v v\n+--+--+--+--+--+--+--+--+--+--+--+\n| 0| 1| 2|10| 4| 5| 6| 9| 8| 7: 3|\n+--+--+--+--+--+--+--+--+--+--+--+\n\nmax = 8, r = 1\n +--------------------+\n v v\n+--+--+--+--+--+--+--+--+--+--+--+\n| 0| 8| 2|10| 4| 5| 6| 9| 1: 7| 3|\n+--+--+--+--+--+--+--+--+--+--+--+\n\nmax = 7, r = 5\n +-----+\n v v\n+--+--+--+--+--+--+--+--+--+--+--+\n| 0| 8| 2|10| 4| 9| 6| 5: 1| 7| 3|\n+--+--+--+--+--+--+--+--+--+--+--+\n\n...\n</code></pre>\n\n<p>After 11 iterations, all numbers in the array have been selected, max == 0, and the array elements are shuffled:</p>\n\n<pre><code>+--+--+--+--+--+--+--+--+--+--+--+\n| 4|10| 8| 6| 2| 0| 9| 5| 1| 7| 3|\n+--+--+--+--+--+--+--+--+--+--+--+\n</code></pre>\n\n<p>At this point, max can be reset to 10 and the process can continue.</p>\n"
},
{
"answer_id": 196164,
"author": "Paul de Vrieze",
"author_id": 4100,
"author_profile": "https://Stackoverflow.com/users/4100",
"pm_score": 5,
"selected": false,
"text": "<p>You could use A <a href=\"http://en.wikipedia.org/wiki/Linear_congruential_generator\" rel=\"noreferrer\">Linear Congruential Generator</a>. Where <code>m</code> (the modulus) would be the nearest prime bigger than 1000. When you get a number out of the range, just get the next one. The sequence will only repeat once all elements have occurred, and you don't have to use a table. Be aware of the disadvantages of this generator though (including lack of randomness).</p>\n"
},
{
"answer_id": 202225,
"author": "plinth",
"author_id": 20481,
"author_profile": "https://Stackoverflow.com/users/20481",
"pm_score": 6,
"selected": false,
"text": "<p>Use a <a href=\"http://en.wikipedia.org/wiki/Linear_feedback_shift_register\" rel=\"noreferrer\">Maximal Linear Feedback Shift Register</a>.</p>\n\n<p>It's implementable in a few lines of C and at runtime does little more than a couple test/branches, a little addition and bit shifting. It's not random, but it fools most people.</p>\n"
},
{
"answer_id": 408677,
"author": "Max",
"author_id": 50023,
"author_profile": "https://Stackoverflow.com/users/50023",
"pm_score": 3,
"selected": false,
"text": "<p>You don't even need an array to solve this one.</p>\n\n<p>You need a bitmask and a counter.</p>\n\n<p>Initialize the counter to zero and increment it on successive calls. XOR the counter with the bitmask (randomly selected at startup, or fixed) to generate a psuedorandom number. If you can't have numbers that exceed 1000, don't use a bitmask wider than 9 bits. (In other words, the bitmask is an integer not above 511.)</p>\n\n<p>Make sure that when the counter passes 1000, you reset it to zero. At this time you can select another random bitmask — if you like — to produce the same set of numbers in a different order.</p>\n"
},
{
"answer_id": 408858,
"author": "pro",
"author_id": 352728,
"author_profile": "https://Stackoverflow.com/users/352728",
"pm_score": 2,
"selected": false,
"text": "<p>You could use a good <a href=\"http://en.wikipedia.org/wiki/Pseudorandom_number_generator\" rel=\"nofollow noreferrer\">pseudo-random number generator</a> with 10 bits and throw away 1001 to 1023 leaving 0 to 1000.</p>\n\n<p>From <a href=\"http://en.wikipedia.org/wiki/Linear_feedback_shift_register\" rel=\"nofollow noreferrer\">here</a> we get the design for a 10 bit PRNG..</p>\n\n<ul>\n<li><p>10 bits, feedback polynomial x^10 + x^7 + 1 (period 1023)</p></li>\n<li><p>use a Galois LFSR to get fast code</p></li>\n</ul>\n"
},
{
"answer_id": 3094476,
"author": "sellibitze",
"author_id": 172531,
"author_profile": "https://Stackoverflow.com/users/172531",
"pm_score": 3,
"selected": false,
"text": "<p>For low numbers like 0...1000, creating a list that contains all the numbers and shuffling it is straight forward. But if the set of numbers to draw from is very large there's another elegant way: You can build a pseudorandom permutation using a key and a cryptographic hash function. See the following C++-ish example pseudo code:</p>\n\n<pre><code>unsigned randperm(string key, unsigned bits, unsigned index) {\n unsigned half1 = bits / 2;\n unsigned half2 = (bits+1) / 2;\n unsigned mask1 = (1 << half1) - 1;\n unsigned mask2 = (1 << half2) - 1;\n for (int round=0; round<5; ++round) {\n unsigned temp = (index >> half1);\n temp = (temp << 4) + round;\n index ^= hash( key + \"/\" + int2str(temp) ) & mask1;\n index = ((index & mask2) << half1) | ((index >> half2) & mask1);\n }\n return index;\n}\n</code></pre>\n\n<p>Here, <code>hash</code> is just some arbitrary pseudo random function that maps a character string to a possibly huge unsigned integer. The function <code>randperm</code> is a permutation of all numbers within 0...pow(2,bits)-1 assuming a fixed key. This follows from the construction because every step that changes the variable <code>index</code> is reversible. This is inspired by a <a href=\"http://en.wikipedia.org/wiki/Feistel_cipher\" rel=\"noreferrer\">Feistel cipher</a>.</p>\n"
},
{
"answer_id": 3568781,
"author": "firedrawndagger",
"author_id": 306528,
"author_profile": "https://Stackoverflow.com/users/306528",
"pm_score": 2,
"selected": false,
"text": "<p>Here's some code I typed up that uses the logic of the first solution. I know this is \"language agnostic\" but just wanted to present this as an example in C# in case anyone is looking for a quick practical solution.</p>\n\n<pre><code>// Initialize variables\nRandom RandomClass = new Random();\nint RandArrayNum;\nint MaxNumber = 10;\nint LastNumInArray;\nint PickedNumInArray;\nint[] OrderedArray = new int[MaxNumber]; // Ordered Array - set\nint[] ShuffledArray = new int[MaxNumber]; // Shuffled Array - not set\n\n// Populate the Ordered Array\nfor (int i = 0; i < MaxNumber; i++) \n{\n OrderedArray[i] = i;\n listBox1.Items.Add(OrderedArray[i]);\n}\n\n// Execute the Shuffle \nfor (int i = MaxNumber - 1; i > 0; i--)\n{\n RandArrayNum = RandomClass.Next(i + 1); // Save random #\n ShuffledArray[i] = OrderedArray[RandArrayNum]; // Populting the array in reverse\n LastNumInArray = OrderedArray[i]; // Save Last Number in Test array\n PickedNumInArray = OrderedArray[RandArrayNum]; // Save Picked Random #\n OrderedArray[i] = PickedNumInArray; // The number is now moved to the back end\n OrderedArray[RandArrayNum] = LastNumInArray; // The picked number is moved into position\n}\n\nfor (int i = 0; i < MaxNumber; i++) \n{\n listBox2.Items.Add(ShuffledArray[i]);\n}\n</code></pre>\n"
},
{
"answer_id": 8931218,
"author": "salva",
"author_id": 124951,
"author_profile": "https://Stackoverflow.com/users/124951",
"pm_score": 2,
"selected": false,
"text": "<p>This method results appropiate when the limit is <strong>high</strong> and you only want to generate a few random numbers.</p>\n\n<pre><code>#!/usr/bin/perl\n\n($top, $n) = @ARGV; # generate $n integer numbers in [0, $top)\n\n$last = -1;\nfor $i (0 .. $n-1) {\n $range = $top - $n + $i - $last;\n $r = 1 - rand(1.0)**(1 / ($n - $i));\n $last += int($r * $range + 1);\n print \"$last ($r)\\n\";\n}\n</code></pre>\n\n<p>Note that the numbers are generated in ascending order, but you can shuffle then afterwards.</p>\n"
},
{
"answer_id": 10726753,
"author": "Erez Robinson",
"author_id": 1413476,
"author_profile": "https://Stackoverflow.com/users/1413476",
"pm_score": 2,
"selected": false,
"text": "<pre><code>public static int[] randN(int n, int min, int max)\n{\n if (max <= min)\n throw new ArgumentException(\"Max need to be greater than Min\");\n if (max - min < n)\n throw new ArgumentException(\"Range needs to be longer than N\");\n\n var r = new Random();\n\n HashSet<int> set = new HashSet<int>();\n\n while (set.Count < n)\n {\n var i = r.Next(max - min) + min;\n if (!set.Contains(i))\n set.Add(i);\n }\n\n return set.ToArray();\n}\n</code></pre>\n\n<p>N Non Repeating random numbers will be of O(n) complexity, as required.<BR>\nNote: Random should be static with thread safety applied.</p>\n"
},
{
"answer_id": 16097246,
"author": "Craig McQueen",
"author_id": 60075,
"author_profile": "https://Stackoverflow.com/users/60075",
"pm_score": 5,
"selected": false,
"text": "<p>You could use <a href=\"http://en.wikipedia.org/wiki/Format-Preserving_Encryption\" rel=\"noreferrer\">Format-Preserving Encryption</a> to encrypt a counter. Your counter just goes from 0 upwards, and the encryption uses a key of your choice to turn it into a seemingly random value of whatever radix and width you want. E.g. for the example in this question: radix 10, width 3.</p>\n\n<p>Block ciphers normally have a fixed block size of e.g. 64 or 128 bits. But Format-Preserving Encryption allows you to take a standard cipher like AES and make a smaller-width cipher, of whatever radix and width you want, with an algorithm which is still cryptographically robust.</p>\n\n<p>It is guaranteed to never have collisions (because cryptographic algorithms create a 1:1 mapping). It is also reversible (a 2-way mapping), so you can take the resulting number and get back to the counter value you started with.</p>\n\n<p>This technique doesn't need memory to store a shuffled array etc, which can be an advantage on systems with limited memory.</p>\n\n<p><a href=\"http://csrc.nist.gov/groups/ST/toolkit/BCM/documents/proposedmodes/ffx/ffx-spec.pdf\" rel=\"noreferrer\">AES-FFX</a> is one proposed standard method to achieve this. I've experimented with some basic Python code which is based on the AES-FFX idea, although not fully conformant--<a href=\"https://github.com/cmcqueen/crypto/blob/master/formatpreservingencryption.py\" rel=\"noreferrer\">see Python code here</a>. It can e.g. encrypt a counter to a random-looking 7-digit decimal number, or a 16-bit number. Here is an example of radix 10, width 3 (to give a number between 0 and 999 inclusive) as the question stated:</p>\n\n<pre><code>000 733\n001 374\n002 882\n003 684\n004 593\n005 578\n006 233\n007 811\n008 072\n009 337\n010 119\n011 103\n012 797\n013 257\n014 932\n015 433\n... ...\n</code></pre>\n\n<p>To get different non-repeating pseudo-random sequences, change the encryption key. Each encryption key produces a different non-repeating pseudo-random sequence.</p>\n"
},
{
"answer_id": 20689250,
"author": "Tod Samay",
"author_id": 3116023,
"author_profile": "https://Stackoverflow.com/users/3116023",
"pm_score": 3,
"selected": false,
"text": "<p>You may use my Xincrol algorithm described here:</p>\n\n<p><a href=\"http://openpatent.blogspot.co.il/2013/04/xincrol-unique-and-random-number.html\" rel=\"noreferrer\">http://openpatent.blogspot.co.il/2013/04/xincrol-unique-and-random-number.html</a></p>\n\n<p>This is a pure algorithmic method of generating random but unique numbers without arrays, lists, permutations or heavy CPU load.</p>\n\n<p>Latest version allows also to set the range of numbers, For example, if I want unique random numbers in range of 0-1073741821.</p>\n\n<p>I've practically used it for </p>\n\n<ul>\n<li>MP3 player which plays every song randomly, but only once per album/directory</li>\n<li>Pixel wise video frames dissolving effect (fast and smooth)</li>\n<li>Creating a secret \"noise\" fog over image for signatures and markers (steganography)</li>\n<li>Data Object IDs for serialization of huge amount of Java objects via Databases</li>\n<li>Triple Majority memory bits protection</li>\n<li>Address+value encryption (every byte is not just only encrypted but also moved to a new encrypted location in buffer). This really made cryptanalysis fellows mad on me :-)</li>\n<li>Plain Text to Plain Like Crypt Text encryption for SMS, emails etc.</li>\n<li>My Texas Hold`em Poker Calculator (THC)</li>\n<li>Several of my games for simulations, \"shuffling\", ranking </li>\n<li>more</li>\n</ul>\n\n<p>It is open, free. Give it a try... </p>\n"
},
{
"answer_id": 28653834,
"author": "Myron Denson",
"author_id": 4589963,
"author_profile": "https://Stackoverflow.com/users/4589963",
"pm_score": 2,
"selected": false,
"text": "<p>Here is some sample COBOL code you can play around with.<br>\nI can send you RANDGEN.exe file so you can play with it to see if it does want you want.</p>\n\n<pre><code> IDENTIFICATION DIVISION.\n PROGRAM-ID. RANDGEN as \"ConsoleApplication2.RANDGEN\".\n AUTHOR. Myron D Denson.\n DATE-COMPILED.\n * ************************************************************** \n * SUBROUTINE TO GENERATE RANDOM NUMBERS THAT ARE GREATER THAN\n * ZERO AND LESS OR EQUAL TO THE RANDOM NUMBERS NEEDED WITH NO\n * DUPLICATIONS. (CALL \"RANDGEN\" USING RANDGEN-AREA.)\n * \n * CALLING PROGRAM MUST HAVE A COMPARABLE LINKAGE SECTION\n * AND SET 3 VARIABLES PRIOR TO THE FIRST CALL IN RANDGEN-AREA \n *\n * FORMULA CYCLES THROUGH EVERY NUMBER OF 2X2 ONLY ONCE. \n * RANDOM-NUMBERS FROM 1 TO RANDOM-NUMBERS-NEEDED ARE CREATED \n * AND PASSED BACK TO YOU.\n *\n * RULES TO USE RANDGEN:\n *\n * RANDOM-NUMBERS-NEEDED > ZERO \n * \n * COUNT-OF-ACCESSES MUST = ZERO FIRST TIME CALLED.\n * \n * RANDOM-NUMBER = ZERO, WILL BUILD A SEED FOR YOU\n * WHEN COUNT-OF-ACCESSES IS ALSO = 0 \n * \n * RANDOM-NUMBER NOT = ZERO, WILL BE NEXT SEED FOR RANDGEN\n * (RANDOM-NUMBER MUST BE <= RANDOM-NUMBERS-NEEDED) \n * \n * YOU CAN PASS RANDGEN YOUR OWN RANDOM-NUMBER SEED\n * THE FIRST TIME YOU USE RANDGEN.\n * \n * BY PLACING A NUMBER IN RANDOM-NUMBER FIELD\n * THAT FOLLOWES THESE SIMPLE RULES:\n * IF COUNT-OF-ACCESSES = ZERO AND \n * RANDOM-NUMBER > ZERO AND \n * RANDOM-NUMBER <= RANDOM-NUMBERS-NEEDED\n * \n * YOU CAN LET RANDGEN BUILD A SEED FOR YOU\n * \n * THAT FOLLOWES THESE SIMPLE RULES:\n * IF COUNT-OF-ACCESSES = ZERO AND \n * RANDOM-NUMBER = ZERO AND \n * RANDOM-NUMBER-NEEDED > ZERO \n * \n * TO INSURING A DIFFERENT PATTERN OF RANDOM NUMBERS\n * A LOW-RANGE AND HIGH-RANGE IS USED TO BUILD\n * RANDOM NUMBERS.\n * COMPUTE LOW-RANGE =\n * ((SECONDS * HOURS * MINUTES * MS) / 3). \n * A HIGH-RANGE = RANDOM-NUMBERS-NEEDED + LOW-RANGE\n * AFTER RANDOM-NUMBER-BUILT IS CREATED \n * AND IS BETWEEN LOW AND HIGH RANGE\n * RANDUM-NUMBER = RANDOM-NUMBER-BUILT - LOW-RANGE\n * \n * ************************************************************** \n ENVIRONMENT DIVISION.\n INPUT-OUTPUT SECTION.\n FILE-CONTROL.\n DATA DIVISION.\n FILE SECTION.\n WORKING-STORAGE SECTION.\n 01 WORK-AREA.\n 05 X2-POWER PIC 9 VALUE 2. \n 05 2X2 PIC 9(12) VALUE 2 COMP-3.\n 05 RANDOM-NUMBER-BUILT PIC 9(12) COMP.\n 05 FIRST-PART PIC 9(12) COMP.\n 05 WORKING-NUMBER PIC 9(12) COMP.\n 05 LOW-RANGE PIC 9(12) VALUE ZERO.\n 05 HIGH-RANGE PIC 9(12) VALUE ZERO.\n 05 YOU-PROVIDE-SEED PIC X VALUE SPACE.\n 05 RUN-AGAIN PIC X VALUE SPACE.\n 05 PAUSE-FOR-A-SECOND PIC X VALUE SPACE. \n 01 SEED-TIME.\n 05 HOURS PIC 99.\n 05 MINUTES PIC 99.\n 05 SECONDS PIC 99.\n 05 MS PIC 99. \n *\n * LINKAGE SECTION.\n * Not used during testing \n 01 RANDGEN-AREA.\n 05 COUNT-OF-ACCESSES PIC 9(12) VALUE ZERO.\n 05 RANDOM-NUMBERS-NEEDED PIC 9(12) VALUE ZERO.\n 05 RANDOM-NUMBER PIC 9(12) VALUE ZERO.\n 05 RANDOM-MSG PIC X(60) VALUE SPACE.\n * \n * PROCEDURE DIVISION USING RANDGEN-AREA.\n * Not used during testing \n * \n PROCEDURE DIVISION.\n 100-RANDGEN-EDIT-HOUSEKEEPING.\n MOVE SPACE TO RANDOM-MSG. \n IF RANDOM-NUMBERS-NEEDED = ZERO\n DISPLAY 'RANDOM-NUMBERS-NEEDED ' NO ADVANCING\n ACCEPT RANDOM-NUMBERS-NEEDED.\n IF RANDOM-NUMBERS-NEEDED NOT NUMERIC \n MOVE 'RANDOM-NUMBERS-NEEDED NOT NUMERIC' TO RANDOM-MSG\n GO TO 900-EXIT-RANDGEN.\n IF RANDOM-NUMBERS-NEEDED = ZERO\n MOVE 'RANDOM-NUMBERS-NEEDED = ZERO' TO RANDOM-MSG\n GO TO 900-EXIT-RANDGEN.\n IF COUNT-OF-ACCESSES NOT NUMERIC\n MOVE 'COUNT-OF-ACCESSES NOT NUMERIC' TO RANDOM-MSG\n GO TO 900-EXIT-RANDGEN.\n IF COUNT-OF-ACCESSES GREATER THAN RANDOM-NUMBERS-NEEDED\n MOVE 'COUNT-OF-ACCESSES > THAT RANDOM-NUMBERS-NEEDED'\n TO RANDOM-MSG\n GO TO 900-EXIT-RANDGEN.\n IF YOU-PROVIDE-SEED = SPACE AND RANDOM-NUMBER = ZERO\n DISPLAY 'DO YOU WANT TO PROVIDE SEED Y OR N: '\n NO ADVANCING\n ACCEPT YOU-PROVIDE-SEED. \n IF RANDOM-NUMBER = ZERO AND\n (YOU-PROVIDE-SEED = 'Y' OR 'y')\n DISPLAY 'ENTER SEED ' NO ADVANCING\n ACCEPT RANDOM-NUMBER. \n IF RANDOM-NUMBER NOT NUMERIC\n MOVE 'RANDOM-NUMBER NOT NUMERIC' TO RANDOM-MSG\n GO TO 900-EXIT-RANDGEN.\n 200-RANDGEN-DATA-HOUSEKEEPING. \n MOVE FUNCTION CURRENT-DATE (9:8) TO SEED-TIME.\n IF COUNT-OF-ACCESSES = ZERO\n COMPUTE LOW-RANGE =\n ((SECONDS * HOURS * MINUTES * MS) / 3).\n COMPUTE RANDOM-NUMBER-BUILT = RANDOM-NUMBER + LOW-RANGE. \n COMPUTE HIGH-RANGE = RANDOM-NUMBERS-NEEDED + LOW-RANGE.\n MOVE X2-POWER TO 2X2. \n 300-SET-2X2-DIVISOR.\n IF 2X2 < (HIGH-RANGE + 1) \n COMPUTE 2X2 = 2X2 * X2-POWER\n GO TO 300-SET-2X2-DIVISOR. \n * ********************************************************* \n * IF FIRST TIME THROUGH AND YOU WANT TO BUILD A SEED. *\n * ********************************************************* \n IF COUNT-OF-ACCESSES = ZERO AND RANDOM-NUMBER = ZERO\n COMPUTE RANDOM-NUMBER-BUILT =\n ((SECONDS * HOURS * MINUTES * MS) + HIGH-RANGE).\n IF COUNT-OF-ACCESSES = ZERO \n DISPLAY 'SEED TIME ' SEED-TIME \n ' RANDOM-NUMBER-BUILT ' RANDOM-NUMBER-BUILT \n ' LOW-RANGE ' LOW-RANGE. \n * ********************************************* \n * END OF BUILDING A SEED IF YOU WANTED TO * \n * ********************************************* \n * ***************************************************\n * THIS PROCESS IS WHERE THE RANDOM-NUMBER IS BUILT * \n * *************************************************** \n 400-RANDGEN-FORMULA.\n COMPUTE FIRST-PART = (5 * RANDOM-NUMBER-BUILT) + 7.\n DIVIDE FIRST-PART BY 2X2 GIVING WORKING-NUMBER \n REMAINDER RANDOM-NUMBER-BUILT. \n IF RANDOM-NUMBER-BUILT > LOW-RANGE AND\n RANDOM-NUMBER-BUILT < (HIGH-RANGE + 1)\n GO TO 600-RANDGEN-CLEANUP.\n GO TO 400-RANDGEN-FORMULA.\n * ********************************************* \n * GOOD RANDOM NUMBER HAS BEEN BUILT * \n * *********************************************\n 600-RANDGEN-CLEANUP.\n ADD 1 TO COUNT-OF-ACCESSES.\n COMPUTE RANDOM-NUMBER = \n RANDOM-NUMBER-BUILT - LOW-RANGE. \n * *******************************************************\n * THE NEXT 3 LINE OF CODE ARE FOR TESTING ON CONSOLE * \n * *******************************************************\n DISPLAY RANDOM-NUMBER.\n IF COUNT-OF-ACCESSES < RANDOM-NUMBERS-NEEDED\n GO TO 100-RANDGEN-EDIT-HOUSEKEEPING. \n 900-EXIT-RANDGEN.\n IF RANDOM-MSG NOT = SPACE\n DISPLAY 'RANDOM-MSG: ' RANDOM-MSG.\n MOVE ZERO TO COUNT-OF-ACCESSES RANDOM-NUMBERS-NEEDED RANDOM-NUMBER. \n MOVE SPACE TO YOU-PROVIDE-SEED RUN-AGAIN.\n DISPLAY 'RUN AGAIN Y OR N '\n NO ADVANCING.\n ACCEPT RUN-AGAIN.\n IF (RUN-AGAIN = 'Y' OR 'y')\n GO TO 100-RANDGEN-EDIT-HOUSEKEEPING.\n ACCEPT PAUSE-FOR-A-SECOND.\n GOBACK.\n</code></pre>\n"
},
{
"answer_id": 30587391,
"author": "sh1",
"author_id": 2417578,
"author_profile": "https://Stackoverflow.com/users/2417578",
"pm_score": 1,
"selected": false,
"text": "<p>Most of the answers here fail to guarantee that they won't return the same number twice. Here's a correct solution:</p>\n\n<pre><code>int nrrand(void) {\n static int s = 1;\n static int start = -1;\n do {\n s = (s * 1103515245 + 12345) & 1023;\n } while (s >= 1001);\n if (start < 0) start = s;\n else if (s == start) abort();\n\n return s;\n}\n</code></pre>\n\n<p>I'm not sure that the constraint is well specified. One assumes that after 1000 other outputs a value is allowed to repeat, but that naively allows 0 to follow immediately after 0 so long as they both appear at the end and start of sets of 1000. Conversely, while it's possible to keep a distance of 1000 other values between repetitions, doing so forces a situation where the sequence replays itself in exactly the same way every time because there's no other value that has occurred outside of that limit.</p>\n\n<p>Here's a method that always guarantees at least 500 other values before a value can be repeated:</p>\n\n<pre><code>int nrrand(void) {\n static int h[1001];\n static int n = -1;\n\n if (n < 0) {\n int s = 1;\n for (int i = 0; i < 1001; i++) {\n do {\n s = (s * 1103515245 + 12345) & 1023;\n } while (s >= 1001);\n /* If we used `i` rather than `s` then our early results would be poorly distributed. */\n h[i] = s;\n }\n n = 0;\n }\n\n int i = rand(500);\n if (i != 0) {\n i = (n + i) % 1001;\n int t = h[i];\n h[i] = h[n];\n h[n] = t;\n }\n i = h[n];\n n = (n + 1) % 1001;\n\n return i;\n}\n</code></pre>\n"
},
{
"answer_id": 36900316,
"author": "Khaled.K",
"author_id": 2128327,
"author_profile": "https://Stackoverflow.com/users/2128327",
"pm_score": 2,
"selected": false,
"text": "<p>Let's say you want to go over shuffled lists over and over, without having the <code>O(n)</code> delay each time you start over to shuffle it again, in that case we can do this:</p>\n\n<ol>\n<li><p>Create 2 lists A and B, with 0 to 1000, takes <code>2n</code> space.</p></li>\n<li><p>Shuffle list A using Fisher-Yates, takes <code>n</code> time.</p></li>\n<li><p>When drawing a number, do 1-step Fisher-Yates shuffle on the other list.</p></li>\n<li><p>When cursor is at list end, switch to the other list.</p></li>\n</ol>\n\n<p><strong>Preprocess</strong></p>\n\n<pre><code>cursor = 0\n\nselector = A\nother = B\n\nshuffle(A)\n</code></pre>\n\n<p><strong>Draw</strong></p>\n\n<pre><code>temp = selector[cursor]\n\nswap(other[cursor], other[random])\n\nif cursor == N\nthen swap(selector, other); cursor = 0\nelse cursor = cursor + 1\n\nreturn temp\n</code></pre>\n"
},
{
"answer_id": 40736962,
"author": "Emanuel Landeholm",
"author_id": 222015,
"author_profile": "https://Stackoverflow.com/users/222015",
"pm_score": 1,
"selected": false,
"text": "<p>When N is greater than 1000 and you need to draw K random samples you could use a set that contains the samples so far. For each draw you use <a href=\"https://en.wikipedia.org/wiki/Rejection_sampling\" rel=\"nofollow noreferrer\">rejection sampling</a>, which will be an \"almost\" O(1) operation, so the total running time is nearly O(K) with O(N) storage.</p>\n\n<p>This algorithm runs into collisions when K is \"near\" N. This means that running time will be a lot worse than O(K). A simple fix is to reverse the logic so that, for K > N/2, you keep a record of all the samples that have not been drawn yet. Each draw removes a sample from the rejection set.</p>\n\n<p>The other obvious problem with rejection sampling is that it is O(N) storage, which is bad news if N is in the billions or more. However, there is an algorithm that solves that problem. This algorithm is called Vitter's algorithm after it's inventor. The algorithm is described <a href=\"https://getkerf.wordpress.com/2016/03/30/the-best-algorithm-no-one-knows-about/\" rel=\"nofollow noreferrer\">here</a>. The gist of Vitter's algorithm is that after each draw, you compute a random skip using a certain distribution which guarantees uniform sampling.</p>\n"
},
{
"answer_id": 41195350,
"author": "Max Abramovich",
"author_id": 6855859,
"author_profile": "https://Stackoverflow.com/users/6855859",
"pm_score": 3,
"selected": false,
"text": "<p>I think that <a href=\"https://en.wikipedia.org/wiki/Linear_congruential_generator\" rel=\"noreferrer\">Linear congruential generator</a> would be the simplest solution.</p>\n\n<p><a href=\"https://i.stack.imgur.com/rFB37.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/rFB37.png\" alt=\"enter image description here\"></a></p>\n\n<p>and there are only 3 restrictions on the <strong><em>a</em></strong>, <strong><em>c</em></strong> and <strong><em>m</em></strong> values</p>\n\n<ol>\n<li><strong><em>m</em></strong> and <strong><em>c</em></strong> are relatively prime,</li>\n<li><strong><em>a-1</em></strong> is divisible by all prime factors of <strong><em>m</em></strong></li>\n<li><strong><em>a-1</em></strong> is divisible by <strong><em>4</em></strong> if <strong><em>m</em></strong> is divisible by <strong><em>4</em></strong></li>\n</ol>\n\n<p><strong>PS</strong> the method was mentioned already but the post has a wrong assumptions about the constant values. The constants below should work fine for your case </p>\n\n<p>In your case you may use <code>a = 1002</code>, <code>c = 757</code>, <code>m = 1001</code></p>\n\n<pre><code>X = (1002 * X + 757) mod 1001\n</code></pre>\n"
},
{
"answer_id": 42541661,
"author": "paparazzo",
"author_id": 607314,
"author_profile": "https://Stackoverflow.com/users/607314",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle\" rel=\"nofollow noreferrer\">Fisher Yates</a> </p>\n\n<pre><code>for i from n−1 downto 1 do\n j ← random integer such that 0 ≤ j ≤ i\n exchange a[j] and a[i]\n</code></pre>\n\n<p>It is actually O(n-1) as you only need one swap for the last two<br>\nThis is C#</p>\n\n<pre><code>public static List<int> FisherYates(int n)\n{\n List<int> list = new List<int>(Enumerable.Range(0, n));\n Random rand = new Random();\n int swap;\n int temp;\n for (int i = n - 1; i > 0; i--)\n {\n swap = rand.Next(i + 1); //.net rand is not inclusive\n if(swap != i) // it can stay in place - if you force a move it is not a uniform shuffle\n {\n temp = list[i];\n list[i] = list[swap];\n list[swap] = temp;\n }\n }\n return list;\n}\n</code></pre>\n"
},
{
"answer_id": 44884435,
"author": "Hans Olsson",
"author_id": 5603247,
"author_profile": "https://Stackoverflow.com/users/5603247",
"pm_score": 2,
"selected": false,
"text": "<p>The question <a href=\"https://stackoverflow.com/questions/158716/how-do-you-efficiently-generate-a-list-of-k-non-repeating-integers-between-0-and?noredirect=1&lq=1\">How do you efficiently generate a list of K non-repeating integers between 0 and an upper bound N</a> is linked as a duplicate - and if you want something that is O(1) per generated random number (with no O(n) startup cost)) there is a simple tweak of the accepted answer.</p>\n\n<p>Create an empty unordered map (an empty ordered map will take O(log k) per element) from integer to integer - instead of using an initialized array.\nSet max to 1000 if that is the maximum,</p>\n\n<ol>\n<li>Pick a random number, r, between 0 and max.</li>\n<li>Ensure that both map elements r and max exist in the unordered map. If they don't exist create them with a value equal to their index. </li>\n<li>Swap elements r and max </li>\n<li>Return element max and decrement max by 1 (if max goes negative\nyou are done). </li>\n<li>Back to step 1.</li>\n</ol>\n\n<p>The only difference compared with using an initialized array is that the initialization of elements is postponed/skipped - but it will generate the exact same numbers from the same PRNG.</p>\n"
},
{
"answer_id": 47008395,
"author": "Pavel Ruzankin",
"author_id": 8794687,
"author_profile": "https://Stackoverflow.com/users/8794687",
"pm_score": 0,
"selected": false,
"text": "<p>Please see my answer at <a href=\"https://stackoverflow.com/a/46807110/8794687\">https://stackoverflow.com/a/46807110/8794687</a></p>\n\n<p>It is one of the simplest algorithms that have average time complexity <em>O</em>(<em>s</em> log <em>s</em>), <em>s</em> denoting the sample size. There are also some links there to hash table algorithms who's complexity is claimed to be <em>O</em>(<em>s</em>).</p>\n"
},
{
"answer_id": 58666154,
"author": "Grog Klingon",
"author_id": 7821991,
"author_profile": "https://Stackoverflow.com/users/7821991",
"pm_score": -1,
"selected": false,
"text": "<p>Someone posted \"creating random numbers in excel\". I am using this ideal.\nCreate a structure with 2 parts, str.index and str.ran;\nFor 10 random numbers create an array of 10 structures.\nSet the str.index from 0 to 9 and str.ran to different random number.</p>\n\n<pre><code>for(i=0;i<10; ++i) {\n arr[i].index = i;\n arr[i].ran = rand();\n}\n</code></pre>\n\n<p>Sort the array on the values in arr[i].ran.\nThe str.index is now in a random order.\nBelow is c code:</p>\n\n<pre><code>#include <stdio.h>\n#include <stdlib.h>\n\nstruct RanStr { int index; int ran;};\nstruct RanStr arr[10];\n\nint sort_function(const void *a, const void *b);\n\nint main(int argc, char *argv[])\n{\n int cnt, i;\n\n //seed(125);\n\n for(i=0;i<10; ++i)\n {\n arr[i].ran = rand();\n arr[i].index = i;\n printf(\"arr[%d] Initial Order=%2d, random=%d\\n\", i, arr[i].index, arr[i].ran);\n }\n\n qsort( (void *)arr, 10, sizeof(arr[0]), sort_function);\n printf(\"\\n===================\\n\");\n for(i=0;i<10; ++i)\n {\n printf(\"arr[%d] Random Order=%2d, random=%d\\n\", i, arr[i].index, arr[i].ran);\n }\n\n return 0;\n}\n\nint sort_function(const void *a, const void *b)\n{\n struct RanStr *a1, *b1;\n\n a1=(struct RanStr *) a;\n b1=(struct RanStr *) b;\n\n return( a1->ran - b1->ran );\n}\n</code></pre>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/196017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3886/"
] |
I'd like to generate unique random numbers between 0 and 1000 that never repeat (i.e. 6 doesn't show up twice), but that doesn't resort to something like an O(N) search of previous values to do it. Is this possible?
|
Initialize an array of 1001 integers with the values 0-1000 and set a variable, max, to the current max index of the array (starting with 1000). Pick a random number, r, between 0 and max, swap the number at the position r with the number at position max and return the number now at position max. Decrement max by 1 and continue. When max is 0, set max back to the size of the array - 1 and start again without the need to reinitialize the array.
**Update:**
Although I came up with this method on my own when I answered the question, after some research I realize this is a modified version of [Fisher-Yates](http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle) known as Durstenfeld-Fisher-Yates or Knuth-Fisher-Yates. Since the description may be a little difficult to follow, I have provided an example below (using 11 elements instead of 1001):
Array starts off with 11 elements initialized to array[n] = n, max starts off at 10:
```
+--+--+--+--+--+--+--+--+--+--+--+
| 0| 1| 2| 3| 4| 5| 6| 7| 8| 9|10|
+--+--+--+--+--+--+--+--+--+--+--+
^
max
```
At each iteration, a random number r is selected between 0 and max, array[r] and array[max] are swapped, the new array[max] is returned, and max is decremented:
```
max = 10, r = 3
+--------------------+
v v
+--+--+--+--+--+--+--+--+--+--+--+
| 0| 1| 2|10| 4| 5| 6| 7| 8| 9| 3|
+--+--+--+--+--+--+--+--+--+--+--+
max = 9, r = 7
+-----+
v v
+--+--+--+--+--+--+--+--+--+--+--+
| 0| 1| 2|10| 4| 5| 6| 9| 8| 7: 3|
+--+--+--+--+--+--+--+--+--+--+--+
max = 8, r = 1
+--------------------+
v v
+--+--+--+--+--+--+--+--+--+--+--+
| 0| 8| 2|10| 4| 5| 6| 9| 1: 7| 3|
+--+--+--+--+--+--+--+--+--+--+--+
max = 7, r = 5
+-----+
v v
+--+--+--+--+--+--+--+--+--+--+--+
| 0| 8| 2|10| 4| 9| 6| 5: 1| 7| 3|
+--+--+--+--+--+--+--+--+--+--+--+
...
```
After 11 iterations, all numbers in the array have been selected, max == 0, and the array elements are shuffled:
```
+--+--+--+--+--+--+--+--+--+--+--+
| 4|10| 8| 6| 2| 0| 9| 5| 1| 7| 3|
+--+--+--+--+--+--+--+--+--+--+--+
```
At this point, max can be reset to 10 and the process can continue.
|
196,020 |
<p>I need to create a 'slider' for a client's site. The slider should allow people to select how many items they want of x item, and show what the price will be based on that. The weird(ish) part is that the ratio of the price increase will go down as the amount of items goes up:</p>
<ul>
<li>1 item: $100</li>
<li>2 items: +90 = $190</li>
<li>3 items: + 80 = $270</li>
<li>4 items: + 70 = $340</li>
<li>5 items: + 60 = $400</li>
<li>6 items: + 50 = $450</li>
<li>7 items: + 50 = $500</li>
</ul>
<p>And all increases from then on are +50. This probably seems like an overly simplistic question, but does anyone know how I could go about doing this? I have almost no experience with JavaScript :( </p>
|
[
{
"answer_id": 196034,
"author": "Dimitry",
"author_id": 27073,
"author_profile": "https://Stackoverflow.com/users/27073",
"pm_score": 3,
"selected": false,
"text": "<p>Check out Yahoo! UI. they have a slider widget: <a href=\"http://developer.yahoo.com/yui/slider/\" rel=\"noreferrer\">http://developer.yahoo.com/yui/slider/</a></p>\n\n<p>The following example should get you started: <a href=\"http://developer.yahoo.com/yui/examples/slider/slider-ticks.html\" rel=\"noreferrer\">http://developer.yahoo.com/yui/examples/slider/slider-ticks.html</a>.</p>\n\n<p>All JavaScript frameworks (<a href=\"http://docs.jquery.com/UI/Slider\" rel=\"noreferrer\">jQuery</a>, <a href=\"http://demos.mootools.net/Slider\" rel=\"noreferrer\">MooTools</a>) seem to offer a slider. The YUI will give you a lot of control and a loader so you don't have to host the script on your server. Beware that YUI does not make implementation as painless as with the two other i mentioned.</p>\n\n<p>Here is a MooTools example:</p>\n\n<pre><code>// First example of http://demos.mootools.net/Slider\n\n<div class=\"slider\" id=\"myslider\">\n <div class=\"knob\" style=\"position: relative;\"/>\n </div>\n</code></pre>\n\n<p>And the JavaScript:</p>\n\n<pre><code>var el = $('myslider'); // The slider graphic\nnew Slider(el, el.getElement('.knob'), {\n steps: 7, // There are 7 choices\n range: [1, 7], // Minimum value is 1, maximum is 7\n onChange: function(value){\n // Calculation of the value goes here\n }\n});\n</code></pre>\n"
},
{
"answer_id": 196040,
"author": "Henrik Paul",
"author_id": 2238,
"author_profile": "https://Stackoverflow.com/users/2238",
"pm_score": 0,
"selected": false,
"text": "<p>While there are presumably endless ways of getting a slider done with JS, I think the easiest way to calculate the prices are just hard-coding (or listing) them somewhere, and just <code>else-if</code>:ing through them.</p>\n\n<p>You <em>could</em> do an algorithm that counts <code>100-(i*10)</code> for the five first items, <code>50</code> for the rest, but that's probably harder to change in the future than the hard-listed way.</p>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/196020",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12765/"
] |
I need to create a 'slider' for a client's site. The slider should allow people to select how many items they want of x item, and show what the price will be based on that. The weird(ish) part is that the ratio of the price increase will go down as the amount of items goes up:
* 1 item: $100
* 2 items: +90 = $190
* 3 items: + 80 = $270
* 4 items: + 70 = $340
* 5 items: + 60 = $400
* 6 items: + 50 = $450
* 7 items: + 50 = $500
And all increases from then on are +50. This probably seems like an overly simplistic question, but does anyone know how I could go about doing this? I have almost no experience with JavaScript :(
|
Check out Yahoo! UI. they have a slider widget: <http://developer.yahoo.com/yui/slider/>
The following example should get you started: <http://developer.yahoo.com/yui/examples/slider/slider-ticks.html>.
All JavaScript frameworks ([jQuery](http://docs.jquery.com/UI/Slider), [MooTools](http://demos.mootools.net/Slider)) seem to offer a slider. The YUI will give you a lot of control and a loader so you don't have to host the script on your server. Beware that YUI does not make implementation as painless as with the two other i mentioned.
Here is a MooTools example:
```
// First example of http://demos.mootools.net/Slider
<div class="slider" id="myslider">
<div class="knob" style="position: relative;"/>
</div>
```
And the JavaScript:
```
var el = $('myslider'); // The slider graphic
new Slider(el, el.getElement('.knob'), {
steps: 7, // There are 7 choices
range: [1, 7], // Minimum value is 1, maximum is 7
onChange: function(value){
// Calculation of the value goes here
}
});
```
|
196,037 |
<p>How can I access a public static member of a Java class from ColdFusion?</p>
|
[
{
"answer_id": 196107,
"author": "Turnkey",
"author_id": 13144,
"author_profile": "https://Stackoverflow.com/users/13144",
"pm_score": 5,
"selected": true,
"text": "<p>You run the createObject but don't call the \"init\" before running the static method. For example:</p>\n\n<pre><code><cfset systemObject = createObject(\"java\", \"java.lang.System\") />\n<cfoutput>#systemObject.currentTimeMillis()#</cfoutput> \n</code></pre>\n\n<p>In this case \"currentTimeMillis()\" is a static method of the System class.</p>\n"
},
{
"answer_id": 436665,
"author": "Ryan Guill",
"author_id": 7186,
"author_profile": "https://Stackoverflow.com/users/7186",
"pm_score": 1,
"selected": false,
"text": "<p>I would also mention that the class has to be in CF's classpath.</p>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/196037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2484/"
] |
How can I access a public static member of a Java class from ColdFusion?
|
You run the createObject but don't call the "init" before running the static method. For example:
```
<cfset systemObject = createObject("java", "java.lang.System") />
<cfoutput>#systemObject.currentTimeMillis()#</cfoutput>
```
In this case "currentTimeMillis()" is a static method of the System class.
|
196,088 |
<p>Assume I have a function template like this:</p>
<pre><code>template<class T>
inline
void
doStuff(T* arr)
{
// stuff that needs to use sizeof(T)
}
</code></pre>
<p>Then in another <code>.h</code> filee I have a template class <code>Foo</code> that has:</p>
<pre><code>public: operator T*() const;
</code></pre>
<p>Now, I realize that those are different Ts. But If I have a variable <code>Foo<Bar> f</code> on the stack, the only way to coerce it to <em>any</em> kind of pointer would be to invoke <code>operator T*()</code>. Yet, if call <code>doStuff(f)</code>, GCC complains that <code>doStuff</code> can't take <code>Foo<Bar></code> instead of automatically using operator <code>T*()</code> to coerce to <code>Bar*</code> and then specializing the function template with <code>Bar</code> as <code>T</code>.</p>
<p>Is there anything I can do to make this work with two templates? Or does either the argument of the template function have to be a real pointer type or the template class with the coercion operator be passed to a non-template function?</p>
|
[
{
"answer_id": 196103,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": -1,
"selected": false,
"text": "<p>I'm not sure why the conversion doesn't work but you could use an overload to fix the problem</p>\n\n<pre><code>\ntemplate \ninline\nvoid \ndoStuff(T& arrRef)\n{\n doStuff(&arrRef);\n}\n</code></pre>\n"
},
{
"answer_id": 196122,
"author": "Paul de Vrieze",
"author_id": 4100,
"author_profile": "https://Stackoverflow.com/users/4100",
"pm_score": -1,
"selected": false,
"text": "<p>Well, T* is not a separate type from T in the sense you think it is. The pointer is a type qualifier. I'm not sure what the standard says about it, but I would say that as the variable is already of type T it does not try to convert again. If you want to do some custom stuff to get a pointer, overload the & operator.</p>\n"
},
{
"answer_id": 196151,
"author": "Leon Timmermans",
"author_id": 4727,
"author_profile": "https://Stackoverflow.com/users/4727",
"pm_score": 3,
"selected": true,
"text": "<p>GCC is correct. In template arguments only exact matches are considered, type conversions are not. This is because otherwise an infinite (or at least exponential) amount of conversions could have to be considered.</p>\n\n<p>If Foo<T> is the only other template that you're going to run in to, the best solution would be to add:</p>\n\n<pre><code>template<typename T> inline void doStuff(const Foo<T>& arr) {\n doStuff(static_cast<T*>(arr));\n}\n</code></pre>\n\n<p>If you are having this issue with a lot of templates, this one should fix it:</p>\n\n<pre><code>#include <boost/type_traits/is_convertible.hpp>\n#include <boost/utility/enable_if.hpp>\ntemplate<template <typename> class T, typename U> inline typename boost::enable_if<typename boost::is_convertible<T<U>, U*>::type>::type doStuff(const T<U>& arr) {\n doStuff(static_cast<U*>(arr));\n}\n</code></pre>\n\n<p>It's a bit verbose though ;-)</p>\n"
},
{
"answer_id": 196153,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>This might be worth a try:</p>\n\n<pre><code>doStuff<Bar>(f);\n</code></pre>\n\n<p>I think this will cause the compiler to expect T* to be Bar* and then use Foo's operator T*() to perform the cast, but I can't say I've tried it.</p>\n"
},
{
"answer_id": 196440,
"author": "Eclipse",
"author_id": 8701,
"author_profile": "https://Stackoverflow.com/users/8701",
"pm_score": 0,
"selected": false,
"text": "<p>Leon's idea is probably best. But in a pinch, you could also call the cast operator explicitly:</p>\n\n<pre><code>doStuff(static_cast<Bar*>(f));\n</code></pre>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/196088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18721/"
] |
Assume I have a function template like this:
```
template<class T>
inline
void
doStuff(T* arr)
{
// stuff that needs to use sizeof(T)
}
```
Then in another `.h` filee I have a template class `Foo` that has:
```
public: operator T*() const;
```
Now, I realize that those are different Ts. But If I have a variable `Foo<Bar> f` on the stack, the only way to coerce it to *any* kind of pointer would be to invoke `operator T*()`. Yet, if call `doStuff(f)`, GCC complains that `doStuff` can't take `Foo<Bar>` instead of automatically using operator `T*()` to coerce to `Bar*` and then specializing the function template with `Bar` as `T`.
Is there anything I can do to make this work with two templates? Or does either the argument of the template function have to be a real pointer type or the template class with the coercion operator be passed to a non-template function?
|
GCC is correct. In template arguments only exact matches are considered, type conversions are not. This is because otherwise an infinite (or at least exponential) amount of conversions could have to be considered.
If Foo<T> is the only other template that you're going to run in to, the best solution would be to add:
```
template<typename T> inline void doStuff(const Foo<T>& arr) {
doStuff(static_cast<T*>(arr));
}
```
If you are having this issue with a lot of templates, this one should fix it:
```
#include <boost/type_traits/is_convertible.hpp>
#include <boost/utility/enable_if.hpp>
template<template <typename> class T, typename U> inline typename boost::enable_if<typename boost::is_convertible<T<U>, U*>::type>::type doStuff(const T<U>& arr) {
doStuff(static_cast<U*>(arr));
}
```
It's a bit verbose though ;-)
|
196,097 |
<p>On a site of mine in which a textarea is used for submission, I have code that can appear something along the lines of the following:</p>
<pre><code><textarea><p>text</p></textarea>
</code></pre>
<p>When validating (XHTML 1.0 Transitional), this error arises,</p>
<pre><code>line 88 column 50 - Error: document type does not allow element "p" here
</code></pre>
<p>If this is not a valid method, then what is expected? I could do a workaround with an onload JavaScript event, but that seems needless. Regardless this doesn't affect the output, but I'd rather my site validate.</p>
|
[
{
"answer_id": 196105,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 4,
"selected": true,
"text": "<p>is there a reason you're trying to put a <code><p></code> within <code><textarea></code>? as you found out it's not valid. if it's for display purposes (ie, showing code) it should be translated:</p>\n\n<pre><code><textarea>&lt;p&gt;text&lt;/p&gt;</textarea>\n</code></pre>\n\n<p>beyond validation issues, allowing arbitrary tags (which are not properly encoded as above) to display can be a huge security issue. it's paramount to make sure any user supplied input has been properly sanitized before it is displayed.</p>\n"
},
{
"answer_id": 196108,
"author": "acrosman",
"author_id": 24215,
"author_profile": "https://Stackoverflow.com/users/24215",
"pm_score": 0,
"selected": false,
"text": "<p>You can leave out the tags in the text area, and when you need new lines use \\n Otherwise use <code>&lt;p&gt;</code> and <code>&lt;/p&gt;</code> in the place of your tags.</p>\n"
},
{
"answer_id": 196134,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>You could use an onload function to replace starts and ends tags of the textarea content.</p>\n\n<pre><code>eg: replace < > with &lt; &gt;\n\n<textarea cols=\"\" rows=\"\">&lt;p&gt;text&lt;/p&gt;</textarea>\n</code></pre>\n\n<p><p>text</p></p>\n"
},
{
"answer_id": 196141,
"author": "Ross",
"author_id": 2025,
"author_profile": "https://Stackoverflow.com/users/2025",
"pm_score": 1,
"selected": false,
"text": "<p>Am I right in thinking your trying to make a WYSIWYG editor, such as TinyMCE? What most seem to do is use HTML entities in the <code>textarea</code> and convert it to HTML via JavaScript.</p>\n"
},
{
"answer_id": 196193,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 2,
"selected": false,
"text": "<p>Would a CDATA section be an option for you?</p>\n\n<pre><code><textarea><![CDATA[\n <p>Blah</p>\n]]></textarea>\n</code></pre>\n"
},
{
"answer_id": 367941,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>you could use this function on the posted data</p>\n\n<pre><code>function clean_data($value) {\n if (get_magic_quotes_gpc()) { $value = stripslashes($value); }\n $value = addslashes(htmlentities(trim($value)));\n $value = str_replace(\"\\'\", \"&#39;\", $value);\n $value = str_replace(\"'\", \"&#39;\", $value);\n $value = str_replace(\":\", \"&#58;\", $value);\n return $value;\n}\n</code></pre>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/196097",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23666/"
] |
On a site of mine in which a textarea is used for submission, I have code that can appear something along the lines of the following:
```
<textarea><p>text</p></textarea>
```
When validating (XHTML 1.0 Transitional), this error arises,
```
line 88 column 50 - Error: document type does not allow element "p" here
```
If this is not a valid method, then what is expected? I could do a workaround with an onload JavaScript event, but that seems needless. Regardless this doesn't affect the output, but I'd rather my site validate.
|
is there a reason you're trying to put a `<p>` within `<textarea>`? as you found out it's not valid. if it's for display purposes (ie, showing code) it should be translated:
```
<textarea><p>text</p></textarea>
```
beyond validation issues, allowing arbitrary tags (which are not properly encoded as above) to display can be a huge security issue. it's paramount to make sure any user supplied input has been properly sanitized before it is displayed.
|
196,109 |
<p>Does anybody know of a good media framework for Flex?<br/>
I'd like to be able to create apps that can play not only those formats that the Flex framework provides support for, but other formats as well (like wav, wma, ogg and other...).</p>
<p><strong>EDIT 13.10.2008.:</strong> It was recently pointed out to me in the answers section that I should perhaps rephrase the question, so here goes: What I'm really looking for is a way to play various media formats in a Flex/Air app. Onekidney posted a nice answer about Ogg/Vorbis. Does anybody know of a way to play other media formats? Never mind about the portability to different platforms now. Portability would be nice, but if I can't get it, I can live without it :-).<br/>
Thanks for the answers!</p>
|
[
{
"answer_id": 196105,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 4,
"selected": true,
"text": "<p>is there a reason you're trying to put a <code><p></code> within <code><textarea></code>? as you found out it's not valid. if it's for display purposes (ie, showing code) it should be translated:</p>\n\n<pre><code><textarea>&lt;p&gt;text&lt;/p&gt;</textarea>\n</code></pre>\n\n<p>beyond validation issues, allowing arbitrary tags (which are not properly encoded as above) to display can be a huge security issue. it's paramount to make sure any user supplied input has been properly sanitized before it is displayed.</p>\n"
},
{
"answer_id": 196108,
"author": "acrosman",
"author_id": 24215,
"author_profile": "https://Stackoverflow.com/users/24215",
"pm_score": 0,
"selected": false,
"text": "<p>You can leave out the tags in the text area, and when you need new lines use \\n Otherwise use <code>&lt;p&gt;</code> and <code>&lt;/p&gt;</code> in the place of your tags.</p>\n"
},
{
"answer_id": 196134,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>You could use an onload function to replace starts and ends tags of the textarea content.</p>\n\n<pre><code>eg: replace < > with &lt; &gt;\n\n<textarea cols=\"\" rows=\"\">&lt;p&gt;text&lt;/p&gt;</textarea>\n</code></pre>\n\n<p><p>text</p></p>\n"
},
{
"answer_id": 196141,
"author": "Ross",
"author_id": 2025,
"author_profile": "https://Stackoverflow.com/users/2025",
"pm_score": 1,
"selected": false,
"text": "<p>Am I right in thinking your trying to make a WYSIWYG editor, such as TinyMCE? What most seem to do is use HTML entities in the <code>textarea</code> and convert it to HTML via JavaScript.</p>\n"
},
{
"answer_id": 196193,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 2,
"selected": false,
"text": "<p>Would a CDATA section be an option for you?</p>\n\n<pre><code><textarea><![CDATA[\n <p>Blah</p>\n]]></textarea>\n</code></pre>\n"
},
{
"answer_id": 367941,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>you could use this function on the posted data</p>\n\n<pre><code>function clean_data($value) {\n if (get_magic_quotes_gpc()) { $value = stripslashes($value); }\n $value = addslashes(htmlentities(trim($value)));\n $value = str_replace(\"\\'\", \"&#39;\", $value);\n $value = str_replace(\"'\", \"&#39;\", $value);\n $value = str_replace(\":\", \"&#58;\", $value);\n return $value;\n}\n</code></pre>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/196109",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19911/"
] |
Does anybody know of a good media framework for Flex?
I'd like to be able to create apps that can play not only those formats that the Flex framework provides support for, but other formats as well (like wav, wma, ogg and other...).
**EDIT 13.10.2008.:** It was recently pointed out to me in the answers section that I should perhaps rephrase the question, so here goes: What I'm really looking for is a way to play various media formats in a Flex/Air app. Onekidney posted a nice answer about Ogg/Vorbis. Does anybody know of a way to play other media formats? Never mind about the portability to different platforms now. Portability would be nice, but if I can't get it, I can live without it :-).
Thanks for the answers!
|
is there a reason you're trying to put a `<p>` within `<textarea>`? as you found out it's not valid. if it's for display purposes (ie, showing code) it should be translated:
```
<textarea><p>text</p></textarea>
```
beyond validation issues, allowing arbitrary tags (which are not properly encoded as above) to display can be a huge security issue. it's paramount to make sure any user supplied input has been properly sanitized before it is displayed.
|
196,114 |
<p>I chmod'ed the directory to 777, same with the directory contents. Still, I get a "permission denied" error. Does PHP throw this error if apache is not the group/owner, regardless of the file permissions? Here's the call that's failing:</p>
<pre><code>rename('/correct/path/to/dir/1', '/correct/path/to/dir/2');
</code></pre>
|
[
{
"answer_id": 196118,
"author": "Ross",
"author_id": 2025,
"author_profile": "https://Stackoverflow.com/users/2025",
"pm_score": 0,
"selected": false,
"text": "<p>Try running the following script:</p>\n\n<pre><code>print_r(posix_getpwuid(getmyuid()));\nprint_r(pathinfo($YOUR_PATH));\n</code></pre>\n\n<p>And see what that returns.</p>\n"
},
{
"answer_id": 196119,
"author": "acrosman",
"author_id": 24215,
"author_profile": "https://Stackoverflow.com/users/24215",
"pm_score": 5,
"selected": true,
"text": "<p>You're editing the higher level directory, so the PHP user needs to have write access to that directory.</p>\n"
},
{
"answer_id": 196123,
"author": "kjensen",
"author_id": 22177,
"author_profile": "https://Stackoverflow.com/users/22177",
"pm_score": 2,
"selected": false,
"text": "<p>Thats probably because apache is not the owner of the parent directory. Renaming (or moving) a file is basically the same thing as creating a new file.</p>\n"
},
{
"answer_id": 196167,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 2,
"selected": false,
"text": "<p>to clarify, php can only rename directories it has actual ownership over:</p>\n\n<pre><code>-rwxrwxrwx user user temp/\n-rwxr-xr-x apache apache temp2/\n-rw-r--r-- user user script.php\n</code></pre>\n\n<p>assume script.php is trying to rename these two directories:</p>\n\n<pre><code>// this operation fails as PHP (running as apache) does not own \"temp\",\n// despite having write permissions \nrename('temp', 'temp.bak');\n\n// this operation is successful as PHP owns \"temp2\"\nrename('temp2, 'temp.bak'); \n</code></pre>\n"
},
{
"answer_id": 196194,
"author": "Jason Baker",
"author_id": 2147,
"author_profile": "https://Stackoverflow.com/users/2147",
"pm_score": 1,
"selected": false,
"text": "<p>Another thing that might help these kinds of situations is to try actually lowering permissions. I've seen occasions where apache denies an application permission to do something because its permissions are set too <em>high</em>. My guess is that this is to encourage good security practice.</p>\n"
},
{
"answer_id": 60288441,
"author": "Alfredo Morales",
"author_id": 12893415,
"author_profile": "https://Stackoverflow.com/users/12893415",
"pm_score": 0,
"selected": false,
"text": "<p>You must change the permissions of the folder and the files contained in it recursively. \nYou need to do this from ssh as root user and then run the following command: </p>\n\n<pre><code>chown -R www-data:www-data /directory/path/to/apply/chown\n</code></pre>\n\n<p>then you can execute the chown statement without any problems.</p>\n\n<p>I found this way after researching, testing for several hours.</p>\n\n<p>Remember that a folder or root owner file cannot be manipulated by another user (delete, rename, move, change properties), while root can do so above any user.</p>\n\n<p>Best regards</p>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/196114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11577/"
] |
I chmod'ed the directory to 777, same with the directory contents. Still, I get a "permission denied" error. Does PHP throw this error if apache is not the group/owner, regardless of the file permissions? Here's the call that's failing:
```
rename('/correct/path/to/dir/1', '/correct/path/to/dir/2');
```
|
You're editing the higher level directory, so the PHP user needs to have write access to that directory.
|
196,171 |
<p>Is it possible to use a CHECK constraint to prevent any date that falls on a Sunday? I don't want to use a trigger.</p>
|
[
{
"answer_id": 196190,
"author": "Mark",
"author_id": 26310,
"author_profile": "https://Stackoverflow.com/users/26310",
"pm_score": 1,
"selected": false,
"text": "<p>Not sure about the actual constraint, but you can use the function:</p>\n\n<pre><code>TO_CHAR(sysdate, 'D'); \n</code></pre>\n\n<p>to get the day of the week as an integer, then do a small check on it </p>\n"
},
{
"answer_id": 196196,
"author": "Plasmer",
"author_id": 397314,
"author_profile": "https://Stackoverflow.com/users/397314",
"pm_score": 4,
"selected": true,
"text": "<p>Yes, a check constraint can check that the day of the week is not Sunday. Here's an example:</p>\n\n<pre><code>create table date_test (entry_date date);\n\nalter table date_test add constraint day_is_not_sunday\n check ( to_char(entry_date,'DAY','NLS_DATE_LANGUAGE = ENGLISH') not like 'SUNDAY%'); \n</code></pre>\n\n<p>--There are blank spaces to the right of SUNDAY so like or rtrim is needed to match the string.</p>\n\n<pre><code>insert into date_test values(to_date('2008-10-12','YYYY-MM-DD')); --Sunday\ninsert into date_test values(to_date('2008-10-11','YYYY-MM-DD'));\ninsert into date_test values(to_date('2008-10-10','YYYY-MM-DD'));\ninsert into date_test values(to_date('2008-10-09','YYYY-MM-DD'));\ninsert into date_test values(to_date('2008-10-08','YYYY-MM-DD'));\ninsert into date_test values(to_date('2008-10-07','YYYY-MM-DD'));\ninsert into date_test values(to_date('2008-10-06','YYYY-MM-DD'));\n</code></pre>\n\n<p>When you try to insert a date that is on a Sunday, it will say:<br>\n<code>ORA-02290: check constraint (SYS.DAY_IS_NOT_SUNDAY) violated</code></p>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/196171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3401/"
] |
Is it possible to use a CHECK constraint to prevent any date that falls on a Sunday? I don't want to use a trigger.
|
Yes, a check constraint can check that the day of the week is not Sunday. Here's an example:
```
create table date_test (entry_date date);
alter table date_test add constraint day_is_not_sunday
check ( to_char(entry_date,'DAY','NLS_DATE_LANGUAGE = ENGLISH') not like 'SUNDAY%');
```
--There are blank spaces to the right of SUNDAY so like or rtrim is needed to match the string.
```
insert into date_test values(to_date('2008-10-12','YYYY-MM-DD')); --Sunday
insert into date_test values(to_date('2008-10-11','YYYY-MM-DD'));
insert into date_test values(to_date('2008-10-10','YYYY-MM-DD'));
insert into date_test values(to_date('2008-10-09','YYYY-MM-DD'));
insert into date_test values(to_date('2008-10-08','YYYY-MM-DD'));
insert into date_test values(to_date('2008-10-07','YYYY-MM-DD'));
insert into date_test values(to_date('2008-10-06','YYYY-MM-DD'));
```
When you try to insert a date that is on a Sunday, it will say:
`ORA-02290: check constraint (SYS.DAY_IS_NOT_SUNDAY) violated`
|
196,173 |
<p>Modern UI's are starting to give their UI elments nice inertia when moving. Tabs slide in, page transitions, even some listboxes and scroll elments have nice inertia to them (the iphone for example). What is the best algorythm for this? It is more than just gravity as they speed up, and then slow down as they fall into place. I have tried various formulae's for speeding up to a maximum (terminal) velocity and then slowing down but nothing I have tried "feels" right. It always feels a little bit off. Is there a standard for this, or is it just a matter of playing with various numbers until it looks/feels right?</p>
|
[
{
"answer_id": 196178,
"author": "Nils Pipenbrinck",
"author_id": 15955,
"author_profile": "https://Stackoverflow.com/users/15955",
"pm_score": 0,
"selected": false,
"text": "<p>It's playing with the numbers.. What feels good is good.</p>\n\n<p>I've tried to develop magic formulas myself for years. In the end the ugly hack always felt best. Just make sure you somehow time your animations properly and don't rely on some kind of redraw/refresh rate. These tend to change based on the OS.</p>\n"
},
{
"answer_id": 196180,
"author": "Mark",
"author_id": 26310,
"author_profile": "https://Stackoverflow.com/users/26310",
"pm_score": 0,
"selected": false,
"text": "<p>Im no expert on this either, but I beleive they are done with quadratic formulas, that, when given the correct parameters, start fast or slow and dramatically increase or decrease towards the end until a certain point is reached.</p>\n"
},
{
"answer_id": 196209,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": true,
"text": "<p>You're talking about two different things here.</p>\n\n<p>One is momentum - giving things residual motion when you release them from a drag. This is simply about remembering the velocity of a thing when the user releases it, then applying that velocity to the object every frame and also reducing the velocity every frame by some amount. How you reduce velocity every frame is what you experiment with to get the feel right.</p>\n\n<p>The other thing is ease-in and ease-out animation. This is about smoothly accelerating/decelerating objects when you move them between two positions, instead of just linearly interpolating. You do this by simply feeding your 'time' value through a sigmoid function before you use it to interpolate an object between two positions. One such function is</p>\n\n<pre><code>smoothstep(t) = 3*t*t - 2*t*t*t [0 <= t <= 1]\n</code></pre>\n\n<p>This gives you both ease-in and ease-out behaviour. However, you'll more commonly see only ease-out used in GUIs. That is, objects start moving snappily, then slow to a halt at their final position. To achieve that you just use the right half of the curve, ie.</p>\n\n<pre><code>smoothstep_eo(t) = 2*smoothstep((t+1)/2) - 1\n</code></pre>\n"
},
{
"answer_id": 196228,
"author": "Edward Z. Yang",
"author_id": 23845,
"author_profile": "https://Stackoverflow.com/users/23845",
"pm_score": 3,
"selected": false,
"text": "<p>Mike F's got it: you apply a time-position function to calculate the position of an object with respect to time (don't muck around with velocity; it's only useful when you're trying to figure out what algorithm you want to use.)</p>\n\n<p><a href=\"http://www.robertpenner.com/easing/easing_demo.html\" rel=\"noreferrer\">Robert Penner's easing equations and demo</a> are superb; like the <a href=\"http://gsgd.co.uk/sandbox/jquery/easing/\" rel=\"noreferrer\">jQuery demo</a>, they demonstrate visually what the easing looks like, but they also give you a position time graph to give you an idea of the equation behind it.</p>\n"
},
{
"answer_id": 196234,
"author": "James Fassett",
"author_id": 27081,
"author_profile": "https://Stackoverflow.com/users/27081",
"pm_score": 2,
"selected": false,
"text": "<p>What you are looking for is <a href=\"http://en.wikipedia.org/wiki/Interpolation\" rel=\"nofollow noreferrer\">interpolation</a>. Roughly speaking, there are functions that vary from 0 to 1 and when scaled and translated create nice looking movement. This is quite often used in Flash and there are tons of examples: (NOTE: in Flash interpolation has picked up the name \"tweening\" and the most popular type of interpolation is known as \"easing\".)</p>\n\n<p>Have a look at this to get an intuitive feel for the movement types:\n<a href=\"http://www.gskinner.com/blog/archives/2008/05/sparktable_visu.html\" rel=\"nofollow noreferrer\">SparkTable: Visualize Easing Equations</a>.</p>\n\n<p>When applied to movement, scaling, rotation an other animations these equations can give a sense of momentum, or friction, or bouncing or elasticity. For an example when applied to animation have a look at <a href=\"http://www.robertpenner.com/easing/easing_demo.html\" rel=\"nofollow noreferrer\">Robert Penners easing demo</a>. He is the author of the most popular series of animation functions (I believe Adobe's built in ones are based on his). This type of transition works equally as well on alpha's (for fade in).</p>\n\n<p>There is a bit of method to the usage. easeInOut start slow, speeds up and the slows down. easeOut starts fast and slows down (like friction) and easeIn starts slow and speeds up (like momentum). Depending on the feel you want you choose the appropriate one. Then you choose between Sine, Expo, Quad and so on for the strength of the effect. The others are easy to work out by their names (e.g. Bounce bounces, Back goes a little further then comes back like an elastic).</p>\n\n<p>Here is a <a href=\"http://code.google.com/p/tweener/source/browse/trunk/as3/caurina/transitions/Equations.as\" rel=\"nofollow noreferrer\">link to the equations from the popular Tweener library</a> for AS3. You should be able to rewrite these in JavaScript (or any other language) with little to no trouble.</p>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/196173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3798/"
] |
Modern UI's are starting to give their UI elments nice inertia when moving. Tabs slide in, page transitions, even some listboxes and scroll elments have nice inertia to them (the iphone for example). What is the best algorythm for this? It is more than just gravity as they speed up, and then slow down as they fall into place. I have tried various formulae's for speeding up to a maximum (terminal) velocity and then slowing down but nothing I have tried "feels" right. It always feels a little bit off. Is there a standard for this, or is it just a matter of playing with various numbers until it looks/feels right?
|
You're talking about two different things here.
One is momentum - giving things residual motion when you release them from a drag. This is simply about remembering the velocity of a thing when the user releases it, then applying that velocity to the object every frame and also reducing the velocity every frame by some amount. How you reduce velocity every frame is what you experiment with to get the feel right.
The other thing is ease-in and ease-out animation. This is about smoothly accelerating/decelerating objects when you move them between two positions, instead of just linearly interpolating. You do this by simply feeding your 'time' value through a sigmoid function before you use it to interpolate an object between two positions. One such function is
```
smoothstep(t) = 3*t*t - 2*t*t*t [0 <= t <= 1]
```
This gives you both ease-in and ease-out behaviour. However, you'll more commonly see only ease-out used in GUIs. That is, objects start moving snappily, then slow to a halt at their final position. To achieve that you just use the right half of the curve, ie.
```
smoothstep_eo(t) = 2*smoothstep((t+1)/2) - 1
```
|
196,177 |
<p>I have code like this:</p>
<pre><code>var newMsg = new Msg
{
Var1 = var1,
Var2 = var2
};
using (AppDataContext appDataContext = new AppDataContext(ConnectionString))
{
appDataContext.CClass.InsertOnSubmit(newMsg);
appDataContext.SubmitChanges();
}
</code></pre>
<p>After reading <a href="https://stackoverflow.com/questions/157924/does-linqs-executecommand-provide-protection-from-sql-injection-attacks">this post</a> I believe that the same logic applies.</p>
<p>Does anyone think that this is subject to SQL Injection Attack?</p>
|
[
{
"answer_id": 196195,
"author": "liggett78",
"author_id": 19762,
"author_profile": "https://Stackoverflow.com/users/19762",
"pm_score": 4,
"selected": true,
"text": "<p>The second answer in the post you're referencing says it:</p>\n\n<blockquote>\n <p>LINQ to SQL uses <em>execute_sql</em> with\n parameters.</p>\n</blockquote>\n\n<p>It does not concatenate property values into a one big INSERT ... VALUES('...', '...')</p>\n"
},
{
"answer_id": 196237,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>No, but you should be validating user data anyhow.</p>\n"
},
{
"answer_id": 196304,
"author": "Aaron Powell",
"author_id": 11388,
"author_profile": "https://Stackoverflow.com/users/11388",
"pm_score": 2,
"selected": false,
"text": "<p>The underlying operation of the DataContext is via the SqlCommand which uses paramatised SQL.</p>\n\n<p>So your insert statement will look like this:</p>\n\n<pre><code>INSERT INTO [MSG] [Var1] = @p1, [Var2] = @p2\n</code></pre>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/196177",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1463/"
] |
I have code like this:
```
var newMsg = new Msg
{
Var1 = var1,
Var2 = var2
};
using (AppDataContext appDataContext = new AppDataContext(ConnectionString))
{
appDataContext.CClass.InsertOnSubmit(newMsg);
appDataContext.SubmitChanges();
}
```
After reading [this post](https://stackoverflow.com/questions/157924/does-linqs-executecommand-provide-protection-from-sql-injection-attacks) I believe that the same logic applies.
Does anyone think that this is subject to SQL Injection Attack?
|
The second answer in the post you're referencing says it:
>
> LINQ to SQL uses *execute\_sql* with
> parameters.
>
>
>
It does not concatenate property values into a one big INSERT ... VALUES('...', '...')
|
196,179 |
<p>I'm having a problem understanding the shift/reduce confict for a grammar that I know has no ambiguity. The case is one of the if else type but it's not the 'dangling else' problem since I have mandatory END clauses delimiting code blocks.</p>
<p>Here is the grammar for gppg (Its a Bison like compiler compiler ... and that was not an echo):</p>
<pre><code>%output=program.cs
%start program
%token FOR
%token END
%token THINGS
%token WHILE
%token SET
%token IF
%token ELSEIF
%token ELSE
%%
program : statements
;
statements : /*empty */
| statements stmt
;
stmt : flow
| THINGS
;
flow : '#' IF '(' ')' statements else
;
else : '#' END
| '#' ELSE statements '#' END
| elseifs
;
elseifs : elseifs '#' ELSEIF statements else
| '#' ELSEIF statements else
;
</code></pre>
<p>Here is the conflict output:</p>
<pre><code>// Parser Conflict Information for grammar file "program.y"
Shift/Reduce conflict on symbol "'#'", parser will shift
Reduce 10: else -> elseifs
Shift "'#'": State-22 -> State-23
Items for From-state State 22
10 else: elseifs .
-lookahead: '#', THINGS, EOF
11 elseifs: elseifs . '#' ELSEIF statements else
Items for Next-state State 23
11 elseifs: elseifs '#' . ELSEIF statements else
// End conflict information for parser
</code></pre>
<p>I already switched arround everything, and I do know how to resolve it, but that solution involves giving up the left recursion on 'elseif' for a right recursion.</p>
<p>Ive been through all the scarse documentation I have found on the internet regarding this issue (I post some links at the end) and still have not found an elegant solution. I know about ANTLR and I don't want to consider it right now. Please limit your solution to Yacc/Bison parsers.</p>
<p>I would appreciate elegant solutions, I managed to do It by eleminating the /* empty */ rules and duplication everything that needed an empty list but in the larger grammar Im working on It just ends up like 'sparghetti grammar syndrome'.</p>
<p>Here are some links:</p>
<p><a href="http://nitsan.org/~maratb/cs164/bison.html" rel="noreferrer">http://nitsan.org/~maratb/cs164/bison.html</a></p>
<p><a href="http://compilers.iecc.com/comparch/article/98-01-079" rel="noreferrer">http://compilers.iecc.com/comparch/article/98-01-079</a></p>
<p><a href="http://plas.fit.qut.edu.au/gppg/" rel="noreferrer">GPPG, the parser I'm using</a></p>
<p><a href="http://www.gnu.org/software/bison/manual/index.html" rel="noreferrer">Bison manual</a></p>
|
[
{
"answer_id": 196201,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 2,
"selected": false,
"text": "<p>I think the problem is in the elseifs clause.</p>\n\n<pre><code>elseifs : elseifs '#' ELSEIF statements else\n | '#' ELSEIF statements else\n ;\n</code></pre>\n\n<p>I think the first version is not required, since the else clause refers back to elseifs anyway:</p>\n\n<pre><code>else : '#' END\n | '#' ELSE statements '#' END\n | elseifs\n ;\n</code></pre>\n\n<p>What happens if you change elseifs?:</p>\n\n<pre><code>elseifs : '#' ELSEIF statements else\n ;\n</code></pre>\n"
},
{
"answer_id": 196229,
"author": "Caerbanog",
"author_id": 23190,
"author_profile": "https://Stackoverflow.com/users/23190",
"pm_score": 0,
"selected": false,
"text": "<p>I'm still switching thing arround, and my original question had some errors since the <strong>elseifs</strong> sequence had an <strong>else</strong> allways at the end which was wrong. Here is another take at the question, this time I get two shift/reduce conflicts:</p>\n\n<pre><code>flow : '#' IF '(' ')' statements elsebody \n ;\n\nelsebody : else \n | elseifs else\n ;\n\nelse : '#' ELSE statements '#' END\n | '#' END\n ;\n\nelseifs : /* empty */\n | elseifs '#' ELSEIF statements\n ;\n</code></pre>\n\n<p>The conflicts now are:</p>\n\n<pre><code>// Parser Conflict Information for grammar file \"program.y\"\n\nShift/Reduce conflict on symbol \"'#'\", parser will shift\n Reduce 12: elseifs -> /* empty */\n Shift \"'#'\": State-10 -> State-13\n Items for From-state State 10\n 7 flow: '#' IF '(' ')' statements . elsebody \n 4 statements: statements . stmt \n Items for Next-state State 13\n 10 else: '#' . ELSE statements '#' END \n 11 else: '#' . END \n 7 flow: '#' . IF '(' ')' statements elsebody \n\nShift/Reduce conflict on symbol \"'#'\", parser will shift\n Reduce 13: elseifs -> elseifs, '#', ELSEIF, statements\n Shift \"'#'\": State-24 -> State-6\n Items for From-state State 24\n 13 elseifs: elseifs '#' ELSEIF statements .\n -lookahead: '#'\n 4 statements: statements . stmt \n Items for Next-state State 6\n 7 flow: '#' . IF '(' ')' statements elsebody \n\n// End conflict information for parser\n</code></pre>\n\n<p>Empty rules just aggravate the gppg i'm affraid. But they seem so natural to use I keep trying them.</p>\n\n<p>I already know right recursion solves the problem as <em>1800 INFORMATION</em> has said. But I'm looking for a solution with <strong>left recursion</strong> on the <strong>elseifs clause</strong>.</p>\n"
},
{
"answer_id": 196301,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 4,
"selected": true,
"text": "<p>Your revised ELSEIF rule has no markers for a condition -- it should nominally have '(' and ')' added.</p>\n\n<p>More seriously, you now have a rule for</p>\n\n<pre><code>elsebody : else\n | elseifs else\n ;\n</code></pre>\n\n<p>and</p>\n\n<pre><code>elseifs : /* Nothing */\n | elseifs ...something... \n ;\n</code></pre>\n\n<p>The 'nothing' is not needed; it is implicitly taken care of by the 'elsebody' without the 'elseifs'.</p>\n\n<p>I would be very inclined to use rules 'opt_elseifs', 'opt_else', and 'end':</p>\n\n<pre><code>flow : '#' IF '(' ')' statements opt_elseifs opt_else end\n ;\n\nopt_elseifs : /* Nothing */\n | opt_elseifs '#' ELSIF '(' ')' statements \n ;\n\nopt_else : /* Nothing */\n | '#' ELSE statements\n ;\n\nend : '#' END\n ;\n</code></pre>\n\n<p>I've not run this through a parser generator, but I find this relatively easy to understand.</p>\n"
},
{
"answer_id": 196306,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<pre><code>elsebody : elseifs else\n | elseifs\n ;\n\nelseifs : /* empty */\n | elseifs '#' ELSEIF statements\n ;\n\nelse : '#' ELSE statements '#' END\n ;\n</code></pre>\n\n<p>I think this should left recurse and always terminate.</p>\n"
},
{
"answer_id": 196410,
"author": "Dominik Grabiec",
"author_id": 3719,
"author_profile": "https://Stackoverflow.com/users/3719",
"pm_score": 1,
"selected": false,
"text": "<p>The answer from Jonathan above seems like it would be the best, but since its not working for you I have a few suggestions you could try that will help you in debugging the error.</p>\n\n<p>Firstly have you considered making the hash/sharp symbol a part of the tokens themselves (i.e. #END, #IF, etc)? So that they get taken out by the lexer, meaning they don't have to be included in the parser.</p>\n\n<p>Secondly I would urge you to rewrite the rules without duplicating any token streams. (Part of the Don't Repeat Yourself principle.) So the rule \" '#' ELSEIF statements else \" should only exist in one place in that file (not two as you have above). </p>\n\n<p>Lastly I suggest that you look into precedence and associativity of the IF/ELSEIF/ELSE tokens. I know that you should be able to write a parser that doesn't require this but it might be the thing that you need in this case.</p>\n"
},
{
"answer_id": 196692,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 0,
"selected": false,
"text": "<p>OK - here is a grammar (not minimal) for if blocks. I dug it out of some code I have (called adhoc, based on hoc from Kernighan & Plauger's \"The UNIX Programming Environment\"). This outline grammar compiles with Yacc with no conflicts.</p>\n\n<pre><code>%token NUMBER IF ELSE\n%token ELIF END\n%token THEN\n%start program\n\n%%\n\nprogram\n : stmtlist\n ;\n\nstmtlist\n : /* Nothing */\n | stmtlist stmt\n ;\n\nstmt\n : ifstmt\n ;\n\nifstmt\n : ifcond endif\n | ifcond else begin\n | ifcond eliflist begin\n ;\n\nifcond\n : ifstart cond then stmtlist\n ;\n\nifstart\n : IF\n ;\n\ncond\n : '(' expr ')'\n ;\n\nthen\n : /* Nothing */\n | THEN\n ;\n\nendif\n : END IF begin\n ;\n\nelse\n : ELSE stmtlist END IF\n ;\n\neliflist\n : elifblock\n | elifcond eliflist begin /* RIGHT RECURSION */\n ;\n\nelifblock\n : elifcond else begin\n | elifcond endif\n ;\n\nelifcond\n : elif cond then stmtlist end\n ;\n\nelif\n : ELIF\n ;\n\nbegin\n : /* Nothing */\n ;\n\nend\n : /* Nothing */\n ;\n\nexpr\n : NUMBER\n ;\n\n%%\n</code></pre>\n\n<p>I used 'NUMBER' as the dummy element, instead of THINGS, and I used ELIF instead of ELSEIF. It includes a THEN, but that is optional. The 'begin' and 'end' operations were used to grab the program counter in the generated program - and therefore should be removable from this without affecting it.</p>\n\n<p>There was a reason I thought I needed to use right recursion instead of the normal left recursion - but I think it was to do with the code generation strategy I was using, rather than anything else. The question mark in the comment was in the original; I remember not being happy with it. The program as a whole does work - it is a project that's been on the back burner for the last decade or so (hmmm...I did some work at the end of 2004 and beginning of 2005; prior to that, it was 1992 and 1993).</p>\n\n<p>I've not spent the time working out why this compiles conflict-free and what I outlined earlier does not. I hope it helps.</p>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/196179",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23190/"
] |
I'm having a problem understanding the shift/reduce confict for a grammar that I know has no ambiguity. The case is one of the if else type but it's not the 'dangling else' problem since I have mandatory END clauses delimiting code blocks.
Here is the grammar for gppg (Its a Bison like compiler compiler ... and that was not an echo):
```
%output=program.cs
%start program
%token FOR
%token END
%token THINGS
%token WHILE
%token SET
%token IF
%token ELSEIF
%token ELSE
%%
program : statements
;
statements : /*empty */
| statements stmt
;
stmt : flow
| THINGS
;
flow : '#' IF '(' ')' statements else
;
else : '#' END
| '#' ELSE statements '#' END
| elseifs
;
elseifs : elseifs '#' ELSEIF statements else
| '#' ELSEIF statements else
;
```
Here is the conflict output:
```
// Parser Conflict Information for grammar file "program.y"
Shift/Reduce conflict on symbol "'#'", parser will shift
Reduce 10: else -> elseifs
Shift "'#'": State-22 -> State-23
Items for From-state State 22
10 else: elseifs .
-lookahead: '#', THINGS, EOF
11 elseifs: elseifs . '#' ELSEIF statements else
Items for Next-state State 23
11 elseifs: elseifs '#' . ELSEIF statements else
// End conflict information for parser
```
I already switched arround everything, and I do know how to resolve it, but that solution involves giving up the left recursion on 'elseif' for a right recursion.
Ive been through all the scarse documentation I have found on the internet regarding this issue (I post some links at the end) and still have not found an elegant solution. I know about ANTLR and I don't want to consider it right now. Please limit your solution to Yacc/Bison parsers.
I would appreciate elegant solutions, I managed to do It by eleminating the /\* empty \*/ rules and duplication everything that needed an empty list but in the larger grammar Im working on It just ends up like 'sparghetti grammar syndrome'.
Here are some links:
<http://nitsan.org/~maratb/cs164/bison.html>
<http://compilers.iecc.com/comparch/article/98-01-079>
[GPPG, the parser I'm using](http://plas.fit.qut.edu.au/gppg/)
[Bison manual](http://www.gnu.org/software/bison/manual/index.html)
|
Your revised ELSEIF rule has no markers for a condition -- it should nominally have '(' and ')' added.
More seriously, you now have a rule for
```
elsebody : else
| elseifs else
;
```
and
```
elseifs : /* Nothing */
| elseifs ...something...
;
```
The 'nothing' is not needed; it is implicitly taken care of by the 'elsebody' without the 'elseifs'.
I would be very inclined to use rules 'opt\_elseifs', 'opt\_else', and 'end':
```
flow : '#' IF '(' ')' statements opt_elseifs opt_else end
;
opt_elseifs : /* Nothing */
| opt_elseifs '#' ELSIF '(' ')' statements
;
opt_else : /* Nothing */
| '#' ELSE statements
;
end : '#' END
;
```
I've not run this through a parser generator, but I find this relatively easy to understand.
|
196,216 |
<p>I am new to strut/web programming and I thought I could learn a lot by reading a sample app. On google, I searched and found a sample app at
<a href="http://www.roseindia.net/struts/struts2/struts2tutorial.zip" rel="nofollow noreferrer">http://www.roseindia.net/struts/struts2/struts2tutorial.zip</a> , the tutorial is really nice and it gives a sample login page.</p>
<p>However, I couldn't run this sample app. I tried posting on the roseindia.net site and got no help neither.</p>
<p>There is no error logged during the start of the server, but when I try and open one of the helloworld's link the following is outputted</p>
<p>I am getting this error</p>
<blockquote>
<p>SEVERE: Could not find action or result There is no Action mapped for
action name HelloWorld. - [unknown location]</p>
</blockquote>
<p>The folder structure of this thing on my eclipse is</p>
<pre><code>/WebContent/WEB-INF/java/net/roseindia/Struts2HelloWorld.java
/WebContent/pages/HelloWorld.jsp
/WebContent/WEB-INF/struts.xml
</code></pre>
<p>while in strut.xml the sample had..<br>
</p>
<pre><code> <action name="HelloWorld" class="net.roseindia.Struts2HelloWorld">
<result>/pages/HelloWorld.jsp</result>
</action>
</code></pre>
<p>I am suspecting something in the strut.xml is wrong? I am using eclipse J2EE and tomcat6, I have already tried posting on roseindia's site and got no help.</p>
|
[
{
"answer_id": 196258,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 2,
"selected": false,
"text": "<p>You will learn a lot by reading sample apps. If your sample doesn't work, perhaps your sample is wrong.</p>\n\n<p>Perhaps you need the actual authoritative documentation. See <a href=\"http://struts.apache.org/1.2.4/faqs/eclipse.html\" rel=\"nofollow noreferrer\">How to setup a basic struts project using Eclipse</a>. This is the as official as any Eclipse - Struts documentation can be.</p>\n\n<p>Perhaps you need a better example. See the Struts Community <a href=\"http://struts.sourceforge.net/community/examples.html\" rel=\"nofollow noreferrer\">Projects and Examples</a> web site for numerous examples.</p>\n"
},
{
"answer_id": 196298,
"author": "David M. Karr",
"author_id": 10508,
"author_profile": "https://Stackoverflow.com/users/10508",
"pm_score": 0,
"selected": false,
"text": "<p>Did you name the file \"strut.xml\" or \"struts.xml\"? It should be the latter (although you could override it if you wanted). Also, in Struts 2 the struts.xml file has to be in the classpath, not at the root of WEB-INF. So, in your project, you should put in the \"src\" folder, so when it deploys it goes into WEB-INF/classes. You can verify it goes into the correct place by doing an \"Export\" of the web application to a WAR file and verifying it went into WEB-INF/classes.</p>\n"
},
{
"answer_id": 723252,
"author": "razlebe",
"author_id": 27615,
"author_profile": "https://Stackoverflow.com/users/27615",
"pm_score": 0,
"selected": false,
"text": "<p>I've just downloaded a copy of this tutorial, and deployed it to Tomcat 6 - and it works!</p>\n\n<p>Perhaps they have fixed the bug since you last tried? Or perhaps there's something wrong with the way you have Eclipse configured. </p>\n\n<p>Al I did was to unzip the tutorial; copy the directory into the Tomcat webapps directory; start Tomcat; navigate to the Tomcat manager page on my PC; and click the link to the struts2tutorial application. </p>\n\n<p>Give it another try...</p>\n"
},
{
"answer_id": 4298347,
"author": "Hans Beemsterboer",
"author_id": 522561,
"author_profile": "https://Stackoverflow.com/users/522561",
"pm_score": 0,
"selected": false,
"text": "<p>I had the same issue in Eclipse and solved it by changing the output folder of the source folder to:</p>\n\n<pre><code>WebContent/WEB-INF/classes\n</code></pre>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/196216",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17085/"
] |
I am new to strut/web programming and I thought I could learn a lot by reading a sample app. On google, I searched and found a sample app at
<http://www.roseindia.net/struts/struts2/struts2tutorial.zip> , the tutorial is really nice and it gives a sample login page.
However, I couldn't run this sample app. I tried posting on the roseindia.net site and got no help neither.
There is no error logged during the start of the server, but when I try and open one of the helloworld's link the following is outputted
I am getting this error
>
> SEVERE: Could not find action or result There is no Action mapped for
> action name HelloWorld. - [unknown location]
>
>
>
The folder structure of this thing on my eclipse is
```
/WebContent/WEB-INF/java/net/roseindia/Struts2HelloWorld.java
/WebContent/pages/HelloWorld.jsp
/WebContent/WEB-INF/struts.xml
```
while in strut.xml the sample had..
```
<action name="HelloWorld" class="net.roseindia.Struts2HelloWorld">
<result>/pages/HelloWorld.jsp</result>
</action>
```
I am suspecting something in the strut.xml is wrong? I am using eclipse J2EE and tomcat6, I have already tried posting on roseindia's site and got no help.
|
You will learn a lot by reading sample apps. If your sample doesn't work, perhaps your sample is wrong.
Perhaps you need the actual authoritative documentation. See [How to setup a basic struts project using Eclipse](http://struts.apache.org/1.2.4/faqs/eclipse.html). This is the as official as any Eclipse - Struts documentation can be.
Perhaps you need a better example. See the Struts Community [Projects and Examples](http://struts.sourceforge.net/community/examples.html) web site for numerous examples.
|
196,224 |
<p>I have a component which writes/generates javascript from a server side renderer. This component can be used in multiple times in a same page. However, once the page is loaded I have to collect all the variables or JSO written by this multiple components in the page. How can I do this so that I will have a collection of all the variables or JSO?
For e.g. If this component (lets say ) is used twice in the page then it emits two javascript block on client/browser -
var arr1 = new Array['First', 'Second'] and
var arr2 = new Array['Third', 'Fourth']. </p>
<p>In order to make a final rendering I have to combine these two arrays.</p>
|
[
{
"answer_id": 196271,
"author": "Vincent Robert",
"author_id": 268,
"author_profile": "https://Stackoverflow.com/users/268",
"pm_score": 2,
"selected": true,
"text": "<p>You will need to be a little more specific about your problem, maybe with an example page but here are some thoughts.</p>\n\n<p>If you have a server-side component that writes JavaScript during page generation, I would generate a function call each time, something like:</p>\n\n<pre><code>Component_appendArray(['First', 'Second']);\n...\nComponent_appendArray(['Third', 'Fourth']);\n</code></pre>\n\n<p>then ensure that you have your function <code>Component_appendArray()</code> defined before these calls:</p>\n\n<pre><code>var globalArray = [];\nfunction Component_appendArray(array)\n{\n globalArray = globalArray.concat(array);\n}\n</code></pre>\n\n<p>At the end, <code>globalArray</code> should contain:</p>\n\n<pre><code>['First', 'Second', 'Third', 'Fourth']\n</code></pre>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 196289,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Although I do not understand the entire scenario, let me suggest that if you are printing out variables throughout the HTML in order to use them after the page loads, that you instead use hidden input fields. I see this often, where variables are used to pass values to a function or a script at the bottom of the page, but using the values of hidden input fields allows you to get all your scripts out of the content areas. It makes for a cleaner solution.</p>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/196224",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3627/"
] |
I have a component which writes/generates javascript from a server side renderer. This component can be used in multiple times in a same page. However, once the page is loaded I have to collect all the variables or JSO written by this multiple components in the page. How can I do this so that I will have a collection of all the variables or JSO?
For e.g. If this component (lets say ) is used twice in the page then it emits two javascript block on client/browser -
var arr1 = new Array['First', 'Second'] and
var arr2 = new Array['Third', 'Fourth'].
In order to make a final rendering I have to combine these two arrays.
|
You will need to be a little more specific about your problem, maybe with an example page but here are some thoughts.
If you have a server-side component that writes JavaScript during page generation, I would generate a function call each time, something like:
```
Component_appendArray(['First', 'Second']);
...
Component_appendArray(['Third', 'Fourth']);
```
then ensure that you have your function `Component_appendArray()` defined before these calls:
```
var globalArray = [];
function Component_appendArray(array)
{
globalArray = globalArray.concat(array);
}
```
At the end, `globalArray` should contain:
```
['First', 'Second', 'Third', 'Fourth']
```
Hope this helps.
|
196,294 |
<p>I'm trying to learn about catamorphisms and I've read <a href="http://en.wikipedia.org/wiki/Catamorphism" rel="noreferrer">the Wikipedia article</a> and the first couple posts in <a href="http://lorgonblog.spaces.live.com/Blog/cns!701679AD17B6D310!256.entry" rel="noreferrer">the series of the topic for F#</a> on the <em>Inside F#</em> blog. </p>
<p>I understand that it's a generalization of folds (i.e., mapping a structure of many values to one value, including a list of values to another list). And I gather that the fold-list and fold-tree is a canonical example.</p>
<p>Can this be shown to be done in C#, using LINQ's <code>Aggregate</code> operator or some other higher-order method?</p>
|
[
{
"answer_id": 196309,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 4,
"selected": false,
"text": "<p>I've been doing more reading, including a Micorosft Research paper on <a href=\"http://research.microsoft.com/~emeijer/Papers/fpca91.pdf\" rel=\"nofollow noreferrer\">functional programming with catamorphisms (\"bananas\")</a>, and it seems that <strong><em>catamorphism</em></strong> just refers to any function that takes a list and typically breaks it down to a single value (<code>IEnumerable<A> => B</code>), like <code>Max()</code>, <code>Min()</code>, and in the general case, <code>Aggregate()</code>, would all be a catamorphisms for lists. </p>\n\n<p>I was previously under the impression that it refefred to a way of creating a function that can generalize different folds, so that it can fold a tree <em>and</em> a list. There may actually still be such a thing, some kind of <em>functor</em> or <em>arrow</em> maybe but right now that's beyond my level of understanding.</p>\n"
},
{
"answer_id": 196451,
"author": "Brian",
"author_id": 19299,
"author_profile": "https://Stackoverflow.com/users/19299",
"pm_score": 6,
"selected": true,
"text": "<p>LINQ's <code>Aggregate()</code> is just for <code>IEnumerables</code>. Catamorphisms in general refer to the pattern of folding for an arbitrary data type. So <code>Aggregate()</code> is to <code>IEnumerables</code> what <code>FoldTree</code> (below) is to <code>Trees</code> (below); both are catamorphisms for their respective data types.</p>\n\n<p>I translated some of the code in <a href=\"http://lorgonblog.spaces.live.com/blog/cns!701679AD17B6D310!248.entry\" rel=\"nofollow noreferrer\">part 4 of the series</a> into C#. The code is below. Note that the equivalent F# used three less-than characters (for generic type parameter annotations), whereas this C# code uses more than 60. This is evidence why no one writes such code in C# - there are too many type annotations. I present the code in case it helps people who know C# but not F# play with this. But the code is so dense in C#, it's very hard to make sense of.</p>\n\n<p>Given the following definition for a binary tree:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Input;\nusing System.Windows.Media;\nusing System.Windows.Shapes;\n\nclass Tree<T> // use null for Leaf\n{\n public T Data { get; private set; }\n public Tree<T> Left { get; private set; }\n public Tree<T> Right { get; private set; }\n public Tree(T data, Tree<T> left, Tree<T> rright)\n {\n this.Data = data;\n this.Left = left;\n this.Right = right;\n }\n\n public static Tree<T> Node<T>(T data, Tree<T> left, Tree<T> right)\n {\n return new Tree<T>(data, left, right);\n }\n}\n</code></pre>\n\n<p>One can fold trees and e.g. measure if two trees have different nodes:</p>\n\n<pre><code>class Tree\n{\n public static Tree<int> Tree7 =\n Node(4, Node(2, Node(1, null, null), Node(3, null, null)),\n Node(6, Node(5, null, null), Node(7, null, null)));\n\n public static R XFoldTree<A, R>(Func<A, R, R, Tree<A>, R> nodeF, Func<Tree<A>, R> leafV, Tree<A> tree)\n {\n return Loop(nodeF, leafV, tree, x => x);\n }\n\n public static R Loop<A, R>(Func<A, R, R, Tree<A>, R> nodeF, Func<Tree<A>, R> leafV, Tree<A> t, Func<R, R> cont)\n {\n if (t == null)\n return cont(leafV(t));\n else\n return Loop(nodeF, leafV, t.Left, lacc =>\n Loop(nodeF, leafV, t.Right, racc =>\n cont(nodeF(t.Data, lacc, racc, t))));\n }\n\n public static R FoldTree<A, R>(Func<A, R, R, R> nodeF, R leafV, Tree<A> tree)\n {\n return XFoldTree((x, l, r, _) => nodeF(x, l, r), _ => leafV, tree);\n }\n\n public static Func<Tree<A>, Tree<A>> XNode<A>(A x, Tree<A> l, Tree<A> r)\n {\n return (Tree<A> t) => x.Equals(t.Data) && l == t.Left && r == t.Right ? t : Node(x, l, r);\n }\n\n // DiffTree: Tree<'a> * Tree<'a> -> Tree<'a * bool> \n // return second tree with extra bool \n // the bool signifies whether the Node \"ReferenceEquals\" the first tree \n public static Tree<KeyValuePair<A, bool>> DiffTree<A>(Tree<A> tree, Tree<A> tree2)\n {\n return XFoldTree((A x, Func<Tree<A>, Tree<KeyValuePair<A, bool>>> l, Func<Tree<A>, Tree<KeyValuePair<A, bool>>> r, Tree<A> t) => (Tree<A> t2) =>\n Node(new KeyValuePair<A, bool>(t2.Data, object.ReferenceEquals(t, t2)),\n l(t2.Left), r(t2.Right)),\n x => y => null, tree)(tree2);\n }\n}\n</code></pre>\n\n<p>In this second example, another tree is reconstructed differently:</p>\n\n<pre><code>class Example\n{\n // original version recreates entire tree, yuck \n public static Tree<int> Change5to0(Tree<int> tree)\n {\n return Tree.FoldTree((int x, Tree<int> l, Tree<int> r) => Tree.Node(x == 5 ? 0 : x, l, r), null, tree);\n }\n\n // here it is with XFold - same as original, only with Xs \n public static Tree<int> XChange5to0(Tree<int> tree)\n {\n return Tree.XFoldTree((int x, Tree<int> l, Tree<int> r, Tree<int> orig) =>\n Tree.XNode(x == 5 ? 0 : x, l, r)(orig), _ => null, tree);\n }\n}\n</code></pre>\n\n<p>And in this third example, folding a tree is used for drawing:</p>\n\n<pre><code>class MyWPFWindow : Window \n{\n void Draw(Canvas canvas, Tree<KeyValuePair<int, bool>> tree)\n {\n // assumes canvas is normalized to 1.0 x 1.0 \n Tree.FoldTree((KeyValuePair<int, bool> kvp, Func<Transform, Transform> l, Func<Transform, Transform> r) => trans =>\n {\n // current node in top half, centered left-to-right \n var tb = new TextBox();\n tb.Width = 100.0; \n tb.Height = 100.0;\n tb.FontSize = 70.0;\n // the tree is a \"diff tree\" where the bool represents \n // \"ReferenceEquals\" differences, so color diffs Red \n tb.Foreground = (kvp.Value ? Brushes.Black : Brushes.Red);\n tb.HorizontalContentAlignment = HorizontalAlignment.Center;\n tb.VerticalContentAlignment = VerticalAlignment.Center;\n tb.RenderTransform = AddT(trans, TranslateT(0.25, 0.0, ScaleT(0.005, 0.005, new TransformGroup())));\n tb.Text = kvp.Key.ToString();\n canvas.Children.Add(tb);\n // left child in bottom-left quadrant \n l(AddT(trans, TranslateT(0.0, 0.5, ScaleT(0.5, 0.5, new TransformGroup()))));\n // right child in bottom-right quadrant \n r(AddT(trans, TranslateT(0.5, 0.5, ScaleT(0.5, 0.5, new TransformGroup()))));\n return null;\n }, _ => null, tree)(new TransformGroup());\n }\n\n public MyWPFWindow(Tree<KeyValuePair<int, bool>> tree)\n {\n var canvas = new Canvas();\n canvas.Width=1.0;\n canvas.Height=1.0;\n canvas.Background = Brushes.Blue;\n canvas.LayoutTransform=new ScaleTransform(200.0, 200.0);\n Draw(canvas, tree);\n this.Content = canvas;\n this.Title = \"MyWPFWindow\";\n this.SizeToContent = SizeToContent.WidthAndHeight;\n }\n TransformGroup AddT(Transform t, TransformGroup tg) { tg.Children.Add(t); return tg; }\n TransformGroup ScaleT(double x, double y, TransformGroup tg) { tg.Children.Add(new ScaleTransform(x,y)); return tg; }\n TransformGroup TranslateT(double x, double y, TransformGroup tg) { tg.Children.Add(new TranslateTransform(x,y)); return tg; }\n\n [STAThread]\n static void Main(string[] args)\n {\n var app = new Application();\n //app.Run(new MyWPFWindow(Tree.DiffTree(Tree.Tree7,Example.Change5to0(Tree.Tree7))));\n app.Run(new MyWPFWindow(Tree.DiffTree(Tree.Tree7, Example.XChange5to0(Tree.Tree7))));\n }\n} \n</code></pre>\n"
},
{
"answer_id": 2154336,
"author": "Thiagarajan",
"author_id": 260946,
"author_profile": "https://Stackoverflow.com/users/260946",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>I understand that it's a\n generalization of folds (i.e., mapping\n a structure of many values to one\n value, including a list of values to\n another list).</p>\n</blockquote>\n\n<p>I wouldn't say one value.It maps it into another structure.</p>\n\n<p>Maybe an example would clarify.let's say summation over a list.</p>\n\n<p>foldr (\\x -> \\y -> x + y) 0 [1,2,3,4,5]</p>\n\n<p>Now this would reduce to 15.\nBut actually,it can be viewed mapping to a purely syntactic structure 1 + 2 + 3 + 4 + 5 + 0.\nIt is just that the programming language(in the above case,haskell) knows how to reduce the above syntactic structure to 15.</p>\n\n<p>Basically,a catamorphism replaces one data constructor with another one.In case of above list,</p>\n\n<p>[1,2,3,4,5] = 1:2:3:4:5:[] (: is the cons operator,[] is the nil element)\nthe catamorphism above replaced : with + and [] with 0.</p>\n\n<p>It can be generalized to any recursive datatypes.</p>\n"
},
{
"answer_id": 11583895,
"author": "Tuomas Hietanen",
"author_id": 17791,
"author_profile": "https://Stackoverflow.com/users/17791",
"pm_score": 2,
"selected": false,
"text": "<p>Brian had great series of posts in his blog. Also Channel9 had a <a href=\"https://channel9.msdn.com/Shows/Going+Deep/C9-Lectures-Dr-Ralf-Lmmel-Going-Bananas\" rel=\"nofollow\">nice video</a>. There is no LINQ syntactic sugar for .Aggregate() so does it matter if it has the definition of LINQ Aggregate method or not? The idea is of course the same.\nFolding over trees... First we need a Node... maybe Tuple could be used, but this is more clear:</p>\n\n<pre><code>public class Node<TData, TLeft, TRight>\n{\n public TLeft Left { get; private set; }\n public TRight Right { get; private set; }\n public TData Data { get; private set; }\n public Node(TData x, TLeft l, TRight r){ Data = x; Left = l; Right = r; }\n}\n</code></pre>\n\n<p>Then, in C# we <em>can</em> make a recursive type, even this is unusual:</p>\n\n<pre><code>public class Tree<T> : Node</* data: */ T, /* left: */ Tree<T>, /* right: */ Tree<T>>\n{\n // Normal node:\n public Tree(T data, Tree<T> left, Tree<T> right): base(data, left, right){}\n // No children:\n public Tree(T data) : base(data, null, null) { }\n}\n</code></pre>\n\n<p>Now, I will quote some of Brian's code, with slight LINQ-style modifications:</p>\n\n<ol>\n<li>In C# Fold is called Aggregate</li>\n<li>LINQ methods are Extension methods that have the item as first parameter with \"this\"-keyword.</li>\n<li>Loop can be private</li>\n</ol>\n\n<p>...</p>\n\n<pre><code>public static class TreeExtensions\n{\n private static R Loop<A, R>(Func<A, R, R, Tree<A>, R> nodeF, Func<Tree<A>, R> leafV, Tree<A> t, Func<R, R> cont)\n {\n if (t == null) return cont(leafV(t));\n return Loop(nodeF, leafV, t.Left, lacc =>\n Loop(nodeF, leafV, t.Right, racc =>\n cont(nodeF(t.Data, lacc, racc, t))));\n } \n public static R XAggregateTree<A, R>(this Tree<A> tree, Func<A, R, R, Tree<A>, R> nodeF, Func<Tree<A>, R> leafV)\n {\n return Loop(nodeF, leafV, tree, x => x);\n }\n\n public static R Aggregate<A, R>(this Tree<A> tree, Func<A, R, R, R> nodeF, R leafV)\n {\n return tree.XAggregateTree((x, l, r, _) => nodeF(x, l, r), _ => leafV);\n }\n}\n</code></pre>\n\n<p>Now, the usage is quite C#-style:</p>\n\n<pre><code>[TestMethod] // or Console Application:\nstatic void Main(string[] args)\n{\n // This is our tree:\n // 4 \n // 2 6 \n // 1 3 5 7 \n var tree7 = new Tree<int>(4, new Tree<int>(2, new Tree<int>(1), new Tree<int>(3)),\n new Tree<int>(6, new Tree<int>(5), new Tree<int>(7)));\n\n var sumTree = tree7.Aggregate((x, l, r) => x + l + r, 0);\n Console.WriteLine(sumTree); // 28\n Console.ReadLine();\n\n var inOrder = tree7.Aggregate((x, l, r) =>\n {\n var tmp = new List<int>(l) {x};\n tmp.AddRange(r);\n return tmp;\n }, new List<int>());\n inOrder.ForEach(Console.WriteLine); // 1 2 3 4 5 6 7\n Console.ReadLine();\n\n var heightTree = tree7.Aggregate((_, l, r) => 1 + (l>r?l:r), 0);\n Console.WriteLine(heightTree); // 3\n Console.ReadLine();\n}\n</code></pre>\n\n<p>I still like F# more.</p>\n"
},
{
"answer_id": 21103146,
"author": "Polymer",
"author_id": 730606,
"author_profile": "https://Stackoverflow.com/users/730606",
"pm_score": 3,
"selected": false,
"text": "<p>Brian's answer in the first paragraph is correct. But his code example doesn't really reflect how one would solve similar problems in a C# style. Consider a simple class <code>node</code>:</p>\n\n<pre><code>class Node {\n public Node Left;\n public Node Right;\n public int value;\n public Node(int v = 0, Node left = null, Node right = null) {\n value = v;\n Left = left;\n Right = right;\n }\n}\n</code></pre>\n\n<p>With this we can create a tree in main:</p>\n\n<pre><code>var Tree = \n new Node(4,\n new Node(2, \n new Node(1),\n new Node(3)\n ),\n new Node(6,\n new Node(5),\n new Node(7)\n )\n );\n</code></pre>\n\n<p>We define a generic fold function in <code>Node</code>'s namespace:</p>\n\n<pre><code>public static R fold<R>(\n Func<int, R, R, R> combine,\n R leaf_value,\n Node tree) {\n\n if (tree == null) return leaf_value;\n\n return \n combine(\n tree.value, \n fold(combine, leaf_value, tree.Left),\n fold(combine, leaf_value, tree.Right)\n );\n}\n</code></pre>\n\n<p>For catamorphisms we should specify the states of data, Nodes can be null, or have children. The generic parameters determine what we do in either case. Notice the iteration strategy(in this case recursion) is hidden inside the fold function.</p>\n\n<p>Now instead of writing:</p>\n\n<pre><code>public static int Sum_Tree(Node tree){\n if (tree == null) return 0;\n var accumulated = tree.value;\n accumulated += Sum_Tree(tree.Left);\n accumulated += Sum_Tree(tree.Right);\n return accumulated; \n}\n</code></pre>\n\n<p>We can write</p>\n\n<pre><code>public static int sum_tree_fold(Node tree) {\n return Node.fold(\n (x, l, r) => x + l + r,\n 0,\n tree\n );\n}\n</code></pre>\n\n<p>Elegant, simple, type checked, maintainable, etc. Easy to use <code>Console.WriteLine(Node.Sum_Tree(Tree));</code>.</p>\n\n<p>It's easy to add new functionality:</p>\n\n<pre><code>public static List<int> In_Order_fold(Node tree) {\n return Node.fold(\n (x, l, r) => {\n var tree_list = new List<int>();\n tree_list.Add(x);\n tree_list.InsertRange(0, l);\n tree_list.AddRange(r);\n return tree_list;\n },\n new List<int>(),\n tree\n );\n}\npublic static int Height_fold(Node tree) {\n return Node.fold(\n (x, l, r) => 1 + Math.Max(l, r),\n 0,\n tree\n );\n}\n</code></pre>\n\n<p>F# wins in the conciseness category for <code>In_Order_fold</code> but that's to be expected when the language provides dedicated operators for constructing and using lists.</p>\n\n<p>The dramatic difference between C# and F# seems to be due to F#'s use of closures, to act as implicit data structures, for triggering the tail call optimization. The example in Brian's answer also takes in to account optimizations in F#, for dodging reconstructing the tree. I'm not sure C# supports the tail call optimization, and maybe <code>In_Order_fold</code> could be written better, but neither of these points are relevant when discussing how expressive C# is when dealing with these Catamorphisms.</p>\n\n<p>When translating code between languages, you need to understand the core idea of the technique, and then implement the idea in terms of the language's primitives.</p>\n\n<p>Maybe now you'll be able to convince your C# co-workers to take folds more seriously.</p>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/196294",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1659/"
] |
I'm trying to learn about catamorphisms and I've read [the Wikipedia article](http://en.wikipedia.org/wiki/Catamorphism) and the first couple posts in [the series of the topic for F#](http://lorgonblog.spaces.live.com/Blog/cns!701679AD17B6D310!256.entry) on the *Inside F#* blog.
I understand that it's a generalization of folds (i.e., mapping a structure of many values to one value, including a list of values to another list). And I gather that the fold-list and fold-tree is a canonical example.
Can this be shown to be done in C#, using LINQ's `Aggregate` operator or some other higher-order method?
|
LINQ's `Aggregate()` is just for `IEnumerables`. Catamorphisms in general refer to the pattern of folding for an arbitrary data type. So `Aggregate()` is to `IEnumerables` what `FoldTree` (below) is to `Trees` (below); both are catamorphisms for their respective data types.
I translated some of the code in [part 4 of the series](http://lorgonblog.spaces.live.com/blog/cns!701679AD17B6D310!248.entry) into C#. The code is below. Note that the equivalent F# used three less-than characters (for generic type parameter annotations), whereas this C# code uses more than 60. This is evidence why no one writes such code in C# - there are too many type annotations. I present the code in case it helps people who know C# but not F# play with this. But the code is so dense in C#, it's very hard to make sense of.
Given the following definition for a binary tree:
```
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Shapes;
class Tree<T> // use null for Leaf
{
public T Data { get; private set; }
public Tree<T> Left { get; private set; }
public Tree<T> Right { get; private set; }
public Tree(T data, Tree<T> left, Tree<T> rright)
{
this.Data = data;
this.Left = left;
this.Right = right;
}
public static Tree<T> Node<T>(T data, Tree<T> left, Tree<T> right)
{
return new Tree<T>(data, left, right);
}
}
```
One can fold trees and e.g. measure if two trees have different nodes:
```
class Tree
{
public static Tree<int> Tree7 =
Node(4, Node(2, Node(1, null, null), Node(3, null, null)),
Node(6, Node(5, null, null), Node(7, null, null)));
public static R XFoldTree<A, R>(Func<A, R, R, Tree<A>, R> nodeF, Func<Tree<A>, R> leafV, Tree<A> tree)
{
return Loop(nodeF, leafV, tree, x => x);
}
public static R Loop<A, R>(Func<A, R, R, Tree<A>, R> nodeF, Func<Tree<A>, R> leafV, Tree<A> t, Func<R, R> cont)
{
if (t == null)
return cont(leafV(t));
else
return Loop(nodeF, leafV, t.Left, lacc =>
Loop(nodeF, leafV, t.Right, racc =>
cont(nodeF(t.Data, lacc, racc, t))));
}
public static R FoldTree<A, R>(Func<A, R, R, R> nodeF, R leafV, Tree<A> tree)
{
return XFoldTree((x, l, r, _) => nodeF(x, l, r), _ => leafV, tree);
}
public static Func<Tree<A>, Tree<A>> XNode<A>(A x, Tree<A> l, Tree<A> r)
{
return (Tree<A> t) => x.Equals(t.Data) && l == t.Left && r == t.Right ? t : Node(x, l, r);
}
// DiffTree: Tree<'a> * Tree<'a> -> Tree<'a * bool>
// return second tree with extra bool
// the bool signifies whether the Node "ReferenceEquals" the first tree
public static Tree<KeyValuePair<A, bool>> DiffTree<A>(Tree<A> tree, Tree<A> tree2)
{
return XFoldTree((A x, Func<Tree<A>, Tree<KeyValuePair<A, bool>>> l, Func<Tree<A>, Tree<KeyValuePair<A, bool>>> r, Tree<A> t) => (Tree<A> t2) =>
Node(new KeyValuePair<A, bool>(t2.Data, object.ReferenceEquals(t, t2)),
l(t2.Left), r(t2.Right)),
x => y => null, tree)(tree2);
}
}
```
In this second example, another tree is reconstructed differently:
```
class Example
{
// original version recreates entire tree, yuck
public static Tree<int> Change5to0(Tree<int> tree)
{
return Tree.FoldTree((int x, Tree<int> l, Tree<int> r) => Tree.Node(x == 5 ? 0 : x, l, r), null, tree);
}
// here it is with XFold - same as original, only with Xs
public static Tree<int> XChange5to0(Tree<int> tree)
{
return Tree.XFoldTree((int x, Tree<int> l, Tree<int> r, Tree<int> orig) =>
Tree.XNode(x == 5 ? 0 : x, l, r)(orig), _ => null, tree);
}
}
```
And in this third example, folding a tree is used for drawing:
```
class MyWPFWindow : Window
{
void Draw(Canvas canvas, Tree<KeyValuePair<int, bool>> tree)
{
// assumes canvas is normalized to 1.0 x 1.0
Tree.FoldTree((KeyValuePair<int, bool> kvp, Func<Transform, Transform> l, Func<Transform, Transform> r) => trans =>
{
// current node in top half, centered left-to-right
var tb = new TextBox();
tb.Width = 100.0;
tb.Height = 100.0;
tb.FontSize = 70.0;
// the tree is a "diff tree" where the bool represents
// "ReferenceEquals" differences, so color diffs Red
tb.Foreground = (kvp.Value ? Brushes.Black : Brushes.Red);
tb.HorizontalContentAlignment = HorizontalAlignment.Center;
tb.VerticalContentAlignment = VerticalAlignment.Center;
tb.RenderTransform = AddT(trans, TranslateT(0.25, 0.0, ScaleT(0.005, 0.005, new TransformGroup())));
tb.Text = kvp.Key.ToString();
canvas.Children.Add(tb);
// left child in bottom-left quadrant
l(AddT(trans, TranslateT(0.0, 0.5, ScaleT(0.5, 0.5, new TransformGroup()))));
// right child in bottom-right quadrant
r(AddT(trans, TranslateT(0.5, 0.5, ScaleT(0.5, 0.5, new TransformGroup()))));
return null;
}, _ => null, tree)(new TransformGroup());
}
public MyWPFWindow(Tree<KeyValuePair<int, bool>> tree)
{
var canvas = new Canvas();
canvas.Width=1.0;
canvas.Height=1.0;
canvas.Background = Brushes.Blue;
canvas.LayoutTransform=new ScaleTransform(200.0, 200.0);
Draw(canvas, tree);
this.Content = canvas;
this.Title = "MyWPFWindow";
this.SizeToContent = SizeToContent.WidthAndHeight;
}
TransformGroup AddT(Transform t, TransformGroup tg) { tg.Children.Add(t); return tg; }
TransformGroup ScaleT(double x, double y, TransformGroup tg) { tg.Children.Add(new ScaleTransform(x,y)); return tg; }
TransformGroup TranslateT(double x, double y, TransformGroup tg) { tg.Children.Add(new TranslateTransform(x,y)); return tg; }
[STAThread]
static void Main(string[] args)
{
var app = new Application();
//app.Run(new MyWPFWindow(Tree.DiffTree(Tree.Tree7,Example.Change5to0(Tree.Tree7))));
app.Run(new MyWPFWindow(Tree.DiffTree(Tree.Tree7, Example.XChange5to0(Tree.Tree7))));
}
}
```
|
196,302 |
<p>Since I keep showing up late for answering questions tagged php where i actually know the answer i figured i'd try asking a question myself.</p>
<p>I've been working on so many complete rewrites of a custom template engine in php for so long and so many times that i thought i'd ask for opinions.</p>
<p>In short, this is the most important part i have implemented so far:</p>
<ol>
<li>Any http request is routed to handler.php</li>
<li>based on the requested URL a controller is instantiated and a method on that controller is called.</li>
<li>The controller method must return an <code>IView</code> compatible class instance ( <code>IView</code> defines a <code>Render()</code> method)
<ol>
<li>The template engine does some xpath for every namespace that ends in 'serverside' <code>sprintf('//%s:*[@runat="server"]', $namespaceprefix )</code></li>
<li>For every found tag, it looks up the php class identified by <code>$tag.localName</code> and instantiates one and attaches it to the original template.</li>
<li>Once attached, the original template node is fed to the 'ServerTag' so it can initialize properly</li>
<li>the fully complete IView compatible instance is assigned to a temporary variable in the controller method. </li>
</ol></li>
<li>The controller asks pushes data from a Model class to the view which does some nifty xpath DOM replacement.</li>
<li>The controller returns the completely filled view to <code>main()</code>the handler, which renders it.</li>
</ol>
<p>I am basing my template on xml. a simple template currently looks like:</p>
<pre><code><html xmlns="http://www.w3.org/1999/xhtml"
xmlns:red="http://www.theredhead.nl/serverside">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Title will be filed by the View depending on the Controller</title>
<link rel="stylesheet" type="text/css" href="/Stylesheet/Get/Main/" />
</head>
<body>
<!-- the entire body may be reset by the view using it, using XPath and DOM functions -->
<!-- Usually the PageHeader and PageFooter would be put back after clearing the body -->
<div id="PageHeader">
<img src="/Image/Get/theredhead_dot_nl.png" alt="Site Logo" />
</div>
<h1>www.theredhead.nl :: Test Template</h1>
<p>
Lorum ipsum dolar sit amet. blah blah blah yackadee schmackadee.
</p>
<div id="PageFooter">
Built by
<br />
<red:UserProfileLink runat="server" Username="kris" />
</div>
</body>
</html>
</code></pre>
<p>At current, this outputs (including the broken indentation):</p>
<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:red="http://www.theredhead.nl/serverside">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Welcome to my site</title>
<link rel="stylesheet" type="text/css" href="/Stylesheet/Get/Main/"/>
<link rel="stylesheet" type="text/css" href="/Stylesheet/Get/Custom/"/>
<link rel="stylesheet" type="text/css" href="/Stylesheet/Get/Profile/"/>
</head>
<body>
<!-- the entire body may be reset by the view using it, using XPath and DOM functions -->
<!-- Usually the PageHeader and PageFooter would be put back after clearing the body -->
<div id="PageHeader">
<img src="/Image/Get/theredhead_dot_nl.png" alt="Site Logo"/>
</div>
<h1>www.theredhead.nl :: ModelViewController</h1>
<p>
Lorum ipsum dolar sit amet. blah blah blah yackadee schmackadee.
</p>
<div id="PageFooter">
Built by
<br/>
<div><div xmlns:profile="http://www.theredhead.nl/profile" class="ProfileBadge" style="font-size : .8em;">
<a style="text-decoration : none; border: none;" href="/Profile/View/kris">
<img style="float : left;" src="http://www.gravatar.com/avatar/5beeab66d6fe021cbd4daa041330cc86?d=identicon&amp;s=32&amp;r=pg" alt="Gravatar"/>
&#xA0;Kris
</a>
<br/>
<small>
&#xA0;Rep:&#xA0;1
</small>
</div></div>
</div>
</body>
</html>
</code></pre>
<ul>
<li>I've only touched on the tip of the iceberg here and yes, I will be stripping unused xmlns attributes from the output once I'm happy with the functionality</li>
<li>there are currently just over 200 classes in my mvc and core frameworks</li>
<li>I am aware there are existing solutions that can do similar things, but I want to build my own.</li>
</ul>
<p>So the big question is: <strong>Do you have any input on must-have functionality?</strong></p>
<p>P.S. if anyone is interested in the complete source-code, please leave a comment, I will be providing it on my site when I reach reasonable developer usability levels.</p>
|
[
{
"answer_id": 197119,
"author": "SchizoDuckie",
"author_id": 18077,
"author_profile": "https://Stackoverflow.com/users/18077",
"pm_score": 3,
"selected": false,
"text": "<p>Why not just use PHP as your templating system. PHP <em>IS</em> the template system.</p>\n\n<p>What is wrong with just dumping <code><?php=$variable;?></code> in an HTML template? You can use foreach loops, etc.\nJust make sure that you run it from within a scope that cannot access any variables you do not want.</p>\n\n<p>I have a really deep founded hate for overcomplicated template systems like this since my Java/Struts nightmares. You have to dive into namespaces, xpath, custom namespaces and all that stuff before you can change just the one thing you need. </p>\n"
},
{
"answer_id": 197203,
"author": "moo",
"author_id": 23107,
"author_profile": "https://Stackoverflow.com/users/23107",
"pm_score": 1,
"selected": false,
"text": "<p>Here's an article on templating engines: <a href=\"http://massassi.com/php/articles/template_engines/\" rel=\"nofollow noreferrer\">http://massassi.com/php/articles/template_engines/</a></p>\n\n<p>You're doing it wrong.</p>\n"
},
{
"answer_id": 206935,
"author": "Kris",
"author_id": 18565,
"author_profile": "https://Stackoverflow.com/users/18565",
"pm_score": 1,
"selected": false,
"text": "<p>Seems to me only Phil Reif actually read <em>and</em> understood the question and its intention.</p>\n\n<p>Those people claiming php <em>is</em> the template engine and that's that are ignoring too many facts and have blinded themselves from the real world where solid frameworks are important.</p>\n\n<p>So, the points must have features so far (that haven't already been implemented) are:</p>\n\n<ol>\n<li>Lists. I'll be handling those in controls similar to <code><asp:DataGrid></code></li>\n<li>Validation. Will be handled with validation controls. Regular expressions, comparisons etc.</li>\n<li>Output is forcibly valid xhtml 1.0, at least until html 5 has sinked in.</li>\n<li>Composite custom controls (based on xml templates instead of code)</li>\n<li>inline php code... I'm considering it, <code><?php ... ?></code> is a valid xml DOMProcessingInstruction node, but the judges are undecided.</li>\n<li>Configurable global exception handling.</li>\n</ol>\n\n<p>I've set the first drafts online so you might take a look and maybe get back to me with some neat ideas.</p>\n\n<p>By the way things look i'll have forms up and running in the next couple days. At the moment it's only a first draft of a design (both code and style wise)</p>\n\n<p>Still hoping for some more input here, what kind of controls do you people use and love? (from any framework/language)</p>\n\n<p>Kris</p>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/196302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18565/"
] |
Since I keep showing up late for answering questions tagged php where i actually know the answer i figured i'd try asking a question myself.
I've been working on so many complete rewrites of a custom template engine in php for so long and so many times that i thought i'd ask for opinions.
In short, this is the most important part i have implemented so far:
1. Any http request is routed to handler.php
2. based on the requested URL a controller is instantiated and a method on that controller is called.
3. The controller method must return an `IView` compatible class instance ( `IView` defines a `Render()` method)
1. The template engine does some xpath for every namespace that ends in 'serverside' `sprintf('//%s:*[@runat="server"]', $namespaceprefix )`
2. For every found tag, it looks up the php class identified by `$tag.localName` and instantiates one and attaches it to the original template.
3. Once attached, the original template node is fed to the 'ServerTag' so it can initialize properly
4. the fully complete IView compatible instance is assigned to a temporary variable in the controller method.
4. The controller asks pushes data from a Model class to the view which does some nifty xpath DOM replacement.
5. The controller returns the completely filled view to `main()`the handler, which renders it.
I am basing my template on xml. a simple template currently looks like:
```
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:red="http://www.theredhead.nl/serverside">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Title will be filed by the View depending on the Controller</title>
<link rel="stylesheet" type="text/css" href="/Stylesheet/Get/Main/" />
</head>
<body>
<!-- the entire body may be reset by the view using it, using XPath and DOM functions -->
<!-- Usually the PageHeader and PageFooter would be put back after clearing the body -->
<div id="PageHeader">
<img src="/Image/Get/theredhead_dot_nl.png" alt="Site Logo" />
</div>
<h1>www.theredhead.nl :: Test Template</h1>
<p>
Lorum ipsum dolar sit amet. blah blah blah yackadee schmackadee.
</p>
<div id="PageFooter">
Built by
<br />
<red:UserProfileLink runat="server" Username="kris" />
</div>
</body>
</html>
```
At current, this outputs (including the broken indentation):
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:red="http://www.theredhead.nl/serverside">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Welcome to my site</title>
<link rel="stylesheet" type="text/css" href="/Stylesheet/Get/Main/"/>
<link rel="stylesheet" type="text/css" href="/Stylesheet/Get/Custom/"/>
<link rel="stylesheet" type="text/css" href="/Stylesheet/Get/Profile/"/>
</head>
<body>
<!-- the entire body may be reset by the view using it, using XPath and DOM functions -->
<!-- Usually the PageHeader and PageFooter would be put back after clearing the body -->
<div id="PageHeader">
<img src="/Image/Get/theredhead_dot_nl.png" alt="Site Logo"/>
</div>
<h1>www.theredhead.nl :: ModelViewController</h1>
<p>
Lorum ipsum dolar sit amet. blah blah blah yackadee schmackadee.
</p>
<div id="PageFooter">
Built by
<br/>
<div><div xmlns:profile="http://www.theredhead.nl/profile" class="ProfileBadge" style="font-size : .8em;">
<a style="text-decoration : none; border: none;" href="/Profile/View/kris">
<img style="float : left;" src="http://www.gravatar.com/avatar/5beeab66d6fe021cbd4daa041330cc86?d=identicon&s=32&r=pg" alt="Gravatar"/>
 Kris
</a>
<br/>
<small>
 Rep: 1
</small>
</div></div>
</div>
</body>
</html>
```
* I've only touched on the tip of the iceberg here and yes, I will be stripping unused xmlns attributes from the output once I'm happy with the functionality
* there are currently just over 200 classes in my mvc and core frameworks
* I am aware there are existing solutions that can do similar things, but I want to build my own.
So the big question is: **Do you have any input on must-have functionality?**
P.S. if anyone is interested in the complete source-code, please leave a comment, I will be providing it on my site when I reach reasonable developer usability levels.
|
Why not just use PHP as your templating system. PHP *IS* the template system.
What is wrong with just dumping `<?php=$variable;?>` in an HTML template? You can use foreach loops, etc.
Just make sure that you run it from within a scope that cannot access any variables you do not want.
I have a really deep founded hate for overcomplicated template systems like this since my Java/Struts nightmares. You have to dive into namespaces, xpath, custom namespaces and all that stuff before you can change just the one thing you need.
|
196,326 |
<p>.NET newbie here... I'd like to make a button in a Windows form that displays a progress or "cooldown" effect. That is, when the button is pressed, it becomes disabled. As some event or timer is progressing, the button shows the progress graphically. When the progress is finished, the graphic completes and the button becomes enabled. Similar effects can be seen in many games.</p>
<p>I'd considered using a combination of the built in Button class, and the GDI+ DrawPath function, but the complexity scales poorly, and I get the nagging feeling that there must be an easier way.</p>
<p>Any ideas? Thanks.</p>
|
[
{
"answer_id": 196330,
"author": "Phil Wright",
"author_id": 6276,
"author_profile": "https://Stackoverflow.com/users/6276",
"pm_score": 1,
"selected": false,
"text": "<p>The easiest approach is to create an instance of the progress bar control and then you do not need to perform any custom coding/custom painting. If you really need to display everything inside the button control then you have two options. You can keep changing the Image property of the button or go the whole hog and perform custom painting of the button. Custom painting is pretty simple as you only need to draw Text plus whatever image you want.</p>\n"
},
{
"answer_id": 196335,
"author": "Fry",
"author_id": 23553,
"author_profile": "https://Stackoverflow.com/users/23553",
"pm_score": 1,
"selected": true,
"text": "<p>If you really need to have it on the button, I'd go with a custom paint event.</p>\n\n<p>something similar to:</p>\n\n<pre><code>button += new buttonPaintEvent(buttonPaintEventHandlerMethod);\n</code></pre>\n"
},
{
"answer_id": 196349,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 1,
"selected": false,
"text": "<p>Another easy way might be to have two controls, a button and a progress bar that occupy the same space on the form. When the user presses the button, hide the button and show the progress bar. Update the progress bar as needed until whatever processing is done. Then, hide the progress bar and show the button again.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/196326",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3696/"
] |
.NET newbie here... I'd like to make a button in a Windows form that displays a progress or "cooldown" effect. That is, when the button is pressed, it becomes disabled. As some event or timer is progressing, the button shows the progress graphically. When the progress is finished, the graphic completes and the button becomes enabled. Similar effects can be seen in many games.
I'd considered using a combination of the built in Button class, and the GDI+ DrawPath function, but the complexity scales poorly, and I get the nagging feeling that there must be an easier way.
Any ideas? Thanks.
|
If you really need to have it on the button, I'd go with a custom paint event.
something similar to:
```
button += new buttonPaintEvent(buttonPaintEventHandlerMethod);
```
|
196,345 |
<p>I want to I check whether a string is in ASCII or not.</p>
<p>I am aware of <code>ord()</code>, however when I try <code>ord('é')</code>, I have <code>TypeError: ord() expected a character, but string of length 2 found</code>. I understood it is caused by the way I built Python (as explained in <a href="http://docs.python.org/library/functions.html#ord" rel="noreferrer"><code>ord()</code>'s documentation</a>). </p>
<p>Is there another way to check?</p>
|
[
{
"answer_id": 196360,
"author": "Steve Moyer",
"author_id": 17008,
"author_profile": "https://Stackoverflow.com/users/17008",
"pm_score": 2,
"selected": false,
"text": "<p>You could use the regular expression library which accepts the Posix standard [[:ASCII:]] definition.</p>\n"
},
{
"answer_id": 196391,
"author": "Vincent Marchetti",
"author_id": 8935,
"author_profile": "https://Stackoverflow.com/users/8935",
"pm_score": 8,
"selected": false,
"text": "<p>I think you are not asking the right question--</p>\n\n<p>A string in python has no property corresponding to 'ascii', utf-8, or any other encoding. The source of your string (whether you read it from a file, input from a keyboard, etc.) may have encoded a unicode string in ascii to produce your string, but that's where you need to go for an answer.</p>\n\n<p>Perhaps the question you can ask is: \"Is this string the result of encoding a unicode string in ascii?\" -- This you can answer\n by trying:</p>\n\n<pre><code>try:\n mystring.decode('ascii')\nexcept UnicodeDecodeError:\n print \"it was not a ascii-encoded unicode string\"\nelse:\n print \"It may have been an ascii-encoded unicode string\"\n</code></pre>\n"
},
{
"answer_id": 196392,
"author": "Alexander Kojevnikov",
"author_id": 712,
"author_profile": "https://Stackoverflow.com/users/712",
"pm_score": 9,
"selected": true,
"text": "<pre><code>def is_ascii(s):\n return all(ord(c) < 128 for c in s)\n</code></pre>\n"
},
{
"answer_id": 198205,
"author": "miya",
"author_id": 293,
"author_profile": "https://Stackoverflow.com/users/293",
"pm_score": 3,
"selected": false,
"text": "<p>How about doing this?</p>\n\n<pre><code>import string\n\ndef isAscii(s):\n for c in s:\n if c not in string.ascii_letters:\n return False\n return True\n</code></pre>\n"
},
{
"answer_id": 200267,
"author": "Glyph",
"author_id": 13564,
"author_profile": "https://Stackoverflow.com/users/13564",
"pm_score": 4,
"selected": false,
"text": "<p>Your question is incorrect; the error you see is not a result of how you built python, but of a confusion between byte strings and unicode strings.</p>\n\n<p>Byte strings (e.g. \"foo\", or 'bar', in python syntax) are sequences of octets; numbers from 0-255. Unicode strings (e.g. u\"foo\" or u'bar') are sequences of unicode code points; numbers from 0-1112064. But you appear to be interested in the character é, which (in your terminal) is a multi-byte sequence that represents a single character.</p>\n\n<p>Instead of <code>ord(u'é')</code>, try this:</p>\n\n<pre><code>>>> [ord(x) for x in u'é']\n</code></pre>\n\n<p>That tells you which sequence of code points \"é\" represents. It may give you [233], or it may give you [101, 770].</p>\n\n<p>Instead of <code>chr()</code> to reverse this, there is <code>unichr()</code>:</p>\n\n<pre><code>>>> unichr(233)\nu'\\xe9'\n</code></pre>\n\n<p>This character may actually be represented either a single or multiple unicode \"code points\", which themselves represent either graphemes or characters. It's either \"e with an acute accent (i.e., code point 233)\", or \"e\" (code point 101), followed by \"an acute accent on the previous character\" (code point 770). So this exact same character may be presented as the Python data structure <code>u'e\\u0301'</code> or <code>u'\\u00e9'</code>.</p>\n\n<p>Most of the time you shouldn't have to care about this, but it can become an issue if you are iterating over a unicode string, as iteration works by code point, not by decomposable character. In other words, <code>len(u'e\\u0301') == 2</code> and <code>len(u'\\u00e9') == 1</code>. If this matters to you, you can convert between composed and decomposed forms by using <a href=\"http://docs.python.org/library/unicodedata.html#unicodedata.normalize\" rel=\"noreferrer\"><code>unicodedata.normalize</code></a>.</p>\n\n<p><a href=\"http://unicode.org/glossary/\" rel=\"noreferrer\">The Unicode Glossary</a> can be a helpful guide to understanding some of these issues, by pointing how how each specific term refers to a different part of the representation of text, which is far more complicated than many programmers realize.</p>\n"
},
{
"answer_id": 200311,
"author": "JacquesB",
"author_id": 7488,
"author_profile": "https://Stackoverflow.com/users/7488",
"pm_score": 2,
"selected": false,
"text": "<p>A sting (<code>str</code>-type) in Python is a series of bytes. There is <strong>no way</strong> of telling just from looking at the string whether this series of bytes represent an ascii string, a string in a 8-bit charset like ISO-8859-1 or a string encoded with UTF-8 or UTF-16 or whatever.</p>\n\n<p>However if you know the encoding used, then you can <code>decode</code> the str into a unicode string and then use a regular expression (or a loop) to check if it contains characters outside of the range you are concerned about.</p>\n"
},
{
"answer_id": 3296808,
"author": "mvknowles",
"author_id": 397587,
"author_profile": "https://Stackoverflow.com/users/397587",
"pm_score": -1,
"selected": false,
"text": "<p>I use the following to determine if the string is ascii or unicode:</p>\n\n<pre><code>>> print 'test string'.__class__.__name__\nstr\n>>> print u'test string'.__class__.__name__\nunicode\n>>> \n</code></pre>\n\n<p>Then just use a conditional block to define the function:</p>\n\n<pre><code>def is_ascii(input):\n if input.__class__.__name__ == \"str\":\n return True\n return False\n</code></pre>\n"
},
{
"answer_id": 6988354,
"author": "Alvin",
"author_id": 141686,
"author_profile": "https://Stackoverflow.com/users/141686",
"pm_score": 4,
"selected": false,
"text": "<p>Ran into something like this recently - for future reference</p>\n\n<pre><code>import chardet\n\nencoding = chardet.detect(string)\nif encoding['encoding'] == 'ascii':\n print 'string is in ascii'\n</code></pre>\n\n<p>which you could use with:</p>\n\n<pre><code>string_ascii = string.decode(encoding['encoding']).encode('ascii')\n</code></pre>\n"
},
{
"answer_id": 12064457,
"author": "Max P Magee",
"author_id": 727541,
"author_profile": "https://Stackoverflow.com/users/727541",
"pm_score": 3,
"selected": false,
"text": "<p>I found this question while trying determine how to use/encode/decode a string whose encoding I wasn't sure of (and how to escape/convert special characters in that string).</p>\n\n<p>My first step should have been to check the type of the string- I didn't realize there I could get good data about its formatting from type(s). <a href=\"https://stackoverflow.com/a/4987367/727541\">This answer was very helpful and got to the real root of my issues.</a></p>\n\n<p>If you're getting a rude and persistent</p>\n\n<blockquote>\n <p>UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 263: ordinal not in range(128)</p>\n</blockquote>\n\n<p>particularly when you're ENCODING, make sure you're not trying to unicode() a string that already IS unicode- for some terrible reason, you get ascii codec errors. (See also the <a href=\"http://packages.python.org/kitchen/unicode-frustrations.html\" rel=\"nofollow noreferrer\">Python Kitchen recipe</a>, and the <a href=\"http://docs.python.org/howto/unicode.html\" rel=\"nofollow noreferrer\">Python docs</a> tutorials for better understanding of how terrible this can be.)</p>\n\n<p>Eventually I determined that what I wanted to do was this:</p>\n\n<pre><code>escaped_string = unicode(original_string.encode('ascii','xmlcharrefreplace'))\n</code></pre>\n\n<p>Also helpful in debugging was setting the default coding in my file to utf-8 (put this at the beginning of your python file):</p>\n\n<pre><code># -*- coding: utf-8 -*-\n</code></pre>\n\n<p>That allows you to test special characters ('àéç') without having to use their unicode escapes (u'\\xe0\\xe9\\xe7').</p>\n\n<pre><code>>>> specials='àéç'\n>>> specials.decode('latin-1').encode('ascii','xmlcharrefreplace')\n'&#224;&#233;&#231;'\n</code></pre>\n"
},
{
"answer_id": 17516466,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>To prevent your code from crashes, you maybe want to use a <code>try-except</code> to catch <code>TypeErrors</code></p>\n\n<pre><code>>>> ord(\"¶\")\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: ord() expected a character, but string of length 2 found\n</code></pre>\n\n<p>For example </p>\n\n<pre><code>def is_ascii(s):\n try:\n return all(ord(c) < 128 for c in s)\n except TypeError:\n return False\n</code></pre>\n"
},
{
"answer_id": 18403812,
"author": "far",
"author_id": 2044053,
"author_profile": "https://Stackoverflow.com/users/2044053",
"pm_score": 7,
"selected": false,
"text": "<p>In Python 3, we can encode the string as UTF-8, then check whether the length stays the same. If so, then the original string is ASCII.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def isascii(s):\n """Check if the characters in string s are in ASCII, U+0-U+7F."""\n return len(s) == len(s.encode())\n</code></pre>\n<p>To check, pass the test string:</p>\n<pre class=\"lang-py prettyprint-override\"><code>>>> isascii("♥O◘♦♥O◘♦")\nFalse\n>>> isascii("Python")\nTrue\n</code></pre>\n"
},
{
"answer_id": 30392263,
"author": "Sergey Nevmerzhitsky",
"author_id": 3155344,
"author_profile": "https://Stackoverflow.com/users/3155344",
"pm_score": 2,
"selected": false,
"text": "<p>To improve Alexander's solution from the Python 2.6 (and in Python 3.x) you can use helper module curses.ascii and use curses.ascii.isascii() function or various other: <a href=\"https://docs.python.org/2.6/library/curses.ascii.html\" rel=\"nofollow\">https://docs.python.org/2.6/library/curses.ascii.html</a></p>\n\n<pre><code>from curses import ascii\n\ndef isascii(s):\n return all(ascii.isascii(c) for c in s)\n</code></pre>\n"
},
{
"answer_id": 32357552,
"author": "drs",
"author_id": 1484957,
"author_profile": "https://Stackoverflow.com/users/1484957",
"pm_score": 5,
"selected": false,
"text": "<p>Vincent Marchetti has the right idea, but <code>str.decode</code> has been deprecated in Python 3. In Python 3 you can make the same test with <code>str.encode</code>:</p>\n\n<pre><code>try:\n mystring.encode('ascii')\nexcept UnicodeEncodeError:\n pass # string is not ascii\nelse:\n pass # string is ascii\n</code></pre>\n\n<p>Note the exception you want to catch has also changed from <code>UnicodeDecodeError</code> to <code>UnicodeEncodeError</code>.</p>\n"
},
{
"answer_id": 32869248,
"author": "Roger Dahl",
"author_id": 442006,
"author_profile": "https://Stackoverflow.com/users/442006",
"pm_score": 0,
"selected": false,
"text": "<pre><code>import re\n\ndef is_ascii(s):\n return bool(re.match(r'[\\x00-\\x7F]+$', s))\n</code></pre>\n\n<p>To include an empty string as ASCII, change the <code>+</code> to <code>*</code>.</p>\n"
},
{
"answer_id": 40309367,
"author": "hobs",
"author_id": 623735,
"author_profile": "https://Stackoverflow.com/users/623735",
"pm_score": 1,
"selected": false,
"text": "<p>Like @RogerDahl's <a href=\"https://stackoverflow.com/a/32869248/623735\">answer</a> but it's more efficient to short-circuit by negating the character class and using search instead of <code>find_all</code> or <code>match</code>.</p>\n\n<pre><code>>>> import re\n>>> re.search('[^\\x00-\\x7F]', 'Did you catch that \\x00?') is not None\nFalse\n>>> re.search('[^\\x00-\\x7F]', 'Did you catch that \\xFF?') is not None\nTrue\n</code></pre>\n\n<p>I imagine a regular expression is well-optimized for this.</p>\n"
},
{
"answer_id": 51141941,
"author": "Taku",
"author_id": 6622817,
"author_profile": "https://Stackoverflow.com/users/6622817",
"pm_score": 7,
"selected": false,
"text": "<h3>New in Python 3.7 (<a href=\"https://bugs.python.org/issue32677\" rel=\"noreferrer\">bpo32677</a>)</h3>\n\n<p>No more tiresome/inefficient ascii checks on strings, new built-in <code>str</code>/<code>bytes</code>/<code>bytearray</code> method - <a href=\"https://docs.python.org/3/library/stdtypes.html#str.isascii\" rel=\"noreferrer\"><code>.isascii()</code></a> will check if the strings is ascii.</p>\n\n<pre><code>print(\"is this ascii?\".isascii())\n# True\n</code></pre>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/196345",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3504/"
] |
I want to I check whether a string is in ASCII or not.
I am aware of `ord()`, however when I try `ord('é')`, I have `TypeError: ord() expected a character, but string of length 2 found`. I understood it is caused by the way I built Python (as explained in [`ord()`'s documentation](http://docs.python.org/library/functions.html#ord)).
Is there another way to check?
|
```
def is_ascii(s):
return all(ord(c) < 128 for c in s)
```
|
196,382 |
<p>I see that the SML/NJ includes a queue structure. I can't figure out how to use it. How do I use the additional libraries provided by SML/NJ?</p>
|
[
{
"answer_id": 224000,
"author": "Vincent Ramdhanie",
"author_id": 27439,
"author_profile": "https://Stackoverflow.com/users/27439",
"pm_score": 1,
"selected": false,
"text": "<p>I don't have a complete answer for you but I could point you in the right direction. You should look up using the compilation manager (CM) which is built in to SML/NJ. You can think of it as Make for SML.</p>\n\n<p>To use a library from the SML/NJ library you then add smlnj-lib.cm to the CM description file of your application. Then you can use the declarations such as Queue from that library.</p>\n\n<p>The smlnj website has some documentation about the <a href=\"http://www.smlnj.org/doc/CM/index.html\" rel=\"nofollow noreferrer\">compilation manager</a>.</p>\n\n<p>Hope this at least points you in the right direction.</p>\n"
},
{
"answer_id": 1070416,
"author": "ephemient",
"author_id": 20713,
"author_profile": "https://Stackoverflow.com/users/20713",
"pm_score": 3,
"selected": true,
"text": "<p>The <a href=\"http://www.smlnj.org/doc/smlnj-lib/Manual/queue.html\" rel=\"nofollow noreferrer\"><code>Queue</code> structure</a> is not specified by SML '97, but it is present in SML/NJ's top-level environment.</p>\n\n<pre>\n$ sml\nStandard ML of New Jersey v110.69 [built: Fri Mar 13 16:02:47 2009]\n- Queue.mkQueue ();\n[autoloading]\n[library $SMLNJ-LIB/Util/smlnj-lib.cm is stable]\n[autoloading done]\nstdIn:1.1-1.17 Warning: type vars not generalized because of\n value restriction are instantiated to dummy types (X1,X2,...)\nval it = - : ?.X1 Queue.queue\n- \n</pre>\n\n<p>You can <code>open</code> a structure. This lets you avoid typing <code>Queue.</code> in front of everything. It's discouraged to do this at the top-level, though, because it pollutes the environment and makes it much less obvious what you're depending on. (Within another structure I'd say it might be acceptable in some situations.)</p>\n\n<pre>\n$ sml\nStandard ML of New Jersey v110.69 [built: Fri Mar 13 16:02:47 2009]\n- open Queue;\n[autoloading]\n[library $SMLNJ-LIB/Util/smlnj-lib.cm is stable]\n[autoloading done]\nopening Queue\n type 'a queue\n exception Dequeue\n val mkQueue : unit -> 'a queue\n val clear : 'a queue -> unit\n val isEmpty : 'a queue -> bool\n val enqueue : 'a queue * 'a -> unit\n val dequeue : 'a queue -> 'a\n val next : 'a queue -> 'a option\n val delete : 'a queue * ('a -> bool) -> unit\n val head : 'a queue -> 'a\n val peek : 'a queue -> 'a option\n val length : 'a queue -> int\n val contents : 'a queue -> 'a list\n val app : ('a -> unit) -> 'a queue -> unit\n val map : ('a -> 'b) -> 'a queue -> 'b queue\n val foldl : ('a * 'b -> 'b) -> 'b -> 'a queue -> 'b\n val foldr : ('a * 'b -> 'b) -> 'b -> 'a queue -> 'b\n- mkQueue ();\nstdIn:3.1-3.11 Warning: type vars not generalized because of\n value restriction are instantiated to dummy types (X1,X2,...)\nval it = - : ?.X1 queue\n- \n</pre>\n"
},
{
"answer_id": 18422301,
"author": "N A",
"author_id": 1415760,
"author_profile": "https://Stackoverflow.com/users/1415760",
"pm_score": 1,
"selected": false,
"text": "<p>If you want to create an integer Queue, use the following code. Replace 'int' with the datatype you want.</p>\n\n<pre><code>val que = Queue.mkqueue(): int Queue.queue\n</code></pre>\n\n<p>Everything else can be found <a href=\"http://www.smlnj.org/doc/smlnj-lib/Manual/queue.html\" rel=\"nofollow\">here.</a></p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/196382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6013/"
] |
I see that the SML/NJ includes a queue structure. I can't figure out how to use it. How do I use the additional libraries provided by SML/NJ?
|
The [`Queue` structure](http://www.smlnj.org/doc/smlnj-lib/Manual/queue.html) is not specified by SML '97, but it is present in SML/NJ's top-level environment.
```
$ sml
Standard ML of New Jersey v110.69 [built: Fri Mar 13 16:02:47 2009]
- Queue.mkQueue ();
[autoloading]
[library $SMLNJ-LIB/Util/smlnj-lib.cm is stable]
[autoloading done]
stdIn:1.1-1.17 Warning: type vars not generalized because of
value restriction are instantiated to dummy types (X1,X2,...)
val it = - : ?.X1 Queue.queue
-
```
You can `open` a structure. This lets you avoid typing `Queue.` in front of everything. It's discouraged to do this at the top-level, though, because it pollutes the environment and makes it much less obvious what you're depending on. (Within another structure I'd say it might be acceptable in some situations.)
```
$ sml
Standard ML of New Jersey v110.69 [built: Fri Mar 13 16:02:47 2009]
- open Queue;
[autoloading]
[library $SMLNJ-LIB/Util/smlnj-lib.cm is stable]
[autoloading done]
opening Queue
type 'a queue
exception Dequeue
val mkQueue : unit -> 'a queue
val clear : 'a queue -> unit
val isEmpty : 'a queue -> bool
val enqueue : 'a queue * 'a -> unit
val dequeue : 'a queue -> 'a
val next : 'a queue -> 'a option
val delete : 'a queue * ('a -> bool) -> unit
val head : 'a queue -> 'a
val peek : 'a queue -> 'a option
val length : 'a queue -> int
val contents : 'a queue -> 'a list
val app : ('a -> unit) -> 'a queue -> unit
val map : ('a -> 'b) -> 'a queue -> 'b queue
val foldl : ('a * 'b -> 'b) -> 'b -> 'a queue -> 'b
val foldr : ('a * 'b -> 'b) -> 'b -> 'a queue -> 'b
- mkQueue ();
stdIn:3.1-3.11 Warning: type vars not generalized because of
value restriction are instantiated to dummy types (X1,X2,...)
val it = - : ?.X1 queue
-
```
|
196,407 |
<p>From within a DLL that's being called by a C#.NET web app, how do you find the base url of the web app?</p>
|
[
{
"answer_id": 196414,
"author": "TheSmurf",
"author_id": 1975282,
"author_profile": "https://Stackoverflow.com/users/1975282",
"pm_score": 0,
"selected": false,
"text": "<p>You can use Assembly.GetExecutingAssembly() to get the assembly object for the DLL.</p>\n\n<p>Then, call Server.MapPath, passing in the FullPath of that Assembly to get the local, rooted path.</p>\n"
},
{
"answer_id": 196464,
"author": "Alexander Kojevnikov",
"author_id": 712,
"author_profile": "https://Stackoverflow.com/users/712",
"pm_score": 5,
"selected": true,
"text": "<p>Will this work?</p>\n\n<pre><code>HttpContext.Current.Request.Url\n</code></pre>\n\n<p>UPDATE:</p>\n\n<p>To get the base URL you can use:</p>\n\n<pre><code>HttpContext.Current.Request.Url.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped)\n</code></pre>\n"
},
{
"answer_id": 196473,
"author": "Guy",
"author_id": 1463,
"author_profile": "https://Stackoverflow.com/users/1463",
"pm_score": 0,
"selected": false,
"text": "<p>I've come up with this although I'm not sure if it's the best solution:</p>\n\n<pre><code>string _baseUrl = String.Empty;\nHttpContext httpContext = HttpContext.Current;\nif (httpContext != null)\n{\n _baseURL = \"http://\" + HttpContext.Current.Request.Url.Host;\n if (!HttpContext.Current.Request.Url.IsDefaultPort)\n {\n _baseURL += \":\" + HttpContext.Current.Request.Url.Port;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 198126,
"author": "Pablo",
"author_id": 22696,
"author_profile": "https://Stackoverflow.com/users/22696",
"pm_score": 1,
"selected": false,
"text": "<p>If it's an assembly that might be referenced by non-web projects then you might want to avoid using the System.Web namespace. </p>\n\n<p>I would use DannySmurf's method.</p>\n"
},
{
"answer_id": 303631,
"author": "netadictos",
"author_id": 31791,
"author_profile": "https://Stackoverflow.com/users/31791",
"pm_score": 1,
"selected": false,
"text": "<p>As Alexander says, you can use HttpContext.Current.Request.Url but if you doesn't want to use the http://:</p>\n\n<pre><code>HttpContext.Current.Request.Url.GetComponents(UriComponents.HostAndPort, UriFormat.Unescaped);\n</code></pre>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/196407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1463/"
] |
From within a DLL that's being called by a C#.NET web app, how do you find the base url of the web app?
|
Will this work?
```
HttpContext.Current.Request.Url
```
UPDATE:
To get the base URL you can use:
```
HttpContext.Current.Request.Url.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped)
```
|
196,415 |
<p>For a current project I am working I need to return an aggregate report based on date ranges. </p>
<p>I have 3 types of reports, yearly, monthly and daily.</p>
<p>To assist in returning this report I need a function that will return all of the sub-ranges of datetimes, within a big range.</p>
<p>So for example if I as for all the daily ranges between '2006-01-01 11:10:00' and '2006-01-05 08:00:00' I would expect the following results.</p>
<pre><code>select *
from dbo.fnGetDateRanges('d', '2006-01-01 11:10:00', '2006-01-05 08:00:00')
2006-01-01 11:10:00.000, 2006-01-02 00:00:00.000
2006-01-02 00:00:00.000, 2006-01-03 00:00:00.000
2006-01-03 00:00:00.000, 2006-01-04 00:00:00.000
2006-01-04 00:00:00.000, 2006-01-05 00:00:00.000
2006-01-05 00:00:00.000, 2006-01-05 08:00:00.000
</code></pre>
<p>For the yearly range of '2006-01-01 11:10:00' to '2009-05-05 08:00:00', I would expect.</p>
<pre><code>select *
from dbo.fnGetDateRanges('y', '2006-01-01 11:10:00', '2009-05-05 08:00:00')
2006-01-01 11:10:00.000, 2007-01-01 00:00:00.000
2007-01-01 00:00:00.000, 2008-01-01 00:00:00.000
2008-01-01 00:00:00.000, 2009-01-01 00:00:00.000
2009-01-01 00:00:00.000, 2009-05-05 08:00:00.000
</code></pre>
<p>How would I implement this function? </p>
|
[
{
"answer_id": 196416,
"author": "Sam Saffron",
"author_id": 17174,
"author_profile": "https://Stackoverflow.com/users/17174",
"pm_score": 3,
"selected": true,
"text": "<p>There are quite a few tricks in here, hope you find it useful</p>\n\n<pre><code>create function dbo.fnGetDateRanges\n(\n @type char(1),\n @start datetime,\n @finish datetime\n)\nreturns @ranges table(start datetime, finish datetime)\nas \nbegin\n\n declare @from datetime \n declare @to datetime \n set @from = @start \n\n if @type = 'd'\n begin \n set @to = dateadd(day, 1,\n convert\n ( datetime,\n cast(DatePart(d,@start) as varchar) + '/' + cast(DatePart(m,@start) as varchar) + '/' + cast(DatePart(yy,@start) as varchar),\n 103\n )\n )\n end\n\n if @type = 'm'\n begin\n set @to = dateadd(month, 1, \n convert\n ( \n datetime,\n '1/' + cast(DatePart(m,@start) as varchar) + '/' + cast(DatePart(yy,@start) as varchar),\n 103\n )\n )\n end \n\n if @type = 'y'\n begin\n set @to = dateadd(year, 1, \n convert\n ( \n datetime,\n '1/1/' + cast(DatePart(yy,@start) as varchar),\n 103\n )\n )\n end \n\n while @to < @finish\n begin \n insert @ranges values (@from, @to)\n set @from = @to \n if @type = 'd'\n set @to = dateadd(day, 1, @to)\n if @type = 'm'\n set @to = dateadd(month, 1, @to)\n if @type = 'y'\n set @to = dateadd(year, 1, @to)\n end\n\n insert @ranges values (@from, @finish)\n\n return \nend\n</code></pre>\n"
},
{
"answer_id": 196731,
"author": "Pittsburgh DBA",
"author_id": 10224,
"author_profile": "https://Stackoverflow.com/users/10224",
"pm_score": 1,
"selected": false,
"text": "<p>If you prefer a set-based solution, use a tactic like the one shown in the following link to produce a range of numeric values from x to y. Then, just join to it with DATEADD() and your own custom limits to create ranges of days, months, quarters, years, or whatever else. I find it helpful to have this range query as a view.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/166321/sql-query-which-returns-a-table-where-each-row-represents-a-date-in-a-given-ran#167618\">Generate Ranges In SQL</a></p>\n"
},
{
"answer_id": 198399,
"author": "gbn",
"author_id": 27535,
"author_profile": "https://Stackoverflow.com/users/27535",
"pm_score": 2,
"selected": false,
"text": "<p>A static number table is useful, single column, say 8000 rows FROM 0 TO 7999</p>\n\n<p>(Not checked)</p>\n\n<pre><code>DECLARE @Start smalldatetime, @End smalldatetime, @Diff int\n\nSELECT @Start = '2006-01-01 11:10:00', @End = '2009-05-05 08:00:00', @diff = DATEDIFF(year,@start,@end)\n\nSELECT\n DATEADD(year,N.Number,@Start)\nFROM\n dbo.Number N\nWHERE\n N.Number <= @diff\n</code></pre>\n"
},
{
"answer_id": 198449,
"author": "StingyJack",
"author_id": 16391,
"author_profile": "https://Stackoverflow.com/users/16391",
"pm_score": 1,
"selected": false,
"text": "<p>From a performance standpoint, you will not want to use a function to generate the date ranges. For each evaluation in the query ( <code>@myDate > dbo.MyFunc()</code> ), the function will have to execute fully. Your best bet is to build static numbers table.</p>\n\n<p>Now on with the numbers tables....</p>\n\n<p>This is a fast way to create a integers table. (Props to Jeff Moden for the Identity Trick)</p>\n\n<pre><code> SELECT TOP 1000000\n IDENTITY(INT,1,1) as N\n INTO dbo.NumbersTable\n FROM Master.dbo.SysColumns \n Master.dbo.SysColumns \n</code></pre>\n\n<p>Less than 2 seconds to populate 1000000 numbers in a table. </p>\n\n<p>Now to address your problem, you will need to use this to build a table of dates. The example below will create a table with the zero hour (12AM) for each day starting from the @startDate</p>\n\n<pre><code>DECLARE @DaysFromStart int\nDECLARE @StartDate datetime\nSET @StartDate = '10/01/2008'\n\nSET @ DaysFromStart = (SELECT (DATEDIFF(dd,@StartDate,GETDATE()) + 1))\n\nCREATE TABLE [dbo].[TableOfDates](\n [fld_date] [datetime] NOT NULL,\n CONSTRAINT [PK_TableOfDates] PRIMARY KEY CLUSTERED \n(\n [fld_date] ASC\n)WITH FILLFACTOR = 99 ON [PRIMARY]\n) ON [PRIMARY]\n\n\nINSERT INTO\n dbo.TableOfDates\nSELECT \n DATEADD(dd,nums.n - @DaysFromStart ,CAST(FLOOR(CAST(GETDATE() as FLOAT)) as DateTime)) as FLD_Date\nFROM #NumbersTable nums\n\nSELECT MIN(FLD_Date) FROM dbo.TableOfDates\nSELECT MAX(FLD_Date) FROM dbo.TableOfDates\n</code></pre>\n\n<p>Now with different combinations of DATEADD/DIFF, you should be able to create the static tables that you will need to do many date range queries efficiently.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/196415",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17174/"
] |
For a current project I am working I need to return an aggregate report based on date ranges.
I have 3 types of reports, yearly, monthly and daily.
To assist in returning this report I need a function that will return all of the sub-ranges of datetimes, within a big range.
So for example if I as for all the daily ranges between '2006-01-01 11:10:00' and '2006-01-05 08:00:00' I would expect the following results.
```
select *
from dbo.fnGetDateRanges('d', '2006-01-01 11:10:00', '2006-01-05 08:00:00')
2006-01-01 11:10:00.000, 2006-01-02 00:00:00.000
2006-01-02 00:00:00.000, 2006-01-03 00:00:00.000
2006-01-03 00:00:00.000, 2006-01-04 00:00:00.000
2006-01-04 00:00:00.000, 2006-01-05 00:00:00.000
2006-01-05 00:00:00.000, 2006-01-05 08:00:00.000
```
For the yearly range of '2006-01-01 11:10:00' to '2009-05-05 08:00:00', I would expect.
```
select *
from dbo.fnGetDateRanges('y', '2006-01-01 11:10:00', '2009-05-05 08:00:00')
2006-01-01 11:10:00.000, 2007-01-01 00:00:00.000
2007-01-01 00:00:00.000, 2008-01-01 00:00:00.000
2008-01-01 00:00:00.000, 2009-01-01 00:00:00.000
2009-01-01 00:00:00.000, 2009-05-05 08:00:00.000
```
How would I implement this function?
|
There are quite a few tricks in here, hope you find it useful
```
create function dbo.fnGetDateRanges
(
@type char(1),
@start datetime,
@finish datetime
)
returns @ranges table(start datetime, finish datetime)
as
begin
declare @from datetime
declare @to datetime
set @from = @start
if @type = 'd'
begin
set @to = dateadd(day, 1,
convert
( datetime,
cast(DatePart(d,@start) as varchar) + '/' + cast(DatePart(m,@start) as varchar) + '/' + cast(DatePart(yy,@start) as varchar),
103
)
)
end
if @type = 'm'
begin
set @to = dateadd(month, 1,
convert
(
datetime,
'1/' + cast(DatePart(m,@start) as varchar) + '/' + cast(DatePart(yy,@start) as varchar),
103
)
)
end
if @type = 'y'
begin
set @to = dateadd(year, 1,
convert
(
datetime,
'1/1/' + cast(DatePart(yy,@start) as varchar),
103
)
)
end
while @to < @finish
begin
insert @ranges values (@from, @to)
set @from = @to
if @type = 'd'
set @to = dateadd(day, 1, @to)
if @type = 'm'
set @to = dateadd(month, 1, @to)
if @type = 'y'
set @to = dateadd(year, 1, @to)
end
insert @ranges values (@from, @finish)
return
end
```
|
196,420 |
<p>Nightly, I need to fill a SQL Server 2005 table from an ODBC source with over 8 million records. Currently I am using an insert statement from linked server with syntax select similar to this:</p>
<pre><code>Insert Into SQLStagingTable from Select * from OpenQuery(ODBCSource, 'Select * from SourceTable')
</code></pre>
<p>This is really inefficient and takes hours to run. I'm in the middle of coding a solution using SqlBulkInsert code similar to the code found in <a href="https://stackoverflow.com/questions/127152/how-to-change-slow-parametrized-inserts-into-fast-bulk-copy-even-from-memory">this question</a>. </p>
<p>The code in that question is first populating a datatable in memory and then passing that datatable to the SqlBulkInserts WriteToServer method. </p>
<p>What should I do if the populated datatable uses more memory than is available on the machine it is running (a server with 16GB of memory in my case)?</p>
<p>I've thought about using the overloaded ODBCDataAdapter <a href="http://msdn.microsoft.com/en-us/library/59wzthcw(VS.80).aspx" rel="nofollow noreferrer">fill</a> method which allows you to fill only the records from x to n (where x is the start index and n is the number of records to fill). However that could turn out to be an even slower solution than what I currently have since it would mean re-running the select statement on the source a number of times.</p>
<p>What should I do? Just populate the whole thing at once and let the OS manage the memory? Should I populate it in chunks? Is there another solution I haven't thought of?</p>
|
[
{
"answer_id": 196433,
"author": "Sam Saffron",
"author_id": 17174,
"author_profile": "https://Stackoverflow.com/users/17174",
"pm_score": 3,
"selected": true,
"text": "<p>The easiest way would be to use ExecuteReader() against your odbc data source and pass the <a href=\"http://msdn.microsoft.com/en-us/library/system.data.idatareader.aspx\" rel=\"nofollow noreferrer\">IDataReader</a> to the <a href=\"http://msdn.microsoft.com/en-us/library/434atets.aspx\" rel=\"nofollow noreferrer\">WriteToServer(IDataReader)</a> overload.</p>\n\n<p>Most data reader implementations will only keep a very small portion of the total results in memory.</p>\n"
},
{
"answer_id": 196543,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 1,
"selected": false,
"text": "<p>SSIS performs well and is very tweakable. In my experience 8 million rows is not out of its league. One of my larger ETLs pulls in 24 million rows a day and does major conversions and dimensional data warehouse manipulations.</p>\n"
},
{
"answer_id": 196577,
"author": "shahkalpesh",
"author_id": 23574,
"author_profile": "https://Stackoverflow.com/users/23574",
"pm_score": 0,
"selected": false,
"text": "<p>If you have indexes on the destination table, you might consider disabling those till the records get inserted?</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/196420",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5458/"
] |
Nightly, I need to fill a SQL Server 2005 table from an ODBC source with over 8 million records. Currently I am using an insert statement from linked server with syntax select similar to this:
```
Insert Into SQLStagingTable from Select * from OpenQuery(ODBCSource, 'Select * from SourceTable')
```
This is really inefficient and takes hours to run. I'm in the middle of coding a solution using SqlBulkInsert code similar to the code found in [this question](https://stackoverflow.com/questions/127152/how-to-change-slow-parametrized-inserts-into-fast-bulk-copy-even-from-memory).
The code in that question is first populating a datatable in memory and then passing that datatable to the SqlBulkInserts WriteToServer method.
What should I do if the populated datatable uses more memory than is available on the machine it is running (a server with 16GB of memory in my case)?
I've thought about using the overloaded ODBCDataAdapter [fill](http://msdn.microsoft.com/en-us/library/59wzthcw(VS.80).aspx) method which allows you to fill only the records from x to n (where x is the start index and n is the number of records to fill). However that could turn out to be an even slower solution than what I currently have since it would mean re-running the select statement on the source a number of times.
What should I do? Just populate the whole thing at once and let the OS manage the memory? Should I populate it in chunks? Is there another solution I haven't thought of?
|
The easiest way would be to use ExecuteReader() against your odbc data source and pass the [IDataReader](http://msdn.microsoft.com/en-us/library/system.data.idatareader.aspx) to the [WriteToServer(IDataReader)](http://msdn.microsoft.com/en-us/library/434atets.aspx) overload.
Most data reader implementations will only keep a very small portion of the total results in memory.
|
196,424 |
<p>Should I be using this method of throwing errors:</p>
<pre><code>if (isset($this->dbfields[$var])) {
return $this->dbfields[$var];
} else {
throw new FieldNotFoundException($var);
}
</code></pre>
<p>or this style:</p>
<pre><code>try {
return $this->dbfields[$var];
} catch (Exception $e) {
throw new FieldNotFoundException($var);
}
</code></pre>
<p>...or something else altogether?</p>
<p><em>quick explanation of the code:</em> <code>$this->dbfields</code> is an array. <code>isset()</code> checks if a variable is set, in this case, whether the array element exists.</p>
|
[
{
"answer_id": 196428,
"author": "Paul Tomblin",
"author_id": 3333,
"author_profile": "https://Stackoverflow.com/users/3333",
"pm_score": 4,
"selected": true,
"text": "<p>The second example is bad. You're taking a lot of overhead to catch an exception when, as you demonstrate, it's just as easy to prevent the exception in the first place. Plus you also assume you know why that exception was thrown - if there was some other exception, like say an out of memory or something, you're reporting it as a \"field not found\" even if it wasn't.</p>\n\n<p>Keep in mind that <code>try</code>/<code>catch</code> in languages like C++ and Java are very expensive because of all the state they have to save and restore. Python, on the other hand, has very cheap exceptions and they positively encourage you to use a <code>try</code>/<code>except</code> for simple validation. But even so, catching everything and pretending it's one type of exception is still bad.</p>\n"
},
{
"answer_id": 196429,
"author": "Mark",
"author_id": 26310,
"author_profile": "https://Stackoverflow.com/users/26310",
"pm_score": 2,
"selected": false,
"text": "<p>Catching \"Exception\" is not, most of the time, considered a good practice, out of the two you displayed, I would use option 1. </p>\n\n<p>Catching all exceptions may hide a different exception and mask it as a FileNotFoundException.</p>\n"
},
{
"answer_id": 196431,
"author": "yfeldblum",
"author_id": 12349,
"author_profile": "https://Stackoverflow.com/users/12349",
"pm_score": 2,
"selected": false,
"text": "<pre><code>//First let's do the checks.\nif(!isset($this->dbfields[$var]))\n throw new FieldNotFoundException($var);\n//Now we're in the clear!\nreturn $this->dbfields[$var];\n</code></pre>\n"
},
{
"answer_id": 196432,
"author": "Lou Franco",
"author_id": 3937,
"author_profile": "https://Stackoverflow.com/users/3937",
"pm_score": 2,
"selected": false,
"text": "<p>I prefer the first one, but if dbfields[$var] throws something reasonable when you access a non-existent element, then I'd prefer just returning it without checking.</p>\n\n<p>I don't particularly like changing the exception type unless I have a good reason -- also if you do, make sure to try to preserve the original exception and stack trace.</p>\n"
},
{
"answer_id": 196434,
"author": "itsmatt",
"author_id": 7862,
"author_profile": "https://Stackoverflow.com/users/7862",
"pm_score": 0,
"selected": false,
"text": "<p>Just re-read your explanation.</p>\n\n<p>I guess your method there in #1 is going to catch any exceptions that might be thrown and simply return a bool. I definitely don't like the catching of the generic exception most of the time, so #2 wouldn't be my choice.</p>\n"
},
{
"answer_id": 196453,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 0,
"selected": false,
"text": "<p>\"...or something else altogether?\"</p>\n\n<p>Neither is very good, so something else would be appropriate.</p>\n\n<p>Fix version 2 to catch the correct exception, not every possible exception. Post that as option 3. I'll upvote something that catches a specific exception instead of <code>Exception</code>.</p>\n"
},
{
"answer_id": 196461,
"author": "Javier",
"author_id": 11649,
"author_profile": "https://Stackoverflow.com/users/11649",
"pm_score": 0,
"selected": false,
"text": "<p>This is far from language-agnostic.</p>\n\n<p>Some languages won't throw errors for accessing non-existant fields, and the preferred pattern depends a lot on the implementations of the arrays, tables, objects, etc.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/196424",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9021/"
] |
Should I be using this method of throwing errors:
```
if (isset($this->dbfields[$var])) {
return $this->dbfields[$var];
} else {
throw new FieldNotFoundException($var);
}
```
or this style:
```
try {
return $this->dbfields[$var];
} catch (Exception $e) {
throw new FieldNotFoundException($var);
}
```
...or something else altogether?
*quick explanation of the code:* `$this->dbfields` is an array. `isset()` checks if a variable is set, in this case, whether the array element exists.
|
The second example is bad. You're taking a lot of overhead to catch an exception when, as you demonstrate, it's just as easy to prevent the exception in the first place. Plus you also assume you know why that exception was thrown - if there was some other exception, like say an out of memory or something, you're reporting it as a "field not found" even if it wasn't.
Keep in mind that `try`/`catch` in languages like C++ and Java are very expensive because of all the state they have to save and restore. Python, on the other hand, has very cheap exceptions and they positively encourage you to use a `try`/`except` for simple validation. But even so, catching everything and pretending it's one type of exception is still bad.
|
196,465 |
<p>The <a href="http://en.wikipedia.org/wiki/Effect_system" rel="noreferrer">Wikipedia article on <em>Effect system</em></a> is currently just a short stub and I've been wondering for a while as to what is an effect system. </p>
<ul>
<li>Are there any languages that have an effect system in addition to a type system? </li>
<li>What would a possible (hypothetical) notation in a <strong>mainstream</strong> language, that you're familiar, with look like with effects? </li>
</ul>
|
[
{
"answer_id": 196489,
"author": "Brian",
"author_id": 19299,
"author_profile": "https://Stackoverflow.com/users/19299",
"pm_score": 3,
"selected": false,
"text": "<p>(This is not an authoritative answer; just trying to trawl my memory.)</p>\n\n<p>In a sense, any time you code a 'state monad' in a language, you're using the type system as a potential effect system. So \"State\" or \"IO\" in Haskell capture this notion (IO captures a whole lot of other effects as well). I vaguely remember reading papers about various languages that use advanced type systems including things like \"dependent types\" to control finer-grained management of effects, so that for instance the type/effect system could capture information about which memory locations would be modified in a given data type. This is useful, as it provides ways to make two functions that modify mutually exclusive bits of state be allowed to \"commute\" (monads don't typically commute, and different monads don't always compose well with one another, which often makes it hard to type (read: assign a static type to) 'reasonable' programs)...</p>\n\n<p>An analogy at a <em>very</em> hand-wavy level is how Java has checked exceptions. You express extra information in the type system about certain effects (you can think of an exception as an 'effect' for the purpose of the analogy), but these 'effects' typically leak out all over your program and don't compose well in practice (you end up with a million 'throws' clauses or else resort to lots of unchecked runtime exception types).</p>\n\n<p>I think a lot of research is being done in this area, both for research-y and mainstream-y languages, as the ability to annotate functions with effect information can unlock the compiler's ability to do a number of optimizations, can impact concurrency, and can do great things for various program analyses and tooling. I don't personally have high hopes for it any time soon, though, as I think lots of smart people have been working on it for a long time and there's still very little to show for it.</p>\n"
},
{
"answer_id": 196748,
"author": "Chris Conway",
"author_id": 1412,
"author_profile": "https://Stackoverflow.com/users/1412",
"pm_score": 5,
"selected": true,
"text": "<p>A \"type and effect system\" describes not only the kinds of values in a program, but the changes in those values. \"Typestate\" checking is a related idea.</p>\n\n<p>An example might be a type system that tracks file handles: instead of having a function <code>close</code> with return type <code>void</code>, the type system would record the <em>effect</em> of <code>close</code> as disposing of the file resource—any attempt to read from or write to the file after calling <code>close</code> would become a type error.</p>\n\n<p>I'm not aware of any type and effect system appearing in a mainstream programming language. They have been used to define static analyses (for example, it's quite natural to define an analysis for proper locking/unlocking in terms of effects). As such, effect systems are usually defined using inference schemes rather than concrete syntax. You could imagine a syntax looking something like</p>\n\n<pre><code>File open(String name) [+File]; // open creates a new file handle\nvoid close(File f) [-f] ; // close destroys f \n</code></pre>\n\n<p>If you want to learn more, the following papers might be interesting (fair warning: the papers are quite theoretical).</p>\n\n<ul>\n<li><a href=\"http://slang.soe.ucsc.edu/cormac/papers/atomic-toplas.pdf\" rel=\"noreferrer\">Types for Atomicity: Static Checking and Inference for Java</a>. Flanagan, Freund, Lipshin, and Qadeer.</li>\n<li><a href=\"http://research.microsoft.com/~maf/Papers/pldi01.pdf\" rel=\"noreferrer\">Enforcing High-Level Protocols in Low-Level Software</a>. Robert DeLine and Manuel Fändrich.</li>\n<li><a href=\"http://www.cs.ucla.edu/~palsberg/tba/papers/nielson-nielson-csd99.pdf\" rel=\"noreferrer\">Type and Effect Systems</a>. Nielson and Nielson.</li>\n</ul>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/196465",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1659/"
] |
The [Wikipedia article on *Effect system*](http://en.wikipedia.org/wiki/Effect_system) is currently just a short stub and I've been wondering for a while as to what is an effect system.
* Are there any languages that have an effect system in addition to a type system?
* What would a possible (hypothetical) notation in a **mainstream** language, that you're familiar, with look like with effects?
|
A "type and effect system" describes not only the kinds of values in a program, but the changes in those values. "Typestate" checking is a related idea.
An example might be a type system that tracks file handles: instead of having a function `close` with return type `void`, the type system would record the *effect* of `close` as disposing of the file resource—any attempt to read from or write to the file after calling `close` would become a type error.
I'm not aware of any type and effect system appearing in a mainstream programming language. They have been used to define static analyses (for example, it's quite natural to define an analysis for proper locking/unlocking in terms of effects). As such, effect systems are usually defined using inference schemes rather than concrete syntax. You could imagine a syntax looking something like
```
File open(String name) [+File]; // open creates a new file handle
void close(File f) [-f] ; // close destroys f
```
If you want to learn more, the following papers might be interesting (fair warning: the papers are quite theoretical).
* [Types for Atomicity: Static Checking and Inference for Java](http://slang.soe.ucsc.edu/cormac/papers/atomic-toplas.pdf). Flanagan, Freund, Lipshin, and Qadeer.
* [Enforcing High-Level Protocols in Low-Level Software](http://research.microsoft.com/~maf/Papers/pldi01.pdf). Robert DeLine and Manuel Fändrich.
* [Type and Effect Systems](http://www.cs.ucla.edu/~palsberg/tba/papers/nielson-nielson-csd99.pdf). Nielson and Nielson.
|
196,468 |
<p>I am using the Maven (2) Cobertura plug-in to create reports on code coverage, and I have the following stub I am using in a method:</p>
<pre><code>try {
System.exit(0);
} catch (final SecurityException exception) {
exception.printStackTrace();
}
System.err.println("The program never exited!");
</code></pre>
<p>I know that I need to log the exception, etc, but that's not the point right now...Cobertura is refusing to acknowledge that the line after the stack trace is printed is covered. That is, the line with the '}' before the <code>System.err.println</code> statement is not being shown as covered. Before, the ending curly brace of the method was not being shown as covered, hence the <code>System.err</code> statement. Any idea how I can convince cobertura's maven plugin that, since the <code>System.err.println</code> statement is covered, that ending brace has to have been covered?</p>
<p>Oh yeah, and I use a mock security manager to throw the security exception, since that's the easiest way I have found of making the test continue executing after the <code>System.exit</code> call.</p>
|
[
{
"answer_id": 196490,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 3,
"selected": false,
"text": "<p>I would look at the coverage report. Double check my tests. Notice that the code really is getting covered and not worry about hitting 100%. Code coverage is best used to find areas that you may have neglected to hit with your tests, but just focusing on getting 100% coverage as a goal is bad habit that can lead to you skipping tests that need to be written just because your tool shows 100%. Use the tool for what it can do but don't fall into the trap of letting the tool define what you do.</p>\n"
},
{
"answer_id": 196493,
"author": "user7116",
"author_id": 7116,
"author_profile": "https://Stackoverflow.com/users/7116",
"pm_score": 2,
"selected": true,
"text": "<p>I haven't used Cobertura in a while (2005?), and saw this behavior back then. A similar problem exists with NCover for C# and curly braces following catch/finally blocks.</p>\n\n<p>My suggestion would be to add to <a href=\"http://sourceforge.net/tracker/index.php?func=detail&aid=1474067&group_id=130558&atid=720015\" rel=\"nofollow noreferrer\">this Cobertura bug report detailing a similar issue</a>. Also, follow @tvanfosson's advice and realize not having coverage on a curly brace, which doesn't actually become anything in the JVM, is something you can ignore as 'noise'.</p>\n"
},
{
"answer_id": 196503,
"author": "ddimitrov",
"author_id": 18187,
"author_profile": "https://Stackoverflow.com/users/18187",
"pm_score": 2,
"selected": false,
"text": "<p>In the Java classfile format every method is annotated with a table mapping code offsets to line numbers. In this case, the closing brace does not produce any bytecode, hence it's not covered. This is an issue of imperfect correspondence between source and bytecode. It should be handled by the coverage tool, recognizing this line as non-code. </p>\n\n<p>I know that <a href=\"http://emma.sourceforge.net/\" rel=\"nofollow noreferrer\">Emma</a> has similar issues. <a href=\"http://www.atlassian.com/software/clover/\" rel=\"nofollow noreferrer\">Clover</a> fares much better, but is commercial (not sure if it would handle this case also). If you use IDEA, you should try their <a href=\"http://www.jetbrains.net/confluence/display/IDEADEV/IDEA+Coverage+Runner\" rel=\"nofollow noreferrer\">new coverage implementation</a> - it's quite good and in active development.</p>\n"
},
{
"answer_id": 16798306,
"author": "Bruno D. Rodrigues",
"author_id": 661475,
"author_profile": "https://Stackoverflow.com/users/661475",
"pm_score": 0,
"selected": false,
"text": "<p>I know this is an old question and that Cobertura has already fixed this, but for completeness the missing coverage on the \"}\" was caused by the internal automatically \"finally\" block.</p>\n\n<p>See your code as this:</p>\n\n<pre><code>try {\n System.exit(0);\n} catch (final SecurityException exception) {\n exception.printStackTrace();\n} finally {\n // noop\n}\n</code></pre>\n\n<p>Fortunately this is no longer happening for some versions.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/196468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8026/"
] |
I am using the Maven (2) Cobertura plug-in to create reports on code coverage, and I have the following stub I am using in a method:
```
try {
System.exit(0);
} catch (final SecurityException exception) {
exception.printStackTrace();
}
System.err.println("The program never exited!");
```
I know that I need to log the exception, etc, but that's not the point right now...Cobertura is refusing to acknowledge that the line after the stack trace is printed is covered. That is, the line with the '}' before the `System.err.println` statement is not being shown as covered. Before, the ending curly brace of the method was not being shown as covered, hence the `System.err` statement. Any idea how I can convince cobertura's maven plugin that, since the `System.err.println` statement is covered, that ending brace has to have been covered?
Oh yeah, and I use a mock security manager to throw the security exception, since that's the easiest way I have found of making the test continue executing after the `System.exit` call.
|
I haven't used Cobertura in a while (2005?), and saw this behavior back then. A similar problem exists with NCover for C# and curly braces following catch/finally blocks.
My suggestion would be to add to [this Cobertura bug report detailing a similar issue](http://sourceforge.net/tracker/index.php?func=detail&aid=1474067&group_id=130558&atid=720015). Also, follow @tvanfosson's advice and realize not having coverage on a curly brace, which doesn't actually become anything in the JVM, is something you can ignore as 'noise'.
|
196,480 |
<p>I have a table with two fields of interest for this particular exercise: a CHAR(3) ID and a DATETIME. The ID identifies the submitter of the data - several thousand rows. The DATETIME is not necessarily unique, either. (The primary keys are other fields of the table.)</p>
<p>Data for this table is submitted every six months. In December, we receive July-December data from each submitter, and in June we receive July-June data. My task is to write a script that identifies people who have only submitted half their data, or only submitted January-June data in June.</p>
<p>...Does anyone have a solution?</p>
|
[
{
"answer_id": 196499,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 1,
"selected": false,
"text": "<p>From your description, I wouldn't worry about the efficiency of the query since apparently it only needs to run twice a year!</p>\n<p>There are a few ways to do this, which one is 'best' depends on the data that you have. The datediff (on max/min date values) you suggested should work, another option is to just count records for each submitted within each date range, e.g.</p>\n<pre><code>select * from (\n select T.submitterId,\n (select count(*) \n from TABLE T1\n where T1.datefield between [july] and [december]\n and T1.submitterId = T.submitterId\n group by T1.submitterId) as JDCount,\n (select count(*)\n from TABLE T2\n where T2.datefield between [december] and [june]\n and T2.submitterId = T.submitterId\n group by T2.submitterId) as DJCount\n from TABLE T) X\nwhere X.JDCount <= 0 OR X.DJCount <= 0\n</code></pre>\n<p>Caveat: untested query off the top of my head; your mileage may vary.</p>\n"
},
{
"answer_id": 203555,
"author": "Margaret",
"author_id": 27290,
"author_profile": "https://Stackoverflow.com/users/27290",
"pm_score": 1,
"selected": false,
"text": "<p>For interest, this is what I wound up using. It was based off Stephen's answer, but with a few adaptations.</p>\n<p>It's part of a larger script that's run every six months, but we're only checking this every twelve months - hence the "If FullYear = 1". I'm sure there's a more stylish way to identify the boundary dates, but this seems to work.</p>\n<pre><code>IF @FullYear = 1 \n BEGIN\n DECLARE @FirstDate AS DATETIME\n DECLARE @LastDayFirstYear AS DATETIME\n DECLARE @SecondYear AS INT\n DECLARE @NewYearsDay AS DATETIME\n DECLARE @LastDate AS DATETIME\n\n SELECT @FirstDate = MIN(dscdate), @LastDate = MAX(dscdate)\n FROM TheTable\n \n SELECT @SecondYear = DATEPART(yyyy, @FirstDate) + 1\n SELECT @NewYearsDay = CAST(CAST(@SecondYear AS VARCHAR) \n + '-01-01' AS DATETIME)\n\n INSERT INTO @AuditResults\n SELECT DISTINCT\n 'Submitter missing Jan-Jun data', t.id\n FROM TheTable t\n WHERE \n EXISTS ( \n SELECT 1\n FROM TheTable t1\n WHERE t.id = t1.id \n AND t1.date >= @FirstDate\n AND t1.date < @NewYearsDay )\n AND NOT EXISTS ( \n SELECT 1\n FROM TheTable t2\n WHERE t2.date >= @NewYearsDay\n AND t2.date <= @LastDate\n AND t2.id = t.id\n GROUP BY t2.id )\n GROUP BY t.id\n END\n</code></pre>\n"
},
{
"answer_id": 555538,
"author": "Margaret",
"author_id": 27290,
"author_profile": "https://Stackoverflow.com/users/27290",
"pm_score": 1,
"selected": true,
"text": "<p>I later realised that I was supposed to check to make sure that there was data for <em>both</em> July to December and January to June. So this is what I wound up in v2:</p>\n\n<pre><code>SELECT @avgmonths = AVG(x.[count])\nFROM ( SELECT CAST(COUNT(DISTINCT DATEPART(month,\n DATEADD(month,\n DATEDIFF(month, 0, dscdate),\n 0))) AS FLOAT) AS [count]\n FROM HospDscDate\n GROUP BY hosp\n ) x\n\nIF @avgmonths > 7 \n SET @months = 12\nELSE \n SET @months = 6\n\n\nSELECT 'Submitter missing data for some months' AS [WarningType],\n t.id\nFROM TheTable t\nWHERE EXISTS ( SELECT 1\n FROM TheTable t1\n WHERE t.id = t1.id\n HAVING COUNT(DISTINCT DATEPART(month,\n DATEADD(month, DATEDIFF(month, 0, t1.Date), 0))) < @months )\nGROUP BY t.id\n</code></pre>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/196480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27290/"
] |
I have a table with two fields of interest for this particular exercise: a CHAR(3) ID and a DATETIME. The ID identifies the submitter of the data - several thousand rows. The DATETIME is not necessarily unique, either. (The primary keys are other fields of the table.)
Data for this table is submitted every six months. In December, we receive July-December data from each submitter, and in June we receive July-June data. My task is to write a script that identifies people who have only submitted half their data, or only submitted January-June data in June.
...Does anyone have a solution?
|
I later realised that I was supposed to check to make sure that there was data for *both* July to December and January to June. So this is what I wound up in v2:
```
SELECT @avgmonths = AVG(x.[count])
FROM ( SELECT CAST(COUNT(DISTINCT DATEPART(month,
DATEADD(month,
DATEDIFF(month, 0, dscdate),
0))) AS FLOAT) AS [count]
FROM HospDscDate
GROUP BY hosp
) x
IF @avgmonths > 7
SET @months = 12
ELSE
SET @months = 6
SELECT 'Submitter missing data for some months' AS [WarningType],
t.id
FROM TheTable t
WHERE EXISTS ( SELECT 1
FROM TheTable t1
WHERE t.id = t1.id
HAVING COUNT(DISTINCT DATEPART(month,
DATEADD(month, DATEDIFF(month, 0, t1.Date), 0))) < @months )
GROUP BY t.id
```
|
196,488 |
<p>Hey all I'm hoping someone has enough experience with Cake PHP to make this work. </p>
<p>I'm working on something that at the moment could affectionately be called a twitter clone. Essentially I have a set up like this. </p>
<p>Users have many friends. This is a many to many relationship to the user table. It is stored in a link tabled called friends_users with columns user_id, friend_id. Users is a table with column user_id. </p>
<p>Then I have a table called tips which associates to a user. A user can have many tips. </p>
<p>I want to figure out a way to do a find on the Tip model that returns all tips owned by the userid i pass in as well as any tips owned by any friends of that user. </p>
<p>This SQL query works perfectly - </p>
<pre><code>SELECT *
FROM `tips`
JOIN users ON users.id = tips.user_id
JOIN friends_users ON tips.user_id = friends_users.friend_id
WHERE (friends_users.user_id =2 or tips.user_id=2)
LIMIT 0 , 30
</code></pre>
<p>That returns user#2s Tips as well as the tips of anyone who is a friend of User 2. </p>
<p>Now how can I do the same thing using <code>$this->Tip->findxxxxx(user_id)</code></p>
<p>I know I can use <code>Tip->query</code> if need be but I'm trying to learn the hard way. </p>
|
[
{
"answer_id": 196496,
"author": "Edward Z. Yang",
"author_id": 23845,
"author_profile": "https://Stackoverflow.com/users/23845",
"pm_score": 0,
"selected": false,
"text": "<p>In CakePHP speak, many to many is \"Has And Belongs To Many\" (HABTM). Assuming you've set up the relations properly, what you then need to do is have a two level recursive find, such that the friend you find on retrieves all of their friends, and those friends get their tips loaded. You may have to dynamically bind/unbind models in order to prevent those friends from getting their friends (although that in practice may not be too much of a problem).</p>\n\n<p>The <a href=\"http://manual.cakephp.org/view/78/Associations-Linking-Models-Together\" rel=\"nofollow noreferrer\">manual entry on associations</a> is a must read.</p>\n"
},
{
"answer_id": 197040,
"author": "neilcrookes",
"author_id": 9968,
"author_profile": "https://Stackoverflow.com/users/9968",
"pm_score": 3,
"selected": true,
"text": "<p>If all you need in the results of the query is a list of tips, I'd be tempted to do this in 2 queries. The first to find a list of user ids of this user and their friends, the second to find the tips that belong to any one of these ids. So, in your Tip model:</p>\n\n<pre><code>function findTipsByUserAndFriends($userId) {\n //FriendsUser is automagically created by CakePHP \"with\" association\n $conditions = array('FriendsUser.user_id'=>$userId);\n $fields = 'FriendsUser.friend_id';\n //get a list friend ids for the given user\n $friendIds = $this->Tip->User->FriendsUser->find('list', compact('conditions', 'fields'));\n //get list of all userIds for whom you want the tips\n $userIds = array($userId) + $friendIds;\n $conditions = array('Tip.user_id'=>$userIds);\n $tips = $this->Tip->find('all', compact('conditions'));\n return $tips;\n}\n</code></pre>\n\n<p>Note that you're calling the first find on the automagically created \"FriendsUser\" model that CakePHP uses to model your HABTM friends_users table, so you don't need to create it.</p>\n\n<p>This is untested, so you might need to debug some of it, but you get the idea.</p>\n"
},
{
"answer_id": 6705344,
"author": "rees",
"author_id": 846203,
"author_profile": "https://Stackoverflow.com/users/846203",
"pm_score": 1,
"selected": false,
"text": "<p>I would recommend that you use containable it works great.</p>\n\n<pre><code>$aCond = array(\n 'fields' => array(\n 'Discount.*'\n ),\n 'contain' => array(\n 'Event' => array(\n 'conditions' => array('Event.id' => $iEventId)\n )\n )\n );\n$aBulkDiscounts = $this->Discount->find('first', $aCond);\n</code></pre>\n\n<p>hope this helps.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/196488",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7018/"
] |
Hey all I'm hoping someone has enough experience with Cake PHP to make this work.
I'm working on something that at the moment could affectionately be called a twitter clone. Essentially I have a set up like this.
Users have many friends. This is a many to many relationship to the user table. It is stored in a link tabled called friends\_users with columns user\_id, friend\_id. Users is a table with column user\_id.
Then I have a table called tips which associates to a user. A user can have many tips.
I want to figure out a way to do a find on the Tip model that returns all tips owned by the userid i pass in as well as any tips owned by any friends of that user.
This SQL query works perfectly -
```
SELECT *
FROM `tips`
JOIN users ON users.id = tips.user_id
JOIN friends_users ON tips.user_id = friends_users.friend_id
WHERE (friends_users.user_id =2 or tips.user_id=2)
LIMIT 0 , 30
```
That returns user#2s Tips as well as the tips of anyone who is a friend of User 2.
Now how can I do the same thing using `$this->Tip->findxxxxx(user_id)`
I know I can use `Tip->query` if need be but I'm trying to learn the hard way.
|
If all you need in the results of the query is a list of tips, I'd be tempted to do this in 2 queries. The first to find a list of user ids of this user and their friends, the second to find the tips that belong to any one of these ids. So, in your Tip model:
```
function findTipsByUserAndFriends($userId) {
//FriendsUser is automagically created by CakePHP "with" association
$conditions = array('FriendsUser.user_id'=>$userId);
$fields = 'FriendsUser.friend_id';
//get a list friend ids for the given user
$friendIds = $this->Tip->User->FriendsUser->find('list', compact('conditions', 'fields'));
//get list of all userIds for whom you want the tips
$userIds = array($userId) + $friendIds;
$conditions = array('Tip.user_id'=>$userIds);
$tips = $this->Tip->find('all', compact('conditions'));
return $tips;
}
```
Note that you're calling the first find on the automagically created "FriendsUser" model that CakePHP uses to model your HABTM friends\_users table, so you don't need to create it.
This is untested, so you might need to debug some of it, but you get the idea.
|
196,498 |
<p>I have a text file in the root of my web app <em><a href="http://localhost/foo.txt" rel="noreferrer">http://localhost/foo.txt</a></em> and I'd like to load it into a variable in javascript.. in groovy I would do this:</p>
<pre><code>def fileContents = 'http://localhost/foo.txt'.toURL().text;
println fileContents;
</code></pre>
<p>How can I get a similar result in javascript?</p>
|
[
{
"answer_id": 196510,
"author": "Edward Z. Yang",
"author_id": 23845,
"author_profile": "https://Stackoverflow.com/users/23845",
"pm_score": 8,
"selected": true,
"text": "<p>XMLHttpRequest, i.e. AJAX, without the XML.</p>\n<p>The precise manner you do this is dependent on what JavaScript framework you're using, but if we disregard interoperability issues, your code will look something like:</p>\n<pre class=\"lang-js prettyprint-override\"><code>var client = new XMLHttpRequest();\nclient.open('GET', '/foo.txt');\nclient.onreadystatechange = function() {\n alert(client.responseText);\n}\nclient.send();\n</code></pre>\n<p>Normally speaking, though, XMLHttpRequest isn't available on all platforms, so some fudgery is done. Once again, your best bet is to use an AJAX framework like jQuery.</p>\n<p>One extra consideration: this will only work as long as foo.txt is on the same domain. If it's on a different domain, same-origin security policies will prevent you from reading the result.</p>\n"
},
{
"answer_id": 196550,
"author": "danb",
"author_id": 2031,
"author_profile": "https://Stackoverflow.com/users/2031",
"pm_score": 7,
"selected": false,
"text": "<p>here is how I did it in jquery:</p>\n\n<pre><code>jQuery.get('http://localhost/foo.txt', function(data) {\n alert(data);\n});\n</code></pre>\n"
},
{
"answer_id": 20724888,
"author": "atmelino",
"author_id": 1502734,
"author_profile": "https://Stackoverflow.com/users/1502734",
"pm_score": 3,
"selected": false,
"text": "<p>One thing to keep in mind is that Javascript runs on the client, and not on the server. You can't really \"load a file\" from the server in Javascript. What happens is that Javascript sends a request to the server, and the server sends back the contents of the requested file. How does Javascript receive the contents? That's what the callback function is for. In Edward's case, that is</p>\n\n<pre><code> client.onreadystatechange = function() {\n</code></pre>\n\n<p>and in danb's case, it is</p>\n\n<pre><code> function(data) {\n</code></pre>\n\n<p>This function is called whenever the data happen to arrive. The jQuery version implicitly uses Ajax, it just makes the coding easier by encapsulating that code in the library.</p>\n"
},
{
"answer_id": 34477256,
"author": "yvesonline",
"author_id": 1278518,
"author_profile": "https://Stackoverflow.com/users/1278518",
"pm_score": 2,
"selected": false,
"text": "<p>When working with jQuery, instead of using <code>jQuery.get</code>, e.g.</p>\n\n<pre><code>jQuery.get(\"foo.txt\", undefined, function(data) {\n alert(data);\n}, \"html\").done(function() {\n alert(\"second success\");\n}).fail(function(jqXHR, textStatus) {\n alert(textStatus);\n}).always(function() {\n alert(\"finished\");\n});\n</code></pre>\n\n<p>you could use <code>.load</code> which gives you a much more condensed form:</p>\n\n<pre><code>$(\"#myelement\").load(\"foo.txt\");\n</code></pre>\n\n<p><code>.load</code> gives you also the option to load partial pages which can come in handy, see <a href=\"http://api.jquery.com/load/\" rel=\"nofollow\">api.jquery.com/load/</a>.</p>\n"
},
{
"answer_id": 39007446,
"author": "Erik Uggeldahl",
"author_id": 2736686,
"author_profile": "https://Stackoverflow.com/users/2736686",
"pm_score": 5,
"selected": false,
"text": "<p>If you only want a constant string from the text file, you could include it as JavaScript:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>// This becomes the content of your foo.txt file\r\nlet text = `\r\nMy test text goes here!\r\n`;</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><script src=\"foo.txt\"></script>\r\n<script>\r\n console.log(text);\r\n</script></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>The string loaded from the file becomes accessible to JavaScript after being loaded. The `(backtick) character begins and ends a <a href=\"https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Template_literals\" rel=\"noreferrer\">template literal</a>, allowing for both \" and ' characters in your text block.</p>\n\n<p>This approach works well when you're attempting to load a file locally, as Chrome will not allow AJAX on URLs with the <code>file://</code> scheme.</p>\n"
},
{
"answer_id": 49673756,
"author": "12Me21",
"author_id": 6232794,
"author_profile": "https://Stackoverflow.com/users/6232794",
"pm_score": 3,
"selected": false,
"text": "<p>This should work in almost all browsers:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>var xhr=new XMLHttpRequest();\nxhr.open(\"GET\",\"https://12Me21.github.io/test.txt\");\nxhr.onload=function(){\n console.log(xhr.responseText);\n}\nxhr.send();\n</code></pre>\n\n<p>Additionally, there's the new <code>Fetch</code> API:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>fetch(\"https://12Me21.github.io/test.txt\")\n.then( response => response.text() )\n.then( text => console.log(text) )\n</code></pre>\n"
},
{
"answer_id": 49680132,
"author": "Vic",
"author_id": 826290,
"author_profile": "https://Stackoverflow.com/users/826290",
"pm_score": 6,
"selected": false,
"text": "<h2>Update 2019: Using Fetch:</h2>\n\n<pre><code>fetch('http://localhost/foo.txt')\n .then(response => response.text())\n .then((data) => {\n console.log(data)\n })\n</code></pre>\n\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API\" rel=\"noreferrer\">https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API</a></p>\n"
},
{
"answer_id": 61195369,
"author": "gman",
"author_id": 128511,
"author_profile": "https://Stackoverflow.com/users/128511",
"pm_score": 4,
"selected": false,
"text": "<h1>Update 2020: Using <a href=\"https://wiki.developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch\" rel=\"noreferrer\">Fetch</a> with async/await</h1>\n\n<pre><code>const response = await fetch('http://localhost/foo.txt');\nconst data = await response.text();\nconsole.log(data);\n</code></pre>\n\n<p>Note that <code>await</code> can only be used in an <code>async</code> function. A longer example might be</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>async function loadFileAndPrintToConsole(url) {\r\n try {\r\n const response = await fetch(url);\r\n const data = await response.text();\r\n console.log(data);\r\n } catch (err) {\r\n console.error(err);\r\n }\r\n}\r\n\r\nloadFileAndPrintToConsole('https://threejsfundamentals.org/LICENSE');</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/196498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2031/"
] |
I have a text file in the root of my web app *<http://localhost/foo.txt>* and I'd like to load it into a variable in javascript.. in groovy I would do this:
```
def fileContents = 'http://localhost/foo.txt'.toURL().text;
println fileContents;
```
How can I get a similar result in javascript?
|
XMLHttpRequest, i.e. AJAX, without the XML.
The precise manner you do this is dependent on what JavaScript framework you're using, but if we disregard interoperability issues, your code will look something like:
```js
var client = new XMLHttpRequest();
client.open('GET', '/foo.txt');
client.onreadystatechange = function() {
alert(client.responseText);
}
client.send();
```
Normally speaking, though, XMLHttpRequest isn't available on all platforms, so some fudgery is done. Once again, your best bet is to use an AJAX framework like jQuery.
One extra consideration: this will only work as long as foo.txt is on the same domain. If it's on a different domain, same-origin security policies will prevent you from reading the result.
|
196,500 |
<p>I have a WordPress installation with an <code>.htaccess</code> file that looks like this:</p>
<pre><code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
</code></pre>
<p>I tried installing a fresh copy of WordPress into a subdirectory for a separate blog and am getting 404 errors within the root WordPress when I try to view it. I'm assuming this is because of the <code>.htaccess</code> file. </p>
<p>How do I change it so that I can view the subfolder?</p>
|
[
{
"answer_id": 196553,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Edit#2</strong>: ok i think i figured this out, but it's pretty messy.</p>\n\n<p>modify your base wordpress install's .htaccess file to look like this:</p>\n\n<pre><code># BEGIN WordPress\n<IfModule mod_rewrite.c>\n RewriteEngine On\n RewriteBase /\n RewriteCond %{REQUEST_URI} !^/blog2/.*\n RewriteCond %{REQUEST_FILENAME} !-f\n RewriteCond %{REQUEST_FILENAME} !-d\n RewriteRule . /index.php [L]\n</IfModule>\n# END WordPress\n</code></pre>\n\n<p>now, load a new copy of wordpress into \"blog2/\", and copy your <code>wp-config.php</code> file over to it. edit the \"/blog2/wp-config.php\" file and change the <code>$table_prefix</code> to something different than your first blog. (this will install both wordpresses into the same database).</p>\n\n<p>once you've done that, you should be able to go to:</p>\n\n<pre><code>http://yourdomain.com/blog2/\n</code></pre>\n\n<p>and finish up the installation without issue. the initial problem was that the new copy of wordpress kept trying to use the first copy's <code>wp-config.php</code> file. moving it over manually fixed that all up.</p>\n\n<p>because i'm insane, i tested this with two fresh copies, wrote a few test articles, and was able to navigate around without issue, so it should work :)</p>\n"
},
{
"answer_id": 8042392,
"author": "Sterling Hamilton",
"author_id": 1034494,
"author_profile": "https://Stackoverflow.com/users/1034494",
"pm_score": 5,
"selected": false,
"text": "<p>For future reference, you may want to try this:</p>\n\n<pre><code># BEGIN WordPress\n<IfModule mod_rewrite.c>\nRewriteEngine On\nRewriteBase /blog2/\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /blog2/index.php [L]\n</IfModule>\n# END WordPress\n</code></pre>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/196500",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12765/"
] |
I have a WordPress installation with an `.htaccess` file that looks like this:
```
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
```
I tried installing a fresh copy of WordPress into a subdirectory for a separate blog and am getting 404 errors within the root WordPress when I try to view it. I'm assuming this is because of the `.htaccess` file.
How do I change it so that I can view the subfolder?
|
For future reference, you may want to try this:
```
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /blog2/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /blog2/index.php [L]
</IfModule>
# END WordPress
```
|
196,505 |
<p>Is there a way to use <strong>THE LOOP</strong> in <strong>Wordpress</strong> to load pages instead of posts?</p>
<p>I would like to be able to query a set of child pages, and then use <strong>THE LOOP</strong> function calls on it - things like <code>the_permalink()</code> and <code>the_title()</code>.</p>
<p>Is there a way to do this? I didn't see anything in <code>query_posts()</code> documentation.</p>
|
[
{
"answer_id": 196742,
"author": "Simon Lehmann",
"author_id": 27011,
"author_profile": "https://Stackoverflow.com/users/27011",
"pm_score": 7,
"selected": true,
"text": "<p>Yes, that's possible. You can create a new WP_Query object. Do something like this:</p>\n\n<pre><code>query_posts(array('showposts' => <number_of_pages_to_show>, 'post_parent' => <ID of the parent page>, 'post_type' => 'page'));\n\nwhile (have_posts()) { the_post();\n /* Do whatever you want to do for every page... */\n}\n\nwp_reset_query(); // Restore global post data\n</code></pre>\n\n<p><strong>Addition</strong>: There are a lot of other parameters that can be used with query_posts. Some, but unfortunately not all, are listed here: <a href=\"http://codex.wordpress.org/Template_Tags/query_posts\" rel=\"noreferrer\">http://codex.wordpress.org/Template_Tags/query_posts</a>. At least <code>post_parent</code> and more important <em><code>post_type</code></em> are not listed there. I dug through the sources of <code>./wp-include/query.php</code> to find out about these.</p>\n"
},
{
"answer_id": 21748630,
"author": "Nathan Dawson",
"author_id": 1310929,
"author_profile": "https://Stackoverflow.com/users/1310929",
"pm_score": 5,
"selected": false,
"text": "<p>Given the age of this question I wanted to provide an updated answer for anyone who stumbles upon it.</p>\n\n<p>I would suggest avoiding query_posts. Here's the alternative I prefer:</p>\n\n<pre><code>$child_pages = new WP_Query( array(\n 'post_type' => 'page', // set the post type to page\n 'posts_per_page' => 10, // number of posts (pages) to show\n 'post_parent' => <ID of the parent page>, // enter the post ID of the parent page\n 'no_found_rows' => true, // no pagination necessary so improve efficiency of loop\n) );\n\nif ( $child_pages->have_posts() ) : while ( $child_pages->have_posts() ) : $child_pages->the_post();\n // Do whatever you want to do for every page. the_title(), the_permalink(), etc...\nendwhile; endif; \n\nwp_reset_postdata();\n</code></pre>\n\n<p>Another alternative would be to use the pre_get_posts filter however this only applies in this case if you need to modify the primary loop. The above example is better when used as a secondary loop.</p>\n\n<p>Further reading: <a href=\"http://codex.wordpress.org/Class_Reference/WP_Query\">http://codex.wordpress.org/Class_Reference/WP_Query</a></p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/196505",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22306/"
] |
Is there a way to use **THE LOOP** in **Wordpress** to load pages instead of posts?
I would like to be able to query a set of child pages, and then use **THE LOOP** function calls on it - things like `the_permalink()` and `the_title()`.
Is there a way to do this? I didn't see anything in `query_posts()` documentation.
|
Yes, that's possible. You can create a new WP\_Query object. Do something like this:
```
query_posts(array('showposts' => <number_of_pages_to_show>, 'post_parent' => <ID of the parent page>, 'post_type' => 'page'));
while (have_posts()) { the_post();
/* Do whatever you want to do for every page... */
}
wp_reset_query(); // Restore global post data
```
**Addition**: There are a lot of other parameters that can be used with query\_posts. Some, but unfortunately not all, are listed here: <http://codex.wordpress.org/Template_Tags/query_posts>. At least `post_parent` and more important *`post_type`* are not listed there. I dug through the sources of `./wp-include/query.php` to find out about these.
|
196,509 |
<p>I want to delete <strong>all</strong> the previously created indices. I am using <code>Lucene.net</code>.</p>
<p>I tried the following:</p>
<pre><code>Term term = new Term(); //empty because I want to delete all the indices
IndexReader rdr = IndexReader.Open(_directory);
rdr.DeleteDocuments(term);
rdr.Close();
</code></pre>
<p>But I get error. Any idea how to go about it?</p>
|
[
{
"answer_id": 229800,
"author": "Jokin",
"author_id": 27369,
"author_profile": "https://Stackoverflow.com/users/27369",
"pm_score": 4,
"selected": false,
"text": "<p>The best way to delete an index is to wipe the filesystem directory. However, if you wan't to regenerate the index, the easiest way is to open a new indexwriter with the create parameter as true. It will start a new index deleting the contents of the existing one. </p>\n"
},
{
"answer_id": 3242491,
"author": "Jeremy Cade",
"author_id": 99240,
"author_profile": "https://Stackoverflow.com/users/99240",
"pm_score": 1,
"selected": false,
"text": "<p>As Jokin said, the easiest was is to delete all of the files within the directory. i.e.;</p>\n\n<pre><code>DirectoryInfo directoryInfo = new DirectoryInfo(@\"IndexLocation\");\nParallel.ForEach(directoryInfo.GetFiles(), file => {\n file.Delete();\n });\n</code></pre>\n"
},
{
"answer_id": 4449046,
"author": "cuh",
"author_id": 292352,
"author_profile": "https://Stackoverflow.com/users/292352",
"pm_score": 1,
"selected": false,
"text": "<p>From the <a href=\"http://lucene.apache.org/lucene.net/docs/2.4.0/\" rel=\"nofollow\">Lucene.Net API Doc</a>:</p>\n\n<blockquote>\n <p><code>public static IndexReader Open(Directory);</code></p>\n \n <p>Expert: Returns a read/write IndexReader reading the index in the given Directory, with a custom IndexDeletionPolicy. NOTE: Starting in 3.0 this will return a <b>readOnly</b> IndexReader. Throws CorruptIndexException if the index is corrupt. Throws IOException if there is a low-level IO error. </p>\n</blockquote>\n\n<p>i guess you should try</p>\n\n<pre><code>IndexReader rdr = IndexReader.Open(_directory, true);\n</code></pre>\n"
},
{
"answer_id": 13509195,
"author": "Mandy",
"author_id": 1839224,
"author_profile": "https://Stackoverflow.com/users/1839224",
"pm_score": 3,
"selected": false,
"text": "<p>although the thread is old i think it's better to give answer.. might be useful for somebody else.\ndeleteAll() method of IndexWriter can be used to delete all documents indexed.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/196509",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I want to delete **all** the previously created indices. I am using `Lucene.net`.
I tried the following:
```
Term term = new Term(); //empty because I want to delete all the indices
IndexReader rdr = IndexReader.Open(_directory);
rdr.DeleteDocuments(term);
rdr.Close();
```
But I get error. Any idea how to go about it?
|
The best way to delete an index is to wipe the filesystem directory. However, if you wan't to regenerate the index, the easiest way is to open a new indexwriter with the create parameter as true. It will start a new index deleting the contents of the existing one.
|
196,518 |
<p>Problem with dynamic controls</p>
<p>Hello all,</p>
<p>I'm wanting to create some dynamic controls, and have them persist their viewstate across page loads. Easy enough, right? All I have to do is re-create the controls upon each page load, using the same IDs. HOWEVER, here's the catch - in my PreRender event, I'm wanting to clear the controls collection, and then recreate the dynamic controls with new values. The reasons for this are complicated, and it would probably take me about a page or so to explain why I want to do it. So, in the interests of brevity, let's just assume that I absolutely must do this, and that there's no other way.</p>
<p>The problem comes in after I re-create the controls in my PreRender event. The re-created controls never bind to the viewstate, and their values do not persist across page loads. I don't understand why this happens. I'm already re-creating the controls in my OnLoad event. When I do this, the newly created controls bind to the ViewState just fine, provided that I use the same IDs every time. However, when I try to do the same thing in the PreRender event, it fails.</p>
<p>In any case, here is my example code : </p>
<p>namespace TestFramework.WebControls
{</p>
<pre><code>public class ValueLinkButton : LinkButton
{
public string Value
{
get
{
return (string)ViewState[ID + "vlbValue"];
}
set
{
ViewState[ID + "vlbValue"] = value;
}
}
}
public class TestControl : WebControl
{
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
Controls.Clear();
ValueLinkButton tempLink = null;
tempLink = new ValueLinkButton();
tempLink.ID = "valueLinkButton";
tempLink.Click += new EventHandler(Value_Click);
if (!Page.IsPostBack)
{
tempLink.Value = "old value";
}
Controls.Add(tempLink);
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
ValueLinkButton tempLink = ((ValueLinkButton)FindControl("valueLinkButton")); //[CASE 1]
//ValueLinkButton tempLink = new ValueLinkButton(); [CASE 2]
tempLink.ID = "valueLinkButton";
tempLink.Value = "new value";
tempLink.Text = "Click";
Controls.Clear();
Controls.Add(tempLink);
}
void Value_Click(object sender, EventArgs e)
{
Page.Response.Write("[" + ((ValueLinkButton)sender).Value + "]");
}
}
</code></pre>
<p>}</p>
<p>So, let's examine case 1, where the line next to [CASE 1] is not commented out, but the line next to [CASE 2] is commented out. Here, everything works just fine. When I put this control on a page and load the page, I see a link that says "Click". When I click the link, the page outputs the text "[new value]", and on the next line, we see the familiar "Click" link. Every subesquent time I click on the "Click" link, we see the same thing. So far, so good.</p>
<p>But now let's examine case 2, where the line next to [CASE 1] is commented out, but the line next to [CASE 2] is not commented out. Here we run into problems. When we load the page, we see the "Click" link. However, when I click on the link, the page outputs the text "[]" instead of "[new value]". The click event is firing normally. However, the "new value" text that I assigned to the Value attribute of the control does not get persisted. Once again, this is a bit of a mystery to me. How come, when I recreate the control in OnLoad, everything's fine and dandy, but when I recreate the control in PreRender, the value doesn't get persisted?</p>
<p>I feel like there simply has to be a way to do this. When I re-create the control in PreRender, is there some way to bind the newly created control to the ViewState?</p>
<p>I've struggled with this for days. Any help that you can give me will be appreciated.</p>
<p>Thanks.</p>
|
[
{
"answer_id": 196532,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>I'm already re-creating the controls in my OnLoad event.</p>\n</blockquote>\n\n<p>That's your problem. OnLoad is too late. Use Init instead.</p>\n"
},
{
"answer_id": 196542,
"author": "user27293",
"author_id": 27293,
"author_profile": "https://Stackoverflow.com/users/27293",
"pm_score": 0,
"selected": false,
"text": "<p>Thank you for your help, but I tried that and it didn't make a difference. Besides, OnLoad works just as well for dynamic controls as OnInit, as long as you give your controls the same IDs every time.</p>\n"
},
{
"answer_id": 196555,
"author": "DocMax",
"author_id": 6234,
"author_profile": "https://Stackoverflow.com/users/6234",
"pm_score": 0,
"selected": false,
"text": "<p>I believe that once you have added the dynamic controls to the page in PageLoad, the ViewState is bound to the controls and the \"ViewState still needs to be bound\" flag (in concept, not an actual flag) is cleared. Then, when you recreate the controls, the existing ViewState is no longer bound.</p>\n\n<p>I faced something similar last year, only in my case I did not <em>want</em> the ViewState to rebind. My issue is that I was <em>not</em> recreating the previous controls, which is why I think that the pseudo-flag notion above applies.</p>\n"
},
{
"answer_id": 196568,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 0,
"selected": false,
"text": "<p>Try calling <code>Page.RegisterRequiresControlState()</code>. You can also use <code>RequiresControlState()</code> to check if it's already been registered.</p>\n"
},
{
"answer_id": 196600,
"author": "Aaron Powell",
"author_id": 11388,
"author_profile": "https://Stackoverflow.com/users/11388",
"pm_score": 2,
"selected": false,
"text": "<p>As others have statement you'll need to ensure that you are creating via the Init method. To learn more about the ASP.NET page life cycle check out this article: <a href=\"http://msdn.microsoft.com/en-us/library/ms178472.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms178472.aspx</a></p>\n"
},
{
"answer_id": 196614,
"author": "Samuel Kim",
"author_id": 437435,
"author_profile": "https://Stackoverflow.com/users/437435",
"pm_score": 0,
"selected": false,
"text": "<p>ViewState works on the Page and its child objects. The new control in [Case 2] has not been added to the Page (or any of its children). In fact, in case of the code above, the object will be out of scope as soon as the OnPreRender method ends and will be garbage collected.</p>\n\n<p>If you absolutely have to swap out the control, you will need to remove the old control from its parent using Remove() method and add the new control at the right place using AddAt().</p>\n\n<p>If the control was the only child of the parent, the code would be something like the following.</p>\n\n<pre><code>ValueLinkButton tempLink = new ValueLinkButton();\nControl parent = FindControl(\"valueLinkButton\").Parent;\nparent.Remove(FindControl(\"valueLinkButton\"));\nparent.AddAt(0, tempLink);\n</code></pre>\n"
},
{
"answer_id": 196963,
"author": "Joe",
"author_id": 13087,
"author_profile": "https://Stackoverflow.com/users/13087",
"pm_score": 5,
"selected": true,
"text": "<p>ViewState-backed properties are only persisted to ViewState if the control is currently tracking ViewState. This is by design to keep ViewState as small as possible: it should only contain data that is truly dynamic. The upshot of this is that:</p>\n\n<p>ViewState propeties set during the Init event are <em>not</em> backed to ViewState (because the Page has not yet started tracking ViewState). Thus Init is a good place to add controls and set (a) properties that won't change between postbacks (ID, CssClass...) as well as initial values for dynamic properties (which can then be modified by code in the rest of the page lifecycle - Load, event handlers, PreRender).</p>\n\n<p>When dynamically adding controls in Load or PreRender, ViewState is being tracked. The developer can then control which propeties are persisted for dynamically added controls as follows:</p>\n\n<ul>\n<li><p>Properties set before the control is added to the page's control tree are not persisted to ViewState. You typically set properties that are not dynamic (ID etc) before adding a control to the control tree.</p></li>\n<li><p>Properties set after the control is added to the page's control tree are persisted to ViewState (ViewState tracking is enabled from before the Load Event to after the PreRender event).</p></li>\n</ul>\n\n<p>In your case, your PreRender handler is setting properties before adding the control to the page's control tree. To get the result you want, set dynamic properties after adding the control to the control tree: \n.</p>\n\n<pre><code>protected override void OnPreRender(EventArgs e)\n{\n base.OnPreRender(e);\n ValueLinkButton tempLink = new ValueLinkButton(); // [CASE 2] \n tempLink.ID = \"valueLinkButton\"; // Not persisted to ViewState\n Controls.Clear();\n Controls.Add(tempLink);\n tempLink.Value = \"new value\"; // Persisted to ViewState\n tempLink.Text = \"Click\"; // Persisted to ViewState\n}\n</code></pre>\n"
},
{
"answer_id": 198813,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Control added before SaveViewState method called in control life cycle should persist their values. I would concur with Joe's answer. Check this image</p>\n\n<p><a href=\"http://emanish.googlepages.com/Asp.Net2.0Lifecycle.PNG\" rel=\"nofollow noreferrer\">http://emanish.googlepages.com/Asp.Net2.0Lifecycle.PNG</a></p>\n"
},
{
"answer_id": 1137559,
"author": "Middletone",
"author_id": 35331,
"author_profile": "https://Stackoverflow.com/users/35331",
"pm_score": 0,
"selected": false,
"text": "<p>I figured out yesterday that you can actually make your app work like normal by loading the control tree right after the loadviewstateevent is fired. if you override the loadviewstate event, call mybase.loadviewstate and then put your own code to regenerate the controls right after it, the values for those controls will be available on page load. In one of my apps I use a viewstate field to hold the ID or the array info that can be used to recreate those controls.</p>\n\n<pre><code>Protected Overrides Sub LoadViewState(ByVal savedState As Object)\n MyBase.LoadViewState(savedState)\n If IsPostBack Then\n CreateMyControls()\n End If\nEnd Sub\n</code></pre>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/196518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27293/"
] |
Problem with dynamic controls
Hello all,
I'm wanting to create some dynamic controls, and have them persist their viewstate across page loads. Easy enough, right? All I have to do is re-create the controls upon each page load, using the same IDs. HOWEVER, here's the catch - in my PreRender event, I'm wanting to clear the controls collection, and then recreate the dynamic controls with new values. The reasons for this are complicated, and it would probably take me about a page or so to explain why I want to do it. So, in the interests of brevity, let's just assume that I absolutely must do this, and that there's no other way.
The problem comes in after I re-create the controls in my PreRender event. The re-created controls never bind to the viewstate, and their values do not persist across page loads. I don't understand why this happens. I'm already re-creating the controls in my OnLoad event. When I do this, the newly created controls bind to the ViewState just fine, provided that I use the same IDs every time. However, when I try to do the same thing in the PreRender event, it fails.
In any case, here is my example code :
namespace TestFramework.WebControls
{
```
public class ValueLinkButton : LinkButton
{
public string Value
{
get
{
return (string)ViewState[ID + "vlbValue"];
}
set
{
ViewState[ID + "vlbValue"] = value;
}
}
}
public class TestControl : WebControl
{
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
Controls.Clear();
ValueLinkButton tempLink = null;
tempLink = new ValueLinkButton();
tempLink.ID = "valueLinkButton";
tempLink.Click += new EventHandler(Value_Click);
if (!Page.IsPostBack)
{
tempLink.Value = "old value";
}
Controls.Add(tempLink);
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
ValueLinkButton tempLink = ((ValueLinkButton)FindControl("valueLinkButton")); //[CASE 1]
//ValueLinkButton tempLink = new ValueLinkButton(); [CASE 2]
tempLink.ID = "valueLinkButton";
tempLink.Value = "new value";
tempLink.Text = "Click";
Controls.Clear();
Controls.Add(tempLink);
}
void Value_Click(object sender, EventArgs e)
{
Page.Response.Write("[" + ((ValueLinkButton)sender).Value + "]");
}
}
```
}
So, let's examine case 1, where the line next to [CASE 1] is not commented out, but the line next to [CASE 2] is commented out. Here, everything works just fine. When I put this control on a page and load the page, I see a link that says "Click". When I click the link, the page outputs the text "[new value]", and on the next line, we see the familiar "Click" link. Every subesquent time I click on the "Click" link, we see the same thing. So far, so good.
But now let's examine case 2, where the line next to [CASE 1] is commented out, but the line next to [CASE 2] is not commented out. Here we run into problems. When we load the page, we see the "Click" link. However, when I click on the link, the page outputs the text "[]" instead of "[new value]". The click event is firing normally. However, the "new value" text that I assigned to the Value attribute of the control does not get persisted. Once again, this is a bit of a mystery to me. How come, when I recreate the control in OnLoad, everything's fine and dandy, but when I recreate the control in PreRender, the value doesn't get persisted?
I feel like there simply has to be a way to do this. When I re-create the control in PreRender, is there some way to bind the newly created control to the ViewState?
I've struggled with this for days. Any help that you can give me will be appreciated.
Thanks.
|
ViewState-backed properties are only persisted to ViewState if the control is currently tracking ViewState. This is by design to keep ViewState as small as possible: it should only contain data that is truly dynamic. The upshot of this is that:
ViewState propeties set during the Init event are *not* backed to ViewState (because the Page has not yet started tracking ViewState). Thus Init is a good place to add controls and set (a) properties that won't change between postbacks (ID, CssClass...) as well as initial values for dynamic properties (which can then be modified by code in the rest of the page lifecycle - Load, event handlers, PreRender).
When dynamically adding controls in Load or PreRender, ViewState is being tracked. The developer can then control which propeties are persisted for dynamically added controls as follows:
* Properties set before the control is added to the page's control tree are not persisted to ViewState. You typically set properties that are not dynamic (ID etc) before adding a control to the control tree.
* Properties set after the control is added to the page's control tree are persisted to ViewState (ViewState tracking is enabled from before the Load Event to after the PreRender event).
In your case, your PreRender handler is setting properties before adding the control to the page's control tree. To get the result you want, set dynamic properties after adding the control to the control tree:
.
```
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
ValueLinkButton tempLink = new ValueLinkButton(); // [CASE 2]
tempLink.ID = "valueLinkButton"; // Not persisted to ViewState
Controls.Clear();
Controls.Add(tempLink);
tempLink.Value = "new value"; // Persisted to ViewState
tempLink.Text = "Click"; // Persisted to ViewState
}
```
|
196,520 |
<p>What's the best/most efficient way to extract text set between parenthesis? Say I wanted to get the string "text" from the string "ignore everything except this (text)" in the most efficient manner possible.</p>
<p>So far, the best I've come up with is this:</p>
<pre><code>$fullString = "ignore everything except this (text)";
$start = strpos('(', $fullString);
$end = strlen($fullString) - strpos(')', $fullString);
$shortString = substr($fullString, $start, $end);
</code></pre>
<p>Is there a better way to do this? I know in general using regex tends to be less efficient, but unless I can reduce the number of function calls, perhaps this would be the best approach? Thoughts?</p>
|
[
{
"answer_id": 196536,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 8,
"selected": true,
"text": "<p>i'd just do a regex and get it over with. unless you are doing enough iterations that it becomes a huge performance issue, it's just easier to code (and understand when you look back on it)</p>\n\n<pre><code>$text = 'ignore everything except this (text)';\npreg_match('#\\((.*?)\\)#', $text, $match);\nprint $match[1];\n</code></pre>\n"
},
{
"answer_id": 196538,
"author": "Edward Z. Yang",
"author_id": 23845,
"author_profile": "https://Stackoverflow.com/users/23845",
"pm_score": 4,
"selected": false,
"text": "<p>So, actually, the code you posted doesn't work: <code>substr()'s</code> parameters are $string, $start and <strong>$length</strong>, and <code>strpos()'s</code> parameters are <code>$haystack</code>, <code>$needle</code>. Slightly modified:</p>\n\n<pre>$str = \"ignore everything except this (text)\";\n$start = strpos($str, '(');\n$end = strpos($str, ')', $start + 1);\n$length = $end - $start;\n$result = substr($str, $start + 1, $length - 1);</pre>\n\n<p>Some subtleties: I used <code>$start + 1</code> in the offset parameter in order to help PHP out while doing the <code>strpos()</code> search on the second parenthesis; we increment <code>$start</code> one and reduce <code>$length</code> to exclude the parentheses from the match.</p>\n\n<p>Also, there's no error checking in this code: you'll want to make sure <code>$start</code> and <code>$end</code> do not === false before performing the <code>substr</code>.</p>\n\n<p>As for using <code>strpos/substr</code> versus regex; performance-wise, this code will beat a regular expression hands down. It's a little wordier though. I eat and breathe <code>strpos/substr</code>, so I don't mind this too much, but someone else may prefer the compactness of a regex.</p>\n"
},
{
"answer_id": 196645,
"author": "Rob",
"author_id": 3542,
"author_profile": "https://Stackoverflow.com/users/3542",
"pm_score": 4,
"selected": false,
"text": "<p>Use a regular expression:</p>\n\n<pre><code>if( preg_match( '!\\(([^\\)]+)\\)!', $text, $match ) )\n $text = $match[1];\n</code></pre>\n"
},
{
"answer_id": 21425624,
"author": "Sachin Murali G",
"author_id": 2653123,
"author_profile": "https://Stackoverflow.com/users/2653123",
"pm_score": 2,
"selected": false,
"text": "<p>This is a sample code to extract all the text between '[' and ']' and store it 2 separate arrays(ie text inside parentheses in one array and text outside parentheses in another array)</p>\n\n<pre><code> function extract_text($string)\n {\n $text_outside=array();\n $text_inside=array();\n $t=\"\";\n for($i=0;$i<strlen($string);$i++)\n {\n if($string[$i]=='[')\n {\n $text_outside[]=$t;\n $t=\"\";\n $t1=\"\";\n $i++;\n while($string[$i]!=']')\n {\n $t1.=$string[$i];\n $i++;\n }\n $text_inside[] = $t1;\n\n }\n else {\n if($string[$i]!=']')\n $t.=$string[$i];\n else {\n continue;\n }\n\n }\n }\n if($t!=\"\")\n $text_outside[]=$t;\n\n var_dump($text_outside);\n echo \"\\n\\n\";\n var_dump($text_inside);\n }\n</code></pre>\n\n<p>Output:\nextract_text(\"hello how are you?\");\nwill produce:</p>\n\n<pre><code>array(1) {\n [0]=>\n string(18) \"hello how are you?\"\n}\n\narray(0) {\n}\n</code></pre>\n\n<p>extract_text(\"hello [http://www.google.com/test.mp3] how are you?\");\nwill produce</p>\n\n<pre><code>array(2) {\n [0]=>\n string(6) \"hello \"\n [1]=>\n string(13) \" how are you?\"\n}\n\n\narray(1) {\n [0]=>\n string(30) \"http://www.google.com/test.mp3\"\n}\n</code></pre>\n"
},
{
"answer_id": 43729786,
"author": "vijay",
"author_id": 3111836,
"author_profile": "https://Stackoverflow.com/users/3111836",
"pm_score": 2,
"selected": false,
"text": "<p>This function may be useful.</p>\n\n<pre><code> public static function getStringBetween($str,$from,$to, $withFromAndTo = false)\n {\n $sub = substr($str, strpos($str,$from)+strlen($from),strlen($str));\n if ($withFromAndTo)\n return $from . substr($sub,0, strrpos($sub,$to)) . $to;\n else\n return substr($sub,0, strrpos($sub,$to));\n }\n $inputString = \"ignore everything except this (text)\";\n $outputString = getStringBetween($inputString, '(', ')'));\n echo $outputString; \n //output will be test\n\n $outputString = getStringBetween($inputString, '(', ')', true));\n echo $outputString; \n //output will be (test)\n</code></pre>\n\n<p>strpos() => which is used to find the position of first occurance in a string.</p>\n\n<p>strrpos() => which is used to find the position of first occurance in a string.</p>\n"
},
{
"answer_id": 55569026,
"author": "Mamed Shahmaliyev",
"author_id": 628176,
"author_profile": "https://Stackoverflow.com/users/628176",
"pm_score": 0,
"selected": false,
"text": "<pre><code>function getStringsBetween($str, $start='[', $end=']', $with_from_to=true){\n$arr = [];\n$last_pos = 0;\n$last_pos = strpos($str, $start, $last_pos);\nwhile ($last_pos !== false) {\n $t = strpos($str, $end, $last_pos);\n $arr[] = ($with_from_to ? $start : '').substr($str, $last_pos + 1, $t - $last_pos - 1).($with_from_to ? $end : '');\n $last_pos = strpos($str, $start, $last_pos+1);\n}\nreturn $arr; }\n</code></pre>\n\n<p>this is a little improvement to the previous answer that will return all patterns in array form:</p>\n\n<p>getStringsBetween('[T]his[] is [test] string [pattern]') will return:</p>\n"
},
{
"answer_id": 56114128,
"author": "Wiktor Stribiżew",
"author_id": 3832970,
"author_profile": "https://Stackoverflow.com/users/3832970",
"pm_score": 2,
"selected": false,
"text": "<p>The already posted regex solutions - <code>\\((.*?)\\)</code> and <code>\\(([^\\)]+)\\)</code> - do not return the <em>innermost</em> strings between an open and close brackets. If a string is <code>Text (abc(xyz 123)</code> they <a href=\"https://regex101.com/r/247sJ2/1\" rel=\"nofollow noreferrer\">both</a> <a href=\"https://regex101.com/r/247sJ2/2\" rel=\"nofollow noreferrer\">return</a> a <code>(abc(xyz 123)</code> as a whole match, and not <code>(xyz 123)</code>.</p>\n\n<p>The pattern that matches substrings (use with <code>preg_match</code> to fetch the first and <code>preg_match_all</code> to fetch all occurrences) in parentheses without other open and close parentheses in between is, if the match should include parentheses:</p>\n\n<pre><code>\\([^()]*\\)\n</code></pre>\n\n<p>Or, you want to get values without parentheses:</p>\n\n<pre><code>\\(([^()]*)\\) // get Group 1 values after a successful call to preg_match_all, see code below\n\\(\\K[^()]*(?=\\)) // this and the one below get the values without parentheses as whole matches \n(?<=\\()[^()]*(?=\\)) // less efficient, not recommended\n</code></pre>\n\n<p>Replace <code>*</code> with <code>+</code> if there must be at least 1 char between <code>(</code> and <code>)</code>.</p>\n\n<p><strong>Details</strong>:</p>\n\n<ul>\n<li><code>\\(</code> - an opening round bracket (must be escaped to denote a literal parenthesis as it is used outside a character class)</li>\n<li><code>[^()]*</code> - <a href=\"http://www.regular-expressions.info/repeat.html\" rel=\"nofollow noreferrer\">zero or more</a> characters other than <code>(</code> and <code>)</code> (note these <code>(</code> and <code>)</code> do not have to be escaped inside a character class as inside it, <code>(</code> and <code>)</code> cannot be used to specify a grouping and are treated as literal parentheses)</li>\n<li><code>\\)</code> - a closing round bracket (must be escaped to denote a literal parenthesis as it is used outside a character class).</li>\n</ul>\n\n<p>The <code>\\(\\K</code> part in an alternative regex matches <code>(</code> and omits from the match value (with the <code>\\K</code> match reset operator). <code>(?<=\\()</code> is a positive lookbehind that requires a <code>(</code> to appear immediately to the left of the current location, but the <code>(</code> is not added to the match value since lookbehind (lookaround) patterns are not consuming. <code>(?=\\()</code> is a positive lookahead that requires a <code>)</code> char to appear immediately to the right of the current location.</p>\n\n<p><a href=\"https://3v4l.org/mBlbR\" rel=\"nofollow noreferrer\">PHP code</a>:</p>\n\n<pre><code>$fullString = 'ignore everything except this (text) and (that (text here))';\nif (preg_match_all('~\\(([^()]*)\\)~', $fullString, $matches)) {\n print_r($matches[0]); // Get whole match values\n print_r($matches[1]); // Get Group 1 values\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>Array ( [0] => (text) [1] => (text here) )\nArray ( [0] => text [1] => text here )\n</code></pre>\n"
},
{
"answer_id": 61134103,
"author": "rüff0",
"author_id": 7092472,
"author_profile": "https://Stackoverflow.com/users/7092472",
"pm_score": 3,
"selected": false,
"text": "<p>i think this is the fastest way to get the words between the first parenthesis in a string.</p>\n\n<pre><code>$string = 'ignore everything except this (text)';\n$string = explode(')', (explode('(', $string)[1]))[0];\necho $string;\n</code></pre>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/196520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5291/"
] |
What's the best/most efficient way to extract text set between parenthesis? Say I wanted to get the string "text" from the string "ignore everything except this (text)" in the most efficient manner possible.
So far, the best I've come up with is this:
```
$fullString = "ignore everything except this (text)";
$start = strpos('(', $fullString);
$end = strlen($fullString) - strpos(')', $fullString);
$shortString = substr($fullString, $start, $end);
```
Is there a better way to do this? I know in general using regex tends to be less efficient, but unless I can reduce the number of function calls, perhaps this would be the best approach? Thoughts?
|
i'd just do a regex and get it over with. unless you are doing enough iterations that it becomes a huge performance issue, it's just easier to code (and understand when you look back on it)
```
$text = 'ignore everything except this (text)';
preg_match('#\((.*?)\)#', $text, $match);
print $match[1];
```
|
196,567 |
<p>I have a mockup layout for something <a href="http://www.mylittlepwnage.com/misc/forms-editor.html" rel="nofollow noreferrer">here</a>. Essentially there are sections, columns and fields, which are all written as a combination of <code><ul></code> and <code><li></code> elements. This is done specifically for later parsing. </p>
<p>A snippet of the HTML:</p>
<pre><code><li class="layout"><span class="type">[Column] </span>
<ul class="layout-children">
<li class="field"><span class="type">[Text] </span>A field</li>
<li class="field"><span class="type">[Text] </span>Another field</li>
<li class="field"><span class="type">[Text] </span>Yet another field</li>
</ul>
</li>
<li class="layout"><span class="type">[Column] </span>
<ul class="layout-children">
<li class="field"><span class="type">[Text] </span>More fields</li>
<li class="field"><span class="type">[Text] </span>And one more field</li>
</ul>
</li>
</code></pre>
<p>If you go to the <a href="http://www.mylittlepwnage.com/misc/forms-editor.html" rel="nofollow noreferrer">linked content</a> you'll note that those columns sit vertically.
I want the columns to sit beside each other, but I am not sure how to go about it.</p>
<p>It would be preferable if the HTML didn't change, just the CSS.</p>
|
[
{
"answer_id": 196571,
"author": "Joe Basirico",
"author_id": 20795,
"author_profile": "https://Stackoverflow.com/users/20795",
"pm_score": 2,
"selected": false,
"text": "<p>In your <code><UL></code> tag use the css attribute \"list-style:none;\" and in the <code><li></code> tag use the css attribute \"display:inline;\" you'll have to play around with the padding and margin to make it look good, but those two attributes will get you on your way. For a better example see my Non-Profit website: <a href=\"http://technicallylearning.org\" rel=\"nofollow noreferrer\">Technically Learning</a></p>\n"
},
{
"answer_id": 196573,
"author": "Dimitry",
"author_id": 27073,
"author_profile": "https://Stackoverflow.com/users/27073",
"pm_score": 0,
"selected": false,
"text": "<p>How about this:</p>\n\n<pre><code>.layout { float: left; width: 50%; margin: 0; border: 0; padding: 0; /* background: transparent */ }\n* html .layout { display: inline } /* IE margin hack */\n.field { clear: both }\n</code></pre>\n"
},
{
"answer_id": 196576,
"author": "lock",
"author_id": 24744,
"author_profile": "https://Stackoverflow.com/users/24744",
"pm_score": 0,
"selected": false,
"text": "<p>yeah using <code>display:block</code> it would be impossible to make them sit beside each other unless if you'd try to specify a width for each of them\nbut if that's the case just use <code>display:inline</code></p>\n"
},
{
"answer_id": 196579,
"author": "Kris",
"author_id": 18565,
"author_profile": "https://Stackoverflow.com/users/18565",
"pm_score": 4,
"selected": true,
"text": "<p>I just added this to your css:</p>\n\n<pre><code>ul .section-children li.layout {\n display : inline-block;\n}\n</code></pre>\n\n<p>Unfortunately, I don't know how well supported inline-block is nowadays.</p>\n"
},
{
"answer_id": 196588,
"author": "eyelidlessness",
"author_id": 17964,
"author_profile": "https://Stackoverflow.com/users/17964",
"pm_score": 3,
"selected": false,
"text": "<pre><code>display: -moz-inline-box;\ndisplay: inline-block;\n*display: inline;\n*zoom: 1;\n</code></pre>\n"
},
{
"answer_id": 196604,
"author": "Elle H",
"author_id": 23666,
"author_profile": "https://Stackoverflow.com/users/23666",
"pm_score": 0,
"selected": false,
"text": "<p>Just an alternative to using inline elements since IE has had a history of padding problems with inline:</p>\n\n<pre><code>.layout-children:after\n{\n content: \"\";\n display: block;\n height: 0px;\n clear: both;\n}\n\n.layout-children .field\n{\n float: left;\n}\n</code></pre>\n"
},
{
"answer_id": 197657,
"author": "Herb Caudill",
"author_id": 239663,
"author_profile": "https://Stackoverflow.com/users/239663",
"pm_score": 0,
"selected": false,
"text": "<p>Using <code>inline</code> or <code>inline-block</code> is going to be nothing but trouble. It's a much better idea to use floats as @Dmitry Z has suggested (but without the margin hack, which isn't necessary).</p>\n"
},
{
"answer_id": 202012,
"author": "Traingamer",
"author_id": 27609,
"author_profile": "https://Stackoverflow.com/users/27609",
"pm_score": 0,
"selected": false,
"text": "<p>A simple float: left will work (with a minor adjustment for the width)</p>\n\n<pre><code>li {\n margin: .5em 1em;\n padding: .1em;\n\n font-family: sans-serif;\n list-style-type: none;\n border: 1px #666 solid;\n float: left;\n}\n#layout-section {\n width: 85%;\n}\n</code></pre>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/196567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1666/"
] |
I have a mockup layout for something [here](http://www.mylittlepwnage.com/misc/forms-editor.html). Essentially there are sections, columns and fields, which are all written as a combination of `<ul>` and `<li>` elements. This is done specifically for later parsing.
A snippet of the HTML:
```
<li class="layout"><span class="type">[Column] </span>
<ul class="layout-children">
<li class="field"><span class="type">[Text] </span>A field</li>
<li class="field"><span class="type">[Text] </span>Another field</li>
<li class="field"><span class="type">[Text] </span>Yet another field</li>
</ul>
</li>
<li class="layout"><span class="type">[Column] </span>
<ul class="layout-children">
<li class="field"><span class="type">[Text] </span>More fields</li>
<li class="field"><span class="type">[Text] </span>And one more field</li>
</ul>
</li>
```
If you go to the [linked content](http://www.mylittlepwnage.com/misc/forms-editor.html) you'll note that those columns sit vertically.
I want the columns to sit beside each other, but I am not sure how to go about it.
It would be preferable if the HTML didn't change, just the CSS.
|
I just added this to your css:
```
ul .section-children li.layout {
display : inline-block;
}
```
Unfortunately, I don't know how well supported inline-block is nowadays.
|
196,585 |
<p>I've got some LINQ to SQL that sometimes throws a </p>
<blockquote>
<p>"Cannot insert duplicate key row in object 'dbo.Table' with unique index
'IX_Indexname'.The statement has been terminated."</p>
</blockquote>
<p>Is there some way I can turn on logging or at least debug into the datacontext to see what sql is being executed at the time that error is raised?</p>
<p><strong>Update:</strong> I should have mentioned I know about the <code>GetChangeSet()</code> method, I was wondering if there is a property on the DataContext that shows the last SQL that was executed, or a property on the sql exception that shows the SQL.</p>
<p>The odd thing about this error is that in the change sets, there is only one update & the only field that's changing is a datetime field that isn't in the index that causing the error.</p>
|
[
{
"answer_id": 196590,
"author": "ChrisHDog",
"author_id": 25719,
"author_profile": "https://Stackoverflow.com/users/25719",
"pm_score": 2,
"selected": false,
"text": "<p>When running into these type issues I've been using the SQL profiler. Basically turning on the profiler, putting a break point on the save/update, clearing the profiler and then running just that statement. From there I have all the SQL that was executed and I can see what was generated. [I've mostly been doing this through DataServices so the .SaveChanges() is a very convenient location to put the breakpoint]</p>\n"
},
{
"answer_id": 196594,
"author": "Aaron Powell",
"author_id": 11388,
"author_profile": "https://Stackoverflow.com/users/11388",
"pm_score": 1,
"selected": false,
"text": "<p>You could use SQL profiler to view the SQL as it's hitting the SQL server.</p>\n\n<p>If you want to see what is actually in the change sets you need to use:</p>\n\n<pre><code>context.GetChangedSet();\n</code></pre>\n\n<p>MSDN - <a href=\"http://msdn.microsoft.com/en-us/library/system.data.linq.datacontext.getchangeset.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.data.linq.datacontext.getchangeset.aspx</a></p>\n\n<p>You can then view each SQL statement before it is sent to the server.</p>\n\n<p>Your last point of call is to use VS 2008's ability to debug through the .NET framework.</p>\n"
},
{
"answer_id": 196607,
"author": "Bradley Grainger",
"author_id": 23633,
"author_profile": "https://Stackoverflow.com/users/23633",
"pm_score": 5,
"selected": true,
"text": "<p>A simple way to do this is to use the <a href=\"http://msdn.microsoft.com/en-us/library/system.data.linq.datacontext.log.aspx\" rel=\"noreferrer\">DataContext.Log</a> property:</p>\n\n<pre><code>using (MyDataContext ctx = new MyDataContext())\n{\n StringWriter sw = new StringWriter();\n ctx.Log = sw;\n\n // execute some LINQ to SQL operations...\n\n string sql = sw.ToString();\n // put a breakpoint here, log it to a file, etc...\n} \n</code></pre>\n"
},
{
"answer_id": 196616,
"author": "yfeldblum",
"author_id": 12349,
"author_profile": "https://Stackoverflow.com/users/12349",
"pm_score": 2,
"selected": false,
"text": "<p>Write a test to isolate the piece or pieces of code causing all the trouble. Set DataContext.Log = Console.Out. Run the test with a testrunner (NUnit, MSTest, etc). The testrunners typically display anything printed to Console.Out along with the test results.</p>\n"
},
{
"answer_id": 329703,
"author": "D3vtr0n",
"author_id": 40899,
"author_profile": "https://Stackoverflow.com/users/40899",
"pm_score": 1,
"selected": false,
"text": "<p>use SQL Profiler. It is your friend and ships with SQL. you can view any SQL statements that are being executed, with complete control over filtering.</p>\n"
},
{
"answer_id": 329719,
"author": "Chatu",
"author_id": 39203,
"author_profile": "https://Stackoverflow.com/users/39203",
"pm_score": 0,
"selected": false,
"text": "<p>I have to agree with Bradley Grainger using the <a href=\"http://msdn.microsoft.com/en-us/library/system.data.linq.datacontext.log.aspx\" rel=\"nofollow noreferrer\">DataContext.Log</a> property is the best way to see the executed sql.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/196585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2975/"
] |
I've got some LINQ to SQL that sometimes throws a
>
> "Cannot insert duplicate key row in object 'dbo.Table' with unique index
> 'IX\_Indexname'.The statement has been terminated."
>
>
>
Is there some way I can turn on logging or at least debug into the datacontext to see what sql is being executed at the time that error is raised?
**Update:** I should have mentioned I know about the `GetChangeSet()` method, I was wondering if there is a property on the DataContext that shows the last SQL that was executed, or a property on the sql exception that shows the SQL.
The odd thing about this error is that in the change sets, there is only one update & the only field that's changing is a datetime field that isn't in the index that causing the error.
|
A simple way to do this is to use the [DataContext.Log](http://msdn.microsoft.com/en-us/library/system.data.linq.datacontext.log.aspx) property:
```
using (MyDataContext ctx = new MyDataContext())
{
StringWriter sw = new StringWriter();
ctx.Log = sw;
// execute some LINQ to SQL operations...
string sql = sw.ToString();
// put a breakpoint here, log it to a file, etc...
}
```
|
196,591 |
<p>I need to pad the output of an integer to a given length.</p>
<p>For example, with a length of 4 digits, the output of the integer 4 is "0004" instead of "4". How can I do this in C# 2.0?</p>
|
[
{
"answer_id": 196599,
"author": "Stephen Wrighton",
"author_id": 7516,
"author_profile": "https://Stackoverflow.com/users/7516",
"pm_score": 6,
"selected": true,
"text": "<p>Use the string.Format command.</p>\n\n<pre><code>output = String.Format(\"{0:0000}\", intVariable); \n</code></pre>\n\n<p>More details: <a href=\"http://msdn.microsoft.com/en-us/library/fht0f5be.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/fht0f5be.aspx</a></p>\n"
},
{
"answer_id": 196605,
"author": "Kris",
"author_id": 18565,
"author_profile": "https://Stackoverflow.com/users/18565",
"pm_score": 2,
"selected": false,
"text": "<p>i think it was: \nintVal.ToString( \"####\" );</p>\n\n<p>but there is some <a href=\"http://msdn.microsoft.com/en-us/library/8wch342y.aspx\" rel=\"nofollow noreferrer\">useful documentation here</a></p>\n"
},
{
"answer_id": 68529323,
"author": "Rob Hoff",
"author_id": 211764,
"author_profile": "https://Stackoverflow.com/users/211764",
"pm_score": 0,
"selected": false,
"text": "<p><strong>In modern .NET 5.0+</strong> (2021 update)</p>\n<pre><code>int myint = 100;\nstring zeroPadded = $"{myint:d8}"; // "00000100"\nstring leftPadded = $"{myint,8}"; // " 100"\nstring rightPadded = $"{myint,-8}"; // "100 "\n</code></pre>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/196591",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20910/"
] |
I need to pad the output of an integer to a given length.
For example, with a length of 4 digits, the output of the integer 4 is "0004" instead of "4". How can I do this in C# 2.0?
|
Use the string.Format command.
```
output = String.Format("{0:0000}", intVariable);
```
More details: <http://msdn.microsoft.com/en-us/library/fht0f5be.aspx>
|
196,603 |
<p>My company has a large application written in VB6, and for historical reasons, the application is navigated with the Enter key instead of with the Tab key. I don't know VB6, but I know that they currently set the focus for each control in a big select statement in the Form's KeyUp event if it's an EnterKey. Now we are starting to convert to .NET, and have to keep things consistent so the users won't have to TAB on some forms and ENTER on others. I want to write ancestor forms that will automatically ENTER from field to field instead of tabbing. A coworker told me that the way it's done in VB6 is to process buttons not on the CLICK event but on the KEYUP event. I need to continue doing this so I won't have leftover KeyUp events to pass back to VB6 after my form is finished. The order of events for buttons is</p>
<ol>
<li>button_PreviewKeyDown </li>
<li>button_Click (apparently replacing the KeyPress event)</li>
<li>form_KeyUp </li>
<li>button_KeyUp</li>
</ol>
<p>I created forms as follows:</p>
<ul>
<li>On the ANCESTOR form's KeyUp event, checks to see if it's an enter key. If it is an enter key, and the active control is not a button, it moves to the next field in tab order. Otherwise it ignores the key and lets the control handle it. If it is a button, the ancestor doesn't presume to know where the button wants control to go, because it will depend on what the button wants to do when it is "clicked".</li>
<li>On the CHILD form's buttons, the click event does nothing, and the processing is duplicated in the KeyUp event and the MouseClick event. </li>
<li>The ANCESTOR form has a protected Boolean, EatKeyUp, that can be set to True by the CHILD. This is used when the child form needs to send a MessageBox, because if the user enters through the OK button on the MessageBox, there is still a leftover KeyUp event that will be consumed by the ancestor form.</li>
</ul>
<p>Although klugey, this actually seems to work. What I want to know is, is there a better way? Perhaps some setting somewhere that I can tell my application "Enter through forms instead of tabbing"? Are the events that I'm using instead of the click events the best ones?</p>
|
[
{
"answer_id": 196599,
"author": "Stephen Wrighton",
"author_id": 7516,
"author_profile": "https://Stackoverflow.com/users/7516",
"pm_score": 6,
"selected": true,
"text": "<p>Use the string.Format command.</p>\n\n<pre><code>output = String.Format(\"{0:0000}\", intVariable); \n</code></pre>\n\n<p>More details: <a href=\"http://msdn.microsoft.com/en-us/library/fht0f5be.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/fht0f5be.aspx</a></p>\n"
},
{
"answer_id": 196605,
"author": "Kris",
"author_id": 18565,
"author_profile": "https://Stackoverflow.com/users/18565",
"pm_score": 2,
"selected": false,
"text": "<p>i think it was: \nintVal.ToString( \"####\" );</p>\n\n<p>but there is some <a href=\"http://msdn.microsoft.com/en-us/library/8wch342y.aspx\" rel=\"nofollow noreferrer\">useful documentation here</a></p>\n"
},
{
"answer_id": 68529323,
"author": "Rob Hoff",
"author_id": 211764,
"author_profile": "https://Stackoverflow.com/users/211764",
"pm_score": 0,
"selected": false,
"text": "<p><strong>In modern .NET 5.0+</strong> (2021 update)</p>\n<pre><code>int myint = 100;\nstring zeroPadded = $"{myint:d8}"; // "00000100"\nstring leftPadded = $"{myint,8}"; // " 100"\nstring rightPadded = $"{myint,-8}"; // "100 "\n</code></pre>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/196603",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12897/"
] |
My company has a large application written in VB6, and for historical reasons, the application is navigated with the Enter key instead of with the Tab key. I don't know VB6, but I know that they currently set the focus for each control in a big select statement in the Form's KeyUp event if it's an EnterKey. Now we are starting to convert to .NET, and have to keep things consistent so the users won't have to TAB on some forms and ENTER on others. I want to write ancestor forms that will automatically ENTER from field to field instead of tabbing. A coworker told me that the way it's done in VB6 is to process buttons not on the CLICK event but on the KEYUP event. I need to continue doing this so I won't have leftover KeyUp events to pass back to VB6 after my form is finished. The order of events for buttons is
1. button\_PreviewKeyDown
2. button\_Click (apparently replacing the KeyPress event)
3. form\_KeyUp
4. button\_KeyUp
I created forms as follows:
* On the ANCESTOR form's KeyUp event, checks to see if it's an enter key. If it is an enter key, and the active control is not a button, it moves to the next field in tab order. Otherwise it ignores the key and lets the control handle it. If it is a button, the ancestor doesn't presume to know where the button wants control to go, because it will depend on what the button wants to do when it is "clicked".
* On the CHILD form's buttons, the click event does nothing, and the processing is duplicated in the KeyUp event and the MouseClick event.
* The ANCESTOR form has a protected Boolean, EatKeyUp, that can be set to True by the CHILD. This is used when the child form needs to send a MessageBox, because if the user enters through the OK button on the MessageBox, there is still a leftover KeyUp event that will be consumed by the ancestor form.
Although klugey, this actually seems to work. What I want to know is, is there a better way? Perhaps some setting somewhere that I can tell my application "Enter through forms instead of tabbing"? Are the events that I'm using instead of the click events the best ones?
|
Use the string.Format command.
```
output = String.Format("{0:0000}", intVariable);
```
More details: <http://msdn.microsoft.com/en-us/library/fht0f5be.aspx>
|
196,610 |
<p>I've been given some code with commenting unlike anything I've come across before:</p>
<pre><code>//{{{ Imports
import imports;
//}}}
</code></pre>
<p>It is the same for each method block, </p>
<pre><code>//{{{ above the code block
//}}} below the code block
</code></pre>
<p>Also see: <a href="http://en.wikipedia.org/wiki/Folding_editor" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Folding_editor</a></p>
|
[
{
"answer_id": 196613,
"author": "Glitch",
"author_id": 324306,
"author_profile": "https://Stackoverflow.com/users/324306",
"pm_score": -1,
"selected": false,
"text": "<p>Maybe it's to emphasize a code block?</p>\n\n<p><em>shrugs</em></p>\n"
},
{
"answer_id": 196620,
"author": "aib",
"author_id": 1088,
"author_profile": "https://Stackoverflow.com/users/1088",
"pm_score": 4,
"selected": true,
"text": "<p>A quick search for <em>\"triple curly\" comment</em> suggests it's \"<a href=\"http://www.emacswiki.org/cgi-bin/wiki/FoldingMode\" rel=\"noreferrer\">Emacs folding mode</a>\".</p>\n\n<p>Or some other code folding marker in any case.</p>\n"
},
{
"answer_id": 196727,
"author": "Matt",
"author_id": 2338,
"author_profile": "https://Stackoverflow.com/users/2338",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://www.jedit.org\" rel=\"nofollow noreferrer\">jEdit</a> uses {{{ and }}} to mark \"explicit\" folds.</p>\n"
},
{
"answer_id": 197010,
"author": "Aleksandar Dimitrov",
"author_id": 11797,
"author_profile": "https://Stackoverflow.com/users/11797",
"pm_score": 1,
"selected": false,
"text": "<p>Actually, Vim uses those triple braces in comments, too.</p>\n\n<p>Tell the one you got the code from, that folding this way is a <a href=\"https://blog.codinghorror.com/the-problem-with-code-folding/\" rel=\"nofollow noreferrer\">bad idea</a>. Vim can set fold points at syntactic folding hints, defined in the highlighting file.</p>\n"
},
{
"answer_id": 198989,
"author": "Scott Stanchfield",
"author_id": 12541,
"author_profile": "https://Stackoverflow.com/users/12541",
"pm_score": 1,
"selected": false,
"text": "<p>It may also be for some code generators. Some generators allow you to edit generated code, and use markers like that so the generator knows where it can regenerate.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/196610",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4857/"
] |
I've been given some code with commenting unlike anything I've come across before:
```
//{{{ Imports
import imports;
//}}}
```
It is the same for each method block,
```
//{{{ above the code block
//}}} below the code block
```
Also see: <http://en.wikipedia.org/wiki/Folding_editor>
|
A quick search for *"triple curly" comment* suggests it's "[Emacs folding mode](http://www.emacswiki.org/cgi-bin/wiki/FoldingMode)".
Or some other code folding marker in any case.
|
196,626 |
<p>I need to do a query that search for a text with <strong>'Nome % teste \ / '</strong> as prefix. I'm doing the query using:</p>
<p><strong>where "name" ILIKE 'Nome a% teste \ /%' ESCAPE 'a'</strong> (using a as escape character).</p>
<p>There is a row that match this, but this query returns nothing. Removing the slash (<strong>'Nome % teste \'</strong>), it works. But I don't see why the <strong>slash</strong> is a problem, since the default escape is a <strong>backslash</strong> and I've changed it to <strong>'a'</strong> in this test.</p>
<p>There is something that I'm missing? (I've consulted TFM)</p>
|
[
{
"answer_id": 196631,
"author": "Adam Pierce",
"author_id": 5324,
"author_profile": "https://Stackoverflow.com/users/5324",
"pm_score": 1,
"selected": false,
"text": "<p>Have you tried just using the backslash to escape it like this:</p>\n\n<pre><code>where \"name\" ILIKE 'Nome \\% teste \\\\\\/';\n</code></pre>\n"
},
{
"answer_id": 196648,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 3,
"selected": true,
"text": "<p>Use the \"ESCAPE\" specifier </p>\n\n<pre><code>WHERE \"name\" ILIKE 'Nome ~% teste \\\\/' ESCAPE '~' \n</code></pre>\n\n<p><a href=\"http://www.postgresql.org/docs/8.2/static/functions-matching.html\" rel=\"nofollow noreferrer\">http://www.postgresql.org/docs/8.2/static/functions-matching.html</a></p>\n\n<p>Note: you still need to have the \\ twice for the string parser. </p>\n\n<p>Without the ESCAPE you would need to do </p>\n\n<pre><code>WHERE \"name\" ILIKE 'Nome \\% test \\\\\\\\/' \n</code></pre>\n\n<p>( 4 \\ 's to represent one literal \\ ) </p>\n\n<hr>\n\n<blockquote>\n <p>Thanks, but I still have the original issue with the slash. Searching with </p>\n\n<pre><code>WHERE \"name\" ILIKE 'Nome \\% test \\\\\\\\/%' \n</code></pre>\n \n <p>don't give me a result, while </p>\n\n<pre><code>WHERE \"name\" ILIKE 'Nome \\% test \\\\\\\\%' \n</code></pre>\n \n <p>(removed the slash, that is present in the row) works as expected. – Kknd </p>\n</blockquote>\n\n<p>its possible your string does not have a literal \"/\" like you specified. you possibly have a null, or other whitespace character inbetween. Or possibly, you have / in a different character set. </p>\n\n<p>I would attempt to use this to test for that possible scenario</p>\n\n<pre><code> WHERE \"name\" ILIKE 'Nome \\% ' AND \"name\" ~* '\\\\.{1,10}/' \n</code></pre>\n\n<p>which will return lines that have / separated by something( but not lines with no separation ) </p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/196626",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18403/"
] |
I need to do a query that search for a text with **'Nome % teste \ / '** as prefix. I'm doing the query using:
**where "name" ILIKE 'Nome a% teste \ /%' ESCAPE 'a'** (using a as escape character).
There is a row that match this, but this query returns nothing. Removing the slash (**'Nome % teste \'**), it works. But I don't see why the **slash** is a problem, since the default escape is a **backslash** and I've changed it to **'a'** in this test.
There is something that I'm missing? (I've consulted TFM)
|
Use the "ESCAPE" specifier
```
WHERE "name" ILIKE 'Nome ~% teste \\/' ESCAPE '~'
```
<http://www.postgresql.org/docs/8.2/static/functions-matching.html>
Note: you still need to have the \ twice for the string parser.
Without the ESCAPE you would need to do
```
WHERE "name" ILIKE 'Nome \% test \\\\/'
```
( 4 \ 's to represent one literal \ )
---
>
> Thanks, but I still have the original issue with the slash. Searching with
>
>
>
> ```
> WHERE "name" ILIKE 'Nome \% test \\\\/%'
>
> ```
>
> don't give me a result, while
>
>
>
> ```
> WHERE "name" ILIKE 'Nome \% test \\\\%'
>
> ```
>
> (removed the slash, that is present in the row) works as expected. – Kknd
>
>
>
its possible your string does not have a literal "/" like you specified. you possibly have a null, or other whitespace character inbetween. Or possibly, you have / in a different character set.
I would attempt to use this to test for that possible scenario
```
WHERE "name" ILIKE 'Nome \% ' AND "name" ~* '\\.{1,10}/'
```
which will return lines that have / separated by something( but not lines with no separation )
|
196,628 |
<p>I have the following problem in my <i>Data Structures and Problem Solving using Java</i> book:</p>
<blockquote>
<p>Write a routine that uses the Collections API to print out the items in any Collection in reverse order. Do not use a ListIterator.</p>
</blockquote>
<p>I'm not putting it up here because I want somebody to do my homework, I just can't seem to understand exactly what it is asking for me to code!</p>
<p>When it asks me to write a 'routine', is it looking for a single method? I don't really understand how I can make a single method work for all of the various types of Collections (linked list, queue, stack).</p>
<p>If anybody could guide me in the right direction, I would greatly appreciate it.</p>
|
[
{
"answer_id": 196633,
"author": "Karan",
"author_id": 11110,
"author_profile": "https://Stackoverflow.com/users/11110",
"pm_score": 0,
"selected": false,
"text": "<p>Well you could have a routine that delegates to other routines based on the input type, however I'm not sure there is a generic enough collection type that can be encompassed into one argument. I guess you could just use method overloading (having multiple methods with the same name, but accept different args).</p>\n\n<p>That could technically count as 1 routine (all have the same name).</p>\n"
},
{
"answer_id": 196638,
"author": "AdamC",
"author_id": 16476,
"author_profile": "https://Stackoverflow.com/users/16476",
"pm_score": 2,
"selected": false,
"text": "<p>First, I believe it is asking you to write a method. Like:</p>\n\n<pre><code>void printReverseList(Collection col) {}\n</code></pre>\n\n<p>Then there are many ways to do this. For example, only using the Collection API, use the toArray method and use a for loop to print out all the items from the end. Make sense?</p>\n\n<p>As for the various classes using the Collection interface, it will automatically work for all of those since they must implement the interface (provided they implement it in a sane way;).</p>\n"
},
{
"answer_id": 196640,
"author": "Moishe Lettvin",
"author_id": 23786,
"author_profile": "https://Stackoverflow.com/users/23786",
"pm_score": 0,
"selected": false,
"text": "<p>Isn't there a base Collection class?</p>\n<p>Probably worth looking here as a starting point: <a href=\"https://docs.oracle.com/javase/1.5.0/docs/api/java/util/Collections.html\" rel=\"nofollow noreferrer\">Collections</a>.</p>\n"
},
{
"answer_id": 196641,
"author": "Kris",
"author_id": 18565,
"author_profile": "https://Stackoverflow.com/users/18565",
"pm_score": 0,
"selected": false,
"text": "<p>I don't know much Java, but considering the \"Collections API\" i imagine all those objects implement an interface you could iterate through someway. i suppose they all could have an itemAtIndex( int index ) and length() or similar method you could use.</p>\n\n<p><a href=\"http://java.sun.com/docs/books/tutorial/collections/intro/index.html\" rel=\"nofollow noreferrer\">You might want to read this.</a></p>\n"
},
{
"answer_id": 196642,
"author": "ddimitrov",
"author_id": 18187,
"author_profile": "https://Stackoverflow.com/users/18187",
"pm_score": 5,
"selected": true,
"text": "<p>Regardless from the question not making much sense as half of the collections have no gstable ordering of have fixed-ordering (i.e. TreeSet or PriorityQueue), you can use the following statement for printing the contents of a collection in reverse-natural order:</p>\n\n<pre><code>List temp = new ArrayList(src);\nCollections.reverse(temp);\nSystem.out.println(temp);\n</code></pre>\n\n<p>I essence you create an array list as lists are the only structure that can be arbitrarily reordered. You pass the <em>src</em> collection to the constructor which initializes the list withj the contents of the <em>src</em> in the collection natural order. Then you pass the list to the <em>Collections.reverse()</em> method which reverses the list and finally you print it.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/196628",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14013/"
] |
I have the following problem in my *Data Structures and Problem Solving using Java* book:
>
> Write a routine that uses the Collections API to print out the items in any Collection in reverse order. Do not use a ListIterator.
>
>
>
I'm not putting it up here because I want somebody to do my homework, I just can't seem to understand exactly what it is asking for me to code!
When it asks me to write a 'routine', is it looking for a single method? I don't really understand how I can make a single method work for all of the various types of Collections (linked list, queue, stack).
If anybody could guide me in the right direction, I would greatly appreciate it.
|
Regardless from the question not making much sense as half of the collections have no gstable ordering of have fixed-ordering (i.e. TreeSet or PriorityQueue), you can use the following statement for printing the contents of a collection in reverse-natural order:
```
List temp = new ArrayList(src);
Collections.reverse(temp);
System.out.println(temp);
```
I essence you create an array list as lists are the only structure that can be arbitrarily reordered. You pass the *src* collection to the constructor which initializes the list withj the contents of the *src* in the collection natural order. Then you pass the list to the *Collections.reverse()* method which reverses the list and finally you print it.
|
196,661 |
<p>I was hoping to do something like this, but it appears to be illegal in C#:</p>
<pre><code>public Collection MethodThatFetchesSomething<T>()
where T : SomeBaseClass
{
return T.StaticMethodOnSomeBaseClassThatReturnsCollection();
}
</code></pre>
<p>I get a compile-time error:</p>
<blockquote>
<p>'T' is a 'type parameter', which is not valid in the given context.</p>
</blockquote>
<p>Given a generic type parameter, how can I call a static method on the generic class? The static method has to be available, given the constraint.</p>
|
[
{
"answer_id": 196670,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 2,
"selected": false,
"text": "<p>As of now, you can't. You need a way of telling the compiler that T has that method, and presently, there's no way to do that. (Many are pushing Microsoft to expand what can be specified in a generic constraint, so maybe this will be possible in the future). </p>\n"
},
{
"answer_id": 196674,
"author": "Brad Wilson",
"author_id": 1554,
"author_profile": "https://Stackoverflow.com/users/1554",
"pm_score": 3,
"selected": false,
"text": "<p>It sounds like you're trying to use generics to work around the fact that there are no \"virtual static methods\" in C#.</p>\n\n<p>Unfortunately, that's not gonna work.</p>\n"
},
{
"answer_id": 196683,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 3,
"selected": false,
"text": "<p>The only way of calling such a method would be via reflection, However, it sounds like it might be possible to wrap that functionality in an interface and use an instance-based IoC / factory / etc pattern.</p>\n"
},
{
"answer_id": 196977,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": 7,
"selected": true,
"text": "<p>In this case you should just call the static method on the constrainted type directly. C# (and the CLR) do not support virtual static methods. So:</p>\n\n<pre><code>T.StaticMethodOnSomeBaseClassThatReturnsCollection\n</code></pre>\n\n<p>...can be no different than:</p>\n\n<pre><code>SomeBaseClass.StaticMethodOnSomeBaseClassThatReturnsCollection\n</code></pre>\n\n<p>Going through the generic type parameter is an unneeded indirection and hence not supported. </p>\n"
},
{
"answer_id": 462136,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Here, i post an example that work, it's a workaround</p>\n\n<pre><code>public interface eInterface {\n void MethodOnSomeBaseClassThatReturnsCollection();\n}\n\npublic T:SomeBaseClass, eInterface {\n\n public void MethodOnSomeBaseClassThatReturnsCollection() \n { StaticMethodOnSomeBaseClassThatReturnsCollection() }\n\n}\n\npublic Collection MethodThatFetchesSomething<T>() where T : SomeBaseClass, eInterface\n{ \n return ((eInterface)(new T()).StaticMethodOnSomeBaseClassThatReturnsCollection();\n}\n</code></pre>\n"
},
{
"answer_id": 4982366,
"author": "johnc",
"author_id": 5302,
"author_profile": "https://Stackoverflow.com/users/5302",
"pm_score": 2,
"selected": false,
"text": "<p><strike>You should be able to do this using reflection, as is described <a href=\"http://blogs.microsoft.co.il/blogs/bursteg/archive/2006/11/15/InvokeStaticGenericMethod.aspx\" rel=\"nofollow noreferrer\">here</a></strike></p>\n\n<p>Due to link being dead, I found the relevant details in the wayback machine:</p>\n\n<blockquote>\n <p>Assume you have a class with a static generic method:</p>\n</blockquote>\n\n<pre><code>class ClassWithGenericStaticMethod\n{\n public static void PrintName<T>(string prefix) where T : class\n {\n Console.WriteLine(prefix + \" \" + typeof(T).FullName);\n }\n}\n</code></pre>\n\n<blockquote>\n <p>How can you invoke this method using relection?</p>\n \n <p>It turns out to be very easy… This is how you Invoke a Static Generic\n Method using Reflection:</p>\n</blockquote>\n\n<pre><code>// Grabbing the type that has the static generic method\nType typeofClassWithGenericStaticMethod = typeof(ClassWithGenericStaticMethod);\n\n// Grabbing the specific static method\nMethodInfo methodInfo = typeofClassWithGenericStaticMethod.GetMethod(\"PrintName\", System.Reflection.BindingFlags.Static | BindingFlags.Public);\n\n// Binding the method info to generic arguments\nType[] genericArguments = new Type[] { typeof(Program) };\nMethodInfo genericMethodInfo = methodInfo.MakeGenericMethod(genericArguments);\n\n// Simply invoking the method and passing parameters\n// The null parameter is the object to call the method from. Since the method is\n// static, pass null.\nobject returnValue = genericMethodInfo.Invoke(null, new object[] { \"hello\" });\n</code></pre>\n"
},
{
"answer_id": 8358651,
"author": "Joshua Pech",
"author_id": 629423,
"author_profile": "https://Stackoverflow.com/users/629423",
"pm_score": 5,
"selected": false,
"text": "<p>To elaborate on a previous answer, I think reflection is closer to what you want here. I could give 1001 reasons why you should or should not do something, I'll just answer your question as asked. I think you should call the GetMethod method on the type of the generic parameter and go from there. For example, for a function:</p>\n\n<pre><code>public void doSomething<T>() where T : someParent\n{\n List<T> items=(List<T>)typeof(T).GetMethod(\"fetchAll\").Invoke(null,new object[]{});\n //do something with items\n}\n</code></pre>\n\n<p>Where T is any class that has the static method fetchAll().</p>\n\n<p>Yes, I'm aware this is horrifically slow and may crash if someParent doesn't force all of its child classes to implement fetchAll but it answers the question as asked.</p>\n"
},
{
"answer_id": 8657544,
"author": "Amir Abiri",
"author_id": 800334,
"author_profile": "https://Stackoverflow.com/users/800334",
"pm_score": 2,
"selected": false,
"text": "<p>I just wanted to throw it out there that sometimes delegates solve these problems, depending on context.</p>\n\n<p>If you need to call the static method as some kind of a factory or initialization method, then you could declare a delegate and pass the static method to the relevant generic factory or whatever it is that needs this \"generic class with this static method\".</p>\n\n<p>For example:</p>\n\n<pre><code>class Factory<TProduct> where TProduct : new()\n{\n public delegate void ProductInitializationMethod(TProduct newProduct);\n\n\n private ProductInitializationMethod m_ProductInitializationMethod;\n\n\n public Factory(ProductInitializationMethod p_ProductInitializationMethod)\n {\n m_ProductInitializationMethod = p_ProductInitializationMethod;\n }\n\n public TProduct CreateProduct()\n {\n var prod = new TProduct();\n m_ProductInitializationMethod(prod);\n return prod;\n }\n}\n\nclass ProductA\n{\n public static void InitializeProduct(ProductA newProduct)\n {\n // .. Do something with a new ProductA\n }\n}\n\nclass ProductB\n{\n public static void InitializeProduct(ProductB newProduct)\n {\n // .. Do something with a new ProductA\n }\n}\n\nclass GenericAndDelegateTest\n{\n public static void Main()\n {\n var factoryA = new Factory<ProductA>(ProductA.InitializeProduct);\n var factoryB = new Factory<ProductB>(ProductB.InitializeProduct);\n\n ProductA prodA = factoryA.CreateProduct();\n ProductB prodB = factoryB.CreateProduct();\n }\n}\n</code></pre>\n\n<p>Unfortunately you can't enforce that the class has the right method, but you can at least compile-time-enforce that the resulting factory method has everything it expects (i.e an initialization method with exactly the right signature). This is better than a run time reflection exception.</p>\n\n<p>This approach also has some benefits, i.e you can reuse init methods, have them be instance methods, etc.</p>\n"
},
{
"answer_id": 66927384,
"author": "micahneitz",
"author_id": 6417406,
"author_profile": "https://Stackoverflow.com/users/6417406",
"pm_score": 3,
"selected": false,
"text": "<p>You can do what I call a surrogate singleton, I've been using it as a sort of "static inheritance" for a while</p>\n<pre class=\"lang-cs prettyprint-override\"><code>interface IFoo<T> where T : IFoo<T>, new()\n{\n ICollection<T> ReturnsCollection();\n}\n\nstatic class Foo<T> where T : IFoo<T>, new()\n{\n private static readonly T value = new();\n public static ICollection<T> ReturnsCollection() => value.ReturnsCollection();\n}\n\n// Use case\n\npublic ICollection<T> DoSomething<T>() where T : IFoo<T>, new()\n{\n return Foo<T>.ReturnsCollection();\n}\n</code></pre>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/196661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8169/"
] |
I was hoping to do something like this, but it appears to be illegal in C#:
```
public Collection MethodThatFetchesSomething<T>()
where T : SomeBaseClass
{
return T.StaticMethodOnSomeBaseClassThatReturnsCollection();
}
```
I get a compile-time error:
>
> 'T' is a 'type parameter', which is not valid in the given context.
>
>
>
Given a generic type parameter, how can I call a static method on the generic class? The static method has to be available, given the constraint.
|
In this case you should just call the static method on the constrainted type directly. C# (and the CLR) do not support virtual static methods. So:
```
T.StaticMethodOnSomeBaseClassThatReturnsCollection
```
...can be no different than:
```
SomeBaseClass.StaticMethodOnSomeBaseClassThatReturnsCollection
```
Going through the generic type parameter is an unneeded indirection and hence not supported.
|
196,668 |
<p>I'm working on a system that includes a large number of reports, generated using <a href="http://jasperforge.org/plugins/project/project_home.php?group_id=102" rel="noreferrer">JasperReports</a>. One of the newer features is that you can define styles for reports.</p>
<p>From the available docs I believe there is some way to have an external file defining styles to use, and you can reference that in your jasper reports. This allows a single style to be used by multiple reports.</p>
<p>I can't find any concrete information on whether this is an actual feature, and if it is, how to use it. Does anyone know if it is possible to have external styles for jasper reports, and if so, how to do it?</p>
|
[
{
"answer_id": 206403,
"author": "Jamie Love",
"author_id": 27308,
"author_profile": "https://Stackoverflow.com/users/27308",
"pm_score": 6,
"selected": true,
"text": "<p>Use <a href=\"http://jasperreports.sourceforge.net/sample.reference/templates/#templates\" rel=\"nofollow noreferrer\">JasperReport templates</a>. A JasperReports template is one that ends in <code>.jrtx</code>, and may look similar to this (<code>styles.jrtx</code>):</p>\n<pre><code><?xml version="1.0"?>\n<!DOCTYPE jasperTemplate\n PUBLIC "-//JasperReports//DTD Template//EN"\n "http://jasperreports.sourceforge.net/dtds/jaspertemplate.dtd">\n\n<jasperTemplate>\n <style name="Report Title" isDefault="false" hAlign="Center" fontSize="24" isBold="true"/>\n <style name="Heading 1" isDefault="false" fontSize="18" isBold="true"/>\n <style name="Heading 2" isDefault="false" fontSize="14" isBold="true"/>\n</jasperTemplate>\n</code></pre>\n<p>and then in your <code>.jrxml</code> file, include it as a template:</p>\n<pre><code>...\n<template><![CDATA["styles.jrtx"]]></template>\n...\n</code></pre>\n<p>iReport also understands this, so your styles are imported and shown in iReport correctly (though I did notice sometimes it wouldn't pick them up an a reload or recompile was necessary).</p>\n"
},
{
"answer_id": 595933,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>You can also avoid specifying the actual file name in the <code><template></code> element by using a parameter passed into your report at runtime</p>\n\n<p><code><parameter name=\"TEMPLATE_FILE\" isForPrompting=\"false\" class=\"java.lang.String\"/></code></p>\n\n<p><code><template><![CDATA[$P{TEMPLATE_FILE}]]></template></code></p>\n\n<p>where $P{TEMPLATE_FILE} is the full path to the style resource</p>\n"
},
{
"answer_id": 3563302,
"author": "roshani",
"author_id": 430185,
"author_profile": "https://Stackoverflow.com/users/430185",
"pm_score": 3,
"selected": false,
"text": "<p>I like to share my learning of using styles in Jasper reports, which I think quite useful for report designers like me, from a book named JasperReport Development cookbook by Bilal Siddiqui. I like this book and found demonstrating styles in a variety of manner like:</p>\n\n<ul>\n<li><p><strong>Creating a reusable style</strong><br/>\nSimply select “Style” while creating a new report and define style for text, line and rectangles. The style file will be stored as .jrtx file.</p></li>\n<li><p>Import reusable style it in your report<br/>\nThere are three chunk of information when importing styles in your report.\nStep1. Name and location of style template<br/> </p></li>\n</ul>\n\n<blockquote>\n<pre><code><template><![CDATA[\"C:\\\\ BigBoldRedTemplate.jrtx\"]]></template>\n</code></pre>\n</blockquote>\n\n<p>Step2. Each time you apply style to your report elements using the style template, a <code><reportElement></code> tag is created as shown below:</p>\n\n<pre><code>//style applied to a rectangle\n<rectangle radius=\"10\">\n <reportElement style=\"BigBoldRed\" mode=\"Transparent\" x=\"0\" y=\"0\" width=\"555\" height=\"44\"/>\n</rectangle>\n//style applied to a the text field\n<staticText>\n <reportElement style=\"BigBoldRed\" x=\"0\" y=\"0\" width=\"555\" height=\"66\"/>\n <textElement textAlignment=\"Center\" verticalAlignment=\"Middle\"/>\n <text><![CDATA[Monthly Customer Invoices]]></text>\n</staticText>\n</code></pre>\n\n<ul>\n<li><strong>Mixing the internal and reusable styles in report</strong><br/></li>\n<li><strong>Using the power of HTML to style your report</strong> <br/>\nFor example, your text field has following expression which includes HTML tags (i.e. <code><li></code>) and you want the HTML tags to work in your report design:</li>\n</ul>\n\n<blockquote>\n<pre><code>\"<li>\"+\"Invoice # \"+$F{InvoiceID}+\", \"+\n</code></pre>\n \n <p>$F{CustomerName}+\" purchased\n \"+$F{ProductName}+\" in\n \"+$F{InvoicePeriod}+\" (Invoice value:\n \\$ \"+$F{InvoiceValue}+\")\"+\"</li></p>\n</blockquote>\n\n<p>Solution is simple, just set “Markup” property of the text field to “Styled” and that it.</p>\n\n<p>I have taken permission from the author to copy code chunk from his JasperReports cookbook in this post.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/196668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27308/"
] |
I'm working on a system that includes a large number of reports, generated using [JasperReports](http://jasperforge.org/plugins/project/project_home.php?group_id=102). One of the newer features is that you can define styles for reports.
From the available docs I believe there is some way to have an external file defining styles to use, and you can reference that in your jasper reports. This allows a single style to be used by multiple reports.
I can't find any concrete information on whether this is an actual feature, and if it is, how to use it. Does anyone know if it is possible to have external styles for jasper reports, and if so, how to do it?
|
Use [JasperReport templates](http://jasperreports.sourceforge.net/sample.reference/templates/#templates). A JasperReports template is one that ends in `.jrtx`, and may look similar to this (`styles.jrtx`):
```
<?xml version="1.0"?>
<!DOCTYPE jasperTemplate
PUBLIC "-//JasperReports//DTD Template//EN"
"http://jasperreports.sourceforge.net/dtds/jaspertemplate.dtd">
<jasperTemplate>
<style name="Report Title" isDefault="false" hAlign="Center" fontSize="24" isBold="true"/>
<style name="Heading 1" isDefault="false" fontSize="18" isBold="true"/>
<style name="Heading 2" isDefault="false" fontSize="14" isBold="true"/>
</jasperTemplate>
```
and then in your `.jrxml` file, include it as a template:
```
...
<template><![CDATA["styles.jrtx"]]></template>
...
```
iReport also understands this, so your styles are imported and shown in iReport correctly (though I did notice sometimes it wouldn't pick them up an a reload or recompile was necessary).
|
196,684 |
<p>All right, say I have this:</p>
<pre><code><select id='list'>
<option value='1'>Option A</option>
<option value='2'>Option B</option>
<option value='3'>Option C</option>
</select>
</code></pre>
<p>What would the selector look like if I wanted to get "Option B" when I have the value '2'?</p>
<p>Please note that this is not asking how to get the <em>selected</em> text value, but just any one of them, whether selected or not, depending on the value attribute. I tried:</p>
<pre><code>$("#list[value='2']").text();
</code></pre>
<p>But it is not working.</p>
|
[
{
"answer_id": 196687,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 11,
"selected": true,
"text": "<p>It's looking for an element with id <code>list</code> which has a property <code>value</code> equal to <code>2</code>.<br>\nWhat you want is the <code>option</code> child of the <code>list</code>:</p>\n\n<pre><code>$(\"#list option[value='2']\").text()\n</code></pre>\n"
},
{
"answer_id": 196689,
"author": "Andrew Moore",
"author_id": 26210,
"author_profile": "https://Stackoverflow.com/users/26210",
"pm_score": 5,
"selected": false,
"text": "<p>Try the following:</p>\n\n<pre><code>$(\"#list option[value=2]\").text();\n</code></pre>\n\n<p>The reason why your original snippet wasn't working is because your <code>OPTION</code> tags are children to your <code>SELECT</code> tag, which has the <code>id</code> <code>list</code>.</p>\n"
},
{
"answer_id": 869486,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 10,
"selected": false,
"text": "<p>If you'd like to get the option with a value of 2, use</p>\n\n<pre><code>$(\"#list option[value='2']\").text();\n</code></pre>\n\n<hr>\n\n<p>If you'd like to get whichever option is currently selected, use</p>\n\n<pre><code>$(\"#list option:selected\").text();\n</code></pre>\n"
},
{
"answer_id": 2941793,
"author": "Mon",
"author_id": 354353,
"author_profile": "https://Stackoverflow.com/users/354353",
"pm_score": 4,
"selected": false,
"text": "<pre><code>$(\"#list [value='2']\").text();\n</code></pre>\n\n<p>leave a space after the id selector.</p>\n"
},
{
"answer_id": 2975038,
"author": "m3ct0n",
"author_id": 358544,
"author_profile": "https://Stackoverflow.com/users/358544",
"pm_score": 5,
"selected": false,
"text": "<pre><code>$(\"#list option:selected\").each(function() {\n alert($(this).text());\n}); \n</code></pre>\n\n<p>for multiple selected value in the <code>#list</code> element.</p>\n"
},
{
"answer_id": 5150943,
"author": "Dilantha",
"author_id": 302281,
"author_profile": "https://Stackoverflow.com/users/302281",
"pm_score": 4,
"selected": false,
"text": "<p>I wanted to get the selected label. This worked for me in jQuery 1.5.1.</p>\n\n<pre><code>$(\"#list :selected\").text();\n</code></pre>\n"
},
{
"answer_id": 5857108,
"author": "asyadiqin",
"author_id": 483050,
"author_profile": "https://Stackoverflow.com/users/483050",
"pm_score": 7,
"selected": false,
"text": "<p>Based on the original HTML posted by Paolo I came up with the following.</p>\n\n<pre><code>$(\"#list\").change(function() {\n alert($(this).find(\"option:selected\").text()+' clicked!');\n});\n</code></pre>\n\n<p>It has been tested to work on Internet Explorer and Firefox.</p>\n"
},
{
"answer_id": 6143723,
"author": "eon",
"author_id": 717833,
"author_profile": "https://Stackoverflow.com/users/717833",
"pm_score": 3,
"selected": false,
"text": "<p>While \"looping\" through dynamically created select elements with a .each(function()...): <code>$(\"option:selected\").text();</code> and <code>$(this + \" option:selected\").text()</code> did not return the selected option text - instead it was null.</p>\n\n<p>But Peter Mortensen's solution worked:</p>\n\n<pre><code>$(this).find(\"option:selected\").text();\n</code></pre>\n\n<p>I do not know why the usual way does not succeed in a <code>.each()</code> (probably my own mistake), but thank you, Peter. I know that wasn't the original question, but am mentioning it \"for newbies coming through Google.\"</p>\n\n<p>I would have started with <code>$('#list option:selected\").each()</code> except I needed to grab stuff from the select element as well.</p>\n"
},
{
"answer_id": 6658076,
"author": "Mary Daisy Sanchez",
"author_id": 560756,
"author_profile": "https://Stackoverflow.com/users/560756",
"pm_score": 3,
"selected": false,
"text": "<p>Use:</p>\n<pre><code>function selected_state(){\n jQuery("#list option").each(function(){\n if(jQuery(this).val() == "2"){\n jQuery(this).attr("selected","selected");\n return false;\n }else\n jQuery(this).removeAttr("selected","selected"); // For toggle effect\n });\n}\n\njQuery(document).ready(function(){\n selected_state();\n});\n</code></pre>\n"
},
{
"answer_id": 6877694,
"author": "raphie",
"author_id": 424543,
"author_profile": "https://Stackoverflow.com/users/424543",
"pm_score": 7,
"selected": false,
"text": "<p>This worked perfectly for me, I was looking for a way to send two different values with options generated by MySQL, and the following is generic and dynamic:</p>\n\n<h3><code>$(this).find(\"option:selected\").text();</code></h3>\n\n<p>As mentioned in one of the comments. With this I was able to create a dynamic function that works with all my selection boxes that I want to get both values, the option value and the text.</p>\n\n<p>Few days ago I noticed that when updating the jQuery from 1.6 to 1.9 of the site I used this code, this stop working... probably was a conflict with another piece of code... anyway, the solution was to remove option from the find() call:</p>\n\n<pre><code>$(this).find(\":selected\").text();\n</code></pre>\n\n<p>That was my solution... use it only if you have any problem after updating your jQuery.</p>\n"
},
{
"answer_id": 8718582,
"author": "gordon",
"author_id": 778294,
"author_profile": "https://Stackoverflow.com/users/778294",
"pm_score": 2,
"selected": false,
"text": "<p>I wanted a dynamic version for select multiple that would display what is selected to the right (wish I'd read on and seen <code>$(this).find</code>... earlier):</p>\n\n<pre><code><script type=\"text/javascript\">\n $(document).ready(function(){\n $(\"select[showChoices]\").each(function(){\n $(this).after(\"<span id='spn\"+$(this).attr('id')+\"' style='border:1px solid black;width:100px;float:left;white-space:nowrap;'>&nbsp;</span>\");\n doShowSelected($(this).attr('id'));//shows initial selections\n }).change(function(){\n doShowSelected($(this).attr('id'));//as user makes new selections\n });\n });\n function doShowSelected(inId){\n var aryVals=$(\"#\"+inId).val();\n var selText=\"\";\n for(var i=0; i<aryVals.length; i++){\n var o=\"#\"+inId+\" option[value='\"+aryVals[i]+\"']\";\n selText+=$(o).text()+\"<br>\";\n }\n $(\"#spn\"+inId).html(selText);\n }\n</script>\n<select style=\"float:left;\" multiple=\"true\" id=\"mySelect\" name=\"mySelect\" showChoices=\"true\">\n <option selected=\"selected\" value=1>opt 1</option>\n <option selected=\"selected\" value=2>opt 2</option>\n <option value=3>opt 3</option>\n <option value=4>opt 4</option>\n</select>\n</code></pre>\n"
},
{
"answer_id": 11007952,
"author": "Beena Shetty",
"author_id": 853453,
"author_profile": "https://Stackoverflow.com/users/853453",
"pm_score": 5,
"selected": false,
"text": "<ol>\n<li><p>If there is only one select tag in on the page then you can specify select inside of id 'list'</p>\n\n<pre><code>jQuery(\"select option[value=2]\").text();\n</code></pre></li>\n<li><p>To get selected text</p>\n\n<pre><code>jQuery(\"select option:selected\").text();\n</code></pre></li>\n</ol>\n"
},
{
"answer_id": 14425761,
"author": "VisioN",
"author_id": 1249581,
"author_profile": "https://Stackoverflow.com/users/1249581",
"pm_score": 2,
"selected": false,
"text": "<p>As an alternative solution, you can also use a <a href=\"http://api.jquery.com/jQuery/#jQuery1\" rel=\"nofollow\">context part of jQuery selector</a> to find <code><option></code> element(s) with <code>value=\"2\"</code> inside the dropdown list:</p>\n\n<pre><code>$(\"option[value='2']\", \"#list\").text();\n</code></pre>\n"
},
{
"answer_id": 14836080,
"author": "Martin Clemens Bloch",
"author_id": 1265209,
"author_profile": "https://Stackoverflow.com/users/1265209",
"pm_score": 2,
"selected": false,
"text": "<p>I needed this answer as I was dealing with a dynamically cast object, and the other methods here did not seem to work:</p>\n\n<pre><code>element.options[element.selectedIndex].text\n</code></pre>\n\n<p>This of course uses the <a href=\"http://en.wikipedia.org/wiki/Document_Object_Model\" rel=\"nofollow\">DOM</a> object instead of parsing its HTML with nodeValue, childNodes, etc.</p>\n"
},
{
"answer_id": 15785944,
"author": "Avinash Saini",
"author_id": 2226601,
"author_profile": "https://Stackoverflow.com/users/2226601",
"pm_score": 4,
"selected": false,
"text": "<pre><code>$(this).children(\":selected\").text()\n</code></pre>\n"
},
{
"answer_id": 19799860,
"author": "FAA",
"author_id": 1212739,
"author_profile": "https://Stackoverflow.com/users/1212739",
"pm_score": 3,
"selected": false,
"text": "<p>I was looking for getting val by internal field name instead of ID and came from google to this post which help but did not find the solution I need, but I got the solution and here it is: </p>\n\n<p>So this might help somebody looking for selected value with field internal name instead of using long id for SharePoint lists: </p>\n\n<pre><code>var e = $('select[title=\"IntenalFieldName\"] option:selected').text(); \n</code></pre>\n"
},
{
"answer_id": 24542571,
"author": "mindmyweb",
"author_id": 730763,
"author_profile": "https://Stackoverflow.com/users/730763",
"pm_score": 4,
"selected": false,
"text": "<p>This is an old Question which has not been updated in some time the correct way to do this now would be to use </p>\n\n<pre><code>$(\"#action\").on('change',function() {\n alert($(this).find(\"option:selected\").text()+' clicked!');\n});\n</code></pre>\n\n<p>I hope this helps :-)</p>\n"
},
{
"answer_id": 28935856,
"author": "Alireza Fattahi",
"author_id": 2648077,
"author_profile": "https://Stackoverflow.com/users/2648077",
"pm_score": 3,
"selected": false,
"text": "<p>A tip: you can use below code if your value is dynamic:</p>\n\n<pre><code>$(\"#list option[value='\"+aDynamicValue+\"']\").text();\n</code></pre>\n\n<p>Or (better style)</p>\n\n<pre><code>$(\"#list option\").filter(function() {\n return this.value === aDynamicValue;\n}).text();\n</code></pre>\n\n<p>As mentioned in <a href=\"https://stackoverflow.com/questions/12135825/jquery-get-specific-option-tag-text-and-placing-dynamic-variable-to-the-value/12135848\">jQuery get specific option tag text and placing dynamic variable to the value</a></p>\n"
},
{
"answer_id": 42551632,
"author": "Dilipkumar63",
"author_id": 7639213,
"author_profile": "https://Stackoverflow.com/users/7639213",
"pm_score": 4,
"selected": false,
"text": "<p>You can get selected option text by using function <code>.text();</code> </p>\n\n<p>you can call the function like this :</p>\n\n<pre><code>jQuery(\"select option:selected\").text();\n</code></pre>\n"
},
{
"answer_id": 50230859,
"author": "Anfath Hifans",
"author_id": 7352537,
"author_profile": "https://Stackoverflow.com/users/7352537",
"pm_score": 2,
"selected": false,
"text": "<p>You can get one of following ways</p>\n\n<pre><code>$(\"#list\").find('option').filter('[value=2]').text()\n\n$(\"#list\").find('option[value=2]').text()\n\n$(\"#list\").children('option[value=2]').text()\n\n$(\"#list option[value='2']\").text()\n</code></pre>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>$(function(){ \r\n \r\n console.log($(\"#list\").find('option').filter('[value=2]').text());\r\n console.log($(\"#list\").find('option[value=2]').text());\r\n console.log($(\"#list\").children('option[value=2]').text());\r\n console.log($(\"#list option[value='2']\").text());\r\n \r\n});</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><script src=\"//ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js\"></script>\r\n<select id='list'>\r\n <option value='1'>Option A</option>\r\n <option value='2'>Option B</option>\r\n <option value='3'>Option C</option>\r\n</select></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 63507191,
"author": "Kamil Kiełczewski",
"author_id": 860099,
"author_profile": "https://Stackoverflow.com/users/860099",
"pm_score": 0,
"selected": false,
"text": "<p>Try</p>\n<pre><code>[...list.options].find(o=> o.value=='2').text\n</code></pre>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>let text = [...list.options].find(o=> o.value=='2').text;\n\nconsole.log(text);</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><select id='list'>\n <option value='1'>Option A</option>\n <option value='2'>Option B</option>\n <option value='3'>Option C</option>\n</select></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 64465676,
"author": "Zakaria Binsaifullah",
"author_id": 8381482,
"author_profile": "https://Stackoverflow.com/users/8381482",
"pm_score": 2,
"selected": false,
"text": "<p>Try this:</p>\n<pre><code>jQuery("#list option[value='2']").text()\n</code></pre>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/196684",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16417/"
] |
All right, say I have this:
```
<select id='list'>
<option value='1'>Option A</option>
<option value='2'>Option B</option>
<option value='3'>Option C</option>
</select>
```
What would the selector look like if I wanted to get "Option B" when I have the value '2'?
Please note that this is not asking how to get the *selected* text value, but just any one of them, whether selected or not, depending on the value attribute. I tried:
```
$("#list[value='2']").text();
```
But it is not working.
|
It's looking for an element with id `list` which has a property `value` equal to `2`.
What you want is the `option` child of the `list`:
```
$("#list option[value='2']").text()
```
|
196,702 |
<p>Say I have a fairly hefty JavaScript file, packed down to roughly 100kb or so. By file I mean it’s an external file that would be linked in via <code><script src="..."></code>, not pasted into the HTML itself.</p>
<p>Where’s the best place to put this in the HTML?</p>
<pre><code><html>
<head>
<!-- here? -->
<link rel="stylesheet" href="stylez.css" type="text/css" />
<!-- here? -->
</head>
<body>
<!-- here? -->
<p>All the page content ...</p>
<!-- or here? -->
</body>
</html>
</code></pre>
<p>Will there be any functional difference between each of the options?</p>
|
[
{
"answer_id": 196708,
"author": "Levi Rosol",
"author_id": 23458,
"author_profile": "https://Stackoverflow.com/users/23458",
"pm_score": 6,
"selected": false,
"text": "<p>The best place for it is just before you need it and no sooner. </p>\n\n<p>Also, depending on your users' physical location, using a service like Amazon's S3 service may help users download it from a server physically closer to them than your server.</p>\n\n<p>Is your js script a commonly used lib like jQuery or prototype? If so, there are a number of companies, like Google and Yahoo, that have tools to provide these files for you on a distributed network.</p>\n"
},
{
"answer_id": 196718,
"author": "Walter Rumsby",
"author_id": 1654,
"author_profile": "https://Stackoverflow.com/users/1654",
"pm_score": 8,
"selected": true,
"text": "<p>The Yahoo! Exceptional Performance team recommend <a href=\"http://developer.yahoo.com/performance/rules.html#js_bottom\" rel=\"noreferrer\">placing scripts at the bottom of your page</a> because of the way browsers download components.</p>\n\n<p>Of course Levi's comment \"just before you need it and no sooner\" is really the correct answer, i.e. \"it depends\".</p>\n"
},
{
"answer_id": 196933,
"author": "bart",
"author_id": 19966,
"author_profile": "https://Stackoverflow.com/users/19966",
"pm_score": 2,
"selected": false,
"text": "<p>With 100k of Javascript, you should never put it inside the file. Use an external script Javascript file. There's no chance in hell you'll only ever use this amount of code in only one HTML page. Likely you're asking where you should load the Javascript file, for this you've received satisfactory answers already.</p>\n\n<p>But I'd like to point out that commonly, modern browsers accept <strong>gzip</strong>ped Javascript files! Just gzip the <code>x.js</code> file to <code>x.js.gz</code>, and point to that in the <code>src</code> attribute. It doesn't work on the local filesystem, you need a webserver for it to work. But the savings in transferred bytes can be enormous.</p>\n\n<p>I've successfully tested it in Firefox 3, MSIE 7, Opera 9, and Google Chrome. It apparently doesn't work this way in Safari 3.</p>\n\n<p>For more info, see <a href=\"http://joseph.randomnetworks.com/archives/2006/07/13/compressed-javascript/\" rel=\"nofollow noreferrer\">this blog post</a>, and another <a href=\"http://schroepl.net/projekte/mod_gzip/browser.htm\" rel=\"nofollow noreferrer\">very ancient page</a> that nevertheless is useful because it points out that the webserver can detect whether a browser can accept gzipped Javascript, or not. If your server side can dynamically choose to send the gzipped or the plain text, you can make the page usable in all web browsers.</p>\n"
},
{
"answer_id": 197020,
"author": "GustyWind",
"author_id": 11114,
"author_profile": "https://Stackoverflow.com/users/11114",
"pm_score": 1,
"selected": false,
"text": "<p>The answer is depends how you are using the objects of javascript. As already pointed loading the javascript files at footer rather than header certainly improves the performance but care should be taken that the objects which are used are initialized later than they are loaded at footer. One more way is load the 'js' files placed in folder\nwhich will be available to all the files.</p>\n"
},
{
"answer_id": 197037,
"author": "Berserk",
"author_id": 26313,
"author_profile": "https://Stackoverflow.com/users/26313",
"pm_score": 0,
"selected": false,
"text": "<p>Like others have said, it should most likely go in an external file. I prefer to include such files at the end of the <head />. This method is more human friendly than machine friendly, but that way I always know where the JS is. It is just not as readable to include script files anywhere else (imho).</p>\n\n<p>I you really need to squeeze out every last ms then you probably should do what Yahoo says.</p>\n"
},
{
"answer_id": 208759,
"author": "Sam Hasler",
"author_id": 2541,
"author_profile": "https://Stackoverflow.com/users/2541",
"pm_score": 2,
"selected": false,
"text": "<p>Using <a href=\"http://stevesouders.com/cuzillion/\" rel=\"nofollow noreferrer\">cuzillion</a> you can test the affect on page load of different placement of script tags using different methods: inline, external, \"HTML tags\", \"document.write\", \"JS DOM element\", \"iframe\", and \"XHR eval\". See the <a href=\"http://stevesouders.com/cuzillion/help.php\" rel=\"nofollow noreferrer\">help</a> for an explanation of the differences. It can also test stylesheets, images and iframes.</p>\n"
},
{
"answer_id": 208844,
"author": "Matthias Wandel",
"author_id": 20073,
"author_profile": "https://Stackoverflow.com/users/20073",
"pm_score": 2,
"selected": false,
"text": "<p>Putting the javascript at the top would seem neater, but functionally, its better to go after the HTML. That way, your javascript won't run and try to reference HTML elements before they are loaded. This sort of problem often only becomes apparent when you load the page over an actual internet connection, especially a slow one.</p>\n\n<p>You could also try to dynamically load the javascript by adding a header element from other javascript code, although that only makes sense if you aren't using all of the code all the time.</p>\n"
},
{
"answer_id": 23476758,
"author": "martynas",
"author_id": 3300831,
"author_profile": "https://Stackoverflow.com/users/3300831",
"pm_score": 6,
"selected": false,
"text": "<p>As a rule of thumb, the best place to put <code><script></code> tags is the bottom of the page, just before <code></body></code> tag. Something like this:</p>\n\n<pre><code><html>\n <head>\n <title>My awesome page</title>\n\n <!-- CSS -->\n <link rel=\"stylesheet\" type=\"text/css\" href=\"...\">\n <link rel=\"stylesheet\" type=\"text/css\" href=\"...\">\n <link rel=\"stylesheet\" type=\"text/css\" href=\"...\">\n <link rel=\"stylesheet\" type=\"text/css\" href=\"...\">\n\n </head>\n <body>\n <!-- Content content content -->\n\n <script type=\"text/javascript\" src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js\"></script>\n <script type=\"text/javascript\" src=\"...\"></script>\n <script type=\"text/javascript\" src=\"...\"></script>\n <script type=\"text/javascript\" src=\"...\"></script>\n </body>\n</html>\n</code></pre>\n\n<h1><strong>Why?</strong></h1>\n\n<blockquote>\n <p>The problem caused by scripts is that they block parallel downloads. The HTTP/1.1 specification suggests that browsers download no more than two components in parallel per hostname. If you serve your images from multiple hostnames, you can get more than two downloads to occur in parallel. While a script is downloading, however, the browser won't start any other downloads, even on different hostnames. <em><a href=\"https://developer.yahoo.com/performance/rules.html\">More...</a></em></p>\n</blockquote>\n\n<h1><strong>CSS</strong></h1>\n\n<p>A little bit off-topic, but... Put stylesheets at the top.</p>\n\n<blockquote>\n <p>While researching performance at Yahoo!, we discovered that moving stylesheets to the document HEAD makes pages appear to be loading faster. This is because putting stylesheets in the HEAD allows the page to render progressively. <em><a href=\"https://developer.yahoo.com/performance/rules.html\">More...</a></em></p>\n</blockquote>\n\n<h1><strong>Further reading</strong></h1>\n\n<p>Yahoo have released a really cool guide that lists best practices to speed up a website. Definitely worth reading:\n<a href=\"https://developer.yahoo.com/performance/rules.html\">https://developer.yahoo.com/performance/rules.html</a></p>\n"
},
{
"answer_id": 33786202,
"author": "Timothy Trousdale",
"author_id": 5577518,
"author_profile": "https://Stackoverflow.com/users/5577518",
"pm_score": 0,
"selected": false,
"text": "<p>Your javascript links can got either in the head or at the end of the body tag, it is true that performance improves by putting the link at the end of your body tag, but unless performance is an issue, placing them in the head is nicer for people to read and you know where the links are located and can reference them easier.</p>\n"
},
{
"answer_id": 38589118,
"author": "Ludus H",
"author_id": 2386823,
"author_profile": "https://Stackoverflow.com/users/2386823",
"pm_score": 0,
"selected": false,
"text": "<p>I would say that it depends of fact what do you planed to achieve with Javascript code:</p>\n\n<ul>\n<li>if you planned to insert external your JS script(s), then the best\nplace is in head of the page </li>\n<li>if you planed to use pages on smartphones, then bottom of page,\njust before tag.</li>\n<li>but, if you planned to make combination HTML and JS (dynamically\ncreated and populated HTML table, for example) then you must put\nit where you need it there.</li>\n</ul>\n"
},
{
"answer_id": 54893387,
"author": "José Salgado",
"author_id": 6914786,
"author_profile": "https://Stackoverflow.com/users/6914786",
"pm_score": 1,
"selected": false,
"text": "<p>The scripts should be included at the end of the body tag because this way the HTML will be parsed by the browser and displayed before the scripts are loaded.</p>\n"
},
{
"answer_id": 62213234,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>The answer to the question depends. There are 2 scenarios in this situation and you'll need to make a choice based on your appropriate scenario.</p>\n\n<p><strong>Scenario 1 - Critical script / Must needed script</strong></p>\n\n<p>In case the script you are using is important to load the website, it is recommended to be placed at the top of your HTML document i.e, <code><head></code>. Some examples include - application code, bootstrap, fonts, etc.</p>\n\n<p><strong>Scenario 2 - Less important / analytics scripts</strong></p>\n\n<p>There are also scripts used which do not affect the website's view. Such scripts are recommended to be loaded after all the important segments are loaded. And the answer to that will be bottom of the document i.e, bottom of your <code><body></code> before the closing tag. Some examples include - Google analytics, hotjar, etc.</p>\n\n<p><strong>Bonus - async / defer</strong></p>\n\n<p>You can also tell the browsers that the script loading can be done simultaneously with others and can be loaded based on the browser's choice using a defer / async argument in the script code.</p>\n\n<p>eg. <code><script async src=\"script.js\"></script></code></p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/196702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9021/"
] |
Say I have a fairly hefty JavaScript file, packed down to roughly 100kb or so. By file I mean it’s an external file that would be linked in via `<script src="...">`, not pasted into the HTML itself.
Where’s the best place to put this in the HTML?
```
<html>
<head>
<!-- here? -->
<link rel="stylesheet" href="stylez.css" type="text/css" />
<!-- here? -->
</head>
<body>
<!-- here? -->
<p>All the page content ...</p>
<!-- or here? -->
</body>
</html>
```
Will there be any functional difference between each of the options?
|
The Yahoo! Exceptional Performance team recommend [placing scripts at the bottom of your page](http://developer.yahoo.com/performance/rules.html#js_bottom) because of the way browsers download components.
Of course Levi's comment "just before you need it and no sooner" is really the correct answer, i.e. "it depends".
|
196,713 |
<p>I need to match something in the form </p>
<pre><code><a href="pic/5" id="piclink"><img src="thumb/5" /></a>
</code></pre>
<p>to find the number, in this case 5, using JavaScript. I have no idea how to use regexes, so I was wondering if anyone here could help out.</p>
|
[
{
"answer_id": 196717,
"author": "num1",
"author_id": 306,
"author_profile": "https://Stackoverflow.com/users/306",
"pm_score": 1,
"selected": false,
"text": "<p>Nevermind, I solved it with a simple </p>\n\n<pre><code>'<a href=\"pic/5\" id=\"piclink\"><img src=\"thumb/5\" /></a>'.match(/[0-9]/);\n</code></pre>\n"
},
{
"answer_id": 196743,
"author": "Rudi",
"author_id": 22830,
"author_profile": "https://Stackoverflow.com/users/22830",
"pm_score": 3,
"selected": true,
"text": "<p>Just to make sure you know what's going on, the pattern you posted in your own answer will match exactly <strong>one</strong> digit between 0 and 9.</p>\n\n<p>If you want to match integers with one or more digits, you might try the pattern</p>\n\n<pre><code>/[0-9]+/\n</code></pre>\n\n<p>Check out <a href=\"http://en.wikipedia.org/wiki/Regular_expressions\" rel=\"nofollow noreferrer\">Wikipedia's article on Regular Expressions</a> for a great overview. Regular Expressions can seem overwhelming if you're just starting out, but once you get a handle on the basic syntax, they're incredibly useful and powerful.</p>\n"
},
{
"answer_id": 196749,
"author": "micahwittman",
"author_id": 11181,
"author_profile": "https://Stackoverflow.com/users/11181",
"pm_score": 1,
"selected": false,
"text": "<p>It's not clear what the general case is (the specific in your example is \"5\"). If you're trying to extract the last segment of the URI path, you can achieve it without employing a regex:</p>\n\n<p>Using jQuery (not necessary, but a really effective tool if the context permits):</p>\n\n<pre><code>$('#picklink > img').attr('src').split('/').pop();\n</code></pre>\n\n<p>The <code>\"$('#picklink > img').attr('src')\"</code> is jQuery and the <code>\".split('/').pop();\"</code> part is straight JavaScript.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/196713",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/306/"
] |
I need to match something in the form
```
<a href="pic/5" id="piclink"><img src="thumb/5" /></a>
```
to find the number, in this case 5, using JavaScript. I have no idea how to use regexes, so I was wondering if anyone here could help out.
|
Just to make sure you know what's going on, the pattern you posted in your own answer will match exactly **one** digit between 0 and 9.
If you want to match integers with one or more digits, you might try the pattern
```
/[0-9]+/
```
Check out [Wikipedia's article on Regular Expressions](http://en.wikipedia.org/wiki/Regular_expressions) for a great overview. Regular Expressions can seem overwhelming if you're just starting out, but once you get a handle on the basic syntax, they're incredibly useful and powerful.
|
196,721 |
<p>I'm trying to configure my WAR project build to fail if the line or branch coverage is below given thresholds. I've been using the configuration provided on page 455 of the excellent book <a href="http://oreilly.com/catalog/9780596527938/" rel="noreferrer">Java Power Tools</a>, but with no success. Here's the relevant snippet of my project's Maven 2 POM:</p>
<pre><code><build>
...
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>cobertura-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<check>
<!-- Per-class thresholds -->
<lineRate>80</lineRate>
<branchRate>80</branchRate>
<!-- Project-wide thresholds -->
<totalLineRate>90</totalLineRate>
<totalBranchRate>90</totalBranchRate>
</check>
<executions>
<execution>
<goals>
<goal>clean</goal>
<goal>check</goal>
</goals>
</execution>
<execution>
<id>coverage-tests</id>
<!-- The "verify" phase occurs just before "install" -->
<phase>verify</phase>
<goals>
<goal>clean</goal>
<goal>check</goal>
</goals>
</execution>
</executions>
<instrumentation>
<excludes>
<exclude>au/**/*Constants.*</exclude>
</excludes>
<ignores>
<ignore>au/**/*Constants.*</ignore>
</ignores>
</instrumentation>
</configuration>
</plugin>
...
</plugins>
...
</build>
</code></pre>
<p>As I say, the coverage report works fine, the problem is that the "install" goal isn't failing as it should if the line or branch coverage is below my specified thresholds. Does anyone have this working, and if so, what does your POM look like and which version of Cobertura and Maven are you using? I'm using Maven 2.0.9 and Cobertura 2.2.</p>
<p>I've tried Googling and reading the Cobertura docs, but no luck (the latter are sparse to say the least).</p>
|
[
{
"answer_id": 197014,
"author": "Brian Matthews",
"author_id": 1969,
"author_profile": "https://Stackoverflow.com/users/1969",
"pm_score": 2,
"selected": false,
"text": "<p>Add the following to the <check/> configuration.</p>\n\n<pre>\n<haltOnFailure>true</haltOnFailure>\n</pre>\n"
},
{
"answer_id": 1618213,
"author": "Pascal Thivent",
"author_id": 70604,
"author_profile": "https://Stackoverflow.com/users/70604",
"pm_score": 5,
"selected": true,
"text": "<p>To my knowledge, <em>if the <code><haltOnFailure></code> element is set to true and any of the specified checks fails, then Cobertura will cause the build to fail</em> which is what you're asking for. But actually, this element defaults to <code>true</code> if you do not specify it so you <strong>don't have to</strong> add it to your <a href=\"http://mojo.codehaus.org/cobertura-maven-plugin/usage.html#Check\" rel=\"noreferrer\">configuration checks</a>. Failing the build below any coverage threshold is (or at least should be) the default behavior. </p>\n\n<p><strong>EDIT:</strong> I did some further testing and <code>haltOnFailure</code> seems to be working as expected on my environment (Maven 2.2.1. and versions 2.3, 2.2, 2.1 of the plugin i.e. versions 1.9.2, 1.9, 1.8 of cobertura on Linux). I'm updating this answer with the result below.</p>\n\n<p>Actually, I've added an <code><execution></code> element to my pom. I may be misinterpreting the part of <a href=\"http://mojo.codehaus.org/cobertura-maven-plugin/check-mojo.html\" rel=\"noreferrer\">cobertura:check</a>'s documentation that says it \"<em>Binds by default to the lifecycle phase: <code>verify</code></em>\" but, without the <code><execution></code> element, <a href=\"http://mojo.codehaus.org/cobertura-maven-plugin/check-mojo.html\" rel=\"noreferrer\">cobertura:check</a> wasn't triggered during the <em>verify</em> phase of my build. Below the setup I've use for the cobertura-maven-plugin:</p>\n\n<pre><code><project>\n ...\n <build>\n ...\n <plugins>\n ...\n <plugin>\n <groupId>org.codehaus.mojo</groupId>\n <artifactId>cobertura-maven-plugin</artifactId>\n <version>2.3</version>\n <configuration>\n <check>\n <!--<haltOnFailure>true</haltOnFailure>--><!-- optional -->\n <!-- Per-class thresholds -->\n <lineRate>80</lineRate>\n <branchRate>80</branchRate>\n <!-- Project-wide thresholds -->\n <totalLineRate>90</totalLineRate>\n <totalBranchRate>90</totalBranchRate>\n </check>\n </configuration>\n <executions>\n <execution>\n <phase>verify</phase>\n <goals>\n <!--<goal>clean</goal>--><!-- works if uncommented -->\n <goal>check</goal>\n </goals>\n </execution>\n </executions>\n </plugin>\n </plugins>\n </build>\n</project>\n</code></pre>\n\n<p>I get the following result when running <code>mvn clean install</code> on a freshly generated maven project (with <code>mvn archetype:create</code>) patched with the plugin configuration mentioned above: </p>\n\n<pre><code>$ mvn archetype:create -DgroupId=com.mycompany.samples -DartifactId=cobertura-haltonfailure-testcase\n...\n$ mvn clean install\n[INFO] Scanning for projects...\n[INFO] ------------------------------------------------------------------------\n[INFO] Building cobertura-haltonfailure-testcase\n[INFO] task-segment: [clean, install]\n[INFO] ------------------------------------------------------------------------\n[INFO] [clean:clean {execution: default-clean}]\n[INFO] Deleting directory /home/pascal/Projects/cobertura-haltonfailure-testcase/target\n[INFO] [resources:resources {execution: default-resources}]\n[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!\n[INFO] skip non existing resourceDirectory /home/pascal/Projects/cobertura-haltonfailure-testcase/src/main/resources\n[INFO] [compiler:compile {execution: default-compile}]\n[INFO] Compiling 1 source file to /home/pascal/Projects/cobertura-haltonfailure-testcase/target/classes\n[INFO] [resources:testResources {execution: default-testResources}]\n[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!\n[INFO] skip non existing resourceDirectory /home/pascal/Projects/cobertura-haltonfailure-testcase/src/test/resources\n[INFO] [compiler:testCompile {execution: default-testCompile}]\n[INFO] Compiling 1 source file to /home/pascal/Projects/cobertura-haltonfailure-testcase/target/test-classes\n[INFO] [surefire:test {execution: default-test}]\n[INFO] Surefire report directory: /home/pascal/Projects/cobertura-haltonfailure-testcase/target/surefire-reports\n\n-------------------------------------------------------\n T E S T S\n-------------------------------------------------------\nRunning com.mycompany.samples.AppTest\nTests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.09 sec\n\nResults :\n\nTests run: 1, Failures: 0, Errors: 0, Skipped: 0\n\n[INFO] [jar:jar {execution: default-jar}]\n[INFO] Building jar: /home/pascal/Projects/cobertura-haltonfailure-testcase/target/cobertura-haltonfailure-testcase-1.0-SNAPSHOT.jar\n[INFO] Preparing cobertura:check\n[WARNING] Removing: check from forked lifecycle, to prevent recursive invocation.\n[INFO] [resources:resources {execution: default-resources}]\n[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!\n[INFO] skip non existing resourceDirectory /home/pascal/Projects/cobertura-haltonfailure-testcase/src/main/resources\n[INFO] [compiler:compile {execution: default-compile}]\n[INFO] Nothing to compile - all classes are up to date\n[INFO] [cobertura:instrument {execution: default}]\n[INFO] Cobertura 1.9.2 - GNU GPL License (NO WARRANTY) - See COPYRIGHT file\nInstrumenting 1 file to /home/pascal/Projects/cobertura-haltonfailure-testcase/target/generated-classes/cobertura\nCobertura: Saved information on 1 classes.\nInstrument time: 337ms\n\n[INFO] Instrumentation was successful.\n[INFO] [resources:testResources {execution: default-testResources}]\n[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!\n[INFO] skip non existing resourceDirectory /home/pascal/Projects/cobertura-haltonfailure-testcase/src/test/resources\n[INFO] [compiler:testCompile {execution: default-testCompile}]\n[INFO] Nothing to compile - all classes are up to date\n[INFO] [surefire:test {execution: default-test}]\n[INFO] Surefire report directory: /home/pascal/Projects/cobertura-haltonfailure-testcase/target/surefire-reports\n\n-------------------------------------------------------\n T E S T S\n-------------------------------------------------------\nRunning com.mycompany.samples.AppTest\nTests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.098 sec\n\nResults :\n\nTests run: 1, Failures: 0, Errors: 0, Skipped: 0\n\n[INFO] [cobertura:check {execution: default}]\n[INFO] Cobertura 1.9.2 - GNU GPL License (NO WARRANTY) - See COPYRIGHT file\nCobertura: Loaded information on 1 classes.\n\n[ERROR] com.mycompany.samples.App failed check. Line coverage rate of 0.0% is below 80.0%\nProject failed check. Total line coverage rate of 0.0% is below 90.0%\n\n[INFO] ------------------------------------------------------------------------\n[ERROR] BUILD ERROR\n[INFO] ------------------------------------------------------------------------\n[INFO] Coverage check failed. See messages above.\n[INFO] ------------------------------------------------------------------------\n[INFO] For more information, run Maven with the -e switch\n[INFO] ------------------------------------------------------------------------\n[INFO] Total time: 18 seconds\n[INFO] Finished at: Sat Oct 24 21:00:39 CEST 2009\n[INFO] Final Memory: 17M/70M\n[INFO] ------------------------------------------------------------------------\n$ \n</code></pre>\n\n<p>I didn't test with maven 2.0.9, but on my machine, <code>haltOnFailure</code> generates a BUILD ERROR and halt the build. I don't see any differences with your plugin configuration, I can't reproduce the behavior you describe. </p>\n"
},
{
"answer_id": 51155073,
"author": "saman ",
"author_id": 2458613,
"author_profile": "https://Stackoverflow.com/users/2458613",
"pm_score": -1,
"selected": false,
"text": "<p>mvn clean install -Dcobertura.skip=true</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/196721",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10433/"
] |
I'm trying to configure my WAR project build to fail if the line or branch coverage is below given thresholds. I've been using the configuration provided on page 455 of the excellent book [Java Power Tools](http://oreilly.com/catalog/9780596527938/), but with no success. Here's the relevant snippet of my project's Maven 2 POM:
```
<build>
...
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>cobertura-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<check>
<!-- Per-class thresholds -->
<lineRate>80</lineRate>
<branchRate>80</branchRate>
<!-- Project-wide thresholds -->
<totalLineRate>90</totalLineRate>
<totalBranchRate>90</totalBranchRate>
</check>
<executions>
<execution>
<goals>
<goal>clean</goal>
<goal>check</goal>
</goals>
</execution>
<execution>
<id>coverage-tests</id>
<!-- The "verify" phase occurs just before "install" -->
<phase>verify</phase>
<goals>
<goal>clean</goal>
<goal>check</goal>
</goals>
</execution>
</executions>
<instrumentation>
<excludes>
<exclude>au/**/*Constants.*</exclude>
</excludes>
<ignores>
<ignore>au/**/*Constants.*</ignore>
</ignores>
</instrumentation>
</configuration>
</plugin>
...
</plugins>
...
</build>
```
As I say, the coverage report works fine, the problem is that the "install" goal isn't failing as it should if the line or branch coverage is below my specified thresholds. Does anyone have this working, and if so, what does your POM look like and which version of Cobertura and Maven are you using? I'm using Maven 2.0.9 and Cobertura 2.2.
I've tried Googling and reading the Cobertura docs, but no luck (the latter are sparse to say the least).
|
To my knowledge, *if the `<haltOnFailure>` element is set to true and any of the specified checks fails, then Cobertura will cause the build to fail* which is what you're asking for. But actually, this element defaults to `true` if you do not specify it so you **don't have to** add it to your [configuration checks](http://mojo.codehaus.org/cobertura-maven-plugin/usage.html#Check). Failing the build below any coverage threshold is (or at least should be) the default behavior.
**EDIT:** I did some further testing and `haltOnFailure` seems to be working as expected on my environment (Maven 2.2.1. and versions 2.3, 2.2, 2.1 of the plugin i.e. versions 1.9.2, 1.9, 1.8 of cobertura on Linux). I'm updating this answer with the result below.
Actually, I've added an `<execution>` element to my pom. I may be misinterpreting the part of [cobertura:check](http://mojo.codehaus.org/cobertura-maven-plugin/check-mojo.html)'s documentation that says it "*Binds by default to the lifecycle phase: `verify`*" but, without the `<execution>` element, [cobertura:check](http://mojo.codehaus.org/cobertura-maven-plugin/check-mojo.html) wasn't triggered during the *verify* phase of my build. Below the setup I've use for the cobertura-maven-plugin:
```
<project>
...
<build>
...
<plugins>
...
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>cobertura-maven-plugin</artifactId>
<version>2.3</version>
<configuration>
<check>
<!--<haltOnFailure>true</haltOnFailure>--><!-- optional -->
<!-- Per-class thresholds -->
<lineRate>80</lineRate>
<branchRate>80</branchRate>
<!-- Project-wide thresholds -->
<totalLineRate>90</totalLineRate>
<totalBranchRate>90</totalBranchRate>
</check>
</configuration>
<executions>
<execution>
<phase>verify</phase>
<goals>
<!--<goal>clean</goal>--><!-- works if uncommented -->
<goal>check</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
```
I get the following result when running `mvn clean install` on a freshly generated maven project (with `mvn archetype:create`) patched with the plugin configuration mentioned above:
```
$ mvn archetype:create -DgroupId=com.mycompany.samples -DartifactId=cobertura-haltonfailure-testcase
...
$ mvn clean install
[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] Building cobertura-haltonfailure-testcase
[INFO] task-segment: [clean, install]
[INFO] ------------------------------------------------------------------------
[INFO] [clean:clean {execution: default-clean}]
[INFO] Deleting directory /home/pascal/Projects/cobertura-haltonfailure-testcase/target
[INFO] [resources:resources {execution: default-resources}]
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory /home/pascal/Projects/cobertura-haltonfailure-testcase/src/main/resources
[INFO] [compiler:compile {execution: default-compile}]
[INFO] Compiling 1 source file to /home/pascal/Projects/cobertura-haltonfailure-testcase/target/classes
[INFO] [resources:testResources {execution: default-testResources}]
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory /home/pascal/Projects/cobertura-haltonfailure-testcase/src/test/resources
[INFO] [compiler:testCompile {execution: default-testCompile}]
[INFO] Compiling 1 source file to /home/pascal/Projects/cobertura-haltonfailure-testcase/target/test-classes
[INFO] [surefire:test {execution: default-test}]
[INFO] Surefire report directory: /home/pascal/Projects/cobertura-haltonfailure-testcase/target/surefire-reports
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.mycompany.samples.AppTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.09 sec
Results :
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
[INFO] [jar:jar {execution: default-jar}]
[INFO] Building jar: /home/pascal/Projects/cobertura-haltonfailure-testcase/target/cobertura-haltonfailure-testcase-1.0-SNAPSHOT.jar
[INFO] Preparing cobertura:check
[WARNING] Removing: check from forked lifecycle, to prevent recursive invocation.
[INFO] [resources:resources {execution: default-resources}]
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory /home/pascal/Projects/cobertura-haltonfailure-testcase/src/main/resources
[INFO] [compiler:compile {execution: default-compile}]
[INFO] Nothing to compile - all classes are up to date
[INFO] [cobertura:instrument {execution: default}]
[INFO] Cobertura 1.9.2 - GNU GPL License (NO WARRANTY) - See COPYRIGHT file
Instrumenting 1 file to /home/pascal/Projects/cobertura-haltonfailure-testcase/target/generated-classes/cobertura
Cobertura: Saved information on 1 classes.
Instrument time: 337ms
[INFO] Instrumentation was successful.
[INFO] [resources:testResources {execution: default-testResources}]
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory /home/pascal/Projects/cobertura-haltonfailure-testcase/src/test/resources
[INFO] [compiler:testCompile {execution: default-testCompile}]
[INFO] Nothing to compile - all classes are up to date
[INFO] [surefire:test {execution: default-test}]
[INFO] Surefire report directory: /home/pascal/Projects/cobertura-haltonfailure-testcase/target/surefire-reports
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.mycompany.samples.AppTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.098 sec
Results :
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
[INFO] [cobertura:check {execution: default}]
[INFO] Cobertura 1.9.2 - GNU GPL License (NO WARRANTY) - See COPYRIGHT file
Cobertura: Loaded information on 1 classes.
[ERROR] com.mycompany.samples.App failed check. Line coverage rate of 0.0% is below 80.0%
Project failed check. Total line coverage rate of 0.0% is below 90.0%
[INFO] ------------------------------------------------------------------------
[ERROR] BUILD ERROR
[INFO] ------------------------------------------------------------------------
[INFO] Coverage check failed. See messages above.
[INFO] ------------------------------------------------------------------------
[INFO] For more information, run Maven with the -e switch
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 18 seconds
[INFO] Finished at: Sat Oct 24 21:00:39 CEST 2009
[INFO] Final Memory: 17M/70M
[INFO] ------------------------------------------------------------------------
$
```
I didn't test with maven 2.0.9, but on my machine, `haltOnFailure` generates a BUILD ERROR and halt the build. I don't see any differences with your plugin configuration, I can't reproduce the behavior you describe.
|
196,730 |
<p>I need to extract only the 2nd level part of the domain from request.servervariables("HTTP_HOST") what is the best way to do this?</p>
|
[
{
"answer_id": 196752,
"author": "Brian Boatright",
"author_id": 3747,
"author_profile": "https://Stackoverflow.com/users/3747",
"pm_score": 1,
"selected": false,
"text": "<pre><code>If Len(strHostDomain) > 0 Then \n aryDomain = Split(strHostDomain,\".\")\n\n If uBound(aryDomain) >= 1 Then\n str2ndLevel = aryDomain(uBound(aryDomain)-1)\n strTopLevel = aryDomain(uBound(aryDomain)) \n strDomainOnly = str2ndLevel & \".\" & strTopLevel\n End If\nEnd If\n</code></pre>\n\n<p>works for what I need but it doesn't handle .co.uk or other domains that have two parts expected for the top level.</p>\n"
},
{
"answer_id": 196907,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 2,
"selected": true,
"text": "<p>This can be solved through a regular expression.</p>\n\n<p>Since the <code>HTTP_HOST</code> server variable can contain only valid host names, we don't need to care about <em>validating</em> the string, only about finding out its structure. Therefore the regex is kept fairly simple, but would not work reliably in broader contexts.</p>\n\n<p>And the structure is <code>3.2.1</code> for third-, second- and first-level (top-level) domains, respectively. </p>\n\n<p>A top-level domain can have 2+ letters (like <code>.com</code> or <code>.de</code>) or, conceptually, a combination, like <code>.co.uk</code>. This is not <em>technically</em> a TLD anymore, but I take it that you are not really interested in getting <code>co</code> as the second-level domain for many British host names.</p>\n\n<p>So we have</p>\n\n<ul>\n<li>optional: all kinds of things at the start (sub-domain), a dot = <code>^(.*?)\\.?</code></li>\n<li>required: a piece in the middle (second-level domain), a dot = <code>(\\w+)\\.</code></li>\n<li>required: a short bit (or two short bits) at the end = <code>(\\w{2,}(?:\\.\\w{2})?)$</code></li>\n</ul>\n\n<p>These three things will be captured in groups 1, 2, and 3.</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Dim re, matches, match\n\nSet re = New RegExp\n\nre.Pattern = \"^(.*?)\\.?(\\w+)\\.(\\w{2,}(?:\\.\\w{2})?)$\"\n\nSet matches = re.Execute( Request.ServerVariables(\"HTTP_HOST\") )\n\nIf matches.Count = 1 Then\n Set match = matches(0)\n\n ' assuming \"images.res.somedomain.co.uk\"\n Response.Write match.SubMatches(0) & \"<br>\" ' will be \"images.res\"\n Response.Write match.SubMatches(1) & \"<br>\" ' will be \"somedomain\"\n Response.Write match.SubMatches(2) & \"<br>\" ' will be \"co.uk\"\n\n ' assuming \"somedomain.com\"\n Response.Write match.SubMatches(0) & \"<br>\" ' will be \"\"\n Response.Write match.SubMatches(1) & \"<br>\" ' will be \"somedomain\"\n Response.Write match.SubMatches(2) & \"<br>\" ' will be \"com\"\nElse\n ' You have an IP address in HTTP_HOST\nEnd If\n</code></pre>\n"
},
{
"answer_id": 207164,
"author": "defeated",
"author_id": 16997,
"author_profile": "https://Stackoverflow.com/users/16997",
"pm_score": -1,
"selected": false,
"text": "<p>Since HTTP_HOST header only returns the domain (excluding any subdomains), you should be able to do the following:</p>\n\n<pre><code>'example: sample.com\n'example: sample.co.uk\nhost = split(request.serverVariables(\"HTTP_HOST\"), \".\")\nhost(0) = \"\" 'clear the \"sample\" part\n\nextension = join(host, \".\") 'put it back together, \".com\" or \".co.uk\"\n</code></pre>\n"
},
{
"answer_id": 1571451,
"author": "Haakon",
"author_id": 190500,
"author_profile": "https://Stackoverflow.com/users/190500",
"pm_score": 0,
"selected": false,
"text": "<p>Just checked the difference on a subdomain off my rented serverspace and both http_host and server_name reported back the domain name including the subdomain.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/196730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3747/"
] |
I need to extract only the 2nd level part of the domain from request.servervariables("HTTP\_HOST") what is the best way to do this?
|
This can be solved through a regular expression.
Since the `HTTP_HOST` server variable can contain only valid host names, we don't need to care about *validating* the string, only about finding out its structure. Therefore the regex is kept fairly simple, but would not work reliably in broader contexts.
And the structure is `3.2.1` for third-, second- and first-level (top-level) domains, respectively.
A top-level domain can have 2+ letters (like `.com` or `.de`) or, conceptually, a combination, like `.co.uk`. This is not *technically* a TLD anymore, but I take it that you are not really interested in getting `co` as the second-level domain for many British host names.
So we have
* optional: all kinds of things at the start (sub-domain), a dot = `^(.*?)\.?`
* required: a piece in the middle (second-level domain), a dot = `(\w+)\.`
* required: a short bit (or two short bits) at the end = `(\w{2,}(?:\.\w{2})?)$`
These three things will be captured in groups 1, 2, and 3.
```vb
Dim re, matches, match
Set re = New RegExp
re.Pattern = "^(.*?)\.?(\w+)\.(\w{2,}(?:\.\w{2})?)$"
Set matches = re.Execute( Request.ServerVariables("HTTP_HOST") )
If matches.Count = 1 Then
Set match = matches(0)
' assuming "images.res.somedomain.co.uk"
Response.Write match.SubMatches(0) & "<br>" ' will be "images.res"
Response.Write match.SubMatches(1) & "<br>" ' will be "somedomain"
Response.Write match.SubMatches(2) & "<br>" ' will be "co.uk"
' assuming "somedomain.com"
Response.Write match.SubMatches(0) & "<br>" ' will be ""
Response.Write match.SubMatches(1) & "<br>" ' will be "somedomain"
Response.Write match.SubMatches(2) & "<br>" ' will be "com"
Else
' You have an IP address in HTTP_HOST
End If
```
|
196,732 |
<p>I've inherited a piece of code with a snippet which empties the database as follows:</p>
<pre><code>dbmopen (%db,"file.db",0666);
foreach $key (keys %db) {
delete $db{$key};
}
dbmclose (%db);
</code></pre>
<p>This is usually okay but sometimes the database grows very large before this cleanup code is called and it's usually when a user wants to do something important.</p>
<p>Is there a better way of doing this?</p>
|
[
{
"answer_id": 196816,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 3,
"selected": false,
"text": "<p>Actually, a workmate has pointed me to a solution. You can apparently do:</p>\n\n<pre><code>dbmopen (%db,\"file.db\",0666);\n%db = ();\ndbmclose (%db);\n</code></pre>\n\n<p>which clears out the hash before closing the database.</p>\n"
},
{
"answer_id": 196884,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 3,
"selected": false,
"text": "<p>There was another answer here which has disappeared for some reason, yet it was likely to be faster, so I'm reposting it (not sure why it was deleted). It involves unlinking the file to delete it then just recreating a blank database file as follows:</p>\n\n<pre><code>unlink (\"file.db\");\ndbmopen (%db,\"file.db\",0666);\ndbmclose (%db);\n</code></pre>\n"
},
{
"answer_id": 197696,
"author": "brian d foy",
"author_id": 2766176,
"author_profile": "https://Stackoverflow.com/users/2766176",
"pm_score": 4,
"selected": true,
"text": "<p>You can just delete the file:</p>\n\n<pre><code>unlink $file;\n</code></pre>\n\n<p>Since your third argument to <a href=\"http://perldoc.perl.org/functions/dbmopen.html\" rel=\"nofollow noreferrer\">dbmopen</a> is a file mode and not <code>undef</code>, <code>dbmopen</code> will recreate the file the next time it's called:</p>\n\n<pre><code>dbmopen my %db, $file, 0666;\n</code></pre>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/196732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14860/"
] |
I've inherited a piece of code with a snippet which empties the database as follows:
```
dbmopen (%db,"file.db",0666);
foreach $key (keys %db) {
delete $db{$key};
}
dbmclose (%db);
```
This is usually okay but sometimes the database grows very large before this cleanup code is called and it's usually when a user wants to do something important.
Is there a better way of doing this?
|
You can just delete the file:
```
unlink $file;
```
Since your third argument to [dbmopen](http://perldoc.perl.org/functions/dbmopen.html) is a file mode and not `undef`, `dbmopen` will recreate the file the next time it's called:
```
dbmopen my %db, $file, 0666;
```
|
196,733 |
<p>I have code like this:</p>
<pre><code>class RetInterface {...}
class Ret1: public RetInterface {...}
class AInterface
{
public:
virtual boost::shared_ptr<RetInterface> get_r() const = 0;
...
};
class A1: public AInterface
{
public:
boost::shared_ptr<Ret1> get_r() const {...}
...
};
</code></pre>
<p><strong>This code does not compile.</strong></p>
<p>In visual studio it raises</p>
<blockquote>
<p>C2555: overriding virtual function return type differs and is not
covariant</p>
</blockquote>
<p>If I do not use <code>boost::shared_ptr</code> but return raw pointers, the code compiles (I understand this is due to <a href="http://en.wikipedia.org/wiki/Parameter_covariance#C.2B.2B" rel="noreferrer">covariant return types</a> in C++). I can see the problem is because <code>boost::shared_ptr</code> of <code>Ret1</code> is not derived from <code>boost::shared_ptr</code> of <code>RetInterface</code>. But I want to return <code>boost::shared_ptr</code> of <code>Ret1</code> for use in other classes, else I must cast the returned value after the return. </p>
<ol>
<li>Am I doing something wrong? </li>
<li>If not, why is the language like this - it should be extensible to handle conversion between smart pointers in this scenario? Is there a desirable workaround?</li>
</ol>
|
[
{
"answer_id": 196744,
"author": "Mr Fooz",
"author_id": 25050,
"author_profile": "https://Stackoverflow.com/users/25050",
"pm_score": 2,
"selected": false,
"text": "<p>You can't change return types (for non-pointer, non-reference return types) when overloading methods in C++. <code>A1::get_r</code> must return a <code>boost::shared_ptr<RetInterface></code>.</p>\n\n<p>Anthony Williams has a nice comprehensive <a href=\"https://stackoverflow.com/a/197157/25050\">answer</a>.</p>\n"
},
{
"answer_id": 196753,
"author": "Mark Ransom",
"author_id": 5987,
"author_profile": "https://Stackoverflow.com/users/5987",
"pm_score": -1,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/questions/196733/smart-pointer-and-virtual#196744\">Mr Fooz </a> answered part 1 of your question. Part 2, it works this way because the compiler doesn't know if it will be calling AInterface::get_r or A1::get_r at compile time - it needs to know what return value it's going to get, so it insists on both methods returning the same type. This is part of the C++ specification.</p>\n\n<p>For the workaround, if A1::get_r returns a pointer to RetInterface, the virtual methods in RetInterface will still work as expected, and the proper object will be deleted when the pointer is destroyed. There's no need for different return types.</p>\n"
},
{
"answer_id": 197157,
"author": "Anthony Williams",
"author_id": 5597,
"author_profile": "https://Stackoverflow.com/users/5597",
"pm_score": 6,
"selected": true,
"text": "<p>Firstly, this is indeed how it works in C++: the return type of a virtual function in a derived class must be the same as in the base class. There is the special exception that a function that returns a reference/pointer to some class X can be overridden by a function that returns a reference/pointer to a class that derives from X, but as you note this doesn't allow for <em>smart</em> pointers (such as <code>shared_ptr</code>), just for plain pointers.</p>\n\n<p>If your interface <code>RetInterface</code> is sufficiently comprehensive, then you won't need to know the actual returned type in the calling code. In general it doesn't make sense anyway: the reason <code>get_r</code> is a <code>virtual</code> function in the first place is because you will be calling it through a pointer or reference to the base class <code>AInterface</code>, in which case you can't know what type the derived class would return. If you are calling this with an actual <code>A1</code> reference, you can just create a separate <code>get_r1</code> function in <code>A1</code> that does what you need.</p>\n\n<pre><code>class A1: public AInterface\n{\n public:\n boost::shared_ptr<RetInterface> get_r() const\n {\n return get_r1();\n }\n boost::shared_ptr<Ret1> get_r1() const {...}\n ...\n};\n</code></pre>\n\n<p>Alternatively, you can use the visitor pattern or something like my <a href=\"http://www.ddj.com/dept/cpp/184429055\" rel=\"noreferrer\">Dynamic Double Dispatch</a> technique to pass a callback in to the returned object which can then invoke the callback with the correct type.</p>\n"
},
{
"answer_id": 970078,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>maybe you could use an out parameter to get around \"covariance with returned boost shared_ptrs. </p>\n\n<pre><code> void get_r_to(boost::shared_ptr<RetInterface>& ) ...\n</code></pre>\n\n<p>since I suspect a caller can drop in a more refined shared_ptr type as argument.</p>\n"
},
{
"answer_id": 16069528,
"author": "morabot",
"author_id": 2292452,
"author_profile": "https://Stackoverflow.com/users/2292452",
"pm_score": 1,
"selected": false,
"text": "<p>What about this solution:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>template<typename Derived, typename Base>\nclass SharedCovariant : public shared_ptr<Base>\n{\npublic:\n\ntypedef Base BaseOf;\n\nSharedCovariant(shared_ptr<Base> & container) :\n shared_ptr<Base>(container)\n{\n}\n\nshared_ptr<Derived> operator ->()\n{\n return boost::dynamic_pointer_cast<Derived>(*this);\n}\n};\n</code></pre>\n\n<p>e.g:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>struct A {};\n\nstruct B : A {};\n\nstruct Test\n{\n shared_ptr<A> get() {return a_; }\n\n shared_ptr<A> a_;\n};\n\ntypedef SharedCovariant<B,A> SharedBFromA;\n\nstruct TestDerived : Test\n{\n SharedBFromA get() { return a_; }\n};\n</code></pre>\n"
},
{
"answer_id": 32529006,
"author": "Grégory MALLET",
"author_id": 4512497,
"author_profile": "https://Stackoverflow.com/users/4512497",
"pm_score": 1,
"selected": false,
"text": "<p>Here is my attempt : </p>\n\n<pre><code>template<class T>\nclass Child : public T\n{\npublic:\n typedef T Parent;\n};\n\ntemplate<typename _T>\nclass has_parent\n{\nprivate:\n typedef char One;\n typedef struct { char array[2]; } Two;\n\n template<typename _C>\n static One test(typename _C::Parent *);\n template<typename _C>\n static Two test(...);\n\npublic:\n enum { value = (sizeof(test<_T>(nullptr)) == sizeof(One)) };\n};\n\nclass A\n{\npublic :\n virtual void print() = 0;\n};\n\nclass B : public Child<A>\n{\npublic:\n void print() override\n {\n printf(\"toto \\n\");\n }\n};\n\ntemplate<class T, bool hasParent = has_parent<T>::value>\nclass ICovariantSharedPtr;\n\ntemplate<class T>\nclass ICovariantSharedPtr<T, true> : public ICovariantSharedPtr<typename T::Parent>\n{\npublic:\n T * get() override = 0;\n};\n\ntemplate<class T>\nclass ICovariantSharedPtr<T, false>\n{\npublic:\n virtual T * get() = 0;\n};\n\ntemplate<class T>\nclass CovariantSharedPtr : public ICovariantSharedPtr<T>\n{\npublic:\n CovariantSharedPtr(){}\n\n CovariantSharedPtr(std::shared_ptr<T> a_ptr) : m_ptr(std::move(a_ptr)){}\n\n T * get() final\n {\n return m_ptr.get();\n }\nprivate:\n std::shared_ptr<T> m_ptr;\n};\n</code></pre>\n\n<p>And a little example : </p>\n\n<pre><code>class UseA\n{\npublic:\n virtual ICovariantSharedPtr<A> & GetPtr() = 0;\n};\n\nclass UseB : public UseA\n{\npublic:\n CovariantSharedPtr<B> & GetPtr() final\n {\n return m_ptrB;\n }\nprivate:\n CovariantSharedPtr<B> m_ptrB = std::make_shared<B>();\n};\n\nint _tmain(int argc, _TCHAR* argv[])\n{\n UseB b;\n UseA & a = b;\n a.GetPtr().get()->print();\n}\n</code></pre>\n\n<p>Explanations : </p>\n\n<p>This solution implies meta-progamming and to modify the classes used in covariant smart pointers. </p>\n\n<p>The simple template struct <code>Child</code> is here to bind the type <code>Parent</code> and inheritance. Any class inheriting from <code>Child<T></code> will inherit from <code>T</code> and define <code>T</code> as <code>Parent</code>. The classes used in covariant smart pointers needs this type to be defined.</p>\n\n<p>The class <code>has_parent</code> is used to detect at compile time if a class defines the type <code>Parent</code> or not. This part is not mine, I used the same code as to detect if a method exists (<a href=\"https://stackoverflow.com/questions/257288/is-it-possible-to-write-a-c-template-to-check-for-a-functions-existence\">see here</a>)</p>\n\n<p>As we want covariance with smart pointers, we want our smart pointers to mimic the existing class architecture. It's easier to explain how it works in the example.</p>\n\n<p>When a <code>CovariantSharedPtr<B></code> is defined, it inherits from <code>ICovariantSharedPtr<B></code>, which is interpreted as <code>ICovariantSharedPtr<B, has_parent<B>::value></code>. As <code>B</code> inherits from <code>Child<A></code>, <code>has_parent<B>::value</code> is true, so <code>ICovariantSharedPtr<B></code> is <code>ICovariantSharedPtr<B, true></code> and inherits from <code>ICovariantSharedPtr<B::Parent></code> which is <code>ICovariantSharedPtr<A></code>. As <code>A</code> has no <code>Parent</code> defined, <code>has_parent<A>::value</code> is false, <code>ICovariantSharedPtr<A></code> is <code>ICovariantSharedPtr<A, false></code> and inherits from nothing. </p>\n\n<p>The main point is as <code>B</code>inherits from <code>A</code>, we have <code>ICovariantSharedPtr<B></code>inheriting from <code>ICovariantSharedPtr<A></code>. So any method returning a pointer or a reference on <code>ICovariantSharedPtr<A></code> can be overloaded by a method returning the same on <code>ICovariantSharedPtr<B></code>.</p>\n"
},
{
"answer_id": 56542651,
"author": "Bruce Adams",
"author_id": 1569204,
"author_profile": "https://Stackoverflow.com/users/1569204",
"pm_score": 3,
"selected": false,
"text": "<p>There is a neat solution posted in <a href=\"https://www.fluentcpp.com/2017/09/12/how-to-return-a-smart-pointer-and-use-covariance/\" rel=\"nofollow noreferrer\">this blog post</a> (from Raoul Borges)</p>\n<p>An excerpt of the bit prior to adding support for mulitple inheritance and abstract methods is:</p>\n<pre><code>template <typename Derived, typename Base>\nclass clone_inherit<Derived, Base> : public Base\n{\npublic:\n std::unique_ptr<Derived> clone() const\n {\n return std::unique_ptr<Derived>(static_cast<Derived *>(this->clone_impl()));\n }\n \nprivate:\n virtual clone_inherit * clone_impl() const override\n {\n return new Derived(*this);\n }\n};\n\nclass concrete: public clone_inherit<concrete, cloneable>\n{\n};\n\nint main()\n{\n std::unique_ptr<concrete> c = std::make_unique<concrete>();\n std::unique_ptr<concrete> cc = c->clone();\n \n cloneable * p = c.get();\n std::unique_ptr<clonable> pp = p->clone();\n}\n</code></pre>\n<p>I would encourage reading the full article. Its simply written and well explained.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/196733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19501/"
] |
I have code like this:
```
class RetInterface {...}
class Ret1: public RetInterface {...}
class AInterface
{
public:
virtual boost::shared_ptr<RetInterface> get_r() const = 0;
...
};
class A1: public AInterface
{
public:
boost::shared_ptr<Ret1> get_r() const {...}
...
};
```
**This code does not compile.**
In visual studio it raises
>
> C2555: overriding virtual function return type differs and is not
> covariant
>
>
>
If I do not use `boost::shared_ptr` but return raw pointers, the code compiles (I understand this is due to [covariant return types](http://en.wikipedia.org/wiki/Parameter_covariance#C.2B.2B) in C++). I can see the problem is because `boost::shared_ptr` of `Ret1` is not derived from `boost::shared_ptr` of `RetInterface`. But I want to return `boost::shared_ptr` of `Ret1` for use in other classes, else I must cast the returned value after the return.
1. Am I doing something wrong?
2. If not, why is the language like this - it should be extensible to handle conversion between smart pointers in this scenario? Is there a desirable workaround?
|
Firstly, this is indeed how it works in C++: the return type of a virtual function in a derived class must be the same as in the base class. There is the special exception that a function that returns a reference/pointer to some class X can be overridden by a function that returns a reference/pointer to a class that derives from X, but as you note this doesn't allow for *smart* pointers (such as `shared_ptr`), just for plain pointers.
If your interface `RetInterface` is sufficiently comprehensive, then you won't need to know the actual returned type in the calling code. In general it doesn't make sense anyway: the reason `get_r` is a `virtual` function in the first place is because you will be calling it through a pointer or reference to the base class `AInterface`, in which case you can't know what type the derived class would return. If you are calling this with an actual `A1` reference, you can just create a separate `get_r1` function in `A1` that does what you need.
```
class A1: public AInterface
{
public:
boost::shared_ptr<RetInterface> get_r() const
{
return get_r1();
}
boost::shared_ptr<Ret1> get_r1() const {...}
...
};
```
Alternatively, you can use the visitor pattern or something like my [Dynamic Double Dispatch](http://www.ddj.com/dept/cpp/184429055) technique to pass a callback in to the returned object which can then invoke the callback with the correct type.
|
196,754 |
<p>I've seen some horrific code written in Perl, but I can't make head nor tail of this one:</p>
<pre><code>select((select(s),$|=1)[0])
</code></pre>
<p>It's in some networking code that we use to communicate with a server and I assume it's something to do with buffering (since it sets <code>$|</code>).</p>
<p>But I can't figure out why there's multiple <code>select</code> calls or the array reference. Can anyone help me out?</p>
|
[
{
"answer_id": 196768,
"author": "Dan",
"author_id": 17121,
"author_profile": "https://Stackoverflow.com/users/17121",
"pm_score": 7,
"selected": true,
"text": "<p>It's a nasty little idiom for setting autoflush on a filehandle other than STDOUT. </p>\n\n<p><code>select()</code> takes the supplied filehandle and (basically) replaces STDOUT with it, and it returns the old filehandle when it's done. </p>\n\n<p>So <code>(select($s),$|=1)</code> redirects the filehandle (remember <code>select</code> returns the old one), and sets autoflush (<code>$| = 1</code>). It does this in a list (<code>(...)[0]</code>) and returns the first value (which is the result of the <code>select</code> call - the original STDOUT), and then passes <em>that</em> back into another <code>select</code> to reinstate the original STDOUT filehandle. Phew.</p>\n\n<p>But now you understand it (well, maybe ;)), do this instead:</p>\n\n<pre><code>use IO::Handle;\n$fh->autoflush;\n</code></pre>\n"
},
{
"answer_id": 196769,
"author": "Andy Lester",
"author_id": 8454,
"author_profile": "https://Stackoverflow.com/users/8454",
"pm_score": 3,
"selected": false,
"text": "<p>It's overly clever code for turning on buffer flushing on handle <code>s</code> and then re-selecting the current handle.</p>\n\n<p>See <code>perldoc -f select</code> for more.</p>\n"
},
{
"answer_id": 197687,
"author": "brian d foy",
"author_id": 2766176,
"author_profile": "https://Stackoverflow.com/users/2766176",
"pm_score": 5,
"selected": false,
"text": "<p>The way to figure out any code is to pick it apart. You know that stuff inside parentheses happens before stuff outside. This is the same way you'd figuring out what code is doing in other languages.</p>\n\n<p>The first bit is then:</p>\n\n<pre><code>( select(s), $|=1 )\n</code></pre>\n\n<p>That list has two elements, which are the results of two operations: one to select the <code>s</code> filehandle as the default then one to set <code>$|</code> to a true value. The <code>$|</code> is one of the per-filehandle variables which only apply to the currently selected filehandle (see <a href=\"http://www.effectiveperlprogramming.com/2010/09/understand-global-variables/\" rel=\"nofollow noreferrer\">Understand global variables</a> at <i>The Effective Perler</i>). In the end, you have a list of two items: the previous default filehandle (the result of <code>select</code>), and 1.</p>\n\n<p>The next part is a literal list slice to pull out the item in index 0:</p>\n\n<pre><code>( PREVIOUS_DEFAULT, 1 )[0]\n</code></pre>\n\n<p>The result of that is the single item that is previous default filehandle.</p>\n\n<p>The next part takes the result of the slice and uses it as the argument to another call to <code>select</code></p>\n\n<pre><code> select( PREVIOUS_DEFAULT );\n</code></pre>\n\n<p>So, in effect, you've set <code>$|</code> on a filehandle and ended up back where you started with the default filehandle.</p>\n"
},
{
"answer_id": 200096,
"author": "Aristotle Pagaltzis",
"author_id": 9410,
"author_profile": "https://Stackoverflow.com/users/9410",
"pm_score": 3,
"selected": false,
"text": "<p>In another venue, I once proposed that a more comprehensible version would be thus:</p>\n\n<pre><code>for ( select $fh ) { $| = 1; select $_ }\n</code></pre>\n\n<p>This preserves the compact idiom’s sole advantage that no variable needs be declared in the surrounding scope.</p>\n\n<p>Or if you’re not comfortable with <code>$_</code>, you can write it like this:</p>\n\n<pre><code>for my $prevfh ( select $fh ) { $| = 1; select $prevfh }\n</code></pre>\n\n<p>The scope of <code>$prevfh</code> is limited to the <code>for</code> block. (But if you write Perl you really have no excuse to be skittish about <code>$_</code>.)</p>\n"
},
{
"answer_id": 2287544,
"author": "ghostdog74",
"author_id": 131527,
"author_profile": "https://Stackoverflow.com/users/131527",
"pm_score": 2,
"selected": false,
"text": "<p>please check <a href=\"http://perldoc.perl.org/functions/select.html\" rel=\"nofollow noreferrer\">perldoc -f select</a>. For the meaning of <code>$|</code>, please check <a href=\"http://perldoc.perl.org/perlvar.html\" rel=\"nofollow noreferrer\">perldoc perlvar</a></p>\n"
},
{
"answer_id": 2287567,
"author": "kennytm",
"author_id": 224671,
"author_profile": "https://Stackoverflow.com/users/224671",
"pm_score": 4,
"selected": false,
"text": "<pre><code>select($fh)\n</code></pre>\n\n<p>Select a new default file handle. See <a href=\"http://perldoc.perl.org/functions/select.html\" rel=\"noreferrer\">http://perldoc.perl.org/functions/select.html</a></p>\n\n<pre><code>(select($fh), $|=1)\n</code></pre>\n\n<p>Turn on autoflush. See <a href=\"http://perldoc.perl.org/perlvar.html\" rel=\"noreferrer\">http://perldoc.perl.org/perlvar.html</a></p>\n\n<pre><code>(select($fh), $|=1)[0]\n</code></pre>\n\n<p>Return the first value of this tuple.</p>\n\n<pre><code>select((select($fh), $|=1)[0])\n</code></pre>\n\n<p><code>select</code> it, i.e. restore the old default file handle.</p>\n\n<hr>\n\n<p>Equivalent to</p>\n\n<pre><code>$oldfh = select($fh);\n$| = 1;\nselect($oldfh);\n</code></pre>\n\n<p>which means</p>\n\n<pre><code>use IO::Handle;\n$fh->autoflush(1);\n</code></pre>\n\n<p>as demonstrated in the perldoc page.</p>\n"
},
{
"answer_id": 2287632,
"author": "Alexandr Ciornii",
"author_id": 13467,
"author_profile": "https://Stackoverflow.com/users/13467",
"pm_score": 2,
"selected": false,
"text": "<p>It is overoptimization to skip loading IO::Handle.</p>\n\n<pre><code>use IO::Handle;\n$fh->autoflush(1);\n</code></pre>\n\n<p>is much more readable.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/196754",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14860/"
] |
I've seen some horrific code written in Perl, but I can't make head nor tail of this one:
```
select((select(s),$|=1)[0])
```
It's in some networking code that we use to communicate with a server and I assume it's something to do with buffering (since it sets `$|`).
But I can't figure out why there's multiple `select` calls or the array reference. Can anyone help me out?
|
It's a nasty little idiom for setting autoflush on a filehandle other than STDOUT.
`select()` takes the supplied filehandle and (basically) replaces STDOUT with it, and it returns the old filehandle when it's done.
So `(select($s),$|=1)` redirects the filehandle (remember `select` returns the old one), and sets autoflush (`$| = 1`). It does this in a list (`(...)[0]`) and returns the first value (which is the result of the `select` call - the original STDOUT), and then passes *that* back into another `select` to reinstate the original STDOUT filehandle. Phew.
But now you understand it (well, maybe ;)), do this instead:
```
use IO::Handle;
$fh->autoflush;
```
|
196,755 |
<p>Given a string of keywords, such as "Python best practices", I would like to obtain the first 10 Stack Overflow questions that contain that keywords, sorted by relevance (?), say from a Python script. My goal is to end up with a list of tuples (title, URL).</p>
<p>How can I accomplish this? Would you consider querying Google instead? (How would you do it from Python?)</p>
|
[
{
"answer_id": 196758,
"author": "Xenph Yan",
"author_id": 264,
"author_profile": "https://Stackoverflow.com/users/264",
"pm_score": 1,
"selected": false,
"text": "<p>You could screen scrape the returned HTML from a valid HTTP request. But that would result in bad karma, and the loss of the ability to enjoy a good night's sleep.</p>\n"
},
{
"answer_id": 196763,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 3,
"selected": false,
"text": "<p>Since Stackoverflow already has this feature you just need to get the contents of the search results page and scrape the information you need. Here is the URL for a search by relevance:</p>\n\n<blockquote>\n <p><a href=\"https://stackoverflow.com/search?q=python+best+practices&sort=relevance\">https://stackoverflow.com/search?q=python+best+practices&sort=relevance</a></p>\n</blockquote>\n\n<p>If you View Source, you'll see that the information you need for each question is on a line like this:</p>\n\n<pre><code><h3><a href=\"/questions/5119/what-are-the-best-rss-feeds-for-programmersdevelopers#5150\" class=\"answer-title\">What are the best RSS feeds for programmers/developers?</a></h3>\n</code></pre>\n\n<p>So you should be able to get the first ten by doing a regex search for a string of that form.</p>\n"
},
{
"answer_id": 196780,
"author": "mhawke",
"author_id": 21945,
"author_profile": "https://Stackoverflow.com/users/21945",
"pm_score": 2,
"selected": false,
"text": "<p>Suggest that a REST API be added to SO. <a href=\"https://web.archive.org/web/20090219112537/http://stackoverflow.uservoice.com:80/\" rel=\"nofollow noreferrer\">http://stackoverflow.uservoice.com/</a></p>\n"
},
{
"answer_id": 196800,
"author": "pookleblinky",
"author_id": 1582786,
"author_profile": "https://Stackoverflow.com/users/1582786",
"pm_score": 0,
"selected": false,
"text": "<p>I would just use Pycurl to concatenate the search terms onto the query uri.</p>\n"
},
{
"answer_id": 196851,
"author": "itsadok",
"author_id": 7581,
"author_profile": "https://Stackoverflow.com/users/7581",
"pm_score": 4,
"selected": true,
"text": "<pre><code>>>> from urllib import urlencode\n>>> params = urlencode({'q': 'python best practices', 'sort': 'relevance'})\n>>> params\n'q=python+best+practices&sort=relevance'\n>>> from urllib2 import urlopen\n>>> html = urlopen(\"http://stackoverflow.com/search?%s\" % params).read()\n>>> import re\n>>> links = re.findall(r'<h3><a href=\"([^\"]*)\" class=\"answer-title\">([^<]*)</a></h3>', html)\n>>> links\n[('/questions/5119/what-are-the-best-rss-feeds-for-programmersdevelopers#5150', 'What are the best RSS feeds for programmers/developers?'), ('/questions/3088/best-ways-to-teach-a-beginner-to-program#13185', 'Best ways to teach a beginner to program?'), ('/questions/13678/textual-versus-graphical-programming-languages#13886', 'Textual versus Graphical Programming Languages'), ('/questions/58968/what-defines-pythonian-or-pythonic#59877', 'What defines &#8220;pythonian&#8221; or &#8220;pythonic&#8221;?'), ('/questions/592/cxoracle-how-do-i-access-oracle-from-python#62392', 'cx_Oracle - How do I access Oracle from Python? '), ('/questions/7170/recommendation-for-straight-forward-python-frameworks#83608', 'Recommendation for straight-forward python frameworks'), ('/questions/100732/why-is-if-not-someobj-better-than-if-someobj-none-in-python#100903', 'Why is if not someobj: better than if someobj == None: in Python?'), ('/questions/132734/presentations-on-switching-from-perl-to-python#134006', 'Presentations on switching from Perl to Python'), ('/questions/136977/after-c-python-or-java#138442', 'After C++ - Python or Java?')]\n>>> from urlparse import urljoin\n>>> links = [(urljoin('http://stackoverflow.com/', url), title) for url,title in links]\n>>> links\n[('http://stackoverflow.com/questions/5119/what-are-the-best-rss-feeds-for-programmersdevelopers#5150', 'What are the best RSS feeds for programmers/developers?'), ('http://stackoverflow.com/questions/3088/best-ways-to-teach-a-beginner-to-program#13185', 'Best ways to teach a beginner to program?'), ('http://stackoverflow.com/questions/13678/textual-versus-graphical-programming-languages#13886', 'Textual versus Graphical Programming Languages'), ('http://stackoverflow.com/questions/58968/what-defines-pythonian-or-pythonic#59877', 'What defines &#8220;pythonian&#8221; or &#8220;pythonic&#8221;?'), ('http://stackoverflow.com/questions/592/cxoracle-how-do-i-access-oracle-from-python#62392', 'cx_Oracle - How do I access Oracle from Python? '), ('http://stackoverflow.com/questions/7170/recommendation-for-straight-forward-python-frameworks#83608', 'Recommendation for straight-forward python frameworks'), ('http://stackoverflow.com/questions/100732/why-is-if-not-someobj-better-than-if-someobj-none-in-python#100903', 'Why is if not someobj: better than if someobj == None: in Python?'), ('http://stackoverflow.com/questions/132734/presentations-on-switching-from-perl-to-python#134006', 'Presentations on switching from Perl to Python'), ('http://stackoverflow.com/questions/136977/after-c-python-or-java#138442', 'After C++ - Python or Java?')]\n</code></pre>\n\n<p>Converting this to a function should be trivial.</p>\n\n<p><strong>EDIT</strong>: Heck, I'll do it...</p>\n\n<pre><code>def get_stackoverflow(query):\n import urllib, urllib2, re, urlparse\n params = urllib.urlencode({'q': query, 'sort': 'relevance'})\n html = urllib2.urlopen(\"http://stackoverflow.com/search?%s\" % params).read()\n links = re.findall(r'<h3><a href=\"([^\"]*)\" class=\"answer-title\">([^<]*)</a></h3>', html)\n links = [(urlparse.urljoin('http://stackoverflow.com/', url), title) for url,title in links]\n\n return links\n</code></pre>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/196755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18770/"
] |
Given a string of keywords, such as "Python best practices", I would like to obtain the first 10 Stack Overflow questions that contain that keywords, sorted by relevance (?), say from a Python script. My goal is to end up with a list of tuples (title, URL).
How can I accomplish this? Would you consider querying Google instead? (How would you do it from Python?)
|
```
>>> from urllib import urlencode
>>> params = urlencode({'q': 'python best practices', 'sort': 'relevance'})
>>> params
'q=python+best+practices&sort=relevance'
>>> from urllib2 import urlopen
>>> html = urlopen("http://stackoverflow.com/search?%s" % params).read()
>>> import re
>>> links = re.findall(r'<h3><a href="([^"]*)" class="answer-title">([^<]*)</a></h3>', html)
>>> links
[('/questions/5119/what-are-the-best-rss-feeds-for-programmersdevelopers#5150', 'What are the best RSS feeds for programmers/developers?'), ('/questions/3088/best-ways-to-teach-a-beginner-to-program#13185', 'Best ways to teach a beginner to program?'), ('/questions/13678/textual-versus-graphical-programming-languages#13886', 'Textual versus Graphical Programming Languages'), ('/questions/58968/what-defines-pythonian-or-pythonic#59877', 'What defines “pythonian” or “pythonic”?'), ('/questions/592/cxoracle-how-do-i-access-oracle-from-python#62392', 'cx_Oracle - How do I access Oracle from Python? '), ('/questions/7170/recommendation-for-straight-forward-python-frameworks#83608', 'Recommendation for straight-forward python frameworks'), ('/questions/100732/why-is-if-not-someobj-better-than-if-someobj-none-in-python#100903', 'Why is if not someobj: better than if someobj == None: in Python?'), ('/questions/132734/presentations-on-switching-from-perl-to-python#134006', 'Presentations on switching from Perl to Python'), ('/questions/136977/after-c-python-or-java#138442', 'After C++ - Python or Java?')]
>>> from urlparse import urljoin
>>> links = [(urljoin('http://stackoverflow.com/', url), title) for url,title in links]
>>> links
[('http://stackoverflow.com/questions/5119/what-are-the-best-rss-feeds-for-programmersdevelopers#5150', 'What are the best RSS feeds for programmers/developers?'), ('http://stackoverflow.com/questions/3088/best-ways-to-teach-a-beginner-to-program#13185', 'Best ways to teach a beginner to program?'), ('http://stackoverflow.com/questions/13678/textual-versus-graphical-programming-languages#13886', 'Textual versus Graphical Programming Languages'), ('http://stackoverflow.com/questions/58968/what-defines-pythonian-or-pythonic#59877', 'What defines “pythonian” or “pythonic”?'), ('http://stackoverflow.com/questions/592/cxoracle-how-do-i-access-oracle-from-python#62392', 'cx_Oracle - How do I access Oracle from Python? '), ('http://stackoverflow.com/questions/7170/recommendation-for-straight-forward-python-frameworks#83608', 'Recommendation for straight-forward python frameworks'), ('http://stackoverflow.com/questions/100732/why-is-if-not-someobj-better-than-if-someobj-none-in-python#100903', 'Why is if not someobj: better than if someobj == None: in Python?'), ('http://stackoverflow.com/questions/132734/presentations-on-switching-from-perl-to-python#134006', 'Presentations on switching from Perl to Python'), ('http://stackoverflow.com/questions/136977/after-c-python-or-java#138442', 'After C++ - Python or Java?')]
```
Converting this to a function should be trivial.
**EDIT**: Heck, I'll do it...
```
def get_stackoverflow(query):
import urllib, urllib2, re, urlparse
params = urllib.urlencode({'q': query, 'sort': 'relevance'})
html = urllib2.urlopen("http://stackoverflow.com/search?%s" % params).read()
links = re.findall(r'<h3><a href="([^"]*)" class="answer-title">([^<]*)</a></h3>', html)
links = [(urlparse.urljoin('http://stackoverflow.com/', url), title) for url,title in links]
return links
```
|
196,771 |
<p>I have a PHP application which needs to output a python script, more specifically a bunch of variable assignment statements, eg.</p>
<pre><code>subject_prefix = 'This String From User Input'
msg_footer = """This one too."""
</code></pre>
<p>The contents of subject_prefix et al need to be written to take user input; as such, I need to escape the contents of the strings. Writing something like the following isn't going to cut it; we're stuffed as soon as someone uses a quote or newline or anything else that I'm not aware of that could be hazardous:</p>
<pre><code>echo "subject_prefix = '".$subject_prefix."'\n";
</code></pre>
<p>So. Any ideas?</p>
<p>(Rewriting the app in Python isn't possible due to time constraints. :P )</p>
<p><strong>Edit, years later:</strong></p>
<p>This was for integration between a web-app (written in PHP) and Mailman (written in Python). I couldn't modify the install of the latter, so I needed to come up with a way to talk in its language to manage its configuration.</p>
<p>This was also a <em>really</em> bad idea.</p>
|
[
{
"answer_id": 196783,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": -1,
"selected": false,
"text": "<p>I suggest writing a function that will take two arguments: the text to be escaped and the type of quotes the string is in. Then, for example, if the type of quotes are single quotes, the function will escape the single quotes in the string and any other characters that need to be escaped (backslash?).</p>\n\n<pre><code>function escape_string($text, $type) {\n // Escape backslashes for all types of strings?\n $text = str_replace('\\\\', '\\\\\\\\', $text);\n\n switch($type) {\n case 'single':\n $text = str_replace(\"'\", \"\\\\'\", $text);\n break;\n case 'double':\n $text = str_replace('\"', '\\\\\"', $text);\n break;\n // etc...\n }\n\n return $text;\n}\n</code></pre>\n\n<p>I'm assuming that for single-quoted strings you want to escape the single quotes, and with double-quoted strings you want to escape the double quotes...</p>\n"
},
{
"answer_id": 196790,
"author": "acrosman",
"author_id": 24215,
"author_profile": "https://Stackoverflow.com/users/24215",
"pm_score": 0,
"selected": false,
"text": "<p>I'd start by standardizing the string type I was using in python, to use triple-quoted strings (\"\"\"). This should reduce the incidents of problems from stray quotes in the input. You'll still need to escape it of course, but it should reduce the number of issues that are a concern.</p>\n\n<p>What I did to escape the strings would somewhat depend on what I'm worried about getting slipped in, and the context that they are getting printed out again. If you're just worried about quotes causing problems, you could simply check for and occurrences of \"\"\" and escape them. On the other hand if I was worried about the input itself being malicious (and it's user input, so you probably should), then I would look at options like strip_tags() or other similar functions.</p>\n"
},
{
"answer_id": 196964,
"author": "Joe Scylla",
"author_id": 25771,
"author_profile": "https://Stackoverflow.com/users/25771",
"pm_score": 0,
"selected": false,
"text": "<p>Another option may be to export the data as array or object as JSON string and modify the python code slightly to handle the new input. While the escaping via JSON is not 100% bulletproof it will be still better than own escaping routines.</p>\n\n<p>And you'll be able to handle errors if the JSON string is malformatted.</p>\n\n<p>There's a package for Python to encode and decode JSON: <a href=\"http://pypi.python.org/pypi/python-json/\" rel=\"nofollow noreferrer\">python-json 3.4</a></p>\n"
},
{
"answer_id": 200315,
"author": "Glyph",
"author_id": 13564,
"author_profile": "https://Stackoverflow.com/users/13564",
"pm_score": 3,
"selected": true,
"text": "<p><strong>Do not</strong> try write this function in PHP. You will inevitably get it wrong and your application will inevitably have an arbitrary remote execution exploit.</p>\n\n<p>First, consider what problem you are actually solving. I presume you are just trying to get data from PHP to Python. You might try to write a .ini file rather than a .py file. Python has an excellent ini syntax parser, <a href=\"http://www.python.org/doc/2.5.2/lib/module-ConfigParser.html\" rel=\"nofollow noreferrer\">ConfigParser</a>. You can write the obvious, and potentially incorrect, quoting function in PHP and nothing serious will happen if (read: when) you get it wrong.</p>\n\n<p>You could also write an XML file. There are too many XML parsers and emitters for PHP and Python for me to even list here.</p>\n\n<p>If I <strong>really</strong> can't convince you that this is a <em>terrible, terrible</em> idea, then you can at least use the pre-existing function that Python has for doing such a thing: <code>repr()</code>.</p>\n\n<p>Here's a handy PHP function which will run a Python script to do this for you:</p>\n\n<pre><code><?php\n\nfunction py_escape($input) {\n $descriptorspec = array(\n 0 => array(\"pipe\", \"r\"),\n 1 => array(\"pipe\", \"w\")\n );\n $process = proc_open(\n \"python -c 'import sys; sys.stdout.write(repr(sys.stdin.read()))'\",\n $descriptorspec, $pipes);\n fwrite($pipes[0], $input);\n fclose($pipes[0]);\n $chunk_size = 8192;\n $escaped = fread($pipes[1], $chunk_size);\n if (strlen($escaped) == $chunk_size) {\n // This is important for security.\n die(\"That string's too big.\\n\");\n }\n proc_close($process);\n return $escaped;\n}\n\n// Example usage:\n$x = \"string \\rfull \\nof\\t crappy stuff\";\nprint py_escape($x);\n</code></pre>\n\n<p>The <code>chunk_size</code> check is intended to prevent an attack whereby your input ends up being two really long strings, which look like <code>(\"hello \" + (\".\" * chunk_size))</code> and <code>'; os.system(\"do bad stuff\")</code> respectively. Now, that naive attack won't work exactly, because Python won't let a single-quoted string end in the middle of a line, and those quotes in the <code>system()</code> call will themselves be quoted, but if the attacker manages to get a line continuation (\"\\\") into the right place and use something like <code>os.system(map(chr, ...))</code> then they can inject some code that will run.</p>\n\n<p>I opted to simply read one chunk and give up if there was more output, rather than continuing to read and accumulate, because there are also limits on Python source file line length; for all I know, that could be another attack vector. Python is not intended to be secure against arbitrary people writing arbitrary source code on your system so this area is unlikely to be audited.</p>\n\n<p>The fact that I had to think of all this for this trivial example is just another example of why you shouldn't use python source code as a data interchange format.</p>\n"
},
{
"answer_id": 1813364,
"author": "Christopher Gutteridge",
"author_id": 220559,
"author_profile": "https://Stackoverflow.com/users/220559",
"pm_score": 0,
"selected": false,
"text": "<p>I needed to code this to escape a string in the \"ntriples\" format, which uses <a href=\"http://docs.python.org/reference/lexical_analysis.html#string-literals\" rel=\"nofollow noreferrer\">python escaping</a>. </p>\n\n<p>The following function takes a utf-8 string and returns it escaped for python (or ntriples format).\nIt may do odd things if given illegal utf-8 data. It doesn't understand about Unicode characters past xFFFF. It does not (currently) wrap the string in double quotes.</p>\n\n<p>The uniord function comes from a comment on php.net.</p>\n\n<pre><code>function python_string_escape( $string ) {\n $string = preg_replace( \"/\\\\\\\\/\", \"\\\\\\\\\", $string ); # \\\\ (first to avoid string re-escaping)\n $string = preg_replace( \"/\\n/\", \"\\\\n\", $string ); # \\n\n $string = preg_replace( \"/\\r/\", \"\\\\r\", $string ); # \\r \n $string = preg_replace( \"/\\t/\", \"\\\\t\", $string ); # \\t \n $string = preg_replace( \"/\\\"/\", \"\\\\\\\"\", $string ); # \\\"\n $string = preg_replace( \"/([\\x{00}-\\x{1F}]|[\\x{7F}-\\x{FFFF}])/ue\",\n \"sprintf(\\\"\\\\u%04X\\\",uniord(\\\"$1\\\"))\",\n $string );\n return $string;\n}\n\nfunction uniord($c) {\n $h = ord($c{0});\n if ($h <= 0x7F) {\n return $h;\n } else if ($h < 0xC2) {\n return false;\n } else if ($h <= 0xDF) {\n return ($h & 0x1F) << 6 | (ord($c{1}) & 0x3F);\n } else if ($h <= 0xEF) {\n return ($h & 0x0F) << 12 | (ord($c{1}) & 0x3F) << 6 | (ord($c{2}) & 0x3F);\n } else if ($h <= 0xF4) {\n return ($h & 0x0F) << 18 | (ord($c{1}) & 0x3F) << 12 | (ord($c{2}) & 0x3F) << 6 | (ord($c{3}) & 0x3F);\n } else {\n return false;\n }\n}\n</code></pre>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/196771",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3528/"
] |
I have a PHP application which needs to output a python script, more specifically a bunch of variable assignment statements, eg.
```
subject_prefix = 'This String From User Input'
msg_footer = """This one too."""
```
The contents of subject\_prefix et al need to be written to take user input; as such, I need to escape the contents of the strings. Writing something like the following isn't going to cut it; we're stuffed as soon as someone uses a quote or newline or anything else that I'm not aware of that could be hazardous:
```
echo "subject_prefix = '".$subject_prefix."'\n";
```
So. Any ideas?
(Rewriting the app in Python isn't possible due to time constraints. :P )
**Edit, years later:**
This was for integration between a web-app (written in PHP) and Mailman (written in Python). I couldn't modify the install of the latter, so I needed to come up with a way to talk in its language to manage its configuration.
This was also a *really* bad idea.
|
**Do not** try write this function in PHP. You will inevitably get it wrong and your application will inevitably have an arbitrary remote execution exploit.
First, consider what problem you are actually solving. I presume you are just trying to get data from PHP to Python. You might try to write a .ini file rather than a .py file. Python has an excellent ini syntax parser, [ConfigParser](http://www.python.org/doc/2.5.2/lib/module-ConfigParser.html). You can write the obvious, and potentially incorrect, quoting function in PHP and nothing serious will happen if (read: when) you get it wrong.
You could also write an XML file. There are too many XML parsers and emitters for PHP and Python for me to even list here.
If I **really** can't convince you that this is a *terrible, terrible* idea, then you can at least use the pre-existing function that Python has for doing such a thing: `repr()`.
Here's a handy PHP function which will run a Python script to do this for you:
```
<?php
function py_escape($input) {
$descriptorspec = array(
0 => array("pipe", "r"),
1 => array("pipe", "w")
);
$process = proc_open(
"python -c 'import sys; sys.stdout.write(repr(sys.stdin.read()))'",
$descriptorspec, $pipes);
fwrite($pipes[0], $input);
fclose($pipes[0]);
$chunk_size = 8192;
$escaped = fread($pipes[1], $chunk_size);
if (strlen($escaped) == $chunk_size) {
// This is important for security.
die("That string's too big.\n");
}
proc_close($process);
return $escaped;
}
// Example usage:
$x = "string \rfull \nof\t crappy stuff";
print py_escape($x);
```
The `chunk_size` check is intended to prevent an attack whereby your input ends up being two really long strings, which look like `("hello " + ("." * chunk_size))` and `'; os.system("do bad stuff")` respectively. Now, that naive attack won't work exactly, because Python won't let a single-quoted string end in the middle of a line, and those quotes in the `system()` call will themselves be quoted, but if the attacker manages to get a line continuation ("\") into the right place and use something like `os.system(map(chr, ...))` then they can inject some code that will run.
I opted to simply read one chunk and give up if there was more output, rather than continuing to read and accumulate, because there are also limits on Python source file line length; for all I know, that could be another attack vector. Python is not intended to be secure against arbitrary people writing arbitrary source code on your system so this area is unlikely to be audited.
The fact that I had to think of all this for this trivial example is just another example of why you shouldn't use python source code as a data interchange format.
|
196,788 |
<p>I'm trying to implement search result highlighting for pdfs in a web app. I have the original pdfs, and small png versions that are used in search results. Essentially I'm looking for an api like:</p>
<pre><code>pdf_document.find_offsets('somestring')
# => { top: 501, left: 100, bottom: 520, right: 150 }, { ... another box ... }, ...
</code></pre>
<p>I know it's possible to get this information out of a pdf because Apple's Preview.app implements this.</p>
<p>Need something that runs on Linux and ideally is open source. I'm aware you can do this with acrobat on windows.</p>
|
[
{
"answer_id": 200768,
"author": "msanders",
"author_id": 1002,
"author_profile": "https://Stackoverflow.com/users/1002",
"pm_score": 1,
"selected": false,
"text": "<p>I think you can do this using the Adobe Acrobat SDK, a Linux version of which can be <a href=\"http://www.adobe.com/devnet/acrobat/index.html?navID=downloads\" rel=\"nofollow noreferrer\">downloaded for free from Adobe</a>. You can use this to <a href=\"http://livedocs.adobe.com/acrobat_sdk/9/Acrobat9_HTMLHelp/wwhelp/wwhimpl/common/html/wwhelp.htm?context=Acrobat9_HTMLHelp&file=DevFAQ_UnderstandingSDK.22.22.html\" rel=\"nofollow noreferrer\">extract text from PDFs</a> and then work out offsets. The PDF can then be highlighted by using the <a href=\"http://www.adobe.com/devnet/pdf/pdfs/HighlightFileFormat.pdf\" rel=\"nofollow noreferrer\">Acrobat XML highlighting file</a>. This is used to specify which words in which positions are to be highlighted and is fed to acrobat as follows:</p>\n\n<p><a href=\"http://example.com/a.pdf#xml=http://example.com/highlightfile.xml\" rel=\"nofollow noreferrer\">http://example.com/a.pdf#xml=http://example.com/highlightfile.xml</a></p>\n"
},
{
"answer_id": 203553,
"author": "Chris Dolan",
"author_id": 14783,
"author_profile": "https://Stackoverflow.com/users/14783",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://search.cpan.org/dist/CAM-PDF/\" rel=\"nofollow noreferrer\">CAM::PDF</a> can do the geometry part quite nicely, but has some trouble with the string matching sometimes. The technique would be something like the following lightly-tested code:</p>\n\n<pre><code>use CAM::PDF;\nmy $pdf = CAM::PDF->new('my.pdf') or die $CAM::PDF::errstr;\nfor my $pagenum (1 .. $pdf->numPages) {\n my $pagetree = $pdf->getPageContentTree($pagenum) or die;\n my @text = $pagetree->traverse('MyRenderer')->getTextBlocks;\n for my $textblock (@text) {\n print \"text '$textblock->{str}' at \",\n \"($textblock->{left},$textblock->{bottom})\\n\";\n }\n}\n\npackage MyRenderer;\nuse base 'CAM::PDF::GS';\n\nsub new {\n my ($pkg, @args) = @_;\n my $self = $pkg->SUPER::new(@args);\n $self->{refs}->{text} = [];\n return $self;\n}\nsub getTextBlocks {\n my ($self) = @_;\n return @{$self->{refs}->{text}};\n}\nsub renderText {\n my ($self, $string, $width) = @_;\n my ($x, $y) = $self->textToDevice(0,0);\n push @{$self->{refs}->{text}}, {\n str => $string,\n left => $x,\n bottom => $y,\n right => $x + $width,\n #top => $y + ???, \n };\n return;\n}\n</code></pre>\n\n<p>where the output looks something like this:</p>\n\n<pre><code>text 'E' at (52.08,704.16)\ntext 'm' at (73.62096,704.16)\ntext 'p' at (113.58936,704.16)\ntext 'lo' at (140.49648,704.16)\ntext 'y' at (181.19904,704.16)\ntext 'e' at (204.43584,704.16)\ntext 'e' at (230.93808,704.16)\ntext ' N' at (257.44032,704.16)\ntext 'a' at (294.6504,704.16)\ntext 'm' at (320.772,704.16)\ntext 'e' at (360.7416,704.16)\ntext 'Employee Name' at (56.4,124.56)\ntext 'Employee Title' at (56.4,114.24)\ntext 'Company Name' at (56.4,103.92)\n</code></pre>\n\n<p>As you can see from that output, the string matching will be a little tedious, but the geometry is straightforward (except maybe for the font height).</p>\n"
},
{
"answer_id": 204277,
"author": "Fabrizio Accatino",
"author_id": 21145,
"author_profile": "https://Stackoverflow.com/users/21145",
"pm_score": 2,
"selected": true,
"text": "<p>Try to look at PdfLib TET\n<a href=\"http://www.pdflib.com/products/tet/\" rel=\"nofollow noreferrer\">http://www.pdflib.com/products/tet/</a></p>\n\n<p>(it's not free)</p>\n\n<p>Fabrizio</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/196788",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3624/"
] |
I'm trying to implement search result highlighting for pdfs in a web app. I have the original pdfs, and small png versions that are used in search results. Essentially I'm looking for an api like:
```
pdf_document.find_offsets('somestring')
# => { top: 501, left: 100, bottom: 520, right: 150 }, { ... another box ... }, ...
```
I know it's possible to get this information out of a pdf because Apple's Preview.app implements this.
Need something that runs on Linux and ideally is open source. I'm aware you can do this with acrobat on windows.
|
Try to look at PdfLib TET
<http://www.pdflib.com/products/tet/>
(it's not free)
Fabrizio
|
196,824 |
<p>How do you process information in Java that was input from a file. For Example: suppose you have a file input.txt. The contents of this file is:
abcdefghizzzzjklmnop
azzbcdefghijklmnop</p>
<p>My hope would be that the information would be put into the argument array of strings such that the following code would output "abcdefghizzzzjklmnop"</p>
<pre><code>class Test {
public static void main(String[] args) {
System.out.println(args[0]);
}
}
</code></pre>
<p>The command I have been using throws an array out of bound exception. This command is:</p>
<blockquote>
<blockquote>
<p>java Test < input.txt</p>
</blockquote>
</blockquote>
<p>Non-file based arguments work fine though. ie. java Test hello,a nd java Test < input.txt hello. </p>
<p>More information:
I have tried putting the file contents all on one line to see if \n \r characters may be messing things up. That didn't seem to help. </p>
<p>Also, I can't use the bufferedreader class for this because this is for a program for school, and it has to work with my professors shell script. He went over this during class, but I didn't write it down (or I can't find it).</p>
<p>Any help?</p>
|
[
{
"answer_id": 196831,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 3,
"selected": false,
"text": "<p>You should be able to read the input data from <code>System.in</code>.</p>\n\n<p>Here's some quick-and-dirty example code. <code>javac Test.java; java Test < Test.java</code>:</p>\n\n<pre><code>class Test\n{\n public static void main (String[] args)\n {\n byte[] bytes = new byte[1024];\n try\n {\n while (System.in.available() > 0)\n {\n int read = System.in.read (bytes, 0, 1024);\n System.out.write (bytes, 0, read);\n }\n } catch (Exception e)\n {\n e.printStackTrace ();\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 196833,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>It seems any time you post a formal question about your problem, you figure it out. </p>\n\n<p>Inputing a file via \"< input.txt\" inputs it as user input rather than as a command line argument. I realized this shortly after I explained why the bufferedreader class wouldn't work. </p>\n\n<p>Turns out you have to use the buffered reader class. </p>\n"
},
{
"answer_id": 196844,
"author": "Uri",
"author_id": 23072,
"author_profile": "https://Stackoverflow.com/users/23072",
"pm_score": -1,
"selected": false,
"text": "<p>I'm not sure why you want to pass the contents of a file as command line arguments unless you're doing some weird testbed.</p>\n\n<p>You could write a script that would read your file, generate a temporary script in which the java command is followed by your needs. </p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/196824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
How do you process information in Java that was input from a file. For Example: suppose you have a file input.txt. The contents of this file is:
abcdefghizzzzjklmnop
azzbcdefghijklmnop
My hope would be that the information would be put into the argument array of strings such that the following code would output "abcdefghizzzzjklmnop"
```
class Test {
public static void main(String[] args) {
System.out.println(args[0]);
}
}
```
The command I have been using throws an array out of bound exception. This command is:
>
>
> >
> > java Test < input.txt
> >
> >
> >
>
>
>
Non-file based arguments work fine though. ie. java Test hello,a nd java Test < input.txt hello.
More information:
I have tried putting the file contents all on one line to see if \n \r characters may be messing things up. That didn't seem to help.
Also, I can't use the bufferedreader class for this because this is for a program for school, and it has to work with my professors shell script. He went over this during class, but I didn't write it down (or I can't find it).
Any help?
|
You should be able to read the input data from `System.in`.
Here's some quick-and-dirty example code. `javac Test.java; java Test < Test.java`:
```
class Test
{
public static void main (String[] args)
{
byte[] bytes = new byte[1024];
try
{
while (System.in.available() > 0)
{
int read = System.in.read (bytes, 0, 1024);
System.out.write (bytes, 0, read);
}
} catch (Exception e)
{
e.printStackTrace ();
}
}
}
```
|
196,830 |
<p>Some ways to iterate through the characters of a string in Java are:</p>
<ol>
<li>Using <code>StringTokenizer</code>?</li>
<li>Converting the <code>String</code> to a <code>char[]</code> and iterating over that.</li>
</ol>
<p>What is the easiest/best/most correct way to iterate?</p>
|
[
{
"answer_id": 196834,
"author": "jjnguy",
"author_id": 2598,
"author_profile": "https://Stackoverflow.com/users/2598",
"pm_score": 10,
"selected": true,
"text": "<p>I use a for loop to iterate the string and use <code>charAt()</code> to get each character to examine it. Since the String is implemented with an array, the <code>charAt()</code> method is a constant time operation.</p>\n\n<pre><code>String s = \"...stuff...\";\n\nfor (int i = 0; i < s.length(); i++){\n char c = s.charAt(i); \n //Process char\n}\n</code></pre>\n\n<p>That's what I would do. It seems the easiest to me.</p>\n\n<p>As far as correctness goes, I don't believe that exists here. It is all based on your personal style.</p>\n"
},
{
"answer_id": 196842,
"author": "Alan",
"author_id": 17205,
"author_profile": "https://Stackoverflow.com/users/17205",
"pm_score": 2,
"selected": false,
"text": "<p>I wouldn't use <code>StringTokenizer</code> as it is one of classes in the JDK that's legacy.</p>\n\n<p>The javadoc says:</p>\n\n<blockquote>\n <p><code>StringTokenizer</code> is a legacy class that\n is retained for compatibility reasons\n although its use is discouraged in new\n code. It is recommended that anyone\n seeking this functionality use the\n split method of <code>String</code> or the\n <code>java.util.regex</code> package instead.</p>\n</blockquote>\n"
},
{
"answer_id": 196858,
"author": "Eugene Yokota",
"author_id": 3827,
"author_profile": "https://Stackoverflow.com/users/3827",
"pm_score": 0,
"selected": false,
"text": "<p>See <a href=\"http://java.sun.com/docs/books/tutorial/java/data/strings.html\" rel=\"nofollow noreferrer\">The Java Tutorials: Strings</a>.</p>\n\n<pre><code>public class StringDemo {\n public static void main(String[] args) {\n String palindrome = \"Dot saw I was Tod\";\n int len = palindrome.length();\n char[] tempCharArray = new char[len];\n char[] charArray = new char[len];\n\n // put original string in an array of chars\n for (int i = 0; i < len; i++) {\n tempCharArray[i] = palindrome.charAt(i);\n } \n\n // reverse array of chars\n for (int j = 0; j < len; j++) {\n charArray[j] = tempCharArray[len - 1 - j];\n }\n\n String reversePalindrome = new String(charArray);\n System.out.println(reversePalindrome);\n }\n}\n</code></pre>\n\n<p>Put the length into <code>int len</code> and use <code>for</code> loop.</p>\n"
},
{
"answer_id": 196866,
"author": "Bruno De Fraine",
"author_id": 6918,
"author_profile": "https://Stackoverflow.com/users/6918",
"pm_score": 4,
"selected": false,
"text": "<p>There are some dedicated classes for this:</p>\n\n<pre><code>import java.text.*;\n\nfinal CharacterIterator it = new StringCharacterIterator(s);\nfor(char c = it.first(); c != CharacterIterator.DONE; c = it.next()) {\n // process c\n ...\n}\n</code></pre>\n"
},
{
"answer_id": 196975,
"author": "Dave Cheney",
"author_id": 6449,
"author_profile": "https://Stackoverflow.com/users/6449",
"pm_score": 8,
"selected": false,
"text": "<p>Two options</p>\n\n<pre><code>for(int i = 0, n = s.length() ; i < n ; i++) { \n char c = s.charAt(i); \n}\n</code></pre>\n\n<p>or</p>\n\n<pre><code>for(char c : s.toCharArray()) {\n // process c\n}\n</code></pre>\n\n<p>The first is probably faster, then 2nd is probably more readable. </p>\n"
},
{
"answer_id": 197390,
"author": "Alan Moore",
"author_id": 20938,
"author_profile": "https://Stackoverflow.com/users/20938",
"pm_score": 0,
"selected": false,
"text": "<p>StringTokenizer is totally unsuited to the task of breaking a string into its individual characters. With <code>String#split()</code> you can do that easily by using a regex that matches nothing, e.g.:</p>\n\n<pre><code>String[] theChars = str.split(\"|\");\n</code></pre>\n\n<p>But StringTokenizer doesn't use regexes, and there's no delimiter string you can specify that will match the nothing between characters. There <em>is</em> one cute little hack you can use to accomplish the same thing: use the string itself as the delimiter string (making every character in it a delimiter) and have it return the delimiters:</p>\n\n<pre><code>StringTokenizer st = new StringTokenizer(str, str, true);\n</code></pre>\n\n<p>However, I only mention these options for the purpose of dismissing them. Both techniques break the original string into one-character strings instead of char primitives, and both involve a great deal of overhead in the form of object creation and string manipulation. Compare that to calling charAt() in a for loop, which incurs virtually no overhead. </p>\n"
},
{
"answer_id": 360930,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "<p>I agree that StringTokenizer is overkill here. Actually I tried out the suggestions above and took the time. </p>\n\n<p>My test was fairly simple: create a StringBuilder with about a million characters, convert it to a String, and traverse each of them with charAt() / after converting to a char array / with a CharacterIterator a thousand times (of course making sure to do something on the string so the compiler can't optimize away the whole loop :-) ).</p>\n\n<p>The result on my 2.6 GHz Powerbook (that's a mac :-) ) and JDK 1.5:</p>\n\n<ul>\n<li>Test 1: charAt + String --> 3138msec</li>\n<li>Test 2: String converted to array --> 9568msec </li>\n<li>Test 3: StringBuilder charAt --> 3536msec </li>\n<li>Test 4: CharacterIterator and String --> 12151msec</li>\n</ul>\n\n<p>As the results are significantly different, the most straightforward way also seems to be the fastest one. Interestingly, charAt() of a StringBuilder seems to be slightly slower than the one of String.</p>\n\n<p>BTW I suggest not to use CharacterIterator as I consider its abuse of the '\\uFFFF' character as \"end of iteration\" a really awful hack. In big projects there's always two guys that use the same kind of hack for two different purposes and the code crashes really mysteriously. </p>\n\n<p>Here's one of the tests:</p>\n\n<pre><code> int count = 1000;\n ...\n\n System.out.println(\"Test 1: charAt + String\");\n long t = System.currentTimeMillis();\n int sum=0;\n for (int i=0; i<count; i++) {\n int len = str.length();\n for (int j=0; j<len; j++) {\n if (str.charAt(j) == 'b')\n sum = sum + 1;\n }\n }\n t = System.currentTimeMillis()-t;\n System.out.println(\"result: \"+ sum + \" after \" + t + \"msec\");\n</code></pre>\n"
},
{
"answer_id": 361345,
"author": "sk.",
"author_id": 16399,
"author_profile": "https://Stackoverflow.com/users/16399",
"pm_score": 7,
"selected": false,
"text": "<p>Note most of the other techniques described here break down if you're dealing with characters outside of the BMP (Unicode <a href=\"http://en.wikipedia.org/wiki/Mapping_of_Unicode_character_planes#Basic_Multilingual_Plane\" rel=\"noreferrer\">Basic Multilingual Plane</a>), i.e. <a href=\"http://en.wikipedia.org/wiki/Code_point\" rel=\"noreferrer\">code points</a> that are outside of the u0000-uFFFF range. This will only happen rarely, since the code points outside this are mostly assigned to dead languages. But there are some useful characters outside this, for example some code points used for mathematical notation, and some used to encode proper names in Chinese.</p>\n\n<p>In that case your code will be:</p>\n\n<pre><code>String str = \"....\";\nint offset = 0, strLen = str.length();\nwhile (offset < strLen) {\n int curChar = str.codePointAt(offset);\n offset += Character.charCount(curChar);\n // do something with curChar\n}\n</code></pre>\n\n<p>The <code>Character.charCount(int)</code> method requires Java 5+.</p>\n\n<p>Source: <a href=\"http://mindprod.com/jgloss/codepoint.html\" rel=\"noreferrer\">http://mindprod.com/jgloss/codepoint.html</a></p>\n"
},
{
"answer_id": 5233839,
"author": "Touko",
"author_id": 28482,
"author_profile": "https://Stackoverflow.com/users/28482",
"pm_score": 4,
"selected": false,
"text": "<p>If you have <a href=\"http://code.google.com/p/guava-libraries/\" rel=\"noreferrer\">Guava</a> on your classpath, the following is a pretty readable alternative. Guava even has a fairly sensible custom List implementation for this case, so this shouldn't be inefficient.</p>\n\n<pre><code>for(char c : Lists.charactersOf(yourString)) {\n // Do whatever you want \n}\n</code></pre>\n\n<p>UPDATE: As @Alex noted, with Java 8 there's also <a href=\"https://docs.oracle.com/javase/8/docs/api/java/lang/CharSequence.html#chars--\" rel=\"noreferrer\"><code>CharSequence#chars</code></a> to use. Even the type is IntStream, so it can be mapped to chars like:</p>\n\n<pre><code>yourString.chars()\n .mapToObj(c -> Character.valueOf((char) c))\n .forEach(c -> System.out.println(c)); // Or whatever you want\n</code></pre>\n"
},
{
"answer_id": 27796856,
"author": "Alex - GlassEditor.com",
"author_id": 3179759,
"author_profile": "https://Stackoverflow.com/users/3179759",
"pm_score": 4,
"selected": false,
"text": "<p>If you need to iterate through the code points of a <code>String</code> (see this <a href=\"https://stackoverflow.com/a/361345/3179759\">answer</a>) a shorter / more readable way is to use the <a href=\"http://docs.oracle.com/javase/8/docs/api/java/lang/CharSequence.html#codePoints--\" rel=\"noreferrer\"><code>CharSequence#codePoints</code></a> method added in Java 8:</p>\n\n<pre><code>for(int c : string.codePoints().toArray()){\n ...\n}\n</code></pre>\n\n<p>or using the stream directly instead of a for loop:</p>\n\n<pre><code>string.codePoints().forEach(c -> ...);\n</code></pre>\n\n<p>There is also <a href=\"http://docs.oracle.com/javase/8/docs/api/java/lang/CharSequence.html#chars--\" rel=\"noreferrer\"><code>CharSequence#chars</code></a> if you want a stream of the characters (although it is an <code>IntStream</code>, since there is no <code>CharStream</code>).</p>\n"
},
{
"answer_id": 40444598,
"author": "Hawkeye Parker",
"author_id": 99717,
"author_profile": "https://Stackoverflow.com/users/99717",
"pm_score": 0,
"selected": false,
"text": "<p>Elaborating on <a href=\"https://stackoverflow.com/a/361345/99717\">this answer</a> and <a href=\"https://stackoverflow.com/a/27796856/99717\">this answer</a>.</p>\n\n<p>Above answers point out the problem of many of the solutions here which don't iterate by code point value -- they would have trouble with any <a href=\"https://en.wikipedia.org/wiki/Universal_Character_Set_characters#Surrogates\" rel=\"nofollow noreferrer\">surrogate chars</a>. The java docs also outline the issue <a href=\"https://docs.oracle.com/javase/8/docs/api/java/lang/Character.html\" rel=\"nofollow noreferrer\">here</a> (see \"Unicode Character Representations\"). Anyhow, here's some code that uses some actual surrogate chars from the supplementary Unicode set, and converts them <em>back</em> to a String. Note that .toChars() returns an array of chars: if you're dealing with surrogates, you'll necessarily have two chars. This code should work for <em>any</em> Unicode character.</p>\n\n<pre><code> String supplementary = \"Some Supplementary: \";\n supplementary.codePoints().forEach(cp -> \n System.out.print(new String(Character.toChars(cp))));\n</code></pre>\n"
},
{
"answer_id": 42805927,
"author": "devDeejay",
"author_id": 6145568,
"author_profile": "https://Stackoverflow.com/users/6145568",
"pm_score": 0,
"selected": false,
"text": "<p>This Example Code will Help you out!</p>\n\n<pre><code>import java.util.Comparator;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.TreeMap;\n\npublic class Solution {\n public static void main(String[] args) {\n HashMap<String, Integer> map = new HashMap<String, Integer>();\n map.put(\"a\", 10);\n map.put(\"b\", 30);\n map.put(\"c\", 50);\n map.put(\"d\", 40);\n map.put(\"e\", 20);\n System.out.println(map);\n\n Map sortedMap = sortByValue(map);\n System.out.println(sortedMap);\n }\n\n public static Map sortByValue(Map unsortedMap) {\n Map sortedMap = new TreeMap(new ValueComparator(unsortedMap));\n sortedMap.putAll(unsortedMap);\n return sortedMap;\n }\n\n}\n\nclass ValueComparator implements Comparator {\n Map map;\n\n public ValueComparator(Map map) {\n this.map = map;\n }\n\n public int compare(Object keyA, Object keyB) {\n Comparable valueA = (Comparable) map.get(keyA);\n Comparable valueB = (Comparable) map.get(keyB);\n return valueB.compareTo(valueA);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 47736566,
"author": "akhil_mittal",
"author_id": 1216775,
"author_profile": "https://Stackoverflow.com/users/1216775",
"pm_score": 5,
"selected": false,
"text": "<p>In <strong>Java 8</strong> we can solve it as:</p>\n<pre><code>String str = "xyz";\nstr.chars().forEachOrdered(i -> System.out.print((char)i));\nstr.codePoints().forEachOrdered(i -> System.out.print((char)i));\n</code></pre>\n<p>The method chars() returns an <code>IntStream</code> as mentioned in <a href=\"https://docs.oracle.com/javase/8/docs/api/java/lang/CharSequence.html#chars--\" rel=\"noreferrer\">doc</a>:</p>\n<blockquote>\n<p>Returns a stream of int zero-extending the char values from this\nsequence. Any char which maps to a surrogate code point is passed\nthrough uninterpreted. If the sequence is mutated while the stream is\nbeing read, the result is undefined.</p>\n</blockquote>\n<p>The method <code>codePoints()</code> also returns an <code>IntStream</code> as per doc:</p>\n<blockquote>\n<p>Returns a stream of code point values from this sequence. Any\nsurrogate pairs encountered in the sequence are combined as if by\nCharacter.toCodePoint and the result is passed to the stream. Any\nother code units, including ordinary BMP characters, unpaired\nsurrogates, and undefined code units, are zero-extended to int values\nwhich are then passed to the stream.</p>\n</blockquote>\n<p><strong>How is char and code point different?</strong> As mentioned in <a href=\"https://blogs.oracle.com/darcy/iterating-over-the-codepoints-of-a-string\" rel=\"noreferrer\">this</a> article:</p>\n<blockquote>\n<p>Unicode 3.1 added supplementary characters, bringing the total number\nof characters to more than the 2^16 = 65536 characters that can be\ndistinguished by a single 16-bit <code>char</code>. Therefore, a <code>char</code> value no\nlonger has a one-to-one mapping to the fundamental semantic unit in\nUnicode. JDK 5 was updated to support the larger set of character\nvalues. Instead of changing the definition of the <code>char</code> type, some of\nthe new supplementary characters are represented by a surrogate pair\nof two <code>char</code> values. To reduce naming confusion, a code point will be\nused to refer to the number that represents a particular Unicode\ncharacter, including supplementary ones.</p>\n</blockquote>\n<p><strong>Finally why <code>forEachOrdered</code> and not <code>forEach</code> ?</strong></p>\n<p>The behaviour of <code>forEach</code> is explicitly nondeterministic where as the <code>forEachOrdered</code> performs an action for each element of this stream, in the <strong>encounter order of the stream</strong> if the stream has a defined encounter order. So <code>forEach</code> does not guarantee that the order would be kept. Also check this <a href=\"https://stackoverflow.com/questions/32797579/foreach-vs-foreachordered-in-java-8-stream\">question</a> for more.</p>\n<p>For <strong>difference between a character, a code point, a glyph and a grapheme</strong> check this <a href=\"https://stackoverflow.com/questions/27331819/whats-the-difference-between-a-character-a-code-point-a-glyph-and-a-grapheme\">question</a>.</p>\n"
},
{
"answer_id": 53912454,
"author": "Enyby",
"author_id": 1504248,
"author_profile": "https://Stackoverflow.com/users/1504248",
"pm_score": 2,
"selected": false,
"text": "<p>If you need performance, then you <strong>must test</strong> on your environment. No other way.</p>\n\n<p>Here example code:</p>\n\n<pre><code>int tmp = 0;\nString s = new String(new byte[64*1024]);\n{\n long st = System.nanoTime();\n for(int i = 0, n = s.length(); i < n; i++) {\n tmp += s.charAt(i);\n }\n st = System.nanoTime() - st;\n System.out.println(\"1 \" + st);\n}\n\n{\n long st = System.nanoTime();\n char[] ch = s.toCharArray();\n for(int i = 0, n = ch.length; i < n; i++) {\n tmp += ch[i];\n }\n st = System.nanoTime() - st;\n System.out.println(\"2 \" + st);\n}\n{\n long st = System.nanoTime();\n for(char c : s.toCharArray()) {\n tmp += c;\n }\n st = System.nanoTime() - st;\n System.out.println(\"3 \" + st);\n}\nSystem.out.println(\"\" + tmp);\n</code></pre>\n\n<p>On <a href=\"http://www.tutorialspoint.com/compile_java_online.php\" rel=\"nofollow noreferrer\">Java online</a> I get:</p>\n\n<pre><code>1 10349420\n2 526130\n3 484200\n0\n</code></pre>\n\n<p>On Android x86 API 17 I get:</p>\n\n<pre><code>1 9122107\n2 13486911\n3 12700778\n0\n</code></pre>\n"
},
{
"answer_id": 61562687,
"author": "Sumit Kapoor",
"author_id": 4184808,
"author_profile": "https://Stackoverflow.com/users/4184808",
"pm_score": 0,
"selected": false,
"text": "<p>So typically there are two ways to iterate through string in java which has already been answered by multiple people here in this thread, just adding my version of it\nFirst is using</p>\n<pre><code>String s = sc.next() // assuming scanner class is defined above\nfor(int i=0; i<s.length(); i++){\n s.charAt(i) // This being the first way and is a constant time operation will hardly add any overhead\n }\n\nchar[] str = new char[10];\nstr = s.toCharArray() // this is another way of doing so and it takes O(n) amount of time for copying contents from your string class to the character array\n</code></pre>\n<p>If performance is at stake then I will recommend using the first one in constant time, if it is not then going with the second one makes your work easier considering the immutability with string classes in java.</p>\n"
},
{
"answer_id": 71684064,
"author": "unpluggeDloop",
"author_id": 12247187,
"author_profile": "https://Stackoverflow.com/users/12247187",
"pm_score": 1,
"selected": false,
"text": "<pre><code>public class Main {\n\npublic static void main(String[] args) {\n String myStr = "Hello";\n String myStr2 = "World";\n \n for (int i = 0; i < myStr.length(); i++) { \n char result = myStr.charAt(i);\n System.out.println(result);\n } \n \n for (int i = 0; i < myStr2.length(); i++) { \n char result = myStr2.charAt(i);\n System.out.print(result); \n } \n }\n}\n</code></pre>\n<p>Output:</p>\n<pre><code>H\ne\nl\nl\no\nWorld\n</code></pre>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/196830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/85/"
] |
Some ways to iterate through the characters of a string in Java are:
1. Using `StringTokenizer`?
2. Converting the `String` to a `char[]` and iterating over that.
What is the easiest/best/most correct way to iterate?
|
I use a for loop to iterate the string and use `charAt()` to get each character to examine it. Since the String is implemented with an array, the `charAt()` method is a constant time operation.
```
String s = "...stuff...";
for (int i = 0; i < s.length(); i++){
char c = s.charAt(i);
//Process char
}
```
That's what I would do. It seems the easiest to me.
As far as correctness goes, I don't believe that exists here. It is all based on your personal style.
|
196,840 |
<p>I am looking for a way to add a drop down list in WPF to a menu. This used to be really easy in winforms and so I am expecting you experts to know just now to do it in WPF. Thanks.</p>
<p>Sorry if this is a bad question, it is late and I don't want to think.</p>
|
[
{
"answer_id": 196873,
"author": "Jobi Joy",
"author_id": 8091,
"author_profile": "https://Stackoverflow.com/users/8091",
"pm_score": 6,
"selected": true,
"text": "<p>It is very easy to add any UIElement to any control, You can just add Combobox to a Menu control and create menu as bellow.</p>\n\n<pre><code><Menu>\n <MenuItem Header=\"File\">\n <MenuItem Header=\"Open\"/>\n <MenuItem Header=\"Close\"/>\n <Separator/>\n <ComboBox Width=\"85\" Height=\"21.96\" />\n </MenuItem>\n</Menu>\n</code></pre>\n"
},
{
"answer_id": 198242,
"author": "Alan Le",
"author_id": 1133,
"author_profile": "https://Stackoverflow.com/users/1133",
"pm_score": 4,
"selected": false,
"text": "<p>While this is very easy to do as Jobi Joy has shown, I think it has horrible usability. The Menu control supports multiple levels of menu items and I would go down that route for UI consistency.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/196840",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22914/"
] |
I am looking for a way to add a drop down list in WPF to a menu. This used to be really easy in winforms and so I am expecting you experts to know just now to do it in WPF. Thanks.
Sorry if this is a bad question, it is late and I don't want to think.
|
It is very easy to add any UIElement to any control, You can just add Combobox to a Menu control and create menu as bellow.
```
<Menu>
<MenuItem Header="File">
<MenuItem Header="Open"/>
<MenuItem Header="Close"/>
<Separator/>
<ComboBox Width="85" Height="21.96" />
</MenuItem>
</Menu>
```
|
196,841 |
<p>In Python, you can do this:</p>
<pre><code>print "Hi! I'm %(name)s, and I'm %(age)d years old." % ({"name":"Brian","age":30})
</code></pre>
<p>What's the closest, simplest Ruby idiom to replicate this behavior? (No monkeypatching the String class, please.)</p>
<p>One of the really excellent benefits of this is that you can store the pre-processed string in a variable and use it as a "template", like so:</p>
<pre><code>template = "Hi! I'm %(name)s, and I'm %(age)d years old."
def greet(template,name,age):
print template % ({"name":name,"age":age})
</code></pre>
<p>This is obviously a trivial example, but there is a lot of utility in being able to store such a string for later use. Ruby's <code>"Hi! I'm #{name}"</code> convention is cursorily similar, but the immediate evaluation makes it less versatile.</p>
|
[
{
"answer_id": 196847,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 2,
"selected": false,
"text": "<p>In a double-quoted string in Ruby, you can insert the result of a Ruby expression like this:</p>\n\n<pre><code>puts \"Hi! I'm #{name}, and I'm #{age} years old.\"\n</code></pre>\n\n<p>Just put an expression inside the curly braces. (It could also be something more complex like #{age + 5}, or #{name + ' ' + last_name}, or a function call.)</p>\n"
},
{
"answer_id": 196850,
"author": "Chris Bunch",
"author_id": 422,
"author_profile": "https://Stackoverflow.com/users/422",
"pm_score": 0,
"selected": false,
"text": "<p>puts \"Hi! I'm #{name}, and I'm #{age} years old.\"</p>\n"
},
{
"answer_id": 196854,
"author": "Honza",
"author_id": 8621,
"author_profile": "https://Stackoverflow.com/users/8621",
"pm_score": 3,
"selected": false,
"text": "<p>There are some nice trick to this in Ruby:</p>\n\n<pre><code>name = \"Peter\"\n@age = 15 # instance variable\nputs \"Hi, you are #{name} and your age is #@age\"\n</code></pre>\n"
},
{
"answer_id": 198795,
"author": "Jonke",
"author_id": 15638,
"author_profile": "https://Stackoverflow.com/users/15638",
"pm_score": 2,
"selected": false,
"text": "<pre><code> class Template\n\n def %(h)\n \"Hi! I'm #{h[:name]}s, and I'm #{h[:age]}d years old.\"\n\n\n end\nend\n</code></pre>\n\n<p>Then call it with </p>\n\n<pre><code>t=Template.new\nt%({:name => \"Peter\", :age => 18})\n</code></pre>\n\n<p>This is not exactly what you asked for but could give you a hint.</p>\n"
},
{
"answer_id": 12562639,
"author": "mdik",
"author_id": 1694005,
"author_profile": "https://Stackoverflow.com/users/1694005",
"pm_score": 2,
"selected": false,
"text": "<p>What works (meanwhile), though, is something along the lines of:</p>\n\n<pre><code>d = {\"key1\" => \"value1\", \"key2\" => \"value2\"}\ns = \"string to be magically induced with variables, which are \\n * %s and \\n * %s.\\n\"\nprint s%d.values()\n# or\nprint s%[d[\"key1\"], d[\"key2\"]]\n</code></pre>\n"
},
{
"answer_id": 12563022,
"author": "knut",
"author_id": 676874,
"author_profile": "https://Stackoverflow.com/users/676874",
"pm_score": 5,
"selected": true,
"text": "<p>You can also use </p>\n\n<pre><code>printf \"1: %<key1>s 2: %<key2>s\\n\", {:key1 => \"value1\", :key2 => \"value2\"}\n</code></pre>\n\n<p>or</p>\n\n<pre><code>data = {:key1 => \"value1\", :key2 => \"value2\"}\nprintf \"1: %<key1>s 2: %<key2>s\\n\", data\n</code></pre>\n\n<p>or (this needs ruby 1.9, for the other examples I'm not sure)</p>\n\n<pre><code>data = {key1: \"value1\", key2: \"value2\"}\nprintf \"1: %<key1>s 2: %<key2>s\\n\", data\n</code></pre>\n\n<p>This prints</p>\n\n<pre><code>1: value1 2: value2\n</code></pre>\n\n<p>Important restriction: The used keys of the hash (<em>data</em> in my example) must be symbols.</p>\n\n<hr>\n\n<p>A remark on the example above:\n<code>printf</code> takes one format string and optional parameters. But there is also a <code>String#%</code>-method.</p>\n\n<p>The following four calls have all the same result:</p>\n\n<pre><code>printf \"1: %<key1>s 2: %<key2>s\\n\" , {:key1 => \"value1\", :key2 => \"value2\"}\nprintf \"1: %<key1>s 2: %<key2>s\\n\" % {:key1 => \"value1\", :key2 => \"value2\"}\nprint \"1: %<key1>s 2: %<key2>s\\n\" % {:key1 => \"value1\", :key2 => \"value2\"}\nputs \"1: %<key1>s 2: %<key2>s\" % {:key1 => \"value1\", :key2 => \"value2\"}\n</code></pre>\n\n<p>The second version uses first the <code>String#%</code>-method and sends the result to <code>printf</code>.</p>\n"
},
{
"answer_id": 13027855,
"author": "Michael Kruglos",
"author_id": 1767938,
"author_profile": "https://Stackoverflow.com/users/1767938",
"pm_score": 4,
"selected": false,
"text": "<p>you do it like this:</p>\n\n<pre><code>values = {:hello => 'world', :world => 'hello'}\nputs \"%{world} %{hello}\" % values\n</code></pre>\n\n<p>Read this for more info:\n<a href=\"http://ruby.runpaint.org/strings#sprintf-hash\" rel=\"noreferrer\">http://ruby.runpaint.org/strings#sprintf-hash</a></p>\n\n<p>If you need something more sophisticated, read about ERB, and google template engines.\nIf you need to generate web pages, emails etc. you'll find that using template engines is a more robust solution.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/196841",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16034/"
] |
In Python, you can do this:
```
print "Hi! I'm %(name)s, and I'm %(age)d years old." % ({"name":"Brian","age":30})
```
What's the closest, simplest Ruby idiom to replicate this behavior? (No monkeypatching the String class, please.)
One of the really excellent benefits of this is that you can store the pre-processed string in a variable and use it as a "template", like so:
```
template = "Hi! I'm %(name)s, and I'm %(age)d years old."
def greet(template,name,age):
print template % ({"name":name,"age":age})
```
This is obviously a trivial example, but there is a lot of utility in being able to store such a string for later use. Ruby's `"Hi! I'm #{name}"` convention is cursorily similar, but the immediate evaluation makes it less versatile.
|
You can also use
```
printf "1: %<key1>s 2: %<key2>s\n", {:key1 => "value1", :key2 => "value2"}
```
or
```
data = {:key1 => "value1", :key2 => "value2"}
printf "1: %<key1>s 2: %<key2>s\n", data
```
or (this needs ruby 1.9, for the other examples I'm not sure)
```
data = {key1: "value1", key2: "value2"}
printf "1: %<key1>s 2: %<key2>s\n", data
```
This prints
```
1: value1 2: value2
```
Important restriction: The used keys of the hash (*data* in my example) must be symbols.
---
A remark on the example above:
`printf` takes one format string and optional parameters. But there is also a `String#%`-method.
The following four calls have all the same result:
```
printf "1: %<key1>s 2: %<key2>s\n" , {:key1 => "value1", :key2 => "value2"}
printf "1: %<key1>s 2: %<key2>s\n" % {:key1 => "value1", :key2 => "value2"}
print "1: %<key1>s 2: %<key2>s\n" % {:key1 => "value1", :key2 => "value2"}
puts "1: %<key1>s 2: %<key2>s" % {:key1 => "value1", :key2 => "value2"}
```
The second version uses first the `String#%`-method and sends the result to `printf`.
|
196,859 |
<p>I need to change color of TextBox whenever its required field validator is fired on Clicking the Submit button</p>
|
[
{
"answer_id": 196916,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 0,
"selected": false,
"text": "<p>Here's some self-contained HTML/JS that does the trick:</p>\n\n<pre><code><html>\n <head>\n <script type=\"text/javascript\">\n function mkclr(cntl,clr) {\n document.getElementById(cntl).style.backgroundColor = clr;\n };\n </script>\n </head>\n <body>\n <form>\n <input type=\"textbox\" id=\"tb1\"></input>\n <input type=\"submit\" value=\"Go\"\n onClick=\"javascript:mkclr('tb1','red');\">\n </input>\n </form>\n </body>\n</html>\n</code></pre>\n"
},
{
"answer_id": 196987,
"author": "Alexander Prokofyev",
"author_id": 11256,
"author_profile": "https://Stackoverflow.com/users/11256",
"pm_score": 4,
"selected": false,
"text": "<p>You could use CustomValidator instead of RequiredFieldValidator:</p>\n\n<p><strong>.ASPX</strong></p>\n\n<pre><code><asp:CustomValidator ID=\"CustomValidator1\" runat=\"server\" ErrorMessage=\"\"\n ControlToValidate=\"TextBox1\" ClientValidationFunction=\"ValidateTextBox\"\n OnServerValidate=\"CustomValidator1_ServerValidate\"\n ValidateEmptyText=\"True\"></asp:CustomValidator>\n\n<asp:TextBox ID=\"TextBox1\" runat=\"server\"></asp:TextBox>\n\n<script src=\"jquery-1.2.6.js\" type=\"text/javascript\"></script>\n<script type=\"text/javascript\">\n function ValidateTextBox(source, args)\n {\n var is_valid = $(\"#TextBox1\").val() != \"\";\n $(\"#TextBox1\").css(\"background-color\", is_valid ? \"white\" : \"red\");\n args.IsValid = is_valid;\n }\n</script>\n</code></pre>\n\n<p><strong>.CS</strong></p>\n\n<pre><code>protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)\n{\n bool is_valid = TextBox1.Text != \"\";\n TextBox1.BackColor = is_valid ? Color.White : Color.Red;\n args.IsValid = is_valid;\n}\n</code></pre>\n\n<p>Logic in client and server validation functions is the same, but the client function uses jQuery to access textbox value and modify its background color.</p>\n"
},
{
"answer_id": 2472593,
"author": "Dillie-O",
"author_id": 71,
"author_profile": "https://Stackoverflow.com/users/71",
"pm_score": 5,
"selected": false,
"text": "<p>What you can do is register a Javascript function that will iterate through the global Page_Validators array after submission and you can set the background appropriately. The nice thing about this is that you can use it on all of your controls on the page. The function looks like this:</p>\n\n<pre><code>function fnOnUpdateValidators()\n{\n for (var i = 0; i < Page_Validators.length; i++)\n {\n var val = Page_Validators[i];\n var ctrl = document.getElementById(val.controltovalidate);\n if (ctrl != null && ctrl.style != null)\n {\n if (!val.isvalid)\n ctrl.style.background = '#FFAAAA';\n else\n ctrl.style.backgroundColor = '';\n }\n }\n}\n</code></pre>\n\n<p>The final step is to register the script with the OnSubmit event:</p>\n\n<p>VB.NET:</p>\n\n<pre><code>Page.ClientScript.RegisterOnSubmitStatement(Me.GetType, \"val\", \"fnOnUpdateValidators();\")\n</code></pre>\n\n<p>C#:</p>\n\n<pre><code>Page.ClientScript.RegisterOnSubmitStatement(this.GetType(), \"val\", \"fnOnUpdateValidators();\");\n</code></pre>\n\n<p>You'll maintain the proper IsValid status in all of your code behind and it can work with all of your controls.</p>\n\n<p><em>Note: I found this solution from the <a href=\"http://codinglifestyle.wordpress.com/2009/09/16/change-background-color-of-invalid-controls-asp-net-validator/\" rel=\"noreferrer\">following blog</a>. I just wanted to document it here in the event the source blog goes down.</em></p>\n"
},
{
"answer_id": 2529532,
"author": "Steve Krile",
"author_id": 303199,
"author_profile": "https://Stackoverflow.com/users/303199",
"pm_score": 2,
"selected": false,
"text": "<p>I liked Alexander's answer, but wanted the javascript to be more generic. So, here is a generic way of consuming the errors from a custom validator.</p>\n\n<pre><code> function ValidateTextBox(source, args) {\n var cntrl_id = $(source).attr(\"controltovalidate\");\n var cntrl = $(\"#\" + cntrl_id);\n var is_valid = $(cntrl).val() != \"\";\n is_valid ? $(cntrl).removeClass(\"error\") : $(cntrl).addClass(\"error\");\n\n args.IsValid = is_valid;\n }\n</code></pre>\n"
},
{
"answer_id": 3157714,
"author": "Lilja",
"author_id": 303998,
"author_profile": "https://Stackoverflow.com/users/303998",
"pm_score": 1,
"selected": false,
"text": "<p>I too liked Alexanders and Steves answer but I wanted the same as in codebehind. I think this code might do it but it differes depending on your setup. My controls are inside a contentplaceholder.</p>\n\n<pre><code>protected void cvPhone_ServerValidate(object source, ServerValidateEventArgs args)\n{\n bool is_valid = !string.IsNullOrEmpty(args.Value);\n string control = ((CustomValidator)source).ControlToValidate;\n ((TextBox)this.Master.FindControl(\"ContentBody\").FindControl(control)).CssClass = is_valid ? string.Empty : \"inputError\";\n args.IsValid = is_valid;\n}\n</code></pre>\n"
},
{
"answer_id": 7110062,
"author": "MJ Hufford",
"author_id": 274449,
"author_profile": "https://Stackoverflow.com/users/274449",
"pm_score": 2,
"selected": false,
"text": "<p>I know this is old, but I have another modified combination from Dillie-O and Alexander. This uses jQuery with the blur event to remove the style when validation succeeds.</p>\n\n<pre><code>function validateFields() {\n try {\n var count = 0;\n var hasFocus = false;\n\n for (var i = 0; i < Page_Validators.length; i++) {\n var val = Page_Validators[i];\n var ctrl = document.getElementById(val.controltovalidate);\n\n validateField(ctrl, val);\n\n if (!val.isvalid) { count++; }\n if (!val.isvalid && hasFocus === false) {\n ctrl.focus(); hasFocus = true;\n }\n }\n\n if (count == 0) {\n hasFocus = false;\n }\n }\n catch (err) { }\n}\n\nfunction validateField(ctrl, val)\n{\n $(ctrl).blur(function () { validateField(ctrl, val); });\n\n if (ctrl != null && $(ctrl).is(':disabled') == false) { // && ctrl.style != null\n val.isvalid ? $(ctrl).removeClass(\"error\") : $(ctrl).addClass(\"error\");\n } \n\n if ($(ctrl).hasClass('rdfd_') == true) { //This is a RadNumericTextBox\n var rtxt = document.getElementById(val.controltovalidate + '_text');\n val.isvalid ? $(rtxt).removeClass(\"error\") : $(rtxt).addClass(\"error\");\n }\n}\n</code></pre>\n"
},
{
"answer_id": 8279074,
"author": "Bala",
"author_id": 1066980,
"author_profile": "https://Stackoverflow.com/users/1066980",
"pm_score": 1,
"selected": false,
"text": "<p>Another way,</p>\n\n<pre><code>$(document).ready(function() {\n HighlightControlToValidate();\n $('#<%=btnSave.ClientID %>').click(function() {\n if (typeof (Page_Validators) != \"undefined\") {\n for (var i = 0; i < Page_Validators.length; i++) {\n if (!Page_Validators[i].isvalid) {\n $('#' + Page_Validators[i].controltovalidate).css(\"background\", \"#f3d74f\");\n }\n else {\n $('#' + Page_Validators[i].controltovalidate).css(\"background\", \"white\");\n }\n }\n }\n });\n});\n</code></pre>\n\n<p>Reference:\n<a href=\"http://www.codedigest.com/Articles/ASPNET/414_Highlight_Input_Controls_when_Validation_fails_in_AspNet_Validator_controls.aspx\" rel=\"nofollow\">http://www.codedigest.com/Articles/ASPNET/414_Highlight_Input_Controls_when_Validation_fails_in_AspNet_Validator_controls.aspx</a></p>\n"
},
{
"answer_id": 10829154,
"author": "Thomas_King",
"author_id": 1427732,
"author_profile": "https://Stackoverflow.com/users/1427732",
"pm_score": 2,
"selected": false,
"text": "<p>Another possibility... this code gives a red border (or whatever you put inside the CSS class) to the control to validate (works for dropdownlists and textbox, but can be extended for buttons etc...)</p>\n\n<p>First of, I make use of a <strong>CustomValidator</strong> instead of a RequiredFieldValidator, because then you can use the <strong>ClientValidationFunction</strong> of the CustomValidator to change the CSS of the control to validate.</p>\n\n<p>For example: change the border of a textbox MyTextBox when a user forgot to fill it in. The CustomValidator for the MyTextBox control would look like this:</p>\n\n<pre><code><asp:CustomValidator ID=\"CustomValidatorMyTextBox\" runat=\"server\" ErrorMessage=\"\"\n Display=\"None\" ClientValidationFunction=\"ValidateInput\" \n ControlToValidate=\"MyTextBox\" ValidateEmptyText=\"true\" \n ValidationGroup=\"MyValidationGroup\">\n </asp:CustomValidator>\n</code></pre>\n\n<p>Or it could also work for a dropdownlist in which a selection is required. The CustomValidator would look the same as above, but with the ControlToValidate pointing to the dropdownlist.</p>\n\n<p>For the client-side script, make use of JQuery. The ValidateInput method would look like this:</p>\n\n<pre><code> <script type=\"text/javascript\">\n function ValidateInput(source, args)\n {\n var controlName = source.controltovalidate;\n var control = $('#' + controlName);\n if (control.is('input:text')) {\n if (control.val() == \"\") {\n control.addClass(\"validation\");\n args.IsValid = false;\n }\n else {\n control.removeClass(\"validation\");\n args.IsValid = true;\n }\n }\n else if (control.is('select')) {\n if (control.val() == \"-1\"[*] ) {\n control.addClass(\"validation\");\n args.IsValid = false;\n }\n else {\n control.removeClass(\"validation\");\n args.IsValid = true;\n }\n }\n }\n </script>\n</code></pre>\n\n<p>The “validation” class is a CSS class that contains the markup when the validator is fired. It could look like this:</p>\n\n<pre><code>.validation { border: solid 2px red; }\n</code></pre>\n\n<p>PS: to make the border color work for the dropdown list in IE, \nadd the following meta tag to the page's heading: <code><meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" /></code>.</p>\n\n<p>[*]This is the same as the “InitialValue” of a RequiredFieldValidator. This is the item that is selected as default when the user hasn’t selected anything yet.</p>\n"
},
{
"answer_id": 11954218,
"author": "Rory",
"author_id": 8479,
"author_profile": "https://Stackoverflow.com/users/8479",
"pm_score": 4,
"selected": false,
"text": "<p>You can very easily override ASP.NET's javascript function that updates the display of validated fields. This is a nice option as you can keep your existing Field Validators, and don't have to write any custom validation logic or go looking for the fields to validate. In the example below I'm adding/removing an 'error' class from the parent element that has class 'control-group' (because I'm using <a href=\"http://twitter.github.com/bootstrap/base-css.html?#forms\" rel=\"nofollow noreferrer\">twitter bootstrap css</a>):</p>\n\n<pre><code> /**\n * Re-assigns the ASP.NET validation JS function to\n * provide a more flexible approach\n */\n function UpgradeASPNETValidation() {\n if (typeof (Page_ClientValidate) != \"undefined\") {\n AspValidatorUpdateDisplay = ValidatorUpdateDisplay;\n ValidatorUpdateDisplay = NicerValidatorUpdateDisplay;\n }\n }\n\n /**\n * This function is called once for each Field Validator, passing in the \n * Field Validator span, which has helpful properties 'isvalid' (bool) and\n * 'controltovalidate' (string = id of the input field to validate).\n */\n function NicerValidatorUpdateDisplay(val) {\n // Do the default asp.net display of validation errors (remove if you want)\n AspValidatorUpdateDisplay(val);\n\n // Add our custom display of validation errors\n if (val.isvalid) {\n // do whatever you want for invalid controls\n $('#' + val.controltovalidate).closest('.control-group').removeClass('error');\n } else {\n // reset invalid controls so they display as valid\n $('#' + val.controltovalidate).closest('.control-group').addClass('error');\n }\n }\n\n // Call UpgradeASPNETValidation after the page has loaded so that it \n // runs after the standard ASP.NET scripts.\n $(document).ready(UpgradeASPNETValidation);\n</code></pre>\n\n<p>This is adapted ever-so-slightly from <a href=\"https://stackoverflow.com/a/125158/8479\">here</a> and with helpful info from <a href=\"http://codingboynamedtracy.com/blog/asp-net-form-validation-with-jquery-part-1/\" rel=\"nofollow noreferrer\">these</a> <a href=\"http://codingboynamedtracy.com/blog/asp-net-form-validation-with-jquery-part-2\" rel=\"nofollow noreferrer\">articles</a>.</p>\n"
},
{
"answer_id": 12859791,
"author": "LarryDavid",
"author_id": 942269,
"author_profile": "https://Stackoverflow.com/users/942269",
"pm_score": 2,
"selected": false,
"text": "<p>I liked Rory's answer, but it doesn't work well with ValidationGroups, certainly in my instance where I have two validators on one field triggered by two different buttons.</p>\n\n<p>The problem is that ValidatorValidate will mark the validator as 'isValid' if it is not in the current ValidationGroup, but our class-changing code does not pay any attention. This meant the the display was not correct (certainly IE9 seems to not like to play).</p>\n\n<p>so to get around it I made the following changes:</p>\n\n<pre><code> /**\n * Re-assigns the ASP.NET validation JS function to\n * provide a more flexible approach\n */\n function UpgradeASPNETValidation() {\n if (typeof (Page_ClientValidate) != \"undefined\") {\n AspValidatorUpdateDisplay = ValidatorUpdateDisplay;\n ValidatorUpdateDisplay = NicerValidatorUpdateDisplay;\n AspValidatorValidate = ValidatorValidate;\n ValidatorValidate = NicerValidatorValidate;\n }\n }\n\n /**\n * This function is called once for each Field Validator, passing in the \n * Field Validator span, which has helpful properties 'isvalid' (bool) and\n * 'controltovalidate' (string = id of the input field to validate).\n */\n function NicerValidatorUpdateDisplay(val) {\n // Do the default asp.net display of validation errors (remove if you want)\n AspValidatorUpdateDisplay(val);\n\n // Add our custom display of validation errors\n // IF we should be paying any attention to this validator at all\n if ((typeof (val.enabled) == \"undefined\" || val.enabled != false) && IsValidationGroupMatch(val, AspValidatorValidating)) {\n if (val.isvalid) {\n // do whatever you want for invalid controls\n $('#' + val.controltovalidate).parents('.control-group:first').removeClass('error');\n } else {\n // reset invalid controls so they display as valid\n //$('#' + val.controltovalidate).parents('.control-group:first').addClass('error');\n var t = $('#' + val.controltovalidate).parents('.control-group:first');\n t.addClass('error');\n }\n }\n }\n\n function NicerValidatorValidate(val, validationGroup, event) {\n AspValidatorValidating = validationGroup;\n AspValidatorValidate(val, validationGroup, event);\n }\n\n // Call UpgradeASPNETValidation after the page has loaded so that it \n // runs after the standard ASP.NET scripts.\n $(document).ready(UpgradeASPNETValidation);\n</code></pre>\n"
},
{
"answer_id": 15200858,
"author": "DevDave",
"author_id": 896631,
"author_profile": "https://Stackoverflow.com/users/896631",
"pm_score": 0,
"selected": false,
"text": "<p>I had to make a few changes to Steve's suggestion to get mine working, </p>\n\n<pre><code> function ValidateTextBox(source, args) {\n var controlId = document.getElementById(source.controltovalidate).id;\n var control = $(\"#\" + controlId);\n var value = control.val();\n var is_valid = value != \"\";\n is_valid ? control.removeClass(\"error\") : control.addClass(\"error\");\n args.IsValid = is_valid;\n }\n</code></pre>\n\n<p>great example though, exactly what I needed.</p>\n"
},
{
"answer_id": 15638922,
"author": "Asim Khan",
"author_id": 2211851,
"author_profile": "https://Stackoverflow.com/users/2211851",
"pm_score": 0,
"selected": false,
"text": "<pre><code><%@ Page Language=\"C#\" AutoEventWireup=\"true\" CodeBehind=\"Custemvalidatin.aspx.cs\" Inherits=\"AspDotNetPractice.Custemvalidatin\" %>\n\n<!DOCTYPE html>\n\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n<head runat=\"server\">\n <title></title>\n <script type=\"text/javascript\">\n function vali(source, args) {\n if (document.getElementById(source.controltovalidate).value.length > 0) {\n args.IsValid = true;\n document.getElementById(source.controltovalidate).style.borderColor = 'green';\n }\n else {\n args.IsValid = false;\n document.getElementById(source.controltovalidate).style.borderColor = 'red';\n }\n\n }\n </script>\n</head>\n<body>\n <form id=\"form1\" runat=\"server\">\n <div>\n <asp:TextBox ID=\"TextBox1\" Style=\"border:1px solid gray; width:270px; height:24px ; border-radius:6px;\" runat=\"server\"></asp:TextBox>\n\n <asp:CustomValidator ID=\"CustomValidator1\" runat=\"server\" ControlToValidate=\"TextBox1\"\n ErrorMessage=\"Enter First Name\" SetFocusOnError=\"True\" Display=\"Dynamic\" ClientValidationFunction=\"vali\" \n ValidateEmptyText=\"True\" Font-Size=\"Small\" ForeColor=\"Red\">Enter First Name</asp:CustomValidator><br /><br /><br />\n\n <asp:TextBox ID=\"TextBox2\" Style=\"border:1px solid gray; width:270px; height:24px ; border-radius:6px;\" runat=\"server\"></asp:TextBox>\n\n <asp:CustomValidator ID=\"CustomValidator2\" runat=\"server\" ClientValidationFunction=\"vali\"\n ControlToValidate=\"TextBox2\" Display=\"Dynamic\" ErrorMessage=\"Enter Second Name\"\n SetFocusOnError=\"True\" ValidateEmptyText=\"True\" Font-Size=\"Small\" ForeColor=\"Red\">Enter Second Name</asp:CustomValidator><br />\n <br />\n <br />\n\n <asp:Button ID=\"Button1\" runat=\"server\" Text=\"Button\" />\n </div>\n </form>\n</body>\n</html>\n</code></pre>\n"
},
{
"answer_id": 22502337,
"author": "Ben Croughs",
"author_id": 3122378,
"author_profile": "https://Stackoverflow.com/users/3122378",
"pm_score": 1,
"selected": false,
"text": "<p>I made a working one pager example of this for regular asp.net, no .control-group</p>\n\n<pre><code><%@ Page Language=\"C#\" AutoEventWireup=\"true\" CodeFile=\"Default.aspx.cs\" Inherits=\"_Default\" %>\n\n<!DOCTYPE html>\n<!-- http://stackoverflow.com/questions/196859/change-text-box-color-using-required-field-validator-no-extender-controls-pleas -->\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n<head runat=\"server\">\n <title></title>\n <script src=\"http://code.jquery.com/jquery-1.11.0.min.js\"></script>\n<script src=\"http://code.jquery.com/jquery-migrate-1.2.1.min.js\"></script>\n <script>\n /**\n * Re-assigns the ASP.NET validation JS function to\n * provide a more flexible approach\n */\n function UpgradeASPNETValidation() {\n if (typeof (Page_ClientValidate) != \"undefined\") {\n AspValidatorUpdateDisplay = ValidatorUpdateDisplay;\n ValidatorUpdateDisplay = NicerValidatorUpdateDisplay;\n AspValidatorValidate = ValidatorValidate;\n ValidatorValidate = NicerValidatorValidate;\n }\n }\n\n /**\n * This function is called once for each Field Validator, passing in the \n * Field Validator span, which has helpful properties 'isvalid' (bool) and\n * 'controltovalidate' (string = id of the input field to validate).\n */\n function NicerValidatorUpdateDisplay(val) {\n // Do the default asp.net display of validation errors (remove if you want)\n AspValidatorUpdateDisplay(val);\n\n // Add our custom display of validation errors\n // IF we should be paying any attention to this validator at all\n if ((typeof (val.enabled) == \"undefined\" || val.enabled != false) && IsValidationGroupMatch(val, AspValidatorValidating)) {\n if (val.isvalid) {\n // do whatever you want for invalid controls\n $('#' + val.controltovalidate).removeClass('error');\n } else {\n // reset invalid controls so they display as valid\n //$('#' + val.controltovalidate).parents('.control-group:first').addClass('error');\n var t = $('#' + val.controltovalidate);\n t.addClass('error');\n }\n }\n }\n\n function NicerValidatorValidate(val, validationGroup, event) {\n AspValidatorValidating = validationGroup;\n AspValidatorValidate(val, validationGroup, event);\n }\n\n // Call UpgradeASPNETValidation after the page has loaded so that it \n // runs after the standard ASP.NET scripts.\n $(document).ready(UpgradeASPNETValidation);\n </script>\n <style>\n .error {\n border: 1px solid red;\n }\n </style>\n</head>\n<body>\n <form id=\"form1\" runat=\"server\">\n <div>\n\n <asp:TextBox ID=\"TextBox1\" runat=\"server\" ></asp:TextBox>\n <asp:RequiredFieldValidator ID=\"RequiredFieldValidator1\" runat=\"server\" ControlToValidate=\"TextBox1\" ErrorMessage=\"RequiredFieldValidator\"></asp:RequiredFieldValidator>\n <asp:Button ID=\"Button1\" runat=\"server\" Text=\"Button\" />\n\n <br />\n <asp:TextBox ID=\"TextBox2\" runat=\"server\"></asp:TextBox>\n <asp:RegularExpressionValidator ID=\"RegularExpressionValidator1\" runat=\"server\" ControlToValidate=\"TextBox2\" ErrorMessage=\"RegularExpressionValidator\" ValidationExpression=\"\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*\"></asp:RegularExpressionValidator>\n <br />\n <asp:TextBox ID=\"TextBox3\" runat=\"server\"></asp:TextBox>\n <asp:RangeValidator ID=\"RangeValidator1\" runat=\"server\" ControlToValidate=\"TextBox3\" ErrorMessage=\"RangeValidator\" MaximumValue=\"100\" MinimumValue=\"0\"></asp:RangeValidator>\n\n </div>\n </form>\n</body>\n</html>\n</code></pre>\n"
},
{
"answer_id": 23952980,
"author": "BigMan",
"author_id": 1039083,
"author_profile": "https://Stackoverflow.com/users/1039083",
"pm_score": 0,
"selected": false,
"text": "<p>It is not exactly without changing controls user used to, but I think this way is easier (not writing the full example, I think it is not necessary):</p>\n\n<p>ASP.NET:</p>\n\n<pre><code> <asp:TextBox ID=\"TextBox1\" runat=\"server\" ></asp:TextBox>\n <asp:CustomValidator runat=\"server\" ControlToValidate=\"TextBox1\" Display=\"Dynamic\" Text=\"TextBox1 Not Set\" ValidateEmptyText=\"true\" OnServerValidate=\"ServerValidate\" />\n <asp:Button ID=\"Button1\" runat=\"server\" Text=\"Button\" OnClick=\"Execute\" />\n</code></pre>\n\n<p>Code:</p>\n\n<pre><code>protected void Execute(object sender, EventArgs e)\n{\n Page.Validate();\n if (Page.IsValid)\n {\n *some code*\n }\n}\n\nprotected void ServerValidate(object source, ServerValidateEventArgs args)\n{\n CustomValidator cval = source as CustomValidator;\n if (cval == null)\n {\n args.IsValid = false;\n return;\n }\n\n if (string.IsNullOrEmpty(args.Value))\n {\n args.IsValid = false;\n string _target = cval.ControlToValidate;\n TextBox tb = cval.Parent.FindControl(_target) as TextBox;\n tb.BorderColor = System.Drawing.Color.Red;\n }\n else\n {\n args.IsValid = true;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 25602922,
"author": "Majid Dehnamaki",
"author_id": 3946856,
"author_profile": "https://Stackoverflow.com/users/3946856",
"pm_score": 2,
"selected": false,
"text": "<p>in css:</p>\n\n<pre><code> .form-control\n {\n width: 100px;\n height: 34px;\n padding: 6px 12px;\n font-size: 14px;\n color: black;\n background-color: white;\n }\n .form-control-Error\n {\n width: 100px;\n height: 34px;\n padding: 6px 12px;\n font-size: 14px;\n color: #EBB8C4;\n background-color: #F9F2F4\n border: 1px solid #DB7791;\n border-radius: 4px;\n }\n</code></pre>\n\n<p>in your page:</p>\n\n<pre><code><asp:TextBox ID=\"txtUserName\" runat=\"server\" CssClass=\"form-control\"></asp:TextBox>\n <asp:RequiredFieldValidatorrunat=\"server\"Display=\"Dynamic\" ErrorMessage=\"PLease Enter UserName\" ControlToValidate=\"txtUserName\"></asp:RequiredFieldValidator>\n</code></pre>\n\n<p>at the end of your page above of </p>\n\n<pre><code><script type=\"text/javascript\">\n function WebForm_OnSubmit() {\n if (typeof (ValidatorOnSubmit) == \"function\" && ValidatorOnSubmit() == false) {\n for (var i in Page_Validators) {\n try {\n var control = document.getElementById(Page_Validators[i].controltovalidate);\n if (!Page_Validators[i].isvalid) {\n control.className = \"form-control-Error\";\n } else {\n control.className = \"form-control\";\n }\n } catch (e) { }\n }\n return false;\n }\n return true;\n }\n</script>\n</code></pre>\n"
},
{
"answer_id": 25857988,
"author": "user2979644",
"author_id": 2979644,
"author_profile": "https://Stackoverflow.com/users/2979644",
"pm_score": 3,
"selected": false,
"text": "<p>Very late to the party, but just in case someone else stumbles across this and wants a complete answer which works with Bootstrap, I've taken all the examples above, and made a version which will work with multiple validators attached to a single control, and will work with validation groups:</p>\n\n<pre><code><script>\n /**\n * Re-assigns the ASP.NET validation JS function to\n * provide a more flexible approach\n */\n function UpgradeASPNETValidation() {\n if (typeof (Page_ClientValidate) != \"undefined\") {\n AspValidatorUpdateDisplay = ValidatorUpdateDisplay;\n ValidatorUpdateDisplay = NicerValidatorUpdateDisplay;\n AspValidatorValidate = ValidatorValidate;\n ValidatorValidate = NicerValidatorValidate;\n\n // Remove the error class on each control group before validating\n // Store a reference to the ClientValidate function\n var origValidate = Page_ClientValidate;\n // Override with our custom version\n Page_ClientValidate = function (validationGroup) {\n // Clear all the validation classes for this validation group\n for (var i = 0; i < Page_Validators.length; i++) {\n if ((typeof(Page_Validators[i].validationGroup) == 'undefined' && !validationGroup) ||\n Page_Validators[i].validationGroup == validationGroup) {\n $(\"#\" + Page_Validators[i].controltovalidate).parents('.form-group').each(function () {\n $(this).removeClass('has-error');\n });\n }\n }\n // Call the original function\n origValidate(validationGroup);\n };\n }\n }\n\n /**\n * This function is called once for each Field Validator, passing in the \n * Field Validator span, which has helpful properties 'isvalid' (bool) and\n * 'controltovalidate' (string = id of the input field to validate).\n */\n function NicerValidatorUpdateDisplay(val) {\n // Do the default asp.net display of validation errors (remove if you want)\n AspValidatorUpdateDisplay(val);\n\n // Add our custom display of validation errors\n // IF we should be paying any attention to this validator at all\n if ((typeof (val.enabled) == \"undefined\" || val.enabled != false) && IsValidationGroupMatch(val, AspValidatorValidating)) {\n if (!val.isvalid) {\n // Set css class for invalid controls\n var t = $('#' + val.controltovalidate).parents('.form-group:first');\n t.addClass('has-error');\n }\n }\n }\n\n function NicerValidatorValidate(val, validationGroup, event) {\n AspValidatorValidating = validationGroup;\n AspValidatorValidate(val, validationGroup, event);\n }\n\n // Call UpgradeASPNETValidation after the page has loaded so that it \n // runs after the standard ASP.NET scripts.\n $(function () {\n UpgradeASPNETValidation();\n });\n</script>\n</code></pre>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/196859",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I need to change color of TextBox whenever its required field validator is fired on Clicking the Submit button
|
What you can do is register a Javascript function that will iterate through the global Page\_Validators array after submission and you can set the background appropriately. The nice thing about this is that you can use it on all of your controls on the page. The function looks like this:
```
function fnOnUpdateValidators()
{
for (var i = 0; i < Page_Validators.length; i++)
{
var val = Page_Validators[i];
var ctrl = document.getElementById(val.controltovalidate);
if (ctrl != null && ctrl.style != null)
{
if (!val.isvalid)
ctrl.style.background = '#FFAAAA';
else
ctrl.style.backgroundColor = '';
}
}
}
```
The final step is to register the script with the OnSubmit event:
VB.NET:
```
Page.ClientScript.RegisterOnSubmitStatement(Me.GetType, "val", "fnOnUpdateValidators();")
```
C#:
```
Page.ClientScript.RegisterOnSubmitStatement(this.GetType(), "val", "fnOnUpdateValidators();");
```
You'll maintain the proper IsValid status in all of your code behind and it can work with all of your controls.
*Note: I found this solution from the [following blog](http://codinglifestyle.wordpress.com/2009/09/16/change-background-color-of-invalid-controls-asp-net-validator/). I just wanted to document it here in the event the source blog goes down.*
|
196,876 |
<p>Just looking at ways of getting named constants in python.</p>
<pre><code>class constant_list:
(A_CONSTANT, B_CONSTANT, C_CONSTANT) = range(3)
</code></pre>
<p>Then of course you can refer to it like so: </p>
<pre><code>constant_list.A_CONSTANT
</code></pre>
<p>I suppose you could use a dictionary, using strings: </p>
<pre><code>constant_dic = {
"A_CONSTANT" : 1,
"B_CONSTANT" : 2,
"C_CONSTANT" : 3,}
</code></pre>
<p>and refer to it like this:</p>
<pre><code>constant_dic["A_CONSTANT"]
</code></pre>
<hr>
<p>My question, then, is simple. Is there any better ways of doing this? Not saying that these are inadequate or anything, just curious - any other common idioms that I've missed?</p>
<p>Thanks in advance.</p>
|
[
{
"answer_id": 196880,
"author": "Simon Peverett",
"author_id": 6063,
"author_profile": "https://Stackoverflow.com/users/6063",
"pm_score": 2,
"selected": false,
"text": "<p>I find the enumeration class recipe (Active State, <a href=\"http://code.activestate.com/recipes/67107/\" rel=\"nofollow noreferrer\">Python Cookbook</a>) to be very effective. </p>\n\n<p>Plus it has a lookup function which is nice.</p>\n\n<p>Pev</p>\n"
},
{
"answer_id": 196881,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 5,
"selected": true,
"text": "<p>For 2.3 or after:</p>\n\n<pre><code>class Enumerate(object):\n def __init__(self, names):\n for number, name in enumerate(names.split()):\n setattr(self, name, number)\n</code></pre>\n\n<p>To use:</p>\n\n<pre><code> codes = Enumerate('FOO BAR BAZ')\n</code></pre>\n\n<p><code>codes.BAZ</code> will be 2 and so on. </p>\n\n<p>If you only have 2.2, precede this with:</p>\n\n<pre><code> from __future__ import generators\n\n def enumerate(iterable):\n number = 0\n for name in iterable:\n yield number, name\n number += 1\n</code></pre>\n\n<p>(<em>This was taken from <a href=\"http://www.velocityreviews.com/forums/t322211-enum-in-python.html\" rel=\"noreferrer\">here</a></em>)</p>\n"
},
{
"answer_id": 196888,
"author": "Anthony Cramp",
"author_id": 488,
"author_profile": "https://Stackoverflow.com/users/488",
"pm_score": 2,
"selected": false,
"text": "<p>An alternative construction for constant_dic:</p>\n\n<pre><code>constants = [\"A_CONSTANT\", \"B_CONSTANT\", \"C_CONSTANT\"]\nconstant_dic = dict([(c,i) for i, c in enumerate(constants)])\n</code></pre>\n"
},
{
"answer_id": 196906,
"author": "DzinX",
"author_id": 18745,
"author_profile": "https://Stackoverflow.com/users/18745",
"pm_score": 1,
"selected": false,
"text": "<p>In Python, strings are immutable and so they are better for constants than numbers. The best approach, in my opinion, is to make an object that keeps constants as strings:</p>\n\n<pre><code>class Enumeration(object):\n def __init__(self, possibilities):\n self.possibilities = set(possibilities.split())\n\n def all(self):\n return sorted(self.possibilities)\n\n def __getattr__(self, name):\n if name in self.possibilities:\n return name\n raise AttributeError(\"Invalid constant: %s\" % name)\n</code></pre>\n\n<p>You could then use it like this:</p>\n\n<pre><code>>>> enum = Enumeration(\"FOO BAR\")\n>>> print enum.all()\n['BAR', 'FOO']\n>>> print enum.FOO\nFOO\n>>> print enum.FOOBAR\nTraceback (most recent call last):\n File \"enum.py\", line 17, in <module>\n print enum.FOOBAR\n File \"enum.py\", line 11, in __getattr__\n raise AttributeError(\"Invalid constant: %s\" % name)\nAttributeError: Invalid constant: FOOBAR\n</code></pre>\n"
},
{
"answer_id": 198101,
"author": "Kevin Little",
"author_id": 14028,
"author_profile": "https://Stackoverflow.com/users/14028",
"pm_score": 2,
"selected": false,
"text": "<p>The following acts like a classisc \"written in stone\" C enum -- once defined, you can't change it, you can only read its values. Neither can you instantiate it. All you have to do is \"import enum.py\" and derive from class Enum.</p>\n\n<pre><code># this is enum.py\nclass EnumException( Exception ):\n pass\n\nclass Enum( object ):\n class __metaclass__( type ):\n def __setattr__( cls, name, value ):\n raise EnumException(\"Can't set Enum class attribute!\")\n def __delattr__( cls, name ):\n raise EnumException(\"Can't delete Enum class attribute!\")\n\n def __init__( self ):\n raise EnumException(\"Enum cannot be instantiated!\")\n</code></pre>\n\n<p>This is the test code:</p>\n\n<pre><code># this is testenum.py\nfrom enum import *\n\nclass ExampleEnum( Enum ):\n A=1\n B=22\n C=333\n\nif __name__ == '__main__' :\n\n print \"ExampleEnum.A |%s|\" % ExampleEnum.A\n print \"ExampleEnum.B |%s|\" % ExampleEnum.B\n print \"ExampleEnum.C |%s|\" % ExampleEnum.C\n z = ExampleEnum.A\n if z == ExampleEnum.A:\n print \"z is A\"\n\n try:\n ExampleEnum.A = 4 \n print \"ExampleEnum.A |%s| FAIL!\" % ExampleEnum.A\n except EnumException:\n print \"Can't change Enum.A (pass...)\"\n\n try:\n del ExampleEnum.A\n except EnumException:\n print \"Can't delete Enum.A (pass...)\"\n\n try:\n bad = ExampleEnum()\n except EnumException:\n print \"Can't instantiate Enum (pass...)\"\n</code></pre>\n"
},
{
"answer_id": 1753196,
"author": "steveha",
"author_id": 166949,
"author_profile": "https://Stackoverflow.com/users/166949",
"pm_score": 2,
"selected": false,
"text": "<p>This is the best one I have seen: \"First Class Enums in Python\"</p>\n\n<p><a href=\"http://code.activestate.com/recipes/413486/\" rel=\"nofollow noreferrer\"><a href=\"http://code.activestate.com/recipes/413486/\" rel=\"nofollow noreferrer\">http://code.activestate.com/recipes/413486/</a></a></p>\n\n<p>It gives you a class, and the class contains all the enums. The enums can be compared to each other, but don't have any particular value; you can't use them as an integer value. (I resisted this at first because I am used to C enums, which are integer values. But if you can't use it as an integer, you can't use it as an integer <em>by mistake</em> so overall I think it is a win.) Each enum is a unique object. You can print enums, you can iterate over them, you can test that an enum value is \"in\" the enum. It's pretty complete and slick.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/196876",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/61/"
] |
Just looking at ways of getting named constants in python.
```
class constant_list:
(A_CONSTANT, B_CONSTANT, C_CONSTANT) = range(3)
```
Then of course you can refer to it like so:
```
constant_list.A_CONSTANT
```
I suppose you could use a dictionary, using strings:
```
constant_dic = {
"A_CONSTANT" : 1,
"B_CONSTANT" : 2,
"C_CONSTANT" : 3,}
```
and refer to it like this:
```
constant_dic["A_CONSTANT"]
```
---
My question, then, is simple. Is there any better ways of doing this? Not saying that these are inadequate or anything, just curious - any other common idioms that I've missed?
Thanks in advance.
|
For 2.3 or after:
```
class Enumerate(object):
def __init__(self, names):
for number, name in enumerate(names.split()):
setattr(self, name, number)
```
To use:
```
codes = Enumerate('FOO BAR BAZ')
```
`codes.BAZ` will be 2 and so on.
If you only have 2.2, precede this with:
```
from __future__ import generators
def enumerate(iterable):
number = 0
for name in iterable:
yield number, name
number += 1
```
(*This was taken from [here](http://www.velocityreviews.com/forums/t322211-enum-in-python.html)*)
|
196,883 |
<p>I am having an ASP.net page in my page i am having this as my code behind files.
on first access the page the page preinit, init, load methods are called. on postbacks
the preinit, init, load methods are called.</p>
<p>My question is LoadViewstate and control state events (Overridden methods) are not firing after postbacks also</p>
<pre><code>protected override void OnPreInit(EventArgs e)
{
base.OnPreInit(e);
}
protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
}
protected override void LoadControlState(object savedState)
{
base.LoadControlState(savedState);
}
protected void Page_Init(object sender, EventArgs e)
{
}
protected void Page_Load(object sender, EventArgs e)
{
// lblName.Text = ViewState["Test"].ToString();
}
</code></pre>
|
[
{
"answer_id": 196880,
"author": "Simon Peverett",
"author_id": 6063,
"author_profile": "https://Stackoverflow.com/users/6063",
"pm_score": 2,
"selected": false,
"text": "<p>I find the enumeration class recipe (Active State, <a href=\"http://code.activestate.com/recipes/67107/\" rel=\"nofollow noreferrer\">Python Cookbook</a>) to be very effective. </p>\n\n<p>Plus it has a lookup function which is nice.</p>\n\n<p>Pev</p>\n"
},
{
"answer_id": 196881,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 5,
"selected": true,
"text": "<p>For 2.3 or after:</p>\n\n<pre><code>class Enumerate(object):\n def __init__(self, names):\n for number, name in enumerate(names.split()):\n setattr(self, name, number)\n</code></pre>\n\n<p>To use:</p>\n\n<pre><code> codes = Enumerate('FOO BAR BAZ')\n</code></pre>\n\n<p><code>codes.BAZ</code> will be 2 and so on. </p>\n\n<p>If you only have 2.2, precede this with:</p>\n\n<pre><code> from __future__ import generators\n\n def enumerate(iterable):\n number = 0\n for name in iterable:\n yield number, name\n number += 1\n</code></pre>\n\n<p>(<em>This was taken from <a href=\"http://www.velocityreviews.com/forums/t322211-enum-in-python.html\" rel=\"noreferrer\">here</a></em>)</p>\n"
},
{
"answer_id": 196888,
"author": "Anthony Cramp",
"author_id": 488,
"author_profile": "https://Stackoverflow.com/users/488",
"pm_score": 2,
"selected": false,
"text": "<p>An alternative construction for constant_dic:</p>\n\n<pre><code>constants = [\"A_CONSTANT\", \"B_CONSTANT\", \"C_CONSTANT\"]\nconstant_dic = dict([(c,i) for i, c in enumerate(constants)])\n</code></pre>\n"
},
{
"answer_id": 196906,
"author": "DzinX",
"author_id": 18745,
"author_profile": "https://Stackoverflow.com/users/18745",
"pm_score": 1,
"selected": false,
"text": "<p>In Python, strings are immutable and so they are better for constants than numbers. The best approach, in my opinion, is to make an object that keeps constants as strings:</p>\n\n<pre><code>class Enumeration(object):\n def __init__(self, possibilities):\n self.possibilities = set(possibilities.split())\n\n def all(self):\n return sorted(self.possibilities)\n\n def __getattr__(self, name):\n if name in self.possibilities:\n return name\n raise AttributeError(\"Invalid constant: %s\" % name)\n</code></pre>\n\n<p>You could then use it like this:</p>\n\n<pre><code>>>> enum = Enumeration(\"FOO BAR\")\n>>> print enum.all()\n['BAR', 'FOO']\n>>> print enum.FOO\nFOO\n>>> print enum.FOOBAR\nTraceback (most recent call last):\n File \"enum.py\", line 17, in <module>\n print enum.FOOBAR\n File \"enum.py\", line 11, in __getattr__\n raise AttributeError(\"Invalid constant: %s\" % name)\nAttributeError: Invalid constant: FOOBAR\n</code></pre>\n"
},
{
"answer_id": 198101,
"author": "Kevin Little",
"author_id": 14028,
"author_profile": "https://Stackoverflow.com/users/14028",
"pm_score": 2,
"selected": false,
"text": "<p>The following acts like a classisc \"written in stone\" C enum -- once defined, you can't change it, you can only read its values. Neither can you instantiate it. All you have to do is \"import enum.py\" and derive from class Enum.</p>\n\n<pre><code># this is enum.py\nclass EnumException( Exception ):\n pass\n\nclass Enum( object ):\n class __metaclass__( type ):\n def __setattr__( cls, name, value ):\n raise EnumException(\"Can't set Enum class attribute!\")\n def __delattr__( cls, name ):\n raise EnumException(\"Can't delete Enum class attribute!\")\n\n def __init__( self ):\n raise EnumException(\"Enum cannot be instantiated!\")\n</code></pre>\n\n<p>This is the test code:</p>\n\n<pre><code># this is testenum.py\nfrom enum import *\n\nclass ExampleEnum( Enum ):\n A=1\n B=22\n C=333\n\nif __name__ == '__main__' :\n\n print \"ExampleEnum.A |%s|\" % ExampleEnum.A\n print \"ExampleEnum.B |%s|\" % ExampleEnum.B\n print \"ExampleEnum.C |%s|\" % ExampleEnum.C\n z = ExampleEnum.A\n if z == ExampleEnum.A:\n print \"z is A\"\n\n try:\n ExampleEnum.A = 4 \n print \"ExampleEnum.A |%s| FAIL!\" % ExampleEnum.A\n except EnumException:\n print \"Can't change Enum.A (pass...)\"\n\n try:\n del ExampleEnum.A\n except EnumException:\n print \"Can't delete Enum.A (pass...)\"\n\n try:\n bad = ExampleEnum()\n except EnumException:\n print \"Can't instantiate Enum (pass...)\"\n</code></pre>\n"
},
{
"answer_id": 1753196,
"author": "steveha",
"author_id": 166949,
"author_profile": "https://Stackoverflow.com/users/166949",
"pm_score": 2,
"selected": false,
"text": "<p>This is the best one I have seen: \"First Class Enums in Python\"</p>\n\n<p><a href=\"http://code.activestate.com/recipes/413486/\" rel=\"nofollow noreferrer\"><a href=\"http://code.activestate.com/recipes/413486/\" rel=\"nofollow noreferrer\">http://code.activestate.com/recipes/413486/</a></a></p>\n\n<p>It gives you a class, and the class contains all the enums. The enums can be compared to each other, but don't have any particular value; you can't use them as an integer value. (I resisted this at first because I am used to C enums, which are integer values. But if you can't use it as an integer, you can't use it as an integer <em>by mistake</em> so overall I think it is a win.) Each enum is a unique object. You can print enums, you can iterate over them, you can test that an enum value is \"in\" the enum. It's pretty complete and slick.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/196883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22162/"
] |
I am having an ASP.net page in my page i am having this as my code behind files.
on first access the page the page preinit, init, load methods are called. on postbacks
the preinit, init, load methods are called.
My question is LoadViewstate and control state events (Overridden methods) are not firing after postbacks also
```
protected override void OnPreInit(EventArgs e)
{
base.OnPreInit(e);
}
protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
}
protected override void LoadControlState(object savedState)
{
base.LoadControlState(savedState);
}
protected void Page_Init(object sender, EventArgs e)
{
}
protected void Page_Load(object sender, EventArgs e)
{
// lblName.Text = ViewState["Test"].ToString();
}
```
|
For 2.3 or after:
```
class Enumerate(object):
def __init__(self, names):
for number, name in enumerate(names.split()):
setattr(self, name, number)
```
To use:
```
codes = Enumerate('FOO BAR BAZ')
```
`codes.BAZ` will be 2 and so on.
If you only have 2.2, precede this with:
```
from __future__ import generators
def enumerate(iterable):
number = 0
for name in iterable:
yield number, name
number += 1
```
(*This was taken from [here](http://www.velocityreviews.com/forums/t322211-enum-in-python.html)*)
|
196,885 |
<p>How can I determine if I'm running on a 32bit or a 64bit version of matlab?</p>
<p>I have some pre-compiled mex-files which need different path's depending on 32/64bit matlab.</p>
|
[
{
"answer_id": 206927,
"author": "Adrian",
"author_id": 28406,
"author_profile": "https://Stackoverflow.com/users/28406",
"pm_score": 2,
"selected": false,
"text": "<p>Does this really work? Which version of matlab are you using?</p>\n\n<p>As far as I'm aware the 64 bit platforms end with \"64\" not 86. From the matlab site \n<a href=\"http://www.mathworks.com/access/helpdesk/help/techdoc/ref/computer.html\" rel=\"nofollow noreferrer\">http://www.mathworks.com/access/helpdesk/help/techdoc/ref/computer.html</a> I don't think that computer will ever return GLNXA86 but GLNXA64 instead.</p>\n\n<p>So this question is specific to GNU Linux 32bit or 64bit version.</p>\n\n<p>If you are testing for any 64bit platform then you probably need to test the last 2 characters to find \"64\" i.e. something like </p>\n\n<pre><code>if regexp(computer,'..$','match','64'),\n % setup 64bit options\nelse,\n % 32bit options\nend\n</code></pre>\n"
},
{
"answer_id": 208589,
"author": "Vebjorn Ljosa",
"author_id": 17498,
"author_profile": "https://Stackoverflow.com/users/17498",
"pm_score": 3,
"selected": false,
"text": "<p>The question of 32 vs. 64 bits is really a red herring. If I understand correctly, you want to determine which set of compiled MEX files are needed so you can set the path appropriately. For this, you can use the function <code>mexext</code>:</p>\n\n<pre><code>>> help mexext\n MEXEXT MEX filename extension for this platform, or all platforms. \n EXT = MEXEXT returns the MEX-file name extension for the current\n platform. \n\n ALLEXT = MEXEXT('all') returns a struct with fields 'arch' and 'ext' \n describing MEX-file name extensions for all platforms.\n\n There is a script named mexext.bat on Windows and mexext.sh on UNIX\n that is intended to be used outside MATLAB in makefiles or scripts. Use\n that script instead of explicitly specifying the MEX-file extension in\n a makefile or script. The script is located in $MATLAB\\bin.\n\n See also MEX, MEXDEBUG.\n</code></pre>\n"
},
{
"answer_id": 377623,
"author": "peje",
"author_id": 27331,
"author_profile": "https://Stackoverflow.com/users/27331",
"pm_score": 4,
"selected": true,
"text": "<p>Taking up on ScottieT812 and dwj suggestions, I post my own solution to earn some points.</p>\n\n<p>The function <code>computer</code> returns the architecture I'm running on. so:</p>\n\n<pre><code>switch computer\n case 'GLNX86'\n display('32-bit stuff')\n case 'GLNXA64'\n display('64-bit stuff')\n otherwise\n display('Not supported')\nend\n</code></pre>\n\n<p>works for me</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/196885",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27331/"
] |
How can I determine if I'm running on a 32bit or a 64bit version of matlab?
I have some pre-compiled mex-files which need different path's depending on 32/64bit matlab.
|
Taking up on ScottieT812 and dwj suggestions, I post my own solution to earn some points.
The function `computer` returns the architecture I'm running on. so:
```
switch computer
case 'GLNX86'
display('32-bit stuff')
case 'GLNXA64'
display('64-bit stuff')
otherwise
display('Not supported')
end
```
works for me
|
196,890 |
<p>I'm having performance oddities with Java2D. I know of the sun.java2d.opengl VM parameter to enable 3D acceleration for 2D, but even using that has some weird issues. </p>
<p>Here are results of tests I ran:</p>
<p>Drawing a 25x18 map with 32x32 pixel tiles on a JComponent<br>
Image 1 = .bmp format, Image 2 = A .png format</p>
<h2>Without -Dsun.java2d.opengl=true</h2>
<p>120 FPS using .BMP image 1<BR>
13 FPS using .PNG image 2</p>
<h2>With -Dsun.java2d.opengl=true</h2>
<p>12 FPS using .BMP image 1<BR>
700 FPS using .PNG image 2</p>
<p>Without acceleration, I'm assuming some kind of transformation is taking place with every drawImage() I do in software, and is pulling down the FPS considerably in the case of .PNG. Why though, with acceleration, would the results switch (and PNG actually performs incredibly faster)?! Craziness!</p>
<p>.BMP Image 1 is translated to an image type of TYPE_INT_RGB. .PNG Image 2 is translated to an image type of TYPE_CUSTOM. In order to get consistent speed with and without opengl acceleration, I have to create a new BufferedImage with an image type of TYPE_INT_ARGB, and draw Image 1 or Image 2 to this new image. </p>
<p>Here are the results running with that:</p>
<h2>Without -Dsun.java2d.opengl=true</h2>
<p>120 FPS using .BMP image 1<BR>
120 FPS using .PNG image 2</p>
<h2>With -Dsun.java2d.opengl=true</h2>
<p>700 FPS using .BMP image 1<BR>
700 FPS using .PNG image 2</p>
<p>My real question is, can I assume that TYPE_INT_ARGB will be the native image type for all systems and platforms? I'm assuming this value could be different. Is there some way for me to get the native value so that I can always create new BufferedImages for maximum performance? </p>
<p>Thanks in advance...</p>
|
[
{
"answer_id": 196893,
"author": "Nick Stinemates",
"author_id": 4960,
"author_profile": "https://Stackoverflow.com/users/4960",
"pm_score": 2,
"selected": false,
"text": "<p>From what I remember when I was thinking about doing graphics programming in Java, the built in libraries are slow. I was advised on GameDev.Net that anyone doing anything serious would have to use something like <a href=\"http://jogl.dev.java.net/\" rel=\"nofollow noreferrer\">jogl</a></p>\n"
},
{
"answer_id": 197060,
"author": "Consty",
"author_id": 1191472,
"author_profile": "https://Stackoverflow.com/users/1191472",
"pm_score": 7,
"selected": true,
"text": "<p>I think I found a solution by researching and putting bits and pieces together from too many Google searches. </p>\n\n<p>Here it is, comments and all:</p>\n\n<pre><code>private BufferedImage toCompatibleImage(BufferedImage image)\n{\n // obtain the current system graphical settings\n GraphicsConfiguration gfxConfig = GraphicsEnvironment.\n getLocalGraphicsEnvironment().getDefaultScreenDevice().\n getDefaultConfiguration();\n\n /*\n * if image is already compatible and optimized for current system \n * settings, simply return it\n */\n if (image.getColorModel().equals(gfxConfig.getColorModel()))\n return image;\n\n // image is not optimized, so create a new image that is\n BufferedImage newImage = gfxConfig.createCompatibleImage(\n image.getWidth(), image.getHeight(), image.getTransparency());\n\n // get the graphics context of the new image to draw the old image on\n Graphics2D g2d = newImage.createGraphics();\n\n // actually draw the image and dispose of context no longer needed\n g2d.drawImage(image, 0, 0, null);\n g2d.dispose();\n\n // return the new optimized image\n return newImage; \n}\n</code></pre>\n\n<p>In my previous post, GraphicsConfiguration was what held the information needed to create optimized images on a system. It seems to work pretty well, but I would have thought Java would automatically do this for you. Obviously you can't get too comfortable with Java. :) I guess I ended up answering my own question. Oh well, hopefully it'll help some of you I've seen trying to make use of Java for 2D games.</p>\n"
},
{
"answer_id": 35306754,
"author": "Alex Byrth",
"author_id": 4304439,
"author_profile": "https://Stackoverflow.com/users/4304439",
"pm_score": 3,
"selected": false,
"text": "<p>Well, this is old post but I'd like to share my findings about direct drawing with Swing/AWT, without BufferedImage.</p>\n\n<p>Some kind of drawing, as 3D, are better done when painting directly to a <strong>int[]</strong> buffer. Once done the images, you can use an <strong>ImageProducer</strong> instance, like <strong>MemoryImageSource</strong>, to produce images. I'm assuming you know how to perform your drawings directly, without help of Graphics/Graphics2.</p>\n\n<pre><code> /**\n* How to use MemoryImageSource to render images on JPanel\n* Example by A.Borges (2015)\n*/\npublic class MyCanvas extends JPanel implements Runnable {\n\npublic int pixel[];\npublic int width;\npublic int height;\nprivate Image imageBuffer; \nprivate MemoryImageSource mImageProducer; \nprivate ColorModel cm; \nprivate Thread thread;\n\n\npublic MyCanvas() {\n super(true);\n thread = new Thread(this, \"MyCanvas Thread\");\n}\n\n/**\n * Call it after been visible and after resizes.\n */\npublic void init(){ \n cm = getCompatibleColorModel();\n width = getWidth();\n height = getHeight();\n int screenSize = width * height;\n if(pixel == null || pixel.length < screenSize){\n pixel = new int[screenSize];\n } \n mImageProducer = new MemoryImageSource(width, height, cm, pixel,0, width);\n mImageProducer.setAnimated(true);\n mImageProducer.setFullBufferUpdates(true); \n imageBuffer = Toolkit.getDefaultToolkit().createImage(mImageProducer); \n if(thread.isInterrupted() || !thread.isAlive()){\n thread.start();\n }\n}\n/**\n* Do your draws in here !!\n* pixel is your canvas!\n*/\npublic /* abstract */ void render(){\n // rubisch draw\n int[] p = pixel; // this avoid crash when resizing\n if(p.length != width * height) return; \n for(int x=0; x < width; x++){\n for(int y=0; y<height; y++){\n int color = (((x + i) % 255) & 0xFF) << 16; //red\n color |= (((y + j) % 255) & 0xFF) << 8; //green\n color |= (((y/2 + x/2 - j) % 255) & 0xFF) ; //blue \n p[ x + y * width] = color;\n }\n } \n i += 1;\n j += 1; \n} \nprivate int i=1,j=256;\n\n@Override\npublic void run() {\n while (true) {\n // request a JPanel re-drawing\n repaint(); \n try {Thread.sleep(5);} catch (InterruptedException e) {}\n }\n}\n\n@Override\npublic void paintComponent(Graphics g) {\n super.paintComponent(g);\n // perform draws on pixels\n render();\n // ask ImageProducer to update image\n mImageProducer.newPixels(); \n // draw it on panel \n g.drawImage(this.imageBuffer, 0, 0, this); \n}\n\n/**\n * Overrides ImageObserver.imageUpdate.\n * Always return true, assuming that imageBuffer is ready to go when called\n */\n@Override\npublic boolean imageUpdate(Image image, int a, int b, int c, int d, int e) {\n return true;\n}\n}// end class\n</code></pre>\n\n<p>Note we need unique instance of <strong>MemoryImageSource</strong> and <strong>Image</strong>. Do not create new Image or new ImageProducer for each frames, unless you have resized your JPanel. See <strong>init()</strong> method above.</p>\n\n<p>In a rendering thread, ask a <strong>repaint()</strong>. On Swing, <strong>repaint()</strong> will call the overridden <strong>paintComponent()</strong>, where it call your <strong>render()</strong> method and then ask your imageProducer to update image.\nWith Image done, draw it with <strong>Graphics.drawImage()</strong>.</p>\n\n<p>To have a compatible Image, use proper <strong>ColorModel</strong> when you create your <strong>Image</strong>. I use <strong>GraphicsConfiguration.getColorModel()</strong>:</p>\n\n<pre><code>/**\n * Get Best Color model available for current screen.\n * @return color model\n */\nprotected static ColorModel getCompatibleColorModel(){ \n GraphicsConfiguration gfx_config = GraphicsEnvironment.\n getLocalGraphicsEnvironment().getDefaultScreenDevice().\n getDefaultConfiguration(); \n return gfx_config.getColorModel();\n}\n</code></pre>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/196890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1191472/"
] |
I'm having performance oddities with Java2D. I know of the sun.java2d.opengl VM parameter to enable 3D acceleration for 2D, but even using that has some weird issues.
Here are results of tests I ran:
Drawing a 25x18 map with 32x32 pixel tiles on a JComponent
Image 1 = .bmp format, Image 2 = A .png format
Without -Dsun.java2d.opengl=true
--------------------------------
120 FPS using .BMP image 1
13 FPS using .PNG image 2
With -Dsun.java2d.opengl=true
-----------------------------
12 FPS using .BMP image 1
700 FPS using .PNG image 2
Without acceleration, I'm assuming some kind of transformation is taking place with every drawImage() I do in software, and is pulling down the FPS considerably in the case of .PNG. Why though, with acceleration, would the results switch (and PNG actually performs incredibly faster)?! Craziness!
.BMP Image 1 is translated to an image type of TYPE\_INT\_RGB. .PNG Image 2 is translated to an image type of TYPE\_CUSTOM. In order to get consistent speed with and without opengl acceleration, I have to create a new BufferedImage with an image type of TYPE\_INT\_ARGB, and draw Image 1 or Image 2 to this new image.
Here are the results running with that:
Without -Dsun.java2d.opengl=true
--------------------------------
120 FPS using .BMP image 1
120 FPS using .PNG image 2
With -Dsun.java2d.opengl=true
-----------------------------
700 FPS using .BMP image 1
700 FPS using .PNG image 2
My real question is, can I assume that TYPE\_INT\_ARGB will be the native image type for all systems and platforms? I'm assuming this value could be different. Is there some way for me to get the native value so that I can always create new BufferedImages for maximum performance?
Thanks in advance...
|
I think I found a solution by researching and putting bits and pieces together from too many Google searches.
Here it is, comments and all:
```
private BufferedImage toCompatibleImage(BufferedImage image)
{
// obtain the current system graphical settings
GraphicsConfiguration gfxConfig = GraphicsEnvironment.
getLocalGraphicsEnvironment().getDefaultScreenDevice().
getDefaultConfiguration();
/*
* if image is already compatible and optimized for current system
* settings, simply return it
*/
if (image.getColorModel().equals(gfxConfig.getColorModel()))
return image;
// image is not optimized, so create a new image that is
BufferedImage newImage = gfxConfig.createCompatibleImage(
image.getWidth(), image.getHeight(), image.getTransparency());
// get the graphics context of the new image to draw the old image on
Graphics2D g2d = newImage.createGraphics();
// actually draw the image and dispose of context no longer needed
g2d.drawImage(image, 0, 0, null);
g2d.dispose();
// return the new optimized image
return newImage;
}
```
In my previous post, GraphicsConfiguration was what held the information needed to create optimized images on a system. It seems to work pretty well, but I would have thought Java would automatically do this for you. Obviously you can't get too comfortable with Java. :) I guess I ended up answering my own question. Oh well, hopefully it'll help some of you I've seen trying to make use of Java for 2D games.
|
196,930 |
<p>How, in the simplest possible way, distinguish between Windows XP and Windows Vista, using Python and <a href="http://python.net/crew/mhammond/win32/Downloads.html" rel="noreferrer">pywin32</a> or <a href="http://www.wxpython.org/" rel="noreferrer">wxPython</a>?</p>
<p>Essentially, I need a function that called will return True iff current OS is Vista:</p>
<pre><code>>>> isWindowsVista()
True
</code></pre>
|
[
{
"answer_id": 196931,
"author": "DzinX",
"author_id": 18745,
"author_profile": "https://Stackoverflow.com/users/18745",
"pm_score": 3,
"selected": false,
"text": "<p>The simplest solution I found is this one:</p>\n\n<pre><code>import sys\n\ndef isWindowsVista():\n '''Return True iff current OS is Windows Vista.'''\n if sys.platform != \"win32\":\n return False\n import win32api\n VER_NT_WORKSTATION = 1\n version = win32api.GetVersionEx(1)\n if not version or len(version) < 9:\n return False\n return ((version[0] == 6) and \n (version[1] == 0) and\n (version[8] == VER_NT_WORKSTATION))\n</code></pre>\n"
},
{
"answer_id": 196962,
"author": "Thomas Hervé",
"author_id": 25409,
"author_profile": "https://Stackoverflow.com/users/25409",
"pm_score": 3,
"selected": false,
"text": "<p>The solution used in Twisted, which doesn't need pywin32:</p>\n\n<pre><code>def isVista():\n if getattr(sys, \"getwindowsversion\", None) is not None:\n return sys.getwindowsversion()[0] == 6\n else:\n return False\n</code></pre>\n\n<p>Note that it will also match Windows Server 2008.</p>\n"
},
{
"answer_id": 200148,
"author": "monkut",
"author_id": 24718,
"author_profile": "https://Stackoverflow.com/users/24718",
"pm_score": 6,
"selected": true,
"text": "<p>Python has the lovely 'platform' module to help you out.</p>\n\n<pre><code>>>> import platform\n>>> platform.win32_ver()\n('XP', '5.1.2600', 'SP2', 'Multiprocessor Free')\n>>> platform.system()\n'Windows'\n>>> platform.version()\n'5.1.2600'\n>>> platform.release()\n'XP'\n</code></pre>\n\n<p>NOTE: As mentioned in the comments proper values may not be returned when using older versions of python.</p>\n"
},
{
"answer_id": 17010604,
"author": "Deming",
"author_id": 2092480,
"author_profile": "https://Stackoverflow.com/users/2092480",
"pm_score": 0,
"selected": false,
"text": "<p>An idea from <a href=\"http://www.brunningonline.net/simon/blog/archives/winGuiAuto.py.html\" rel=\"nofollow\">http://www.brunningonline.net/simon/blog/archives/winGuiAuto.py.html</a> might help, which can basically answer your question:</p>\n\n<pre><code>win_version = {4: \"NT\", 5: \"2K\", 6: \"XP\"}[os.sys.getwindowsversion()[0]]\nprint \"win_version=\", win_version\n</code></pre>\n"
},
{
"answer_id": 43156269,
"author": "Boštjan Mejak",
"author_id": 7771315,
"author_profile": "https://Stackoverflow.com/users/7771315",
"pm_score": 0,
"selected": false,
"text": "<pre><code>import platform\nif platform.release() == \"Vista\":\n # Do something.\n</code></pre>\n\n<p>or</p>\n\n<pre><code>import platform\nif \"Vista\" in platform.release():\n # Do something.\n</code></pre>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/196930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18745/"
] |
How, in the simplest possible way, distinguish between Windows XP and Windows Vista, using Python and [pywin32](http://python.net/crew/mhammond/win32/Downloads.html) or [wxPython](http://www.wxpython.org/)?
Essentially, I need a function that called will return True iff current OS is Vista:
```
>>> isWindowsVista()
True
```
|
Python has the lovely 'platform' module to help you out.
```
>>> import platform
>>> platform.win32_ver()
('XP', '5.1.2600', 'SP2', 'Multiprocessor Free')
>>> platform.system()
'Windows'
>>> platform.version()
'5.1.2600'
>>> platform.release()
'XP'
```
NOTE: As mentioned in the comments proper values may not be returned when using older versions of python.
|
196,936 |
<p>I'm writing some code for a class constructor which loops through all the properties of the class and calls a generic static method which populates my class with data from an external API. So I've got this as an example class:</p>
<pre><code>public class MyClass{
public string Property1 { get; set; }
public int Property2 { get; set; }
public bool Property3 { get; set; }
public static T DoStuff<T>(string name){
// get the data for the property from the external API
// or if there's a problem return 'default(T)'
}
}
</code></pre>
<p>Now in my constructor I want something like this:</p>
<pre><code>public MyClass(){
var properties = this.GetType().GetProperties();
foreach(PropertyInfo p in properties){
p.SetValue(this, DoStuff(p.Name), new object[0]);
}
}
</code></pre>
<p>So the above constructor will thrown an error because I'm not supplying the generic type.</p>
<p>So how do I pass in the type of the property in?</p>
|
[
{
"answer_id": 196945,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 5,
"selected": true,
"text": "<p>Do you want to call DoStuff<T> with T = the type of each property? In which case, \"as is\" you would need to use reflection and MakeGenericMethod - i.e.</p>\n\n<pre><code>var properties = this.GetType().GetProperties();\nforeach (PropertyInfo p in properties)\n{\n object value = typeof(MyClass)\n .GetMethod(\"DoStuff\")\n .MakeGenericMethod(p.PropertyType)\n .Invoke(null, new object[] { p.Name });\n p.SetValue(this, value, null);\n}\n</code></pre>\n\n<p>However, this isn't very pretty. In reality I wonder if it wouldn't be better just to have:</p>\n\n<pre><code>static object DoStuff(string name, Type propertyType);\n... and then\nobject value = DoStuff(p.Name, p.PropertyType);\n</code></pre>\n\n<p>What does the generics give you in this example? Note that value-types will still get boxed etc during the reflection call - and even then boxing <a href=\"http://msmvps.com/blogs/jon_skeet/archive/2008/10/08/why-boxing-doesn-t-keep-me-awake-at-nights.aspx\" rel=\"nofollow noreferrer\">isn't as bad as you might think</a>.</p>\n\n<p>Finally, in many scenarios, TypeDescriptor.GetProperties() is more appropriate than Type.GetProperties() - allows for flexible object models etc.</p>\n"
},
{
"answer_id": 196947,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": false,
"text": "<p>Was your constructor code meant to read like this:</p>\n\n<pre><code>public MyClass(){\n var properties = this.GetType().GetProperties();\n foreach(PropertyInfo p in properties){\n p.SetValue(this, DoStuff(p.Name), new object[0]);\n }\n}\n</code></pre>\n\n<p>? Note the <code>DoStuff</code> instead of <code>MyClass</code>.</p>\n\n<p>If so, the problem is that you're trying to use generics when they're really not applicable. The point of generics (well, one of the points) is to use compile-time type safety. Here you don't know the type at compile time! You could call the method by reflection (fetching the open form and then calling <a href=\"http://msdn.microsoft.com/en-us/library/system.reflection.methodinfo.makegenericmethod.aspx\" rel=\"nofollow noreferrer\">MakeGenericMethod</a>) but that's pretty ugly.</p>\n\n<p>Does <code>DoStuff</code> really need to be generic in the first place? Is it being used from elsewhere? The parameter to <code>PropertyInfo.SetValue</code> is just object, so you'd still get boxing etc even if you <em>could</em> call the method generically.</p>\n"
},
{
"answer_id": 197021,
"author": "Gaspar Nagy",
"author_id": 26530,
"author_profile": "https://Stackoverflow.com/users/26530",
"pm_score": 2,
"selected": false,
"text": "<p>If you don't use DoStuff from another place, I also suggest to write a non-generic method.</p>\n\n<p>Maybe you created the generic method to be able to use default(T). To replace that in a non-generic method, you can use Activator.CreateInstance(T) for value types and null for reference types:</p>\n\n<pre><code>object defaultResult = type.IsValueType ? Activator.CreateInstance(type) : null\n</code></pre>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/196936",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11388/"
] |
I'm writing some code for a class constructor which loops through all the properties of the class and calls a generic static method which populates my class with data from an external API. So I've got this as an example class:
```
public class MyClass{
public string Property1 { get; set; }
public int Property2 { get; set; }
public bool Property3 { get; set; }
public static T DoStuff<T>(string name){
// get the data for the property from the external API
// or if there's a problem return 'default(T)'
}
}
```
Now in my constructor I want something like this:
```
public MyClass(){
var properties = this.GetType().GetProperties();
foreach(PropertyInfo p in properties){
p.SetValue(this, DoStuff(p.Name), new object[0]);
}
}
```
So the above constructor will thrown an error because I'm not supplying the generic type.
So how do I pass in the type of the property in?
|
Do you want to call DoStuff<T> with T = the type of each property? In which case, "as is" you would need to use reflection and MakeGenericMethod - i.e.
```
var properties = this.GetType().GetProperties();
foreach (PropertyInfo p in properties)
{
object value = typeof(MyClass)
.GetMethod("DoStuff")
.MakeGenericMethod(p.PropertyType)
.Invoke(null, new object[] { p.Name });
p.SetValue(this, value, null);
}
```
However, this isn't very pretty. In reality I wonder if it wouldn't be better just to have:
```
static object DoStuff(string name, Type propertyType);
... and then
object value = DoStuff(p.Name, p.PropertyType);
```
What does the generics give you in this example? Note that value-types will still get boxed etc during the reflection call - and even then boxing [isn't as bad as you might think](http://msmvps.com/blogs/jon_skeet/archive/2008/10/08/why-boxing-doesn-t-keep-me-awake-at-nights.aspx).
Finally, in many scenarios, TypeDescriptor.GetProperties() is more appropriate than Type.GetProperties() - allows for flexible object models etc.
|
196,946 |
<p>I was trying the following example, but with external URLs:
<a href="http://android-developers.blogspot.com/2008/09/using-webviews.html" rel="nofollow noreferrer">Using WebViews</a></p>
<p>The example shows how to load an HTML file from assets folder (<code>file:// url</code>) and display it in a WebView. </p>
<p>But when I try it with external URLs (like <a href="http://google.com" rel="nofollow noreferrer">http://google.com</a>), I am always getting a "Website Not Available" error. Android's built-in browser is able to access all external URLs. </p>
<p>I suspect that it has something to do with permissions, but wasn't able to confirm it.</p>
|
[
{
"answer_id": 198662,
"author": "Tahir Akhtar",
"author_id": 18027,
"author_profile": "https://Stackoverflow.com/users/18027",
"pm_score": 6,
"selected": true,
"text": "<p>I found out the answer myself.</p>\n\n<p>The permission name is android.permission.INTERNET.</p>\n\n<p>Adding following line to the AndroidManifest.xml (nested directly in tag) did the trick:</p>\n\n<pre><code><uses-permission android:name=\"android.permission.INTERNET\"></uses-permission>\n</code></pre>\n\n<p>The file can also be edited graphically in Eclipse plugin through permissions tab.</p>\n"
},
{
"answer_id": 679774,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>It's a user permission:</p>\n\n<pre><code><uses-permission android:name=\"android.permission.INTERNET\" />\n</code></pre>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/196946",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18027/"
] |
I was trying the following example, but with external URLs:
[Using WebViews](http://android-developers.blogspot.com/2008/09/using-webviews.html)
The example shows how to load an HTML file from assets folder (`file:// url`) and display it in a WebView.
But when I try it with external URLs (like <http://google.com>), I am always getting a "Website Not Available" error. Android's built-in browser is able to access all external URLs.
I suspect that it has something to do with permissions, but wasn't able to confirm it.
|
I found out the answer myself.
The permission name is android.permission.INTERNET.
Adding following line to the AndroidManifest.xml (nested directly in tag) did the trick:
```
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
```
The file can also be edited graphically in Eclipse plugin through permissions tab.
|
196,949 |
<p>I have an application that I have to run as Administrator.</p>
<p>One small part of that application is to start other applications with Process.Start</p>
<p>The started applications will also be run as administrators, but I'd rather see them run as the 'normal' user.</p>
<p>How do I accomplish that?</p>
<p>/johan/</p>
|
[
{
"answer_id": 196959,
"author": "Greg Dean",
"author_id": 1200558,
"author_profile": "https://Stackoverflow.com/users/1200558",
"pm_score": 3,
"selected": false,
"text": "<p>From: <a href=\"http://go.microsoft.com/fwlink/?LinkId=81232\" rel=\"nofollow noreferrer\">http://go.microsoft.com/fwlink/?LinkId=81232</a></p>\n\n<blockquote>\n <p>A frequently asked question is how to\n launch an un-elevated application from\n an elevated process, or more\n fundamentally, how to I launch a\n process using my un-elevated token\n once I’m running elevated. Since\n there is no direct way to do this, the\n situation can usually be avoided by\n launching the original application as\n standard user and only elevating those\n portions of the application that\n require administrative rights. This\n way there is always a non-elevated\n process that can be used to launch\n additional applications as the\n currently logged on desktop user. \n Sometimes, however, an elevated\n process needs to get another\n application running un-elevated. This\n can be accomplished by using the task\n scheduler within Windows Vista. The\n elevated process can register a task\n to run as the currently logged on\n desktop user.</p>\n</blockquote>\n\n<p>Here is an example of how to schedule the un-elevated process (again from the same link)</p>\n\n<pre><code>//---------------------------------------------------------------------\n// This file is part of the Microsoft .NET Framework SDK Code Samples.\n// \n// Copyright (C) Microsoft Corporation. All rights reserved.\n// \n//This source code is intended only as a supplement to Microsoft\n//Development Tools and/or on-line documentation. See these other\n//materials for detailed information regarding Microsoft code samples.\n// \n//THIS CODE AND INFORMATION ARE PROVIDED AS IS WITHOUT WARRANTY OF ANY\n//KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n//IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A\n//PARTICULAR PURPOSE.\n//---------------------------------------------------------------------\n\n/****************************************************************************\n* Main.cpp - Sample application for Task Scheduler V2 COMAPI * Component: Task Scheduler \n* Copyright (c) 2002 - 2003, Microsoft Corporation \n* This sample creates a task to that launches as the currently logged on deskup user. The task launches as soon as it is registered. *\n****************************************************************************/\n#include \"stdafx.h\"\n#include <windows.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <comdef.h>\n#include <comutil.h>\n//Include Task header files - Included in Windows Vista Beta-2 SDK from MSDN\n#include <taskschd.h>\n#include <conio.h>\n#include <iostream>\n#include <time.h>\n\nusing namespace std;\n\n#define CLEANUP \\\npRootFolder->Release();\\\n pTask->Release();\\\n CoUninitialize();\n\nHRESULT CreateMyTask(LPCWSTR, wstring);\n\nvoid __cdecl wmain(int argc, wchar_t** argv)\n{\nwstring wstrExecutablePath;\nWCHAR taskName[20];\nHRESULT result;\n\nif( argc < 2 )\n{\nprintf(\"\\nUsage: LaunchApp yourapp.exe\" );\nreturn;\n}\n\n// Pick random number for task name\nsrand((unsigned int) time(NULL));\nwsprintf((LPWSTR)taskName, L\"Launch %d\", rand());\n\nwstrExecutablePath = argv[1];\n\nresult = CreateMyTask(taskName, wstrExecutablePath);\nprintf(\"\\nReturn status:%d\\n\", result);\n\n}\nHRESULT CreateMyTask(LPCWSTR wszTaskName, wstring wstrExecutablePath)\n{\n // ------------------------------------------------------\n // Initialize COM.\nTASK_STATE taskState;\nint i;\n HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);\n if( FAILED(hr) )\n {\n printf(\"\\nCoInitializeEx failed: %x\", hr );\n return 1;\n }\n\n // Set general COM security levels.\n hr = CoInitializeSecurity(\n NULL,\n -1,\n NULL,\n NULL,\n RPC_C_AUTHN_LEVEL_PKT_PRIVACY,\n RPC_C_IMP_LEVEL_IMPERSONATE,\n NULL,\n 0,\n NULL);\n\n if( FAILED(hr) )\n {\n printf(\"\\nCoInitializeSecurity failed: %x\", hr );\n CoUninitialize();\n return 1;\n }\n\n // ------------------------------------------------------\n // Create an instance of the Task Service. \n ITaskService *pService = NULL;\n hr = CoCreateInstance( CLSID_TaskScheduler,\n NULL,\n CLSCTX_INPROC_SERVER,\n IID_ITaskService,\n (void**)&pService ); \n if (FAILED(hr))\n {\n printf(\"Failed to CoCreate an instance of the TaskService class: %x\", hr);\n CoUninitialize();\n return 1;\n }\n\n // Connect to the task service.\n hr = pService->Connect(_variant_t(), _variant_t(), _variant_t(), _variant_t());\n if( FAILED(hr) )\n {\n printf(\"ITaskService::Connect failed: %x\", hr );\n pService->Release();\n CoUninitialize();\n return 1;\n }\n\n // ------------------------------------------------------\n // Get the pointer to the root task folder. This folder will hold the\n // new task that is registered.\n ITaskFolder *pRootFolder = NULL;\n hr = pService->GetFolder( _bstr_t( L\"\\\\\") , &pRootFolder );\n if( FAILED(hr) )\n {\n printf(\"Cannot get Root Folder pointer: %x\", hr );\n pService->Release();\n CoUninitialize();\n return 1;\n }\n\n // Check if the same task already exists. If the same task exists, remove it.\n hr = pRootFolder->DeleteTask( _bstr_t( wszTaskName), 0 );\n\n // Create the task builder object to create the task.\n ITaskDefinition *pTask = NULL;\n hr = pService->NewTask( 0, &pTask );\n\n pService->Release(); // COM clean up. Pointer is no longer used.\n if (FAILED(hr))\n {\n printf(\"Failed to CoCreate an instance of the TaskService class: %x\", hr);\n pRootFolder->Release();\n CoUninitialize();\n return 1;\n }\n\n\n // ------------------------------------------------------\n // Get the trigger collection to insert the registration trigger.\n ITriggerCollection *pTriggerCollection = NULL;\n hr = pTask->get_Triggers( &pTriggerCollection );\n if( FAILED(hr) )\n {\n printf(\"\\nCannot get trigger collection: %x\", hr );\n CLEANUP\n return 1;\n }\n\n // Add the registration trigger to the task.\n ITrigger *pTrigger = NULL;\n\n hr = pTriggerCollection->Create( TASK_TRIGGER_REGISTRATION, &pTrigger ); \n pTriggerCollection->Release(); // COM clean up. Pointer is no longer used.\n if( FAILED(hr) )\n {\n printf(\"\\nCannot add registration trigger to the Task %x\", hr );\n CLEANUP\n return 1;\n }\n pTrigger->Release();\n\n // ------------------------------------------------------\n // Add an Action to the task. \n IExecAction *pExecAction = NULL;\n IActionCollection *pActionCollection = NULL;\n\n // Get the task action collection pointer.\n hr = pTask->get_Actions( &pActionCollection );\n if( FAILED(hr) )\n {\n printf(\"\\nCannot get Task collection pointer: %x\", hr );\n CLEANUP\n return 1;\n }\n\n // Create the action, specifying that it is an executable action.\n IAction *pAction = NULL;\n hr = pActionCollection->Create( TASK_ACTION_EXEC, &pAction );\n pActionCollection->Release(); // COM clean up. Pointer is no longer used.\n if( FAILED(hr) )\n {\n printf(\"\\npActionCollection->Create failed: %x\", hr );\n CLEANUP\n return 1;\n }\n\n hr = pAction->QueryInterface( IID_IExecAction, (void**) &pExecAction );\n pAction->Release();\n if( FAILED(hr) )\n {\n printf(\"\\npAction->QueryInterface failed: %x\", hr );\n CLEANUP\n return 1;\n }\n\n // Set the path of the executable to the user supplied executable.\n hr = pExecAction->put_Path( _bstr_t( wstrExecutablePath.c_str() ) ); \n\n if( FAILED(hr) )\n {\n printf(\"\\nCannot set path of executable: %x\", hr );\n pExecAction->Release();\n CLEANUP\n return 1;\n }\n hr = pExecAction->put_Arguments( _bstr_t( L\"\" ) ); \n\n if( FAILED(hr) )\n {\n printf(\"\\nCannot set arguments of executable: %x\", hr );\n pExecAction->Release();\n CLEANUP\n return 1;\n }\n\n // ------------------------------------------------------\n // Save the task in the root folder.\n IRegisteredTask *pRegisteredTask = NULL;\n hr = pRootFolder->RegisterTaskDefinition(\n _bstr_t( wszTaskName ),\n pTask,\n TASK_CREATE, \n_variant_t(_bstr_t( L\"S-1-5-32-545\")),//Well Known SID for \\\\Builtin\\Users group\n_variant_t(), \nTASK_LOGON_GROUP,\n _variant_t(L\"\"),\n &pRegisteredTask);\n if( FAILED(hr) )\n {\n printf(\"\\nError saving the Task : %x\", hr );\n CLEANUP\n return 1;\n }\n printf(\"\\n Success! Task successfully registered. \" );\n for (i=0; i<100; i++)//give 10 seconds for the task to start\n{\npRegisteredTask->get_State(&taskState);\nif (taskState == TASK_STATE_RUNNING)\n{\nprintf(\"\\nTask is running\\n\");\nbreak;\n}\nSleep(100);\n}\nif (i>= 100) printf(\"Task didn't start\\n\");\n\n //Delete the task when done\n hr = pRootFolder->DeleteTask(\n _bstr_t( wszTaskName ),\n NULL);\n if( FAILED(hr) )\n {\n printf(\"\\nError deleting the Task : %x\", hr );\n CLEANUP\n return 1;\n }\n\n printf(\"\\n Success! Task successfully deleted. \" );\n\n// Clean up.\n CLEANUP\n CoUninitialize();\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 287072,
"author": "Ian Boyd",
"author_id": 12597,
"author_profile": "https://Stackoverflow.com/users/12597",
"pm_score": 5,
"selected": true,
"text": "<p>The WinSafer API's allow a process to be launched as a limited, normal, or elevated user.</p>\n\n<p><strong>Sample Usage:</strong></p>\n\n<pre><code>CreateSaferProcess(@\"calc.exe\", \"\", SaferLevel.NormalUser);\n</code></pre>\n\n<p><strong>Source code:</strong></p>\n\n<pre><code>//http://odetocode.com/Blogs/scott/archive/2004/10/28/602.aspx\npublic static void CreateSaferProcess(String fileName, String arguments, SaferLevel saferLevel)\n{\n IntPtr saferLevelHandle = IntPtr.Zero;\n\n //Create a SaferLevel handle to match what was requested\n if (!WinSafer.SaferCreateLevel(\n SaferLevelScope.User, \n saferLevel, \n SaferOpen.Open, \n out saferLevelHandle, \n IntPtr.Zero))\n {\n throw new Win32Exception(Marshal.GetLastWin32Error());\n }\n try\n {\n //Generate the access token to use, based on the safer level handle.\n IntPtr hToken = IntPtr.Zero;\n\n if (!WinSafer.SaferComputeTokenFromLevel(\n saferLevelHandle, // SAFER Level handle\n IntPtr.Zero, // NULL is current thread token.\n out hToken, // Target token\n SaferTokenBehaviour.Default, // No flags\n IntPtr.Zero)) // Reserved\n {\n throw new Win32Exception(Marshal.GetLastWin32Error());\n }\n try\n {\n //Now that we have a security token, we can lauch the process\n //using the standard CreateProcessAsUser API\n STARTUPINFO si = new STARTUPINFO();\n si.cb = Marshal.SizeOf(si);\n si.lpDesktop = String.Empty;\n\n PROCESS_INFORMATION pi = new PROCESS_INFORMATION();\n\n // Spin up the new process\n Boolean bResult = Windows.CreateProcessAsUser(\n hToken,\n fileName,\n arguments,\n IntPtr.Zero, //process attributes\n IntPtr.Zero, //thread attributes\n false, //inherit handles\n 0, //CREATE_NEW_CONSOLE\n IntPtr.Zero, //environment\n null, //current directory\n ref si, //startup info\n out pi); //process info\n\n if (!bResult)\n throw new Win32Exception(Marshal.GetLastWin32Error());\n\n if (pi.hProcess != IntPtr.Zero)\n Windows.CloseHandle(pi.hProcess);\n\n if (pi.hThread != IntPtr.Zero)\n Windows.CloseHandle(pi.hThread);\n }\n finally\n {\n if (hToken != IntPtr.Zero)\n Windows.CloseHandle(hToken);\n }\n }\n finally\n {\n WinSafer.SaferCloseLevel(saferLevelHandle);\n }\n}\n</code></pre>\n\n<p><strong>P/Invoke declarations:</strong></p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.Runtime.InteropServices;\n\nnamespace PInvoke\n{\n public class WinSafer\n {\n /// <summary>\n /// The SaferCreateLevel function opens a SAFER_LEVEL_HANDLE.\n /// </summary>\n /// <param name=\"scopeId\">The scope of the level to be created.</param>\n /// <param name=\"levelId\">The level of the handle to be opened.</param>\n /// <param name=\"openFlags\">Must be SaferOpenFlags.Open</param>\n /// <param name=\"levelHandle\">The returned SAFER_LEVEL_HANDLE. When you have finished using the handle, release it by calling the SaferCloseLevel function.</param>\n /// <param name=\"reserved\">This parameter is reserved for future use. IntPtr.Zero</param>\n /// <returns></returns>\n [DllImport(\"advapi32\", SetLastError = true, CallingConvention = CallingConvention.StdCall)]\n public static extern bool SaferCreateLevel(SaferLevelScope scopeId, SaferLevel levelId, SaferOpen openFlags,\n out IntPtr levelHandle, IntPtr reserved);\n\n /// <summary>\n /// The SaferComputeTokenFromLevel function restricts a token using restrictions specified by a SAFER_LEVEL_HANDLE.\n /// </summary>\n /// <param name=\"levelHandle\">SAFER_LEVEL_HANDLE that contains the restrictions to place on the input token. Do not pass handles with a LevelId of SAFER_LEVELID_FULLYTRUSTED or SAFER_LEVELID_DISALLOWED to this function. This is because SAFER_LEVELID_FULLYTRUSTED is unrestricted and SAFER_LEVELID_DISALLOWED does not contain a token.</param>\n /// <param name=\"inAccessToken\">Token to be restricted. If this parameter is NULL, the token of the current thread will be used. If the current thread does not contain a token, the token of the current process is used.</param>\n /// <param name=\"outAccessToken\">The resulting restricted token.</param>\n /// <param name=\"flags\">Specifies the behavior of the method.</param>\n /// <param name=\"lpReserved\">Reserved for future use. This parameter should be set to IntPtr.EmptyParam.</param>\n /// <returns></returns>\n [DllImport(\"advapi32\", SetLastError = true, CallingConvention = CallingConvention.StdCall)]\n public static extern bool SaferComputeTokenFromLevel(IntPtr levelHandle, IntPtr inAccessToken,\n out IntPtr outAccessToken, SaferTokenBehaviour flags, IntPtr lpReserved);\n\n /// <summary>\n /// The SaferCloseLevel function closes a SAFER_LEVEL_HANDLE that was opened by using the SaferIdentifyLevel function or the SaferCreateLevel function.</summary>\n /// <param name=\"levelHandle\">The SAFER_LEVEL_HANDLE to be closed.</param>\n /// <returns>TRUE if the function succeeds; otherwise, FALSE. For extended error information, call GetLastWin32Error.</returns>\n [DllImport(\"advapi32\", SetLastError = true, CallingConvention = CallingConvention.StdCall)]\n public static extern bool SaferCloseLevel(IntPtr levelHandle);\n } //class WinSafer\n\n /// <summary>\n /// Specifies the behaviour of the SaferComputeTokenFromLevel method\n /// </summary>\n public enum SaferTokenBehaviour : uint\n {\n /// <summary></summary>\n Default = 0x0,\n /// <summary>If the OutAccessToken parameter is not more restrictive than the InAccessToken parameter, the OutAccessToken parameter returns NULL.</summary>\n NullIfEqual = 0x1,\n /// <summary></summary>\n CompareOnly = 0x2,\n /// <summary></summary>\n MakeInert = 0x4,\n /// <summary></summary>\n WantFlags = 0x8\n }\n\n /// <summary>\n /// The level of the handle to be opened.\n /// </summary>\n public enum SaferLevel : uint\n {\n /// <summary>Software will not run, regardless of the user rights of the user.</summary>\n Disallowed = 0,\n /// <summary>Allows programs to execute with access only to resources granted to open well-known groups, blocking access to Administrator and Power User privileges and personally granted rights.</summary>\n Untrusted = 0x1000,\n /// <summary>Software cannot access certain resources, such as cryptographic keys and credentials, regardless of the user rights of the user.</summary>\n Constrained = 0x10000,\n /// <summary>Allows programs to execute as a user that does not have Administrator or Power User user rights. Software can access resources accessible by normal users.</summary>\n NormalUser = 0x20000,\n /// <summary>Software user rights are determined by the user rights of the user.</summary>\n FullyTrusted = 0x40000\n }\n\n /// <summary>\n /// The scope of the level to be created.\n /// </summary>\n public enum SaferLevelScope : uint\n {\n /// <summary>The created level is scoped by computer.</summary>\n Machine = 1,\n /// <summary>The created level is scoped by user.</summary>\n User = 2\n }\n\n public enum SaferOpen : uint\n {\n Open = 1\n }\n} //namespace PInvoke\n</code></pre>\n"
},
{
"answer_id": 34473238,
"author": "magicandre1981",
"author_id": 1466046,
"author_profile": "https://Stackoverflow.com/users/1466046",
"pm_score": 2,
"selected": false,
"text": "<p>I had the same requirement and I come to the solution to use the task scheduler service from Windows.</p>\n\n<p>So, first add <a href=\"https://taskscheduler.codeplex.com/\" rel=\"nofollow\">the <code>Task Scheduler Managed Wrapper</code></a> <a href=\"https://www.nuget.org/packages/TaskScheduler/\" rel=\"nofollow\">library to your project</a> and use this code to create a task, configure it to run as limited user (<code>td.Principal.RunLevel = TaskRunLevel.LUA;</code>), register the task, run the task and after finish, delete the task.</p>\n\n<pre><code>// Get the service on the local machine\nusing (var ts = new TaskService())\n{\n const string taskName = \"foo\";\n\n // Create a new task definition and assign properties\n var td = ts.NewTask();\n td.RegistrationInfo.Description = \"start foo.exe as limited user\";\n\n // Create an action that will launch foo.exe, with argument bar in workingdir C:\\\\\n td.Actions.Add(new ExecAction(\"C:\\\\foo.exe\", \"bar\", \"C:\\\\\"));\n\n td.Settings.Priority = ProcessPriorityClass.Normal;\n\n // run with limited token\n td.Principal.RunLevel = TaskRunLevel.LUA;\n\n td.Settings.AllowDemandStart = true;\n\n td.Settings.DisallowStartIfOnBatteries = false;\n\n td.Settings.StopIfGoingOnBatteries = false;\n\n // Register the task in the root folder\n var ret = ts.RootFolder.RegisterTaskDefinition(taskName, td);\n\n var fooTask = ts.FindTask(taskName, true);\n if (null != fooTask )\n {\n if (fooTask.Enabled)\n {\n fooTask.Run();\n\n Thread.Sleep(TimeSpan.FromSeconds(1));\n\n // find process and wait for Exit\n var processlist = Process.GetProcesses();\n\n foreach(var theprocess in processlist)\n {\n if (theprocess.ProcessName != \"foo\")\n continue;\n\n theprocess.WaitForExit();\n break;\n }\n }\n }\n\n // Remove the task we just created\n ts.RootFolder.DeleteTask(taskName);\n}\n</code></pre>\n"
},
{
"answer_id": 58579679,
"author": "Paul",
"author_id": 2604492,
"author_profile": "https://Stackoverflow.com/users/2604492",
"pm_score": 2,
"selected": false,
"text": "<p>Raymond Chen addressed this in his blog:</p>\n\n<p><a href=\"https://devblogs.microsoft.com/oldnewthing/?p=2643\" rel=\"nofollow noreferrer\">How can I launch an unelevated process from my elevated process and vice versa?</a></p>\n\n<p>Searching in GitHub for a C# version of this code, I found the following implementation in Microsoft's <strong>Node.js tools for Visual Studio</strong> repository: <a href=\"https://github.com/microsoft/nodejstools/blob/master/Nodejs/Product/Nodejs/SharedProject/SystemUtilities.cs\" rel=\"nofollow noreferrer\">SystemUtilities.cs</a> (the <code>ExecuteProcessUnElevated</code> function).</p>\n\n<p>Just in case the file disappears, here's the file's contents:</p>\n\n<pre><code>// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\n\nusing System;\nusing System.Runtime.InteropServices;\n\nnamespace Microsoft.NodejsTools.SharedProject\n{\n /// <summary>\n /// Utility for accessing window IShell* interfaces in order to use them to launch a process unelevated\n /// </summary>\n internal class SystemUtility\n {\n /// <summary>\n /// We are elevated and should launch the process unelevated. We can't create the\n /// process directly without it becoming elevated. So to workaround this, we have\n /// explorer do the process creation (explorer is typically running unelevated).\n /// </summary>\n internal static void ExecuteProcessUnElevated(string process, string args, string currentDirectory = \"\")\n {\n var shellWindows = (IShellWindows)new CShellWindows();\n\n // Get the desktop window\n object loc = CSIDL_Desktop;\n object unused = new object();\n int hwnd;\n var serviceProvider = (IServiceProvider)shellWindows.FindWindowSW(ref loc, ref unused, SWC_DESKTOP, out hwnd, SWFO_NEEDDISPATCH);\n\n // Get the shell browser\n var serviceGuid = SID_STopLevelBrowser;\n var interfaceGuid = typeof(IShellBrowser).GUID;\n var shellBrowser = (IShellBrowser)serviceProvider.QueryService(ref serviceGuid, ref interfaceGuid);\n\n // Get the shell dispatch\n var dispatch = typeof(IDispatch).GUID;\n var folderView = (IShellFolderViewDual)shellBrowser.QueryActiveShellView().GetItemObject(SVGIO_BACKGROUND, ref dispatch);\n var shellDispatch = (IShellDispatch2)folderView.Application;\n\n // Use the dispatch (which is unelevated) to launch the process for us\n shellDispatch.ShellExecute(process, args, currentDirectory, string.Empty, SW_SHOWNORMAL);\n }\n\n /// <summary>\n /// Interop definitions\n /// </summary>\n private const int CSIDL_Desktop = 0;\n private const int SWC_DESKTOP = 8;\n private const int SWFO_NEEDDISPATCH = 1;\n private const int SW_SHOWNORMAL = 1;\n private const int SVGIO_BACKGROUND = 0;\n private readonly static Guid SID_STopLevelBrowser = new Guid(\"4C96BE40-915C-11CF-99D3-00AA004AE837\");\n\n [ComImport]\n [Guid(\"9BA05972-F6A8-11CF-A442-00A0C90A8F39\")]\n [ClassInterfaceAttribute(ClassInterfaceType.None)]\n private class CShellWindows\n {\n }\n\n [ComImport]\n [Guid(\"85CB6900-4D95-11CF-960C-0080C7F4EE85\")]\n [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]\n private interface IShellWindows\n {\n [return: MarshalAs(UnmanagedType.IDispatch)]\n object FindWindowSW([MarshalAs(UnmanagedType.Struct)] ref object pvarloc, [MarshalAs(UnmanagedType.Struct)] ref object pvarlocRoot, int swClass, out int pHWND, int swfwOptions);\n }\n\n [ComImport]\n [Guid(\"6d5140c1-7436-11ce-8034-00aa006009fa\")]\n [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]\n private interface IServiceProvider\n {\n [return: MarshalAs(UnmanagedType.Interface)]\n object QueryService(ref Guid guidService, ref Guid riid);\n }\n\n [ComImport]\n [Guid(\"000214E2-0000-0000-C000-000000000046\")]\n [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]\n private interface IShellBrowser\n {\n void VTableGap01(); // GetWindow\n void VTableGap02(); // ContextSensitiveHelp\n void VTableGap03(); // InsertMenusSB\n void VTableGap04(); // SetMenuSB\n void VTableGap05(); // RemoveMenusSB\n void VTableGap06(); // SetStatusTextSB\n void VTableGap07(); // EnableModelessSB\n void VTableGap08(); // TranslateAcceleratorSB\n void VTableGap09(); // BrowseObject\n void VTableGap10(); // GetViewStateStream\n void VTableGap11(); // GetControlWindow\n void VTableGap12(); // SendControlMsg\n IShellView QueryActiveShellView();\n }\n\n [ComImport]\n [Guid(\"000214E3-0000-0000-C000-000000000046\")]\n [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]\n private interface IShellView\n {\n void VTableGap01(); // GetWindow\n void VTableGap02(); // ContextSensitiveHelp\n void VTableGap03(); // TranslateAcceleratorA\n void VTableGap04(); // EnableModeless\n void VTableGap05(); // UIActivate\n void VTableGap06(); // Refresh\n void VTableGap07(); // CreateViewWindow\n void VTableGap08(); // DestroyViewWindow\n void VTableGap09(); // GetCurrentInfo\n void VTableGap10(); // AddPropertySheetPages\n void VTableGap11(); // SaveViewState\n void VTableGap12(); // SelectItem\n\n [return: MarshalAs(UnmanagedType.Interface)]\n object GetItemObject(UInt32 aspectOfView, ref Guid riid);\n }\n\n [ComImport]\n [Guid(\"00020400-0000-0000-C000-000000000046\")]\n [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]\n private interface IDispatch\n {\n }\n\n [ComImport]\n [Guid(\"E7A1AF80-4D96-11CF-960C-0080C7F4EE85\")]\n [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]\n private interface IShellFolderViewDual\n {\n object Application { [return: MarshalAs(UnmanagedType.IDispatch)] get; }\n }\n\n [ComImport]\n [Guid(\"A4C6892C-3BA9-11D2-9DEA-00C04FB16162\")]\n [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]\n public interface IShellDispatch2\n {\n void ShellExecute([MarshalAs(UnmanagedType.BStr)] string File, [MarshalAs(UnmanagedType.Struct)] object vArgs, [MarshalAs(UnmanagedType.Struct)] object vDir, [MarshalAs(UnmanagedType.Struct)] object vOperation, [MarshalAs(UnmanagedType.Struct)] object vShow);\n }\n }\n}\n</code></pre>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/196949",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21761/"
] |
I have an application that I have to run as Administrator.
One small part of that application is to start other applications with Process.Start
The started applications will also be run as administrators, but I'd rather see them run as the 'normal' user.
How do I accomplish that?
/johan/
|
The WinSafer API's allow a process to be launched as a limited, normal, or elevated user.
**Sample Usage:**
```
CreateSaferProcess(@"calc.exe", "", SaferLevel.NormalUser);
```
**Source code:**
```
//http://odetocode.com/Blogs/scott/archive/2004/10/28/602.aspx
public static void CreateSaferProcess(String fileName, String arguments, SaferLevel saferLevel)
{
IntPtr saferLevelHandle = IntPtr.Zero;
//Create a SaferLevel handle to match what was requested
if (!WinSafer.SaferCreateLevel(
SaferLevelScope.User,
saferLevel,
SaferOpen.Open,
out saferLevelHandle,
IntPtr.Zero))
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
try
{
//Generate the access token to use, based on the safer level handle.
IntPtr hToken = IntPtr.Zero;
if (!WinSafer.SaferComputeTokenFromLevel(
saferLevelHandle, // SAFER Level handle
IntPtr.Zero, // NULL is current thread token.
out hToken, // Target token
SaferTokenBehaviour.Default, // No flags
IntPtr.Zero)) // Reserved
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
try
{
//Now that we have a security token, we can lauch the process
//using the standard CreateProcessAsUser API
STARTUPINFO si = new STARTUPINFO();
si.cb = Marshal.SizeOf(si);
si.lpDesktop = String.Empty;
PROCESS_INFORMATION pi = new PROCESS_INFORMATION();
// Spin up the new process
Boolean bResult = Windows.CreateProcessAsUser(
hToken,
fileName,
arguments,
IntPtr.Zero, //process attributes
IntPtr.Zero, //thread attributes
false, //inherit handles
0, //CREATE_NEW_CONSOLE
IntPtr.Zero, //environment
null, //current directory
ref si, //startup info
out pi); //process info
if (!bResult)
throw new Win32Exception(Marshal.GetLastWin32Error());
if (pi.hProcess != IntPtr.Zero)
Windows.CloseHandle(pi.hProcess);
if (pi.hThread != IntPtr.Zero)
Windows.CloseHandle(pi.hThread);
}
finally
{
if (hToken != IntPtr.Zero)
Windows.CloseHandle(hToken);
}
}
finally
{
WinSafer.SaferCloseLevel(saferLevelHandle);
}
}
```
**P/Invoke declarations:**
```
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace PInvoke
{
public class WinSafer
{
/// <summary>
/// The SaferCreateLevel function opens a SAFER_LEVEL_HANDLE.
/// </summary>
/// <param name="scopeId">The scope of the level to be created.</param>
/// <param name="levelId">The level of the handle to be opened.</param>
/// <param name="openFlags">Must be SaferOpenFlags.Open</param>
/// <param name="levelHandle">The returned SAFER_LEVEL_HANDLE. When you have finished using the handle, release it by calling the SaferCloseLevel function.</param>
/// <param name="reserved">This parameter is reserved for future use. IntPtr.Zero</param>
/// <returns></returns>
[DllImport("advapi32", SetLastError = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool SaferCreateLevel(SaferLevelScope scopeId, SaferLevel levelId, SaferOpen openFlags,
out IntPtr levelHandle, IntPtr reserved);
/// <summary>
/// The SaferComputeTokenFromLevel function restricts a token using restrictions specified by a SAFER_LEVEL_HANDLE.
/// </summary>
/// <param name="levelHandle">SAFER_LEVEL_HANDLE that contains the restrictions to place on the input token. Do not pass handles with a LevelId of SAFER_LEVELID_FULLYTRUSTED or SAFER_LEVELID_DISALLOWED to this function. This is because SAFER_LEVELID_FULLYTRUSTED is unrestricted and SAFER_LEVELID_DISALLOWED does not contain a token.</param>
/// <param name="inAccessToken">Token to be restricted. If this parameter is NULL, the token of the current thread will be used. If the current thread does not contain a token, the token of the current process is used.</param>
/// <param name="outAccessToken">The resulting restricted token.</param>
/// <param name="flags">Specifies the behavior of the method.</param>
/// <param name="lpReserved">Reserved for future use. This parameter should be set to IntPtr.EmptyParam.</param>
/// <returns></returns>
[DllImport("advapi32", SetLastError = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool SaferComputeTokenFromLevel(IntPtr levelHandle, IntPtr inAccessToken,
out IntPtr outAccessToken, SaferTokenBehaviour flags, IntPtr lpReserved);
/// <summary>
/// The SaferCloseLevel function closes a SAFER_LEVEL_HANDLE that was opened by using the SaferIdentifyLevel function or the SaferCreateLevel function.</summary>
/// <param name="levelHandle">The SAFER_LEVEL_HANDLE to be closed.</param>
/// <returns>TRUE if the function succeeds; otherwise, FALSE. For extended error information, call GetLastWin32Error.</returns>
[DllImport("advapi32", SetLastError = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool SaferCloseLevel(IntPtr levelHandle);
} //class WinSafer
/// <summary>
/// Specifies the behaviour of the SaferComputeTokenFromLevel method
/// </summary>
public enum SaferTokenBehaviour : uint
{
/// <summary></summary>
Default = 0x0,
/// <summary>If the OutAccessToken parameter is not more restrictive than the InAccessToken parameter, the OutAccessToken parameter returns NULL.</summary>
NullIfEqual = 0x1,
/// <summary></summary>
CompareOnly = 0x2,
/// <summary></summary>
MakeInert = 0x4,
/// <summary></summary>
WantFlags = 0x8
}
/// <summary>
/// The level of the handle to be opened.
/// </summary>
public enum SaferLevel : uint
{
/// <summary>Software will not run, regardless of the user rights of the user.</summary>
Disallowed = 0,
/// <summary>Allows programs to execute with access only to resources granted to open well-known groups, blocking access to Administrator and Power User privileges and personally granted rights.</summary>
Untrusted = 0x1000,
/// <summary>Software cannot access certain resources, such as cryptographic keys and credentials, regardless of the user rights of the user.</summary>
Constrained = 0x10000,
/// <summary>Allows programs to execute as a user that does not have Administrator or Power User user rights. Software can access resources accessible by normal users.</summary>
NormalUser = 0x20000,
/// <summary>Software user rights are determined by the user rights of the user.</summary>
FullyTrusted = 0x40000
}
/// <summary>
/// The scope of the level to be created.
/// </summary>
public enum SaferLevelScope : uint
{
/// <summary>The created level is scoped by computer.</summary>
Machine = 1,
/// <summary>The created level is scoped by user.</summary>
User = 2
}
public enum SaferOpen : uint
{
Open = 1
}
} //namespace PInvoke
```
|
196,960 |
<p>I have a dict, which I need to pass key/values as keyword arguments.. For example..</p>
<pre><code>d_args = {'kw1': 'value1', 'kw2': 'value2'}
example(**d_args)
</code></pre>
<p>This works fine, <em>but</em> if there are values in the d_args dict that are not accepted by the <code>example</code> function, it obviously dies.. Say, if the example function is defined as <code>def example(kw2):</code></p>
<p>This is a problem since I don't control either the generation of the <code>d_args</code>, or the <code>example</code> function.. They both come from external modules, and <code>example</code> only accepts some of the keyword-arguments from the dict..</p>
<p>Ideally I would just do</p>
<pre><code>parsed_kwargs = feedparser.parse(the_url)
valid_kwargs = get_valid_kwargs(parsed_kwargs, valid_for = PyRSS2Gen.RSS2)
PyRSS2Gen.RSS2(**valid_kwargs)
</code></pre>
<p>I will probably just filter the dict, from a list of valid keyword-arguments, but I was wondering: <strong>Is there a way to programatically list the keyword arguments the a specific function takes?</strong></p>
|
[
{
"answer_id": 196978,
"author": "DzinX",
"author_id": 18745,
"author_profile": "https://Stackoverflow.com/users/18745",
"pm_score": 5,
"selected": false,
"text": "<p>This will print names of all passable arguments, keyword and non-keyword ones:</p>\n<pre><code>def func(one, two="value"):\n y = one, two\n return y\nprint func.func_code.co_varnames[:func.func_code.co_argcount]\n</code></pre>\n<p>This is because first <code>co_varnames</code> are always parameters (next are local variables, like <code>y</code> in the example above).</p>\n<p>So now you could have a function:</p>\n<pre><code>def get_valid_args(func, args_dict):\n '''Return dictionary without invalid function arguments.'''\n validArgs = func.func_code.co_varnames[:func.func_code.co_argcount]\n return dict((key, value) for key, value in args_dict.iteritems() \n if key in validArgs)\n</code></pre>\n<p>Which you then could use like this:</p>\n<pre><code>>>> func(**get_valid_args(func, args))\n</code></pre>\n<hr />\n<p>if you <strong>really need only keyword arguments</strong> of a function, you can use the <code>func_defaults</code> attribute to extract them:</p>\n<pre><code>def get_valid_kwargs(func, args_dict):\n validArgs = func.func_code.co_varnames[:func.func_code.co_argcount]\n kwargsLen = len(func.func_defaults) # number of keyword arguments\n validKwargs = validArgs[-kwargsLen:] # because kwargs are last\n return dict((key, value) for key, value in args_dict.iteritems() \n if key in validKwargs)\n</code></pre>\n<p>You could now call your function with known args, but extracted kwargs, e.g.:</p>\n<pre><code>func(param1, param2, **get_valid_kwargs(func, kwargs_dict))\n</code></pre>\n<p>This assumes that <code>func</code> uses no <code>*args</code> or <code>**kwargs</code> magic in its signature.</p>\n"
},
{
"answer_id": 196997,
"author": "Claudiu",
"author_id": 15055,
"author_profile": "https://Stackoverflow.com/users/15055",
"pm_score": 2,
"selected": false,
"text": "<p>Extending DzinX's answer:</p>\n\n<pre><code>argnames = example.func_code.co_varnames[:func.func_code.co_argcount]\nargs = dict((key, val) for key,val in d_args.iteritems() if key in argnames)\nexample(**args)\n</code></pre>\n"
},
{
"answer_id": 197053,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 8,
"selected": true,
"text": "<p>A little nicer than inspecting the code object directly and working out the variables is to use the inspect module.</p>\n<pre><code>>>> import inspect\n>>> def func(a,b,c=42, *args, **kwargs): pass\n>>> inspect.getargspec(func)\n(['a', 'b', 'c'], 'args', 'kwargs', (42,))\n</code></pre>\n<p>If you want to know if its callable with a particular set of args, you need the args without a default already specified. These can be got by:</p>\n<pre><code>def get_required_args(func):\n args, varargs, varkw, defaults = inspect.getargspec(func)\n if defaults:\n args = args[:-len(defaults)]\n return args # *args and **kwargs are not required, so ignore them.\n</code></pre>\n<p>Then a function to tell what you are missing from your particular dict is:</p>\n<pre><code>def missing_args(func, argdict):\n return set(get_required_args(func)).difference(argdict)\n</code></pre>\n<p>Similarly, to check for invalid args, use:</p>\n<pre><code>def invalid_args(func, argdict):\n args, varargs, varkw, defaults = inspect.getargspec(func)\n if varkw: return set() # All accepted\n return set(argdict) - set(args)\n</code></pre>\n<p>And so a full test if it is callable is :</p>\n<pre><code>def is_callable_with_args(func, argdict):\n return not missing_args(func, argdict) and not invalid_args(func, argdict)\n</code></pre>\n<p>(This is good only as far as python's arg parsing. Any runtime checks for invalid values in <code>kwargs</code> obviously can't be detected.)</p>\n"
},
{
"answer_id": 197101,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 3,
"selected": false,
"text": "<p>In Python 3.0:</p>\n\n<pre><code>>>> import inspect\n>>> import fileinput\n>>> print(inspect.getfullargspec(fileinput.input))\nFullArgSpec(args=['files', 'inplace', 'backup', 'bufsize', 'mode', 'openhook'],\nvarargs=None, varkw=None, defaults=(None, 0, '', 0, 'r', None), kwonlyargs=[], \nkwdefaults=None, annotations={})\n</code></pre>\n"
},
{
"answer_id": 45373004,
"author": "Dimitris Fasarakis Hilliard",
"author_id": 4952130,
"author_profile": "https://Stackoverflow.com/users/4952130",
"pm_score": 4,
"selected": false,
"text": "<p>For a Python 3 solution, you can use <a href=\"https://docs.python.org/3/library/inspect.html#inspect.signature\" rel=\"noreferrer\"><code>inspect.signature</code></a> and filter according to <a href=\"https://docs.python.org/3/library/inspect.html#inspect.Parameter.kind\" rel=\"noreferrer\">the kind of parameters</a> you'd like to know about. </p>\n\n<p>Taking a sample function with positional or keyword, keyword-only, var positional and var keyword parameters:</p>\n\n<pre><code>def spam(a, b=1, *args, c=2, **kwargs):\n print(a, b, args, c, kwargs)\n</code></pre>\n\n<p>You can create a signature object for it:</p>\n\n<pre><code>from inspect import signature\nsig = signature(spam)\n</code></pre>\n\n<p>and then filter with a list comprehension to find out the details you need:</p>\n\n<pre><code>>>> # positional or keyword\n>>> [p.name for p in sig.parameters.values() if p.kind == p.POSITIONAL_OR_KEYWORD]\n['a', 'b']\n>>> # keyword only\n>>> [p.name for p in sig.parameters.values() if p.kind == p.KEYWORD_ONLY]\n['c']\n</code></pre>\n\n<p>and, similarly, for var positionals using <code>p.VAR_POSITIONAL</code> and var keyword with <code>VAR_KEYWORD</code>. </p>\n\n<p>In addition, you can add a clause to the if to check if a default value exists by checking if <code>p.default</code> equals <code>p.empty</code>.</p>\n"
},
{
"answer_id": 67854523,
"author": "Sumit",
"author_id": 15582748,
"author_profile": "https://Stackoverflow.com/users/15582748",
"pm_score": 2,
"selected": false,
"text": "<p>Just use this for a function name 'myfun':</p>\n<pre><code>myfun.__code__.co_varnames\n</code></pre>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/196960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/745/"
] |
I have a dict, which I need to pass key/values as keyword arguments.. For example..
```
d_args = {'kw1': 'value1', 'kw2': 'value2'}
example(**d_args)
```
This works fine, *but* if there are values in the d\_args dict that are not accepted by the `example` function, it obviously dies.. Say, if the example function is defined as `def example(kw2):`
This is a problem since I don't control either the generation of the `d_args`, or the `example` function.. They both come from external modules, and `example` only accepts some of the keyword-arguments from the dict..
Ideally I would just do
```
parsed_kwargs = feedparser.parse(the_url)
valid_kwargs = get_valid_kwargs(parsed_kwargs, valid_for = PyRSS2Gen.RSS2)
PyRSS2Gen.RSS2(**valid_kwargs)
```
I will probably just filter the dict, from a list of valid keyword-arguments, but I was wondering: **Is there a way to programatically list the keyword arguments the a specific function takes?**
|
A little nicer than inspecting the code object directly and working out the variables is to use the inspect module.
```
>>> import inspect
>>> def func(a,b,c=42, *args, **kwargs): pass
>>> inspect.getargspec(func)
(['a', 'b', 'c'], 'args', 'kwargs', (42,))
```
If you want to know if its callable with a particular set of args, you need the args without a default already specified. These can be got by:
```
def get_required_args(func):
args, varargs, varkw, defaults = inspect.getargspec(func)
if defaults:
args = args[:-len(defaults)]
return args # *args and **kwargs are not required, so ignore them.
```
Then a function to tell what you are missing from your particular dict is:
```
def missing_args(func, argdict):
return set(get_required_args(func)).difference(argdict)
```
Similarly, to check for invalid args, use:
```
def invalid_args(func, argdict):
args, varargs, varkw, defaults = inspect.getargspec(func)
if varkw: return set() # All accepted
return set(argdict) - set(args)
```
And so a full test if it is callable is :
```
def is_callable_with_args(func, argdict):
return not missing_args(func, argdict) and not invalid_args(func, argdict)
```
(This is good only as far as python's arg parsing. Any runtime checks for invalid values in `kwargs` obviously can't be detected.)
|
196,966 |
<p>I need to develop a generic jQuery-based search plugin for the ASP.NET MVC application I'm building, but I can't figure out how it's supposed to fit, or what the best practice is. I want to do the following:</p>
<pre><code>$().ready(function() {
$('#searchHolder').customSearch('MyApp.Models.User');
});
</code></pre>
<p>As long as I have implemented a specific interface on Models.User, jQuery will be able to talk to a reflection service to generically construct the relevant UI.</p>
<p>Sounds fun, but it seems that I'm now calling the JavaScript from the View, which is in turn going to do some View-related activity to build the search UI, and then to do the search and interact with the user it's going to throw a bunch of Controller tasks in there.</p>
<p>So where does this really fit? Is there a different way I can structure my jQuery plugin so that it conforms more to the idea of MVC? Does MVC work when it scales down to its own form <em>within</em> another MVC structure? Should I just ignore these issues for the sake of one plugin?</p>
|
[
{
"answer_id": 196999,
"author": "liggett78",
"author_id": 19762,
"author_profile": "https://Stackoverflow.com/users/19762",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not sure I understand what you're trying to accomplish, but I would construct the relevant UI on the server as part of your view (e.g. as a user control that can be rendered on different pages), set it's display:none style and use JQuery on the client side to show it when the user clicks on some link or whatever.</p>\n\n<p>After that the plugin would use $.ajax to send the search request to your application where you can perform relevant activities and render a partial view with your search result. Your ajax code would then pick it up and insert it in your document.</p>\n"
},
{
"answer_id": 200340,
"author": "tags2k",
"author_id": 192,
"author_profile": "https://Stackoverflow.com/users/192",
"pm_score": 3,
"selected": true,
"text": "<p>Just to follow up (I'm very surprised nobody else has had any opinions on this), in an effort to keep best practice I've opted to adopt <a href=\"http://jtemplates.tpython.com/\" rel=\"nofollow noreferrer\">jTemplates</a>.</p>\n\n<p>It enables me to request some Model-style JSON from my server-side Controller and process it using syntax similar to that I would already use in a View, which now keeps any required JavaScript UI MVC-compatible. There's a small overhead in that the client will need to request the View template from the server, but if that becomes too slow I can always sacrifice a little and send it over with the initial JSON request.</p>\n"
},
{
"answer_id": 200385,
"author": "Ken",
"author_id": 20074,
"author_profile": "https://Stackoverflow.com/users/20074",
"pm_score": 0,
"selected": false,
"text": "<p>Approach it as if you have two seperate systems, with models,views and controllers on the server and (Javascript/DOM) models, views and controllers on the client(browser). Ajax is just the client's method of requesting services from the Server. </p>\n"
},
{
"answer_id": 200410,
"author": "roryf",
"author_id": 270,
"author_profile": "https://Stackoverflow.com/users/270",
"pm_score": 1,
"selected": false,
"text": "<p>It sounds to me like what you want are <code>partials</code>, a RoR term so not sure that they exist in the same format in ASP.NET MVC. Basically a partial is a part of a View thats defined in its own file and can be called from anywhere. So in your search controller, you would pull out the Model asked for, do some reflection to get the data and construct it into JSON, and also grab the partial View for that model. You might find it easier if you follow a convention for naming the partials based on the Model name, to save you having any big <code>switch</code> statements or extra config files.</p>\n\n<p>I could be wrong, but it sounds like you're a bit worried making a call to the Controller from Javascript and getting HTML returned. Thats perfectly OK, its just a case of fetching the View appropriately and making sure you don't process the rest of the page, only what you need for that call (why MVC is so much better than <code>UpdatePanel</code>s!)</p>\n"
},
{
"answer_id": 4436090,
"author": "David Pirek",
"author_id": 183916,
"author_profile": "https://Stackoverflow.com/users/183916",
"pm_score": 1,
"selected": false,
"text": "<p>so I have actually been looking into this a lot lot, and have found that the new officially supported jquery plugin tmpl can work as a view engine. I have <a href=\"http://www.davidpirek.com/blog/javascript-mvc-view-engine-with-jquerytmpl-js\" rel=\"nofollow\">written a tutorial here</a>, how you can create a full MVC/MVP paradigm in JavaScript</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/196966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/192/"
] |
I need to develop a generic jQuery-based search plugin for the ASP.NET MVC application I'm building, but I can't figure out how it's supposed to fit, or what the best practice is. I want to do the following:
```
$().ready(function() {
$('#searchHolder').customSearch('MyApp.Models.User');
});
```
As long as I have implemented a specific interface on Models.User, jQuery will be able to talk to a reflection service to generically construct the relevant UI.
Sounds fun, but it seems that I'm now calling the JavaScript from the View, which is in turn going to do some View-related activity to build the search UI, and then to do the search and interact with the user it's going to throw a bunch of Controller tasks in there.
So where does this really fit? Is there a different way I can structure my jQuery plugin so that it conforms more to the idea of MVC? Does MVC work when it scales down to its own form *within* another MVC structure? Should I just ignore these issues for the sake of one plugin?
|
Just to follow up (I'm very surprised nobody else has had any opinions on this), in an effort to keep best practice I've opted to adopt [jTemplates](http://jtemplates.tpython.com/).
It enables me to request some Model-style JSON from my server-side Controller and process it using syntax similar to that I would already use in a View, which now keeps any required JavaScript UI MVC-compatible. There's a small overhead in that the client will need to request the View template from the server, but if that becomes too slow I can always sacrifice a little and send it over with the initial JSON request.
|
196,972 |
<p>Is there a simple way to convert a string to Title Case? E.g. <code>john smith</code> becomes <code>John Smith</code>. I'm not looking for something complicated like <a href="http://ejohn.org/blog/title-capitalization-in-javascript/" rel="noreferrer">John Resig's solution</a>, just (hopefully) some kind of one- or two-liner.</p>
|
[
{
"answer_id": 196989,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 3,
"selected": false,
"text": "<pre><code>var toMatch = \"john w. smith\";\nvar result = toMatch.replace(/(\\w)(\\w*)/g, function (_, i, r) {\n return i.toUpperCase() + (r != null ? r : \"\");\n }\n)\n</code></pre>\n\n<p>Seems to work...\nTested with the above, \"the quick-brown, fox? /jumps/ ^over^ the ¡lazy! dog...\" and \"C:/program files/some vendor/their 2nd application/a file1.txt\".</p>\n\n<p>If you want 2Nd instead of 2nd, you can change to <code>/([a-z])(\\w*)/g</code>.</p>\n\n<p>The first form can be simplified as:</p>\n\n<pre><code>function toTitleCase(toTransform) {\n return toTransform.replace(/\\b([a-z])/g, function (_, initial) {\n return initial.toUpperCase();\n });\n}\n</code></pre>\n"
},
{
"answer_id": 196991,
"author": "Greg Dean",
"author_id": 1200558,
"author_profile": "https://Stackoverflow.com/users/1200558",
"pm_score": 10,
"selected": false,
"text": "<p>Try this:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function toTitleCase(str) {\n return str.replace(\n /\\w\\S*/g,\n function(txt) {\n return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();\n }\n );\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><form>\n Input:\n <br /><textarea name=\"input\" onchange=\"form.output.value=toTitleCase(this.value)\" onkeyup=\"form.output.value=toTitleCase(this.value)\"></textarea>\n <br />Output:\n <br /><textarea name=\"output\" readonly onclick=\"select(this)\"></textarea>\n</form></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 2195924,
"author": "Lwangaman",
"author_id": 265725,
"author_profile": "https://Stackoverflow.com/users/265725",
"pm_score": 4,
"selected": false,
"text": "<p>I made this function which can handle last names (so it's not title case) such as \"McDonald\" or \"MacDonald\" or \"O'Toole\" or \"D'Orazio\". It doesn't however handle German or Dutch names with \"van\" or \"von\" which are often in lower-case... I believe \"de\" is often lower-case too such as \"Robert de Niro\". These would still have to be addressed.</p>\n\n<pre><code>function toProperCase(s)\n{\n return s.toLowerCase().replace( /\\b((m)(a?c))?(\\w)/g,\n function($1, $2, $3, $4, $5) { if($2){return $3.toUpperCase()+$4+$5.toUpperCase();} return $1.toUpperCase(); });\n}\n</code></pre>\n"
},
{
"answer_id": 3054478,
"author": "Talha Ashfaque",
"author_id": 362193,
"author_profile": "https://Stackoverflow.com/users/362193",
"pm_score": 8,
"selected": false,
"text": "<p>If a CSS solution meets your needs, you can apply the <a href=\"http://www.w3.org/TR/CSS2/text.html#caps-prop\" rel=\"noreferrer\">text-transform</a> CSS style to your controls:</p>\n<pre class=\"lang-css prettyprint-override\"><code>text-transform: capitalize;\n</code></pre>\n<p>Just be aware that this will transform:<br />\n<code>hello world</code> to <code>Hello World</code><br />\n<code>HELLO WORLD</code> to <code>HELLO WORLD</code> (no change)<br />\n<code>emily-jane o'brien</code> to <code>Emily-jane O'brien</code> (incorrect)<br />\n<code>Maria von Trapp</code> to <code>Maria Von Trapp</code> (incorrect)</p>\n"
},
{
"answer_id": 4171093,
"author": "fncomp",
"author_id": 455581,
"author_profile": "https://Stackoverflow.com/users/455581",
"pm_score": 4,
"selected": false,
"text": "<p>Just in case you are worried about those filler words, you can always just tell the function what not to capitalize.</p>\n\n<pre><code>/**\n * @param String str The text to be converted to titleCase.\n * @param Array glue the words to leave in lowercase. \n */\nvar titleCase = function(str, glue){\n glue = (glue) ? glue : ['of', 'for', 'and'];\n return str.replace(/(\\w)(\\w*)/g, function(_, i, r){\n var j = i.toUpperCase() + (r != null ? r : \"\");\n return (glue.indexOf(j.toLowerCase())<0)?j:j.toLowerCase();\n });\n};\n</code></pre>\n\n<p>Hope this helps you out.</p>\n\n<h3>edit</h3>\n\n<p>If you want to handle leading glue words, you can keep track of this w/ one more variable:</p>\n\n<pre><code>var titleCase = function(str, glue){\n glue = !!glue ? glue : ['of', 'for', 'and', 'a'];\n var first = true;\n return str.replace(/(\\w)(\\w*)/g, function(_, i, r) {\n var j = i.toUpperCase() + (r != null ? r : '').toLowerCase();\n var result = ((glue.indexOf(j.toLowerCase()) < 0) || first) ? j : j.toLowerCase();\n first = false;\n return result;\n });\n};\n</code></pre>\n"
},
{
"answer_id": 5574446,
"author": "Tuan",
"author_id": 360053,
"author_profile": "https://Stackoverflow.com/users/360053",
"pm_score": 8,
"selected": false,
"text": "<p>A slightly more elegant way, adapting Greg Dean's function:</p>\n\n<pre><code>String.prototype.toProperCase = function () {\n return this.replace(/\\w\\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});\n};\n</code></pre>\n\n<p>Call it like:</p>\n\n<pre><code>\"pascal\".toProperCase();\n</code></pre>\n"
},
{
"answer_id": 6475125,
"author": "Geoffrey Booth",
"author_id": 223225,
"author_profile": "https://Stackoverflow.com/users/223225",
"pm_score": 7,
"selected": false,
"text": "<p>Here’s my function that converts to title case but also preserves defined acronyms as uppercase and minor words as lowercase:</p>\n\n<pre><code>String.prototype.toTitleCase = function() {\n var i, j, str, lowers, uppers;\n str = this.replace(/([^\\W_]+[^\\s-]*) */g, function(txt) {\n return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();\n });\n\n // Certain minor words should be left lowercase unless \n // they are the first or last words in the string\n lowers = ['A', 'An', 'The', 'And', 'But', 'Or', 'For', 'Nor', 'As', 'At', \n 'By', 'For', 'From', 'In', 'Into', 'Near', 'Of', 'On', 'Onto', 'To', 'With'];\n for (i = 0, j = lowers.length; i < j; i++)\n str = str.replace(new RegExp('\\\\s' + lowers[i] + '\\\\s', 'g'), \n function(txt) {\n return txt.toLowerCase();\n });\n\n // Certain words such as initialisms or acronyms should be left uppercase\n uppers = ['Id', 'Tv'];\n for (i = 0, j = uppers.length; i < j; i++)\n str = str.replace(new RegExp('\\\\b' + uppers[i] + '\\\\b', 'g'), \n uppers[i].toUpperCase());\n\n return str;\n}\n</code></pre>\n\n<p>For example:</p>\n\n<pre><code>\"TO LOGIN TO THIS SITE and watch tv, please enter a valid id:\".toTitleCase();\n// Returns: \"To Login to This Site and Watch TV, Please Enter a Valid ID:\"\n</code></pre>\n"
},
{
"answer_id": 8564268,
"author": "Mike",
"author_id": 276939,
"author_profile": "https://Stackoverflow.com/users/276939",
"pm_score": 4,
"selected": false,
"text": "<p>Without using regex just for reference:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>String.prototype.toProperCase = function() {\r\n var words = this.split(' ');\r\n var results = [];\r\n for (var i = 0; i < words.length; i++) {\r\n var letter = words[i].charAt(0).toUpperCase();\r\n results.push(letter + words[i].slice(1));\r\n }\r\n return results.join(' ');\r\n};\r\n\r\nconsole.log(\r\n 'john smith'.toProperCase()\r\n)</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 10625035,
"author": "Maxi Baez",
"author_id": 1202001,
"author_profile": "https://Stackoverflow.com/users/1202001",
"pm_score": 3,
"selected": false,
"text": "<p>Try this</p>\n\n<pre><code>String.prototype.toProperCase = function(){\n return this.toLowerCase().replace(/(^[a-z]| [a-z]|-[a-z])/g, \n function($1){\n return $1.toUpperCase();\n }\n );\n};\n</code></pre>\n\n<p>Example</p>\n\n<pre><code>var str = 'john smith';\nstr.toProperCase();\n</code></pre>\n"
},
{
"answer_id": 12533554,
"author": "Billy Moon",
"author_id": 665261,
"author_profile": "https://Stackoverflow.com/users/665261",
"pm_score": 0,
"selected": false,
"text": "<p>As full featured as John Resig's solution, but as a one-liner: (based on <a href=\"https://github.com/gouch/to-title-case\" rel=\"nofollow\">this github project</a>)</p>\n\n<pre><code>function toTitleCase(e){var t=/^(a|an|and|as|at|but|by|en|for|if|in|of|on|or|the|to|vs?\\.?|via)$/i;return e.replace(/([^\\W_]+[^\\s-]*) */g,function(e,n,r,i){return r>0&&r+n.length!==i.length&&n.search(t)>-1&&i.charAt(r-2)!==\":\"&&i.charAt(r-1).search(/[^\\s-]/)<0?e.toLowerCase():n.substr(1).search(/[A-Z]|\\../)>-1?e:e.charAt(0).toUpperCase()+e.substr(1)})};\n\nconsole.log( toTitleCase( \"ignores mixed case words like iTunes, and allows AT&A and website.com/address etc...\" ) );\n</code></pre>\n"
},
{
"answer_id": 20763116,
"author": "simo",
"author_id": 1260020,
"author_profile": "https://Stackoverflow.com/users/1260020",
"pm_score": 5,
"selected": false,
"text": "<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var result =\r\n 'this is very interesting'.replace(/\\b[a-z]/g, (x) => x.toUpperCase())\r\n\r\nconsole.log(result) // This Is Very Interesting</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 22193094,
"author": "a8m",
"author_id": 2503796,
"author_profile": "https://Stackoverflow.com/users/2503796",
"pm_score": 7,
"selected": false,
"text": "<p>Here's my version, IMO it's easy to understand and elegant too.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const str = \"foo bar baz\";\nconst newStr = str.split(' ')\n .map(w => w[0].toUpperCase() + w.substring(1).toLowerCase())\n .join(' ');\nconsole.log(newStr);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 24784109,
"author": "lewax00",
"author_id": 864070,
"author_profile": "https://Stackoverflow.com/users/864070",
"pm_score": 3,
"selected": false,
"text": "<p>Most of these answers seem to ignore the possibility of using the word boundary metacharacter (\\b). A shorter version of Greg Dean's answer utilizing it:</p>\n\n<pre><code>function toTitleCase(str)\n{\n return str.replace(/\\b\\w/g, function (txt) { return txt.toUpperCase(); });\n}\n</code></pre>\n\n<p>Works for hyphenated names like Jim-Bob too.</p>\n"
},
{
"answer_id": 26128016,
"author": "Asereware",
"author_id": 1048751,
"author_profile": "https://Stackoverflow.com/users/1048751",
"pm_score": 2,
"selected": false,
"text": "<p>Taking the \"lewax00\" solution I created this simple solution that force to \"w\" starting with space or \"w\" that initiate de word, but is not able to remove the extra intermediate spaces.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>\"SOFÍA vergara\".toLowerCase().replace(/\\b(\\s\\w|^\\w)/g, function (txt) { return txt.toUpperCase(); });</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>The result is \"Sofía Vergara\".</p>\n"
},
{
"answer_id": 29760794,
"author": "Spencer Shattuck",
"author_id": 4806162,
"author_profile": "https://Stackoverflow.com/users/4806162",
"pm_score": 1,
"selected": false,
"text": "<p>It's not short but here is what I came up with on a recent assignment in school:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var myPoem = 'What is a jQuery but a misunderstood object?'\r\n//What is a jQuery but a misunderstood object? --> What Is A JQuery But A Misunderstood Object?\r\n\r\n //code here\r\nvar capitalize = function(str) {\r\n var strArr = str.split(' ');\r\n var newArr = [];\r\n for (var i = 0; i < strArr.length; i++) {\r\n newArr.push(strArr[i].charAt(0).toUpperCase() + strArr[i].slice(1))\r\n };\r\n return newArr.join(' ') \r\n}\r\n\r\nvar fixedPoem = capitalize(myPoem);\r\nalert(fixedPoem);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 30710880,
"author": "vijayscode",
"author_id": 4053617,
"author_profile": "https://Stackoverflow.com/users/4053617",
"pm_score": 0,
"selected": false,
"text": "<pre class=\"lang-js prettyprint-override\"><code>function toTitleCase(str) {\n var strnew = \"\";\n var i = 0;\n\n for (i = 0; i < str.length; i++) {\n if (i == 0) {\n strnew = strnew + str[i].toUpperCase();\n } else if (i != 0 && str[i - 1] == \" \") {\n strnew = strnew + str[i].toUpperCase();\n } else {\n strnew = strnew + str[i];\n }\n }\n\n alert(strnew);\n}\n\ntoTitleCase(\"hello world how are u\");\n</code></pre>\n"
},
{
"answer_id": 31278078,
"author": "aagamezl",
"author_id": 4246683,
"author_profile": "https://Stackoverflow.com/users/4246683",
"pm_score": 0,
"selected": false,
"text": "<p>This is one line solution, if you want convert every work in the string, Split the string by \" \", iterate over the parts and apply this solution to each part, add every converted part to a array and join it with \" \".</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var stringToConvert = 'john';\r\nstringToConvert = stringToConvert.charAt(0).toUpperCase() + Array.prototype.slice.call(stringToConvert, 1).join('');\r\nconsole.log(stringToConvert);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 31865052,
"author": "dipole_moment",
"author_id": 1869326,
"author_profile": "https://Stackoverflow.com/users/1869326",
"pm_score": 1,
"selected": false,
"text": "<p>Prototype solution of Greg Dean's solution:</p>\n\n<pre><code>String.prototype.capitalize = function() {\n return this.replace(/\\w\\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});\n}\n</code></pre>\n"
},
{
"answer_id": 32485600,
"author": "Rafael Sanches",
"author_id": 410293,
"author_profile": "https://Stackoverflow.com/users/410293",
"pm_score": 1,
"selected": false,
"text": "<p>Simpler more performant version, with simple caching. </p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code> var TITLE_CASE_LOWER_MAP = {\r\n 'a': 1, 'an': 1, 'and': 1, 'as': 1, 'at': 1, 'but': 1, 'by': 1, 'en':1, 'with': 1,\r\n 'for': 1, 'if': 1, 'in': 1, 'of': 1, 'on': 1, 'the': 1, 'to': 1, 'via': 1\r\n };\r\n\r\n // LEAK/CACHE TODO: evaluate using LRU.\r\n var TITLE_CASE_CACHE = new Object();\r\n\r\n toTitleCase: function (title) {\r\n if (!title) return null;\r\n\r\n var result = TITLE_CASE_CACHE[title];\r\n if (result) {\r\n return result;\r\n }\r\n\r\n result = \"\";\r\n var split = title.toLowerCase().split(\" \");\r\n for (var i=0; i < split.length; i++) {\r\n\r\n if (i > 0) {\r\n result += \" \";\r\n }\r\n\r\n var word = split[i];\r\n if (i == 0 || TITLE_CASE_LOWER_MAP[word] != 1) {\r\n word = word.substr(0,1).toUpperCase() + word.substr(1);\r\n }\r\n\r\n result += word;\r\n }\r\n\r\n TITLE_CASE_CACHE[title] = result;\r\n\r\n return result;\r\n },</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 33815550,
"author": "Jamesy Dimmick May",
"author_id": 2677107,
"author_profile": "https://Stackoverflow.com/users/2677107",
"pm_score": 2,
"selected": false,
"text": "<p>This is based on my solution for <a href=\"http://www.freecodecamp.com/challenges/bonfire-title-case-a-sentence\" rel=\"nofollow\">FreeCodeCamp's Bonfire \"Title Case\"</a>, which requires you to first convert the given string to all lower case and then convert every character proceeding a space to upper case.</p>\n\n<p>Without using regex:</p>\n\n<pre><code>function titleCase(str) {\n return str.toLowerCase().split(' ').map(function(val) { return val.replace(val[0], val[0].toUpperCase()); }).join(' ');\n}\n</code></pre>\n"
},
{
"answer_id": 34251961,
"author": "Pro N00P",
"author_id": 5674751,
"author_profile": "https://Stackoverflow.com/users/5674751",
"pm_score": 0,
"selected": false,
"text": "<pre><code>function titleCase(str) {\n str = str.toLowerCase();\n\n var strArray = str.split(\" \");\n\n\n for(var i = 0; i < strArray.length; i++){\n strArray[i] = strArray[i].charAt(0).toUpperCase() + strArray[i].substr(1);\n\n }\n\n var result = strArray.join(\" \");\n\n //Return the string\n return result;\n}\n</code></pre>\n"
},
{
"answer_id": 35236310,
"author": "zurfyx",
"author_id": 2013580,
"author_profile": "https://Stackoverflow.com/users/2013580",
"pm_score": 0,
"selected": false,
"text": "<pre><code>String.prototype.capitalize = function() {\n return this.toLowerCase().split(' ').map(capFirst).join(' ');\n function capFirst(str) {\n return str.length === 0 ? str : str[0].toUpperCase() + str.substr(1);\n }\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>\"hello world\".capitalize()\n</code></pre>\n"
},
{
"answer_id": 35681245,
"author": "immazharkhan",
"author_id": 4945514,
"author_profile": "https://Stackoverflow.com/users/4945514",
"pm_score": 4,
"selected": false,
"text": "<p>If regex used in the above solutions is getting you confused, try this code:</p>\n\n<pre><code>function titleCase(str) {\n return str.split(' ').map(function(val){ \n return val.charAt(0).toUpperCase() + val.substr(1).toLowerCase();\n }).join(' ');\n}\n</code></pre>\n"
},
{
"answer_id": 36991252,
"author": "Suryatapa",
"author_id": 4978139,
"author_profile": "https://Stackoverflow.com/users/4978139",
"pm_score": 1,
"selected": false,
"text": "<p>My simple and easy version to the problem:</p>\n\n<pre><code> function titlecase(str){\n var arr=[]; \n var str1=str.split(' ');\n for (var i = 0; i < str1.length; i++) {\n var upper= str1[i].charAt(0).toUpperCase()+ str1[i].substr(1);\n arr.push(upper);\n };\n return arr.join(' ');\n }\n titlecase('my name is suryatapa roy');\n</code></pre>\n"
},
{
"answer_id": 37931321,
"author": "le_m",
"author_id": 1647737,
"author_profile": "https://Stackoverflow.com/users/1647737",
"pm_score": 3,
"selected": false,
"text": "<p>Use <code>/\\S+/g</code> to support diacritics:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function toTitleCase(str) {\r\n return str.replace(/\\S+/g, str => str.charAt(0).toUpperCase() + str.substr(1).toLowerCase());\r\n}\r\n\r\nconsole.log(toTitleCase(\"a city named örebro\")); // A City Named Örebro</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>However: \"<strong>s</strong>unshine (<strong>y</strong>ellow)\" ⇒ \"<strong>S</strong>unshine (<strong>y</strong>ellow)\"</p>\n"
},
{
"answer_id": 38640255,
"author": "Scott",
"author_id": 1655035,
"author_profile": "https://Stackoverflow.com/users/1655035",
"pm_score": 0,
"selected": false,
"text": "<p>Just another version to add to the mix. This will also check if the string.length is 0:</p>\n\n<pre><code>String.prototype.toTitleCase = function() {\n var str = this;\n if(!str.length) {\n return \"\";\n }\n str = str.split(\" \");\n for(var i = 0; i < str.length; i++) {\n str[i] = str[i].charAt(0).toUpperCase() + (str[i].substr(1).length ? str[i].substr(1) : '');\n }\n return (str.length ? str.join(\" \") : str);\n};\n</code></pre>\n"
},
{
"answer_id": 40090269,
"author": "Wayne Chiu",
"author_id": 6778784,
"author_profile": "https://Stackoverflow.com/users/6778784",
"pm_score": 1,
"selected": false,
"text": "<p>Robust Functional programming way to do <code>Title Case Function</code></p>\n\n<p><strong>Exaplin Version</strong></p>\n\n<pre><code>function toTitleCase(input){\n let output = input\n .split(' ') // 'HOw aRe YOU' => ['HOw' 'aRe' 'YOU']\n .map((letter) => {\n let firstLetter = letter[0].toUpperCase() // H , a , Y => H , A , Y\n let restLetters = letter.substring(1).toLowerCase() // Ow, Re, OU => ow, re, ou\n return firstLetter + restLetters // conbine together\n })\n .join(' ') //['How' 'Are' 'You'] => 'How Are You'\n return output\n}\n</code></pre>\n\n<p><strong>Implementation version</strong></p>\n\n<pre><code>function toTitleCase(input){\n return input\n .split(' ')\n .map(i => i[0].toUpperCase() + i.substring(1).toLowerCase())\n .join(' ') \n}\n\ntoTitleCase('HoW ARe yoU') // reuturn 'How Are You'\n</code></pre>\n"
},
{
"answer_id": 40111894,
"author": "KevBot",
"author_id": 2056157,
"author_profile": "https://Stackoverflow.com/users/2056157",
"pm_score": 6,
"selected": false,
"text": "<p>You could immediately <code>toLowerCase</code> the string, and then just <code>toUpperCase</code> the first letter of each word. Becomes a very simple 1 liner:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"true\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function titleCase(str) {\n return str.toLowerCase().replace(/\\b\\w/g, s => s.toUpperCase());\n}\n\nconsole.log(titleCase('iron man'));\nconsole.log(titleCase('iNcrEdible hulK'));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 40287630,
"author": "hacklikecrack",
"author_id": 1181545,
"author_profile": "https://Stackoverflow.com/users/1181545",
"pm_score": -1,
"selected": false,
"text": "<p>ES6 one liner</p>\n\n<pre><code>const toTitleCase = string => string.split(' ').map((word) => [word[0].toUpperCase(), ...word.substr(1)].join('')).join(' ');\n</code></pre>\n"
},
{
"answer_id": 40289152,
"author": "jssridhar",
"author_id": 1024119,
"author_profile": "https://Stackoverflow.com/users/1024119",
"pm_score": 4,
"selected": false,
"text": "<p>ES 6</p>\n\n<pre><code>str.split(' ')\n .map(s => s.slice(0, 1).toUpperCase() + s.slice(1).toLowerCase())\n .join(' ')\n</code></pre>\n\n<p>else</p>\n\n<pre><code>str.split(' ').map(function (s) {\n return s.slice(0, 1).toUpperCase() + s.slice(1).toLowerCase();\n}).join(' ')\n</code></pre>\n"
},
{
"answer_id": 41088451,
"author": "Ouatataz",
"author_id": 6710722,
"author_profile": "https://Stackoverflow.com/users/6710722",
"pm_score": 3,
"selected": false,
"text": "<p>Here is my function that is taking care of accented characters (important for french !) and that can switch on/off the handling of lowers exceptions. Hope that helps.</p>\n\n<pre><code>String.prototype.titlecase = function(lang, withLowers = false) {\n var i, string, lowers, uppers;\n\n string = this.replace(/([^\\s:\\-'])([^\\s:\\-']*)/g, function(txt) {\n return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();\n }).replace(/Mc(.)/g, function(match, next) {\n return 'Mc' + next.toUpperCase();\n });\n\n if (withLowers) {\n if (lang == 'EN') {\n lowers = ['A', 'An', 'The', 'At', 'By', 'For', 'In', 'Of', 'On', 'To', 'Up', 'And', 'As', 'But', 'Or', 'Nor', 'Not'];\n }\n else {\n lowers = ['Un', 'Une', 'Le', 'La', 'Les', 'Du', 'De', 'Des', 'À', 'Au', 'Aux', 'Par', 'Pour', 'Dans', 'Sur', 'Et', 'Comme', 'Mais', 'Ou', 'Où', 'Ne', 'Ni', 'Pas'];\n }\n for (i = 0; i < lowers.length; i++) {\n string = string.replace(new RegExp('\\\\s' + lowers[i] + '\\\\s', 'g'), function(txt) {\n return txt.toLowerCase();\n });\n }\n }\n\n uppers = ['Id', 'R&d'];\n for (i = 0; i < uppers.length; i++) {\n string = string.replace(new RegExp('\\\\b' + uppers[i] + '\\\\b', 'g'), uppers[i].toUpperCase());\n }\n\n return string;\n}\n</code></pre>\n"
},
{
"answer_id": 41378781,
"author": "waqas",
"author_id": 649388,
"author_profile": "https://Stackoverflow.com/users/649388",
"pm_score": 4,
"selected": false,
"text": "<p>If you can use third party libraries in your code then lodash has a helper function for us.</p>\n\n<p><a href=\"https://lodash.com/docs/4.17.3#startCase\" rel=\"noreferrer\">https://lodash.com/docs/4.17.3#startCase</a></p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>_.startCase('foo bar');\r\n// => 'Foo Bar'\r\n\r\n_.startCase('--foo-bar--');\r\n// => 'Foo Bar'\r\n \r\n_.startCase('fooBar');\r\n// => 'Foo Bar'\r\n \r\n_.startCase('__FOO_BAR__');\r\n// => 'FOO BAR'</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 44386787,
"author": "Vikram",
"author_id": 2025736,
"author_profile": "https://Stackoverflow.com/users/2025736",
"pm_score": 3,
"selected": false,
"text": "<p>Try this, shortest way:</p>\n\n<pre><code>str.replace(/(^[a-z])|(\\s+[a-z])/g, txt => txt.toUpperCase());\n</code></pre>\n"
},
{
"answer_id": 44387386,
"author": "lashja",
"author_id": 6564610,
"author_profile": "https://Stackoverflow.com/users/6564610",
"pm_score": 2,
"selected": false,
"text": "<p>For those of us who are scared of regular expressions (lol):</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function titleCase(str)\r\n{\r\n var words = str.split(\" \");\r\n for ( var i = 0; i < words.length; i++ )\r\n {\r\n var j = words[i].charAt(0).toUpperCase();\r\n words[i] = j + words[i].substr(1);\r\n }\r\n return words.join(\" \");\r\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 44665163,
"author": "chasnz",
"author_id": 8191338,
"author_profile": "https://Stackoverflow.com/users/8191338",
"pm_score": 0,
"selected": false,
"text": "<p>This solution takes punctuation into account for new sentences, handles quotations, converts minor words to lowercase and ignores acronyms or all-caps words.</p>\n\n<pre><code>var stopWordsArray = new Array(\"a\", \"all\", \"am\", \"an\", \"and\", \"any\", \"are\", \"as\", \"at\", \"be\", \"but\", \"by\", \"can\", \"can't\", \"did\", \"didn't\", \"do\", \"does\", \"doesn't\", \"don't\", \"else\", \"for\", \"get\", \"gets\", \"go\", \"got\", \"had\", \"has\", \"he\", \"he's\", \"her\", \"here\", \"hers\", \"hi\", \"him\", \"his\", \"how\", \"i'd\", \"i'll\", \"i'm\", \"i've\", \"if\", \"in\", \"is\", \"isn't\", \"it\", \"it's\", \"its\", \"let\", \"let's\", \"may\", \"me\", \"my\", \"no\", \"of\", \"off\", \"on\", \"our\", \"ours\", \"she\", \"so\", \"than\", \"that\", \"that's\", \"thats\", \"the\", \"their\", \"theirs\", \"them\", \"then\", \"there\", \"there's\", \"these\", \"they\", \"they'd\", \"they'll\", \"they're\", \"they've\", \"this\", \"those\", \"to\", \"too\", \"try\", \"until\", \"us\", \"want\", \"wants\", \"was\", \"wasn't\", \"we\", \"we'd\", \"we'll\", \"we're\", \"we've\", \"well\", \"went\", \"were\", \"weren't\", \"what\", \"what's\", \"when\", \"where\", \"which\", \"who\", \"who's\", \"whose\", \"why\", \"will\", \"with\", \"won't\", \"would\", \"yes\", \"yet\", \"you\", \"you'd\", \"you'll\", \"you're\", \"you've\", \"your\");\n\n// Only significant words are transformed. Handles acronyms and punctuation\nString.prototype.toTitleCase = function() {\n var newSentence = true;\n return this.split(/\\s+/).map(function(word) {\n if (word == \"\") { return; }\n var canCapitalise = true;\n // Get the pos of the first alpha char (word might start with \" or ')\n var firstAlphaCharPos = word.search(/\\w/);\n // Check for uppercase char that is not the first char (might be acronym or all caps)\n if (word.search(/[A-Z]/) > 0) {\n canCapitalise = false;\n } else if (stopWordsArray.indexOf(word) != -1) {\n // Is a stop word and not a new sentence\n word.toLowerCase();\n if (!newSentence) {\n canCapitalise = false;\n }\n }\n // Is this the last word in a sentence?\n newSentence = (word.search(/[\\.!\\?:]['\"]?$/) > 0)? true : false;\n return (canCapitalise)? word.replace(word[firstAlphaCharPos], word[firstAlphaCharPos].toUpperCase()) : word;\n }).join(' ');\n}\n\n// Pass a string using dot notation:\nalert(\"A critical examination of Plato's view of the human nature\".toTitleCase());\nvar str = \"Ten years on: a study into the effectiveness of NCEA in New Zealand schools\";\nstr.toTitleCase());\nstr = \"\\\"Where to from here?\\\" the effectivness of eLearning in childhood education\";\nalert(str.toTitleCase());\n\n/* Result:\nA Critical Examination of Plato's View of the Human Nature.\nTen Years On: A Study Into the Effectiveness of NCEA in New Zealand Schools.\n\"Where to From Here?\" The Effectivness of eLearning in Childhood Education. */\n</code></pre>\n"
},
{
"answer_id": 44770157,
"author": "Covfefe",
"author_id": 8217903,
"author_profile": "https://Stackoverflow.com/users/8217903",
"pm_score": 1,
"selected": false,
"text": "<p>Here is a compact solution to the problem:</p>\n\n<pre><code>function Title_Case(phrase) \n{\n var revised = phrase.charAt(0).toUpperCase();\n\n for ( var i = 1; i < phrase.length; i++ ) {\n\n if (phrase.charAt(i - 1) == \" \") {\n revised += phrase.charAt(i).toUpperCase(); }\n else {\n revised += phrase.charAt(i).toLowerCase(); }\n\n }\n\nreturn revised;\n}\n</code></pre>\n"
},
{
"answer_id": 44962866,
"author": "wondim",
"author_id": 3674573,
"author_profile": "https://Stackoverflow.com/users/3674573",
"pm_score": 3,
"selected": false,
"text": "<p>I think the simplest is using css. </p>\n\n<pre><code>function format_str(str) {\n str = str.toLowerCase();\n return '<span style=\"text-transform: capitalize\">'+ str +'</span>';\n}\n</code></pre>\n"
},
{
"answer_id": 45167876,
"author": "jjr2000",
"author_id": 3412043,
"author_profile": "https://Stackoverflow.com/users/3412043",
"pm_score": 2,
"selected": false,
"text": "<p>We have been having a discussion back here at the office and we think that trying to automatically correct the way people input names in the current way you want it doing is fraught with possible issues.</p>\n\n<p>We have come up with several cases where different types of auto capitalization fall apart <strong>and these are just for English names alone, each language has its own complexities.</strong></p>\n\n<p><strong>Issues with capitalizing the first letter of each name:</strong></p>\n\n<p>• Acronyms such as IBM aren’t allowed to be inputted, would turn into Ibm.</p>\n\n<p>• The Name McDonald would turn into Mcdonald which is incorrect, the same thing is MacDonald too.</p>\n\n<p>• Double barrelled names such as Marie-Tonks would get turned into Marie-tonks.</p>\n\n<p>• Names like O’Connor would turn into O’connor.</p>\n\n<p><strong>For most of these you could write custom rules to deal with it, however, this still has issues with Acronyms as before and you get a new issue:</strong></p>\n\n<p>• Adding in a rule to fix names with Mac such as MacDonald, would the break names such as Macy turning it into MacY.</p>\n\n<p>The only solution we have come up with that is never incorrect is to capitalize every letter which is a brute force method that the DBS appear to also use.</p>\n\n<p>So if you want to automate the process it is as good as impossible to do without a dictionary of every single name and word and how it should be capitlized, <strong>If you don't have a rule that covers everything don't use it as it will just annoy your users and prompt people who want to enter their names correctly to go else where.</strong></p>\n"
},
{
"answer_id": 46501455,
"author": "xGeo",
"author_id": 7291240,
"author_profile": "https://Stackoverflow.com/users/7291240",
"pm_score": 4,
"selected": false,
"text": "<p>First, convert your <code>string</code> into array by <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split\" rel=\"noreferrer\">splitting</a> it by spaces:</p>\n<pre><code>var words = str.split(' ');\n</code></pre>\n<p>Then use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map\" rel=\"noreferrer\">array.map</a> to create a new array containing the capitalized words.</p>\n<pre><code>var capitalized = words.map(function(word) {\n return word.charAt(0).toUpperCase() + word.substring(1, word.length);\n});\n</code></pre>\n<p>Then <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join\" rel=\"noreferrer\">join</a> the new array with spaces:</p>\n<pre><code>capitalized.join(" ");\n</code></pre>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function titleCase(str) {\n str = str.toLowerCase(); //ensure the HeLlo will become Hello at the end\n var words = str.split(\" \");\n\n var capitalized = words.map(function(word) {\n return word.charAt(0).toUpperCase() + word.substring(1, word.length);\n });\n return capitalized.join(\" \");\n}\n\nconsole.log(titleCase(\"I'm a little tea pot\"));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p><strong>NOTE:</strong></p>\n<p>This of course has a drawback. This will only capitalize the first letter of every word. By word, this means that it treats every string separated by spaces as 1 word.</p>\n<p>Supposedly you have:</p>\n<p><code>str = "I'm a little/small tea pot";</code></p>\n<p>This will produce</p>\n<blockquote>\n<p>I'm A Little/<em>small</em> Tea Pot</p>\n</blockquote>\n<p>compared to the expected</p>\n<blockquote>\n<p>I'm A Little/Small Tea Pot</p>\n</blockquote>\n<p>In that case, using Regex and <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace\" rel=\"noreferrer\">.replace</a> will do the trick:</p>\n<p><strong>with ES6:</strong></p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const capitalize = str => str.length\n ? str[0].toUpperCase() +\n str.slice(1).toLowerCase()\n : '';\n\nconst escape = str => str.replace(/./g, c => `\\\\${c}`);\nconst titleCase = (sentence, seps = ' _-/') => {\n let wordPattern = new RegExp(`[^${escape(seps)}]+`, 'g');\n \n return sentence.replace(wordPattern, capitalize);\n};\nconsole.log( titleCase(\"I'm a little/small tea pot.\") );</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>or without <strong>ES6</strong>:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function capitalize(str) {\n return str.charAt(0).toUpperCase() + str.substring(1, str.length).toLowerCase();\n}\n\nfunction titleCase(str) {\n return str.replace(/[^\\ \\/\\-\\_]+/g, capitalize);\n}\n\nconsole.log(titleCase(\"I'm a little/small tea pot.\"));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 46774740,
"author": "dipole_moment",
"author_id": 1869326,
"author_profile": "https://Stackoverflow.com/users/1869326",
"pm_score": 4,
"selected": false,
"text": "<p><strong>If you need a grammatically correct answer:</strong></p>\n<p>This answer takes into account prepositions such as "of", "from", ..\nThe output will generate an editorial style title you would expect to see in a paper.</p>\n<p><strong>toTitleCase Function</strong></p>\n<p>The function that takes into account grammar rules <a href=\"http://www.superheronation.com/2011/08/16/words-that-should-not-be-capitalized-in-titles/\" rel=\"noreferrer\">listed here</a>.\nThe function also consolidates whitespace and removes special characters (modify regex for your needs)</p>\n<pre><code>const toTitleCase = (str) => {\n const articles = ['a', 'an', 'the'];\n const conjunctions = ['for', 'and', 'nor', 'but', 'or', 'yet', 'so'];\n const prepositions = [\n 'with', 'at', 'from', 'into','upon', 'of', 'to', 'in', 'for',\n 'on', 'by', 'like', 'over', 'plus', 'but', 'up', 'down', 'off', 'near'\n ];\n\n // The list of spacial characters can be tweaked here\n const replaceCharsWithSpace = (str) => str.replace(/[^0-9a-z&/\\\\]/gi, ' ').replace(/(\\s\\s+)/gi, ' ');\n const capitalizeFirstLetter = (str) => str.charAt(0).toUpperCase() + str.substr(1);\n const normalizeStr = (str) => str.toLowerCase().trim();\n const shouldCapitalize = (word, fullWordList, posWithinStr) => {\n if ((posWithinStr == 0) || (posWithinStr == fullWordList.length - 1)) {\n return true;\n }\n\n return !(articles.includes(word) || conjunctions.includes(word) || prepositions.includes(word));\n }\n\n str = replaceCharsWithSpace(str);\n str = normalizeStr(str);\n\n let words = str.split(' ');\n if (words.length <= 2) { // Strings less than 3 words long should always have first words capitalized\n words = words.map(w => capitalizeFirstLetter(w));\n }\n else {\n for (let i = 0; i < words.length; i++) {\n words[i] = (shouldCapitalize(words[i], words, i) ? capitalizeFirstLetter(words[i], words, i) : words[i]);\n }\n }\n\n return words.join(' ');\n}\n</code></pre>\n<p><strong>Unit Tests to Ensure Correctness</strong></p>\n<pre><code>import { expect } from 'chai';\nimport { toTitleCase } from '../../src/lib/stringHelper';\n\ndescribe('toTitleCase', () => {\n it('Capitalizes first letter of each word irrespective of articles, conjunctions or prepositions if string is no greater than two words long', function(){\n expect(toTitleCase('the dog')).to.equal('The Dog'); // Capitalize articles when only two words long\n expect(toTitleCase('for all')).to.equal('For All'); // Capitalize conjunctions when only two words long\n expect(toTitleCase('with cats')).to.equal('With Cats'); // Capitalize prepositions when only two words long\n });\n\n it('Always capitalize first and last words in a string irrespective of articles, conjunctions or prepositions', function(){\n expect(toTitleCase('the beautiful dog')).to.equal('The Beautiful Dog');\n expect(toTitleCase('for all the deadly ninjas, be it so')).to.equal('For All the Deadly Ninjas Be It So');\n expect(toTitleCase('with cats and dogs we are near')).to.equal('With Cats and Dogs We Are Near');\n });\n\n it('Replace special characters with space', function(){\n expect(toTitleCase('[wolves & lions]: be careful')).to.equal('Wolves & Lions Be Careful');\n expect(toTitleCase('wolves & lions, be careful')).to.equal('Wolves & Lions Be Careful');\n });\n\n it('Trim whitespace at beginning and end', function(){\n expect(toTitleCase(' mario & Luigi superstar saga ')).to.equal('Mario & Luigi Superstar Saga');\n });\n\n it('articles, conjunctions and prepositions should not be capitalized in strings of 3+ words', function(){\n expect(toTitleCase('The wolf and the lion: a tale of two like animals')).to.equal('The Wolf and the Lion a Tale of Two like Animals');\n expect(toTitleCase('the three Musketeers And plus ')).to.equal('The Three Musketeers and Plus');\n });\n});\n</code></pre>\n<p>Please note that I am removing quite a bit of special characters from the strings provided. You will need to tweak the regex to address the requirements of your project.</p>\n"
},
{
"answer_id": 46959528,
"author": "Tom Kay",
"author_id": 1073738,
"author_profile": "https://Stackoverflow.com/users/1073738",
"pm_score": 6,
"selected": false,
"text": "<p>I prefer the following over the other answers. It matches only the first letter of each word and capitalises it. Simpler code, easier to read and less bytes. It preserves existing capital letters to prevent distorting acronyms. However you can always call <code>toLowerCase()</code> on your string first.</p>\n\n<pre><code>function title(str) {\n return str.replace(/(^|\\s)\\S/g, function(t) { return t.toUpperCase() });\n}\n</code></pre>\n\n<p>You can add this to your string prototype which will allow you to <code>'my string'.toTitle()</code> as follows:</p>\n\n<pre><code>String.prototype.toTitle = function() {\n return this.replace(/(^|\\s)\\S/g, function(t) { return t.toUpperCase() });\n}\n</code></pre>\n\n<p><strong>Example:</strong>\n<div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>String.prototype.toTitle = function() {\r\n return this.replace(/(^|\\s)\\S/g, function(t) { return t.toUpperCase() });\r\n}\r\n\r\nconsole.log('all lower case ->','all lower case'.toTitle());\r\nconsole.log('ALL UPPER CASE ->','ALL UPPER CASE'.toTitle());\r\nconsole.log(\"I'm a little teapot ->\",\"I'm a little teapot\".toTitle());</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 49398245,
"author": "Stephen Quan",
"author_id": 881441,
"author_profile": "https://Stackoverflow.com/users/881441",
"pm_score": 1,
"selected": false,
"text": "<p>There's been some great answers, but, with many people using regex to find the word, but, for some reason, nobody else uses regex to replace the first character. For explanation, I'll provide a long solution and a shorter one.</p>\n\n<p>The long solution (more explanatory). By using regular expression <code>[^\\s_\\-/]*</code> we can find every word in the sentence. Subsequently, we can use the regular expression <code>.</code> to match to the first character in a word. Using the regular expression version of replace for both of these, we can change the solution like this:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function toUpperCase(str) { return str.toUpperCase(); }\r\nfunction capitalizeWord(word) { return word.replace(/./, toUpperCase); }\r\nfunction capitalize(sentence) { return sentence.toLowerCase().replace(/[^\\s_\\-/]*/g, capitalizeWord); }\r\n\r\nconsole.log(capitalize(\"hello world\")); // Outputs: Hello World</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>For a single function that does the same thing, we nest the <code>replace</code> calls as follows:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function capitalize(sentence) {\r\n return sentence.toLowerCase().replace(/[^\\s_\\-/]*/g, function (word) {\r\n return word.replace(/./, function (ch) { return ch.toUpperCase(); } );\r\n } );\r\n}\r\n\r\nconsole.log(capitalize(\"hello world\")); // Outputs: Hello World</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 51346019,
"author": "bajran",
"author_id": 7763149,
"author_profile": "https://Stackoverflow.com/users/7763149",
"pm_score": 1,
"selected": false,
"text": "<p><code>this is a test</code> ---> <code>This Is A Test</code></p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function capitalize(str) {\r\n\r\n const word = [];\r\n\r\n for (let char of str.split(' ')) {\r\n word.push(char[0].toUpperCase() + char.slice(1))\r\n }\r\n\r\n return word.join(' ');\r\n\r\n}\r\n\r\nconsole.log(capitalize(\"this is a test\"));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 52175696,
"author": "Wayne Li",
"author_id": 5894959,
"author_profile": "https://Stackoverflow.com/users/5894959",
"pm_score": 0,
"selected": false,
"text": "<p>A method use reduce</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function titleCase(str) {\r\n const arr = str.split(\" \");\r\n const result = arr.reduce((acc, cur) => {\r\n const newStr = cur[0].toUpperCase() + cur.slice(1).toLowerCase();\r\n return acc += `${newStr} `\r\n },\"\")\r\n return result.slice(0, result.length-1);\r\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 52344286,
"author": "Muhammad Usman",
"author_id": 6298042,
"author_profile": "https://Stackoverflow.com/users/6298042",
"pm_score": 0,
"selected": false,
"text": "<p>Another approach to achieve something similar can be as follows.</p>\n\n<pre><code>formatName(name) {\n let nam = '';\n name.split(' ').map((word, index) => {\n if (index === 0) {\n nam += word.split('').map((l, i) => i === 0 ? l.toUpperCase() : l.toLowerCase()).join('');\n } else {\n nam += ' ' + word.split('').map(l => l.toLowerCase()).join('');\n }\n });\n return nam;\n}\n</code></pre>\n"
},
{
"answer_id": 52952471,
"author": "Mayur Nandane",
"author_id": 5314943,
"author_profile": "https://Stackoverflow.com/users/5314943",
"pm_score": 0,
"selected": false,
"text": "<pre><code>ES-6 way to get title case of a word or entire line.\nex. input = 'hEllo' --> result = 'Hello'\nex. input = 'heLLo woRLd' --> result = 'Hello World'\n\nconst getTitleCase = (str) => {\n if(str.toLowerCase().indexOf(' ') > 0) {\n return str.toLowerCase().split(' ').map((word) => {\n return word.replace(word[0], word[0].toUpperCase());\n }).join(' ');\n }\n else {\n return str.slice(0, 1).toUpperCase() + str.slice(1).toLowerCase();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 52988991,
"author": "henrie",
"author_id": 9602904,
"author_profile": "https://Stackoverflow.com/users/9602904",
"pm_score": 3,
"selected": false,
"text": "<p>here's another solution using css (and javascript, if the text you want to transform is in uppercase):</p>\n\n<p><strong>html</strong></p>\n\n<pre><code><span id='text'>JOHN SMITH</span>\n</code></pre>\n\n<p><strong>js</strong></p>\n\n<pre><code>var str = document.getElementById('text').innerHtml;\nvar return_text = str.toLowerCase();\n</code></pre>\n\n<p><strong>css</strong></p>\n\n<pre><code>#text{text-transform:capitalize;}\n</code></pre>\n"
},
{
"answer_id": 54104929,
"author": "Siddharth Joshi",
"author_id": 3401966,
"author_profile": "https://Stackoverflow.com/users/3401966",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"https://lodash.com/docs/4.17.11#capitalize\" rel=\"nofollow noreferrer\">https://lodash.com/docs/4.17.11#capitalize</a></p>\n\n<p>Use Lodash Library..!! More Reliable</p>\n\n<pre><code>_.capitalize('FRED'); => 'Fred'\n</code></pre>\n"
},
{
"answer_id": 54527288,
"author": "iMartin",
"author_id": 1877349,
"author_profile": "https://Stackoverflow.com/users/1877349",
"pm_score": 1,
"selected": false,
"text": "<p>john smith -> John Smith</p>\n\n<pre><code>'john smith'.replace(/(^\\w|\\s+\\w){1}/g, function(str){ return str.toUpperCase() } );\n</code></pre>\n"
},
{
"answer_id": 56699654,
"author": "Proximo",
"author_id": 111624,
"author_profile": "https://Stackoverflow.com/users/111624",
"pm_score": 3,
"selected": false,
"text": "<pre><code>\"john f. kennedy\".replace(/\\b\\S/g, t => t.toUpperCase())\n</code></pre>\n"
},
{
"answer_id": 57486489,
"author": "Fouad Boukredine",
"author_id": 7594095,
"author_profile": "https://Stackoverflow.com/users/7594095",
"pm_score": 2,
"selected": false,
"text": "<p>My one line solution:</p>\n\n<pre><code>String.prototype.capitalizeWords = function() {\n return this.split(\" \").map(function(ele){ return ele[0].toUpperCase() + ele.slice(1).toLowerCase();}).join(\" \");\n};\n</code></pre>\n\n<p>Then, you can call the method <code>capitalizeWords()</code> on any string. For example:</p>\n\n<pre><code>var myS = \"this actually works!\";\nmyS.capitalizeWords();\n\n>>> This Actually Works\n</code></pre>\n\n<p>My other solution:</p>\n\n<pre><code>function capitalizeFirstLetter(word) {\n return word[0].toUpperCase() + word.slice(1).toLowerCase();\n}\nString.prototype.capitalizeAllWords = function() {\n var arr = this.split(\" \");\n for(var i = 0; i < arr.length; i++) {\n arr[i] = capitalizeFirstLetter(arr[i]);\n }\n return arr.join(\" \");\n};\n</code></pre>\n\n<p>Then, you can call the method <code>capitalizeWords()</code> on any string. For example:</p>\n\n<pre><code>var myStr = \"this one works too!\";\nmyStr.capitalizeWords();\n\n>>> This One Works Too\n</code></pre>\n\n<p><em>Alternative solution based on Greg Dean answer:</em></p>\n\n<pre><code>function capitalizeFirstLetter(word) {\n return word[0].toUpperCase() + word.slice(1).toLowerCase();\n}\nString.prototype.capitalizeWords = function() {\n return this.replace(/\\w\\S*/g, capitalizeFirstLetter);\n};\n</code></pre>\n\n<p>Then, you can call the method <code>capitalizeWords()</code> on any string. For example:</p>\n\n<pre><code>var myString = \"yes and no\";\nmyString.capitalizeWords()\n\n>>> Yes And No\n</code></pre>\n"
},
{
"answer_id": 58451659,
"author": "Avinash",
"author_id": 2753071,
"author_profile": "https://Stackoverflow.com/users/2753071",
"pm_score": 1,
"selected": false,
"text": "<p>A solution using lodash - </p>\n\n<pre><code>import { words, lowerCase, capitalize, endsWith, padEnd } from 'lodash';\nconst titleCase = string =>\n padEnd(\n words(string, /[^ ]+/g)\n .map(lowerCase)\n .map(capitalize)\n .join(' '),\n string.length,\n );\n</code></pre>\n"
},
{
"answer_id": 59478805,
"author": "Neeraj Kumar",
"author_id": 1555696,
"author_profile": "https://Stackoverflow.com/users/1555696",
"pm_score": 0,
"selected": false,
"text": "<p>I think you should try with this function.</p>\n\n<pre><code>var toTitleCase = function (str) {\n str = str.toLowerCase().split(' ');\n for (var i = 0; i < str.length; i++) {\n str[i] = str[i].charAt(0).toUpperCase() + str[i].slice(1);\n }\n return str.join(' ');\n};\n</code></pre>\n"
},
{
"answer_id": 61123252,
"author": "Regular Jo",
"author_id": 3917091,
"author_profile": "https://Stackoverflow.com/users/3917091",
"pm_score": 2,
"selected": false,
"text": "<p>My list is based on three quick searches. One for a list of words not to be capitalized, and one for a full list of prepositions.</p>\n\n<p>One final search made the <em>suggestion</em> that prepositions 5 letters or longer should be capitalized, which is something I liked. My purpose is for informal use. I left 'without' in their, because it's the obvious counterpart to with.</p>\n\n<p>So it capitalizes acronyms, the first letter of the title, and the first letter of most words.</p>\n\n<p>It is not intended to handle words in caps-lock. I wanted to leave those alone.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function camelCase(str) {\r\n return str.replace(/((?:^|\\.)\\w|\\b(?!(?:a|amid|an|and|anti|as|at|but|but|by|by|down|for|for|for|from|from|in|into|like|near|nor|of|of|off|on|on|onto|or|over|past|per|plus|save|so|than|the|to|to|up|upon|via|with|without|yet)\\b)\\w)/g, function(character) {\r\n return character.toUpperCase();\r\n})}\r\n \r\nconsole.log(camelCase('The quick brown fox jumped over the lazy dog, named butter, who was taking a nap outside the u.s. Post Office. The fox jumped so high that NASA saw him on their radar.'));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 61843287,
"author": "mschwartz",
"author_id": 11194082,
"author_profile": "https://Stackoverflow.com/users/11194082",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Simple way to convert an individual word to title case</strong></p>\n\n<p><em>Using the \"Slice\" method and String concatenation</em></p>\n\n<pre><code>str.slice(0, 1).toUpperCase() + str.slice(1, str.length)\n</code></pre>\n\n<p>*Add .toLowerCase() to the end if you want to lowercase the rest of the word</p>\n\n<p><em>Using ES6 Spread Operator, Map, and Join</em></p>\n\n<pre><code>[...str].map((w, i) => i === 0 ? w[0].toUpperCase() : w).join('')\n</code></pre>\n"
},
{
"answer_id": 61874826,
"author": "kapil pandey",
"author_id": 11693215,
"author_profile": "https://Stackoverflow.com/users/11693215",
"pm_score": 5,
"selected": false,
"text": "<p>Surprised to see no one mentioned the use of rest parameter. Here is a simple one liner that uses ES6 Rest parameters.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>let str=\"john smith\"\r\nstr=str.split(\" \").map(([firstChar,...rest])=>firstChar.toUpperCase()+rest.join(\"\").toLowerCase()).join(\" \")\r\nconsole.log(str)</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 64892968,
"author": "its4zahoor",
"author_id": 2013403,
"author_profile": "https://Stackoverflow.com/users/2013403",
"pm_score": 2,
"selected": false,
"text": "<p>A one-liner using regex, get all <code>\\g</code> starting characters of words <code>\\b[a-zA-Z]</code> , and apply <code>.toUpperCase()</code></p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const textString = \"Convert string to title case with Javascript.\";\nconst converted = textString.replace(/\\b[a-zA-Z]/g, (match) => match.toUpperCase());\nconsole.log(converted)</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 64909945,
"author": "Hedley Smith",
"author_id": 3320740,
"author_profile": "https://Stackoverflow.com/users/3320740",
"pm_score": 3,
"selected": false,
"text": "<p>Here's a really simple & concise ES6 function to do this:</p>\n<pre><code>const titleCase = (str) => {\n return str.replace(/\\w\\S*/g, (t) => { return t.charAt(0).toUpperCase() + t.substr(1).toLowerCase() });\n}\n\nexport default titleCase;\n</code></pre>\n<p>Works well included in a <code>utilities</code> folder and used as follows:</p>\n<pre><code>import titleCase from './utilities/titleCase.js';\n\nconst string = 'my title & string';\n\nconsole.log(titleCase(string)); //-> 'My Title & String'\n</code></pre>\n"
},
{
"answer_id": 64910248,
"author": "Ulysse BN",
"author_id": 6320039,
"author_profile": "https://Stackoverflow.com/users/6320039",
"pm_score": 5,
"selected": false,
"text": "<h1>Benchmark</h1>\n<h2>TL;DR</h2>\n<p>The winner of this benchmark is the plain old for loop:</p>\n<pre class=\"lang-js prettyprint-override\"><code>function titleize(str) {\n let upper = true\n let newStr = ""\n for (let i = 0, l = str.length; i < l; i++) {\n // Note that you can also check for all kinds of spaces with\n // str[i].match(/\\s/)\n if (str[i] == " ") {\n upper = true\n newStr += str[i]\n continue\n }\n newStr += upper ? str[i].toUpperCase() : str[i].toLowerCase()\n upper = false\n }\n return newStr\n}\n// NOTE: you could beat that using charcode and string builder I guess.\n</code></pre>\n<h2>Details</h2>\n<p>I've taken the most popular and distinct answers and made <a href=\"https://jsben.ch/bDBKL\" rel=\"noreferrer\">a benchmark</a> with those.</p>\n<p>Here's the result on my MacBook pro:</p>\n<p><a href=\"https://i.stack.imgur.com/Dc4ZU.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/Dc4ZU.png\" alt=\"enter image description here\" /></a></p>\n<p>And for completeness, here are the functions used:</p>\n<pre class=\"lang-js prettyprint-override\"><code>str = "the QUICK BrOWn Fox jUMPS oVeR the LAzy doG";\nfunction regex(str) {\n return str.replace(\n /\\w\\S*/g,\n function(txt) {\n return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();\n }\n );\n}\n\nfunction split(str) {\n return str.\n split(' ').\n map(w => w[0].toUpperCase() + w.substr(1).toLowerCase()).\n join(' ');\n}\n\nfunction complete(str) {\n var i, j, str, lowers, uppers;\n str = str.replace(/([^\\W_]+[^\\s-]*) */g, function(txt) {\n return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();\n });\n\n // Certain minor words should be left lowercase unless \n // they are the first or last words in the string\n lowers = ['A', 'An', 'The', 'And', 'But', 'Or', 'For', 'Nor', 'As', 'At', \n 'By', 'For', 'From', 'In', 'Into', 'Near', 'Of', 'On', 'Onto', 'To', 'With'];\n for (i = 0, j = lowers.length; i < j; i++)\n str = str.replace(new RegExp('\\\\s' + lowers[i] + '\\\\s', 'g'), \n function(txt) {\n return txt.toLowerCase();\n });\n\n // Certain words such as initialisms or acronyms should be left uppercase\n uppers = ['Id', 'Tv'];\n for (i = 0, j = uppers.length; i < j; i++)\n str = str.replace(new RegExp('\\\\b' + uppers[i] + '\\\\b', 'g'), \n uppers[i].toUpperCase());\n\n return str;\n}\n\nfunction firstLetterOnly(str) {\n return str.replace(/\\b(\\S)/g, function(t) { return t.toUpperCase(); });\n}\n\nfunction forLoop(str) {\n let upper = true;\n let newStr = "";\n for (let i = 0, l = str.length; i < l; i++) {\n if (str[i] == " ") {\n upper = true;\n newStr += " ";\n continue;\n }\n newStr += upper ? str[i].toUpperCase() : str[i].toLowerCase();\n upper = false;\n }\n return newStr;\n}\n</code></pre>\n<p>Note that i deliberately did not change the prototype since I consider it a really bad practice and I don't think we should promote such practice in our answers. This is only ok for small codebases when you're the only one working on it.</p>\n<p>If you want to add any other way to do it to this benchmark, please comment a link to the answer !</p>\n<hr />\n<p><strong>EDIT 2022 Mac M1:</strong> On my new computer, with more recent chrome, split wins. If you really care about performance on a specific machine you should run the benchmark yourself</p>\n"
},
{
"answer_id": 65167625,
"author": "Soham Patel",
"author_id": 7370437,
"author_profile": "https://Stackoverflow.com/users/7370437",
"pm_score": 2,
"selected": false,
"text": "<p>Here is my answer Guys Please comment and like if your problem solved.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function toTitleCase(str) {\n return str.replace(\n /(\\w*\\W*|\\w*)\\s*/g,\n function(txt) {\n return(txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase())\n }\n ); \n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><form>\n Input:\n <br /><textarea name=\"input\" onchange=\"form.output.value=toTitleCase(this.value)\" onkeyup=\"form.output.value=toTitleCase(this.value)\"></textarea>\n <br />Output:\n <br /><textarea name=\"output\" readonly onclick=\"select(this)\"></textarea>\n</form></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 67641990,
"author": "PaperinFlames",
"author_id": 13929460,
"author_profile": "https://Stackoverflow.com/users/13929460",
"pm_score": 2,
"selected": false,
"text": "<p>You can capitalize 1st char and join with the remaining string.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>let str = 'john smith';\nlet res = str.split(\" \");\nres.forEach((w, index) => {\n res[index] = w.charAt(0).toUpperCase().concat(w.slice(1, w.length))\n});\nres = res.join(\" \");\nconsole.log(res);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 68236885,
"author": "Max",
"author_id": 14647822,
"author_profile": "https://Stackoverflow.com/users/14647822",
"pm_score": -1,
"selected": false,
"text": "<p>My answer using regex.</p>\n<p>for more details regex: <a href=\"https://regex101.com/r/AgRM3p/1\" rel=\"nofollow noreferrer\">https://regex101.com/r/AgRM3p/1</a></p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function toTitleCase(string = '') {\n const regex = /^[a-z]{0,1}|\\s\\w/gi;\n\n string = string.toLowerCase();\n\n string.match(regex).forEach((char) => {\n string = string.replace(char, char.toUpperCase());\n });\n\n return string;\n}\n\nconst input = document.getElementById('fullname');\nconst button = document.getElementById('button');\nconst result = document.getElementById('result');\n\nbutton.addEventListener('click', () => {\n result.innerText = toTitleCase(input.value);\n});</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Test</title>\n</head>\n<body>\n <input type=\"text\" id=\"fullname\">\n <button id=\"button\">click me</button>\n <p id=\"result\">Result here</p>\n <script src=\"./index.js\"></script>\n</body>\n</html></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 68635466,
"author": "Anshul",
"author_id": 8671374,
"author_profile": "https://Stackoverflow.com/users/8671374",
"pm_score": -1,
"selected": false,
"text": "<p>No regex, no loop, no split, no substring:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>String.prototype.toTitleCase = function () { return this.valueOf().toLowerCase().replace(this.valueOf()[0], this.valueOf()[0].toUpperCase()); }\n\nconsole.log('laiLA'.toTitleCase());</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 70546786,
"author": "o17t H1H' S'k",
"author_id": 664456,
"author_profile": "https://Stackoverflow.com/users/664456",
"pm_score": 2,
"selected": false,
"text": "<p>jim-bob -> Jim-Bob</p>\n<p>jim/bob -> Jim/Bob</p>\n<p>jim_bob -> Jim_Bob</p>\n<p>isn't -> Isn't</p>\n<p>école -> École</p>\n<p>McDonalds -> McDonalds</p>\n<pre><code>function toTitleCase(str) {\n return str.replace(/\\p{L}+('\\p{L}+)?/gu, function(txt) {\n return txt.charAt(0).toUpperCase() + txt.slice(1)\n })\n}\n</code></pre>\n"
},
{
"answer_id": 70682133,
"author": "Kerem",
"author_id": 1421528,
"author_profile": "https://Stackoverflow.com/users/1421528",
"pm_score": 3,
"selected": false,
"text": "<p>I've tested this solution for Turkish and it works with special characters too.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function toTitleCase(str) {\n return str.toLocaleLowerCase().replace(\n /(^|Ü|ü|Ş|ş|Ç|ç|İ|ı|Ö|ö|\\w)\\S*/g,\n (txt) => txt.charAt(0).toLocaleUpperCase() + txt.substring(1),\n )\n}\n\nconsole.log(toTitleCase('İSMAİL HAKKI'))\nconsole.log(toTitleCase('ŞAHMARAN BİNBİR GECE MASALLARI'))\nconsole.log(toTitleCase('TEKNOLOJİ ÜRÜNÜ'))</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>I've added "toLocaleLowerCase" at the begining since I've all caps data. You can discard it if you don't need it.</p>\n<p>Using locale operations is important for non-english languages.</p>\n"
},
{
"answer_id": 70959264,
"author": "rinogo",
"author_id": 114558,
"author_profile": "https://Stackoverflow.com/users/114558",
"pm_score": 0,
"selected": false,
"text": "<p>If you'd like to use an NPM library, check out <a href=\"https://www.npmjs.com/package/title-case\" rel=\"nofollow noreferrer\"><code>title-case</code></a>:</p>\n<p>Installation:</p>\n<pre><code>npm install title-case --save\n</code></pre>\n<p>Usage:</p>\n<pre class=\"lang-js prettyprint-override\"><code>import { titleCase } from "title-case";\n\ntitleCase("string"); //=> "String"\ntitleCase("follow step-by-step instructions"); //=> "Follow Step-by-Step Instructions"\n</code></pre>\n"
},
{
"answer_id": 72497564,
"author": "Brendan Sluke",
"author_id": 7660196,
"author_profile": "https://Stackoverflow.com/users/7660196",
"pm_score": 0,
"selected": false,
"text": "<p>I highly recommend just using an open source NPM package if you can, this package works great in typescript:</p>\n<p>NPM: <a href=\"https://www.npmjs.com/package/title-case\" rel=\"nofollow noreferrer\">https://www.npmjs.com/package/title-case</a></p>\n<p>Github: <a href=\"https://github.com/blakeembrey/change-case/tree/master/packages/title-case#readme\" rel=\"nofollow noreferrer\">https://github.com/blakeembrey/change-case/tree/master/packages/title-case#readme</a></p>\n<p>Run <code>npm install title-case</code> to add the package to your project.</p>\n<p>Example Code using the <code>title-case</code> npm package:</p>\n<pre class=\"lang-js prettyprint-override\"><code>import { titleCase } from "title-case";\n\ntitleCase("string"); //=> "String"\ntitleCase("follow step-by-step instructions"); //=> "Follow Step-by-Step Instructions"\n</code></pre>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/196972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1896/"
] |
Is there a simple way to convert a string to Title Case? E.g. `john smith` becomes `John Smith`. I'm not looking for something complicated like [John Resig's solution](http://ejohn.org/blog/title-capitalization-in-javascript/), just (hopefully) some kind of one- or two-liner.
|
Try this:
```js
function toTitleCase(str) {
return str.replace(
/\w\S*/g,
function(txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
}
);
}
```
```html
<form>
Input:
<br /><textarea name="input" onchange="form.output.value=toTitleCase(this.value)" onkeyup="form.output.value=toTitleCase(this.value)"></textarea>
<br />Output:
<br /><textarea name="output" readonly onclick="select(this)"></textarea>
</form>
```
|
196,976 |
<p>I have an old project that was built using visual studio 2003 and I recompiled it with vs2005 recently. However, during runtime, I get the following error:</p>
<p>list iterator not incrementable</p>
<p>I traced the program to this function:</p>
<pre><code>void InputQueue::update()
{
list<PCB>::iterator iter;
list<PCB>::iterator iterTemp;
for(iter = begin(); iter != end(); iter++)
{
if(iter->arrivalTime == 0)
{
ReadyQueue::getInstance()->add(*iter);
iterTemp = iter;
iter++;
erase(iterTemp);
}
}
}
</code></pre>
<p>I'm not a C++ expert and this is as far as the VS debugger got me. Could somebody explain to me what the problem is?</p>
<p>Thanks</p>
|
[
{
"answer_id": 196988,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 3,
"selected": false,
"text": "<p>Notice that if <code>iter->arrivalTime == 0</code>, then the list iterator gets incremented twice: once before element removal, and once again at the end of the loop.</p>\n\n<p>If the item to be removed is the last item in the list, this will obviously not work correctly. I dare say that it never did work correctly even in VS2003, but VS2005 alerts you about it better. :-)</p>\n\n<p>Remember, it's undefined behaviour to iterate past <code>end()</code>. Absolutely anything can happen, such as program crash, or (in this case) an error message.</p>\n"
},
{
"answer_id": 196994,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 1,
"selected": false,
"text": "<p>I'm just going to elide a few lines of your code to show where the problem lies:</p>\n\n<pre><code> for(iter = begin(); iter != end(); iter++) // ***\n {\n if(iter->arrivalTime == 0)\n { \n\n iter++; // ***\n\n }\n }\n</code></pre>\n\n<p>On the two lines marked ***, you are incrementing the iterator. The problem is that on the second of the two lines, you aren't checking to see that you haven't gone to the end of the container. Effectively, if you get into the inner loop, you are incrementing twice, but only checking if you are able to increment once.</p>\n\n<p>One solution is to check whether you are at <code>end()</code> before doing the second increment, but it looks to me like you are trying to preform the same operation as I was in <a href=\"https://stackoverflow.com/questions/180516/how-to-filter-items-from-a-stdmap#180616\">my question a while ago</a> to do with filtering items from a container (a map in that case, but the same applies for most STL containers).</p>\n"
},
{
"answer_id": 196995,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 0,
"selected": false,
"text": "<p>I beliebe Chris is right. However, another problem might stem from the fact that you assign to the iterator. – Are list iterators guaranteed to be assignable? Without looking at the standard, I don't think so because assignability is nowhere mentioned in the SGI documentation of iterators.</p>\n"
},
{
"answer_id": 196996,
"author": "Mark Ingram",
"author_id": 986,
"author_profile": "https://Stackoverflow.com/users/986",
"pm_score": 4,
"selected": false,
"text": "<p>I would re-write your loop to be like the following:</p>\n\n<pre><code>while (iter != end())\n{\n if (iter->arrivalTime == 0)\n {\n ReadyQueue::getInstance()->add(*iter);\n iter = erase(iter);\n }\n else\n {\n ++iter;\n }\n}\n</code></pre>\n\n<p>Now you are correctly looping through the list checking every index.</p>\n"
},
{
"answer_id": 197007,
"author": "xtofl",
"author_id": 6610,
"author_profile": "https://Stackoverflow.com/users/6610",
"pm_score": 0,
"selected": false,
"text": "<p>This is but a sidenote, but an important one.</p>\n\n<p>I guess you inherit from a <code>std::ist<PCB></code>. I must say: inheriting to reuse functionality hasn't often turned out well for me. But since you're also 'inheriting' the project, there's nothing much to do about it...</p>\n"
},
{
"answer_id": 197098,
"author": "João Augusto",
"author_id": 6909,
"author_profile": "https://Stackoverflow.com/users/6909",
"pm_score": 0,
"selected": false,
"text": "<p>If you getting \"list iterator incompatible\" it's probably because inside your \"ReadyQueue::getInstance()->add(*iter);\" you are changing something in *iter that is making the hash algorithm returns a different value for erase than it did during the insert.</p>\n"
},
{
"answer_id": 197153,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 0,
"selected": false,
"text": "<p>May I suggest a simpler algorithm?</p>\n\n<p>The free function <code>std::remove_if</code> can be used to partition your list in 2, elements that match or don't match the predicate (i.e. arrivalTime==0). It returns the iterator seperating the ranges. You can then call <code>ReadyQueue::getInstance()->add(subrange_begin, subrange_end)</code> <em>(you do have that overload, right?)</em> and erase the subrange afterwards.</p>\n\n<p>Just a case where you can use STL algorithms instead of writing your own loops.</p>\n"
},
{
"answer_id": 19817468,
"author": "suc",
"author_id": 2730054,
"author_profile": "https://Stackoverflow.com/users/2730054",
"pm_score": 1,
"selected": false,
"text": "<p>The root cause is \"list.erase()\" will change the iterator. The correct write for \"for\" loop:</p>\n\n<pre><code> for (list<CMessage*>::iterator it=que.begin(); it!=que.end(); ++it)\n {\n if(m_type == (*it)->m_type)\n {\n delete *it;\n it=que.erase(it); //\"list.erase()\" will change the iterator!!!\n if(it==que.end()) break; //Check again!!!\n //still has side effect here. --it?\n }\n }\n</code></pre>\n\n<p>But it still has side effect, so Mark's while solution will be the best.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/196976",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I have an old project that was built using visual studio 2003 and I recompiled it with vs2005 recently. However, during runtime, I get the following error:
list iterator not incrementable
I traced the program to this function:
```
void InputQueue::update()
{
list<PCB>::iterator iter;
list<PCB>::iterator iterTemp;
for(iter = begin(); iter != end(); iter++)
{
if(iter->arrivalTime == 0)
{
ReadyQueue::getInstance()->add(*iter);
iterTemp = iter;
iter++;
erase(iterTemp);
}
}
}
```
I'm not a C++ expert and this is as far as the VS debugger got me. Could somebody explain to me what the problem is?
Thanks
|
I would re-write your loop to be like the following:
```
while (iter != end())
{
if (iter->arrivalTime == 0)
{
ReadyQueue::getInstance()->add(*iter);
iter = erase(iter);
}
else
{
++iter;
}
}
```
Now you are correctly looping through the list checking every index.
|
196,993 |
<p>i have a wordpress blog and want to give people the same user experience for adding comments that is in stackoverflow. There are a number of comments ajax plugins out there but i can't find a working one that allows you to inline on the main page, go in and add comments without first drilling down into a seperate single post page.</p>
<p>Can anyone help here with either a wordpress plugin or php code to do this.</p>
|
[
{
"answer_id": 199132,
"author": "Jay",
"author_id": 20840,
"author_profile": "https://Stackoverflow.com/users/20840",
"pm_score": 2,
"selected": false,
"text": "<p>I think <a href=\"http://wordpress.org/extend/plugins/ajaxd-wordpress/\" rel=\"nofollow noreferrer\">AJAXed Wordpress</a> does what you're looking for, among other things:</p>\n<h3><a href=\"http://anthologyoi.com/awp\" rel=\"nofollow noreferrer\">AJAXed Wordpress</a></h3>\n<blockquote>\n<p>AJAXed Wordpress (AWP) harnesses the power of both AJAX and Wordpress to improve\nthe user experience, the administration capabilities and the design potential of\nany Wordpress based blog. It works on all WordPress versions from 2.1 - 2.6.</p>\n<p>Some of AWP’s features include loading posts inline, <strong>inline comments</strong>, threaded\ncomments, AJAX comment submission, AJAX Navigation, live comment preview and much\nmore. AWP is endlessly customizable and extensible. Even though AWP provides many\nfeatures, you are never forced to use features that you don’t want. All aspects of\nthe plugin are easily customized through a single Administration panel.</p>\n</blockquote>\n<p>Demo is available here <a href=\"http://wordpress.mu/\" rel=\"nofollow noreferrer\">http://wordpress.mu/</a> and you can see the inline comments in action. Looks like what you were asking for.</p>\n"
},
{
"answer_id": 207140,
"author": "coderGeek",
"author_id": 28426,
"author_profile": "https://Stackoverflow.com/users/28426",
"pm_score": 4,
"selected": true,
"text": "<p>I was never able to get AJAXed Wordpress to do what me (and apparently the questioner) want to do.</p>\n\n<p>I use a custom solution that makes use of a plug-in called <a href=\"http://kashou.net/blog/inline-ajax-comments\" rel=\"nofollow noreferrer\">Inline Ajax Comments</a>. I had a heck of a time finding a download link, but here's one that still works: <a href=\"http://kashou.net/files/inline-ajax-comments.zip\" rel=\"nofollow noreferrer\">http://kashou.net/files/inline-ajax-comments.zip</a></p>\n\n<p>In WordPress' theme editor, I edit index.html. After the following:</p>\n\n<pre><code><?php the_content(''); ?>\n</code></pre>\n\n<p>I add (after enabling the plug-in of course):</p>\n\n<pre><code><?php ajax_comments_link(); ?>\n<?php ajax_comments_div(); ?>\n</code></pre>\n\n<p>I then edited the plugin PHP file itself. I commented out blocks of code as follows:</p>\n\n<pre><code>if ($comment_count == '1') {\n echo('<span id=\"show-inline-comments-'. $id .'\"> ');\n /* echo('<a href=\"javascript:;\" id=\"show-inline-comments-link-'. $id .'\" onmouseup=\"ajaxShowComments('. $id .', \\''. $throbberURL .'\\', \\''. $commentpageURL .'\\'); return false;\">show comment &raquo;</a>'); \n*/\n echo('</span>');\n echo('<span id=\"hide-inline-comments-'. $id .'\" style=\"display: none;\"> ');\n /* echo('<a href=\"#comments-'. $id .'\" onmouseup=\"ajaxHideComments('. $id .', \\''. $throbberURL .'\\', \\''. $commentpageURL .'\\'); return true;\">&laquo; hide comment</a>'); \n*/\n echo('</span>');\n} else if ($comment_count > '1') {\n echo('<span id=\"show-inline-comments-'. $id .'\"> ');\n /* echo('<a href=\"javascript:;\" id=\"show-inline-comments-link-'. $id .'\" onmouseup=\"ajaxShowComments('. $id .', \\''. $throbberURL .'\\', \\''. $commentpageURL .'\\'); return false;\">show comments &raquo;</a>'); \n*/\n echo('</span>');\n echo('<span id=\"hide-inline-comments-'. $id .'\" style=\"display: none;\"> ');\n /* echo('<a href=\"#comments-'. $id .'\" onmouseup=\"ajaxHideComments('. $id .', \\''. $throbberURL .'\\', \\''. $commentpageURL .'\\'); return true;\">&laquo; hide comments</a>'); \n*/\n echo('</span>');\n}\n</code></pre>\n\n<p>IIRC, that's all I had to do, but let me know if that doesn't work for you. I'm trying to reverse engineer my own solution since it seems to be exactly what you want to do as well.</p>\n"
},
{
"answer_id": 1073629,
"author": "Jacky",
"author_id": 131878,
"author_profile": "https://Stackoverflow.com/users/131878",
"pm_score": 0,
"selected": false,
"text": "<p>You might want to try <a href=\"http://wordpress.org/extend/plugins/ajax-comment-posting/\" rel=\"nofollow noreferrer\">Ajax Comment Posting</a>. It works for me.</p>\n\n<blockquote>\n <p>There are many comment-related plugins\n in Wordpress plugin directory.\n However, if you'd like to find just a\n simple comment-posting Ajax plugin,\n you won't find any. That's why I\n developed a simple and small (5kB) yet\n functional Ajax Comment Posting (ACP)\n plugin. Not only will it post your\n comment without refreshing the page,\n but it will also make sure that you've\n filled all the form fields correctly.</p>\n</blockquote>\n"
},
{
"answer_id": 1076923,
"author": "shiva",
"author_id": 11018,
"author_profile": "https://Stackoverflow.com/users/11018",
"pm_score": 0,
"selected": false,
"text": "<p>You could use a \n1. AJAX comments plugins (<a href=\"http://wordpress.org/extend/plugins/search.php?q=ajax+comments\" rel=\"nofollow noreferrer\">search for \"Ajax comments\" on wordpress</a>)\n2. Write your own custom code.\n3. Use disqus.</p>\n\n<p>Regardless of the option you choose from the above, you still need to expose comments on the main page. This can be done (based on the option you choose) by changing the index.php of your template, to display comments after displaying the text of every post. however, this will increase page load times, and also affect the design of your main page (plus linking to a specific page will not have much value anymore).</p>\n"
},
{
"answer_id": 1080950,
"author": "marcgg",
"author_id": 90691,
"author_profile": "https://Stackoverflow.com/users/90691",
"pm_score": 0,
"selected": false,
"text": "<p>There are a lot of plugins doing that. Ajax Comment Posting is pretty simple to install and use. As they say:</p>\n\n<ol>\n<li>Upload the plugin directory ajax-comment-posting to the wp-content/plugins directory.</li>\n<li>Activate the plugin through the 'Plugins' menu in WordPress.</li>\n<li>That's it!</li>\n</ol>\n\n<p><a href=\"http://wordpress.org/extend/plugins/ajax-comment-posting/\" rel=\"nofollow noreferrer\">http://wordpress.org/extend/plugins/ajax-comment-posting/</a></p>\n"
},
{
"answer_id": 1082189,
"author": "anshul",
"author_id": 17674,
"author_profile": "https://Stackoverflow.com/users/17674",
"pm_score": 1,
"selected": false,
"text": "<p>You could repurpose code from <a href=\"http://wordpress.org/extend/themes/p2\" rel=\"nofollow noreferrer\">P2</a> theme. It's a rather well written theme so this should largely work without any problems. Copy all the code from their <code>functions.php</code> to the bottom of your theme's <code>functions.php</code>. Copy their <code>inc</code> directory and <code>entry.php</code> to your theme directory.</p>\n\n<p>Replace in your <code>index.php</code></p>\n\n<pre><code> <?php if (have_posts()) : ?> \n\n <?php while (have_posts()) : the_post(); ?> \n <?php /* your themes code must be here */ ?>\n\n <?php endwhile; ?> \n</code></pre>\n\n<p>with</p>\n\n<pre><code> <?php if (have_posts()) : ?> \n\n <?php while (have_posts()) : the_post(); ?> \n <?php require dirname(__FILE__) . '/entry.php'; ?> \n\n <?php endwhile; ?> \n</code></pre>\n\n<p>and then modify the css and other stuff in entry.php to taste.</p>\n"
},
{
"answer_id": 7620627,
"author": "Wanda Amers",
"author_id": 974512,
"author_profile": "https://Stackoverflow.com/users/974512",
"pm_score": 0,
"selected": false,
"text": "<p>I recommend this <a href=\"http://wordpress.org/extend/plugins/ajax-comment-posting/\" rel=\"nofollow\">http://wordpress.org/extend/plugins/ajax-comment-posting/</a> . I hope it helps.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/196993",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4653/"
] |
i have a wordpress blog and want to give people the same user experience for adding comments that is in stackoverflow. There are a number of comments ajax plugins out there but i can't find a working one that allows you to inline on the main page, go in and add comments without first drilling down into a seperate single post page.
Can anyone help here with either a wordpress plugin or php code to do this.
|
I was never able to get AJAXed Wordpress to do what me (and apparently the questioner) want to do.
I use a custom solution that makes use of a plug-in called [Inline Ajax Comments](http://kashou.net/blog/inline-ajax-comments). I had a heck of a time finding a download link, but here's one that still works: <http://kashou.net/files/inline-ajax-comments.zip>
In WordPress' theme editor, I edit index.html. After the following:
```
<?php the_content(''); ?>
```
I add (after enabling the plug-in of course):
```
<?php ajax_comments_link(); ?>
<?php ajax_comments_div(); ?>
```
I then edited the plugin PHP file itself. I commented out blocks of code as follows:
```
if ($comment_count == '1') {
echo('<span id="show-inline-comments-'. $id .'"> ');
/* echo('<a href="javascript:;" id="show-inline-comments-link-'. $id .'" onmouseup="ajaxShowComments('. $id .', \''. $throbberURL .'\', \''. $commentpageURL .'\'); return false;">show comment »</a>');
*/
echo('</span>');
echo('<span id="hide-inline-comments-'. $id .'" style="display: none;"> ');
/* echo('<a href="#comments-'. $id .'" onmouseup="ajaxHideComments('. $id .', \''. $throbberURL .'\', \''. $commentpageURL .'\'); return true;">« hide comment</a>');
*/
echo('</span>');
} else if ($comment_count > '1') {
echo('<span id="show-inline-comments-'. $id .'"> ');
/* echo('<a href="javascript:;" id="show-inline-comments-link-'. $id .'" onmouseup="ajaxShowComments('. $id .', \''. $throbberURL .'\', \''. $commentpageURL .'\'); return false;">show comments »</a>');
*/
echo('</span>');
echo('<span id="hide-inline-comments-'. $id .'" style="display: none;"> ');
/* echo('<a href="#comments-'. $id .'" onmouseup="ajaxHideComments('. $id .', \''. $throbberURL .'\', \''. $commentpageURL .'\'); return true;">« hide comments</a>');
*/
echo('</span>');
}
```
IIRC, that's all I had to do, but let me know if that doesn't work for you. I'm trying to reverse engineer my own solution since it seems to be exactly what you want to do as well.
|
197,005 |
<p>I'm using System.Reflection.Emit for a while now, and find it (who don't?) as painful as bug prone.</p>
<p>Do you know if there is a good wrapper around the IL Generator, something that I can rely on to emit IL in a more safe and easier manner than with playing directly with SRE?</p>
<p><strong>Edit:</strong></p>
<p>I know that manipulating expression trees is definitively easier and safer than emitting IL directly, but they also have some constraints right now. I can't create code blocs, use loops, declare and work with several locals, etc. We need to wait until .NET 4 comes out :)</p>
<p>Moreover, I'm dealing with a code base which already relies on SRE.</p>
<p>Obviously, ILGenerator do everything I need. But I would appreciate more assistance when manipulating it. When I'm referring to a ILGenerator wrapper, which remains at a pretty low level, I think about something which could provide methods like:</p>
<pre><code>// Performs a virtual or direct call on the method, depending if it is a
// virtual or a static one.
Call(MethodInfo methodInfo)
// Pushes the default value of the type on the stack, then emit
// the Ret opcode.
ReturnDefault(Type type)
// Test the object type to emit the corresponding push
// opcode (Ldstr, Ldc_I*, Ldc_R*, etc.)
LoadConstant(object o)
</code></pre>
<p>It's really 3 naive examples, but it could be enough to demonstrate what I expect. We can see that as a set of extension methods, but it could be nice to have support for conditional statements and loops like in <a href="http://www.codeproject.com/KB/dotnet/runsharp.aspx" rel="noreferrer">RunSharp</a>. In fact, RunSharp is pretty close that what I want, but it abstracts the ILGenerator too much and doesn't expose all its functionality.</p>
<p>I can't remember where, but I already saw such an helper in an open source project.</p>
|
[
{
"answer_id": 197017,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": false,
"text": "<p>If you're using .NET 3.5, you may find using Expression Trees to be more reasonable. It entirely depends on what you're doing - and it can still be quite painful - but it's certainly another option to be aware of.</p>\n"
},
{
"answer_id": 197018,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 2,
"selected": false,
"text": "<p>[updated]: I thought of the name ;-p <a href=\"http://www.codeproject.com/KB/dotnet/runsharp.aspx\" rel=\"nofollow noreferrer\">RunSharp</a>. I can't vouch for it, but it might be what you need.</p>\n\n<p>However; what do you need to generate? <a href=\"http://msdn.microsoft.com/en-us/library/y2k85ax6.aspx\" rel=\"nofollow noreferrer\">CodeDom</a> is one option. For creating methods, you might find that you can do a lot more than you expect with the <a href=\"http://msdn.microsoft.com/en-us/library/system.linq.expressions.expression.aspx\" rel=\"nofollow noreferrer\">Expression</a> class in .NET 3.5 (after compiling it to a typed delegate via Expression.Lambda/Compile.</p>\n"
},
{
"answer_id": 197024,
"author": "jfs",
"author_id": 718,
"author_profile": "https://Stackoverflow.com/users/718",
"pm_score": 2,
"selected": false,
"text": "<p>Try using <a href=\"http://www.mono-project.com/Cecil\" rel=\"nofollow noreferrer\">Mono.Cecil</a></p>\n\n<blockquote>\n <p>Cecil is a library written by <a href=\"http://evain.net/blog/\" rel=\"nofollow noreferrer\">Jb Evain</a>\n to generate\n and inspect programs and libraries in\n the ECMA CIL format. It has full\n support for generics, and support some\n debugging symbol format.</p>\n</blockquote>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197005",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4687/"
] |
I'm using System.Reflection.Emit for a while now, and find it (who don't?) as painful as bug prone.
Do you know if there is a good wrapper around the IL Generator, something that I can rely on to emit IL in a more safe and easier manner than with playing directly with SRE?
**Edit:**
I know that manipulating expression trees is definitively easier and safer than emitting IL directly, but they also have some constraints right now. I can't create code blocs, use loops, declare and work with several locals, etc. We need to wait until .NET 4 comes out :)
Moreover, I'm dealing with a code base which already relies on SRE.
Obviously, ILGenerator do everything I need. But I would appreciate more assistance when manipulating it. When I'm referring to a ILGenerator wrapper, which remains at a pretty low level, I think about something which could provide methods like:
```
// Performs a virtual or direct call on the method, depending if it is a
// virtual or a static one.
Call(MethodInfo methodInfo)
// Pushes the default value of the type on the stack, then emit
// the Ret opcode.
ReturnDefault(Type type)
// Test the object type to emit the corresponding push
// opcode (Ldstr, Ldc_I*, Ldc_R*, etc.)
LoadConstant(object o)
```
It's really 3 naive examples, but it could be enough to demonstrate what I expect. We can see that as a set of extension methods, but it could be nice to have support for conditional statements and loops like in [RunSharp](http://www.codeproject.com/KB/dotnet/runsharp.aspx). In fact, RunSharp is pretty close that what I want, but it abstracts the ILGenerator too much and doesn't expose all its functionality.
I can't remember where, but I already saw such an helper in an open source project.
|
If you're using .NET 3.5, you may find using Expression Trees to be more reasonable. It entirely depends on what you're doing - and it can still be quite painful - but it's certainly another option to be aware of.
|
197,009 |
<p>A python script is running two parallel python processes ( created via os.fork() ) each of which eventually tries to check out a subversion repository leaf into the same working copy dir.</p>
<p>Before running 'svn co ...' command in a sub-process ( via python subprocess module ) the parent python code checks if the working copy dir already exists. </p>
<pre><code> if os.path.isdir(checkout_dir):
# working copy dir already exists
return checkout_dir
</code></pre>
<p>So that if it does there shouldn't be any 'svn co' running, but rather immediate return from the parent function.</p>
<p>Nevertheless some collision happened and one of the python processes failed on 'svn co ..' with the following error.</p>
<pre><code>checked-out failed: svn: Working copy '/tmp/qm_23683' locked
svn: run 'svn cleanup' to remove locks (type 'svn help cleanup' for details)**
</code></pre>
<p>So the first question is why the working copy dir existence check didn't work and the second - is there a way to find out that a working copy dir is locked by svn and loop until it is unlocked?</p>
<p>Thanks.</p>
|
[
{
"answer_id": 197025,
"author": "Liam",
"author_id": 18333,
"author_profile": "https://Stackoverflow.com/users/18333",
"pm_score": 2,
"selected": false,
"text": "<p>Within the directory, there should be a directory called '.svn'. Within this, a file named 'locked' indicates that the directory is locked.</p>\n"
},
{
"answer_id": 199791,
"author": "zaphod",
"author_id": 13871,
"author_profile": "https://Stackoverflow.com/users/13871",
"pm_score": 3,
"selected": true,
"text": "<p>This sounds like a potential race condition, in that something like the following can happen:</p>\n\n<ol>\n<li>Process A checks to see if the directory exists (it doesn't yet).</li>\n<li>Process B checks to see if the directory exists (it doesn't yet).</li>\n<li>Process A invokes <code>svn</code>, which creates the directory.</li>\n<li>Process B invokes <code>svn</code>, which subsequently fails.</li>\n</ol>\n\n<p>An easy way to avoid this is to have each process attempt to <em>create</em> the directory rather than checking for its existence. If the other process has already created the directory, the other process is guaranteed to get a well-defined error code under a very wide variety of platforms and filesystems. For instance, this is one of the only reliable ways to do synchronization on many implementations of NFS. Luckily, <code>svn</code> won't care if the working directory already exists.</p>\n\n<p>The Python code would look something like this:</p>\n\n<pre><code>import os, errno\n\n# ...\n\ntry:\n os.mkdir(dirName)\nexcept OSError, e:\n if e.errno != errno.EEXIST: raise # some other error\n print 'Directory already exists.'\nelse:\n print 'Successfully created new directory.'\n</code></pre>\n\n<p>This technique is easy to implement, very reliable, and useful in a wide variety of situations.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/140995/"
] |
A python script is running two parallel python processes ( created via os.fork() ) each of which eventually tries to check out a subversion repository leaf into the same working copy dir.
Before running 'svn co ...' command in a sub-process ( via python subprocess module ) the parent python code checks if the working copy dir already exists.
```
if os.path.isdir(checkout_dir):
# working copy dir already exists
return checkout_dir
```
So that if it does there shouldn't be any 'svn co' running, but rather immediate return from the parent function.
Nevertheless some collision happened and one of the python processes failed on 'svn co ..' with the following error.
```
checked-out failed: svn: Working copy '/tmp/qm_23683' locked
svn: run 'svn cleanup' to remove locks (type 'svn help cleanup' for details)**
```
So the first question is why the working copy dir existence check didn't work and the second - is there a way to find out that a working copy dir is locked by svn and loop until it is unlocked?
Thanks.
|
This sounds like a potential race condition, in that something like the following can happen:
1. Process A checks to see if the directory exists (it doesn't yet).
2. Process B checks to see if the directory exists (it doesn't yet).
3. Process A invokes `svn`, which creates the directory.
4. Process B invokes `svn`, which subsequently fails.
An easy way to avoid this is to have each process attempt to *create* the directory rather than checking for its existence. If the other process has already created the directory, the other process is guaranteed to get a well-defined error code under a very wide variety of platforms and filesystems. For instance, this is one of the only reliable ways to do synchronization on many implementations of NFS. Luckily, `svn` won't care if the working directory already exists.
The Python code would look something like this:
```
import os, errno
# ...
try:
os.mkdir(dirName)
except OSError, e:
if e.errno != errno.EEXIST: raise # some other error
print 'Directory already exists.'
else:
print 'Successfully created new directory.'
```
This technique is easy to implement, very reliable, and useful in a wide variety of situations.
|
197,027 |
<p>I would like to declare a dropdown box in a view in an ASP.NET MVC application, for letting the user select a lookup value. I know how to declare plain text boxes but is there an official helper for declaring dropdown boxes (date time pickers and the rest)?.</p>
<p>I also don't know what structure I should pass to my view for giving the values to the dropdown box. I assume I need both an id and a description.</p>
<p>Finally, how do I pass the selected id from the dropdown box back to my action in the controller?</p>
|
[
{
"answer_id": 197549,
"author": "Elijah Manor",
"author_id": 4481,
"author_profile": "https://Stackoverflow.com/users/4481",
"pm_score": 1,
"selected": false,
"text": "<p>You might check out this blog entry by Scott Guthrie about <a href=\"http://weblogs.asp.net/scottgu/archive/2007/12/09/asp-net-mvc-framework-part-4-handling-form-edit-and-post-scenarios.aspx\" rel=\"nofollow noreferrer\">Handling Form Edit Post Scenarios</a>. He uses a drop down list in an example of his.</p>\n\n<p>You can provide a list of complex objects to the drop down list too (Scott Guthrie's example doesn't show that, but it alludes to it).</p>\n\n<p>You can do something like this...</p>\n\n<pre><code><%= Html.DropDownList(\"Select One\", \"CategoryId\", ViewData.Model.Categories, \"Id\", \"Name\", ViewData.Model.SelectedCategoryId)) %>\n</code></pre>\n\n<p>\"Id\" and \"Name\" refer to properties on your ViewData.Model.Categories list of objects.</p>\n\n<p>If SelectedCategoryId has a value, then it will default the dropdownlist. </p>\n"
},
{
"answer_id": 476759,
"author": "Konstantinos",
"author_id": 17443,
"author_profile": "https://Stackoverflow.com/users/17443",
"pm_score": 3,
"selected": true,
"text": "<p>If you have a table of Product Types with description and a value ( id ) that you want to map to your dropdown then do the following inside your action in the controller.</p>\n\n<pre><code>//Lets assume you retrieve your product types somehow here\nViewData[\"ProductTypes\"] = new List<ProductType>();\n</code></pre>\n\n<p>Then inside your view type the following</p>\n\n<pre><code><%= Html.DropDownList(\"productType\",\n new SelectList((IEnumerable)ViewData[\"ProductTypes\"],\n \"TypeID\", \"Description\"))%>\n</code></pre>\n\n<p>TypeID and Description refers to the properties of your object of type ProductType</p>\n\n<p>Also, you might not find Html.DropDownList if you have an older version of MVC installed, make sure you have a Beta+ version before you try this out.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197027",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2812/"
] |
I would like to declare a dropdown box in a view in an ASP.NET MVC application, for letting the user select a lookup value. I know how to declare plain text boxes but is there an official helper for declaring dropdown boxes (date time pickers and the rest)?.
I also don't know what structure I should pass to my view for giving the values to the dropdown box. I assume I need both an id and a description.
Finally, how do I pass the selected id from the dropdown box back to my action in the controller?
|
If you have a table of Product Types with description and a value ( id ) that you want to map to your dropdown then do the following inside your action in the controller.
```
//Lets assume you retrieve your product types somehow here
ViewData["ProductTypes"] = new List<ProductType>();
```
Then inside your view type the following
```
<%= Html.DropDownList("productType",
new SelectList((IEnumerable)ViewData["ProductTypes"],
"TypeID", "Description"))%>
```
TypeID and Description refers to the properties of your object of type ProductType
Also, you might not find Html.DropDownList if you have an older version of MVC installed, make sure you have a Beta+ version before you try this out.
|
197,028 |
<p>neither</p>
<pre><code><?php system('php file.php'); ?>
</code></pre>
<p>nor</p>
<pre><code><?php system('/usr/bin/php file.php'); ?>
</code></pre>
<p>worked. Why?</p>
<p>I tried with <code>-q</code>, with <code>!#/usr/bin/php</code> etc.</p>
|
[
{
"answer_id": 197032,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 0,
"selected": false,
"text": "<p>Without any more info... it's probably the path to the PHP executable, the path to file.php or a file permissions problem.</p>\n"
},
{
"answer_id": 197034,
"author": "Vegard Larsen",
"author_id": 1606,
"author_profile": "https://Stackoverflow.com/users/1606",
"pm_score": 2,
"selected": false,
"text": "<p>You are supposed to call it with -f, but it should work without it as well:</p>\n\n<pre><code><?php system('/usr/bin/php -f file.php'); ?>\n</code></pre>\n\n<p>What do you mean by \"it doesn't work\"? </p>\n\n<p>Did you want the contents to be outputted as if they were from your script? Use <a href=\"http://php.net/include\" rel=\"nofollow noreferrer\">include</a> or <a href=\"http://php.net/require\" rel=\"nofollow noreferrer\">require</a>.</p>\n\n<p>Did you want the contents in a variable? Use the <a href=\"http://www.php.net/manual/en/language.operators.execution.php\" rel=\"nofollow noreferrer\">backtick operator</a>.</p>\n\n<p>You can see what you get back from the command by using the backtick operator instead of system.</p>\n"
},
{
"answer_id": 197035,
"author": "Roel",
"author_id": 11449,
"author_profile": "https://Stackoverflow.com/users/11449",
"pm_score": 0,
"selected": false,
"text": "<p>What happens when you pass in a full path to 'file.php'?</p>\n\n<p>Also, try to redirect the output (but stdout and stderr) to a file so that you can see the error messages that are generated.</p>\n"
},
{
"answer_id": 197038,
"author": "Tahir Akhtar",
"author_id": 18027,
"author_profile": "https://Stackoverflow.com/users/18027",
"pm_score": 1,
"selected": false,
"text": "<p>Could be due to safe mode. </p>\n\n<blockquote>\n<pre><code>Note: When safe mode is enabled, you can only execute files within the safe_mode_exec_dir. For practical reasons, it is currently not allowed to have .. components in the path to the executable.\n</code></pre>\n \n <p><a href=\"http://www.php.net/system\" rel=\"nofollow noreferrer\">http://www.php.net/system</a>. </p>\n</blockquote>\n"
},
{
"answer_id": 197084,
"author": "barredo",
"author_id": 7398,
"author_profile": "https://Stackoverflow.com/users/7398",
"pm_score": 0,
"selected": false,
"text": "<p>Thanks all for answering!!</p>\n\n<p>For 'doesn't work' I meant: it does not return or print anything.</p>\n\n<p>I have two files a.php && b.php (with all permissions) and safe_mode is off</p>\n\n<p>b.php</p>\n\n<pre><code><?php\n$a = system('/usr/bin/php -f /Applications/MAMP/htdocs/a.php',$b);\nprint_r($a);\necho '-'; # for separation\nprint_r($b); ?>\n</code></pre>\n\n<p>and a.php</p>\n\n<pre><code><?php echo 'hello world'; ?>\n</code></pre>\n\n<p>and when I run b.php from my browser (localhost/b.php) it prints:</p>\n\n<blockquote>\n <p>string(0) \"\"\n -int(5)</p>\n</blockquote>\n\n<p>that means $b variable is 5 but... 5 what?</p>\n"
},
{
"answer_id": 197085,
"author": "olle",
"author_id": 22422,
"author_profile": "https://Stackoverflow.com/users/22422",
"pm_score": 0,
"selected": false,
"text": "<p>What does it say when you turn on error reporting?</p>\n\n<pre><code><?php\nerror_reporting(E_ALL);\nini_set(\"display_errors\", 1);\n$a = system('/usr/bin/php -f /Applications/MAMP/htdocs/a.php',$b);\nprint_r($a);\necho '-'; # for separation\nprint_r($b);\n</code></pre>\n"
},
{
"answer_id": 197256,
"author": "barredo",
"author_id": 7398,
"author_profile": "https://Stackoverflow.com/users/7398",
"pm_score": 0,
"selected": false,
"text": "<p>When I change</p>\n\n<pre><code>system('/usr/bin/php -f /Applications/MAMP/htdocs/a.php',$b);\n</code></pre>\n\n<p>for</p>\n\n<pre><code>('/bin/php -f /Applications/MAMP/htdocs/a.php',$b);\n</code></pre>\n\n<p>then it says 127 instead of 5, I guess these are error codes</p>\n"
},
{
"answer_id": 197259,
"author": "Milan Babuškov",
"author_id": 14690,
"author_profile": "https://Stackoverflow.com/users/14690",
"pm_score": -1,
"selected": false,
"text": "<p>You obviously don't understand how <em>system</em> function works. What you really need is probably <a href=\"http://www.php.net/popen\" rel=\"nofollow noreferrer\">popen</a>. Start the process with <em>popen</em> and then read its output with <em>fgets</em> for example.</p>\n\n<p>Alternatively, you can use the backtick operator as already suggested by others.</p>\n"
},
{
"answer_id": 197276,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 0,
"selected": false,
"text": "<p>Try:</p>\n\n<pre><code>$output = array();\n$returnCode = 0;\nexec('/usr/bin/php -f /Applications/MAMP/htdocs/a.php 2>&1', $output, $returnCode);\nprint_r($output);\n</code></pre>\n\n<p>The <code>2>&1</code> redirects stderr to stdout, so any error messages will be captured in <code>$output</code></p>\n"
},
{
"answer_id": 197286,
"author": "ZombieSheep",
"author_id": 377,
"author_profile": "https://Stackoverflow.com/users/377",
"pm_score": 0,
"selected": false,
"text": "<p>Hang on... What are you actually trying to achieve here? Just run a.php and return the output to the browser? In that case, <a href=\"http://www.php.net/include\" rel=\"nofollow noreferrer\">include</a> it. From the looks of your posted content of a.php ( <?php echo 'hello world'; ?> ), that seems to be what you want. </p>\n\n<p>If there's more to the content of a.php, then please post back and explain what you really want to do.</p>\n"
},
{
"answer_id": 197908,
"author": "Gary Richardson",
"author_id": 2506,
"author_profile": "https://Stackoverflow.com/users/2506",
"pm_score": 0,
"selected": false,
"text": "<p>Try:</p>\n\n<pre><code>$fp = popen('/usr/bin/php -f file.php', 'r');\n\nif(false === $fp)\n{\n // something bad happened: error handle\n}\n\n$contents = '';\n\nwhile(false === feof($fp))\n{\n $contents .= fgets($fp);\n}\n\nfclose($fp); \necho $contents;\n</code></pre>\n\n<p>That will allow you to capture the subshell's output and trap for errors.</p>\n"
},
{
"answer_id": 199452,
"author": "Zoredache",
"author_id": 20267,
"author_profile": "https://Stackoverflow.com/users/20267",
"pm_score": 0,
"selected": false,
"text": "<p>}} For 'doesn't work' I meant: it does not return or print anything.</p>\n\n<p>Try get a terminal/shell on your server and try your system command. If your OS is unixy you can use something like <strong>which php</strong> to find the correct path to the php cli.</p>\n\n<p>You did install the php cli right? It generally isn't installed by default.</p>\n\n<p>Does your web server do a chroot or something? Perhaps the php cli doesn't exist in the environment where you are trying to use system().</p>\n\n<p>Instead of trying to call a script try doing a simple <strong>system('php -v')</strong>. Once you get that to correctly output the php version number then add the call to your script.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197028",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7398/"
] |
neither
```
<?php system('php file.php'); ?>
```
nor
```
<?php system('/usr/bin/php file.php'); ?>
```
worked. Why?
I tried with `-q`, with `!#/usr/bin/php` etc.
|
You are supposed to call it with -f, but it should work without it as well:
```
<?php system('/usr/bin/php -f file.php'); ?>
```
What do you mean by "it doesn't work"?
Did you want the contents to be outputted as if they were from your script? Use [include](http://php.net/include) or [require](http://php.net/require).
Did you want the contents in a variable? Use the [backtick operator](http://www.php.net/manual/en/language.operators.execution.php).
You can see what you get back from the command by using the backtick operator instead of system.
|
197,033 |
<p>Where is the location of my oracle event log (on a default Linux installation)?</p>
|
[
{
"answer_id": 197108,
"author": "cagcowboy",
"author_id": 19629,
"author_profile": "https://Stackoverflow.com/users/19629",
"pm_score": 5,
"selected": true,
"text": "<pre><code>select value from v$parameter where name = 'background_dump_dest'\n</code></pre>\n"
},
{
"answer_id": 197120,
"author": "Andrew",
"author_id": 5662,
"author_profile": "https://Stackoverflow.com/users/5662",
"pm_score": 3,
"selected": false,
"text": "<p>Using @<a href=\"https://stackoverflow.com/questions/197033/where-is-the-oracle-event-log-located#197108\">cagcowboy's answer</a>, a default <a href=\"http://www.oracle.com/technology/products/database/xe/index.html\" rel=\"nofollow noreferrer\">Oracle XE</a> installation on Linux writes out to:</p>\n<pre><code>/usr/lib/oracle/xe/app/oracle/admin/XE/bdump\n</code></pre>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197033",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27346/"
] |
Where is the location of my oracle event log (on a default Linux installation)?
|
```
select value from v$parameter where name = 'background_dump_dest'
```
|
197,045 |
<p>Is it possible to set a default value for columns in JPA, and if, how is it done using annotations?</p>
|
[
{
"answer_id": 197072,
"author": "PEELY",
"author_id": 17641,
"author_profile": "https://Stackoverflow.com/users/17641",
"pm_score": 2,
"selected": false,
"text": "<p>This isn't possible in JPA.</p>\n\n<p>Here's what you <em>can</em> do with the Column annotation: <a href=\"http://java.sun.com/javaee/5/docs/api/javax/persistence/Column.html\" rel=\"nofollow noreferrer\">http://java.sun.com/javaee/5/docs/api/javax/persistence/Column.html</a></p>\n"
},
{
"answer_id": 346874,
"author": "Timo",
"author_id": 44002,
"author_profile": "https://Stackoverflow.com/users/44002",
"pm_score": 3,
"selected": false,
"text": "<p>You can't do this with the column annotation. I think the only way is to set the default value when a object is created. Maybe the default constructor would be the right place to do that. </p>\n"
},
{
"answer_id": 375202,
"author": "Cameron Pope",
"author_id": 1385388,
"author_profile": "https://Stackoverflow.com/users/1385388",
"pm_score": 9,
"selected": true,
"text": "<p>Actually it is possible in JPA, although a little bit of a hack using the <code>columnDefinition</code> property of the <code>@Column</code> annotation, for example:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>@Column(name=\"Price\", columnDefinition=\"Decimal(10,2) default '100.00'\")\n</code></pre>\n"
},
{
"answer_id": 1013520,
"author": "Pablo Venturino",
"author_id": 16732,
"author_profile": "https://Stackoverflow.com/users/16732",
"pm_score": 8,
"selected": false,
"text": "<p>You can do the following:</p>\n\n<pre><code>@Column(name=\"price\")\nprivate double price = 0.0;\n</code></pre>\n\n<p>There! You've just used zero as the default value.</p>\n\n<p>Note this will serve you if you're only accessing the database from this application. If other applications also use the database, then you should make this check from the database using <a href=\"https://stackoverflow.com/questions/197045/setting-default-values-for-columns-in-jpa/375202#375202\">Cameron's</a> <em>columnDefinition</em> annotation attribute, or some other way.</p>\n"
},
{
"answer_id": 2554796,
"author": "asd",
"author_id": 306202,
"author_profile": "https://Stackoverflow.com/users/306202",
"pm_score": 3,
"selected": false,
"text": "<pre><code>@Column(columnDefinition=\"tinyint(1) default 1\")\n</code></pre>\n\n<p>I just tested the issue. <strong>It works just fine.</strong> Thanks for the hint. </p>\n\n<hr>\n\n<p>About the comments:</p>\n\n<pre><code>@Column(name=\"price\") \nprivate double price = 0.0;\n</code></pre>\n\n<p>This one <strong>doesn't</strong> set the default column value in the database (of course). </p>\n"
},
{
"answer_id": 2622053,
"author": "Marco",
"author_id": 314510,
"author_profile": "https://Stackoverflow.com/users/314510",
"pm_score": 4,
"selected": false,
"text": "<p>JPA doesn't support that and it would be useful if it did. Using columnDefinition is DB-specific and not acceptable in many cases. setting a default in the class is not enough when you retrieve a record having null values (which typically happens when you re-run old DBUnit tests). What I do is this: </p>\n\n<pre><code>public class MyObject\n{\n int attrib = 0;\n\n /** Default is 0 */\n @Column ( nullable = true )\n public int getAttrib()\n\n /** Falls to default = 0 when null */\n public void setAttrib ( Integer attrib ) {\n this.attrib = attrib == null ? 0 : attrib;\n }\n}\n</code></pre>\n\n<p>Java auto-boxing helps a lot in that. </p>\n"
},
{
"answer_id": 3400418,
"author": "Derek Mahar",
"author_id": 107158,
"author_profile": "https://Stackoverflow.com/users/107158",
"pm_score": 1,
"selected": false,
"text": "<p>Neither JPA nor Hibernate annotations support the notion of a default column value. As a workaround to this limitation, set all default values just before you invoke a Hibernate <code>save()</code> or <code>update()</code> on the session. This closely as possible (short of Hibernate setting the default values) mimics the behaviour of the database which sets default values when it saves a row in a table.</p>\n\n<p>Unlike setting the default values in the model class as this <a href=\"https://stackoverflow.com/questions/197045/setting-default-values-for-columns-in-jpa/1013520#1013520\">alternative answer</a> suggests, this approach also ensures that criteria queries that use an <code>Example</code> object as a prototype for the search will continue to work as before. When you set the default value of a nullable attribute (one that has a non-primitive type) in a model class, a Hibernate query-by-example will no longer ignore the associated column where previously it would ignore it because it was null.</p>\n"
},
{
"answer_id": 4167460,
"author": "TC1",
"author_id": 454597,
"author_profile": "https://Stackoverflow.com/users/454597",
"pm_score": 3,
"selected": false,
"text": "<p>Seeing as I stumbled upon this from Google while trying to solve the very same problem, I'm just gonna throw in the solution I cooked up in case someone finds it useful.</p>\n\n<p>From my point of view there's really only 1 solutions to this problem -- @PrePersist. If you do it in @PrePersist, you gotta check if the value's been set already though.</p>\n"
},
{
"answer_id": 8585494,
"author": "Lenik",
"author_id": 217071,
"author_profile": "https://Stackoverflow.com/users/217071",
"pm_score": 3,
"selected": false,
"text": "<p>In my case, I modified hibernate-core source code, well, to introduce a new annotation <code>@DefaultValue</code>:</p>\n\n<pre><code>commit 34199cba96b6b1dc42d0d19c066bd4d119b553d5\nAuthor: Lenik <xjl at 99jsj.com>\nDate: Wed Dec 21 13:28:33 2011 +0800\n\n Add default-value ddl support with annotation @DefaultValue.\n\ndiff --git a/hibernate-core/src/main/java/org/hibernate/annotations/DefaultValue.java b/hibernate-core/src/main/java/org/hibernate/annotations/DefaultValue.java\nnew file mode 100644\nindex 0000000..b3e605e\n--- /dev/null\n+++ b/hibernate-core/src/main/java/org/hibernate/annotations/DefaultValue.java\n@@ -0,0 +1,35 @@\n+package org.hibernate.annotations;\n+\n+import static java.lang.annotation.ElementType.FIELD;\n+import static java.lang.annotation.ElementType.METHOD;\n+import static java.lang.annotation.RetentionPolicy.RUNTIME;\n+\n+import java.lang.annotation.Retention;\n+\n+/**\n+ * Specify a default value for the column.\n+ *\n+ * This is used to generate the auto DDL.\n+ *\n+ * WARNING: This is not part of JPA 2.0 specification.\n+ *\n+ * @author 谢继雷\n+ */\[email protected]({ FIELD, METHOD })\n+@Retention(RUNTIME)\n+public @interface DefaultValue {\n+\n+ /**\n+ * The default value sql fragment.\n+ *\n+ * For string values, you need to quote the value like 'foo'.\n+ *\n+ * Because different database implementation may use different \n+ * quoting format, so this is not portable. But for simple values\n+ * like number and strings, this is generally enough for use.\n+ */\n+ String value();\n+\n+}\ndiff --git a/hibernate-core/src/main/java/org/hibernate/cfg/Ejb3Column.java b/hibernate-core/src/main/java/org/hibernate/cfg/Ejb3Column.java\nindex b289b1e..ac57f1a 100644\n--- a/hibernate-core/src/main/java/org/hibernate/cfg/Ejb3Column.java\n+++ b/hibernate-core/src/main/java/org/hibernate/cfg/Ejb3Column.java\n@@ -29,6 +29,7 @@ import org.hibernate.AnnotationException;\n import org.hibernate.AssertionFailure;\n import org.hibernate.annotations.ColumnTransformer;\n import org.hibernate.annotations.ColumnTransformers;\n+import org.hibernate.annotations.DefaultValue;\n import org.hibernate.annotations.common.reflection.XProperty;\n import org.hibernate.cfg.annotations.Nullability;\n import org.hibernate.mapping.Column;\n@@ -65,6 +66,7 @@ public class Ejb3Column {\n private String propertyName;\n private boolean unique;\n private boolean nullable = true;\n+ private String defaultValue;\n private String formulaString;\n private Formula formula;\n private Table table;\n@@ -175,7 +177,15 @@ public class Ejb3Column {\n return mappingColumn.isNullable();\n }\n\n- public Ejb3Column() {\n+ public String getDefaultValue() {\n+ return defaultValue;\n+ }\n+\n+ public void setDefaultValue(String defaultValue) {\n+ this.defaultValue = defaultValue;\n+ }\n+\n+ public Ejb3Column() {\n }\n\n public void bind() {\n@@ -186,7 +196,7 @@ public class Ejb3Column {\n }\n else {\n initMappingColumn(\n- logicalColumnName, propertyName, length, precision, scale, nullable, sqlType, unique, true\n+ logicalColumnName, propertyName, length, precision, scale, nullable, sqlType, unique, defaultValue, true\n );\n log.debug( \"Binding column: \" + toString());\n }\n@@ -201,6 +211,7 @@ public class Ejb3Column {\n boolean nullable,\n String sqlType,\n boolean unique,\n+ String defaultValue,\n boolean applyNamingStrategy) {\n if ( StringHelper.isNotEmpty( formulaString ) ) {\n this.formula = new Formula();\n@@ -217,6 +228,7 @@ public class Ejb3Column {\n this.mappingColumn.setNullable( nullable );\n this.mappingColumn.setSqlType( sqlType );\n this.mappingColumn.setUnique( unique );\n+ this.mappingColumn.setDefaultValue(defaultValue);\n\n if(writeExpression != null && !writeExpression.matches(\"[^?]*\\\\?[^?]*\")) {\n throw new AnnotationException(\n@@ -454,6 +466,11 @@ public class Ejb3Column {\n else {\n column.setLogicalColumnName( columnName );\n }\n+ DefaultValue _defaultValue = inferredData.getProperty().getAnnotation(DefaultValue.class);\n+ if (_defaultValue != null) {\n+ String defaultValue = _defaultValue.value();\n+ column.setDefaultValue(defaultValue);\n+ }\n\n column.setPropertyName(\n BinderHelper.getRelativePath( propertyHolder, inferredData.getPropertyName() )\ndiff --git a/hibernate-core/src/main/java/org/hibernate/cfg/Ejb3JoinColumn.java b/hibernate-core/src/main/java/org/hibernate/cfg/Ejb3JoinColumn.java\nindex e57636a..3d871f7 100644\n--- a/hibernate-core/src/main/java/org/hibernate/cfg/Ejb3JoinColumn.java\n+++ b/hibernate-core/src/main/java/org/hibernate/cfg/Ejb3JoinColumn.java\n@@ -423,6 +424,7 @@ public class Ejb3JoinColumn extends Ejb3Column {\n getMappingColumn() != null ? getMappingColumn().isNullable() : false,\n referencedColumn.getSqlType(),\n getMappingColumn() != null ? getMappingColumn().isUnique() : false,\n+ null, // default-value\n false\n );\n linkWithValue( value );\n@@ -502,6 +504,7 @@ public class Ejb3JoinColumn extends Ejb3Column {\n getMappingColumn().isNullable(),\n column.getSqlType(),\n getMappingColumn().isUnique(),\n+ null, // default-value\n false //We do copy no strategy here\n );\n linkWithValue( value );\n</code></pre>\n\n<p>Well, this is a hibernate-only solution.</p>\n"
},
{
"answer_id": 8750327,
"author": "Tong",
"author_id": 1133136,
"author_profile": "https://Stackoverflow.com/users/1133136",
"pm_score": 3,
"selected": false,
"text": "<p>I use <code>columnDefinition</code> and it works very good</p>\n\n<pre><code>@Column(columnDefinition=\"TIMESTAMP DEFAULT CURRENT_TIMESTAMP\")\n\nprivate Date createdDate;\n</code></pre>\n"
},
{
"answer_id": 9191447,
"author": "Gal Bracha",
"author_id": 395804,
"author_profile": "https://Stackoverflow.com/users/395804",
"pm_score": 2,
"selected": false,
"text": "<p>If you're using a double, you can use the following:</p>\n\n<pre><code>@Column(columnDefinition=\"double precision default '96'\")\n\nprivate Double grolsh;\n</code></pre>\n\n<p>Yes it's db specific.</p>\n"
},
{
"answer_id": 13432234,
"author": "Husin Wijaya",
"author_id": 637042,
"author_profile": "https://Stackoverflow.com/users/637042",
"pm_score": 7,
"selected": false,
"text": "<p>another approach is using javax.persistence.PrePersist</p>\n\n<pre><code>@PrePersist\nvoid preInsert() {\n if (this.createdTime == null)\n this.createdTime = new Date();\n}\n</code></pre>\n"
},
{
"answer_id": 35761040,
"author": "Dave Anderson",
"author_id": 6010634,
"author_profile": "https://Stackoverflow.com/users/6010634",
"pm_score": 1,
"selected": false,
"text": "<p>You can define the default value in the database designer, or when you create the table. For instance in SQL Server you can set the default vault of a Date field to (<code>getDate()</code>). Use <code>insertable=false</code> as mentioned in your column definition. JPA will not specify that column on inserts and the database will generate the value for you.</p>\n"
},
{
"answer_id": 36423172,
"author": "Thomas Zhang",
"author_id": 4250694,
"author_profile": "https://Stackoverflow.com/users/4250694",
"pm_score": 3,
"selected": false,
"text": "<p>you can use the java reflect api:</p>\n\n<pre><code> @PrePersist\n void preInsert() {\n PrePersistUtil.pre(this);\n }\n</code></pre>\n\n<p>This is common:</p>\n\n<pre><code> public class PrePersistUtil {\n\n private static SimpleDateFormat sdf = new SimpleDateFormat(\"yyyy-MM-dd\");\n\n\n public static void pre(Object object){\n try {\n Field[] fields = object.getClass().getDeclaredFields();\n for(Field field : fields){\n field.setAccessible(true);\n if (field.getType().getName().equals(\"java.lang.Long\")\n && field.get(object) == null){\n field.set(object,0L);\n }else if (field.getType().getName().equals(\"java.lang.String\")\n && field.get(object) == null){\n field.set(object,\"\");\n }else if (field.getType().getName().equals(\"java.util.Date\")\n && field.get(object) == null){\n field.set(object,sdf.parse(\"1900-01-01\"));\n }else if (field.getType().getName().equals(\"java.lang.Double\")\n && field.get(object) == null){\n field.set(object,0.0d);\n }else if (field.getType().getName().equals(\"java.lang.Integer\")\n && field.get(object) == null){\n field.set(object,0);\n }else if (field.getType().getName().equals(\"java.lang.Float\")\n && field.get(object) == null){\n field.set(object,0.0f);\n }\n }\n } catch (IllegalAccessException e) {\n e.printStackTrace();\n } catch (ParseException e) {\n e.printStackTrace();\n }\n }\n }\n</code></pre>\n"
},
{
"answer_id": 42150940,
"author": "Ondra Žižka",
"author_id": 145989,
"author_profile": "https://Stackoverflow.com/users/145989",
"pm_score": 6,
"selected": false,
"text": "<p>In 2017, JPA 2.1 still has only <code>@Column(columnDefinition='...')</code> to which you put the literal SQL definition of the column. Which is quite unflexible and forces you to also declare the other aspects like type, short-circuiting the JPA implementation's view on that matter.</p>\n\n<p>Hibernate though, has this:</p>\n\n<pre><code>@Column(length = 4096, nullable = false)\[email protected](\"\")\nprivate String description;\n</code></pre>\n\n<blockquote>\n <p>Identifies the DEFAULT value to apply to the associated column via DDL.</p>\n</blockquote>\n\n<ul>\n<li><a href=\"https://docs.jboss.org/hibernate/orm/4.3/javadocs/org/hibernate/annotations/ColumnDefault.html\" rel=\"noreferrer\">Hibernate 4.3 docs</a> (4.3 to show it's been here for quite some time) </li>\n<li>Hibernate manual on <a href=\"https://docs.jboss.org/hibernate/orm/5.2/userguide/html_single/Hibernate_User_Guide.html#schema-generation-column-default-value\" rel=\"noreferrer\">Default value for database column</a></li>\n</ul>\n\n<p>Two notes to that:</p>\n\n<p>1) Don't be afraid of going non-standard. Working as a JBoss developer, I've seen quite some specification processes. The specification is basically the baseline that the big players in given field are willing to commit to support for the next decade or so. It's true for security, for messaging, ORM is no difference (although JPA covers quite a lot). My experience as a developer is that in a complex application, sooner or later you will need a non-standard API anyway. And <code>@ColumnDefault</code> is an example when it outweigts the negatives of using a non-standard solution.</p>\n\n<p>2) It's nice how everyone waves @PrePersist or constructor member initialization. But that's NOT the same. How about bulk SQL updates? How about statements that don't set the column? <code>DEFAULT</code> has it's role and that's not substitutable by initializing a Java class member. </p>\n"
},
{
"answer_id": 44791049,
"author": "Appesh",
"author_id": 2244734,
"author_profile": "https://Stackoverflow.com/users/2244734",
"pm_score": 3,
"selected": false,
"text": "<ol>\n<li><code>@Column(columnDefinition='...')</code> doesn't work when you set the default constraint in database while inserting the data.</li>\n<li>You need to make <code>insertable = false</code> and remove <code>columnDefinition='...'</code> from annotation, then database will automatically insert the default value from the database.</li>\n<li>E.g. when you set varchar gender is male by default in database.</li>\n<li>You just need to add <code>insertable = false</code> in Hibernate/JPA, it will work.</li>\n</ol>\n"
},
{
"answer_id": 46688515,
"author": "Mohammed Rafeeq",
"author_id": 1752917,
"author_profile": "https://Stackoverflow.com/users/1752917",
"pm_score": 2,
"selected": false,
"text": "<pre><code>@PrePersist\nvoid preInsert() {\n if (this.dateOfConsent == null)\n this.dateOfConsent = LocalDateTime.now();\n if(this.consentExpiry==null)\n this.consentExpiry = this.dateOfConsent.plusMonths(3);\n}\n</code></pre>\n\n<p>In my case due to the field being LocalDateTime i used this, it is recommended due to vendor independence</p>\n"
},
{
"answer_id": 69636978,
"author": "Diego Macario",
"author_id": 2101212,
"author_profile": "https://Stackoverflow.com/users/2101212",
"pm_score": 2,
"selected": false,
"text": "<p>I found another way to resolve the same problem, because when I create my own object and persist in database and didn´t respect the DDL with default value.</p>\n<p>So I looked at my console, and the SQL generated, and saw that insert came with all fields, but only one propertie in my object has the value changed.</p>\n<p>So I put in the model class this annotation.</p>\n<p><code>@DynamicInsert</code></p>\n<p>When is inserting data, the framework not insert null values or values that are not modified, making the insert shorter.</p>\n<p>Also has <code>@DynamicUpdate</code> annotation.</p>\n"
},
{
"answer_id": 69670332,
"author": "Oxnard",
"author_id": 9745488,
"author_profile": "https://Stackoverflow.com/users/9745488",
"pm_score": 0,
"selected": false,
"text": "<p>I tried a couple of JPA/Hiberate ways but none seemed to work well. Since I am using Oracle I create a "before trigger" within the trigger a simple test of null then if null set as needed</p>\n"
},
{
"answer_id": 72163049,
"author": "Akash Verma",
"author_id": 4273204,
"author_profile": "https://Stackoverflow.com/users/4273204",
"pm_score": 0,
"selected": false,
"text": "<pre><code>@ColumnDefault("abcd")\nvar name: String,\n</code></pre>\n<p>There! you have set the default value for column name</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16152/"
] |
Is it possible to set a default value for columns in JPA, and if, how is it done using annotations?
|
Actually it is possible in JPA, although a little bit of a hack using the `columnDefinition` property of the `@Column` annotation, for example:
```java
@Column(name="Price", columnDefinition="Decimal(10,2) default '100.00'")
```
|
197,059 |
<p>What is the most efficient way of turning the list of values of a dictionary into an array?</p>
<p>For example, if I have a <code>Dictionary</code> where <code>Key</code> is <code>String</code> and <code>Value</code> is <code>Foo</code>, I want to get <code>Foo[]</code></p>
<p>I am using VS 2005, C# 2.0</p>
|
[
{
"answer_id": 197062,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 8,
"selected": true,
"text": "<pre><code>// dict is Dictionary<string, Foo>\n\nFoo[] foos = new Foo[dict.Count];\ndict.Values.CopyTo(foos, 0);\n\n// or in C# 3.0:\nvar foos = dict.Values.ToArray();\n</code></pre>\n"
},
{
"answer_id": 197071,
"author": "Grzenio",
"author_id": 5363,
"author_profile": "https://Stackoverflow.com/users/5363",
"pm_score": 3,
"selected": false,
"text": "<p>There is a ToArray() function on Values:</p>\n\n<pre><code>Foo[] arr = new Foo[dict.Count]; \ndict.Values.CopyTo(arr, 0);\n</code></pre>\n\n<p>But I don't think its efficient (I haven't really tried, but I guess it copies all these values to the array). Do you really need an Array? If not, I would try to pass IEnumerable:</p>\n\n<pre><code>IEnumerable<Foo> foos = dict.Values;\n</code></pre>\n"
},
{
"answer_id": 9928420,
"author": "Steztric",
"author_id": 1069178,
"author_profile": "https://Stackoverflow.com/users/1069178",
"pm_score": 4,
"selected": false,
"text": "<p>Store it in a list. It is easier;</p>\n\n<pre><code>List<Foo> arr = new List<Foo>(dict.Values);\n</code></pre>\n\n<p>Of course if you specifically want it in an array;</p>\n\n<pre><code>Foo[] arr = (new List<Foo>(dict.Values)).ToArray();\n</code></pre>\n"
},
{
"answer_id": 15003916,
"author": "Piotr Czyż",
"author_id": 851516,
"author_profile": "https://Stackoverflow.com/users/851516",
"pm_score": 3,
"selected": false,
"text": "<p>If you would like to use linq, so you can try following:</p>\n\n<pre><code>Dictionary<string, object> dict = new Dictionary<string, object>();\nvar arr = dict.Select(z => z.Value).ToArray();\n</code></pre>\n\n<p>I don't know which one is faster or better. Both work for me.</p>\n"
},
{
"answer_id": 50420276,
"author": "Lior Kirshner",
"author_id": 8960627,
"author_profile": "https://Stackoverflow.com/users/8960627",
"pm_score": 2,
"selected": false,
"text": "<p>These days, once you have LINQ available, you can convert the dictionary keys and their values to a single string. </p>\n\n<p>You can use the following code:</p>\n\n<pre><code>// convert the dictionary to an array of strings\nstring[] strArray = dict.Select(x => (\"Key: \" + x.Key + \", Value: \" + x.Value)).ToArray();\n\n// convert a string array to a single string\nstring result = String.Join(\", \", strArray);\n</code></pre>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197059",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4653/"
] |
What is the most efficient way of turning the list of values of a dictionary into an array?
For example, if I have a `Dictionary` where `Key` is `String` and `Value` is `Foo`, I want to get `Foo[]`
I am using VS 2005, C# 2.0
|
```
// dict is Dictionary<string, Foo>
Foo[] foos = new Foo[dict.Count];
dict.Values.CopyTo(foos, 0);
// or in C# 3.0:
var foos = dict.Values.ToArray();
```
|
197,070 |
<p>Could you provide an example of accessing the Eclipse Abstract Syntax Tree programmatically for a given piece of code?</p>
<p>eg getting the AST for:</p>
<hr>
<h2>Class1.java</h2>
<pre><code>package parseable;
public class Class1 {
/**
* @param args
*/
public static void main(String[] args) {
System.out.println("Hello world!");
}
</code></pre>
<p>}</p>
|
[
{
"answer_id": 197079,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 3,
"selected": true,
"text": "<p>It is not an <em>exact</em> answer, that may give you a place where to start:</p>\n\n<p>As said in this <a href=\"https://stackoverflow.com/questions/160382/extract-all-string-from-a-java-project#161145\">question</a>, </p>\n\n<p>A full example is available in this <a href=\"http://www.eclipse.org/articles/article.php?file=Article-JavaCodeManipulation_AST/index.html\" rel=\"nofollow noreferrer\">eclipse corner article</a>, also more details in the <a href=\"http://help.eclipse.org/help33/index.jsp?topic=/org.eclipse.jdt.doc.isv/reference/api/org/eclipse/jdt/core/dom/ASTParser.html\" rel=\"nofollow noreferrer\">eclipse help</a>. And in the slide 59 of <a href=\"http://www1.cs.columbia.edu/~aho/cs4117/lectures/Static%20Analysis%20for%20Java%20in%20Eclipse.pdf\" rel=\"nofollow noreferrer\">this presentation</a>, you see how to apply a change to your source code.</p>\n"
},
{
"answer_id": 6565258,
"author": "johncip",
"author_id": 353434,
"author_profile": "https://Stackoverflow.com/users/353434",
"pm_score": 1,
"selected": false,
"text": "<pre><code>// get an ICompilationUnit by some means\n// you might drill down from an IJavaProject, for instance \nICompilationUnit iunit = ...\n\n// create a new parser for the latest Java Language Spec\nASTParser parser = ASTParser.newParser(AST.JLS3);\n\n// tell the parser you are going to pass it some code where the type level is a source file\n// you might also just want to parse a block, or a method (\"class body declaration\"), etc\nparser.setKind(ASTParser.K_COMPILATION_UNIT);\n\n// set the source to be parsed to the ICompilationUnit\n// we could also use a character array\nparser.setSource(iunit);\n\n// parse it.\n// the output will be a CompilationUnit (also an ASTNode)\n// the null is because we're not using a progress monitor\nCompilationUnit unit = (CompilationUnit) parser.createAST(null);\n</code></pre>\n\n<p>Don't be confused by the ICompilationUnit vs CompilationUnit distinction, which seems to be just the result of uncreative naming on their part. CompilationUnit is a type of ASTNode. ICompilationUnit in this context resembles a file handle. For more info on the distinction, see here: <a href=\"http://wiki.eclipse.org/FAQ_How_do_I_manipulate_Java_code%3F\" rel=\"nofollow\">http://wiki.eclipse.org/FAQ_How_do_I_manipulate_Java_code%3F</a></p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197070",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15441/"
] |
Could you provide an example of accessing the Eclipse Abstract Syntax Tree programmatically for a given piece of code?
eg getting the AST for:
---
Class1.java
-----------
```
package parseable;
public class Class1 {
/**
* @param args
*/
public static void main(String[] args) {
System.out.println("Hello world!");
}
```
}
|
It is not an *exact* answer, that may give you a place where to start:
As said in this [question](https://stackoverflow.com/questions/160382/extract-all-string-from-a-java-project#161145),
A full example is available in this [eclipse corner article](http://www.eclipse.org/articles/article.php?file=Article-JavaCodeManipulation_AST/index.html), also more details in the [eclipse help](http://help.eclipse.org/help33/index.jsp?topic=/org.eclipse.jdt.doc.isv/reference/api/org/eclipse/jdt/core/dom/ASTParser.html). And in the slide 59 of [this presentation](http://www1.cs.columbia.edu/~aho/cs4117/lectures/Static%20Analysis%20for%20Java%20in%20Eclipse.pdf), you see how to apply a change to your source code.
|
197,081 |
<p>How can I do the Ruby method <a href="http://www.ruby-doc.org/core/classes/Array.html#M002241" rel="noreferrer">"Flatten" Ruby Method</a> in C#. This method flattens a jagged array into a single-dimensional array.</p>
<p>For example:</p>
<pre><code>s = [ 1, 2, 3 ] #=> [1, 2, 3]
t = [ 4, 5, 6, [7, 8] ] #=> [4, 5, 6, [7, 8]]
a = [ s, t, 9, 10 ] #=> [[1, 2, 3], [4, 5, 6, [7, 8]], 9, 10]
a.flatten #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10
</code></pre>
|
[
{
"answer_id": 197087,
"author": "Alexander Kojevnikov",
"author_id": 712,
"author_profile": "https://Stackoverflow.com/users/712",
"pm_score": 5,
"selected": true,
"text": "<p>Recursive solution:</p>\n\n<pre><code>IEnumerable Flatten(IEnumerable array)\n{\n foreach(var item in array)\n {\n if(item is IEnumerable)\n {\n foreach(var subitem in Flatten((IEnumerable)item))\n {\n yield return subitem;\n }\n }\n else\n {\n yield return item;\n }\n }\n}\n</code></pre>\n\n<p>EDIT 1:</p>\n\n<p><a href=\"https://stackoverflow.com/users/22656/jon-skeet\">Jon</a> explains in the comments why it cannot be a generic method, take a look!</p>\n\n<p>EDIT 2:</p>\n\n<p><a href=\"https://stackoverflow.com/users/615/matt-hamilton\">Matt</a> suggested making it an extension method. Here you go, just replace the first line with:</p>\n\n<pre><code>public static IEnumerable Flatten(this IEnumerable array)\n</code></pre>\n\n<p>and you can use it like this:</p>\n\n<pre><code>foreach(var item in myArray.Flatten()) { ... }\n</code></pre>\n"
},
{
"answer_id": 200144,
"author": "Matt",
"author_id": 2338,
"author_profile": "https://Stackoverflow.com/users/2338",
"pm_score": 2,
"selected": false,
"text": "<p>I would have responded in a comment, but I need more than 300 characters.</p>\n\n<p>@Alexander's solution is awesome, but it runs into a problem with arrays of strings. Since string implements IEnumerable, I think it will end up returning each character in every string. You can use a generic parameter to tell it what kind of thing you are hoping to have returned in these cases, e.g.:</p>\n\n<pre><code>public static IEnumerable Flatten<T>(IEnumerable e)\n{\n if (e == null) yield break;\n foreach (var item in e)\n {\n if (item is T)\n yield return (T)item;\n else if (item is IEnumerable)\n {\n foreach (var subitem in Flatten<T>((IEnumerable)item))\n yield return subitem;\n }\n else\n yield return item;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 2194616,
"author": "ravinggenius",
"author_id": 265558,
"author_profile": "https://Stackoverflow.com/users/265558",
"pm_score": 2,
"selected": false,
"text": "<p>Couldn't you just use IEnumerable#SelectMany?</p>\n"
},
{
"answer_id": 70032423,
"author": "had",
"author_id": 1326212,
"author_profile": "https://Stackoverflow.com/users/1326212",
"pm_score": 0,
"selected": false,
"text": "<p>I would also agree that SelectMany does this.</p>\n<pre><code>var s = new[] { 1, 2, 3 };\nvar t = new[] { 4, 5, 6 };\nvar a = new[] { s, t, new[] {7, 8} };\n\na.SelectMany(e => e); \n// IEnumerable<int> {1,2,3,4,5,6,7,8}\n</code></pre>\n<p>I normalized the array. s and t are arrays of int.\na is an array of arrays.\nYou don't have mixed arrays with int and arrays, like you can do in ruby.</p>\n<p>But vice-versa.\nflatten is the ruby equivalent I was looking for SelectMany in C#</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4455/"
] |
How can I do the Ruby method ["Flatten" Ruby Method](http://www.ruby-doc.org/core/classes/Array.html#M002241) in C#. This method flattens a jagged array into a single-dimensional array.
For example:
```
s = [ 1, 2, 3 ] #=> [1, 2, 3]
t = [ 4, 5, 6, [7, 8] ] #=> [4, 5, 6, [7, 8]]
a = [ s, t, 9, 10 ] #=> [[1, 2, 3], [4, 5, 6, [7, 8]], 9, 10]
a.flatten #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10
```
|
Recursive solution:
```
IEnumerable Flatten(IEnumerable array)
{
foreach(var item in array)
{
if(item is IEnumerable)
{
foreach(var subitem in Flatten((IEnumerable)item))
{
yield return subitem;
}
}
else
{
yield return item;
}
}
}
```
EDIT 1:
[Jon](https://stackoverflow.com/users/22656/jon-skeet) explains in the comments why it cannot be a generic method, take a look!
EDIT 2:
[Matt](https://stackoverflow.com/users/615/matt-hamilton) suggested making it an extension method. Here you go, just replace the first line with:
```
public static IEnumerable Flatten(this IEnumerable array)
```
and you can use it like this:
```
foreach(var item in myArray.Flatten()) { ... }
```
|
197,088 |
<p>In WPF, there are two ways to set the focus to an element.<br>
You can either call the .Focus() method of the input element, or call Keyboard.Focus() with the input element as parameter.</p>
<pre><code>// first way:
item.Focus();
// alternate way:
Keyboard.Focus(item);
</code></pre>
<p>What is the difference between these two? Are there special reasons to use one of them instead of the other in some cases?<br>
So far I noticed no difference - what ever method I used, the item always got logical focus as well as keyboard focus.</p>
|
[
{
"answer_id": 197100,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 3,
"selected": false,
"text": "<p>As per <a href=\"http://msdn.microsoft.com/en-us/library/aa969768.aspx\" rel=\"noreferrer\">WPF documentation on MSDN</a>:</p>\n\n<blockquote>\n <p>In WPF there are two main concepts that pertain to focus: keyboard focus and logical focus. Keyboard focus refers to the element that receives keyboard input and logical focus refers to the element in a focus scope that has focus.</p>\n</blockquote>\n\n<p>and</p>\n\n<blockquote>\n <p>An element that has keyboard focus will also have logical focus, but an element that has logical focus does not necessarily have keyboard focus.</p>\n</blockquote>\n"
},
{
"answer_id": 197309,
"author": "decasteljau",
"author_id": 12082,
"author_profile": "https://Stackoverflow.com/users/12082",
"pm_score": 0,
"selected": false,
"text": "<p>Also, you may want to know that item.Focus() is the equivalent of calling:</p>\n\n<pre><code>DependencyObject focusScope = FocusManager.GetFocusScope(item);\nif (FocusManager.GetFocusedElement(focusScope) == null)\n{\n FocusManager.SetFocusedElement(focusScope, item);\n}\n</code></pre>\n"
},
{
"answer_id": 197582,
"author": "Joel B Fant",
"author_id": 22211,
"author_profile": "https://Stackoverflow.com/users/22211",
"pm_score": 6,
"selected": true,
"text": "<p>One of the first things that <code>item.Focus()</code> does is call <code>Keyboard.Focus( this )</code>. If that fails, then it makes calls to <code>FocusManager</code>, as decasteljau has answered.</p>\n\n<p>The following are copied from disassambler view in <a href=\"http://reflector.red-gate.com/\" rel=\"noreferrer\">Reflector</a>.</p>\n\n<p>This is from <code>UIElement</code> (<code>UIElement3D</code> is the same):</p>\n\n<pre><code>public bool Focus()\n{\n if (Keyboard.Focus(this) == this)\n {\n return true;\n }\n if (this.Focusable && this.IsEnabled)\n {\n DependencyObject focusScope = FocusManager.GetFocusScope(this);\n if (FocusManager.GetFocusedElement(focusScope) == null)\n {\n FocusManager.SetFocusedElement(focusScope, this);\n }\n }\n return false;\n}\n</code></pre>\n\n<p>This is from <code>ContentElement</code>:</p>\n\n<pre><code>public bool Focus()\n{\n return (Keyboard.Focus(this) == this);\n}\n</code></pre>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7021/"
] |
In WPF, there are two ways to set the focus to an element.
You can either call the .Focus() method of the input element, or call Keyboard.Focus() with the input element as parameter.
```
// first way:
item.Focus();
// alternate way:
Keyboard.Focus(item);
```
What is the difference between these two? Are there special reasons to use one of them instead of the other in some cases?
So far I noticed no difference - what ever method I used, the item always got logical focus as well as keyboard focus.
|
One of the first things that `item.Focus()` does is call `Keyboard.Focus( this )`. If that fails, then it makes calls to `FocusManager`, as decasteljau has answered.
The following are copied from disassambler view in [Reflector](http://reflector.red-gate.com/).
This is from `UIElement` (`UIElement3D` is the same):
```
public bool Focus()
{
if (Keyboard.Focus(this) == this)
{
return true;
}
if (this.Focusable && this.IsEnabled)
{
DependencyObject focusScope = FocusManager.GetFocusScope(this);
if (FocusManager.GetFocusedElement(focusScope) == null)
{
FocusManager.SetFocusedElement(focusScope, this);
}
}
return false;
}
```
This is from `ContentElement`:
```
public bool Focus()
{
return (Keyboard.Focus(this) == this);
}
```
|
197,095 |
<p>The following code has a simple binding which binds the Text of the TextBlock named MyTextBlock to TextBox's Text and ToolTip property using the exact same Binding notation:</p>
<pre><code><StackPanel>
<TextBlock x:Name="MyTextBlock">Foo Bar</TextBlock>
<TextBox Text="{Binding ElementName=MyTextBlock, Path=Text, StringFormat='It is: \{0\}'}"
ToolTip="{Binding ElementName=MyTextBlock, Path=Text, StringFormat='It is: \{0\}'}" />
</StackPanel>
</code></pre>
<p>The binding also uses the <a href="http://blogs.msdn.com/llobo/archive/2008/05/19/wpf-3-5-sp1-feature-stringformat.aspx" rel="noreferrer">StringFormat property introduced with .NET 3.5 SP1</a> which is working fine for the above Text property but seems to be broken for the ToolTip. The expected result is "It is: Foo Bar" but when you hover over the TextBox, the ToolTip shows only the binding value, not the string formatted value. Any ideas?</p>
|
[
{
"answer_id": 197130,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 7,
"selected": false,
"text": "<p>ToolTips in WPF can contain anything, not just text, so they provide a ContentStringFormat property for the times you just want text. You'll need to use the expanded syntax as far as I know:</p>\n\n<pre><code><TextBox ...>\n <TextBox.ToolTip>\n <ToolTip \n Content=\"{Binding ElementName=myTextBlock,Path=Text}\"\n ContentStringFormat=\"{}It is: {0}\"\n />\n </TextBox.ToolTip>\n</TextBox>\n</code></pre>\n\n<p>I'm not 100% sure about the validity of binding using the ElementName syntax from a nested property like that, but the ContentStringFormat property is what you're looking for.</p>\n"
},
{
"answer_id": 197370,
"author": "huseyint",
"author_id": 39,
"author_profile": "https://Stackoverflow.com/users/39",
"pm_score": -1,
"selected": true,
"text": "<p>The following is a wordy solution but it works. </p>\n\n<pre><code><StackPanel>\n <TextBox Text=\"{Binding Path=., StringFormat='The answer is: {0}'}\">\n <TextBox.DataContext>\n <sys:Int32>42</sys:Int32>\n </TextBox.DataContext>\n <TextBox.ToolTip>\n <ToolTip Content=\"{Binding}\" ContentStringFormat=\"{}The answer is: {0}\" />\n </TextBox.ToolTip>\n </TextBox>\n</StackPanel>\n</code></pre>\n\n<p>I would prefer a much simpler syntax, something like the one in my original question.</p>\n"
},
{
"answer_id": 14034294,
"author": "Athari",
"author_id": 293099,
"author_profile": "https://Stackoverflow.com/users/293099",
"pm_score": 2,
"selected": false,
"text": "<p>Your code can be as short as this:</p>\n\n<pre><code><TextBlock ToolTip=\"{Binding PrideLands.YearsTillSimbaReturns,\n Converter={StaticResource convStringFormat},\n ConverterParameter='Rejoice! Just {0} years left!'}\" Text=\"Hakuna Matata\"/>\n</code></pre>\n\n<p>We'll use the fact Converters are never ignored, unlike StringFormat.</p>\n\n<p>Put this into <strong>StringFormatConverter.cs</strong>:</p>\n\n<pre><code>using System;\nusing System.Globalization;\nusing System.Windows;\nusing System.Windows.Data;\n\nnamespace TLKiaWOL\n{\n [ValueConversion (typeof(object), typeof(string))]\n public class StringFormatConverter : IValueConverter\n {\n public object Convert (object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (ReferenceEquals(value, DependencyProperty.UnsetValue))\n return DependencyProperty.UnsetValue;\n return string.Format(culture, (string)parameter, value);\n }\n\n public object ConvertBack (object value, Type targetType, object parameter, CultureInfo culture)\n {\n throw new NotSupportedException();\n }\n }\n}\n</code></pre>\n\n<p>Put this into your <strong>ResourceDictionary.xaml</strong>:</p>\n\n<pre><code><conv:StringFormatConverter x:Key=\"convStringFormat\"/>\n</code></pre>\n"
},
{
"answer_id": 21096381,
"author": "Lucas Locatelli",
"author_id": 1575144,
"author_profile": "https://Stackoverflow.com/users/1575144",
"pm_score": 3,
"selected": false,
"text": "<p>As Matt said ToolTip can contain anything inside so for your you could bind a TextBox.Text inside your ToolTip.</p>\n\n<pre><code><StackPanel>\n <TextBlock x:Name=\"MyTextBlock\">Foo Bar</TextBlock>\n <TextBox Text=\"{Binding ElementName=MyTextBlock, Path=Text, StringFormat='It is: \\{0\\}'}\">\n <TextBox.ToolTip>\n <TextBlock>\n <TextBlock.Text>\n <Binding ElementName=MyTextBlock Path=\"Text\" StringFormat=\"It is: {0}\" />\n </TextBlock.Text>\n </TextBlock>\n </TextBox.ToolTip>\n </TextBox>\n</StackPanel>\n</code></pre>\n\n<p>Even you can Stack a grid inside the ToolTip and layout your text if you want.</p>\n"
},
{
"answer_id": 25055900,
"author": "MuiBienCarlota",
"author_id": 231977,
"author_profile": "https://Stackoverflow.com/users/231977",
"pm_score": 5,
"selected": false,
"text": "<p>It could be a bug.\nWhen you use short syntax for tooltip:</p>\n<pre><code><TextBox ToolTip="{Binding WhatEverYouWant StringFormat='It is: \\{0\\}'}" />\n</code></pre>\n<p>StringFormat is ignore but when you use expanded syntax:</p>\n<pre><code><TextBox Text="text">\n <TextBox.ToolTip>\n <TextBlock Text="{Binding WhatEverYouWant StringFormat='It is: \\{0\\}'}"/>\n </TextBox.ToolTip>\n</TextBox>\n</code></pre>\n<p>It works as expected.</p>\n"
},
{
"answer_id": 48195359,
"author": "Сергей Игнахин",
"author_id": 9200565,
"author_profile": "https://Stackoverflow.com/users/9200565",
"pm_score": 0,
"selected": false,
"text": "<p>In this situation, you can use relative binding:</p>\n\n<pre><code><StackPanel>\n <TextBlock x:Name=\"MyTextBlock\">Foo Bar</TextBlock>\n <TextBox Text=\"{Binding ElementName=MyTextBlock, Path=Text, StringFormat='It is: \\{0\\}'}\"\n ToolTip=\"{Binding Text, RelativeSource={RelativeSource Self}}\" />\n</StackPanel>\n</code></pre>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197095",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39/"
] |
The following code has a simple binding which binds the Text of the TextBlock named MyTextBlock to TextBox's Text and ToolTip property using the exact same Binding notation:
```
<StackPanel>
<TextBlock x:Name="MyTextBlock">Foo Bar</TextBlock>
<TextBox Text="{Binding ElementName=MyTextBlock, Path=Text, StringFormat='It is: \{0\}'}"
ToolTip="{Binding ElementName=MyTextBlock, Path=Text, StringFormat='It is: \{0\}'}" />
</StackPanel>
```
The binding also uses the [StringFormat property introduced with .NET 3.5 SP1](http://blogs.msdn.com/llobo/archive/2008/05/19/wpf-3-5-sp1-feature-stringformat.aspx) which is working fine for the above Text property but seems to be broken for the ToolTip. The expected result is "It is: Foo Bar" but when you hover over the TextBox, the ToolTip shows only the binding value, not the string formatted value. Any ideas?
|
The following is a wordy solution but it works.
```
<StackPanel>
<TextBox Text="{Binding Path=., StringFormat='The answer is: {0}'}">
<TextBox.DataContext>
<sys:Int32>42</sys:Int32>
</TextBox.DataContext>
<TextBox.ToolTip>
<ToolTip Content="{Binding}" ContentStringFormat="{}The answer is: {0}" />
</TextBox.ToolTip>
</TextBox>
</StackPanel>
```
I would prefer a much simpler syntax, something like the one in my original question.
|
197,096 |
<p>In a SQL-database I make some selects, that get an duration (as result of a subtraction between two dates) in seconds as an int. But I want to format this result in a human-readable form like 'hh:mm' or 'dd:hh'. Is that possible in SQL and how can I realize this?</p>
|
[
{
"answer_id": 197138,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": true,
"text": "<p>In SQL 2005, You can use the following:</p>\n\n<pre><code> select convert(varchar(8), dateadd(second, [SecondsColumn], 0), 108)\n</code></pre>\n\n<p>Which first converts the seconds into a date after 1900-01-01, and then gets the hh:mm:ss part. </p>\n\n<p>If the column is more than 24 hours, this will roll over, if you want days and then hours in that case just do something like:</p>\n\n<pre><code>case when SecondsColumn> (24*60*60) \n then \n cast(datepart(day,datediff(dd, 0, dateadd(second, SecondsColumn, 0))) as varchar(4))\n + 'd' + convert(varchar(2), dateadd(second, SecondsColumn, 0), 108) \n else\n convert(varchar(8), dateadd(second, SecondsColumn, 0), 108) \n end\n</code></pre>\n"
},
{
"answer_id": 197143,
"author": "Adam Pierce",
"author_id": 5324,
"author_profile": "https://Stackoverflow.com/users/5324",
"pm_score": 2,
"selected": false,
"text": "<p>Every database does it differently. I use PostgreSQL and it does it like so:</p>\n\n<pre><code>select to_char(my_date - my_other_date, 'HH:MM:SS');\n</code></pre>\n\n<p>You'll have to consult the manual for the database you are using.</p>\n"
},
{
"answer_id": 197151,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 2,
"selected": false,
"text": "<p>Assuming you have seconds:</p>\n\n<pre><code>DECLARE @DurationSeconds INT\n\n-- 25h 45m 14s\nSET @DurationSeconds = (25 * 3600) + (45 * 60) + (14)\n\nSELECT \n @DurationSeconds, \n @DurationSeconds / 3600 hours, \n @DurationSeconds % 3600 / 60 minutes,\n @DurationSeconds % (3600 / 60) seconds\n</code></pre>\n\n<p>I'll let the task of formatting that nicely to you. :-)</p>\n"
},
{
"answer_id": 197540,
"author": "bobince",
"author_id": 18936,
"author_profile": "https://Stackoverflow.com/users/18936",
"pm_score": 0,
"selected": false,
"text": "<p>There is no standard, though many DBMSs have their own custom syntax.</p>\n\n<p>In general it is better to be doing formatting-for-human-readability work in your application's presentation layer rather than anywhere near the database.</p>\n"
},
{
"answer_id": 9185734,
"author": "grokster",
"author_id": 502441,
"author_profile": "https://Stackoverflow.com/users/502441",
"pm_score": 0,
"selected": false,
"text": "<p>In Oracle SQL:</p>\n\n<pre><code> -- 86,400 seconds in a day\n -- 3,600 seconds in an hour\n -- 60 seconds in a minute\n select duration, -- seconds\n trunc((duration)/86400) || ':' || -- dd\n trunc(mod(duration,86400)/3600) || ':' || -- hh\n trunc(mod(mod(duration,86400),3600)/60) || ':' || -- mm\n mod(mod(mod(duration,86400),3600),60) -- ss\n as human_readable\n from dual\n ;\n</code></pre>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21005/"
] |
In a SQL-database I make some selects, that get an duration (as result of a subtraction between two dates) in seconds as an int. But I want to format this result in a human-readable form like 'hh:mm' or 'dd:hh'. Is that possible in SQL and how can I realize this?
|
In SQL 2005, You can use the following:
```
select convert(varchar(8), dateadd(second, [SecondsColumn], 0), 108)
```
Which first converts the seconds into a date after 1900-01-01, and then gets the hh:mm:ss part.
If the column is more than 24 hours, this will roll over, if you want days and then hours in that case just do something like:
```
case when SecondsColumn> (24*60*60)
then
cast(datepart(day,datediff(dd, 0, dateadd(second, SecondsColumn, 0))) as varchar(4))
+ 'd' + convert(varchar(2), dateadd(second, SecondsColumn, 0), 108)
else
convert(varchar(8), dateadd(second, SecondsColumn, 0), 108)
end
```
|
197,097 |
<p>I'm having a bit of trouble with the UTL_MAIL package in Oracle 10g, and was wondering if anyone had any solutions?</p>
<p>I connect to my DB as SYSMAN and load the following two scripts;</p>
<p><strong>@C:\oracle\product\10.2.0\db_1\rdbms\admin\utlmail.sql</strong></p>
<p><strong>@C:\oracle\product\10.2.0\db_1\rdbms\admin\prvtmail.plb</strong></p>
<p>I set up the SMTP server;</p>
<p><strong>ALTER SYSTEM SET smtp_out_server='mymailserver.fake:25' SCOPE=BOTH;</strong></p>
<p>I grant the user the required permission;</p>
<p><strong>GRANT execute ON utl_mail TO MYUSER;</strong></p>
<p>But then if I connect to the "MYTABLESPACE" (where MYUSER exists), I get the following error if I make reference to UTL_MAIL.SEND;</p>
<p><strong>PLS-00201: identifier 'UTL_MAIL.SEND' must be declared</strong></p>
<p>If I prefix it with SYSMAN though (SYSMAN.UTL_MAIL.SEND), it works, but I don't want to do this as this procedure that contains this call has no knowledge of the tablespace which installed the scripts.</p>
<p>Is there a way to install these scripts so that they are accessible universally, and do not require the SYSMAN prefix to execute?</p>
<p>Cheers,</p>
<p>Chris</p>
|
[
{
"answer_id": 197103,
"author": "cagcowboy",
"author_id": 19629,
"author_profile": "https://Stackoverflow.com/users/19629",
"pm_score": 2,
"selected": false,
"text": "<p>Sounds like you need to create a PUBLIC SYNONYM for the package..</p>\n\n<pre><code>CREATE PUBLIC SYNONYM UTL_MAIL FOR SYSMAN.UTL_MAIL;\n</code></pre>\n"
},
{
"answer_id": 197197,
"author": "cagcowboy",
"author_id": 19629,
"author_profile": "https://Stackoverflow.com/users/19629",
"pm_score": 4,
"selected": true,
"text": "<p>I'm pretty sure that public synonyms will be the only difference.</p>\n\n<pre><code>SELECT * FROM ALL_SYNONYMS WHERE OWNER = 'PUBLIC' and table_name LIKE 'UTL%'\n</code></pre>\n\n<p>will confirm or deny</p>\n"
},
{
"answer_id": 1495864,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>logon as sys and run the scripts</p>\n"
},
{
"answer_id": 1728408,
"author": "KkK",
"author_id": 210337,
"author_profile": "https://Stackoverflow.com/users/210337",
"pm_score": 1,
"selected": false,
"text": "<p>try <code>ALTER SYSTEM SET smtp_out_server='mymailserver.fake:25' SCOPE=BOTH;</code> as the user you are running the procedure not as sys. </p>\n\n<p>ie. \nconnect to <code>MYTABLESPACE as MYUSER</code> and run the alter session \nHope am clear </p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197097",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5827/"
] |
I'm having a bit of trouble with the UTL\_MAIL package in Oracle 10g, and was wondering if anyone had any solutions?
I connect to my DB as SYSMAN and load the following two scripts;
**@C:\oracle\product\10.2.0\db\_1\rdbms\admin\utlmail.sql**
**@C:\oracle\product\10.2.0\db\_1\rdbms\admin\prvtmail.plb**
I set up the SMTP server;
**ALTER SYSTEM SET smtp\_out\_server='mymailserver.fake:25' SCOPE=BOTH;**
I grant the user the required permission;
**GRANT execute ON utl\_mail TO MYUSER;**
But then if I connect to the "MYTABLESPACE" (where MYUSER exists), I get the following error if I make reference to UTL\_MAIL.SEND;
**PLS-00201: identifier 'UTL\_MAIL.SEND' must be declared**
If I prefix it with SYSMAN though (SYSMAN.UTL\_MAIL.SEND), it works, but I don't want to do this as this procedure that contains this call has no knowledge of the tablespace which installed the scripts.
Is there a way to install these scripts so that they are accessible universally, and do not require the SYSMAN prefix to execute?
Cheers,
Chris
|
I'm pretty sure that public synonyms will be the only difference.
```
SELECT * FROM ALL_SYNONYMS WHERE OWNER = 'PUBLIC' and table_name LIKE 'UTL%'
```
will confirm or deny
|
197,099 |
<p>I'm trying to select data from a table defined similar to the following :</p>
<pre><code>Column | Data Type
-------------------------
Id | Int
DataType | Int
LoggedData | XML
</code></pre>
<p>but I only want to select those rows with a specific DataType value, and that contain a string (or evaluates a piece of XPath) in the LoggedData column.</p>
<p>A quick Google search turned up nothing useful, and I am in a bit of a rush to get an answer... I'll carry on searching, but if anyone can help me out on this in the mean time, I'd really appreciate it.</p>
<p><strong>EDIT</strong> _ Clarification</p>
<p>So, what I'm after is something like this, but in the correct format...</p>
<pre><code>select Id, LoggedData from myTable where DataType = 29 and LoggedData.query('RootNode/ns1:ChildNode[@value="searchterm"]');
</code></pre>
<p>Still might not be clear...</p>
|
[
{
"answer_id": 197106,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 0,
"selected": false,
"text": "<p>Is this not doing the trick for you?</p>\n\n<pre><code>SELECT\n Id, \n LoggedData \nFROM\n myTable \nWHERE\n DataType = 29 \n AND LoggedData.exist('RootNode/ns1:ChildNode[@value=\"searchterm\"]') = 1\n</code></pre>\n"
},
{
"answer_id": 199950,
"author": "leoinfo",
"author_id": 6948,
"author_profile": "https://Stackoverflow.com/users/6948",
"pm_score": 2,
"selected": true,
"text": "<p>If you want to filter by a <em>searchterm</em> (like a SQL variable) you will probably need to use something like this:</p>\n\n<pre><code>Select Id, LoggedData From myTable Where DataType = 29 And \nLoggedData.exist('RootNode/ns1:ChildNode[@value=sql:variable(\"@searchterm\")]')=1\n</code></pre>\n\n<p>where @searchterm is your SQL variable.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197099",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/377/"
] |
I'm trying to select data from a table defined similar to the following :
```
Column | Data Type
-------------------------
Id | Int
DataType | Int
LoggedData | XML
```
but I only want to select those rows with a specific DataType value, and that contain a string (or evaluates a piece of XPath) in the LoggedData column.
A quick Google search turned up nothing useful, and I am in a bit of a rush to get an answer... I'll carry on searching, but if anyone can help me out on this in the mean time, I'd really appreciate it.
**EDIT** \_ Clarification
So, what I'm after is something like this, but in the correct format...
```
select Id, LoggedData from myTable where DataType = 29 and LoggedData.query('RootNode/ns1:ChildNode[@value="searchterm"]');
```
Still might not be clear...
|
If you want to filter by a *searchterm* (like a SQL variable) you will probably need to use something like this:
```
Select Id, LoggedData From myTable Where DataType = 29 And
LoggedData.exist('RootNode/ns1:ChildNode[@value=sql:variable("@searchterm")]')=1
```
where @searchterm is your SQL variable.
|
197,111 |
<p>What is an example of a fast SQL to get duplicates in datasets with hundreds of thousands of records. I typically use something like:</p>
<pre><code>SELECT afield1, afield2 FROM afile a
WHERE 1 < (SELECT count(afield1) FROM afile b WHERE a.afield1 = b.afield1);
</code></pre>
<p>But this is quite slow.</p>
|
[
{
"answer_id": 197114,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 7,
"selected": true,
"text": "<p>This is the more direct way:</p>\n\n<pre><code>select afield1,count(afield1) from atable \ngroup by afield1 having count(afield1) > 1\n</code></pre>\n"
},
{
"answer_id": 197117,
"author": "Tony Andrews",
"author_id": 18747,
"author_profile": "https://Stackoverflow.com/users/18747",
"pm_score": 4,
"selected": false,
"text": "<p>You could try:</p>\n\n<pre><code>select afield1, afield2 from afile a\nwhere afield1 in\n( select afield1\n from afile\n group by afield1\n having count(*) > 1\n);\n</code></pre>\n"
},
{
"answer_id": 197484,
"author": "Walter Mitty",
"author_id": 19937,
"author_profile": "https://Stackoverflow.com/users/19937",
"pm_score": 3,
"selected": false,
"text": "<p>A similar question was asked last week. There are some good answers there.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/182544/sql-to-find-duplicate-entries-within-a-group\">SQL to find duplicate entries (within a group)</a></p>\n\n<p>In that question, the OP was interested in all the columns (fields) in the table (file),\nbut rows belonged in the same group if they had the same key value (afield1).</p>\n\n<p>There are three kinds of answers:</p>\n\n<p>subqueries in the where clause, like some of the other answers in here.</p>\n\n<p>an inner join between the table and the groups viewed as a table (my answer)</p>\n\n<p>and analytic queries (something that's new to me).</p>\n"
},
{
"answer_id": 4753091,
"author": "Magnus Smith",
"author_id": 11461,
"author_profile": "https://Stackoverflow.com/users/11461",
"pm_score": 3,
"selected": false,
"text": "<p>By the way, if anyone wants to remove the duplicates, I have used this:</p>\n\n<pre><code>delete from MyTable where MyTableID in (\n select max(MyTableID)\n from MyTable\n group by Thing1, Thing2, Thing3\n having count(*) > 1\n)\n</code></pre>\n"
},
{
"answer_id": 12048993,
"author": "Simon East",
"author_id": 195835,
"author_profile": "https://Stackoverflow.com/users/195835",
"pm_score": 2,
"selected": false,
"text": "<p>This should be reasonably fast (even faster if the dupeFields are indexed).</p>\n\n<pre><code>SELECT DISTINCT a.id, a.dupeField1, a.dupeField2\nFROM TableX a\nJOIN TableX b\nON a.dupeField1 = b.dupeField2\nAND a.dupeField2 = b.dupeField2\nAND a.id != b.id\n</code></pre>\n\n<p>I guess the only downside to this query is that because you're not doing a <code>COUNT(*)</code> you can't check for the <em>number of times</em> it is duplicated, only that it appears more than once.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197111",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3535708/"
] |
What is an example of a fast SQL to get duplicates in datasets with hundreds of thousands of records. I typically use something like:
```
SELECT afield1, afield2 FROM afile a
WHERE 1 < (SELECT count(afield1) FROM afile b WHERE a.afield1 = b.afield1);
```
But this is quite slow.
|
This is the more direct way:
```
select afield1,count(afield1) from atable
group by afield1 having count(afield1) > 1
```
|
197,112 |
<p>This <a href="http://my.php.net/static" rel="nofollow noreferrer">example</a> is from php.net:</p>
<pre><code><?php
function Test()
{
static $a = 0;
echo $a;
$a++;
}
?>
</code></pre>
<p>And this is my code:</p>
<pre><code>function getNextQuestionID()
{
static $idx = 0;
return $idx++;
}
</code></pre>
<p>And I use it in JavaScript:</p>
<pre><code>'quizID=' + "<?php echo getNextQuestionID(); ?>"
</code></pre>
<p>Returns 0 everytime. Why?</p>
|
[
{
"answer_id": 197126,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": true,
"text": "<p>I believe you misunderstand what static vars do. Try this code and you may understand better:</p>\n\n<pre><code>echo getNextQuestionID() . \", \" getNextQuestionID() . \", \" getNextQuestionID();\n</code></pre>\n\n<p>And you will see what I mean.</p>\n\n<p>The static var only lives as long as the script does.</p>\n\n<p>The reason it is returning 0 on the first run instead of 1 is because you are using the postfix operator $var++ instead of the prefix version - ++$var. The difference is is that the increment only gets applied when using the postfix operator after the function returns - but if you use the prefix operator it is applied before the function returns.</p>\n"
},
{
"answer_id": 197184,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>If you want your data to persist across multiple pages, you need to use <a href=\"http://www.php.net/session\" rel=\"nofollow noreferrer\">sessions</a>.</p>\n"
},
{
"answer_id": 197600,
"author": "Tom Haigh",
"author_id": 22224,
"author_profile": "https://Stackoverflow.com/users/22224",
"pm_score": 0,
"selected": false,
"text": "<pre><code>session_start();\nfunction getNextQuestionID()\n{\n if (!isset($_SESSION['qNo'])) {\n $_SESSION['qNo'] = 0;\n } else {\n $_SESSION['qNo']++;\n }\n\n return $_SESSION['qNo'];\n}\n</code></pre>\n"
},
{
"answer_id": 36086853,
"author": "djot",
"author_id": 1077754,
"author_profile": "https://Stackoverflow.com/users/1077754",
"pm_score": 0,
"selected": false,
"text": "<pre><code>function getNextQuestionID()\n{\n if (!isset($idx)) {\n static $idx = 0; // OR -1, if you want to start with 0 (ZERO);\n }\n $idx++;\n return $idx;\n}\n\necho getNextQuestionID().'<br />';\necho getNextQuestionID().'<br />';\necho getNextQuestionID().'<br />';\necho getNextQuestionID().'<br />';\n</code></pre>\n\n<p>returns 1,2,3,4</p>\n\n<p>\"static\" means, the value of the variable is kept as long as your script is running (one website call! to keep it over several website calls, you'll need SESSIONS). If the function gets called more than once, the value is kept and not re-initialised all the time, and thus, incrementable.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15345/"
] |
This [example](http://my.php.net/static) is from php.net:
```
<?php
function Test()
{
static $a = 0;
echo $a;
$a++;
}
?>
```
And this is my code:
```
function getNextQuestionID()
{
static $idx = 0;
return $idx++;
}
```
And I use it in JavaScript:
```
'quizID=' + "<?php echo getNextQuestionID(); ?>"
```
Returns 0 everytime. Why?
|
I believe you misunderstand what static vars do. Try this code and you may understand better:
```
echo getNextQuestionID() . ", " getNextQuestionID() . ", " getNextQuestionID();
```
And you will see what I mean.
The static var only lives as long as the script does.
The reason it is returning 0 on the first run instead of 1 is because you are using the postfix operator $var++ instead of the prefix version - ++$var. The difference is is that the increment only gets applied when using the postfix operator after the function returns - but if you use the prefix operator it is applied before the function returns.
|
197,121 |
<p>I'm trying to do the following without too much special case code to deal with invalidated POSITIONs etc:</p>
<p>What's the best way to fill in the blanks?</p>
<pre><code>void DeleteUnreferencedRecords(CAtlMap<Record>& records)
{
for(____;____;____)
{
if( NotReferencedElsewhere(record) )
{
// Delete record
_______;
}
}
}
</code></pre>
|
[
{
"answer_id": 197209,
"author": "Rob",
"author_id": 9236,
"author_profile": "https://Stackoverflow.com/users/9236",
"pm_score": 0,
"selected": false,
"text": "<p>My first thoughts would be the save the current POSITION before calling <code>GetNext</code>, then, if you delete the element you can reset it. However, perhaps the safest way would be to create a new map containing the elements you want to keep, else you could be relying on how the internal implementation of POSITION works.</p>\n"
},
{
"answer_id": 198050,
"author": "Head Geek",
"author_id": 12193,
"author_profile": "https://Stackoverflow.com/users/12193",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not too familiar with <code>CAtlMap</code>, but if it's similar to the STL's <code>map</code> type, then <a href=\"https://stackoverflow.com/questions/197121/how-do-i-write-a-for-loop-that-iterates-over-a-catlmap-selectively-deleting-ele#197209\">Rob's \"first thought\"</a> is safe -- deleting an item does not affect any iterators except the one(s) pointing to the item being deleted.</p>\n"
},
{
"answer_id": 198542,
"author": "Lou Franco",
"author_id": 3937,
"author_profile": "https://Stackoverflow.com/users/3937",
"pm_score": 3,
"selected": true,
"text": "<p>According to this:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/0h4c3zkw(VS.80).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/0h4c3zkw(VS.80).aspx</a></p>\n\n<p>RemoveAtPos has these semantics</p>\n\n<blockquote>\n <p>Removes the key/value pair stored at the specified position. The memory used to store the element is freed. The POSITION referenced by pos becomes invalid, and while the POSITION of any other elements in the map remains valid, they do not necessarily retain the same order.</p>\n</blockquote>\n\n<p>The problem is that the order can change -- which means that GetNext() won't really continue the iteration. It looks like you need to collect the POSITIONs you want to delete in one pass and delete them in the next. Removing a POSITION does not invalidate the other POSITION objects</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11898/"
] |
I'm trying to do the following without too much special case code to deal with invalidated POSITIONs etc:
What's the best way to fill in the blanks?
```
void DeleteUnreferencedRecords(CAtlMap<Record>& records)
{
for(____;____;____)
{
if( NotReferencedElsewhere(record) )
{
// Delete record
_______;
}
}
}
```
|
According to this:
<http://msdn.microsoft.com/en-us/library/0h4c3zkw(VS.80).aspx>
RemoveAtPos has these semantics
>
> Removes the key/value pair stored at the specified position. The memory used to store the element is freed. The POSITION referenced by pos becomes invalid, and while the POSITION of any other elements in the map remains valid, they do not necessarily retain the same order.
>
>
>
The problem is that the order can change -- which means that GetNext() won't really continue the iteration. It looks like you need to collect the POSITIONs you want to delete in one pass and delete them in the next. Removing a POSITION does not invalidate the other POSITION objects
|
197,150 |
<p>I can write a trivial script to do this but in my ongoing quest to get more familliar with unix I'd like to learn efficient methods using built in commands instead.</p>
<p>I need to deal with very large files that have a variable number of header lines. the last header line consists of the text 'LastHeaderLine'. I wish to output everything after this line. (I'm not worried about false positive matches.)</p>
|
[
{
"answer_id": 197169,
"author": "Avi",
"author_id": 1605,
"author_profile": "https://Stackoverflow.com/users/1605",
"pm_score": 4,
"selected": false,
"text": "<p>Using sed:</p>\n\n<pre><code>sed -ne '/LastHeaderLine/,$p' <inputfile\n</code></pre>\n\n<p>will match everything from the regex match to the end of the file. 'p' prints the lines that match.</p>\n\n<p>Edit:</p>\n\n<p>On second thought, you don't want to print the line matching LastHeaderLine. This is difficult to do with sed. In perl, you could do the following:</p>\n\n<pre><code>perl -ne 'if ($flag) {print;} if (/LastHeaderFile/) {$flag=1;}' <inputfile\n</code></pre>\n\n<p>This would print only lines strictly following the regex match.</p>\n"
},
{
"answer_id": 197175,
"author": "Ralph M. Rickenbach",
"author_id": 4549416,
"author_profile": "https://Stackoverflow.com/users/4549416",
"pm_score": 4,
"selected": false,
"text": "<p>Why not try awk for this? It would look like this:</p>\n\n<pre><code>awk 'NR == 1, /LastHeaderLine/ { next } { print }' myinputfile > myoutputfile\n</code></pre>\n\n<p>where <strong>NR == 1</strong> is true for the first line, <strong>/LastHeaderLine/</strong> matches your last header line. The comma operator lets the following function <strong>{ next }</strong> fire for all sentences in the range of the two regular expression. In this case it will skip to the next line of input without further operation. For all other input lines it will print the lines to the standard output, which you can redirect using >.</p>\n"
},
{
"answer_id": 197185,
"author": "mweerden",
"author_id": 4285,
"author_profile": "https://Stackoverflow.com/users/4285",
"pm_score": 5,
"selected": false,
"text": "<p>Similar to the answer of <a href=\"https://stackoverflow.com/questions/197150/skip-file-lines-until-a-match-is-found-then-output-the-rest#197169\">Avi</a>, but without including the line with \"LastHeaderLine\".</p>\n\n<pre><code>sed -e '1,/LastHeaderLine/d'\n</code></pre>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I can write a trivial script to do this but in my ongoing quest to get more familliar with unix I'd like to learn efficient methods using built in commands instead.
I need to deal with very large files that have a variable number of header lines. the last header line consists of the text 'LastHeaderLine'. I wish to output everything after this line. (I'm not worried about false positive matches.)
|
Similar to the answer of [Avi](https://stackoverflow.com/questions/197150/skip-file-lines-until-a-match-is-found-then-output-the-rest#197169), but without including the line with "LastHeaderLine".
```
sed -e '1,/LastHeaderLine/d'
```
|
197,164 |
<p>In my views I use a helper that takes arbitrary HTML as a block:</p>
<pre><code><% some_block_helper do %>
Some arbitrary HTML and ERB variables here.
More HTML here.
<% end %>
</code></pre>
<p>My helper does a bunch of things to the passed block of HTML before rendering it back to the view (Markdown and other formatting). I would like to know what are the cleanest ways of testing the result of the helper call in rSpec, if any. I've found a few examples that muck about with private methods of ERB but that seems a bit brittle and hard to read.</p>
|
[
{
"answer_id": 248778,
"author": "James Baker",
"author_id": 9365,
"author_profile": "https://Stackoverflow.com/users/9365",
"pm_score": 1,
"selected": false,
"text": "<ol>\n<li>For a functional test, write a normal <a href=\"http://rspec.info/documentation/rails/writing/views.html\" rel=\"nofollow noreferrer\">view spec</a> and test the result.</li>\n<li>To unit test your <a href=\"http://rspec.info/documentation/rails/writing/helpers.html\" rel=\"nofollow noreferrer\">helper</a>, pass an arbitrary html input string to it directly.</li>\n</ol>\n\n<p>If there's any other difficulty I'm missing, please comment?</p>\n"
},
{
"answer_id": 249295,
"author": "Cameron Booth",
"author_id": 14873,
"author_profile": "https://Stackoverflow.com/users/14873",
"pm_score": 3,
"selected": false,
"text": "<p>To add just a bit to what James said, I think something like this should work just fine:</p>\n\n<pre><code>describe SomeHelper do\n it 'should do something' do\n helper.some_block_helper { the_block_code }.should XXXX\n end\nend\n</code></pre>\n"
},
{
"answer_id": 4311761,
"author": "James Healy",
"author_id": 127255,
"author_profile": "https://Stackoverflow.com/users/127255",
"pm_score": 1,
"selected": false,
"text": "<p>Here's another example that expands on Cameron's answer</p>\n\n<pre><code>describe SomeHelper do\n it 'should do something' do\n content = lambda { \"blah\" } \n result = helper.some_block_helper(&content)\n\n result.should include(\"blah\")\n result.should XXX\n end\nend\n</code></pre>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197164",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21702/"
] |
In my views I use a helper that takes arbitrary HTML as a block:
```
<% some_block_helper do %>
Some arbitrary HTML and ERB variables here.
More HTML here.
<% end %>
```
My helper does a bunch of things to the passed block of HTML before rendering it back to the view (Markdown and other formatting). I would like to know what are the cleanest ways of testing the result of the helper call in rSpec, if any. I've found a few examples that muck about with private methods of ERB but that seems a bit brittle and hard to read.
|
To add just a bit to what James said, I think something like this should work just fine:
```
describe SomeHelper do
it 'should do something' do
helper.some_block_helper { the_block_code }.should XXXX
end
end
```
|
197,171 |
<p>Not too long ago, I had a problem which required me to <a href="https://stackoverflow.com/questions/186237/program-only-crashes-as-release-build-how-to-debug">set WinDbg.exe as the default post-mortem debugger</a>. Now that I've fixed that and am back doing normal work, it would be really nice if I could set VS to be my default post-mortem debugger. How does one go about doing this?</p>
<p>Also, how do I make VS attach to an already existing session? That is, I've got my VS project open in one window, and a command line open where I'm launching my program from. If the program crashes, how do I get VS to figure out to attach the debugger to the active line in the project that's already open?</p>
|
[
{
"answer_id": 197208,
"author": "MvdD",
"author_id": 18044,
"author_profile": "https://Stackoverflow.com/users/18044",
"pm_score": 4,
"selected": true,
"text": "<p>from the <a href=\"http://support.microsoft.com/kb/121434\" rel=\"noreferrer\">Microsoft support page</a>:</p>\n\n<pre><code>1. Start Registry Editor and locate the following Registry subkey in the HKEY_LOCAL_MACHINE subtree:\n\n\\SOFTWARE\\MICROSOFT\\WINDOWS NT\\CURRENTVERSION\\AEDEBUG\n2. Select the Debugger value.\n3. On the Edit menu, click String.\n\n• To use the Windows debugger, type windbg -p %ld -e %ld.\n• To use Visual C++ 4.2 or earlier, type msvc -p %ld -e %ld.\n• To use Visual C++ 5.0 or later, type msdev.exe -p %ld -e %ld.\n• To use Dr. Watson, type drwtsn32.exe -p %ld -e %ld. You can also make Dr. Watson the default debugger by running this command:drwtsn32.exe -i.\n4. Choose OK and exit Registry Editor. \n</code></pre>\n"
},
{
"answer_id": 643031,
"author": "Josh Sklare",
"author_id": 21277,
"author_profile": "https://Stackoverflow.com/users/21277",
"pm_score": 5,
"selected": false,
"text": "<p>You can re-enable Visual Studio for Just-In-Time debugging from within Visual Studio:</p>\n\n<p>Go to the <strong>Tools | Options</strong> | <strong>Debugging | Just-In-Time</strong> dialog. Then make sure all <strong>Native</strong> and <strong>Managed</strong> (if you're debugging a .NET application) are checked. Next time you get a crash, the Visual Studio Just-In-Time debugger will come up.</p>\n\n<p>The Visual Studio Just-In-Time debugger let's you choose whether you want to open a new instance of Visual Studio or start debugging with a currently open solution.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14302/"
] |
Not too long ago, I had a problem which required me to [set WinDbg.exe as the default post-mortem debugger](https://stackoverflow.com/questions/186237/program-only-crashes-as-release-build-how-to-debug). Now that I've fixed that and am back doing normal work, it would be really nice if I could set VS to be my default post-mortem debugger. How does one go about doing this?
Also, how do I make VS attach to an already existing session? That is, I've got my VS project open in one window, and a command line open where I'm launching my program from. If the program crashes, how do I get VS to figure out to attach the debugger to the active line in the project that's already open?
|
from the [Microsoft support page](http://support.microsoft.com/kb/121434):
```
1. Start Registry Editor and locate the following Registry subkey in the HKEY_LOCAL_MACHINE subtree:
\SOFTWARE\MICROSOFT\WINDOWS NT\CURRENTVERSION\AEDEBUG
2. Select the Debugger value.
3. On the Edit menu, click String.
• To use the Windows debugger, type windbg -p %ld -e %ld.
• To use Visual C++ 4.2 or earlier, type msvc -p %ld -e %ld.
• To use Visual C++ 5.0 or later, type msdev.exe -p %ld -e %ld.
• To use Dr. Watson, type drwtsn32.exe -p %ld -e %ld. You can also make Dr. Watson the default debugger by running this command:drwtsn32.exe -i.
4. Choose OK and exit Registry Editor.
```
|
197,190 |
<p>So, I understand <i>that</i> the following doesn't work, but <i>why</i> doesn't it work?</p>
<pre><code>interface Adapter<E> {}
class Adaptulator<I> {
<E, A extends I & Adapter<E>> void add(Class<E> extl, Class<A> intl) {
addAdapterFactory(new AdapterFactory<E, A>(extl, intl));
}
}
</code></pre>
<p>The <code>add()</code> method gives me a compile error, "Cannot specify any additional bound Adapter<E> when first bound is a type parameter" (in Eclipse), or "Type parameter cannot be followed by other bounds" (in IDEA), take your pick.</p>
<p>Clearly you're just Not Allowed to use the type parameter <code>I</code> there, before the <code>&</code>, and that's that. (And before you ask, it doesn't work if you switch 'em, because there's no guarantee that <code>I</code> isn't a concrete class.) But why not? I've looked through Angelika Langer's FAQ and can't find an answer.</p>
<p>Generally when some generics limitation seems arbitrary, it's because you've created a situation where the type system can't actually enforce correctness. But I don't see what case would break what I'm trying to do here. I'd say maybe it has something to do with method dispatch after type erasure, but there's only one <code>add()</code> method, so it's not like there's any ambiguity...</p>
<p>Can someone demonstrate the problem for me?</p>
|
[
{
"answer_id": 197301,
"author": "Miserable Variable",
"author_id": 18573,
"author_profile": "https://Stackoverflow.com/users/18573",
"pm_score": 2,
"selected": false,
"text": "<p>This probably does not answer the root question, but just want to point out that the spec unambiguously forbids it. Google search for the error message took me to <a href=\"http://blogs.oracle.com/vr/entry/a_type_variable_may_not\" rel=\"nofollow noreferrer\" title=\"this blog entry\">this blog entry</a>, which further points to <a href=\"http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#108850\" rel=\"nofollow noreferrer\">jls 4.4</a>:</p>\n\n<blockquote>\n <p>The bound consists of either a type variable, or a class or interface type T possibly followed by further interface types I1 , ..., In.</p>\n</blockquote>\n\n<p>So, if you use type parameter as bound you cannot use any other bound, just as the error message says. </p>\n\n<p>Why the restriction? I have no idea.</p>\n"
},
{
"answer_id": 197391,
"author": "Bruno De Fraine",
"author_id": 6918,
"author_profile": "https://Stackoverflow.com/users/6918",
"pm_score": 6,
"selected": true,
"text": "<p>I'm also not sure why the restriction is there. You could try sending a friendly e-mail to the designers of Java 5 Generics (chiefly Gilad Bracha and Neal Gafter).</p>\n\n<p>My guess is that they wanted to support only an absolute minimum of <a href=\"https://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.9\" rel=\"noreferrer\">intersection types</a> (which is what multiple bounds essentially are), to make the language no more complex than needed. An intersection cannot be used as a type annotation; a programmer can only express an intersection when it appears as the upper bound of a type variable.</p>\n\n<p>And why was this case even supported? The answer is that multiple bounds allow you to control the erasure, which allows to maintain binary compatibility when generifying existing classes. As explained in section 17.4 of the <a href=\"http://java-generics-book.dev.java.net/\" rel=\"noreferrer\">book</a> by Naftalin and Wadler, a <code>max</code> method would logically have the following signature:</p>\n\n<pre><code>public static <T extends Comparable<? super T>> T max(Collection<? extends T> coll)\n</code></pre>\n\n<p>However, this erases to:</p>\n\n<pre><code>public static Comparable max(Collection coll)\n</code></pre>\n\n<p>Which does not match the historical signature of <code>max</code>, and causes old clients to break.\nWith multiple bounds, only the left-most bound is considered for the erasure, so if <code>max</code> is given the following signature:</p>\n\n<pre><code>public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll)\n</code></pre>\n\n<p>Then the erasure of its signature becomes:</p>\n\n<pre><code>public static Object max(Collection coll)\n</code></pre>\n\n<p>Which is equal to the signature of <code>max</code> before Generics.</p>\n\n<p>It seems plausible that the Java designers only cared about this simple case and restricted other (more advanced) uses of intersection types because they were just unsure of the complexity that it might bring. So the reason for this design decision does not need to be a possible safety problem (as the question suggests).</p>\n\n<p>More discussion on intersection types and restrictions of generics in an <a href=\"http://www.cs.rice.edu/~javaplt/papers/oopsla2008.pdf\" rel=\"noreferrer\">upcoming OOPSLA paper</a>.</p>\n"
},
{
"answer_id": 198073,
"author": "Jan Soltis",
"author_id": 3997,
"author_profile": "https://Stackoverflow.com/users/3997",
"pm_score": 4,
"selected": false,
"text": "<p>Here's another quote from <a href=\"https://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.9\" rel=\"noreferrer\">JLS</a>:</p>\n\n<blockquote>\n <p>The form of a bound is restricted (only the first element may be a class or type variable, and only one type variable may appear in the bound) to <strong>preclude certain awkward situations coming into existence</strong>. </p>\n</blockquote>\n\n<p>What exactly are those awkward situations, I don't know.</p>\n"
},
{
"answer_id": 210992,
"author": "Chris Povirk",
"author_id": 28465,
"author_profile": "https://Stackoverflow.com/users/28465",
"pm_score": 4,
"selected": false,
"text": "<p>Two possible reasons for outlawing this:</p>\n<ol>\n<li><p>Complexity. <a href=\"https://bugs.openjdk.java.net/browse/JDK-4899305\" rel=\"nofollow noreferrer\">JDK-4899305</a> suggests that a bound containing a type parameter plus additional parameterized types would allow for even more complicated mutually recursive types than already exist. In short, <a href=\"https://stackoverflow.com/questions/197190/why-cant-i-use-a-type-argument-in-a-type-parameter-with-multiple-bounds#197391\">Bruno's answer</a>.</p>\n</li>\n<li><p>The possibility of specifying illegal types. Specifically, <a href=\"http://forums.sun.com/thread.jspa?messageID=2731375#2731541\" rel=\"nofollow noreferrer\">extending a generic interface twice with different parameters</a>. I can't come up with a non-contrived example, but: <pre>/** Contains a Comparator<String> that also implements the given type T. */\nclass StringComparatorHolder<T, C extends T & Comparator<String>> {\n private final C comparator;\n // ...\n}\n \nvoid foo(StringComparatorHolder<Comparator<Integer>, ?> holder) { ... }</pre></p>\n</li>\n</ol>\n<p>Now <code>holder.comparator</code> is a <code>Comparator<Integer></code> and a <code>Comparator<String></code>. It's not clear to me exactly how much trouble this would cause for the compiler, but it's clearly not good. Suppose in particular that <code>Comparator</code> had a method like this:<pre>void sort(List<? extends T> list);</pre></p>\n<p>Our <code>Comparator<Integer></code> / <code>Comparator<String></code> hybrid now has two methods with the same erasure:<pre>void sort(List<? extends Integer> list);\nvoid sort(List<? extends String> list);</pre></p>\n<p>It's for these kinds of reasons that you can't specify such a type directly:</p>\n<pre><T extends Comparator<Integer> & Comparator<String>> void bar() { ... }</pre>\n<pre>java.util.Comparator cannot be inherited with different arguments:\n <java.lang.Integer> and <java.lang.String></pre>\n<p>Since <code><A extends I & Adapter<E>></code> allows you to do the same thing indirectly, it's out, too.</p>\n"
},
{
"answer_id": 60572215,
"author": "Ealrann",
"author_id": 4030058,
"author_profile": "https://Stackoverflow.com/users/4030058",
"pm_score": 0,
"selected": false,
"text": "<p>I had the same problem, and found a working solution:</p>\n<pre><code> interface Adapter<E>\n {}\n\n interface Adaptulator<I>\n {\n void add(Container<?, ? extends I> container);\n }\n\n static final class Container<E, I extends Adapter<E>>\n {\n public final Class<E> extl;\n public final Class<I> intl;\n\n public Container(Class<E> extl, Class<I> intl)\n {\n this.extl = extl;\n this.intl = intl;\n }\n }\n</code></pre>\n<h3>Why it's working</h3>\n<p>To understand that, we need to state our requirements:</p>\n<ol>\n<li>Keep two different generics synchronized on something. In your case, this is the <strong>E</strong>.</li>\n<li>One of the two generic needs to have some extra inheritance, here it's <strong>I</strong>.</li>\n</ol>\n<p>Creating an extra class allow to meet these two requirements, by creating a tight context.</p>\n<ol start=\"3\">\n<li>An extra requirement (but probably the most important) was the need of a generic method (not bound too much to our class).</li>\n</ol>\n<p>This is solved by the permissive parameter <code>Container<?, ? extends I></code>.</p>\n<p><strong>Note</strong></p>\n<p>It's just a guess, but in this kind of usage, in general, you quickly need a <code>? super A</code> or <code>? super I</code> somewhere.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197190",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27358/"
] |
So, I understand *that* the following doesn't work, but *why* doesn't it work?
```
interface Adapter<E> {}
class Adaptulator<I> {
<E, A extends I & Adapter<E>> void add(Class<E> extl, Class<A> intl) {
addAdapterFactory(new AdapterFactory<E, A>(extl, intl));
}
}
```
The `add()` method gives me a compile error, "Cannot specify any additional bound Adapter<E> when first bound is a type parameter" (in Eclipse), or "Type parameter cannot be followed by other bounds" (in IDEA), take your pick.
Clearly you're just Not Allowed to use the type parameter `I` there, before the `&`, and that's that. (And before you ask, it doesn't work if you switch 'em, because there's no guarantee that `I` isn't a concrete class.) But why not? I've looked through Angelika Langer's FAQ and can't find an answer.
Generally when some generics limitation seems arbitrary, it's because you've created a situation where the type system can't actually enforce correctness. But I don't see what case would break what I'm trying to do here. I'd say maybe it has something to do with method dispatch after type erasure, but there's only one `add()` method, so it's not like there's any ambiguity...
Can someone demonstrate the problem for me?
|
I'm also not sure why the restriction is there. You could try sending a friendly e-mail to the designers of Java 5 Generics (chiefly Gilad Bracha and Neal Gafter).
My guess is that they wanted to support only an absolute minimum of [intersection types](https://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.9) (which is what multiple bounds essentially are), to make the language no more complex than needed. An intersection cannot be used as a type annotation; a programmer can only express an intersection when it appears as the upper bound of a type variable.
And why was this case even supported? The answer is that multiple bounds allow you to control the erasure, which allows to maintain binary compatibility when generifying existing classes. As explained in section 17.4 of the [book](http://java-generics-book.dev.java.net/) by Naftalin and Wadler, a `max` method would logically have the following signature:
```
public static <T extends Comparable<? super T>> T max(Collection<? extends T> coll)
```
However, this erases to:
```
public static Comparable max(Collection coll)
```
Which does not match the historical signature of `max`, and causes old clients to break.
With multiple bounds, only the left-most bound is considered for the erasure, so if `max` is given the following signature:
```
public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll)
```
Then the erasure of its signature becomes:
```
public static Object max(Collection coll)
```
Which is equal to the signature of `max` before Generics.
It seems plausible that the Java designers only cared about this simple case and restricted other (more advanced) uses of intersection types because they were just unsure of the complexity that it might bring. So the reason for this design decision does not need to be a possible safety problem (as the question suggests).
More discussion on intersection types and restrictions of generics in an [upcoming OOPSLA paper](http://www.cs.rice.edu/~javaplt/papers/oopsla2008.pdf).
|
197,218 |
<p>I am trying to get system date in a C program on a MSVC++ 6.0 compiler. I am using a system call:</p>
<p><strong>system("date /T")</strong> (output is e.g. 13-Oct-08 which is date on my system in the format i have set) </p>
<p>but this prints the date to the i/o console. </p>
<p>How do i make take this date as returned by above system call and store it as a string value to a string defined in my code?
Or </p>
<p>Is there any other API i can use to get the date in above mentioned format (13-Oct-08, or 13-10-08) ?</p>
<p>-AD</p>
|
[
{
"answer_id": 197227,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 0,
"selected": false,
"text": "<p>There are a couple of ways to do this using API functions, two that jump to mind are <a href=\"http://msdn.microsoft.com/en-us/library/aa272978(VS.60).aspx\" rel=\"nofollow noreferrer\">strftime</a> and <a href=\"http://msdn.microsoft.com/en-us/library/ms776293.aspx\" rel=\"nofollow noreferrer\">GetDateFormat</a>.</p>\n\n<p>I'd like to provide examples but I'm afraid I don't have a Win32 compiler handy at the moment. Hopefully the examples in the above documentation are sufficient.</p>\n"
},
{
"answer_id": 197230,
"author": "Constantin",
"author_id": 20310,
"author_profile": "https://Stackoverflow.com/users/20310",
"pm_score": 1,
"selected": false,
"text": "<pre><code>#include <windows.h>\n#include <iostream>\n\nint main() {\n\n SYSTEMTIME systmDateTime = {};\n ::GetLocalTime(&systmDateTime);\n\n wchar_t wszDate[64] = {};\n int const result = ::GetDateFormatW(\n LOCALE_USER_DEFAULT, DATE_SHORTDATE,\n &systmDateTime, 0, wszDate, _countof(wszDate));\n\n if (result) {\n std::wcout << wszDate;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 197234,
"author": "Adam Wright",
"author_id": 1200,
"author_profile": "https://Stackoverflow.com/users/1200",
"pm_score": 0,
"selected": false,
"text": "<p>Have a read of <a href=\"http://msdn.microsoft.com/en-us/library/ms725473(VS.85).aspx\" rel=\"nofollow noreferrer\">Win32 Time functions</a>; GetLocalTime may be your friend. There are also the standard C time functions, time and strftime.</p>\n\n<p>For future reference, in a C program, it is almost always the wrong answer to invoke an external utility and capture it's STDOUT.</p>\n"
},
{
"answer_id": 197293,
"author": "goldenmean",
"author_id": 2759376,
"author_profile": "https://Stackoverflow.com/users/2759376",
"pm_score": 0,
"selected": false,
"text": "<p>Thanks for the pointers.</p>\n\n<p>I used this and it served my purpose:</p>\n\n<pre><code>#include <time.h>\n#include <stdio.h>\n#include <sys/types.h>\n#include <sys/timeb.h>\n#include <string.h>\n int main()\n\n { \n\n char tmpbuf[128];\n\n time_t ltime;\n\n struct tm *today;\n\n _strdate( tmpbuf );\n printf(\"\\n before formatting date is %s\",tmpbuf); \n\n time(&ltime);\n today = localtime( &ltime );\n\n strftime(tmpbuf,128,\"%d-%m-%y\",today);\n printf( \"\\nafter formatting date is %s\\n\", tmpbuf );\n\n }\n</code></pre>\n\n<p>-AD</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197218",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2759376/"
] |
I am trying to get system date in a C program on a MSVC++ 6.0 compiler. I am using a system call:
**system("date /T")** (output is e.g. 13-Oct-08 which is date on my system in the format i have set)
but this prints the date to the i/o console.
How do i make take this date as returned by above system call and store it as a string value to a string defined in my code?
Or
Is there any other API i can use to get the date in above mentioned format (13-Oct-08, or 13-10-08) ?
-AD
|
```
#include <windows.h>
#include <iostream>
int main() {
SYSTEMTIME systmDateTime = {};
::GetLocalTime(&systmDateTime);
wchar_t wszDate[64] = {};
int const result = ::GetDateFormatW(
LOCALE_USER_DEFAULT, DATE_SHORTDATE,
&systmDateTime, 0, wszDate, _countof(wszDate));
if (result) {
std::wcout << wszDate;
}
}
```
|
197,220 |
<p>I've got an ASP.NET 2.0 website that connects to a SQL database. I've upgraded the SQL server from 2000 to 2008 and since then, one page refuses to work. </p>
<p>I've worked out the problem is that the call to SqlDataReader.HasRows is returning false even though the dataset is not empty and removing the check allows the loop through reader.Read() to access the expected data. </p>
<pre><code> _connectionString = WebConfigurationManager.ConnectionStrings["SQLServer"].ConnectionString;
SqlConnection connection = new SqlConnection(_connectionString);
SqlCommand command = new SqlCommand(searchtype, connection);
SqlParameter _parSeachTerm = new SqlParameter("@searchterm", SqlDbType.VarChar, 255);
_parSeachTerm.Value = searchterm;
command.Parameters.Add(_parSeachTerm);
command.CommandType = CommandType.StoredProcedure;
try
{
connection.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows) //this always returns false!?
{
while (reader.Read())
{...
</code></pre>
<p>Does anybody have any idea what's going on? There are similar code blocks on other pages where HasRows returns the correct value.</p>
<p>EDIT- Just to clarify, the stored procedure DOES return results which I have confirmed because the loop runs through fine if I remove the HasRows check. Changing just the name of the SQL server in the connection string to an identical database running on SQL 2000 makes the problem go away. I've checked that NOCOUNT is off, so what else could make HasRows return false when that's not the case??</p>
<p>EDIT2- Here's the SP</p>
<pre><code>CREATE PROCEDURE StaffEnquirySurnameSearch
@searchterm varchar(255)
AS
SELECT AD.Name, AD.Company, AD.telephoneNumber, AD.manager, CVS.Position, CVS.CompanyArea, CVS.Location, CVS.Title, AD.guid AS guid,
AD.firstname, AD.surname
FROM ADCVS AD
LEFT OUTER JOIN CVS ON
AD.Guid=CVS.Guid
WHERE AD.SurName LIKE @searchterm
ORDER BY AD.Surname, AD.Firstname
GO
</code></pre>
<p>Many thanks in advance.</p>
|
[
{
"answer_id": 197287,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 1,
"selected": false,
"text": "<p>Does the stored procedure work if you invoke it in directly, say in SSMS? I'd start by making sure that it does.</p>\n"
},
{
"answer_id": 197296,
"author": "Jonas Lincoln",
"author_id": 17436,
"author_profile": "https://Stackoverflow.com/users/17436",
"pm_score": 0,
"selected": false,
"text": "<p>First, check the procedure as @tvanfosson says. \nSecond, the check for HasRows() is actually unnecessary in the code snippet. </p>\n"
},
{
"answer_id": 197923,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>You're not using RAISEERROR by chance? We found some problems using the same pattern as above (check HasRows, then reader.Read()) and found that if RAISEERROR was used with a certain error code (above 16, I believe) then the HasRows would return false <strong>and</strong> we would have problems catching an exception.</p>\n"
},
{
"answer_id": 197928,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>It is either your connection string, the stored procedure, or a bug in the sql driver.\nMost people are guessing the stored procedure.\nSo show us the code.\nWhile you are at it, show us the connection string and searchtype variable contents.</p>\n"
},
{
"answer_id": 197964,
"author": "Mitch Wheat",
"author_id": 16076,
"author_profile": "https://Stackoverflow.com/users/16076",
"pm_score": 1,
"selected": false,
"text": "<p><code>HasRows</code> requires a scrollable cursor. </p>\n\n<p>Do the rows you are bringing back contain any large <code>image/BLOB</code> data?</p>\n\n<p>As someone else suggested, I think posting the <code>Stored Procedure</code> might throw some light on the matter...</p>\n"
},
{
"answer_id": 198127,
"author": "shahkalpesh",
"author_id": 23574,
"author_profile": "https://Stackoverflow.com/users/23574",
"pm_score": 0,
"selected": false,
"text": "<p>I am speculating again.<br>\nDo you have multiple datareaders open by any chance?</p>\n\n<p>Add MARS_Connection=yes; OR MultipleActiveResultSets=true to the connection string, if that helps.<br>\nAlso, your usage of connection & datareader is not a recommended way of doing things<br></p>\n\n<p>a simpler way to write it could be</p>\n\n<pre>\n<code>\nusing (connection cnn = new Connection(...)\n{\nusing (SqlDataReader rdr = ....\n{\n//some code which deals with datareader\n}\n}\n</code>\n</pre>\n\n<p>This will close the connection and datareader once the operation is complete.</p>\n"
},
{
"answer_id": 199214,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I think you've got NOCOUNT backwards.\nI believe NOCOUNT needs to be on for this to work.</p>\n\n<p>In your stored procedure add\nSET NOCOUNT ON\nafter the AS and before any code.\nOtherwise it returns two result sets.\nOne with the count and one with the actual data.\nYou only want the result set with the actual data.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197220",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27377/"
] |
I've got an ASP.NET 2.0 website that connects to a SQL database. I've upgraded the SQL server from 2000 to 2008 and since then, one page refuses to work.
I've worked out the problem is that the call to SqlDataReader.HasRows is returning false even though the dataset is not empty and removing the check allows the loop through reader.Read() to access the expected data.
```
_connectionString = WebConfigurationManager.ConnectionStrings["SQLServer"].ConnectionString;
SqlConnection connection = new SqlConnection(_connectionString);
SqlCommand command = new SqlCommand(searchtype, connection);
SqlParameter _parSeachTerm = new SqlParameter("@searchterm", SqlDbType.VarChar, 255);
_parSeachTerm.Value = searchterm;
command.Parameters.Add(_parSeachTerm);
command.CommandType = CommandType.StoredProcedure;
try
{
connection.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows) //this always returns false!?
{
while (reader.Read())
{...
```
Does anybody have any idea what's going on? There are similar code blocks on other pages where HasRows returns the correct value.
EDIT- Just to clarify, the stored procedure DOES return results which I have confirmed because the loop runs through fine if I remove the HasRows check. Changing just the name of the SQL server in the connection string to an identical database running on SQL 2000 makes the problem go away. I've checked that NOCOUNT is off, so what else could make HasRows return false when that's not the case??
EDIT2- Here's the SP
```
CREATE PROCEDURE StaffEnquirySurnameSearch
@searchterm varchar(255)
AS
SELECT AD.Name, AD.Company, AD.telephoneNumber, AD.manager, CVS.Position, CVS.CompanyArea, CVS.Location, CVS.Title, AD.guid AS guid,
AD.firstname, AD.surname
FROM ADCVS AD
LEFT OUTER JOIN CVS ON
AD.Guid=CVS.Guid
WHERE AD.SurName LIKE @searchterm
ORDER BY AD.Surname, AD.Firstname
GO
```
Many thanks in advance.
|
Does the stored procedure work if you invoke it in directly, say in SSMS? I'd start by making sure that it does.
|
197,228 |
<p>I'm using the jquery library to load the content of an html file. Something like this:</p>
<p>$("#Main").load("login.html")</p>
<p>If the file (in this case 'login.html') does not exist, I would like to detect it so that I can redirect the user to an error page for example. Any ideas how I can detect if the file to load exists or not?</p>
|
[
{
"answer_id": 197237,
"author": "redsquare",
"author_id": 6440,
"author_profile": "https://Stackoverflow.com/users/6440",
"pm_score": 5,
"selected": true,
"text": "<p>You can use the ajaxComplete event, whis gives you access to the xhr object which you can query the status of the request e.g a status of 404 will mean the file does not exist.</p>\n\n<p>More Info in the docs <a href=\"http://docs.jquery.com/Ajax/ajaxComplete#callback\" rel=\"noreferrer\">http://docs.jquery.com/Ajax/ajaxComplete#callback</a></p>\n\n<p>Test here <a href=\"http://pastebin.me/48f32a74927bb\" rel=\"noreferrer\">http://pastebin.me/48f32a74927bb</a></p>\n\n<p>e.g</p>\n\n<pre><code>$(\"#someDivId\").ajaxComplete(function(request, settings){\n if (settings.status===404){\n //redirect here\n }\n});\n</code></pre>\n"
},
{
"answer_id": 200519,
"author": "Remy Sharp",
"author_id": 22617,
"author_profile": "https://Stackoverflow.com/users/22617",
"pm_score": 1,
"selected": false,
"text": "<p>@PConroy's solution works, but it does the same thing for all failed ajax requests.</p>\n\n<p>If you need this on a per request basis - i.e. if the first request fails it goes to X page and if the second fails go to Y, then you need to do this using the error handle in the $.ajax function:</p>\n\n<p><a href=\"http://jsbin.com/iwume\" rel=\"nofollow noreferrer\">http://jsbin.com/iwume</a></p>\n\n<p>(to edit: <a href=\"http://jsbin.com/iwume/edit\" rel=\"nofollow noreferrer\">http://jsbin.com/iwume/edit</a>)</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15928/"
] |
I'm using the jquery library to load the content of an html file. Something like this:
$("#Main").load("login.html")
If the file (in this case 'login.html') does not exist, I would like to detect it so that I can redirect the user to an error page for example. Any ideas how I can detect if the file to load exists or not?
|
You can use the ajaxComplete event, whis gives you access to the xhr object which you can query the status of the request e.g a status of 404 will mean the file does not exist.
More Info in the docs <http://docs.jquery.com/Ajax/ajaxComplete#callback>
Test here <http://pastebin.me/48f32a74927bb>
e.g
```
$("#someDivId").ajaxComplete(function(request, settings){
if (settings.status===404){
//redirect here
}
});
```
|
197,266 |
<p>Below is the code of a simple html with a table layout.
In FF it's looking as I think it should look like,
in IE7 it doesn't. what am I doing wrong?<br><br>
And how can I fix it?</p>
<pre><code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<TITLE>test</TITLE>
</head>
<body>
<table id="MainTable" cellspacing="0" cellpadding="0" border="1">
<tbody>
<tr>
<td colspan="4">
<div style='width:769; height:192;'>192
</div>
</td>
</tr>
<tr>
<td colspan="2" valign="top">
<div style='width:383; height:100;'>100
</div>
</td>
<td rowspan="2" valign="top">
<div style='width:190; height:200;'>200
</div>
</td>
<td rowspan="2" valign="top">
<div style='width:190; height:200;'>200
</div>
</td>
</tr>
<tr>
<td valign="top" rowspan="2">
<div style='width:190; height:200;'>200
</div>
</td>
<td valign="top" rowspan="2">
<div style='width:190; height:200;'>200
</div>
</td>
</tr>
<tr>
<td valign="top">
<div style='width:190; height:100;'>100
</div>
</td>
<td valign="top" >
<div style='width:190; height:100;'>100
</div>
</td>
</tr>
<tr>
<td colspan="2">
<div style='width:383; height:100;'>100
</div>
</td>
<td colspan="2">
<div style='width:383; height:100;'>100
</div>
</td>
</tr>
<tr>
<td>
<div style='width:190; height:100;'>100
</div>
</td>
<td>
<div style='width:190; height:100;'>100
</div>
</td>
<td colspan="2">
<div style='width:383; height:100;'>100
</div>
</td>
</tr>
</tbody>
</table>
</body>
</html>
</code></pre>
|
[
{
"answer_id": 197283,
"author": "roundcrisis",
"author_id": 162325,
"author_profile": "https://Stackoverflow.com/users/162325",
"pm_score": 0,
"selected": false,
"text": "<p>completely agree, you can have a look at blueprint CSS or other CSS frameworks for some help</p>\n"
},
{
"answer_id": 197284,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 2,
"selected": false,
"text": "<p>For a start, your CSS values should have units, e.g. <code>width:190;</code> should be <code>width: 190px;</code></p>\n"
},
{
"answer_id": 197316,
"author": "rslite",
"author_id": 15682,
"author_profile": "https://Stackoverflow.com/users/15682",
"pm_score": 0,
"selected": false,
"text": "<p>At first sight it looks like IE7 has some broken support for this kind of formatting. At first I was going to propose to get rid of the divs and move the formatting (width and height) directly on the TD, but I tried that and doesn't seem to solve the problem.</p>\n\n<p>I guess this is not a nice solution, but would it be possible to replace the rowspan cells with more cells with an invisible border between them? However this solution fails if the text is larger than the size of the upper cell.</p>\n"
},
{
"answer_id": 197317,
"author": "bobince",
"author_id": 18936,
"author_profile": "https://Stackoverflow.com/users/18936",
"pm_score": 3,
"selected": true,
"text": "<p>I assume you are complaining about the minimal height of the middle row (the one containing only rowspanned cells), and the enlarged height of the adjacent rows to compensate, leaving gaps between the divs.</p>\n\n<p>IE cannot calculate optimal row heights when the row contains only rowspanned cells. The usual solution when you absolutely cannot rejig it to get rid of the rowspan is to add a 1px 'dummy' column to one side of the table, containing empty cells, each with the 'height' set to how high the row should be.</p>\n\n<p>But yes, depending on what you're planning to do with this, a CSS layout may well be more appropriate. If it's really a fixed-pixels-for-everything layout like this example, absolute positioning for each div will be a lot, lot easier.</p>\n\n<p>Other bits: CSS width/height values require units (presumably 'px'); valign/cellspacing/etc. can be more easily done in a stylesheet even if you are using table layouts; a standards-mode DOCTYPE may prevent some of the worse IE bugs (although, not this old, non-CSS-related one).</p>\n"
},
{
"answer_id": 197342,
"author": "hmcclungiii",
"author_id": 24333,
"author_profile": "https://Stackoverflow.com/users/24333",
"pm_score": -1,
"selected": false,
"text": "<p>You should definitely go with CSS. Tables should NEVER be used for layout.</p>\n"
},
{
"answer_id": 197413,
"author": "Quentin",
"author_id": 19068,
"author_profile": "https://Stackoverflow.com/users/19068",
"pm_score": 0,
"selected": false,
"text": "<p>The choice of Doctype (4.01 Transitional with no system identifier (url)) triggers Quirks mode in IE which makes it highly inconsistent with other browsers.</p>\n\n<p>Switch to:</p>\n\n<pre><code><!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\"\n \"http://www.w3.org/TR/html4/strict.dtd\"></code></pre>\n\n<p>Or at least:</p>\n\n<pre><code><!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\n \"http://www.w3.org/TR/html4/loose.dtd\"></code></pre>\n\n<p>(and, of course, <a href=\"http://validator.w3.org/\" rel=\"nofollow noreferrer\">validate</a> but the HTML and CSS (which would pick the the missing units on your length values)).</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15981/"
] |
Below is the code of a simple html with a table layout.
In FF it's looking as I think it should look like,
in IE7 it doesn't. what am I doing wrong?
And how can I fix it?
```
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<TITLE>test</TITLE>
</head>
<body>
<table id="MainTable" cellspacing="0" cellpadding="0" border="1">
<tbody>
<tr>
<td colspan="4">
<div style='width:769; height:192;'>192
</div>
</td>
</tr>
<tr>
<td colspan="2" valign="top">
<div style='width:383; height:100;'>100
</div>
</td>
<td rowspan="2" valign="top">
<div style='width:190; height:200;'>200
</div>
</td>
<td rowspan="2" valign="top">
<div style='width:190; height:200;'>200
</div>
</td>
</tr>
<tr>
<td valign="top" rowspan="2">
<div style='width:190; height:200;'>200
</div>
</td>
<td valign="top" rowspan="2">
<div style='width:190; height:200;'>200
</div>
</td>
</tr>
<tr>
<td valign="top">
<div style='width:190; height:100;'>100
</div>
</td>
<td valign="top" >
<div style='width:190; height:100;'>100
</div>
</td>
</tr>
<tr>
<td colspan="2">
<div style='width:383; height:100;'>100
</div>
</td>
<td colspan="2">
<div style='width:383; height:100;'>100
</div>
</td>
</tr>
<tr>
<td>
<div style='width:190; height:100;'>100
</div>
</td>
<td>
<div style='width:190; height:100;'>100
</div>
</td>
<td colspan="2">
<div style='width:383; height:100;'>100
</div>
</td>
</tr>
</tbody>
</table>
</body>
</html>
```
|
I assume you are complaining about the minimal height of the middle row (the one containing only rowspanned cells), and the enlarged height of the adjacent rows to compensate, leaving gaps between the divs.
IE cannot calculate optimal row heights when the row contains only rowspanned cells. The usual solution when you absolutely cannot rejig it to get rid of the rowspan is to add a 1px 'dummy' column to one side of the table, containing empty cells, each with the 'height' set to how high the row should be.
But yes, depending on what you're planning to do with this, a CSS layout may well be more appropriate. If it's really a fixed-pixels-for-everything layout like this example, absolute positioning for each div will be a lot, lot easier.
Other bits: CSS width/height values require units (presumably 'px'); valign/cellspacing/etc. can be more easily done in a stylesheet even if you are using table layouts; a standards-mode DOCTYPE may prevent some of the worse IE bugs (although, not this old, non-CSS-related one).
|
197,291 |
<p>Given a table (mytable) containing a numeric field (mynum), how would one go about writing an SQL query which summarizes the table's data based on ranges of values in that field rather than each distinct value?</p>
<p>For the sake of a more concrete example, let's make it intervals of 3 and just "summarize" with a count(*), such that the results tell the number of rows where mynum is 0-2.99, the number of rows where it's 3-5.99, where it's 6-8.99, etc.</p>
|
[
{
"answer_id": 197300,
"author": "Jouni K. Seppänen",
"author_id": 26575,
"author_profile": "https://Stackoverflow.com/users/26575",
"pm_score": 5,
"selected": true,
"text": "<p>The idea is to compute some function of the field that has constant value within each group you want:</p>\n\n<pre><code>select count(*), round(mynum/3.0) foo from mytable group by foo;\n</code></pre>\n"
},
{
"answer_id": 197325,
"author": "ila",
"author_id": 1178,
"author_profile": "https://Stackoverflow.com/users/1178",
"pm_score": 3,
"selected": false,
"text": "<p>I do not know if this is applicable to mySql, anyway in SQL Server I think you can \"simply\" use group by in both the select list AND the group by list.</p>\n\n<p>Something like:</p>\n\n<pre><code>select \n CASE \n WHEN id <= 20 THEN 'lessthan20' \n WHEN id > 20 and id <= 30 THEN '20and30' ELSE 'morethan30' END,\n count(*) \nfrom Profiles \nwhere 1=1 \ngroup by \n CASE \n WHEN id <= 20 THEN 'lessthan20' \n WHEN id > 20 and id <= 30 THEN '20and30' ELSE 'morethan30' END\n</code></pre>\n\n<p>returns something like</p>\n\n<pre><code> column1 column2 \n ---------- ---------- \n 20and30 3 \n lessthan20 3 \n morethan30 13 \n</code></pre>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18914/"
] |
Given a table (mytable) containing a numeric field (mynum), how would one go about writing an SQL query which summarizes the table's data based on ranges of values in that field rather than each distinct value?
For the sake of a more concrete example, let's make it intervals of 3 and just "summarize" with a count(\*), such that the results tell the number of rows where mynum is 0-2.99, the number of rows where it's 3-5.99, where it's 6-8.99, etc.
|
The idea is to compute some function of the field that has constant value within each group you want:
```
select count(*), round(mynum/3.0) foo from mytable group by foo;
```
|
197,294 |
<p>I have a simple lambda expression which runs fine as a UNIT test and also runs fine when I copy the code into the Main method of my application. However, when I run the same piece of code within a callback method (via JMS courier) I get the above error. Has anyone encountered this?</p>
<p>Example code failing:</p>
<pre><code>Expression<Func<JupiterDividend, bool>> expr = v => true;
expr.Compile(); // This is what fails
</code></pre>
|
[
{
"answer_id": 197352,
"author": "leppie",
"author_id": 15541,
"author_profile": "https://Stackoverflow.com/users/15541",
"pm_score": 2,
"selected": false,
"text": "<p>You will normally get this sort of error when a ModuleBuilder has already been 'compiled', or a TypeBuilder has already been 'compiled'.</p>\n\n<p>I would check where such things happen. Also, a stack trace may be handy in this case.</p>\n"
},
{
"answer_id": 207770,
"author": "liggett78",
"author_id": 19762,
"author_profile": "https://Stackoverflow.com/users/19762",
"pm_score": -1,
"selected": false,
"text": "<p>There is a bug report <a href=\"https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=338242\" rel=\"nofollow noreferrer\">here</a>, not sure though if it is the same issue that you experience. Apparently this has been fixed in .NET 3.5 SP1.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197294",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I have a simple lambda expression which runs fine as a UNIT test and also runs fine when I copy the code into the Main method of my application. However, when I run the same piece of code within a callback method (via JMS courier) I get the above error. Has anyone encountered this?
Example code failing:
```
Expression<Func<JupiterDividend, bool>> expr = v => true;
expr.Compile(); // This is what fails
```
|
You will normally get this sort of error when a ModuleBuilder has already been 'compiled', or a TypeBuilder has already been 'compiled'.
I would check where such things happen. Also, a stack trace may be handy in this case.
|
197,297 |
<p>I'm writing code that looks similar to this:</p>
<pre><code>public IEnumerable<T> Unfold<T>(this T seed)
{
while (true)
{
yield return [next (T)object in custom sequence];
}
}
</code></pre>
<p>Obviously, this method is never going to return. (The C# compiler silently allows this, while R# gives me the warning <em>"Function never returns"</em>.)</p>
<p>Generally speaking, is it <em>bad</em> design to provide an enumerator that returns an infinite number of items, without supplying a way to stop enumerating?</p>
<p>Are there any special considerations for this scenario? Mem? Perf? Other gotchas?</p>
<p>If we always supply an exit condition, which are the options? E.g:</p>
<ul>
<li>an object of type T that represents the inclusive or exclusive boundary</li>
<li>a <code>Predicate<T> continue</code> (as <code>TakeWhile</code> does)</li>
<li>a count (as <code>Take</code> does)</li>
<li>...</li>
</ul>
<p>Should we rely on users calling <code>Take(...)</code> / <code>TakeWhile(...)</code> after <code>Unfold(...)</code>? (Maybe the preferred option, since it leverages existing Linq knowledge.)</p>
<p>Would you answer this question differently if the code was going to be published in a public API, either as-is (generic) or as a specific implementation of this pattern?</p>
|
[
{
"answer_id": 197299,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": true,
"text": "<p>So long as you document very clearly that the method will never finish iterating (the method itself returns very quickly, of course) then I think it's fine. Indeed, it can make some algorithms much neater. I don't believe there are any significant memory/perf implications - although if you refer to an \"expensive\" object within your iterator, that reference will be captured.</p>\n\n<p>There are always ways of abusing APIs: so long as your docs are clear, I think it's fine.</p>\n"
},
{
"answer_id": 197328,
"author": "Pop Catalin",
"author_id": 4685,
"author_profile": "https://Stackoverflow.com/users/4685",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n <p>\"Generally speaking, is it bad desing\n to provide an enumerator that returns\n an infinite amount of items, without\n supplying a way to stop enumerating?\"</p>\n</blockquote>\n\n<p>The consumer of the code, can <strong>always</strong> stop enumerating (using break for example or other means). If your enumerator returns and infinite sequence, that doesn't mean the client of the enumerator is somehow forced to never break enumeration, actually you can't make an enumerator which is guaranteed to be fully enumerated by a client. </p>\n\n<blockquote>\n <p>Should we rely on users calling\n Take(...) / TakeWhile(...) after\n Unfold(...)? (Maybe the preferred\n option, since it leverages existing\n Linq knowledge.)</p>\n</blockquote>\n\n<p>Yes, as long as you clearly specify in your documentation that the enumerator returns and infinite sequence and breaking of enumeration is the caller's responsibility, everything should be fine.</p>\n\n<p>Returning infinite sequences isn't a bad idea, functional programing languages have done it for a long time now. </p>\n"
},
{
"answer_id": 197343,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 2,
"selected": false,
"text": "<p>I agree with Jon. Compiler transforms your method to class implementing simple state machine that keeps reference to current value (i.e. value that will be returned via Current property). I used this approach several times to simplify code. If you clearly document method's behavior it should work just fine.</p>\n"
},
{
"answer_id": 197366,
"author": "Dan Goldstein",
"author_id": 23427,
"author_profile": "https://Stackoverflow.com/users/23427",
"pm_score": 0,
"selected": false,
"text": "<p>I would not use an infinite enumerator in a public API. C# programmers, myself included, are too used to the foreach loop. This would also be consistent with the .NET Framework; notice how the Enumerable.Range and Enumerable.Repeat methods take an argument to limit the number of items in the Enumerable. Microsoft chose to use Enumerable.Repeat(\" \", 10) instead of Enumerable.Repeat(\" \").Take(10) to avoid the infinite enumeration and I would adhere to their design choices.</p>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11808/"
] |
I'm writing code that looks similar to this:
```
public IEnumerable<T> Unfold<T>(this T seed)
{
while (true)
{
yield return [next (T)object in custom sequence];
}
}
```
Obviously, this method is never going to return. (The C# compiler silently allows this, while R# gives me the warning *"Function never returns"*.)
Generally speaking, is it *bad* design to provide an enumerator that returns an infinite number of items, without supplying a way to stop enumerating?
Are there any special considerations for this scenario? Mem? Perf? Other gotchas?
If we always supply an exit condition, which are the options? E.g:
* an object of type T that represents the inclusive or exclusive boundary
* a `Predicate<T> continue` (as `TakeWhile` does)
* a count (as `Take` does)
* ...
Should we rely on users calling `Take(...)` / `TakeWhile(...)` after `Unfold(...)`? (Maybe the preferred option, since it leverages existing Linq knowledge.)
Would you answer this question differently if the code was going to be published in a public API, either as-is (generic) or as a specific implementation of this pattern?
|
So long as you document very clearly that the method will never finish iterating (the method itself returns very quickly, of course) then I think it's fine. Indeed, it can make some algorithms much neater. I don't believe there are any significant memory/perf implications - although if you refer to an "expensive" object within your iterator, that reference will be captured.
There are always ways of abusing APIs: so long as your docs are clear, I think it's fine.
|
197,302 |
<p>How can I unset variable? For example, PHP has an <code>unset($var)</code> function.</p>
|
[
{
"answer_id": 197306,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 5,
"selected": false,
"text": "<p>You can't. There's no notion of \"unsetting\" a variable. You can set it to a different value - 0, null, whatever's appropriate. Instance/static variables don't even have a concept of whether the variable is set/unset, and local variables only have \"definitely assigned\" or \"not definitely assigned\".</p>\n\n<p>What is it you're trying to achieve?</p>\n"
},
{
"answer_id": 197312,
"author": "gimel",
"author_id": 6491,
"author_profile": "https://Stackoverflow.com/users/6491",
"pm_score": 3,
"selected": false,
"text": "<p>Maybe you'd like to free the <em>object</em> that the variable is referencing:</p>\n\n<pre><code>MyVar = null;\n</code></pre>\n"
},
{
"answer_id": 197326,
"author": "Nico",
"author_id": 22970,
"author_profile": "https://Stackoverflow.com/users/22970",
"pm_score": 6,
"selected": true,
"text": "<p>There is not really an equivalent to \"unset\".</p>\n\n<p>The closest match I know is the use of the <a href=\"http://msdn.microsoft.com/en-us/library/xwth0h0d(VS.80).aspx\" rel=\"noreferrer\">default</a> keyword.</p>\n\n<p>For example:</p>\n\n<pre><code>MyType myvar = default(MyType);\nstring a = default(string);\n</code></pre>\n\n<p>The variable will still be \"set\", but it will have its default value.</p>\n"
},
{
"answer_id": 197327,
"author": "Arry",
"author_id": 26792,
"author_profile": "https://Stackoverflow.com/users/26792",
"pm_score": 4,
"selected": false,
"text": "<p>Generally setting it to null does the job (for variable of types like int you would have to make it a nullable version int?).</p>\n\n<p>If you only want to use the variable for a short period of time in a bigger function you can scope it, like this:</p>\n\n<pre><code>{\n int i = 2;\n}\n</code></pre>\n\n<p>The variable will only last until the closing brace.</p>\n\n<p>If these do not cover your circumstance then can you elaborate on where you need to do this.</p>\n"
},
{
"answer_id": 197335,
"author": "rslite",
"author_id": 15682,
"author_profile": "https://Stackoverflow.com/users/15682",
"pm_score": 2,
"selected": false,
"text": "<p>Value-type variables don't need unset. They are permanently allocated.</p>\n\n<p>For reference-type variables you just set them to <em>null</em> and the garbage collector will destroy the associated object (and free the memory). But note that the variable itself will continue to exist throughout its scope (code block, method, object life, ...)</p>\n\n<p>If you want to use this to free memory then just set all not-needed objects to null and wait for the garbage collector to do its job.</p>\n\n<p><strong>Edit</strong>: As noted in comments I ommited to say that the garbage collector won't start the collection immediately. This will happen usually when the framework tries to allocated memory and can't find enough free. It's possible to start \"manually\" a garbage collection, but it's not advisable and might worsen the behavior of the program. For most purposes the default behavior of the GC should be enough.</p>\n"
},
{
"answer_id": 197340,
"author": "benPearce",
"author_id": 4490,
"author_profile": "https://Stackoverflow.com/users/4490",
"pm_score": 1,
"selected": false,
"text": "<p>For an object you can set it to null, a string is best set to String.Empty, or you can declare a variable as nullable such as:</p>\n\n<pre><code>int? i = null;\n</code></pre>\n"
},
{
"answer_id": 197617,
"author": "Rick Minerich",
"author_id": 9251,
"author_profile": "https://Stackoverflow.com/users/9251",
"pm_score": 1,
"selected": false,
"text": "<p>You could define a scope for that variable. When the scope exits, the variable will no longer be defined:</p>\n\n<pre><code>System.Console.WriteLine(\"let's give this a try: \");\n{\n int j = 0;\n System.Console.WriteLine(j);\n}\n//Won't compile with the following line.\n//System.Console.WriteLine(j);\n</code></pre>\n"
},
{
"answer_id": 720957,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>personally I just go</p>\n\n<p><strong>variable = Nothing</strong></p>\n\n<p>that seems to free up the resources especially when working with mobile phones!</p>\n"
},
{
"answer_id": 27567648,
"author": "Laura",
"author_id": 4378163,
"author_profile": "https://Stackoverflow.com/users/4378163",
"pm_score": 2,
"selected": false,
"text": "<p>To unset environment variable use the same Environment.SetEnvironmentVariable method, but pass null, or string.Empty as a value <a href=\"http://msdn.microsoft.com/en-us/library/96xafkes(v=vs.110).aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/96xafkes(v=vs.110).aspx</a></p>\n\n<blockquote>\n <p>\"If value is empty and the environment variable named by variable exists, the environment variable is deleted.\"</p>\n</blockquote>\n"
},
{
"answer_id": 65674601,
"author": "Starlk",
"author_id": 14974522,
"author_profile": "https://Stackoverflow.com/users/14974522",
"pm_score": -1,
"selected": false,
"text": "<p>I think you need to make it <code>null</code>, and to do so:</p>\n<pre><code>int? Foo = 5;\nFoo = null;\n</code></pre>\n"
}
] |
2008/10/13
|
[
"https://Stackoverflow.com/questions/197302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25413/"
] |
How can I unset variable? For example, PHP has an `unset($var)` function.
|
There is not really an equivalent to "unset".
The closest match I know is the use of the [default](http://msdn.microsoft.com/en-us/library/xwth0h0d(VS.80).aspx) keyword.
For example:
```
MyType myvar = default(MyType);
string a = default(string);
```
The variable will still be "set", but it will have its default value.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.