qid int64 4 19.1M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
354,476 | <p>I need to achieve the following when opening an HTML in Excel <code>(Response.contentType="application/vnd.ms-excel")</code> :</p>
<ul>
<li>force Excel to consider content of td cells as numbers</li>
<li>make the above so that any subsequent user-entered formulas work on these cells (when the spreadsheet is opened)</li>
</ul>
<p>So far I was successful with adding <code>style="vnd.ms-excel.numberformat:0.00"</code> to the td cells in question. The contents of the cells are correctly shown as numbers when I right click on them in the Excel, however the formulas don't work.</p>
<p>If successful, that technique would be quite useful because any web Excel report could be user enhanced with appropriate formulas according to custom requirements. Thanks in advance.</p>
| [
{
"answer_id": 354574,
"author": "scunliffe",
"author_id": 6144,
"author_profile": "https://Stackoverflow.com/users/6144",
"pm_score": 5,
"selected": false,
"text": ".num {\n mso-number-format:General;\n}\n.date {\n mso-number-format:\"Short Date\";\n}\n <td class=\"num\">34</td>\n<td class=\"num\">17.0</td>\n<td class=\"date\">12/17/2008</td> <!-- if you are playing with dates too -->\n"
},
{
"answer_id": 12709340,
"author": "Mayank Pathak",
"author_id": 1490287,
"author_profile": "https://Stackoverflow.com/users/1490287",
"pm_score": 2,
"selected": false,
"text": "css class Style TD style=\"mso-number-format:\\@;\"\n mso-number-format:General\n"
},
{
"answer_id": 31553487,
"author": "Andy Castles",
"author_id": 335886,
"author_profile": "https://Stackoverflow.com/users/335886",
"pm_score": 1,
"selected": false,
"text": "<td x:num>123</td>"
},
{
"answer_id": 63322870,
"author": "ElayaRaja Sambasivam",
"author_id": 14074003,
"author_profile": "https://Stackoverflow.com/users/14074003",
"pm_score": -1,
"selected": false,
"text": "mso-number-format:0 NO Decimals\nmso-number-format:\"\\#\\,\\#\\#0\\.000\" 3 Decimals \nmso-number-format:\"mm\\/dd\\/yy\" Thousand comma with 3 decimals \nmso-number-format:\"mmmm\\\\ d\\\\\\,\\\\ yyyy\" Date7 \nmso-number-format:\"m\\/d\\/yy\\\\ h\\:mm\\\\ AM\\/PM\" Date9 \n \"<td style=\\\"mso-number-format:'\\@'\\\">\"\n <td style=\"mso-number-format:'\\@'\">\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
354,477 | <p>What's the best way, using C# or other .NET language, to determine if a file path string is on the local machine or a remote server?</p>
<p>It's possible to determine if a path string is UNC using the following:</p>
<pre><code>new Uri(path).IsUnc
</code></pre>
<p>That works great for paths that start with C:\ or other drive letter, but what about paths like:</p>
<pre><code>\\machinename\sharename\directory
\\10.12.34.56\sharename\directory
</code></pre>
<p>...where both refer to the local machine - these are UNC paths but are still local.</p>
| [
{
"answer_id": 354558,
"author": "tbetts42",
"author_id": 44770,
"author_profile": "https://Stackoverflow.com/users/44770",
"pm_score": 0,
"selected": false,
"text": "Host string hostName = System.Net.Dns.GetHostName()\n System.Net.IPAddress[] addresses = System.Net.Dns.GetHostAddresses(hostName);\n HostNameType UriHostNameType.Dns UriHostNameType.IPv4"
},
{
"answer_id": 354585,
"author": "Eric Rosenberger",
"author_id": 41624,
"author_profile": "https://Stackoverflow.com/users/41624",
"pm_score": 5,
"selected": true,
"text": " IPAddress[] host;\n IPAddress[] local;\n bool isLocal = false;\n\n host = Dns.GetHostAddresses(uri.Host);\n local = Dns.GetHostAddresses(Dns.GetHostName());\n\n foreach (IPAddress hostAddress in host)\n {\n if (IPAddress.IsLoopback(hostAddress))\n {\n isLocal = true;\n break;\n }\n else\n {\n foreach (IPAddress localAddress in local)\n {\n if (hostAddress.Equals(localAddress))\n {\n isLocal = true;\n break;\n }\n }\n\n if (isLocal)\n {\n break;\n }\n }\n }\n"
},
{
"answer_id": 4432346,
"author": "Renato Heeb",
"author_id": 374988,
"author_profile": "https://Stackoverflow.com/users/374988",
"pm_score": 5,
"selected": false,
"text": " public static bool IsLocal(DirectoryInfo dir)\n {\n foreach (DriveInfo d in DriveInfo.GetDrives())\n {\n if (string.Compare(dir.Root.FullName, d.Name, StringComparison.OrdinalIgnoreCase) == 0) //[drweb86] Fix for different case.\n {\n return (d.DriveType != DriveType.Network);\n }\n }\n throw new DriveNotFoundException();\n }\n"
},
{
"answer_id": 7268316,
"author": "David",
"author_id": 905783,
"author_profile": "https://Stackoverflow.com/users/905783",
"pm_score": 4,
"selected": false,
"text": " private bool IsLocalHost(string input)\n {\n IPAddress[] host;\n //get host addresses\n try { host = Dns.GetHostAddresses(input); }\n catch (Exception) { return false; }\n //get local adresses\n IPAddress[] local = Dns.GetHostAddresses(Dns.GetHostName()); \n //check if local\n return host.Any(hostAddress => IPAddress.IsLoopback(hostAddress) || local.Contains(hostAddress));\n }\n"
},
{
"answer_id": 19810527,
"author": "user1471935",
"author_id": 1471935,
"author_profile": "https://Stackoverflow.com/users/1471935",
"pm_score": 0,
"selected": false,
"text": "var isLocal = Dns.GetHostName() == _host || Dns.GetHostEntry(Dns.GetHostName()).AddressList.Any(i => i.ToString().Equals(_host));\n"
},
{
"answer_id": 20671816,
"author": "Stephen",
"author_id": 3117427,
"author_profile": "https://Stackoverflow.com/users/3117427",
"pm_score": 3,
"selected": false,
"text": "private static bool IsLocalPath(String path)\n{\n if (!PathIsUNC(path))\n {\n return !PathIsNetworkPath(path);\n }\n\n Uri uri = new Uri(path);\n return IsLocalHost(uri.Host); // Refer to David's answer\n}\n\n[DllImport(\"Shlwapi.dll\")]\n[return: MarshalAs(UnmanagedType.Bool)]\nstatic extern bool PathIsNetworkPath(String pszPath);\n\n[DllImport(\"Shlwapi.dll\")]\n[return: MarshalAs(UnmanagedType.Bool)]\nstatic extern bool PathIsUNC(String pszPath);\n"
},
{
"answer_id": 21885960,
"author": "Art",
"author_id": 3328922,
"author_profile": "https://Stackoverflow.com/users/3328922",
"pm_score": 3,
"selected": false,
"text": " internal static bool IsFileRemote(string path)\n {\n if (String.IsNullOrEmpty(path))\n {\n return false;\n }\n if (new Uri(path).IsUnc)\n {\n return true;\n }\n if (new DriveInfo(path).DriveType == DriveType.Network)\n {\n return true;\n }\n return false;\n }\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10039/"
] |
354,490 | <p>As per <a href="http://www.gnu.org/software/emacs/manual/html_node/emacs/File-Names.html" rel="noreferrer">the Emacs docs</a>, every time you open a file, Emacs changes <code>default-directory</code> to the directory containing that file. </p>
<p>Then, if the cursor is in that buffer and you (for example) start SLIME, it uses <code>default-directory</code> as the current working directory for SLIME. If you try to open a new file, it opens the file with <code>default-directory</code> as your starting point.</p>
<p>I want to be able to <code>M-x cd</code> or otherwise <code>cd</code> to a directory, and then never have Emacs change my current working directory to anything but that directory until I tell it otherwise. I want this to be global across all buffers, so that any time I'm doing something involving the current working directory, I know what it's set to regardless of where my cursor is at the moment. Is there a way to do this?</p>
| [
{
"answer_id": 354654,
"author": "link0ff",
"author_id": 23952,
"author_profile": "https://Stackoverflow.com/users/23952",
"pm_score": 5,
"selected": true,
"text": "(add-hook 'find-file-hook\n (lambda ()\n (setq default-directory command-line-default-directory)))\n"
},
{
"answer_id": 376184,
"author": "link0ff",
"author_id": 23952,
"author_profile": "https://Stackoverflow.com/users/23952",
"pm_score": 2,
"selected": false,
"text": "((nil . ((default-directory . \"~/.emacs.d/\"))))\n"
},
{
"answer_id": 455703,
"author": "Brian Carper",
"author_id": 23070,
"author_profile": "https://Stackoverflow.com/users/23070",
"pm_score": 2,
"selected": false,
"text": "(defun find-file-save-directory ()\n (interactive)\n (setq saved-default-directory default-directory)\n (ido-find-file)\n (setq default-directory saved-default-directory))\n(global-set-key \"\\C-x\\C-f\" 'find-file-save-directory)\n default-directory C-x C-f"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23070/"
] |
354,526 | <p>I have two files with slight differences. A normal <code>diff</code> will show me the differences between the files. With <code>-c</code> or <code>-u</code> I can add an amount of context to each hunk. What options can I pass to <code>diff</code> to see every unchanged line alongside the changes, and get the diff as a single, large hunk?</p>
| [
{
"answer_id": 354552,
"author": "madlep",
"author_id": 14160,
"author_profile": "https://Stackoverflow.com/users/14160",
"pm_score": 6,
"selected": true,
"text": "* Lorem ipsum dolor sit amet, consectetuer adipiscing elit. * Lorem ipsum dolor sit amet, consectetuer adipiscing elit.\n* Praesent fringilla facilisis pede. * Praesent fringilla facilisis pede.\n* Nulla sit amet tellus id massa luctus pellentesque. * Nulla sit amet tellus id massa luctus pellentesque.\n* Pellentesque a neque nec elit aliquam congue. * Pellentesque a neque nec elit aliquam congue.\n* Quisque rhoncus ultricies elit. * Quisque rhoncus ultricies elit.\n* Pellentesque laoreet urna id arcu. * Pellentesque laoreet urna id arcu.\n* Aenean non erat et elit egestas dictum. * Aenean non erat et elit egestas dictum.\n* Proin ornare sem eget nulla. * Proin ornare sem eget nulla.\n* Phasellus placerat convallis elit. * Phasellus placerat convallis elit.\n* Donec ultricies metus non purus. * Donec ultricies metus non purus.\n* Sed vel enim et nunc accumsan egestas. * Sed vel enim et nunc accumsan egestas.\n* Cras eget elit in purus luctus ornare. * Cras eget elit in purus luctus ornare.\n* In pharetra ligula sodales pede. <\n* Morbi consectetuer mi vitae sem. * Morbi consectetuer mi vitae sem.\n* Donec sollicitudin pretium erat. * Donec sollicitudin pretium erat.\n* Cras facilisis nunc sed leo. * Cras facilisis nunc sed leo.\n* Nunc varius ante sed nisi. * Nunc varius ante sed nisi.\n > THIS SHOULDN'T BE HERE\n > THIS SHOULDN'T EITHER!\n* Aenean in quam sagittis est ornare ultricies. * Aenean in quam sagittis est ornare ultricies.\n* Etiam dignissim scelerisque velit. * Etiam dignissim scelerisque velit.\n* Mauris porta fringilla sapien. * Mauris porta fringilla sapien.\n* Proin vitae nisl vitae mauris viverra tempor. * Proin vitae nisl vitae mauris viverra tempor.\n* Maecenas quis arcu sed lorem mollis bibendum. * Maecenas quis arcu sed lorem mollis bibendum.\n* Morbi sed turpis non risus molestie posuere. | * Morbi sed non risus molestie posuere.\n* Curabitur id magna in nulla commodo tristique. * Curabitur id magna in nulla commodo tristique.\n* Praesent quis nulla vel augue faucibus viverra. | * Praesent quis nulla BAD vel augue faucibus viverra.\n* Sed interdum libero. | * Sed lacinia interdum libero.\n > ANOTHER ADDITION\n* Donec ultricies posuere arcu. * Donec ultricies posuere arcu.\n* Etiam interdum auctor mi. * Etiam interdum auctor mi.\n"
},
{
"answer_id": 354590,
"author": "Alex B",
"author_id": 6180,
"author_profile": "https://Stackoverflow.com/users/6180",
"pm_score": 5,
"selected": false,
"text": "diff --new-line-format='+%L' --old-line-format='-%L' --unchanged-line-format=' %L' file1 file2\n diff -u file1 file2"
},
{
"answer_id": 47546781,
"author": "Martin Monperrus",
"author_id": 1153476,
"author_profile": "https://Stackoverflow.com/users/1153476",
"pm_score": 5,
"selected": false,
"text": "diff -U 1000000 file1.txt file2.txt\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354526",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4937/"
] |
354,547 | <p>When I'm running a simple Ruby script, what's the easiest way to dump an object's fields to the console? </p>
<p>I'm looking for something similar to PHP's <code>print_r()</code> that will work with arrays as well.</p>
| [
{
"answer_id": 354578,
"author": "Christian Lescuyer",
"author_id": 341,
"author_profile": "https://Stackoverflow.com/users/341",
"pm_score": 10,
"selected": true,
"text": "puts variable.inspect\n"
},
{
"answer_id": 354624,
"author": "dylanfm",
"author_id": 38795,
"author_profile": "https://Stackoverflow.com/users/38795",
"pm_score": 6,
"selected": false,
"text": "methods print_r >> \"Hello\".methods.sort\n=> [\"%\", \"*\", \"+\", \"<\", \"<<\", \"<=\", \"<=>\", \"==\", \"===\", \"=~\", \">\", \">=\", \"[]\", \"[]=\", \"__id__\", \"__send__\", \"all?\", \"any?\", \"between?\", \"capitalize\", \"capitalize!\", \"casecmp\", \"center\", \"chomp\", \"chomp!\", \"chop\", \"chop!\", \"class\", \"clone\", \"collect\", \"concat\", \"count\", \"crypt\", \"delete\", \"delete!\", \"detect\", \"display\", \"downcase\", \"downcase!\", \"dump\", \"dup\", \"each\", \"each_byte\", \"each_line\", \"each_with_index\", \"empty?\", \"entries\", \"eql?\", \"equal?\", \"extend\", \"find\", \"find_all\", \"freeze\", \"frozen?\", \"grep\", \"gsub\", \"gsub!\", \"hash\", \"hex\", \"id\", \"include?\", \"index\", \"inject\", \"insert\", \"inspect\", \"instance_eval\", \"instance_of?\", \"instance_variable_defined?\", \"instance_variable_get\", \"instance_variable_set\", \"instance_variables\", \"intern\", \"is_a?\", \"is_binary_data?\", \"is_complex_yaml?\", \"kind_of?\", \"length\", \"ljust\", \"lstrip\", \"lstrip!\", \"map\", \"match\", \"max\", \"member?\", \"method\", \"methods\", \"min\", \"next\", \"next!\", \"nil?\", \"object_id\", \"oct\", \"partition\", \"private_methods\", \"protected_methods\", \"public_methods\", \"reject\", \"replace\", \"respond_to?\", \"reverse\", \"reverse!\", \"rindex\", \"rjust\", \"rstrip\", \"rstrip!\", \"scan\", \"select\", \"send\", \"singleton_methods\", \"size\", \"slice\", \"slice!\", \"sort\", \"sort_by\", \"split\", \"squeeze\", \"squeeze!\", \"strip\", \"strip!\", \"sub\", \"sub!\", \"succ\", \"succ!\", \"sum\", \"swapcase\", \"swapcase!\", \"taguri\", \"taguri=\", \"taint\", \"tainted?\", \"to_a\", \"to_f\", \"to_i\", \"to_s\", \"to_str\", \"to_sym\", \"to_yaml\", \"to_yaml_properties\", \"to_yaml_style\", \"tr\", \"tr!\", \"tr_s\", \"tr_s!\", \"type\", \"unpack\", \"untaint\", \"upcase\", \"upcase!\", \"upto\", \"zip\"]\n"
},
{
"answer_id": 355017,
"author": "rampion",
"author_id": 9859,
"author_profile": "https://Stackoverflow.com/users/9859",
"pm_score": 5,
"selected": false,
"text": "p object\n p p(*args) public"
},
{
"answer_id": 1528759,
"author": "mjs",
"author_id": 11543,
"author_profile": "https://Stackoverflow.com/users/11543",
"pm_score": 6,
"selected": false,
"text": "to_yaml $foo = {:name => \"Clem\", :age => 43}\n\nputs $foo.to_yaml\n --- \n:age: 43\n:name: Clem\n YAML"
},
{
"answer_id": 14321293,
"author": "Mike",
"author_id": 991251,
"author_profile": "https://Stackoverflow.com/users/991251",
"pm_score": 4,
"selected": false,
"text": "obj.instance_variables.each do |var|\n puts [var, obj.instance_variable_get(var).inspect].join(\":\")\nend\n obj.instance_variables.each{ |var| puts [var, obj.instance_variable_get(var).inspect].join(\":\")}\n"
},
{
"answer_id": 30631498,
"author": "Conor",
"author_id": 3348716,
"author_profile": "https://Stackoverflow.com/users/3348716",
"pm_score": 2,
"selected": false,
"text": "object.attribute_names\n\n# => [\"id\", \"name\", \"email\", \"created_at\", \"updated_at\", \"password_digest\", \"remember_token\", \"admin\", \"marketing_permissions\", \"terms_and_conditions\", \"disable\", \"black_list\", \"zero_cost\", \"password_reset_token\", \"password_reset_sent_at\"]\n\n\nobject.attributes.values\n\n# => [1, \"tom\", \"tom@tom.com\", Tue, 02 Jun 2015 00:16:03 UTC +00:00, Tue, 02 Jun 2015 00:22:35 UTC +00:00, \"$2a$10$gUTr3lpHzXvCDhVvizo8Gu/MxiTrazOWmOQqJXMW8gFLvwDftF9Lm\", \"2dd1829c9fb3af2a36a970acda0efe5c1d471199\", true, nil, nil, nil, nil, nil, nil, nil] \n"
},
{
"answer_id": 40649897,
"author": "ROMANIA_engineer",
"author_id": 3885376,
"author_profile": "https://Stackoverflow.com/users/3885376",
"pm_score": 3,
"selected": false,
"text": "require 'json'\n...\nputs JSON.pretty_generate(JSON.parse(object.to_json))\n"
},
{
"answer_id": 45239513,
"author": "Gregor",
"author_id": 6412456,
"author_profile": "https://Stackoverflow.com/users/6412456",
"pm_score": 3,
"selected": false,
"text": "object.to_hash"
},
{
"answer_id": 67189003,
"author": "QETHAN",
"author_id": 2280031,
"author_profile": "https://Stackoverflow.com/users/2280031",
"pm_score": 0,
"selected": false,
"text": "#<File::Stat\n dev=0x1000004,\n ino=71426291,\n mode=041777 (directory rwxrwxrwt),\n nlink=15,\n uid=0 (root),\n gid=0 (wheel),\n rdev=0x0 (0, 0),\n size=480,\n blksize=4096,\n blocks=0,\n atime=2021-04-20 17:50:33.062419819 +0800 (1618912233),\n mtime=2021-04-21 11:35:32.808546288 +0800 (1618976132),\n ctime=2021-04-21 11:35:32.808546288 +0800 (1618976132)>\n"
},
{
"answer_id": 68126187,
"author": "Igor Kasyanchuk",
"author_id": 929251,
"author_profile": "https://Stackoverflow.com/users/929251",
"pm_score": 0,
"selected": false,
"text": "user.wp puts \"-\"*10\nputs user.inspect\nputs \"-\"*10\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354547",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/270/"
] |
354,556 | <p>I often want to trigger a certain function just once, but I need to trigger it from within another function that gets repeatedly called. For instance, taking a snapshot of something for later use. I usually do it by setting a global boolean.</p>
<p>I'm wondering whether the way I do it is actually best way? </p>
<p>I seem to recall reading that global variables are bad, and global boolean variables are even worse!</p>
<p>Anyway, this is how I usually accomplish triggering a certain method just once:</p>
<p>In my initial set of variables...</p>
<pre><code>private var myStatus:Boolean = false;
</code></pre>
<p>Then, within the function that gets called often...</p>
<pre><code>if (!myStatus) {
doMyFunction();
myStatus = true;
}
</code></pre>
<p>It seems fairly logical to me, but is it <em>the right thing</em>?</p>
<p><strong>UPDATE</strong>: Well, based on what I learned from your answers, instead of checking a global boolean variable, I now first check whether the XML node exists (I am storing the images within an XML structure before any writing to disk occurs), and, if it doesn't, then I append a new node with the base64 encoded image data. I do still set a boolean flag so that later on I can overwrite the blank image with user edited image data if need be. It works perfectly. Thank you all for your help!</p>
<p>I also now feel more comfortable about using that particular (thread unsafe) system in certain situations.</p>
| [
{
"answer_id": 354573,
"author": "Ned Batchelder",
"author_id": 14343,
"author_profile": "https://Stackoverflow.com/users/14343",
"pm_score": 3,
"selected": false,
"text": "doMyFunction myStatus doMyFunction if (!myStatus) {\n myStatus = true;\n doMyFunction();\n}\n"
},
{
"answer_id": 354582,
"author": "Todd Gamblin",
"author_id": 9122,
"author_profile": "https://Stackoverflow.com/users/9122",
"pm_score": 2,
"selected": false,
"text": "void doMyFunction() {\n // gets called only once.\n // side effects go here.\n}\n\nvoid functionThatGetsCalledALot() {\n static bool called = false;\n if (!called) {\n doMyFunction();\n called = true;\n }\n // do more stuff\n}\n"
},
{
"answer_id": 357395,
"author": "Brad Gilbert",
"author_id": 1337,
"author_profile": "https://Stackoverflow.com/users/1337",
"pm_score": 0,
"selected": false,
"text": "state use 5.010;\n\nsub test{\n state $once = 1;\n\n if( $once ){\n $once = undef;\n say 'first';\n } else {\n say 'not first';\n }\n}\n\ntest for 1..5;\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10875/"
] |
354,568 | <p>In C#, I'm creating an XML file from a DataTable using dataTable.WriteXml(filePath), and get the following:</p>
<pre><code><?xml version="1.0" encoding="utf-8" ?>
<ExperienceProfiles>
<ExperienceProfile>
<Col1>blah</Col1>
<Col2>4ed397bf-a4d5-4ace-9d44-8c1a5cdb0f34</Col2>
</ExperienceProfile>
</ExperienceProfiles>
</code></pre>
<p>How can I get it to write the XML in the following format?:</p>
<pre><code><?xml version="1.0" encoding="utf-8" ?>
<ExperienceProfiles>
<ExperienceProfile Col1="blah"
Col2="blah" ></ExperienceProfile>
</ExperienceProfiles>
</code></pre>
| [
{
"answer_id": 1458913,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "column.ColumnMapping = MappingType.Attribute\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354568",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33185/"
] |
354,587 | <p><strong>Update</strong> - for those of a facetious frame of mind, you can assume that Aggregate still produces the normal result whatever function is passed to it, including in the case being optimized.</p>
<p>I wrote this program to build a long string of integers from 0 to 19999 separate by commas.</p>
<pre><code>using System;
using System.Linq;
using System.Diagnostics;
namespace ConsoleApplication5
{
class Program
{
static void Main(string[] args)
{
const int size = 20000;
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
Enumerable.Range(0, size).Select(n => n.ToString()).Aggregate((a, b) => a + ", " + b);
stopwatch.Stop();
Console.WriteLine(stopwatch.ElapsedMilliseconds + "ms");
}
}
}
</code></pre>
<p>When I run it, it says:</p>
<pre><code>5116ms
</code></pre>
<p>Over five seconds, terrible. Of course it's because the whole string is being copied each time around the loop.</p>
<p>But what if make one very small change indicated by the comment?</p>
<pre><code>using System;
using System.Linq;
using System.Diagnostics;
namespace ConsoleApplication5
{
using MakeAggregateGoFaster; // <---- inserted this
class Program
{
static void Main(string[] args)
{
const int size = 20000;
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
Enumerable.Range(0, size).Select(n => n.ToString()).Aggregate((a, b) => a + ", " + b);
stopwatch.Stop();
Console.WriteLine(stopwatch.ElapsedMilliseconds + "ms");
}
}
}
</code></pre>
<p>Now when I run it, it says:</p>
<pre><code>42ms
</code></pre>
<p>Over 100x faster.</p>
<h3>Question</h3>
<p>What's in the MakeAggregateGoFaster namespace?</p>
<p><strong>Update 2:</strong> <a href="http://incrediblejourneysintotheknown.blogspot.com/2008/12/optimizing-aggregate-for-string.html" rel="noreferrer">Wrote up my answer here</a>.</p>
| [
{
"answer_id": 354594,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 2,
"selected": false,
"text": "namespace MakeAggregateGoFaster\n{\n public static class Extensions\n {\n public static String Aggregate(this IEnumerable<String> source, Func<String, String, String> fn)\n {\n StringBuilder sb = new StringBuilder();\n foreach (String s in source)\n {\n if (sb.Length > 0)\n sb.Append(\", \");\n sb.Append(s);\n }\n\n return sb.ToString();\n }\n }\n}\n"
},
{
"answer_id": 354596,
"author": "Jimmy",
"author_id": 4435,
"author_profile": "https://Stackoverflow.com/users/4435",
"pm_score": 3,
"selected": false,
"text": "string.Join(\", \",Enumerable.Range(0, size).Select(n => n.ToString()).ToArray())\n"
},
{
"answer_id": 354616,
"author": "mackenir",
"author_id": 25457,
"author_profile": "https://Stackoverflow.com/users/25457",
"pm_score": 5,
"selected": true,
"text": "IEnumerable<string> Expression<Func<string, string, string>> Func<string, string, string>"
},
{
"answer_id": 354627,
"author": "Jimmy",
"author_id": 4435,
"author_profile": "https://Stackoverflow.com/users/4435",
"pm_score": 2,
"selected": false,
"text": "public static string Aggregate(this IEnumerable<string> l, Func<string, string, string> f) {\n return \"\";\n}\n public static string Aggregate(this IEnumerable<string> l, Func<string, string, string> f) {\n StringBuilder sb = new StringBuilder();\n foreach (string item in l)\n sb.Append(\", \").Append(item);\n return sb.Remove(0,2).ToString();\n}\n"
},
{
"answer_id": 443880,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "Enumerable.Range(0, size ).Aggregate(new StringBuilder(),\n (a, b) => a.Append(\", \" + b.ToString()),\n (a) => a.Remove(0,2).ToString());\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27423/"
] |
354,599 | <p>Looking to get a list of all the files (commit comments would be nice too) of a user in cvs. </p>
| [
{
"answer_id": 354611,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 5,
"selected": true,
"text": "cvs log -t -wJellyJoe\n"
},
{
"answer_id": 354618,
"author": "Alex B",
"author_id": 6180,
"author_profile": "https://Stackoverflow.com/users/6180",
"pm_score": 2,
"selected": false,
"text": "cvs log | egrep -A 1 'Working file|username'\n Working file: bin/scriptname\nhead: 1.14\n--\ndate: 2008/01/01 15:15:30; author: username; state: Exp; lines +3 -2\nFirst line of checkin comment will appear here.\n"
},
{
"answer_id": 474309,
"author": "Sally",
"author_id": 6539,
"author_profile": "https://Stackoverflow.com/users/6539",
"pm_score": 3,
"selected": false,
"text": "cvs history -a -c -D 2009-01-20\n"
},
{
"answer_id": 550604,
"author": "Yonatan Broza",
"author_id": 33463,
"author_profile": "https://Stackoverflow.com/users/33463",
"pm_score": 4,
"selected": false,
"text": "cvs -q log -N -S -wuser dir/\n -N -S -w[logins] cvs -H log\n"
},
{
"answer_id": 16296097,
"author": "Christoph",
"author_id": 2335228,
"author_profile": "https://Stackoverflow.com/users/2335228",
"pm_score": 4,
"selected": false,
"text": "cvs history -u user -c -D 2009-01-20\ncvs history -u user -l -c -D 2009-01-20\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
354,610 | <p>Can anyone guide me in the correct way to build a colored bubble/circle programmatically?</p>
<p>I can't use images as I need it to be able to be any color depending on user interaction.</p>
<p>My thought was maybe to make a white circle image and then overlay a color on top of it.
However I am not sure if this would work, or how to really go about it.</p>
<p>If someone could point me the right direction I would appreciate it.</p>
| [
{
"answer_id": 354635,
"author": "Marc Charbonneau",
"author_id": 35136,
"author_profile": "https://Stackoverflow.com/users/35136",
"pm_score": 4,
"selected": true,
"text": "[myColor set] [myPath fill]"
},
{
"answer_id": 354677,
"author": "joshperry",
"author_id": 30587,
"author_profile": "https://Stackoverflow.com/users/30587",
"pm_score": 5,
"selected": false,
"text": "NSRect rect = NSMakeRect(10, 10, 10, 10);\nNSBezierPath* circlePath = [NSBezierPath bezierPath];\n[circlePath appendBezierPathWithOvalInRect: rect];\n [[NSColor blackColor] setStroke];\n[[NSColor redColor] setFill];\n [path stroke];\n[path fill];\n - (void)drawRect:(NSRect)rect\n{\n // Get the graphics context that we are currently executing under\n NSGraphicsContext* gc = [NSGraphicsContext currentContext];\n\n // Save the current graphics context settings\n [gc saveGraphicsState];\n\n // Set the color in the current graphics context for future draw operations\n [[NSColor blackColor] setStroke];\n [[NSColor redColor] setFill];\n\n // Create our circle path\n NSRect rect = NSMakeRect(10, 10, 10, 10);\n NSBezierPath* circlePath = [NSBezierPath bezierPath];\n [circlePath appendBezierPathWithOvalInRect: rect];\n\n // Outline and fill the path\n [circlePath stroke];\n [circlePath fill];\n\n // Restore the context to what it was before we messed with it\n [gc restoreGraphicsState];\n}\n"
},
{
"answer_id": 7725089,
"author": "Sorted",
"author_id": 952701,
"author_profile": "https://Stackoverflow.com/users/952701",
"pm_score": 3,
"selected": false,
"text": " CGContextRef c = UIGraphicsGetCurrentContext();\n CGContextSetRGBFillColor(c, 40, 0, 255, 0.1);\n CGContextSetRGBStrokeColor(c, 0, 40, 255, 0.5);\n\n // Draw a green solid circle\n CGContextSetRGBFillColor(c, 0, 255, 0, 1);\n CGContextFillEllipseInRect(c, CGRectMake(100, 100, 25, 25));\n"
},
{
"answer_id": 13785927,
"author": "Almas Adilbek",
"author_id": 320018,
"author_profile": "https://Stackoverflow.com/users/320018",
"pm_score": 4,
"selected": false,
"text": "UIView radius // Add framework CoreGraphics.framework\n#import <QuartzCore/QuartzCore.h>\n\n-(UIView *)circleWithColor:(UIColor *)color radius:(int)radius {\n UIView *circle = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 2 * radius, 2 * radius)];\n circle.backgroundColor = color;\n circle.layer.cornerRadius = radius;\n circle.layer.masksToBounds = YES;\n return circle;\n}\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354610",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26728/"
] |
354,613 | <p>How can I convert a bitmap to a byte array in c++ WITHOUT the .net framework?</p>
| [
{
"answer_id": 354621,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 4,
"selected": true,
"text": "GetDIBits"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37875/"
] |
354,639 | <p>How do I check the type of a value on runtime?</p>
<p>I'd like to find out where I'm creating doubles.</p>
| [
{
"answer_id": 354855,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": true,
"text": "[myObject isKindOfClass: [InterestingClass class]]"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36182/"
] |
354,640 | <p>Suppose we have <em>n</em> elements, <em>a</em><sub>1</sub>, <em>a</em><sub>2</sub>, ..., <em>a</em><sub>n</sub>, arranged in a circle. That is, <em>a</em><sub>2</sub> is between <em>a</em><sub>1</sub> and <em>a</em><sub>3</sub>, <em>a</em><sub>3</sub> is between <em>a</em><sub>2</sub> and <em>a</em><sub>4</sub>, <em>a</em><sub><em>n</em></sub> is between <em>a</em><sub><em>n</em>-1</sub> and <em>a</em><sub>1</sub>, and so forth.</p>
<p>Each element can take the value of either 1 or 0. Two arrangements are different if there are corresponding <em>a</em><sub><em>i</em></sub>'s whose values differ. For instance, when <em>n</em>=3, (1, 0, 0) and (0, 1, 0) are different arrangements, even though they may be isomorphic under rotation or reflection.</p>
<p>Because there are <em>n</em> elements, each of which can take two values, the total number of arrangements is 2<sup><em>n</em></sup>.</p>
<p><strong>Here is the question:</strong></p>
<p>How many arrangements are possible, such that no two adjacent elements both have the value 1? If it helps, only consider cases where <em>n</em>>3. </p>
<p>I ask here for several reasons:</p>
<ol>
<li>This arose while I was solving a programming problem</li>
<li>It sounds like the problem may benefit from Boolean logic/bit arithmetic</li>
<li>Maybe there is no closed solution.</li>
</ol>
| [
{
"answer_id": 354701,
"author": "codelogic",
"author_id": 43427,
"author_profile": "https://Stackoverflow.com/users/43427",
"pm_score": 1,
"selected": false,
"text": "#!/usr/bin/python\nimport sys\n\n# thx google \nbstr_pos = lambda n: n>0 and bstr_pos(n>>1)+str(n&1) or \"\"\n\ndef arrangements(n):\n count = 0\n for v in range(0, pow(2,n)-1):\n bin = bstr_pos(v).rjust(n, '0')\n if not ( bin.find(\"11\")!=-1 or ( bin[0]=='1' and bin[-1]=='1' ) ):\n count += 1\n print bin\n print \"Total = \" + str(count)\n\narrangements(int(sys.argv[1]))\n"
},
{
"answer_id": 354710,
"author": "Oddthinking",
"author_id": 8014,
"author_profile": "https://Stackoverflow.com/users/8014",
"pm_score": 0,
"selected": false,
"text": "def arcCombinations(n, lastDigitMustBeZero):\n \"\"\"Takes the length of the remaining arc of the circle, and computes\n the number of legal combinations.\n The last digit may be restricted to 0 (because the first digit is a 1)\"\"\"\n\n if n == 1: \n if lastDigitMustBeZero:\n return 1 # only legal answer is 0\n else:\n return 2 # could be 1 or 0.\n elif n == 2:\n if lastDigitMustBeZero:\n return 2 # could be 00 or 10\n else:\n return 3 # could be 10, 01 or 00\n else:\n # Could be a 1, in which case next item is a zero.\n return (\n arcCombinations(n-2, lastDigitMustBeZero) # If it starts 10\n + arcCombinations(n-1, lastDigitMustBeZero) # If it starts 0\n )\n\ndef circleCombinations(n):\n \"\"\"Computes the number of legal combinations for a given circle size.\"\"\"\n\n # Handle case where it starts with 0 or with 1.\n total = (\n arcCombinations(n-1,True) # Number of combinations where first digit is a 1.\n +\n arcCombinations(n-1,False) # Number of combinations where first digit is a 0.\n )\n return total\n\n\nprint circleCombinations(13)\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354640",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44511/"
] |
354,650 | <p>I need to keep an NSPathControl updated with the currently selected path in an NSBrowser, but I'm having trouble figuring out a way of getting notifications when the path has changed from the NSBrowser. The ideal way to do this would just to be to observe the path key path in the NSBrowser, but that gives a KVO can only observe set<code><key></code> methods which return void message and no updates (setPath returns a bool success value).</p>
<p>I also tried observing the selectedCell key path, but I'm not getting notifications when the selection there is changed.</p>
<p>Is there some other really obvious way to do this that I'm missing?</p>
| [
{
"answer_id": 354682,
"author": "Marc Charbonneau",
"author_id": 35136,
"author_profile": "https://Stackoverflow.com/users/35136",
"pm_score": 0,
"selected": false,
"text": "- (BOOL)browser:(NSBrowser *)sender selectRow:(NSInteger)row inColumn:(NSInteger)column - (BOOL)browser:(NSBrowser *)sender selectCellWithString:(NSString *)title inColumn:(NSInteger)column"
},
{
"answer_id": 355010,
"author": "Redwood",
"author_id": 1512,
"author_profile": "https://Stackoverflow.com/users/1512",
"pm_score": 4,
"selected": true,
"text": "- (void)browserClicked: NSBrowser action - (void)browserClicked:(id)browser {\n self.pathToSelectedCell = [browser path]; // NSPathControl is bound to pathToSelectedCell\n}\n"
},
{
"answer_id": 15255441,
"author": "matt",
"author_id": 370800,
"author_profile": "https://Stackoverflow.com/users/370800",
"pm_score": 0,
"selected": false,
"text": "- (NSIndexSet *)browser:(NSBrowser *)browser selectionIndexesForProposedSelection:(NSIndexSet *)proposedSelectionIndexes inColumn:(NSInteger)column\n{\n NSLog(@\"New first item of the new selection is at index %@\", [proposedSelectionIndexes firstIndex]);\n // Do something with the selected index or indicies\n return proposedSelectionIndexes; // Allow the selection to occur by not changing this\n}\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1512/"
] |
354,651 | <p>I have a couple of mdb files with the exact table structure. I have to change the primary key of the main table from autonumber to number in all of them, which means I have to:</p>
<ol>
<li>Drop the all the relationships the main table has</li>
<li>Change the main table</li>
<li>Create the relationships again,... for all the tables.</li>
</ol>
<p>Is there any way to export the relationships from one file and importing them to all the rest?</p>
<p>I am sure this can be done with some macro/vb code. Does anyone has an example I could use?</p>
<p>Thanks.</p>
| [
{
"answer_id": 354954,
"author": "Patrick Cuff",
"author_id": 7903,
"author_profile": "https://Stackoverflow.com/users/7903",
"pm_score": 5,
"selected": true,
"text": "Function PrintRelationships()\n For Each rel In CurrentDb.Relations\n With rel\n Debug.Print \"Name: \" & .Name\n Debug.Print \"Attributes: \" & .Attributes\n Debug.Print \"Table: \" & .Table\n Debug.Print \"ForeignTable: \" & .ForeignTable\n\n Debug.Print \"Fields:\"\n For Each fld In .Fields\n Debug.Print \"Field: \" & fld.Name\n Next\n End With\n Next\nEnd Function\n Function DropRelationships()\n With CurrentDb\n For Each rel In .Relations\n .Relations.Delete Name:=rel.Name\n Next\n End With\nEnd Function\n Function CreateRelationships()\n With CurrentDb\n Set rel = .CreateRelation(Name:=\"[rel.Name]\", Table:=\"[rel.Table]\", ForeignTable:=\"[rel.FireignTable]\", Attributes:=[rel.Attributes])\n rel.Fields.Append rel.CreateField(\"[fld.Name for relation]\")\n rel.Fields(\"[fld.Name for relation]\").ForeignName = \"[fld.Name for relation]\"\n .Relations.Append rel\n End With\nEnd Function\n"
},
{
"answer_id": 355077,
"author": "Fionnuala",
"author_id": 2548,
"author_profile": "https://Stackoverflow.com/users/2548",
"pm_score": 1,
"selected": false,
"text": "Sub RunExamples()\nDim strCopyMDB As String\nDim fs As FileSystemObject\nDim blnFound As Boolean\nDim i\n\n' This code is not intended for general users, it is sample code built '\n' around the OP '\n'You will need a reference to the Microsoft DAO 3.x Object Library '\n'This line causes an error, but it will run '\n'It is not suitable for anything other than saving a little time '\n'when setting up a new database '\nApplication.References.AddFromFile (\"C:\\Program Files\\Common Files\\Microsoft Shared\\DAO\\dao360.dll\")\n\n'You must first create a back-up copy '\nSet fs = CreateObject(\"Scripting.FileSystemObject\")\n\nstrCopyMDB = CurrentProject.Path & \"\\c.mdb\"\nblnFound = fs.FileExists(strCopyMDB)\n\ni = 0\nDo While blnFound\n strCopyMDB = CurrentProject.Path & \"\\c\" & i & \".mdb\"\n blnFound = fs.FileExists(strCopyMDB)\nLoop\n\nfs.CopyFile CurrentProject.FullName, strCopyMDB\n\nChangeTables\nAddIndexesFromBU strCopyMDB\nAddRelationsFromBU strCopyMDB\nEnd Sub \n\n\nSub ChangeTables()\nDim db As Database\nDim tdf As DAO.TableDef\nDim rel As DAO.Relation\nDim fld As DAO.Field\nDim ndx As DAO.Index\nDim i\n\n Set db = CurrentDb\n 'In order to programmatically change an autonumber, '\n 'it is necessary to delete any relationships that '\n 'depend on it. ' \n 'When deleting from a collection, it is best '\n 'to iterate backwards. '\n For i = db.Relations.Count - 1 To 0 Step -1\n db.Relations.Delete db.Relations(i).Name\n Next\n\n 'The indexes must also be deleted or the '\n 'number cannot be changed. '\n For Each tdf In db.TableDefs\n If Left(tdf.Name, 4) <> \"Msys\" Then\n For i = tdf.Indexes.Count - 1 To 0 Step -1\n tdf.Indexes.Delete tdf.Indexes(i).Name\n Next\n\n tdf.Indexes.Refresh\n\n For Each fld In tdf.Fields\n 'If the field is an autonumber, '\n 'use code supplied by MS to change the type '\n If (fld.Attributes And dbAutoIncrField) Then\n\n AlterFieldType tdf.Name, fld.Name, \"Long\"\n\n End If\n Next\n End If\n\n Next\nEnd Sub\n\n\nSub AddIndexesFromBU(MDBBU)\nDim db As Database\nDim dbBU As Database\nDim tdf As DAO.TableDef\nDim tdfBU As DAO.TableDef\nDim ndx As DAO.Index\nDim ndxBU As DAO.Index\nDim i\n\nSet db = CurrentDb\n'This is the back-up made before starting '\nSet dbBU = OpenDatabase(MDBBU)\n\n For Each tdfBU In dbBU.TableDefs\n 'Skip system tables '\n If Left(tdfBU.Name, 4) <> \"Msys\" Then\n For i = tdfBU.Indexes.Count - 1 To 0 Step -1\n 'Get each index from the back-up '\n Set ndxBU = tdfBU.Indexes(i)\n Set tdf = db.TableDefs(tdfBU.Name)\n Set ndx = tdf.CreateIndex(ndxBU.Name)\n ndx.Fields = ndxBU.Fields\n ndx.IgnoreNulls = ndxBU.IgnoreNulls\n ndx.Primary = ndxBU.Primary\n ndx.Required = ndxBU.Required\n ndx.Unique = ndxBU.Unique\n\n ' and add it to the current db '\n tdf.Indexes.Append ndx\n Next\n\n tdf.Indexes.Refresh\n End If\n Next\n\nEnd Sub\n\nSub AddRelationsFromBU(MDBBU)\nDim db As Database\nDim dbBU As Database\nDim rel As DAO.Relation\nDim fld As DAO.Field\nDim relBU As DAO.Relation\nDim i, j, f\n\nOn Error GoTo ErrTrap\n\n Set db = CurrentDb\n 'The back-up again '\n Set dbBU = OpenDatabase(MDBBU)\n\n For i = dbBU.Relations.Count - 1 To 0 Step -1\n 'Get each relationship from bu '\n Set relBU = dbBU.Relations(i)\n Debug.Print relBU.Name\n Set rel = db.CreateRelation(relBU.Name, relBU.Table, relBU.ForeignTable, relBU.Attributes)\n For j = 0 To relBU.Fields.Count - 1\n f = relBU.Fields(j).Name\n rel.Fields.Append rel.CreateField(f)\n rel.Fields(f).ForeignName = relBU.Fields(j).ForeignName\n Next\n 'For some relationships, I am getting error'\n '3284 Index already exists, which I will try'\n 'and track down tomorrow, I hope'\n 'EDIT: Apparently this is due to Access creating hidden indexes\n 'and tracking these down would take quite a bit of effort\n 'more information can be found in this link:\n 'http://groups.google.ie/group/microsoft.public.access/browse_thread/thread/ca58ce291bdc62df?hl=en&ie=UTF-8&q=create+relation+3284+Index+already+exists\n 'It is an occasional problem, so I've added an error trap\n\n 'Add the relationship to the current db'\n db.Relations.Append rel\n Next\nExitHere:\n Exit Sub\n\nErrTrap:\n If Err.Number = 3284 Then\n Debug.Print relBU.Name, relBU.Table, relBU.ForeignTable, relBU.Attributes\n Resume Next\n Else\n 'this is not a user sub, so may as well ... '\n Stop\n\nEnd If\nEnd Sub\n\nSub AlterFieldType(TblName As String, FieldName As String, _\n NewDataType As String)\n'http://support.microsoft.com/kb/128016'\n\n Dim db As Database\n Dim qdf As QueryDef\n Set db = CurrentDb()\n\n ' Create a dummy QueryDef object.'\n Set qdf = db.CreateQueryDef(\"\", \"Select * from PROD1\")\n\n ' Add a temporary field to the table.'\n qdf.SQL = \"ALTER TABLE [\" & TblName & \"] ADD COLUMN AlterTempField \" & NewDataType\n qdf.Execute\n\n ' Copy the data from old field into the new field.'\n qdf.SQL = \"UPDATE DISTINCTROW [\" & TblName _\n & \"] SET AlterTempField = [\" & FieldName & \"]\"\n qdf.Execute\n\n ' Delete the old field.'\n qdf.SQL = \"ALTER TABLE [\" & TblName & \"] DROP COLUMN [\" _\n & FieldName & \"]\"\n qdf.Execute\n\n ' Rename the temporary field to the old field's name.'\n db.TableDefs(\"[\" & TblName & \"]\").Fields(\"AlterTempField\").Name = FieldName\n\nEnd Sub\n"
},
{
"answer_id": 2651233,
"author": "Vivek",
"author_id": 318256,
"author_profile": "https://Stackoverflow.com/users/318256",
"pm_score": 0,
"selected": false,
"text": "target.mdb AddIndexesFromBU ndxBU.Unique tdf.Indexes.Append ndx source.mdb ndxBU.Unique"
},
{
"answer_id": 35437624,
"author": "Jakub M.",
"author_id": 4863744,
"author_profile": "https://Stackoverflow.com/users/4863744",
"pm_score": 2,
"selected": false,
"text": "'supply the Access Application object into this function and path to file to which the output should be written\nFunction ExportRelationships(oApplication, sExportpath)\n Dim relDoc, myObj\n Set relDoc = CreateObject(\"Microsoft.XMLDOM\")\n relDoc.appendChild relDoc.createElement(\"Relations\") 'create root xml element\n\n 'loop though all the relations\n For Each myObj In oApplication.CurrentDb.Relations\n If Not Left(myObj.Name, 4) = \"MSys\" Then 'exclude system relations\n Dim relName, relAttrib, relTable, relFoTable, fld\n\n relDoc.childNodes(0).appendChild relDoc.createElement(\"Relation\")\n\n Set relName = relDoc.createElement(\"Name\")\n relName.Text = myObj.Name\n relDoc.childNodes(0).lastChild.appendChild relName\n\n Set relAttrib = relDoc.createElement(\"Attributes\")\n relAttrib.Text = myObj.Attributes\n relDoc.childNodes(0).lastChild.appendChild relAttrib\n\n Set relTable = relDoc.createElement(\"Table\")\n relTable.Text = myObj.Table\n relDoc.childNodes(0).lastChild.appendChild relTable\n\n Set relFoTable = relDoc.createElement(\"ForeignTable\")\n relFoTable.Text = myObj.ForeignTable\n relDoc.childNodes(0).lastChild.appendChild relFoTable\n\n 'in case the relationship works with more fields\n For Each fld In myObj.Fields\n Dim lf, ff\n relDoc.childNodes(0).lastChild.appendChild relDoc.createElement(\"Field\")\n\n Set lf = relDoc.createElement(\"Name\")\n lf.Text = fld.Name\n relDoc.childNodes(0).lastChild.lastChild.appendChild lf\n\n Set ff = relDoc.createElement(\"ForeignName\")\n ff.Text = fld.ForeignName\n relDoc.childNodes(0).lastChild.lastChild.appendChild ff\n Next\n End If\n Next\n relDoc.insertBefore relDoc.createProcessingInstruction(\"xml\",\"version='1.0'\"), relDoc.childNodes(0)\n relDoc.Save sExportpath\nEnd Function\n 'supply the Access Application object into this function and path to file from which the input should be read\nFunction ImportRelationships(oApplication, sImportpath)\n Dim relDoc, myObj\n Set relDoc = CreateObject(\"Microsoft.XMLDOM\")\n relDoc.Load(sImportpath)\n Dim xmlRel, xmlField, accessRel, relTable, relName, relFTable, relAttr, i\n\n 'loop through every Relation node inside .xml file\n For Each xmlRel in relDoc.selectNodes(\"/Relations/Relation\")\n relName = xmlRel.selectSingleNode(\"Name\").Text\n relTable = xmlRel.selectSingleNode(\"Table\").Text\n relFTable = xmlRel.selectSingleNode(\"ForeignTable\").Text\n relAttr = xmlRel.selectSingleNode(\"Attributes\").Text\n\n 'remove any possible conflicting relations or indexes\n On Error Resume next\n oApplication.CurrentDb.Relations.Delete (relName)\n oApplication.CurrentDb.TableDefs(relTable).Indexes.Delete(relName)\n oApplication.CurrentDb.TableDefs(relFTable).Indexes.Delete(relName)\n On Error Goto 0\n\n 'create the relationship object\n Set accessRel = oApplication.CurrentDb.CreateRelation(relName, relTable, relFTable, relAttr)\n\n 'in case the relationship works with more fields\n For Each xmlField In xmlRel.selectNodes(\"Field\")\n accessRel.Fields.Append accessRel.CreateField(xmlField.selectSingleNode(\"Name\").Text)\n accessRel.Fields(xmlField.selectSingleNode(\"Name\").Text).ForeignName = xmlField.selectSingleNode(\"ForeignName\").Text\n Next\n\n 'and finally append the newly created relationship to the database\n oApplication.CurrentDb.Relations.Append accessRel\n Next\nEnd Function\n Set oApplication = CreateObject(\"Access.Application\")\noApplication.NewCurrentDatabase path 'new database\noApplication.OpenCurrentDatabase path 'existing database\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15884/"
] |
354,653 | <p>What is the best way to close a browser window of an AJAX ASP.NET application after the server-side has been executed.</p>
<p>I found this <a href="https://stackoverflow.com/questions/250450/aspnet-ajax-close-window-after-ajax-call">solution</a>, but it seems a little complex for what I want to accomplish. Or is this the best way to accomplish my task.</p>
<p><b>UPDATE:</b> I have to close the window after the button is pressed</p>
<p><b>UPDATE 1:</b> I tried the solution from the other SO question, and it did not work for me.</p>
<pre><code><asp:Button ID="btnMyButton" runat="server" onClick="btnMyButton_Click" />
protected void btnMyButton_Click(object sender, EventArgs e)
{
}
</code></pre>
<hr>
<p>I used the following code in my page, but the "The webpage you are viewing is trying to close the windows" module window pops up.</p>
<pre><code>if (ScriptManager.GetCurrent(this).IsInAsyncPostBack)
ScriptManager.RegisterStartupScript(upApproveRequest, typeof(string), "closeWindow", "window.close();", true);
</code></pre>
<p>Any way to prevent this?</p>
| [
{
"answer_id": 354658,
"author": "Strelok",
"author_id": 2788,
"author_profile": "https://Stackoverflow.com/users/2788",
"pm_score": -1,
"selected": false,
"text": "ScriptManager.RegisterStartupScript(...)"
},
{
"answer_id": 3685477,
"author": "hyprsleepy",
"author_id": 285371,
"author_profile": "https://Stackoverflow.com/users/285371",
"pm_score": 2,
"selected": false,
"text": "protected void btnMyButton_Click(object sender, ImageClickEventArgs e)\n{\n // Update database\n bool success = Presenter.DoDatabaseStuff();\n\n if (success)\n {\n // Close window after success\n const string javaScript = \"<script language=javascript>window.top.close();</script>\";\n if (!ClientScript.IsStartupScriptRegistered(\"CloseMyWindow\"))\n {\n ClientScript.RegisterStartupScript(GetType(),\"CloseMyWindow\", javaScript);\n }\n }\n else\n {\n // Display failure result\n result_msg_area.Visible = true;\n lblError.Text = \"An error occurred!\"; \n }\n}\n"
},
{
"answer_id": 9283178,
"author": "PhilDulac",
"author_id": 755977,
"author_profile": "https://Stackoverflow.com/users/755977",
"pm_score": 1,
"selected": false,
"text": "window.open('', '_self', '');window.close();\n if (ScriptManager.GetCurrent(this).IsInAsyncPostBack)\n ScriptManager.RegisterStartupScript(upApproveRequest, typeof(string), \"closeWindow\", \"window.open('', '_self', '');window.close();\", true);\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354653",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26327/"
] |
354,657 | <p><a href="http://api.rubyonrails.com/classes/ActiveSupport/CoreExtensions/Time/Conversions.html" rel="noreferrer">Rails' ActiveSupport module extends the builtin ruby Time class with a number of methods.</a></p>
<p>Notably, there is the <code>to_formatted_s</code> method, which lets you write <code>Time.now.to_formatted_s(:db)</code> to get a string in Database format, rather than having to write ugly <code>strftime</code> format-strings everywhere.</p>
<p>My question is, is there a way to go backwards? </p>
<p>Something like <code>Time.parse_formatted_s(:db)</code> which would parse a string in Database format, returning a new Time object. This seems like something that rails should be providing, but if it is, I can't find it.</p>
<p>Am I just not able to find it, or do I need to write it myself?</p>
<p>Thanks</p>
| [
{
"answer_id": 1474238,
"author": "Tyler Rick",
"author_id": 47185,
"author_profile": "https://Stackoverflow.com/users/47185",
"pm_score": 6,
"selected": false,
"text": ":db > Time.zone.parse('2009-09-24 08:28:43')\n=> Thu, 24 Sep 2009 08:28:43 PDT -07:00\n\n > Time.zone.parse('2009-09-24 08:28:43').class\n=> ActiveSupport::TimeWithZone\n > Time.zone.parse('2009-09-24 08:28:43').utc\n=> 2009-09-24 15:28:43 UTC\n > ActiveSupport::TimeZone.us_zones.map(&:name)\n=> [\"Hawaii\", \"Alaska\", \"Pacific Time (US & Canada)\", \"Arizona\", \"Mountain Time (US & Canada)\", \"Central Time (US & Canada)\", \"Eastern Time (US & Canada)\", \"Indiana (East)\"]\n\n > Time.zone.parse('2009-09-24 08:28:43').utc.in_time_zone('Eastern Time (US & Canada)')\n=> Thu, 24 Sep 2009 11:28:43 EDT -04:00\n > DateTime.strptime('2009-09-24 08:28:43', '%Y-%m-%d %H:%M:%S').to_time\n=> 2009-09-24 08:28:43 UTC\n > DateTime.strptime('2009-09-24 08:28:43', '%Y-%m-%d %H:%M:%S').to_time.in_time_zone\n=> Thu, 24 Sep 2009 01:28:43 PDT -07:00\n irb -> Time.zone.parse('Wed, 23 Sep 2009 02:18:08').to_s(:db)\n => \"2009-09-23 09:18:08\"\n\nirb -> Time.zone.parse('Wed, 23 Sep 2009 02:18:08 EDT').to_s(:db)\n => \"2009-09-23 06:18:08\"\n Time.zone = 'Eastern Time (US & Canada)' # => 'Eastern Time (US & Canada)'\n Time.zone.local(2007, 2, 10, 15, 30, 45) # => Sat, 10 Feb 2007 15:30:45 EST -05:00\n Time.zone.parse('2007-02-10 15:30:45') # => Sat, 10 Feb 2007 15:30:45 EST -05:00\n Time.zone.at(1170361845) # => Sat, 10 Feb 2007 15:30:45 EST -05:00\n Time.zone.now # => Sun, 18 May 2008 13:07:55 EDT -04:00\n Time.utc(2007, 2, 10, 20, 30, 45).in_time_zone # => Sat, 10 Feb 2007 15:30:45 EST -05:00\n"
},
{
"answer_id": 1475032,
"author": "eremite",
"author_id": 167369,
"author_profile": "https://Stackoverflow.com/users/167369",
"pm_score": 1,
"selected": false,
"text": ">> \"2009-09-24\".to_date\n=> Thu, 24 Sep 2009\n>> \"9/24/2009\".to_date\n=> Thu, 24 Sep 2009\n"
},
{
"answer_id": 3416836,
"author": "Leventix",
"author_id": 157328,
"author_profile": "https://Stackoverflow.com/users/157328",
"pm_score": 3,
"selected": false,
"text": "ActiveSupport::TimeZone.new('UTC').parse('2009-09-23 09:18:08')\n=> Wed, 23 Sep 2009 09:18:08 UTC +00:00\n"
},
{
"answer_id": 10644422,
"author": "Ben Mabey",
"author_id": 233964,
"author_profile": "https://Stackoverflow.com/users/233964",
"pm_score": 2,
"selected": false,
"text": "ActiveSupport::TimeZone Time .strptime TimeZone ActiveSupport::TimeZone.strptime class ActiveSupport::TimeZone\n def strptime(str, fmt, now = self.now)\n date_parts = Date._strptime(str, fmt)\n return if date_parts.blank?\n time = Time.strptime(str, fmt, now) rescue DateTime.strptime(str, fmt, now)\n if date_parts[:offset].nil?\n ActiveSupport::TimeWithZone.new(nil, self, time)\n else\n time.in_time_zone(self)\n end\n end\n end\n"
},
{
"answer_id": 35250529,
"author": "deprecated",
"author_id": 569050,
"author_profile": "https://Stackoverflow.com/users/569050",
"pm_score": 2,
"selected": false,
"text": "strptime value = '1999-12-31 14:00:00'\nformat = '%Y-%m-%d %H:%M:%S'\nTime.zone.strptime(value, format)\n# => Fri, 31 Dec 1999 14:00:00 HST -10:00\n\nActiveSupport::TimeZone.all.sample.strptime(value, format)\n# => Fri, 31 Dec 1999 14:00:00 GST +04:00\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/234/"
] |
354,664 | <p>This pretty much has me defeated.</p>
<p>On XP and earlier versions of Windows you could customise Open With filetypes to include java - jar "myjar.jar", but on Vista this functionality seems to have been removed. I can of course create a .bat file to launch my application, but is it possible to make Vista execute a .jar as required?</p>
| [
{
"answer_id": 355011,
"author": "RealHowTo",
"author_id": 25122,
"author_profile": "https://Stackoverflow.com/users/25122",
"pm_score": 6,
"selected": true,
"text": ">assoc .jar\n.jar=jarfile\n >assoc .jar=jarfile\n >ftype jarfile\njarfile=\"C:\\Program Files\\Java\\jre1.5.0_10\\bin\\javaw.exe\" -jar \"%1\" %*\n >ftype jarfile=\"C:\\Program Files\\Java\\jre1.5.0_10\\bin\\javaw.exe\" -jar \"%1\" %*\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354664",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1293123/"
] |
354,669 | <p>I have the following attributes in my DB.</p>
<blockquote>
<p>statistic id, devicename, value, timestamp.</p>
</blockquote>
<p>For a given statistic, I want to find the 2 most recent timestamps and corresopnding values for a every unique device.</p>
<p>I am trying stuff like </p>
<p>Trial 1)</p>
<pre><code>select statistic, devicename, value, timestamp
from X_STATSVALUE
where statistic=19
order by orgtime DESC limit 2;
</code></pre>
<p>This gives me the top 2 timestamps, but not per device.</p>
<p>Trial 2)</p>
<pre><code>select statistic, devicename, value, timestamp
from X_STATSVALUE as x
where x.statistic=241
and (select count(*)
from X_STATSVALUE as y
where y.statistic=x.statistic
and y.device=x.device
and y.timestamp > x.timestamp) <=1;
</code></pre>
<p>But that's not working too well either..</p>
<p>Basically, I want the 2 most recent timestamps with values for each device, for a given statistic.. any help is really appreciated :)</p>
| [
{
"answer_id": 354696,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 2,
"selected": false,
"text": "SELECT x.statistic, x.devicename, x.value, x.timestamp\nFROM X_STATSVALUE AS x\n LEFT OUTER JOIN X_STATSVALUE AS x2\n ON (x.statistic = x2.statistic \n AND x.devicename = x2.devicename \n AND x.timestamp < x2.timestamp)\nGROUP BY x.statistic, x.devicename\nHAVING COUNT(*) < 2;\n statistic devicename timestamp timestamp"
},
{
"answer_id": 355428,
"author": "mat",
"author_id": 42083,
"author_profile": "https://Stackoverflow.com/users/42083",
"pm_score": 1,
"selected": false,
"text": "SELECT DISTINCT x.statistic, x.devicename, x.value, x.timestamp\nFROM X_STATSVALUE AS x\nWHERE x.timestamp IN (SELECT timestamp\n FROM X_STATSVALUE\n WHERE devicename = x.devicename AND statistic = x.statistic\n ORDER BY timestamp LIMIT 2)\n"
},
{
"answer_id": 355496,
"author": "Samiksha",
"author_id": 29515,
"author_profile": "https://Stackoverflow.com/users/29515",
"pm_score": 1,
"selected": false,
"text": " select t1.statistic, devicename, value, timestamp from X_STATSVALUE as t1 \n\n inner join \n\n ( select statistic, max(orgtime) as orgtime from X_STATSVALUE group by statistic ) \nas t2 \n\n on t1.statistic = t2.statistic and t1.orgtime = t2.orgtime\n\n UNION\n\n select tb1.statistic, tb1.devicename, tb1.value, tb1.timestamp\n from X_STATSVALUE as tb1 inner join \n\n ( select statistic, max(orgtime) as orgtime from X_STATSVALUE WHERE statistic+orgtime not in \n (select t1.statistic+t1.orgtime from X_STATSVALUE as t1 inner join \n ( select statistic, max(orgtime) as orgtime from X_STATSVALUE group by statistic ) \nas t2 on t1.statistic = t2.statistic and t1.orgtime = t2.orgtime\n ) group by statistic \n ) \n\n as tb2 on tb1.statistic = tb2.statistic and tb1.orgtime = tb2.orgtime\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354669",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
354,680 | <p>I have balls bouncing around and each time they collide their speed vector is reduced by the Coefficient of Restitution.</p>
<p>Right now my balls CoR for my balls is .80 . So after many bounces my balls have "stopped" rolling because their speed has becoming some ridiculously small number. </p>
<p>In what stage is it appropriate to check if a speed value is small enough to simply call it zero (so I don't have the crazy jittering of the balls reacting to their micro-velocities). I've read on some forums before that people will sometimes use an epsilon constant, some small number and check against that.</p>
<p>Should I define an epsilon constant and do something like:</p>
<pre><code>if Math.abs(velocity.x) < epsilon then velocity.x = 0
</code></pre>
<p>Each time I update the balls velocity and position? Is this what is generally done? Would it be reasonable to place that in my Vector classes setters for x and y? Or should I do it outside of my vector class when I'm calculating the velocities. </p>
<p>Also, what would be a reasonable epsilon value if I was using floats for my speed vector?</p>
| [
{
"answer_id": 354758,
"author": "benjismith",
"author_id": 22979,
"author_profile": "https://Stackoverflow.com/users/22979",
"pm_score": 1,
"selected": false,
"text": "void UpdatePosition(Ball b) {\n\n TimeStamp now = Clock.GetTime();\n float secondsSinceLastUpdate = now.TimeSince(b.LastUpdate).InSeconds;\n\n Point3D oldPosition = b.Position;\n Point3D newPosition = CalculatePosition(b.Position, b.Velocity, interval);\n b.MoveTo(newPosition);\n\n float epsilonOfAccuracy = 0.5; // Accurate to one half-pixel\n float pixelDistance = Camera.PixelDistance(oldPosition, newPosition);\n float fps = System.CurrentFramesPerSecond;\n float secondsToMoveOnePixel = (pixelDistance * secondsSinceLastUpdate) / fps;\n float nextUpdateInterval = secondsToMoveOnePixel / epsilonOfAccuracy;\n\n b.SetNextUpdateAt(now + nextUpdateInterval);\n}\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/354680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2635/"
] |
354,685 | <p>I recognize that there's an obvious pattern in the output to this, I just want to know why lispbox's REPL aborts when I try to run anything > 52. Also, any suggestions on improving the code are more than welcome. ^-^</p>
<pre><code>(defun count-reduced-fractions (n d sum)
(setf g (gcd n d))
(if (equal 1 d)
(return-from count-reduced-fractions sum)
(if (zerop n)
(if (= 1 g)
(count-reduced-fractions (1- d) (1- d) (1+ sum))
(count-reduced-fractions (1- d) (1- d) sum))
(if (= 1 g)
(count-reduced-fractions (1- n) d (1+ sum))
(count-reduced-fractions (1- n) d sum)))))
</code></pre>
<p>All I get when I call </p>
<p><code>(count-reduced-fractions 53 53 0)</code></p>
<p>is</p>
<blockquote>
<p>;Evaluation aborted</p>
</blockquote>
<p>It doesn't make much sense to me, considering it'll run (and return the accurate result) on all numbers below that, and that I could (if i wanted to) do 53 in my head, on paper, or one line at a time in lisp. I even tested on many different numbers greater than 53 to make sure it wasnt specific to 53. Nothing works.</p>
| [
{
"answer_id": 354694,
"author": "Kyle Cronin",
"author_id": 658,
"author_profile": "https://Stackoverflow.com/users/658",
"pm_score": 2,
"selected": false,
"text": "* (count-reduced-fractions 53 53 0)\n881\n\n* (count-reduced-fractions 100 100 0)\n3043\n"
},
{
"answer_id": 354705,
"author": "Josh Sandlin",
"author_id": 13293,
"author_profile": "https://Stackoverflow.com/users/13293",
"pm_score": 1,
"selected": false,
"text": "(defun test (n &optional (d n) (sum 0)) .. )\n"
},
{
"answer_id": 354719,
"author": "Svante",
"author_id": 31615,
"author_profile": "https://Stackoverflow.com/users/31615",
"pm_score": 3,
"selected": false,
"text": "return-from sum (return-from count-reduced-fractions sum) sum (declaim (optimize (speed 3)\n (debug 0))) declare declaim g (let ((g (gcd n d)))\n ;; ...\n )\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/354685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
354,691 | <p>What I am trying to do is so simple but I am having a hard time making it work. I saw some posts along the same lines but I still have questions.</p>
<p>I have a MenuItem object called mnuA. All I want is set the icon property programatically in C#. I have tried the following</p>
<p>a) <code>mnuA.Icon = new BitmapImage{UriSource = new Uri(@"c:\icons\A.png")};</code>
Results: Instead of showing the actual icon, I get the class name (<code>System.Windows.Media.Imaging.BitmapImage</code>)</p>
<p>b) <code>mnuA.Icon = new BitmapImage(new Uri(@"c:\icons\A.png"));</code>
Results: Instead of showing the actual icon, I get the path of the image (<code>file:///c:/icons/A.png</code>)</p>
<p>What am I doing wrong? Do I really need a converter class for something simple like this?</p>
| [
{
"answer_id": 354754,
"author": "w4g3n3r",
"author_id": 36745,
"author_profile": "https://Stackoverflow.com/users/36745",
"pm_score": 4,
"selected": true,
"text": "Image img = new Image();\nimg.Source = new BitmapImage(new Uri(@\"c:\\icons\\A.png\"));\nmnuA.Icon = img;\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/354691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28029/"
] |
354,695 | <p>I need to use one logical PGM based multicast address in application while enable such application "seamlessly" running across several different geo-locations (i.e. think US/Europe/Australia).</p>
<p>Application is quite throughput (several million biz. messages a day) and latency demanding whith a lot of small but very frequently send messages. Classical Atom pub will not work here due some external limits of latencies.</p>
<p>I have come up with several options to connect those datacenters but can’t find the best one.
Options which I have considered are:
1) Forward multicast messages via VPN’s (can VPN handle such big load).
2) Translate all multicast messages to “wrapper messages” and forward them via AMQP.
3) Write specialized in-house gate which tunnels multicast messages via TCP to other two locations.
4) Any other solution </p>
<p>I would prefer option 1 as it does not need additional code writes from devs. but I’m afraid it will not be reliable connection.</p>
<p>Are there any rules to apply for such connectivity?</p>
<p>What the best network configuration with regard to the geographical configuration is for above constrains.</p>
| [
{
"answer_id": 354754,
"author": "w4g3n3r",
"author_id": 36745,
"author_profile": "https://Stackoverflow.com/users/36745",
"pm_score": 4,
"selected": true,
"text": "Image img = new Image();\nimg.Source = new BitmapImage(new Uri(@\"c:\\icons\\A.png\"));\nmnuA.Icon = img;\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/354695",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30777/"
] |
354,703 | <p>I am trying to process files one at a time that are stored over a network. Reading the files is fast due to buffering is not the issue. The problem I have is just listing the directories in a folder. I have at least 10k files per folder over many folders.</p>
<p>Performance is super slow since File.list() returns an array instead of an iterable. Java goes off and collects all the names in a folder and packs it into an array before returning.</p>
<p>The bug entry for this is <a href="http://bugs.sun.com/view_bug.do;jsessionid=db7fcf25bcce13541c4289edeb4?bug_id=4285834" rel="noreferrer">http://bugs.sun.com/view_bug.do;jsessionid=db7fcf25bcce13541c4289edeb4?bug_id=4285834</a> and doesn't have a work around. They just say this has been fixed for JDK7.</p>
<p>A few questions:</p>
<ol>
<li>Does anybody have a workaround to this performance bottleneck?</li>
<li>Am I trying to achieve the impossible? Is performance still going to be poor even if it just iterates over the directories?</li>
<li>Could I use the beta JDK7 builds that have this functionality without having to build my entire project on it?</li>
</ol>
| [
{
"answer_id": 354743,
"author": "OscarRyz",
"author_id": 20654,
"author_profile": "https://Stackoverflow.com/users/20654",
"pm_score": 2,
"selected": false,
"text": "File [] content = new File(\"X:\\\\remote\\\\dir\").listFiles();\n\nfor ( File f : content ) {\n process( f );\n}\n String [] content = fetchViaHttpTheListNameOf(\"x:\\\\remote\\\\dir\");\n\nfor ( String fileName : content ) {\n process( new File( fileName ) );\n}\n"
},
{
"answer_id": 355867,
"author": "user2427",
"author_id": 1356709,
"author_profile": "https://Stackoverflow.com/users/1356709",
"pm_score": 0,
"selected": false,
"text": "private static class SequentialIterator implements Iterator<File> {\n private DirectoryStack dir = null;\n private File current = null;\n private long limit;\n private FileFilter filter = null;\n\n public SequentialIterator(String path, long limit, FileFilter ff) {\n current = new File(path);\n this.limit = limit;\n filter = ff;\n dir = DirectoryStack.getNewStack(current);\n }\n\n public boolean hasNext() {\n while(walkOver());\n return isMore && (limit > count || limit < 0) && dir.getCurrent() != null;\n }\n\n private long count = 0;\n\n public File next() {\n File aux = dir.getCurrent();\n dir.advancePostition();\n count++;\n return aux;\n }\n\n private boolean walkOver() {\n if (dir.isOutOfDirListRange()) {\n if (dir.isCantGoParent()) {\n isMore = false;\n return false;\n } else {\n dir.goToParent();\n dir.advancePostition();\n return true;\n }\n } else {\n if (dir.isCurrentDirectory()) {\n if (dir.isDirectoryEmpty()) {\n dir.advancePostition();\n } else {\n dir.goIntoDir();\n }\n return true;\n } else {\n if (filter.accept(dir.getCurrent())) {\n return false;\n } else {\n dir.advancePostition();\n return true;\n }\n }\n }\n }\n\n private boolean isMore = true;\n\n public void remove() {\n throw new UnsupportedOperationException();\n }\n\n}\n public class DirectoryStack {\n private class Element{\n private File files[] = null;\n private int currentPointer;\n public Element(File current) {\n currentPointer = 0;\n if (current.exists()) {\n if(current.isDirectory()){\n files = current.listFiles();\n Set<File> set = new TreeSet<File>();\n for (int i = 0; i < files.length; i++) {\n File file = files[i];\n set.add(file);\n }\n set.toArray(files);\n }else{\n throw new IllegalArgumentException(\"File current must be directory\");\n }\n } else {\n throw new IllegalArgumentException(\"File current not exist\");\n }\n\n }\n public String toString(){\n return \"current=\"+getCurrent().toString();\n }\n public int getCurrentPointer() {\n return currentPointer;\n }\n public void setCurrentPointer(int currentPointer) {\n this.currentPointer = currentPointer;\n }\n public File[] getFiles() {\n return files;\n }\n public File getCurrent(){\n File ret = null;\n try{\n ret = getFiles()[getCurrentPointer()];\n }catch (Exception e){\n }\n return ret;\n }\n public boolean isDirectoryEmpty(){\n return !(getFiles().length>0);\n }\n public Element advancePointer(){\n setCurrentPointer(getCurrentPointer()+1);\n return this;\n }\n }\n private DirectoryStack(File first){\n getStack().push(new Element(first));\n }\n public static DirectoryStack getNewStack(File first){\n return new DirectoryStack(first);\n }\n public String toString(){\n String ret = \"stack:\\n\";\n int i = 0;\n for (Element elem : stack) {\n ret += \"nivel \" + i++ + elem.toString()+\"\\n\";\n }\n return ret;\n }\n private Stack<Element> stack=null;\n private Stack<Element> getStack(){\n if(stack==null){\n stack = new Stack<Element>();\n }\n return stack;\n }\n public File getCurrent(){\n return getStack().peek().getCurrent();\n }\n public boolean isDirectoryEmpty(){\n return getStack().peek().isDirectoryEmpty();\n }\n public DirectoryStack downLevel(){\n getStack().pop();\n return this;\n }\n public DirectoryStack goToParent(){\n return downLevel();\n }\n public DirectoryStack goIntoDir(){\n return upLevel();\n }\n public DirectoryStack upLevel(){\n if(isCurrentNotNull())\n getStack().push(new Element(getCurrent()));\n return this;\n }\n public DirectoryStack advancePostition(){\n getStack().peek().advancePointer();\n return this;\n }\n public File[] peekDirectory(){\n return getStack().peek().getFiles();\n }\n public boolean isLastFileOfDirectory(){\n return getStack().peek().getFiles().length <= getStack().peek().getCurrentPointer();\n }\n public boolean gotMoreLevels() {\n return getStack().size()>0;\n }\n public boolean gotMoreInCurrentLevel() {\n return getStack().peek().getFiles().length > getStack().peek().getCurrentPointer()+1;\n }\n public boolean isRoot() {\n return !(getStack().size()>1);\n }\n public boolean isCurrentNotNull() {\n if(!getStack().isEmpty()){\n int currentPointer = getStack().peek().getCurrentPointer();\n int maxFiles = getStack().peek().getFiles().length;\n return currentPointer < maxFiles;\n }else{\n return false;\n }\n }\n public boolean isCurrentDirectory() {\n return getStack().peek().getCurrent().isDirectory();\n }\n public boolean isLastFromDirList() {\n return getStack().peek().getCurrentPointer() == (getStack().peek().getFiles().length-1);\n }\n public boolean isCantGoParent() {\n return !(getStack().size()>1);\n }\n public boolean isOutOfDirListRange() {\n return getStack().peek().getFiles().length <= getStack().peek().getCurrentPointer();\n }\n\n}\n"
},
{
"answer_id": 14550059,
"author": "Peter",
"author_id": 777443,
"author_profile": "https://Stackoverflow.com/users/777443",
"pm_score": 1,
"selected": false,
"text": "JNIEXPORT jstring JNICALL Java_javaxt_io_File_GetFiles(JNIEnv *env, jclass, jstring directory)\n{\n HANDLE hFind;\n try {\n\n //Convert jstring to wstring\n const jchar *_directory = env->GetStringChars(directory, 0);\n jsize x = env->GetStringLength(directory);\n wstring path; //L\"C:\\\\temp\\\\*\";\n path.assign(_directory, _directory + x);\n env->ReleaseStringChars(directory, _directory);\n\n if (x<2){\n jclass exceptionClass = env->FindClass(\"java/lang/Exception\");\n env->ThrowNew(exceptionClass, \"Invalid path, less than 2 characters long.\");\n }\n\n wstringstream ss;\n BOOL bContinue = TRUE;\n WIN32_FIND_DATAW data;\n hFind = FindFirstFileW(path.c_str(), &data);\n if (INVALID_HANDLE_VALUE == hFind){\n jclass exceptionClass = env->FindClass(\"java/lang/Exception\");\n env->ThrowNew(exceptionClass, \"FindFirstFileW returned invalid handle.\");\n }\n\n\n //HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);\n //DWORD dwBytesWritten;\n\n\n // If we have no error, loop thru the files in this dir\n while (hFind && bContinue){\n\n /*\n //Debug Print Statment. DO NOT DELETE! cout and wcout do not print unicode correctly.\n WriteConsole(hStdOut, data.cFileName, (DWORD)_tcslen(data.cFileName), &dwBytesWritten, NULL);\n WriteConsole(hStdOut, L\"\\n\", 1, &dwBytesWritten, NULL);\n */\n\n //Check if this entry is a directory\n if (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY){\n // Make sure this dir is not . or ..\n if (wstring(data.cFileName) != L\".\" &&\n wstring(data.cFileName) != L\"..\")\n { \n ss << wstring(data.cFileName) << L\"\\\\\" << L\"\\n\";\n }\n }\n else{\n ss << wstring(data.cFileName) << L\"\\n\";\n }\n bContinue = FindNextFileW(hFind, &data);\n } \n FindClose(hFind); // Free the dir structure\n\n\n\n wstring cstr = ss.str();\n int len = cstr.size();\n //WriteConsole(hStdOut, cstr.c_str(), len, &dwBytesWritten, NULL);\n //WriteConsole(hStdOut, L\"\\n\", 1, &dwBytesWritten, NULL);\n jchar* raw = new jchar[len];\n memcpy(raw, cstr.c_str(), len*sizeof(wchar_t));\n jstring result = env->NewString(raw, len);\n delete[] raw;\n return result;\n }\n catch(...){\n FindClose(hFind);\n jclass exceptionClass = env->FindClass(\"java/lang/Exception\");\n env->ThrowNew(exceptionClass, \"Exception occured.\");\n }\n\n return NULL;\n}\n JNIEXPORT jlongArray JNICALL Java_javaxt_io_File_GetFileAttributesEx(JNIEnv *env, jclass, jstring filename)\n{ \n\n //Convert jstring to wstring\n const jchar *_filename = env->GetStringChars(filename, 0);\n jsize len = env->GetStringLength(filename);\n wstring path;\n path.assign(_filename, _filename + len);\n env->ReleaseStringChars(filename, _filename);\n\n\n //Get attributes\n WIN32_FILE_ATTRIBUTE_DATA fileAttrs;\n BOOL result = GetFileAttributesExW(path.c_str(), GetFileExInfoStandard, &fileAttrs);\n if (!result) {\n jclass exceptionClass = env->FindClass(\"java/lang/Exception\");\n env->ThrowNew(exceptionClass, \"Exception Occurred\");\n }\n\n //Create an array to store the WIN32_FILE_ATTRIBUTE_DATA\n jlong buffer[6];\n buffer[0] = fileAttrs.dwFileAttributes;\n buffer[1] = date2int(fileAttrs.ftCreationTime);\n buffer[2] = date2int(fileAttrs.ftLastAccessTime);\n buffer[3] = date2int(fileAttrs.ftLastWriteTime);\n buffer[4] = fileAttrs.nFileSizeHigh;\n buffer[5] = fileAttrs.nFileSizeLow;\n\n jlongArray jLongArray = env->NewLongArray(6);\n env->SetLongArrayRegion(jLongArray, 0, 6, buffer);\n return jLongArray;\n}\n"
},
{
"answer_id": 19520486,
"author": "NiTiN",
"author_id": 457541,
"author_profile": "https://Stackoverflow.com/users/457541",
"pm_score": 3,
"selected": false,
"text": "import java.io.File; \nimport java.io.FilenameFilter;\n\npublic class Temp {\n private static void processFile(File dir, String name) {\n File file = new File(dir, name);\n System.out.println(\"processing file \" + file.getName());\n }\n\n private static void forEachFile(File dir) {\n String [] ignore = dir.list(new FilenameFilter() {\n public boolean accept(File dir, String name) {\n processFile(dir, name);\n return false;\n }\n });\n }\n\n public static void main(String[] args) {\n long before, after;\n File dot = new File(\".\");\n before = System.currentTimeMillis();\n forEachFile(dot);\n after = System.currentTimeMillis();\n System.out.println(\"after call, delta is \" + (after - before));\n } \n}\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/354703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21838/"
] |
354,718 | <p>How do you detect which form input has focus using JavaScript or jQuery?</p>
<p>From within a function I want to be able to determine which form input has focus. I'd like to be able to do this in straight JavaScript and/or jQuery.</p>
| [
{
"answer_id": 354849,
"author": "Paolo Bergantino",
"author_id": 16417,
"author_profile": "https://Stackoverflow.com/users/16417",
"pm_score": 5,
"selected": true,
"text": "var selectedInput = null;\n$(function() {\n $('input, textarea, select').focus(function() {\n selectedInput = this;\n }).blur(function(){\n selectedInput = null;\n });\n});\n"
},
{
"answer_id": 4455401,
"author": "Ruan Mendes",
"author_id": 227299,
"author_profile": "https://Stackoverflow.com/users/227299",
"pm_score": 6,
"selected": false,
"text": "document.activeElement document.body"
},
{
"answer_id": 5373323,
"author": "Vivek Viswanathan",
"author_id": 668779,
"author_profile": "https://Stackoverflow.com/users/668779",
"pm_score": -1,
"selected": false,
"text": "window.getSelection().getRangeAt(0).startContainer\n"
},
{
"answer_id": 7246897,
"author": "Maxime Kjaer",
"author_id": 918389,
"author_profile": "https://Stackoverflow.com/users/918389",
"pm_score": 2,
"selected": false,
"text": "<input type=\"text\" onfocus=\"txtfocus=1\" onblur=\"txtfocus=0\" />\n if (txtfocus==1)\n{\n//Whatever code you want to run\n}\n\nif (txtfocus==0)\n{\n//Something else here\n}\n"
},
{
"answer_id": 10695246,
"author": "vapcguy",
"author_id": 1181535,
"author_profile": "https://Stackoverflow.com/users/1181535",
"pm_score": 1,
"selected": false,
"text": "function getSender(field) {\n switch (field.id) {\n case \"someID\":\n case \"someOtherID\":\n return 1;\n break;\n default:\n return 0;\n }\n}\n\nfunction doSomething(elem) {\n if (getSender(elem) == 1) {\n // do your stuff\n }\n /* else {\n // do something else\n } */\n}\n <input id=\"someID\" onfocus=\"doSomething(this)\" />\n<input id=\"someOtherID\" onfocus=\"doSomething(this)\" />\n<input id=\"someOtherGodForsakenID\" onfocus=\"doSomething(this)\" />\n"
},
{
"answer_id": 11746913,
"author": "Magnitus",
"author_id": 1014014,
"author_profile": "https://Stackoverflow.com/users/1014014",
"pm_score": 1,
"selected": false,
"text": " <script>\n //The selector to get the text/password/textarea input that has focus is: jQuery('[data-selected=true]')\n jQuery(document).ready(function() {\n jQuery('body').bind({'focusin': function(Event){\n var Target = jQuery(Event.target);\n if(Target.is(':text')||Target.is(':password')||Target.is('textarea'))\n {\n Target.attr('data-selected', 'true');\n }\n }, 'focusout': function(Event){\n var Target = jQuery(Event.target);\n if(Target.is(':text')||Target.is(':password')||Target.is('textarea'))\n {\n Target.attr('data-selected', 'false');\n }\n }});\n });\n </script>\n <script>\n //The selector to get the text/password/textarea input that has focus is: jQuery('[name='+jQuery('body').data('Selected_input')+']')\n jQuery(document).ready(function() {\n jQuery('body').bind({'focusin': function(Event){\n var Target = jQuery(Event.target);\n if(Target.is(':text')||Target.is(':password')||target.is('textarea'))\n {\n jQuery('body').data('Selected_input', Target.attr('name'));\n }\n }, 'focusout': function(Event){\n var Target = jQuery(Event.target);\n if(Target.is(':text')||Target.is(':password')||target.is('textarea'))\n {\n jQuery('body').data('Selected_input', null);\n }\n }});\n });\n </script>\n"
},
{
"answer_id": 15638700,
"author": "user2211815",
"author_id": 2211815,
"author_profile": "https://Stackoverflow.com/users/2211815",
"pm_score": 0,
"selected": false,
"text": "var selectedInput = null;\n$(function() {\n $('form').on('focus', 'input, textarea, select', function() {\n selectedInput = this;\n }).on('blur', 'input, textarea, select', function() {\n selectedInput = null;\n });\n});\n"
},
{
"answer_id": 30917118,
"author": "Kevin Cohen",
"author_id": 4481287,
"author_profile": "https://Stackoverflow.com/users/4481287",
"pm_score": 0,
"selected": false,
"text": "<input type=\"text\" onfocus=\"myFunction()\">\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/354718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25991/"
] |
354,723 | <p><strong>Problem:</strong> a table of coordinate lat/lngs. Two rows can potentially have the same coordinate. We want a query that returns a set of rows with unique coordinates (within the returned set). Note that <code>distinct</code> is not usable because I need to return the id column which is, by definition, distinct. This sort of works (<code>@maxcount</code> is the number of rows we need, <code>intid</code> is a unique int id column):</p>
<pre><code>select top (@maxcount) max(intid)
from Documents d
group by d.geoLng, d.geoLat
</code></pre>
<p>It will always return the same row for a given coordinate unfortunately, which is bit of a shame for my use. If only we had a <code>rand()</code> aggregate we could use instead of <code>max()</code>... Note that you can't use <code>max()</code> with guids created by <code>newid()</code>.</p>
<p>Any ideas?
(there's some more background here, if you're interested: <a href="http://www.itu.dk/~friism/blog/?p=121" rel="nofollow noreferrer">http://www.itu.dk/~friism/blog/?p=121</a>)</p>
<p>UPDATE: Full solution <a href="http://www.itu.dk/~friism/blog/?p=213" rel="nofollow noreferrer">here</a></p>
| [
{
"answer_id": 354959,
"author": "Tom H",
"author_id": 5696608,
"author_profile": "https://Stackoverflow.com/users/5696608",
"pm_score": 3,
"selected": true,
"text": "WITH cte AS\n(\n SELECT\n intID,\n ROW_NUMBER() OVER\n (\n PARTITION BY geoLat, geoLng\n ORDER BY NEWID()\n ) AS row_num,\n COUNT(intID) OVER (PARTITION BY geoLat, geoLng) AS TotalCount\n FROM\n dbo.Documents\n)\nSELECT TOP (@maxcount)\n intID, RAND(intID)\nFROM\n cte\nWHERE\n row_num = 1 + FLOOR(RAND() * TotalCount)\n"
},
{
"answer_id": 355762,
"author": "Mladen Prajdic",
"author_id": 31345,
"author_profile": "https://Stackoverflow.com/users/31345",
"pm_score": 1,
"selected": false,
"text": "select top (@maxcount) *\nfrom \n(\n select max(intid) as id from Documents d group by d.geoLng, d.geoLat\n) t \norder by newid()\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/354723",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2942/"
] |
354,724 | <p>Currently I use this reg ex:</p>
<pre><code>"\bI([ ]{1,2})([a-zA-Z]|\d){2,13}\b"
</code></pre>
<p>It was just brought to my attention that the text that I use this against could contain a "<code>\</code>" (backslash). How do I add this to the expression?</p>
| [
{
"answer_id": 354730,
"author": "user44511",
"author_id": 44511,
"author_profile": "https://Stackoverflow.com/users/44511",
"pm_score": 3,
"selected": true,
"text": "|\\\\ \\d"
},
{
"answer_id": 354742,
"author": "dreftymac",
"author_id": 42223,
"author_profile": "https://Stackoverflow.com/users/42223",
"pm_score": 1,
"selected": false,
"text": "([a-zA-Z]|\\d){2,13}\n ([\\w]{2,13})\n ([\\w\\x5c]{2,13})\n \"\\bI([\\x20]{1,2})([\\w\\x5c]{2,13})\\b\"\n"
},
{
"answer_id": 354850,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 0,
"selected": false,
"text": "\\d [:alpha:] [:digit:] [:alnum:] \\w perl -n -e 'print \"$2\\n\" if m/\\bI( {1,2})([a-zA-Z\\d\\\\]){2,13}\\b/'\n\nperl -n -e 'print \"$2\\n\" if m/\\bI( {1,2})([a-zA-Z\\d\\\\]{2,13})\\b/'\n I a123 $& m/\\bI( {1,2})([[:alnum:]\\\\]{2,13})\\b/\n"
},
{
"answer_id": 355103,
"author": "Axeman",
"author_id": 11289,
"author_profile": "https://Stackoverflow.com/users/11289",
"pm_score": 0,
"selected": false,
"text": "\\\\ \\b /\\bI([ ]{1,2})([\\p{IsAlnum}\\\\]{2,13})(?:[^\\w\\\\]|$)/ \n /\\bI([ ]{1,2})([\\p{IsAlnum}\\\\]{2,13})(?=[^\\w\\\\]|$)/ \n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/354724",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38349/"
] |
354,727 | <p>Using the WCF web programming model one can specify an operation contract like so:</p>
<pre><code>[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Xml, UriTemplate = "SomeRequest?qs1={qs1}&qs2={qs2}")]
XElement SomeRequest1(string qs1, string qs2);
</code></pre>
<p>Now if we had to make a contract that accepts an array of parameters with the same name (in this case <strong>qs1</strong>) contract like so...</p>
<pre><code>[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Xml, UriTemplate = "SomeRequest?qs1={qs1}&qs1={qs2}")]
XElement SomeRequest2(string qs1, string qs2);
</code></pre>
<p>We get the error message at run time when we make the invocation to the method:</p>
<blockquote>
<p>the query string must have 'name=value' pairs with unique names. Note that the names are case-insensitive. See the documentation for UriTemplate for more details.</p>
</blockquote>
<p>How does one define an HTTP service that exposes a resource with an array of parameters without resorting to a loosey-goosey interface?</p>
| [
{
"answer_id": 354823,
"author": "joshperry",
"author_id": 30587,
"author_profile": "https://Stackoverflow.com/users/30587",
"pm_score": 6,
"selected": true,
"text": "[OperationContract]\n[WebGet(ResponseFormat = WebMessageFormat.Xml,\n UriTemplate = \"SomeRequest?qs1={qs1}\")]\nXElement SomeRequest2(string[] qs1);\n public class CustomHttpBehavior : System.ServiceModel.Description.WebHttpBehavior\n{\n protected override System.ServiceModel.Dispatcher.QueryStringConverter GetQueryStringConverter(System.ServiceModel.Description.OperationDescription operationDescription)\n {\n return new CustomQueryStringConverter();\n }\n}\n public class CustomQueryStringConverter : System.ServiceModel.Dispatcher.QueryStringConverter\n{\n public override bool CanConvert(Type type)\n {\n if (type == typeof(string[]))\n {\n return true;\n }\n\n return base.CanConvert(type);\n }\n\n public override object ConvertStringToValue(string parameter, Type parameterType)\n {\n if (parameterType == typeof(string[]))\n {\n string[] parms = parameter.Split(',');\n return parms;\n }\n\n return base.ConvertStringToValue(parameter, parameterType);\n }\n\n public override string ConvertValueToString(object parameter, Type parameterType)\n {\n if (parameterType == typeof(string[]))\n {\n string valstring = string.Join(\",\", parameter as string[]);\n return valstring;\n }\n\n return base.ConvertValueToString(parameter, parameterType);\n }\n}\n public class CustomHttpBehaviorExtensionElement : System.ServiceModel.Configuration.BehaviorExtensionElement\n{\n protected override object CreateBehavior()\n {\n return new CustomHttpBehavior();\n }\n\n public override Type BehaviorType\n {\n get { return typeof(CustomHttpBehavior); }\n }\n}\n <webHttp /> <system.serviceModel>\n <services>\n <service name=\"NameSpace.ServiceClass\">\n <endpoint address=\"\" behaviorConfiguration=\"MyServiceBehavior\"\n binding=\"webHttpBinding\" contract=\"NameSpace.ServiceClass\" />\n </service>\n </services>\n <behaviors>\n <endpointBehaviors>\n <behavior name=\"MyServiceBehavior\">\n <customWebHttp/>\n </behavior>\n </endpointBehaviors>\n </behaviors>\n <extensions>\n <behaviorExtensions>\n <add name=\"customWebHttp\" type=\"NameSpace.CustomHttpBehaviorExtensionElement, MyAssemblyName\" />\n </behaviorExtensions>\n </extensions>\n <serviceHostingEnvironment aspNetCompatibilityEnabled=\"true\" />\n </system.serviceModel>\n"
},
{
"answer_id": 357952,
"author": "joshperry",
"author_id": 30587,
"author_profile": "https://Stackoverflow.com/users/30587",
"pm_score": 3,
"selected": false,
"text": "[WebGet(ResponseFormat = WebMessageFormat.Xml,\n UriTemplate = \"SomeRequest?qs1={*qs1}\")]\nXElement SomeRequest2(string qs1);\n"
},
{
"answer_id": 1957653,
"author": "pootow",
"author_id": 238055,
"author_profile": "https://Stackoverflow.com/users/238055",
"pm_score": 2,
"selected": false,
"text": " <extensions>\n <behaviorExtensions>\n <add name=\"customWebHttp\" type=\"NameSpace.CustomHttpBehaviorExtensionElement, MyAssemblyName, NOT SUFFICIENT HERE\" />\n </behaviorExtensions>\n </extensions>\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/354727",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19219/"
] |
354,738 | <p>I am making a small <strong>C#</strong> application and would like to extract a <strong>tag cloud</strong> from a simple plain text. Is there a function that could do that for me?</p>
| [
{
"answer_id": 354759,
"author": "Nathan W",
"author_id": 6335,
"author_profile": "https://Stackoverflow.com/users/6335",
"pm_score": 0,
"selected": false,
"text": "Dim Words = \"Hello World ))))) This is a test Hello World\"\nDim CountTheWords = From str In Words.Split(\" \") _\n Where Char.IsLetter(str) _\n Group By str Into Count()\n"
},
{
"answer_id": 354776,
"author": "Ramiro Berrelleza",
"author_id": 548,
"author_profile": "https://Stackoverflow.com/users/548",
"pm_score": 4,
"selected": false,
"text": "double max = Searches.Max(x => (double)x.Count);\nList<SearchTagElement> processedTags = new List<SearchTagElement>();\n\nforeach (SearchRecordEntity sd in Searches)\n{\n var element = new SearchTagElement(); \n\n double count = (double)sd.Count;\n double percent = (count / max) * 100; \n\n if (percent < 20)\n {\n element.TagCategory = \"smallestTag\";\n }\n else if (percent < 40)\n {\n element.TagCategory = \"smallTag\";\n }\n else if (percent < 60)\n {\n element.TagCategory = \"mediumTag\";\n }\n else if (percent < 80)\n {\n element.TagCategory = \"largeTag\";\n }\n else\n {\n element.TagCategory = \"largestTag\";\n }\n\n processedTags.Add(element);\n}\n"
},
{
"answer_id": 354825,
"author": "ine",
"author_id": 4965,
"author_profile": "https://Stackoverflow.com/users/4965",
"pm_score": 2,
"selected": false,
"text": "the an a"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/354738",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19159/"
] |
354,739 | <p>I have noticed a common technique is to place a generic container <em>div</em> in the root of the <em>body</em> tag:</p>
<pre><code><html>
<head>
...
</head>
<body>
<div id="container">
...
</div>
</body>
</html>
</code></pre>
<p>Is there a valid reason for doing this? Why can't the CSS just reference the <em>body</em> tag?</p>
| [
{
"answer_id": 354752,
"author": "Jonathan Tran",
"author_id": 12887,
"author_profile": "https://Stackoverflow.com/users/12887",
"pm_score": 6,
"selected": false,
"text": "margin-left: auto; margin-right: auto"
},
{
"answer_id": 3065886,
"author": "Quentin",
"author_id": 19068,
"author_profile": "https://Stackoverflow.com/users/19068",
"pm_score": 2,
"selected": false,
"text": "width max-width"
},
{
"answer_id": 14605858,
"author": "Michael Albers",
"author_id": 2025610,
"author_profile": "https://Stackoverflow.com/users/2025610",
"pm_score": 2,
"selected": false,
"text": "html {\n text-align: center;\n}\n\nbody {\n margin: 0 auto;\n width: 960px;\n}\n"
},
{
"answer_id": 73008489,
"author": "Isaac Pak",
"author_id": 1991020,
"author_profile": "https://Stackoverflow.com/users/1991020",
"pm_score": -1,
"selected": false,
"text": "div class=\"container\""
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/354739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44810/"
] |
354,745 | <p>How can i make my Java Swing GUI Components [Right To Left] for Arabic language from NetBeans Desktop Application?</p>
| [
{
"answer_id": 354816,
"author": "John Gardner",
"author_id": 13687,
"author_profile": "https://Stackoverflow.com/users/13687",
"pm_score": 4,
"selected": true,
"text": "Component.setComponentOrientation( ComponentOrientation.RIGHT_TO_LEFT )\n"
},
{
"answer_id": 356994,
"author": "Markus",
"author_id": 45064,
"author_profile": "https://Stackoverflow.com/users/45064",
"pm_score": 3,
"selected": false,
"text": " Component.setComponentOrientation( ComponentOrientation.RIGHT_TO_LEFT )\n"
},
{
"answer_id": 25226955,
"author": "Mina Girgis",
"author_id": 2677646,
"author_profile": "https://Stackoverflow.com/users/2677646",
"pm_score": 0,
"selected": false,
"text": " Component[] component = contentPane.getComponents();\n for(int i=0; i<component.length; i++){\n component[i].applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);\n Component[] cp = ((Container) component[i]).getComponents();\n for(int j=0; j<cp.length; j++){\n try{\n ((Component) ((JComboBox) cp[j]).getRenderer()).applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);\n }catch(Exception e){\n continue;\n\n }\n }\n }\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/354745",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
354,755 | <p>I'm working on a blog application in Django. Naturally, I have models set up such that there are Posts and Comments, and a particular Post may have many Comments; thus, Post is a ForeignKey in the Comments model.</p>
<p>Given a Post object, is there an easy way (ideally, through a method call) to find out how many Comments belong to the Post?</p>
| [
{
"answer_id": 354765,
"author": "Daniel Naab",
"author_id": 32638,
"author_profile": "https://Stackoverflow.com/users/32638",
"pm_score": 4,
"selected": true,
"text": "Comments.objects.filter(post=post).count()\n post.comment_set.count()\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/354755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28804/"
] |
354,763 | <p>I am setting up a very small MySQL database that stores, first name, last name, email and phone number and am struggling to find the 'perfect' datatype for each field. I know there is no such thing as a perfect answer, but there must be some sort of common convention for commonly used fields such as these. For instance, I have determined that an unformatted US phone number is too big to be stored as an unsigned int, it must be at least a bigint.</p>
<p>Because I am sure other people would probably find this useful, I dont want to restrict my question to just the fields I mentioned above.</p>
<p>What datatypes are appropriate for common database fields? Fields like phone number, email and address?</p>
| [
{
"answer_id": 354800,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 3,
"selected": false,
"text": "[field length]"
},
{
"answer_id": 1972154,
"author": "yentsun",
"author_id": 216042,
"author_profile": "https://Stackoverflow.com/users/216042",
"pm_score": 6,
"selected": false,
"text": "| Column | Data type | Note\n| ---------------- | ------------- | -------------------------------------\n| id | INTEGER | AUTO_INCREMENT, UNSIGNED | \n| uuid | CHAR(36) | or CHAR(16) binary | \n| title | VARCHAR(255) | | \n| full name | VARCHAR(70) | | \n| gender | TINYINT | UNSIGNED | \n| description | TINYTEXT | often may not be enough, use TEXT \n instead \n| post body | TEXT | | \n| email | VARCHAR(255) | | \n| url | VARCHAR(2083) | MySQL version < 5.0.3 - use TEXT | \n| salt | CHAR(x) | randomly generated string, usually of \n fixed length (x) \n| digest (md5) | CHAR(32) | | \n| phone number | VARCHAR(20) | | \n| US zip code | CHAR(5) | Use CHAR(10) if you store extended \n codes \n| US/Canada p.code | CHAR(6) | | \n| file path | VARCHAR(255) | | \n| 5-star rating | DECIMAL(3,2) | UNSIGNED | \n| price | DECIMAL(10,2) | UNSIGNED | \n| date (creation) | DATE/DATETIME | usually displayed as initial date of \n a post | \n| date (tracking) | TIMESTAMP | can be used for tracking changes in a \n post | \n| tags, categories | TINYTEXT | comma separated values * | \n| status | TINYINT(1) | 1 – published, 0 – unpublished, … You \n can also use ENUM for human-readable \n values\n| json data | JSON | or LONGTEXT \n"
},
{
"answer_id": 66188578,
"author": "HoldOffHunger",
"author_id": 2430549,
"author_profile": "https://Stackoverflow.com/users/2430549",
"pm_score": 2,
"selected": false,
"text": "INT(11) BINARY(x) BLOB(x) binary SELECT HEX(field)... SELECT ... WHERE field = UNHEX(\"ABCD....\") DATETIME DATE TIME DATETIME DATETIME BIT(1) BOOLEAN(1) BOOLEAN TINYINT(1) INT(11) SUM() VARCHAR(255) Person.GivenName Person.FamilyName VARCHAR(256) 320 VARCHAR(255) VARCHAR(10) 12345 12345-6789 VARCHAR(2000) DECIMAL(11,2)"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/354763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44816/"
] |
354,769 | <p>The (web based) software I am working on needs a way for users to be able to customize an email template.</p>
<p>I'm familiar with TinyMCE et al. web based wysiwyg editors. However they strive to produce valid (x)html markup, with heavy use of style sheets. All of which won't render nicely in email clients (yes, I'm looking at you.. outlook 2007). </p>
<p>Is anyone aware of one that can be configured for generating email friendly html?</p>
| [
{
"answer_id": 354800,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 3,
"selected": false,
"text": "[field length]"
},
{
"answer_id": 1972154,
"author": "yentsun",
"author_id": 216042,
"author_profile": "https://Stackoverflow.com/users/216042",
"pm_score": 6,
"selected": false,
"text": "| Column | Data type | Note\n| ---------------- | ------------- | -------------------------------------\n| id | INTEGER | AUTO_INCREMENT, UNSIGNED | \n| uuid | CHAR(36) | or CHAR(16) binary | \n| title | VARCHAR(255) | | \n| full name | VARCHAR(70) | | \n| gender | TINYINT | UNSIGNED | \n| description | TINYTEXT | often may not be enough, use TEXT \n instead \n| post body | TEXT | | \n| email | VARCHAR(255) | | \n| url | VARCHAR(2083) | MySQL version < 5.0.3 - use TEXT | \n| salt | CHAR(x) | randomly generated string, usually of \n fixed length (x) \n| digest (md5) | CHAR(32) | | \n| phone number | VARCHAR(20) | | \n| US zip code | CHAR(5) | Use CHAR(10) if you store extended \n codes \n| US/Canada p.code | CHAR(6) | | \n| file path | VARCHAR(255) | | \n| 5-star rating | DECIMAL(3,2) | UNSIGNED | \n| price | DECIMAL(10,2) | UNSIGNED | \n| date (creation) | DATE/DATETIME | usually displayed as initial date of \n a post | \n| date (tracking) | TIMESTAMP | can be used for tracking changes in a \n post | \n| tags, categories | TINYTEXT | comma separated values * | \n| status | TINYINT(1) | 1 – published, 0 – unpublished, … You \n can also use ENUM for human-readable \n values\n| json data | JSON | or LONGTEXT \n"
},
{
"answer_id": 66188578,
"author": "HoldOffHunger",
"author_id": 2430549,
"author_profile": "https://Stackoverflow.com/users/2430549",
"pm_score": 2,
"selected": false,
"text": "INT(11) BINARY(x) BLOB(x) binary SELECT HEX(field)... SELECT ... WHERE field = UNHEX(\"ABCD....\") DATETIME DATE TIME DATETIME DATETIME BIT(1) BOOLEAN(1) BOOLEAN TINYINT(1) INT(11) SUM() VARCHAR(255) Person.GivenName Person.FamilyName VARCHAR(256) 320 VARCHAR(255) VARCHAR(10) 12345 12345-6789 VARCHAR(2000) DECIMAL(11,2)"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/354769",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23300/"
] |
354,796 | <p>I am writing Eclipse plugins, and frequently have a situation where a running Job needs to pause for a short while, run something asynchronously on the UI thread, and resume.</p>
<p>So my code usually looks something like:</p>
<pre class="lang-java prettyprint-override"><code>Display display = Display.getDefault();
display.syncExec(new Runnable() {
public void run() {
// Do some calculation
// How do I return a value from here?
}
});
// I want to be able to use the calculation result here!
</code></pre>
<p>One way to do it is to have the entire Job class have some field. Another is to use a customized class (rather than anonymous for this and use its resulting data field, etc.
What's the best and most elegant approach?</p>
| [
{
"answer_id": 355039,
"author": "SCdF",
"author_id": 1666,
"author_profile": "https://Stackoverflow.com/users/1666",
"pm_score": 0,
"selected": false,
"text": "run() final Container container = new Container();\nDisplay display = Display.getDefault();\ndisplay.syncExec(new Runnable()\n{\n public void run()\n {\n container.setValue(\"foo\");\n }\n}\nSystem.out.println(container.getValue());\n public class Container {\n private Object value;\n public Object getValue() {\n return value;\n }\n public void setValue(Object o) {\n value = o;\n }\n}\n syncExec asyncExec()"
},
{
"answer_id": 355090,
"author": "Dave Ray",
"author_id": 40310,
"author_profile": "https://Stackoverflow.com/users/40310",
"pm_score": 3,
"selected": false,
"text": "final Object[] result = new Object[1];\nDisplay display = Display.getDefault();\ndisplay.syncExec(new Runnable()\n{\n public void run()\n {\n result[0] = \"foo\";\n }\n}\nSystem.out.println(result[0]);\n final AtomicReference<Object> result = new AtomicReference<Object>();\nDisplay display = Display.getDefault();\ndisplay.syncExec(new Runnable()\n{\n public void run()\n {\n result.set(\"foo\");\n }\n}\nSystem.out.println(result.get());\n"
},
{
"answer_id": 356186,
"author": "jamesh",
"author_id": 4737,
"author_profile": "https://Stackoverflow.com/users/4737",
"pm_score": 3,
"selected": true,
"text": "Runnable asyncExec java.util.concurrent.Future"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/354796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23072/"
] |
354,799 | <p>I'm working on a website with a em-based layout (so it can stretch and compress gracefully when users increase or decrease font size). This site has a header that should be displayed across all pages. I have a "header" div in all pages, and the site-wide css file includes the code:</p>
<pre><code>#header
{
width: 50em;
height: 6em;
margin-bottom: .5em;
background: url("/IMAGES/header.png");
}
</code></pre>
<p>The problem is that this doesn't really stretch gracefully. When text size increase, the height and width change, but **the image doesn't increase in size; it simply repeats*.*</p>
<p><strong>How can I make my image stretch and squish, instead of repeating or getting cut off?</strong> (I'd like a css-based solution if possible... I've got some html ideas in store, already).</p>
| [
{
"answer_id": 355039,
"author": "SCdF",
"author_id": 1666,
"author_profile": "https://Stackoverflow.com/users/1666",
"pm_score": 0,
"selected": false,
"text": "run() final Container container = new Container();\nDisplay display = Display.getDefault();\ndisplay.syncExec(new Runnable()\n{\n public void run()\n {\n container.setValue(\"foo\");\n }\n}\nSystem.out.println(container.getValue());\n public class Container {\n private Object value;\n public Object getValue() {\n return value;\n }\n public void setValue(Object o) {\n value = o;\n }\n}\n syncExec asyncExec()"
},
{
"answer_id": 355090,
"author": "Dave Ray",
"author_id": 40310,
"author_profile": "https://Stackoverflow.com/users/40310",
"pm_score": 3,
"selected": false,
"text": "final Object[] result = new Object[1];\nDisplay display = Display.getDefault();\ndisplay.syncExec(new Runnable()\n{\n public void run()\n {\n result[0] = \"foo\";\n }\n}\nSystem.out.println(result[0]);\n final AtomicReference<Object> result = new AtomicReference<Object>();\nDisplay display = Display.getDefault();\ndisplay.syncExec(new Runnable()\n{\n public void run()\n {\n result.set(\"foo\");\n }\n}\nSystem.out.println(result.get());\n"
},
{
"answer_id": 356186,
"author": "jamesh",
"author_id": 4737,
"author_profile": "https://Stackoverflow.com/users/4737",
"pm_score": 3,
"selected": true,
"text": "Runnable asyncExec java.util.concurrent.Future"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/354799",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1615/"
] |
354,811 | <p>I have a ToggleButtonBar with a DataProvider setup like this:</p>
<pre><code> <mx:ToggleButtonBar itemClick="clickHandler(event);" selectedIndex="0">
<mx:dataProvider>
<mx:String>{resourceManager.getString('dashboard','daily')}</mx:String>
<mx:String>{resourceManager.getString('dashboard','monthly')}</mx:String>
<mx:String>{resourceManager.getString('dashboard','quarterly')}</mx:String>
<mx:String>{resourceManager.getString('dashboard','yearly')}</mx:String>
</mx:dataProvider>
</mx:ToggleButtonBar>
</code></pre>
<p>To switch locale to Chinese, I have a combobox with this handler:</p>
<pre><code>resourceManager.localeChain = "zh_CN";
</code></pre>
<p>My problem is that on locale change, while the labels for all the other controls on the screen dynamically reload for the new locale, the <code>dataProvider</code> values don't refresh.
I can manually reset them in code, but is there a cleaner solution? </p>
| [
{
"answer_id": 355822,
"author": "Alexandru",
"author_id": 44226,
"author_profile": "https://Stackoverflow.com/users/44226",
"pm_score": 1,
"selected": false,
"text": "[Bindable(\"langChange\")]\npublic function get dataProviderToggleB():ArrayCollection\n{\n var arr :ArrayCollection = new ArrayCollection();\n\n arr.addItem(resourceManager.getString('dashboard','daily'));\n arr.addItem(resourceManager.getString('dashboard','monthly'));\n\n return arr; \n}\n dispatchEvent(new Event(\"langChange\"));\n <mx:ToggleButtonBar dataProvider=\"{dataProviderToggleB} itemClick=\"clickHandler(event);\" selectedIndex=\"0\">\n"
},
{
"answer_id": 360376,
"author": "Ryan Guill",
"author_id": 7186,
"author_profile": "https://Stackoverflow.com/users/7186",
"pm_score": 3,
"selected": true,
"text": "<mx:Script>\n <![CDATA[\n [Bindable]\n myArray:Array = new Array(\n [resourceManager.getString('dashboard','daily')]\n , [resourceManager.getString('dashboard','monthly')]\n , [{resourceManager.getString('dashboard','quarterly')]\n , [resourceManager.getString('dashboard','yearly')]);\n\n ]]>\n</mx:Script>\n\n\n<mx:ToggleButtonBar itemClick=\"clickHandler(event);\" \nselectedIndex=\"0\" id=\"myToggleButtonBar\" dataprovider=\"{myArray}\" />\n myToggleButtonBar.dataProvider = myArray; \n"
},
{
"answer_id": 9128069,
"author": "xastor",
"author_id": 151657,
"author_profile": "https://Stackoverflow.com/users/151657",
"pm_score": 0,
"selected": false,
"text": "<mx:ToggleButtonBar itemClick=\"clickHandler(event);\" selectedIndex=\"0\" \n dataProvider=\"{[ (resourceManager.getString('dashboard','daily')),\n (resourceManager.getString('dashboard','monthly')),\n (resourceManager.getString('dashboard','quarterly')), \n (resourceManager.getString('dashboard','yearly')) ]}\">\n</mx:ToggleButtonBar>\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/354811",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16534/"
] |
354,835 | <p>If I just want to know if a domain name is reserved; is it sufficient to use this command and see if any domain name servers turn up, in which case it's reserved?</p>
<pre><code>host -t NS example.com
</code></pre>
<p>It's a lot faster than visiting <a href="http://www.internic.net/whois.html" rel="nofollow noreferrer">http://www.internic.net/whois.html</a> and typing example.com to get much more detailed results, which I'm not interested in anyway.</p>
| [
{
"answer_id": 354839,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 1,
"selected": false,
"text": "whois stackoverflow.com\n"
},
{
"answer_id": 356546,
"author": "Alnitak",
"author_id": 6782,
"author_profile": "https://Stackoverflow.com/users/6782",
"pm_score": 2,
"selected": true,
"text": "whois"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/354835",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
354,837 | <p>Why one would use one of the following packages instead of the other?</p>
<ul>
<li>Java Logging</li>
<li>Commons Logging</li>
<li>Log4j</li>
<li>SLF4j</li>
<li>Logback</li>
</ul>
| [
{
"answer_id": 354868,
"author": "Stephen",
"author_id": 37193,
"author_profile": "https://Stackoverflow.com/users/37193",
"pm_score": 7,
"selected": true,
"text": "logger.debug(\"The entry is {}.\", entry);\n//which expands effectively to\nif (logger.isDebugEnabled()){\n // Note that it's actually *more* efficient than this - see Huxi's comment below...\n logger.debug(\"The entry is \" + entry + \".\"); \n}\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/354837",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39057/"
] |
354,838 | <p>I want to convert user-submitted date format (mm/dd/yyyy) to a MySQL date format (YYYY-mm-dd). Submission is via a simple PHP form direc tto MySQL database. </p>
| [
{
"answer_id": 354844,
"author": "Paolo Bergantino",
"author_id": 16417,
"author_profile": "https://Stackoverflow.com/users/16417",
"pm_score": 3,
"selected": false,
"text": "$mysql_date = date('Y-m-d H:i:s', strtotime($user_date));\n"
},
{
"answer_id": 14595598,
"author": "John Conde",
"author_id": 250259,
"author_profile": "https://Stackoverflow.com/users/250259",
"pm_score": 0,
"selected": false,
"text": "$datetime = new DateTime($user_date);\necho $datetime->format('Y-m-d H:i:s');\n"
},
{
"answer_id": 20986133,
"author": "Simeon",
"author_id": 1378769,
"author_profile": "https://Stackoverflow.com/users/1378769",
"pm_score": 0,
"selected": false,
"text": " CONVERT(VARCHAR(11),$user_date,111)\n\n //e.g.\n SELECT CONVERT(VARCHAR(11),DATEFIELD,111) AS DATE\n //or\n SET DATEFIELD = CONVERT(VARCHAR(11),'\".$user_date.\"',111)\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/354838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
354,840 | <p>I'm developing an application with Adobe Flex and AIR, and I've been banging my head against the wall trying to figure out how to solve a scrolling issue.</p>
<p>The basic structure of my main application window (simplified greatly) is this:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml"
paddingTop="0" paddingRight="0" paddingBottom="0" paddingLeft="0"
width="800" height="600" layout="vertical" verticalAlign="top"
>
<mx:VBox id="MainContainer" width="100%" height="100%">
<mx:Panel id="Toolbars" width="100%" height="25" />
<mx:HDividedBox width="100%" height="100%" >
<mx:Panel id="Navigation" minWidth="200" height="100%" />
<mx:VBox id="MainContent" width="100%">
<mx:Panel width="100%" height="200" />
<mx:Panel width="100%" height="200" />
<mx:Panel width="100%" height="200" />
<mx:Panel width="100%" height="200" />
<mx:Panel width="100%" height="200" />
</mx:VBox>
<mx:Panel id="HelpContent" minWidth="200" height="100%" />
</mx:HDividedBox>
<mx:Panel id="FooterContent" width="100%" height="25" />
</mx:VBox>
</mx:WindowedApplication>
</code></pre>
<p>The trouble is that the "MainContent" box might contain a huge list of subcomponents, and the presence of that long list causes a vertical scrollbar to appear at the highest level of the GUI, surrounding the "MainContainer" vbox.</p>
<p>It looks really silly, having scrollbars around the entire application window.</p>
<p>What I'm looking for instead is a solution where the scrollbar is only applied to the "MainContent" vbox (as well as the Navigation and HelpContent panels, if their content stretches past the window bounds).</p>
<p>I found a <a href="https://stackoverflow.com/questions/245292/best-way-to-size-containers-in-flex-to-obey-only-parent-containers-explicit-dim">related question</a> on StackOverflow, where the problem's solution was to use "autoLayout" and "verticalScrollPolicy" attributes on parent containers.</p>
<p>So I tried adding autoLayout="false" and verticalScrollPolicy="off" attributes to all of the parent containers, as well as verticalScrollPolicy="on" to the "MainContent" vbox. But the end-result of that experiment was that the content was simply clipped from the main container (and a useless scrollbar with no thumb was added to the MainContent vbox).</p>
<p>Anyone know how to solve this?</p>
| [
{
"answer_id": 355898,
"author": "hasseg",
"author_id": 4111,
"author_profile": "https://Stackoverflow.com/users/4111",
"pm_score": 0,
"selected": false,
"text": "measure() Box package whatever\n{\n import mx.containers.Box;\n\n /**\n * A Box that has no measure() implementation.\n * \n * <p>\n * See http://old.nabble.com/-flex_india%3A3318--Size-layout-issues-with-respect-to-parent-containers-to12882767.html\n * for more info.\n * </p>\n */\n public class NonMeasuredBox extends Box\n {\n /**\n * Constructor\n */\n public function NonMeasuredBox():void\n {\n super();\n }\n\n override protected function measure():void { /* disabled */ }\n }\n}\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/354840",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22979/"
] |
354,842 | <p>I would like to create my ObjectDataProvider in my C# code behind rather than my XAML.</p>
<p>I was wondering how to change this XAML into equivalent C#. The XAML was generated by Microsoft Expression Blend 2, so the d: namespace can be ignored safely.</p>
<pre><code><ObjectDataProvider x:Key="FooSourceDS" ObjectType="{x:Type myNS:FooSource}" d:IsDataSource="True"/>
</code></pre>
<p>myNS is a namespace referencing my CLR object. </p>
<p>I'm getting hung up on specifying the ObjectType in C#:</p>
<pre><code>ObjectDataProvider FooSourceDS = new ObjectDataProvider();
FooSourceDS.ObjectType = myNamespace.FooSource;
</code></pre>
<p>The Intellisence is correctly identifying FooSource as a 'type' which is what ObjectType is looking for isn't it? </p>
| [
{
"answer_id": 355898,
"author": "hasseg",
"author_id": 4111,
"author_profile": "https://Stackoverflow.com/users/4111",
"pm_score": 0,
"selected": false,
"text": "measure() Box package whatever\n{\n import mx.containers.Box;\n\n /**\n * A Box that has no measure() implementation.\n * \n * <p>\n * See http://old.nabble.com/-flex_india%3A3318--Size-layout-issues-with-respect-to-parent-containers-to12882767.html\n * for more info.\n * </p>\n */\n public class NonMeasuredBox extends Box\n {\n /**\n * Constructor\n */\n public function NonMeasuredBox():void\n {\n super();\n }\n\n override protected function measure():void { /* disabled */ }\n }\n}\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/354842",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36234/"
] |
354,853 | <p>Regex to Find Second Char is Alpha up to 5 Alpha Followed by 1 numeral.</p>
<p>Thanks</p>
| [
{
"answer_id": 354865,
"author": "UnkwnTech",
"author_id": 115,
"author_profile": "https://Stackoverflow.com/users/115",
"pm_score": 0,
"selected": false,
"text": ".\\w{1,5}\\d\n"
},
{
"answer_id": 354878,
"author": "Jonathan Lonowski",
"author_id": 15031,
"author_profile": "https://Stackoverflow.com/users/15031",
"pm_score": 0,
"selected": false,
"text": "/.[A-Za-z]{1,6}\\d/\n"
},
{
"answer_id": 354960,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": -1,
"selected": false,
"text": "[a-zA-Z {1,5"
},
{
"answer_id": 356471,
"author": "user38349",
"author_id": 38349,
"author_profile": "https://Stackoverflow.com/users/38349",
"pm_score": 1,
"selected": false,
"text": "Dim IsSidStar As Boolean = False\n If aAirways.Name.Length > 2 Then\n Dim a2ndChar As Char = aAirways.Name(1)\n Dim alastChar As Char = aAirways.Name(aAirways.Name.ToString.Length - 1)\n Dim a2ndlastChar As Char = aAirways.Name(aAirways.Name.ToString.Length - 2)\n\n If Char.IsLetter(a2ndChar) = True AndAlso Char.IsNumber(alastChar) = True AndAlso Char.IsNumber(a2ndlastChar) = False Then\n IsSidStar = True\n End If\n End If\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/354853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38349/"
] |
354,869 | <p>I want to create a C# program to provision Windows Mobile devices. I have found MSDN documentation on a function called <a href="http://msdn.microsoft.com/en-us/library/ms852998.aspx" rel="nofollow noreferrer">DMProcessConfigXML</a>, but no instructions on how to use this function.</p>
<p>How can I use this function in my Windows Mobile app? I suspect it has something to do with using pinvoke.</p>
<p>Thanks,<br>
Paul</p>
| [
{
"answer_id": 355397,
"author": "Shane Powell",
"author_id": 23235,
"author_profile": "https://Stackoverflow.com/users/23235",
"pm_score": 1,
"selected": false,
"text": "<wap-provisioningdoc>\n <characteristic type=\"Registry\">\n <characteristic type=\"HKCU\\ControlPanel\\Home\">\n <parm-query name=\"Timeout\"/>\n </characteristic>\n </characteristic>\n</wap-provisioningdoc>\n <wap-provisioningdoc>\n <characteristic type=\"Registry\">\n <characteristic type=\"HKCU\\ControlPanel\\Home\">\n <parm name=\"Timeout\" value=\"10000\"/>\n </characteristic>\n </characteristic>\n</wap-provisioningdoc>\n"
},
{
"answer_id": 365751,
"author": "mjf",
"author_id": 44645,
"author_profile": "https://Stackoverflow.com/users/44645",
"pm_score": 4,
"selected": true,
"text": "XmlDocument configDoc = new XmlDocument();\nconfigDoc.LoadXml(\n \"<wap-provisioningdoc>\"+\n \"<characteristic type=\\\"BrowserFavorite\\\">\"+\n \"<characteristic type=\\\"Microsoft\\\">\"+\n \"<parm name=\\\"URL\\\" value=\\\"http://www.microsoft.com\\\"/>\"+\n \"</characteristic>\"+\n \"</characteristic>\"+\n \"</wap-provisioningdoc>\"\n );\nConfigurationManager.ProcessConfiguration(configDoc, false);\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/354869",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37481/"
] |
354,870 | <p>Is there a command in oracle 9i that displays the foreign keys of a table and also the table that those foreign keys reference?</p>
<p>I was searching, did not find anything but i found an equivalent command that works with MySql which is SHOW CREATE TABLE </p>
<p>Is there an equivalent command for this within oracle's SQL?</p>
<p>I appreciate your response, however I thought there was a really short way of doing this like MySql. </p>
| [
{
"answer_id": 354944,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 1,
"selected": false,
"text": "SELECT fk.owner, fk.constraint_name, fk.table_name, fc.column_name,\n pk.owner, pk.constraint_name, pk.table_name, pc.column_name\nFROM all_constraints fk\n JOIN all_cons_columns fc ON (fk.owner = fc.owner AND fk.constraint_name = fc.constraint_name)\n JOIN (all_constraints pk\n JOIN all_cons_columns pc ON (pk.owner = pc.owner AND pk.constraint_name = pc.constraint_name)) \n ON (fk.r_owner = pk.owner AND fk.r_constraint_name = pk.constraint_name\n AND fc.position = pc.position)\nWHERE fk.constraint_type = 'R' AND pk.constraint_type IN ('P', 'U')\n AND fk.owner = '<schema>' AND fk.table_name = '<table>';\n"
},
{
"answer_id": 354946,
"author": "ninesided",
"author_id": 1030,
"author_profile": "https://Stackoverflow.com/users/1030",
"pm_score": 2,
"selected": false,
"text": "SELECT\n acc.table_name\n ,acc.column_name\n ,acc.constraint_name\n ,ac.r_constraint_name AS referenced_constraint\nFROM all_cons_columns acc\nINNER JOIN all_constraints ac ON (acc.constraint_name = ac.constraint_name)\nWHERE acc.table_name = UPPER('your_table_here');\n"
},
{
"answer_id": 354964,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 2,
"selected": false,
"text": "dbms_metadata SELECT dbms_metadata.get_ddl('TABLE', '<table>', '<schema>') FROM dual;\n"
},
{
"answer_id": 2031081,
"author": "bpelhos",
"author_id": 246771,
"author_profile": "https://Stackoverflow.com/users/246771",
"pm_score": 0,
"selected": false,
"text": "select \n DBMS_METADATA.GET_DEPENDENT_DDL('REF_CONSTRAINT' ,atb.table_name, atb.owner) \nfrom \n all_tables atb, all_constraints ac\nwhere \n atb.owner = ac.owner and\n ac.constraint_type = 'R' and\n ac.table_name = atb.table_name and\n atb.owner = 'YOURSCHEMA';\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/354870",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31274/"
] |
354,875 | <p>I have been working on a Java project for a class for a while now. It is an implementation of a linked list (here called <code>AddressList</code>, containing simple nodes called <code>ListNode</code>). The catch is that everything would have to be done with recursive algorithms. I was able to do everything fine sans one method: <code>public AddressList reverse()</code> </p>
<p>ListNode: </p>
<pre><code>public class ListNode{
public String data;
public ListNode next;
}
</code></pre>
<p>Right now my <code>reverse</code> function just calls a helper function that takes an argument to allow recursion.</p>
<pre><code>public AddressList reverse(){
return new AddressList(this.reverse(this.head));
}
</code></pre>
<p>With my helper function having the signature of <code>private ListNode reverse(ListNode current)</code>.</p>
<p>At the moment, I have it working iteratively using a stack, but this is not what the specification requires. I had found an algorithm in C that recursively reversed and converted it to Java code by hand, and it worked, but I had no understanding of it.</p>
<p>Edit: Nevermind, I figured it out in the meantime.</p>
<pre><code>private AddressList reverse(ListNode current, AddressList reversedList){
if(current == null)
return reversedList;
reversedList.addToFront(current.getData());
return this.reverse(current.getNext(), reversedList);
}
</code></pre>
<p>While I'm here, does anyone see any problems with this route?</p>
| [
{
"answer_id": 354906,
"author": "Ari Ronen",
"author_id": 34957,
"author_profile": "https://Stackoverflow.com/users/34957",
"pm_score": 5,
"selected": false,
"text": "\n //Takes as parameters a node in a linked list, and p, the previous node in that list\n //returns the head of the new list\n Node reverse(Node n,Node p){ \n if(n==null) return null;\n if(n.next==null){ //if this is the end of the list, then this is the new head\n n.next=p;\n return n;\n }\n Node r=reverse(n.next,n); //call reverse for the next node, \n //using yourself as the previous node\n n.next=p; //Set your next node to be the previous node \n return r; //Return the head of the new list\n }\n "
},
{
"answer_id": 354937,
"author": "plinth",
"author_id": 20481,
"author_profile": "https://Stackoverflow.com/users/20481",
"pm_score": 9,
"selected": true,
"text": "public ListNode Reverse(ListNode list)\n{\n if (list == null) return null; // first question\n\n if (list.next == null) return list; // second question\n\n // third question - in Lisp this is easy, but we don't have cons\n // so we grab the second element (which will be the last after we reverse it)\n\n ListNode secondElem = list.next;\n\n // bug fix - need to unlink list from the rest or you will get a cycle\n list.next = null;\n\n // then we reverse everything from the second element on\n ListNode reverseRest = Reverse(secondElem);\n\n // then we join the two lists\n secondElem.next = list;\n\n return reverseRest;\n}\n"
},
{
"answer_id": 356071,
"author": "Devesh Rao",
"author_id": 44944,
"author_profile": "https://Stackoverflow.com/users/44944",
"pm_score": 3,
"selected": false,
"text": "Head \n| \n1-->2-->3-->4-->N-->null\n\nnull-->1-->2-->3-->4-->N<--null\n\nnull-->1-->2-->3-->4<--N<--null\n\nnull-->1-->2-->3<--4<--N<--null\n\nnull-->1-->2<--3<--4<--N<--null\n\nnull-->1<--2<--3<--4<--N<--null\n\nnull<--1<--2<--3<--4<--N\n |\n Head\n public ListNode reverse(ListNode toBeNextNode, ListNode currentNode)\n{ \n ListNode currentHead = currentNode; // keep track of the head\n\n if ((currentNode==null ||currentNode.next==null )&& toBeNextNode ==null)return currentHead; // ignore for size 0 & 1\n\n if (currentNode.next!=null)currentHead = reverse(currentNode, currentNode.next); // travarse till end recursively\n\n currentNode.next = toBeNextNode; // reverse link\n\n return currentHead;\n}\n head-->12345\n\nhead-->54321\n"
},
{
"answer_id": 1251737,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "Node reverse(Node head) {\n // if head is null or only one node, it's reverse of itself.\n if ( (head==null) || (head.next == null) ) return head;\n\n // reverse the sub-list leaving the head node.\n Node reverse = reverse(head.next);\n\n // head.next still points to the last element of reversed sub-list.\n // so move the head to end.\n head.next.next = head;\n\n // point last node to nil, (get rid of cycles)\n head.next = null;\n return reverse;\n}\n"
},
{
"answer_id": 2376502,
"author": "Swapneel Patil",
"author_id": 251769,
"author_profile": "https://Stackoverflow.com/users/251769",
"pm_score": 3,
"selected": false,
"text": "// Example:\n// reverse0(1->2->3, null) => \n// reverse0(2->3, 1) => \n// reverse0(3, 2->1) => reverse0(null, 3->2->1)\n// once the first argument is null, return the second arg\n// which is nothing but the reveresed list.\n\nLink reverse0(Link f, Link n) {\n if (f != null) {\n Link t = new Link(f.data1, f.data2); \n t.nextLink = n; \n f = f.nextLink; // assuming first had n elements before, \n // now it has (n-1) elements\n reverse0(f, t);\n }\n return n;\n}\n"
},
{
"answer_id": 3079734,
"author": "readdear",
"author_id": 225236,
"author_profile": "https://Stackoverflow.com/users/225236",
"pm_score": 3,
"selected": false,
"text": "public Node reverse(Node previous, Node current) {\n if(previous == null)\n return null;\n if(previous.equals(head))\n previous.setNext(null);\n if(current == null) { // end of list\n head = previous;\n return head;\n } else {\n Node temp = current.getNext();\n current.setNext(previous);\n reverse(current, temp);\n }\n return null; //should never reach here.\n} \n Node newHead = reverse(head, head.getNext());\n"
},
{
"answer_id": 5598402,
"author": "Michael",
"author_id": 699058,
"author_profile": "https://Stackoverflow.com/users/699058",
"pm_score": 0,
"selected": false,
"text": "public class Singlelinkedlist {\n public static void main(String[] args) {\n Elem list = new Elem();\n Reverse(list); //list is populate some where or some how\n }\n\n //this is the part you should be concerned with the function/Method has only 3 lines\n\n public static void Reverse(Elem e){\n if (e!=null)\n if(e.next !=null )\n Reverse(e.next);\n //System.out.println(e.data);\n }\n}\n\nclass Elem {\n public Elem next; // Link to next element in the list.\n public String data; // Reference to the data.\n}\n"
},
{
"answer_id": 6642366,
"author": "KNA",
"author_id": 837790,
"author_profile": "https://Stackoverflow.com/users/837790",
"pm_score": 2,
"selected": false,
"text": "public Node reverseListRecursive(Node curr)\n{\n if(curr == null){//Base case\n return head;\n }\n else{\n (reverseListRecursive(curr.next)).next = (curr);\n }\n return curr;\n}\n"
},
{
"answer_id": 7425426,
"author": "PointZeroTwo",
"author_id": 724262,
"author_profile": "https://Stackoverflow.com/users/724262",
"pm_score": 3,
"selected": false,
"text": "class Node<T>\n{\n Node<T> next;\n public T data;\n}\n\nclass LinkedList<T>\n{\n Node<T> head = null;\n\n public void Reverse()\n {\n if (head != null)\n head = RecursiveReverse(null, head);\n }\n\n private Node<T> RecursiveReverse(Node<T> prev, Node<T> curr)\n {\n Node<T> next = curr.next;\n curr.next = prev;\n return (next == null) ? curr : RecursiveReverse(curr, next);\n }\n}\n"
},
{
"answer_id": 15142293,
"author": "akshayd",
"author_id": 1822258,
"author_profile": "https://Stackoverflow.com/users/1822258",
"pm_score": 2,
"selected": false,
"text": "public static ListNode recRev(ListNode curr){\n\n if(curr.next == null){\n return curr;\n }\n ListNode head = recRev(curr.next);\n curr.next.next = curr;\n curr.next = null;\n\n // propogate the head value\n return head;\n\n}\n"
},
{
"answer_id": 16319781,
"author": "Murali Mohan",
"author_id": 258001,
"author_profile": "https://Stackoverflow.com/users/258001",
"pm_score": 0,
"selected": false,
"text": "public Node reverseRec(Node prev, Node curr) {\n if (curr == null) return null; \n\n if (curr.next == null) {\n curr.next = prev;\n return curr;\n\n } else {\n Node temp = curr.next; \n curr.next = prev;\n return reverseRec(curr, temp);\n } \n}\n"
},
{
"answer_id": 16381858,
"author": "user2351329",
"author_id": 2351329,
"author_profile": "https://Stackoverflow.com/users/2351329",
"pm_score": 1,
"selected": false,
"text": "public void reverseList(){\n if(head!=null){\n head = reverseListNodes(null , head);\n }\n}\n\nprivate Node reverseListNodes(Node parent , Node child ){\n Node next = child.next;\n child.next = parent;\n return (next==null)?child:reverseListNodes(child, next);\n}\n"
},
{
"answer_id": 16499419,
"author": "Nima Ghaedsharafi",
"author_id": 902167,
"author_profile": "https://Stackoverflow.com/users/902167",
"pm_score": 0,
"selected": false,
"text": "Public LinkedList reverse(LinkedList List)\n{\n if(List == null)\n return null;\n if(List.next() == null)\n return List;\n LinkedList temp = this.reverse( List.next() );\n return temp.setNext( List );\n}\n"
},
{
"answer_id": 17604091,
"author": "Arijit Pal",
"author_id": 2574394,
"author_profile": "https://Stackoverflow.com/users/2574394",
"pm_score": 0,
"selected": false,
"text": "package com.mypackage;\nclass list{\n\n node first; \n node last;\n\n list(){\n first=null;\n last=null;\n}\n\n/*returns true if first is null*/\npublic boolean isEmpty(){\n return first==null;\n}\n/*Method for insertion*/\n\npublic void insert(int value){\n\n if(isEmpty()){\n first=last=new node(value);\n last.next=null;\n }\n else{\n node temp=new node(value);\n last.next=temp;\n last=temp;\n last.next=null;\n }\n\n}\n/*simple traversal from beginning*/\npublic void traverse(){\n node t=first;\n while(!isEmpty() && t!=null){\n t.printval();\n t= t.next;\n }\n}\n/*static method for creating a reversed linked list*/\npublic static void reverse(node n,list l1){\n\n if(n.next!=null)\n reverse(n.next,l1);/*will traverse to the very end*/\n l1.insert(n.value);/*every stack frame will do insertion now*/\n\n}\n/*private inner class node*/\nprivate class node{\n int value;\n node next;\n node(int value){\n this.value=value;\n }\n void printval(){\n System.out.print(value+\" \");\n }\n}\n\n }\n"
},
{
"answer_id": 19279748,
"author": "Fredton Doan",
"author_id": 2864170,
"author_profile": "https://Stackoverflow.com/users/2864170",
"pm_score": 2,
"selected": false,
"text": "public ListNode reverse(ListNode head) {\n if (head == null || head.next == null) return head; \n ListNode rHead = reverse(head.next);\n rHead.next = head;\n head = null;\n return rHead;\n}\n public ListNode reverse(ListNode head) {\n if (head == null || head.next == null) return head; \n ListNode prev = null;\n ListNode cur = head\n ListNode next = head.next;\n while (next != null) {\n cur.next = prev;\n prev = cur;\n cur = next;\n next = next.next;\n }\n return cur;\n}\n"
},
{
"answer_id": 19603170,
"author": "Vara",
"author_id": 2922236,
"author_profile": "https://Stackoverflow.com/users/2922236",
"pm_score": -1,
"selected": false,
"text": "public void reverse(){\n if(isEmpty()){\n return;\n }\n Node<T> revHead = new Node<T>();\n this.reverse(head.next, revHead);\n this.head = revHead;\n}\n\nprivate Node<T> reverse(Node<T> node, Node<T> revHead){\n if(node.next == null){\n revHead.next = node;\n return node;\n }\n Node<T> reverse = this.reverse(node.next, revHead);\n reverse.next = node;\n node.next = null;\n return node;\n}\n"
},
{
"answer_id": 20822946,
"author": "Austin Nwachukwu",
"author_id": 3143405,
"author_profile": "https://Stackoverflow.com/users/3143405",
"pm_score": 2,
"selected": false,
"text": "public void reverse() {\n head = reverseNodes(null, head);\n}\n\nprivate Node reverseNodes(Node prevNode, Node currentNode) {\n if (currentNode == null)\n return prevNode;\n Node nextNode = currentNode.next;\n currentNode.next = prevNode;\n return reverseNodes(currentNode, nextNode);\n}\n"
},
{
"answer_id": 21011075,
"author": "Sudheer Aedama",
"author_id": 1332911,
"author_profile": "https://Stackoverflow.com/users/1332911",
"pm_score": -1,
"selected": false,
"text": "scala> import scala.collection.mutable.LinkedList\nimport scala.collection.mutable.LinkedList\n\nscala> def reverseLinkedList[A](ll: LinkedList[A]): LinkedList[A] =\n ll.foldLeft(LinkedList.empty[A])((accumulator, nextElement) => nextElement +: accumulator)\nreverseLinkedList: [A](ll: scala.collection.mutable.LinkedList[A])scala.collection.mutable.LinkedList[A]\n\nscala> reverseLinkedList(LinkedList(\"a\", \"b\", \"c\"))\nres0: scala.collection.mutable.LinkedList[java.lang.String] = LinkedList(c, b, a)\n\nscala> reverseLinkedList(LinkedList(\"1\", \"2\", \"3\"))\nres1: scala.collection.mutable.LinkedList[java.lang.String] = LinkedList(3, 2, 1)\n"
},
{
"answer_id": 21203877,
"author": "Gordon Hamachi",
"author_id": 3209756,
"author_profile": "https://Stackoverflow.com/users/3209756",
"pm_score": 2,
"selected": false,
"text": "/**\n * Reverse the list\n * @return reference to the new list head\n */\npublic LinkNode reverse() {\n if (next == null) {\n return this; // Return the old tail of the list as the new head\n }\n LinkNode oldTail = next.reverse(); // Recurse to find the old tail\n next.next = this; // The old next node now points back to this node\n next = null; // Make sure old head has no next\n return oldTail; // Return the old tail all the way back to the top\n}\n public class LinkNode {\n private char name;\n private LinkNode next;\n\n /**\n * Return a linked list of nodes, whose names are characters from the given string\n * @param str node names\n */\n public LinkNode(String str) {\n if ((str == null) || (str.length() == 0)) {\n throw new IllegalArgumentException(\"LinkNode constructor arg: \" + str);\n }\n name = str.charAt(0);\n if (str.length() > 1) {\n next = new LinkNode(str.substring(1));\n }\n }\n\n public String toString() {\n return name + ((next == null) ? \"\" : next.toString());\n }\n\n public static void main(String[] args) {\n LinkNode head = new LinkNode(\"abc\");\n System.out.println(head);\n System.out.println(head.reverse());\n }\n}\n"
},
{
"answer_id": 24122015,
"author": "shreyas",
"author_id": 574776,
"author_profile": "https://Stackoverflow.com/users/574776",
"pm_score": 2,
"selected": false,
"text": "public static Node reverse(Node root) {\n if (root == null || root.next == null) {\n return root;\n }\n\n Node curr, prev, next;\n curr = root; prev = next = null;\n while (curr != null) {\n next = curr.next;\n curr.next = prev;\n\n prev = curr;\n curr = next;\n }\n return prev;\n}\n public static Node reverseR(Node node) {\n if (node == null || node.next == null) {\n return node;\n }\n\n Node next = node.next;\n node.next = null;\n\n Node remaining = reverseR(next);\n next.next = node;\n return remaining;\n}\n"
},
{
"answer_id": 24723577,
"author": "javasolsz",
"author_id": 3834379,
"author_profile": "https://Stackoverflow.com/users/3834379",
"pm_score": 0,
"selected": false,
"text": "package basic;\n\nimport custom.ds.nodes.Node;\n\npublic class RevLinkedList {\n\nprivate static Node<Integer> first = null;\n\npublic static void main(String[] args) {\n Node<Integer> f = new Node<Integer>();\n Node<Integer> s = new Node<Integer>();\n Node<Integer> t = new Node<Integer>();\n Node<Integer> fo = new Node<Integer>();\n f.setNext(s);\n s.setNext(t);\n t.setNext(fo);\n fo.setNext(null);\n\n f.setItem(1);\n s.setItem(2);\n t.setItem(3);\n fo.setItem(4);\n Node<Integer> curr = f;\n display(curr);\n revLL(null, f);\n display(first);\n}\n\npublic static void display(Node<Integer> curr) {\n while (curr.getNext() != null) {\n System.out.println(curr.getItem());\n System.out.println(curr.getNext());\n curr = curr.getNext();\n }\n}\n\npublic static void revLL(Node<Integer> pn, Node<Integer> cn) {\n while (cn.getNext() != null) {\n revLL(cn, cn.getNext());\n break;\n }\n if (cn.getNext() == null) {\n first = cn;\n }\n cn.setNext(pn);\n}\n"
},
{
"answer_id": 25486038,
"author": "Rohit",
"author_id": 3864024,
"author_profile": "https://Stackoverflow.com/users/3864024",
"pm_score": 0,
"selected": false,
"text": "static void reverseList(){\n\nif(head!=null||head.next!=null){\nListNode tail=head;//head points to tail\n\n\nListNode Second=head.next;\nListNode Third=Second.next;\ntail.next=null;//tail previous head is poiniting null\nSecond.next=tail;\nListNode current=Third;\nListNode prev=Second;\nif(Third.next!=null){\n\n\n\n while(current!=null){\n ListNode next=current.next;\n current.next=prev;\n prev=current;\n current=next;\n }\n }\nhead=prev;//new head\n}\n}\nclass ListNode{\n public int data;\n public ListNode next;\n public int getData() {\n return data;\n }\n\n public ListNode(int data) {\n super();\n this.data = data;\n this.next=null;\n }\n\n public ListNode(int data, ListNode next) {\n super();\n this.data = data;\n this.next = next;\n }\n\n public void setData(int data) {\n this.data = data;\n }\n public ListNode getNext() {\n return next;\n }\n public void setNext(ListNode next) {\n this.next = next;\n }\n\n\n\n\n\n}\n"
},
{
"answer_id": 25569222,
"author": "pat",
"author_id": 997629,
"author_profile": "https://Stackoverflow.com/users/997629",
"pm_score": 0,
"selected": false,
"text": "private Node ReverseList(Node current, Node previous)\n {\n if (current == null) return null;\n Node originalNext = current.next;\n current.next = previous;\n if (originalNext == null) return current;\n return ReverseList(originalNext, current);\n }\n"
},
{
"answer_id": 26292646,
"author": "jeantimex",
"author_id": 1218999,
"author_profile": "https://Stackoverflow.com/users/1218999",
"pm_score": 2,
"selected": false,
"text": "static ListNode reverseR(ListNode head) {\n if (head == null || head.next == null) {\n return head;\n }\n\n ListNode first = head;\n ListNode rest = head.next;\n\n // reverse the rest of the list recursively\n head = reverseR(rest);\n\n // fix the first node after recursion\n first.next.next = first;\n first.next = null;\n\n return head;\n}\n"
},
{
"answer_id": 32804564,
"author": "Rahul Saraf",
"author_id": 4500433,
"author_profile": "https://Stackoverflow.com/users/4500433",
"pm_score": 0,
"selected": false,
"text": "//this function reverses the linked list\npublic Node reverseList(Node p) {\n if(head == null){\n return null;\n }\n //make the last node as head\n if(p.next == null){\n head.next = null;\n head = p;\n return p;\n }\n //traverse to the last node, then reverse the pointers by assigning the 2nd last node to last node and so on..\n return reverseList(p.next).next = p;\n}\n"
},
{
"answer_id": 32817498,
"author": "Mohit Datta",
"author_id": 5383645,
"author_profile": "https://Stackoverflow.com/users/5383645",
"pm_score": -1,
"selected": false,
"text": "List Reverse(List l)\n{\n if (IsEmpty(l) || Size(l) == 1) return l;\n return reverse(rest(l))::first(l);\n}\n"
},
{
"answer_id": 33331029,
"author": "vsn harish rayasam",
"author_id": 5368232,
"author_profile": "https://Stackoverflow.com/users/5368232",
"pm_score": 0,
"selected": false,
"text": "//Recursive solution\nclass SLL\n{\n int data;\n SLL next;\n}\n\nSLL reverse(SLL head)\n{\n //base case - 0 or 1 elements\n if(head == null || head.next == null) return head;\n\n SLL temp = reverse(head.next);\n head.next.next = head;\n head.next = null;\n return temp;\n}\n"
},
{
"answer_id": 35531786,
"author": "phoganuci",
"author_id": 103807,
"author_profile": "https://Stackoverflow.com/users/103807",
"pm_score": 0,
"selected": false,
"text": "/**\n Node is a class that stores an arbitrary value of generic type T \n and a pointer to another Node of the same time. This is a recursive \n data structure representative of a member of a unidirectional linked\n list.\n */\npublic class Node<T> {\n public let value: T\n public let next: Node<T>?\n\n public init(value: T, next: Node<T>?) {\n self.value = value\n self.next = next\n }\n\n public func reversedList() -> Node<T> {\n if let next = self.next {\n // 3. The reverse of the second element on followed by the first element.\n return next.reversedList() + value\n } else {\n // 2. Reverse of a one element list is itself\n return self\n }\n }\n}\n\n/**\n @return Returns a newly created Node consisting of the lhs list appended with rhs value.\n */\npublic func +<T>(lhs: Node<T>, rhs: T) -> Node<T> {\n let tail: Node<T>?\n if let next = lhs.next {\n // The new tail is created recursively, as long as there is a next node.\n tail = next + rhs\n } else {\n // If there is not a next node, create a new tail node to append\n tail = Node<T>(value: rhs, next: nil)\n }\n // Return a newly created Node consisting of the lhs list appended with rhs value.\n return Node<T>(value: lhs.value, next: tail)\n}\n"
},
{
"answer_id": 37694481,
"author": "gurubelli",
"author_id": 2896382,
"author_profile": "https://Stackoverflow.com/users/2896382",
"pm_score": 0,
"selected": false,
"text": " public ListNode reverseR(ListNode p) {\n\n //Base condition, Once you reach the last node,return p \n if (p == null || p.next == null) { \n return p;\n }\n //Go on making the recursive call till reach the last node,now head points to the last node\n\n ListNode head = reverseR(p.next); //Head points to the last node\n\n //Here, p points to the last but one node(previous node), q points to the last node. Then next next step is to adjust the links\n ListNode q = p.next; \n\n //Last node link points to the P (last but one node)\n q.next = p; \n //Set the last but node (previous node) next to null\n p.next = null; \n return head; //Head points to the last node\n }\n"
},
{
"answer_id": 39070902,
"author": "Shafqat",
"author_id": 1093700,
"author_profile": "https://Stackoverflow.com/users/1093700",
"pm_score": -1,
"selected": false,
"text": " public void Reverse()\n {\n Node currentNode, nextNode=null, prevNode=null;\n currentNode = head;\n while(currentNode!=null)\n {\n nextNode = currentNode.next;\n currentNode.next = prevNode;\n prevNode = currentNode;\n currentNode = nextNode;\n }\n head = prevNode;\n } \n"
},
{
"answer_id": 44194643,
"author": "M Sach",
"author_id": 802050,
"author_profile": "https://Stackoverflow.com/users/802050",
"pm_score": 0,
"selected": false,
"text": "public void reverseLinkedList(Node node){\n if(node==null){\n return;\n }\n\n reverseLinkedList(node.next);\n Node temp = node.next;\n node.next=node.prev;\n node.prev=temp;\n return;\n}\n"
},
{
"answer_id": 70222976,
"author": "jtroconisa",
"author_id": 674595,
"author_profile": "https://Stackoverflow.com/users/674595",
"pm_score": -1,
"selected": false,
"text": "function reverse_linked_list_1(node){\n function reverse_linked_list_1(node, result){\n return node ? reverse_linked_list_1(node.next, {data: node.data, next: result}) : result;\n }\n return reverse_linked_list_1(node, null);\n}\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/354875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41200/"
] |
354,883 | <p>The canonical way to return multiple values in languages that support it is often <a href="https://stackoverflow.com/questions/38508/whats-the-best-way-to-return-multiple-values-from-a-function-in-python">tupling</a>.</p>
<h3>Option: Using a tuple</h3>
<p>Consider this trivial example:</p>
<pre><code>def f(x):
y0 = x + 1
y1 = x * 3
y2 = y0 ** y3
return (y0, y1, y2)
</code></pre>
<p>However, this quickly gets problematic as the number of values returned increases. What if you want to return four or five values? Sure, you could keep tupling them, but it gets easy to forget which value is where. It's also rather ugly to unpack them wherever you want to receive them.</p>
<h3>Option: Using a dictionary</h3>
<p>The next logical step seems to be to introduce some sort of 'record notation'. In Python, the obvious way to do this is by means of a <code>dict</code>.</p>
<p>Consider the following:</p>
<pre><code>def g(x):
y0 = x + 1
y1 = x * 3
y2 = y0 ** y3
return {'y0': y0, 'y1': y1 ,'y2': y2}
</code></pre>
<p>(Just to be clear, y0, y1, and y2 are just meant as abstract identifiers. As pointed out, in practice you'd use meaningful identifiers.)</p>
<p>Now, we have a mechanism whereby we can project out a particular member of the returned object. For example,</p>
<pre><code>result['y0']
</code></pre>
<h3>Option: Using a class</h3>
<p>However, there is another option. We could instead return a specialized structure. I've framed this in the context of Python, but I'm sure it applies to other languages as well. Indeed, if you were working in C this might very well be your only option. Here goes:</p>
<pre><code>class ReturnValue:
def __init__(self, y0, y1, y2):
self.y0 = y0
self.y1 = y1
self.y2 = y2
def g(x):
y0 = x + 1
y1 = x * 3
y2 = y0 ** y3
return ReturnValue(y0, y1, y2)
</code></pre>
<p>In Python the previous two are perhaps very similar in terms of plumbing - after all <code>{ y0, y1, y2 }</code> just end up being entries in the internal <code>__dict__</code> of the <code>ReturnValue</code>.</p>
<p>There is one additional feature provided by Python though for tiny objects, the <code>__slots__</code> attribute. The class could be expressed as:</p>
<pre><code>class ReturnValue(object):
__slots__ = ["y0", "y1", "y2"]
def __init__(self, y0, y1, y2):
self.y0 = y0
self.y1 = y1
self.y2 = y2
</code></pre>
<p>From the <a href="http://www.network-theory.co.uk/docs/pylang/__slots__.html" rel="noreferrer">Python Reference Manual</a>:</p>
<blockquote>
<p>The <code>__slots__</code> declaration takes a sequence of instance variables and reserves just enough space in each instance to hold a value for each variable. Space is saved because <code>__dict__</code> is not created for each instance.</p>
</blockquote>
<h3>Option: Using a <a href="https://docs.python.org/3/library/dataclasses.html" rel="noreferrer">dataclass</a> (Python 3.7+)</h3>
<p>Using Python 3.7's new dataclasses, return a class with automatically added special methods, typing and other useful tools:</p>
<pre><code>@dataclass
class Returnvalue:
y0: int
y1: float
y3: int
def total_cost(x):
y0 = x + 1
y1 = x * 3
y2 = y0 ** y3
return ReturnValue(y0, y1, y2)
</code></pre>
<h3>Option: Using a list</h3>
<p>Another suggestion which I'd overlooked comes from Bill the Lizard:</p>
<pre><code>def h(x):
result = [x + 1]
result.append(x * 3)
result.append(y0 ** y3)
return result
</code></pre>
<p>This is my least favorite method though. I suppose I'm tainted by exposure to Haskell, but the idea of mixed-type lists has always felt uncomfortable to me. In this particular example the list is -not- mixed type, but it conceivably could be.</p>
<p>A list used in this way really doesn't gain anything with respect to the tuple as far as I can tell. The only real difference between lists and tuples in Python is that lists are <a href="http://docs.python.org/library/stdtypes.html#typesseq-mutable" rel="noreferrer">mutable</a>, whereas tuples are not.</p>
<p>I personally tend to carry over the conventions from functional programming: use lists for any number of elements of the same type, and tuples for a fixed number of elements of predetermined types.</p>
<h1>Question</h1>
<p>After the lengthy preamble, comes the inevitable question. Which method (do you think) is best?</p>
| [
{
"answer_id": 354892,
"author": "UnkwnTech",
"author_id": 115,
"author_profile": "https://Stackoverflow.com/users/115",
"pm_score": 5,
"selected": false,
"text": "def g(x):\n y0 = x + 1\n y1 = x * 3\n y2 = y0 ** y3\n return {'y0':y0, 'y1':y1 ,'y2':y2 }\n"
},
{
"answer_id": 354918,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 5,
"selected": false,
"text": "class Some3SpaceThing(object):\n def __init__(self,x):\n self.g(x)\n def g(self,x):\n self.y0 = x + 1\n self.y1 = x * 3\n self.y2 = y0 ** y3\n\nr = Some3SpaceThing( x )\nr.y0\nr.y1\nr.y2\n"
},
{
"answer_id": 354929,
"author": "too much php",
"author_id": 28835,
"author_profile": "https://Stackoverflow.com/users/28835",
"pm_score": 8,
"selected": false,
"text": "ReturnValue \"y0\" \"y1\" \"y2\" ReturnValue .y0 .y1 .y2 def get_image_data(filename):\n [snip]\n return size, (format, version, compression), (width,height)\n\nsize, type, dimensions = get_image_data(x)\n re.match() open(file)"
},
{
"answer_id": 354958,
"author": "monkut",
"author_id": 24718,
"author_profile": "https://Stackoverflow.com/users/24718",
"pm_score": 6,
"selected": false,
"text": "def g(x):\n y0 = x + 1\n y1 = x * 3\n y2 = y0 ** y3\n return {'y0':y0, 'y1':y1 ,'y2':y2 }\n"
},
{
"answer_id": 356695,
"author": "A. Coady",
"author_id": 36433,
"author_profile": "https://Stackoverflow.com/users/36433",
"pm_score": 9,
"selected": false,
"text": ">>> import collections\n>>> Point = collections.namedtuple('Point', ['x', 'y'])\n>>> p = Point(1, y=2)\n>>> p.x, p.y\n1 2\n>>> p[0], p[1]\n1 2\n typing NamedTuple typing.NamedTuple class Employee(NamedTuple): # inherit from typing.NamedTuple\n name: str\n id: int = 3 # default value\n\nemployee = Employee('Guido')\nassert employee.id == 3\n"
},
{
"answer_id": 18218465,
"author": "Russell Borogove",
"author_id": 374746,
"author_profile": "https://Stackoverflow.com/users/374746",
"pm_score": 4,
"selected": false,
"text": "struct class struct dict tuple struct tuple class dict tuple dict tuple for score,id,name in scoreAllTheThings():\n if score > goodScoreThreshold:\n print \"%6.3f #%6d %s\"%(score,id,name)\n for entry in scoreAllTheThings():\n if entry.score > goodScoreThreshold:\n print \"%6.3f #%6d %s\"%(entry.score,entry.id,entry.name)\n dict for entry in scoreAllTheThings():\n if entry['score'] > goodScoreThreshold:\n print \"%6.3f #%6d %s\"%(entry['score'],entry['id'],entry['name'])\n dict"
},
{
"answer_id": 21970184,
"author": "rlms",
"author_id": 2387370,
"author_profile": "https://Stackoverflow.com/users/2387370",
"pm_score": 5,
"selected": false,
"text": ">>> def f(x):\n y0 = x + 1\n yield y0\n yield x * 3\n yield y0 ** 4\n\n\n>>> a, b, c = f(5)\n>>> a\n6\n>>> b\n15\n>>> c\n1296\n"
},
{
"answer_id": 28076666,
"author": "WebQube",
"author_id": 1574104,
"author_profile": "https://Stackoverflow.com/users/1574104",
"pm_score": 5,
"selected": false,
"text": ">>> def func():\n... return [1,2,3]\n...\n>>> a,b,c = func()\n>>> a\n1\n>>> b\n2\n>>> c\n3\n"
},
{
"answer_id": 36632980,
"author": "Joe Hansen",
"author_id": 756329,
"author_profile": "https://Stackoverflow.com/users/756329",
"pm_score": 8,
"selected": false,
"text": "def f():\n return True, False\nx, y = f()\nprint(x)\nprint(y)\n True\nFalse\n"
},
{
"answer_id": 47017170,
"author": "Elis Byberi",
"author_id": 2430448,
"author_profile": "https://Stackoverflow.com/users/2430448",
"pm_score": 2,
"selected": false,
"text": "form = {\n 'level': 0,\n 'points': 0,\n 'game': {\n 'name': ''\n }\n}\n\n\ndef test(form):\n form['game']['name'] = 'My game!'\n form['level'] = 2\n\n return form\n\n>>> print(test(form))\n{u'game': {u'name': u'My game!'}, u'points': 0, u'level': 2}\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/354883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37984/"
] |
354,886 | <p>I've just finished a six hour debugging session for a weird UI effect where I found that my favorite framework's implementation of an interface function called "getVisibleRegion" disabled some UI feature (and apparently forgot to restore it). </p>
<p>I've filed a bug with the framework, but this made me think about proper design: under what conditions is it legitimate to have any side-effects on an operation with a name that implies a mere calculation/getting operation?</p>
<p>For those interested in the actual details: I had a report on a bug where my plug-in kept breaking Eclipse's code folding so that the folding bar disappeared and it was impossible to "unfold" or see folded code .
I traced it down to a call to getVisibleRegion() on an ITextViewer whose type represents a source code viewer. Now, ITextViewer's documentation does state that "Viewers implementing ITextViewerExtension5 may be forced to change the fractions of the input document that are shown, in order to fulfill this contract". The actual implementation, however, took this a little <em>too</em> liberally and just disabled projection (folding) permanently, never to bring it back. </p>
| [
{
"answer_id": 354921,
"author": "MBCook",
"author_id": 18189,
"author_profile": "https://Stackoverflow.com/users/18189",
"pm_score": 2,
"selected": false,
"text": " MakeMyLifeEasyObject mmleo = new MakeMyLifeEasyObject(x, y, z, default, 12, something);\n\n Object uniqueObjectOne = mmleo.getNewUniqueObject();\n Object uniqueObjectTwo = mmleo.getNewUniqueObject();\n\n System.out.println(uniqueObjectOne.getId() == uniqueObjectTwo.getId()); // Prints \"false\"\n Object thing = list.getNextObjectAndRemoveFromList();\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/354886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23072/"
] |
354,900 | <p>So I'm teaching myself Ruby on Rails, with a PHP background. I've written a sloppy, proof-of-concept PHP application called "<a href="http://rezich.com/storybored" rel="nofollow noreferrer">2NDP.</a>" I want to re-create this in Ruby on Rails (but more basic, more clean, and with a better interface), so I can learn some of the basics.</p>
<p>2NDP is a website where you can basically write your own "Choose-Your-Own-Adventure" books, but collaboratively, with other people. The way I made this work with PHP/MySQL is, I had a table of stories and a table of pages. The pages would belong to stories (obviously), but each page would have references to up to four other pages by having four separate columns, one for each possible page ID that could be referenced.</p>
<p>So right now in my RoR application, I have "stories" that have "pages" that are associated with them. I need a way to get the pages to reference each other, but the possibility of more than one reference per page (one page may reference up to four other pages).</p>
<p>I really like the "references" thing that RoR has, but is there any way to gracefully implement this sort of system? Keep in mind that my only RoR experience is walking through four tutorials, and I'm trying to re-apply what I've learned with a "real-life application."</p>
| [
{
"answer_id": 355437,
"author": "Hates_",
"author_id": 3410,
"author_profile": "https://Stackoverflow.com/users/3410",
"pm_score": 3,
"selected": true,
"text": "class Pages < ActiveRecord::Base\n has_many :linked_pages\n has_many :pages, :through => :linked_pages\nend\n\nclass LinkedPages < ActiveRecord::Base\n belongs_to :pages, :class_name => \"Pages\", :foreign_key => \"page_id\"\n belongs_to :linked_pages, :class_name => \"Pages\", :foreign_key => \"linked_id\" \nend\n my_page.pages\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/354900",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34795/"
] |
354,902 | <p>How do you open a path in explorer by code in c++. I googled and couldn't find any thing but systems commands to do this, however, i dont want it to block or show the console window.</p>
| [
{
"answer_id": 354916,
"author": "berlindev",
"author_id": 44276,
"author_profile": "https://Stackoverflow.com/users/44276",
"pm_score": 2,
"selected": false,
"text": "\nsystem(\"explorer C:\\\\\");\n"
},
{
"answer_id": 354922,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": true,
"text": "ShellExecute() shellapi.h ShellExecuteA(NULL, \"open\", \"C:\\\\\", NULL, NULL, SW_SHOWDEFAULT);\n ShellExecuteA(NULL, \"open\", \"http://www.google.com\", NULL, NULL, SW_SHOWDEFAULT);\n CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE)\n"
},
{
"answer_id": 67605582,
"author": "yu yang Jian",
"author_id": 4573839,
"author_profile": "https://Stackoverflow.com/users/4573839",
"pm_score": 0,
"selected": false,
"text": "ShellExecute(NULL, L\"open\", L\"YourFolderPath\\\\YourFile.xxx\", NULL, NULL, SW_RESTORE);\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/354902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23339/"
] |
354,909 | <p>Ok this is more of a computer science question, than a question based on a particular language, but is there a difference between a map operation and a foreach operation? Or are they simply different names for the same thing?</p>
| [
{
"answer_id": 354917,
"author": "Henk",
"author_id": 44427,
"author_profile": "https://Stackoverflow.com/users/44427",
"pm_score": 7,
"selected": false,
"text": "map foreach map foreach"
},
{
"answer_id": 354923,
"author": "treat your mods well",
"author_id": 20772,
"author_profile": "https://Stackoverflow.com/users/20772",
"pm_score": 2,
"selected": false,
"text": "map forEach map forEach forEach"
},
{
"answer_id": 2932766,
"author": "wilhelmtell",
"author_id": 456,
"author_profile": "https://Stackoverflow.com/users/456",
"pm_score": 5,
"selected": false,
"text": "foreach map foreach map foreach foreach map map map foreach map map foreach foreach foreach map foreach foreach map map foreach copy foreach foreach copy map copy foreach map map foreach foreach map transform map map"
},
{
"answer_id": 14581275,
"author": "abhisekp",
"author_id": 1262108,
"author_profile": "https://Stackoverflow.com/users/1262108",
"pm_score": 5,
"selected": false,
"text": "Array.protototype.map Array.protototype.forEach var arr = [1, 2, 3, 4, 5];\n\narr.map(function(val, ind, arr){\n console.log(\"arr[\" + ind + \"]: \" + Math.pow(val,2));\n});\n\nconsole.log();\n\narr.forEach(function(val, ind, arr){\n console.log(\"arr[\" + ind + \"]: \" + Math.pow(val,2));\n});\n arr[0]: 1\narr[1]: 4\narr[2]: 9\narr[3]: 16\narr[4]: 25\n\narr[0]: 1\narr[1]: 4\narr[2]: 9\narr[3]: 16\narr[4]: 25\n var arr = [1, 2, 3, 4, 5];\n\nvar ar1 = arr.map(function(val, ind, arr){\n console.log(\"arr[\" + ind + \"]: \" + Math.pow(val,2));\n return val;\n});\n\nconsole.log();\nconsole.log(ar1);\nconsole.log();\n\nvar ar2 = arr.forEach(function(val, ind, arr){\n console.log(\"arr[\" + ind + \"]: \" + Math.pow(val,2));\n return val;\n});\n\nconsole.log();\nconsole.log(ar2);\nconsole.log();\n arr[0]: 1\narr[1]: 4\narr[2]: 9\narr[3]: 16\narr[4]: 25\n\n[ 1, 2, 3, 4, 5 ]\n\narr[0]: 1\narr[1]: 4\narr[2]: 9\narr[3]: 16\narr[4]: 25\n\nundefined\n Array.prototype.map Array.prototype.forEach Array.prototype.forEach"
},
{
"answer_id": 23625678,
"author": "irudyak",
"author_id": 2047442,
"author_profile": "https://Stackoverflow.com/users/2047442",
"pm_score": 2,
"selected": false,
"text": "def map(f: Int ⇒ Int): List[Int]\ndef foreach(f: Int ⇒ Unit): Unit\n scala> val list = List(1, 2, 3)\nlist: List[Int] = List(1, 2, 3)\n\nscala> list map (x => x * 2)\nres0: List[Int] = List(2, 4, 6)\n scala> var sum = 0\nsum: Int = 0\n\nscala> list foreach (sum += _)\n\nscala> sum\nres2: Int = 6 // res1 is empty\n"
},
{
"answer_id": 25010698,
"author": "Sumukh Barve",
"author_id": 3086783,
"author_profile": "https://Stackoverflow.com/users/3086783",
"pm_score": 4,
"selected": false,
"text": "map forEach map forEach forEach map forEach map forEach each forEach printSquares arr var printSquares = function (arr) {\n arr.forEach(function (n) {\n console.log(n * n);\n });\n};\n map selfDot arr arr var selfDot = function (arr) {\n return arr.map(function (n) {\n return n * n;\n });\n};\n map forEach map forEach forEach map map forEach forEach map map forEach map forEach each Array.prototype.each = function (func) {\n this.map(func);\n};\n prototype var each = function (arr, func) {\n arr.map(func); // Or map(arr, func);\n};\n forEach map() forEach() map() var a = [0, 1, 2, 3, 4], b = null;\nb = a.map(function (x) { a[x] = 'What!!'; return x*x; });\nconsole.log(b); // logs [0, 1, 4, 9, 16] \nconsole.log(a); // logs [\"What!!\", \"What!!\", \"What!!\", \"What!!\", \"What!!\"]\n a a[i] === i i < a.length map() map() map() map()"
},
{
"answer_id": 55102592,
"author": "user2456047",
"author_id": 2456047,
"author_profile": "https://Stackoverflow.com/users/2456047",
"pm_score": 0,
"selected": false,
"text": "map() nums = sc.parallelize([1,2,3,4,5,6,7,8,9,10])\nnum2 = nums.map(lambda x: x+2)\nprint (\"num2\",num2.collect())\nnum3 = nums.foreach(lambda x : x*x)\nprint (\"num3\",num3.collect())\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/354909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15124/"
] |
354,927 | <p>I will take the example of the SO site. To go to the list of questions, the url is www.stackoverflow.com/questions. Behind the scene, this goes to a controller (whose name is unknown) and to one of its actions. Let's say that this is <strong>controller=home</strong> and <strong>action=questions</strong>.</p>
<p>How to prevent the user to type www.stackoverflow.com/<strong>home</strong>/<strong>questions</strong> which would lead to the same page and would lower the rank of the page as far as SEO is concerned. Does it take a redirect to solve this? Does it take some special routing rules to handle this kind of situation? Something else?</p>
<p>Thanks</p>
| [
{
"answer_id": 354917,
"author": "Henk",
"author_id": 44427,
"author_profile": "https://Stackoverflow.com/users/44427",
"pm_score": 7,
"selected": false,
"text": "map foreach map foreach"
},
{
"answer_id": 354923,
"author": "treat your mods well",
"author_id": 20772,
"author_profile": "https://Stackoverflow.com/users/20772",
"pm_score": 2,
"selected": false,
"text": "map forEach map forEach forEach"
},
{
"answer_id": 2932766,
"author": "wilhelmtell",
"author_id": 456,
"author_profile": "https://Stackoverflow.com/users/456",
"pm_score": 5,
"selected": false,
"text": "foreach map foreach map foreach foreach map map map foreach map map foreach foreach foreach map foreach foreach map map foreach copy foreach foreach copy map copy foreach map map foreach foreach map transform map map"
},
{
"answer_id": 14581275,
"author": "abhisekp",
"author_id": 1262108,
"author_profile": "https://Stackoverflow.com/users/1262108",
"pm_score": 5,
"selected": false,
"text": "Array.protototype.map Array.protototype.forEach var arr = [1, 2, 3, 4, 5];\n\narr.map(function(val, ind, arr){\n console.log(\"arr[\" + ind + \"]: \" + Math.pow(val,2));\n});\n\nconsole.log();\n\narr.forEach(function(val, ind, arr){\n console.log(\"arr[\" + ind + \"]: \" + Math.pow(val,2));\n});\n arr[0]: 1\narr[1]: 4\narr[2]: 9\narr[3]: 16\narr[4]: 25\n\narr[0]: 1\narr[1]: 4\narr[2]: 9\narr[3]: 16\narr[4]: 25\n var arr = [1, 2, 3, 4, 5];\n\nvar ar1 = arr.map(function(val, ind, arr){\n console.log(\"arr[\" + ind + \"]: \" + Math.pow(val,2));\n return val;\n});\n\nconsole.log();\nconsole.log(ar1);\nconsole.log();\n\nvar ar2 = arr.forEach(function(val, ind, arr){\n console.log(\"arr[\" + ind + \"]: \" + Math.pow(val,2));\n return val;\n});\n\nconsole.log();\nconsole.log(ar2);\nconsole.log();\n arr[0]: 1\narr[1]: 4\narr[2]: 9\narr[3]: 16\narr[4]: 25\n\n[ 1, 2, 3, 4, 5 ]\n\narr[0]: 1\narr[1]: 4\narr[2]: 9\narr[3]: 16\narr[4]: 25\n\nundefined\n Array.prototype.map Array.prototype.forEach Array.prototype.forEach"
},
{
"answer_id": 23625678,
"author": "irudyak",
"author_id": 2047442,
"author_profile": "https://Stackoverflow.com/users/2047442",
"pm_score": 2,
"selected": false,
"text": "def map(f: Int ⇒ Int): List[Int]\ndef foreach(f: Int ⇒ Unit): Unit\n scala> val list = List(1, 2, 3)\nlist: List[Int] = List(1, 2, 3)\n\nscala> list map (x => x * 2)\nres0: List[Int] = List(2, 4, 6)\n scala> var sum = 0\nsum: Int = 0\n\nscala> list foreach (sum += _)\n\nscala> sum\nres2: Int = 6 // res1 is empty\n"
},
{
"answer_id": 25010698,
"author": "Sumukh Barve",
"author_id": 3086783,
"author_profile": "https://Stackoverflow.com/users/3086783",
"pm_score": 4,
"selected": false,
"text": "map forEach map forEach forEach map forEach map forEach each forEach printSquares arr var printSquares = function (arr) {\n arr.forEach(function (n) {\n console.log(n * n);\n });\n};\n map selfDot arr arr var selfDot = function (arr) {\n return arr.map(function (n) {\n return n * n;\n });\n};\n map forEach map forEach forEach map map forEach forEach map map forEach map forEach each Array.prototype.each = function (func) {\n this.map(func);\n};\n prototype var each = function (arr, func) {\n arr.map(func); // Or map(arr, func);\n};\n forEach map() forEach() map() var a = [0, 1, 2, 3, 4], b = null;\nb = a.map(function (x) { a[x] = 'What!!'; return x*x; });\nconsole.log(b); // logs [0, 1, 4, 9, 16] \nconsole.log(a); // logs [\"What!!\", \"What!!\", \"What!!\", \"What!!\", \"What!!\"]\n a a[i] === i i < a.length map() map() map() map()"
},
{
"answer_id": 55102592,
"author": "user2456047",
"author_id": 2456047,
"author_profile": "https://Stackoverflow.com/users/2456047",
"pm_score": 0,
"selected": false,
"text": "map() nums = sc.parallelize([1,2,3,4,5,6,7,8,9,10])\nnum2 = nums.map(lambda x: x+2)\nprint (\"num2\",num2.collect())\nnum3 = nums.foreach(lambda x : x*x)\nprint (\"num3\",num3.collect())\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/354927",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29244/"
] |
354,936 | <p>I get a 2032 stream error from Flash in response to POST requests that return "201 Created" in IE (Firefox works fine). Since Flash doesn't provide access to the HTTP status I can't tell that it has actually succeeded. The request is being made with HTTPService.</p>
<p>Any suggestions? Has anyone else seen this?</p>
<p>Thanks, Alex</p>
| [
{
"answer_id": 404448,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": " class ApplicationController < ActionController::Base\n helper :all # include all helpers, all the time\n include AuthenticatedSystem\n before_filter :login_required\n\n\n after_filter :flex_error_handling\n def flex_error_handling\n response.headers['Status'] = interpret_status(200) if response.headers['Status'] == interpret_status(422)\n response.headers['Status'] = interpret_status(200) if response.headers['Status'] == interpret_status(201)\n end\n def rescue_action_in_public(exception)\n render_exception(exception)\n\n\n end\n def rescue_action_locally(exception)\n render_exception(exception)\n end\n rescue_from ActiveRecord::RecordNotFound, :with => :render_exception\n def render_exception(exception)\n render :text => \"<errors><error>#{exception}</error></errors>\", :status => 200\n end\nend\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/354936",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15899/"
] |
354,942 | <p>If I have two objects, one being the list of items, and the other having a property storing the selected item of the other list, is it possible to update the selected item through binding in WPF?</p>
<p>Lets say I have these two data structures:</p>
<pre><code>public class MyDataList
{
public ObservableCollection<Guid> Data { get; set; }
}
public class MyDataStructure
{
public Guid ChosenItem { get; set; }
}
</code></pre>
<p>Is it possible to bind a Listbox to an instance of both objects so that the ChosenItem property gets set by the selected item of the ListBox?</p>
<p>EDIT: To make things a bit clearer, there might be many instances of MyDataStructure, each with a chosen item from MyDataList. The data list is common to all the instances, and I need a way to select an item and store that selection in the MyDataStructure.</p>
| [
{
"answer_id": 355007,
"author": "Jobi Joy",
"author_id": 8091,
"author_profile": "https://Stackoverflow.com/users/8091",
"pm_score": 1,
"selected": false,
"text": " public class MyDataList : INotifyPropertyChanged\n{\n private Guid _choosen;\n\n public ObservableCollection<Guid> Data { get; set; }\n\n public Guid ChosenItem {\n get\n {\n return _choosen;\n }\n set \n {\n _choosen = value;\n PropertyChanged(this, new PropertyChangedEventArgs(\"ChosenItem\"));\n } \n }\n\n public event PropertyChangedEventHandler PropertyChanged;\n}\n <ListBox ItemsSource=\"{Binding Data}\" SelectedValue=\"{Binding Path=ChosenItem}\" x:Name=\"listBox\"/>\n"
},
{
"answer_id": 355061,
"author": "Excel Kobayashi",
"author_id": 42911,
"author_profile": "https://Stackoverflow.com/users/42911",
"pm_score": 3,
"selected": true,
"text": "<Window.Resources>\n <local:MyDataStructure x:Key=\"mds1\" />\n</Window.Resources> \n<ListBox ItemsSource=\"{Binding Data}\" SelectedValue=\"{Binding Source={StaticResource mds1} Path=ChosenItem}\"/>\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/354942",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3820/"
] |
354,945 | <p>What would be the most effective way to grab the schema + table name in this scenario:</p>
<p>SELECT [t0].[Id], [t0].[CODE] AS [arg0], [t0].[DESC] AS [arg1]
FROM [SchemaName].[TableName] AS [t0]
WHERE ([t0].[Id] <> @p0)</p>
<p>The outcome needs to be: "SchemaName.TableName" ....</p>
<p>I'm using C#.</p>
<p>Thanks!</p>
| [
{
"answer_id": 355007,
"author": "Jobi Joy",
"author_id": 8091,
"author_profile": "https://Stackoverflow.com/users/8091",
"pm_score": 1,
"selected": false,
"text": " public class MyDataList : INotifyPropertyChanged\n{\n private Guid _choosen;\n\n public ObservableCollection<Guid> Data { get; set; }\n\n public Guid ChosenItem {\n get\n {\n return _choosen;\n }\n set \n {\n _choosen = value;\n PropertyChanged(this, new PropertyChangedEventArgs(\"ChosenItem\"));\n } \n }\n\n public event PropertyChangedEventHandler PropertyChanged;\n}\n <ListBox ItemsSource=\"{Binding Data}\" SelectedValue=\"{Binding Path=ChosenItem}\" x:Name=\"listBox\"/>\n"
},
{
"answer_id": 355061,
"author": "Excel Kobayashi",
"author_id": 42911,
"author_profile": "https://Stackoverflow.com/users/42911",
"pm_score": 3,
"selected": true,
"text": "<Window.Resources>\n <local:MyDataStructure x:Key=\"mds1\" />\n</Window.Resources> \n<ListBox ItemsSource=\"{Binding Data}\" SelectedValue=\"{Binding Source={StaticResource mds1} Path=ChosenItem}\"/>\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/354945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
354,962 | <p>I'm using Altera Quartus 2 to do a custom 8 bit processor and it takes forever to compile on my laptop. I'm only using simulations and making my processor in schematic (block diagram) and VHDL. Right now it takes around 10 minutes to compile, which is a pain since I'm more on the debugging phase of the project where I have to fix up the internal timing and make lots of very little changes to see what happens.</p>
<p>I'm not actually putting it on a FPGA, so do I need the compiling phases of "fitter" and "assembler"?</p>
<p>Can I change the contents of a memory file of one lpm_ram_dq and test it in simulation without recompiling?</p>
<p>In summary anyone knows how to make it compile faster?</p>
| [
{
"answer_id": 46964300,
"author": "Charles Clayton",
"author_id": 2374028,
"author_profile": "https://Stackoverflow.com/users/2374028",
"pm_score": 3,
"selected": false,
"text": "set_global_assignment -name PHYSICAL_SYNTHESIS_EFFORT FAST\n set_global_assignment -name FITTER_EFFORT FAST_FIT\n execute_flow -compile execute_flow -implement\n -implement -compile set_global_assignment -name SYNTHESIS_EFFORT FAST\n set_global_assignment -name OPTIMIZATION_MODE \"AGGRESSIVE COMPILE TIME\"\nset_global_assignment -name ALLOW_REGISTER_RETIMING \"OFF\"\nset_global_assignment -name HYPER_RETIMER_FAST_FORWARD \"OFF\"\n set_global_assignment -name TIMEQUEST_MULTICORNER_ANALYSIS \"OFF\"\n AGGRESSIVE COMPILE TIME set_blocal_assignment -name OPTIMIZATION_MODE \"FAST FUNCTIONAL TEST\" \n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/354962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3485/"
] |
354,976 | <p>The ActiveScaffold list view has a search form that is loaded via ajax when a user click the search link. I'd prefer to have the form show by default when a user opens a list page.</p>
<p>I've figured out a way to trigger the ajax call when the page loads, but I'm wondering if there's a way to get ActiveScaffold to render the form automatically. Is there a template or a method I can override? I've had a look through the code but there's nothing obvious, at least to me.</p>
<p>Update: </p>
<p>srboisvert's answer inspired me to have a better look. </p>
<p>The trick is to use Template overrides to refactor the following: list.rhtml, _list_header.rhtml, _search.rhtml so that the search form partial renders inline.</p>
| [
{
"answer_id": 2224000,
"author": "Jakub",
"author_id": 230656,
"author_profile": "https://Stackoverflow.com/users/230656",
"pm_score": 0,
"selected": false,
"text": "config.list.always_show_search = true"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/354976",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/575/"
] |
354,981 | <p>I'm porting a process which creates a MASSIVE <code>CROSS JOIN</code> of two tables. The resulting table contains 15m records (looks like the process makes a 30m cross join with a 2600 row table and a 12000 row table and then does some grouping which must split it in half). The rows are relatively narrow - just 6 columns. It's been running for 5 hours with no sign of completion. I only just noticed the count discrepancy between the known good and what I would expect for the cross join, so my output doesn't have the grouping or deduping which will halve the final table - but this still seems like it's not going to complete any time soon.</p>
<p>First I'm going to look to eliminate this table from the process if at all possible - obviously it could be replaced by joining to both tables individually, but right now I do not have visibility into everywhere else it is used.</p>
<p>But given that the existing process does it (in less time, on a less powerful machine, using the FOCUS language), are there any options for improving the performance of large <code>CROSS JOIN</code>s in SQL Server (2005) (hardware is not really an option, this box is a 64-bit 8-way with 32-GB of RAM)?</p>
<p>Details:</p>
<p>It's written this way in FOCUS (I'm trying to produce the same output, which is a CROSS JOIN in SQL):</p>
<pre><code>JOIN CLEAR *
DEFINE FILE COSTCENT
WBLANK/A1 = ' ';
END
TABLE FILE COSTCENT
BY WBLANK BY CC_COSTCENT
ON TABLE HOLD AS TEMPCC FORMAT FOCUS
END
DEFINE FILE JOINGLAC
WBLANK/A1 = ' ';
END
TABLE FILE JOINGLAC
BY WBLANK BY ACCOUNT_NO BY LI_LNTM
ON TABLE HOLD AS TEMPAC FORMAT FOCUS INDEX WBLANK
JOIN CLEAR *
JOIN WBLANK IN TEMPCC TO ALL WBLANK IN TEMPAC
DEFINE FILE TEMPCC
CA_JCCAC/A16=EDIT(CC_COSTCENT)|EDIT(ACCOUNT_NO);
END
TABLE FILE TEMPCC
BY CA_JCCAC BY CC_COSTCENT AS COST CENTER BY ACCOUNT_NO
BY LI_LNTM
ON TABLE HOLD AS TEMPCCAC
END
</code></pre>
<p>So the required output really is a CROSS JOIN (it's joining a blank column from each side).</p>
<p>In SQL:</p>
<pre><code>CREATE TABLE [COSTCENT](
[COST_CTR_NUM] [int] NOT NULL,
[CC_CNM] [varchar](40) NULL,
[CC_DEPT] [varchar](7) NULL,
[CC_ALSRC] [varchar](6) NULL,
[CC_HIER_CODE] [varchar](20) NULL,
CONSTRAINT [PK_LOOKUP_GL_COST_CTR] PRIMARY KEY NONCLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY
= OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
CREATE TABLE [JOINGLAC](
[ACCOUNT_NO] [int] NULL,
[LI_LNTM] [int] NULL,
[PR_PRODUCT] [varchar](5) NULL,
[PR_GROUP] [varchar](1) NULL,
[AC_NAME_LONG] [varchar](40) NULL,
[LI_NM_LONG] [varchar](30) NULL,
[LI_INC] [int] NULL,
[LI_MULT] [int] NULL,
[LI_ANLZ] [int] NULL,
[LI_TYPE] [varchar](2) NULL,
[PR_SORT] [varchar](2) NULL,
[PR_NM] [varchar](26) NULL,
[PZ_SORT] [varchar](2) NULL,
[PZNAME] [varchar](26) NULL,
[WANLZ] [varchar](3) NULL,
[OPMLNTM] [int] NULL,
[PS_GROUP] [varchar](5) NULL,
[PS_SORT] [varchar](2) NULL,
[PS_NAME] [varchar](26) NULL,
[PT_GROUP] [varchar](5) NULL,
[PT_SORT] [varchar](2) NULL,
[PT_NAME] [varchar](26) NULL
) ON [PRIMARY]
CREATE TABLE [JOINCCAC](
[CA_JCCAC] [varchar](16) NOT NULL,
[CA_COSTCENT] [int] NOT NULL,
[CA_GLACCOUNT] [int] NOT NULL,
[CA_LNTM] [int] NOT NULL,
[CA_UNIT] [varchar](6) NOT NULL,
CONSTRAINT [PK_JOINCCAC_KNOWN_GOOD] PRIMARY KEY CLUSTERED
(
[CA_JCCAC] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY
= OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
</code></pre>
<p>With the SQL Code:</p>
<pre><code>INSERT INTO [JOINCCAC]
(
[CA_JCCAC]
,[CA_COSTCENT]
,[CA_GLACCOUNT]
,[CA_LNTM]
,[CA_UNIT]
)
SELECT Util.PADLEFT(CONVERT(varchar, CC.COST_CTR_NUM), '0',
7)
+ Util.PADLEFT(CONVERT(varchar, GL.ACCOUNT_NO), '0',
9) AS CC_JCCAC
,CC.COST_CTR_NUM AS CA_COSTCENT
,GL.ACCOUNT_NO % 900000000 AS CA_GLACCOUNT
,GL.LI_LNTM AS CA_LNTM
,udf_BUPDEF(GL.ACCOUNT_NO, CC.COST_CTR_NUM, GL.LI_LNTM, 'N') AS CA_UNIT
FROM JOINGLAC AS GL
CROSS JOIN COSTCENT AS CC
</code></pre>
<p>Depending on how this table is subsequently used, it should be able to be eliminated from the process, by simply joining to both the original tables used to build it. However, this is an extremely large porting effort, and I might not find the usage of the table for some time, so I was wondering if there were any tricks to <code>CROSS JOIN</code>ing big tables like that in a timely fashion (especially given that the existing process in FOCUS is able to do it more speedily). That way I could validate the correctness of my building of the replacement query and then later factor it out with views or whatever.</p>
<p>I am also considering factoring out the UDFs and string manipulation and performing the CROSS JOIN first to break the process up a bit.</p>
<p><strong>RESULTS SO FAR:</strong></p>
<p>It turns out that the UDFs do contribute a lot (negatively) to the performance. But there also appears to be a big difference between a 15m row cross join and a 30m row cross join. I do not have SHOWPLAN rights (boo hoo), so I can't tell whether the plan it is using is better or worse after changing indexes. I have not refactored it yet, but am expecting the entire table to go away shortly.</p>
| [
{
"answer_id": 355132,
"author": "shahkalpesh",
"author_id": 23574,
"author_profile": "https://Stackoverflow.com/users/23574",
"pm_score": 1,
"selected": false,
"text": "\n SELECT CC.COST_CTR_NUM, GL.ACCOUNT_NO\n ,CC.COST_CTR_NUM AS CA_COSTCENT\n ,GL.ACCOUNT_NO AS CA_GLACCOUNT\n ,GL.LI_LNTM AS CA_LNTM\n-- I don't know what is BUPDEF doing? but remove it from the query for time being\n-- ,udf_BUPDEF(GL.ACCOUNT_NO, CC.COST_CTR_NUM, GL.LI_LNTM, 'N') AS CA_UNIT\n FROM JOINGLAC AS GL\n CROSS JOIN COSTCENT AS CC\n"
},
{
"answer_id": 355164,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 3,
"selected": true,
"text": "CREATE INDEX COSTCENTCoverCross ON COSTCENT(COST_CTR_NUM)\nCREATE INDEX JOINGLACCoverCross ON JOINGLAC(ACCOUNT_NO, LI_LNTM)\n RIGHT('z00000000000000000000000000' + columnName, 7)\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/354981",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18255/"
] |
354,993 | <p>I have following table structure:</p>
<pre><code>Table: Plant
PlantID: Primary Key
PlantName: String
Table: Party
PartyID: Primary Key
PartyName: String
PlantID: link to Plant table
Table: Customer
PartyID: Primary Key, link to Party
CustomerCode: String
</code></pre>
<p>I'd like to have Customer entity object with following fields:</p>
<pre><code> PartyID: Primary Key
CustomerCode: String
PartyName: String
PlantName: String
</code></pre>
<p>I am having trouble with PlantName field (which is brought from Plant table
I connected Customer to Party and Party to Plant with associations
However I can not connect Customer to Plant with association ( because it does not have one)
I can not add Plant table to mapping, when I do that - I am getting following error:</p>
<pre><code>Error 3024: Problem in Mapping Fragment starting at line 352: Must specify mapping for all key properties (CustomerSet.PartyID) of the EntitySet CustomerSet
</code></pre>
<p>Removing Plant association works.
Any hints or directions very appreciated.</p>
| [
{
"answer_id": 355968,
"author": "YeahStu",
"author_id": 1300,
"author_profile": "https://Stackoverflow.com/users/1300",
"pm_score": 3,
"selected": true,
"text": "Customer.Party.PartyName Customer.Party.Plant.PlantName"
},
{
"answer_id": 723556,
"author": "Kris",
"author_id": 14439,
"author_profile": "https://Stackoverflow.com/users/14439",
"pm_score": 2,
"selected": false,
"text": "public partial class Customer\n{\n public string PartyName\n {\n get { return Party.PartyName; }\n set { Party.PartyName = value; }\n }\n\n public string PlantName\n {\n get { return Party.Plant.PlantName; }\n set { Party.Plant.PlantName = value; }\n }\n}\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/354993",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44838/"
] |
354,994 | <p>I have my SVN repository hosted somewhere. I want to move to somebody else. How can I create a dump of my repository so I can import it into my new host? This is all I keep seeing: svnadmin dump /path/to/repos > repos.dump</p>
<p>My repository is hosted, so it's not local.</p>
| [
{
"answer_id": 356353,
"author": "Bert Huijben",
"author_id": 2094,
"author_profile": "https://Stackoverflow.com/users/2094",
"pm_score": 3,
"selected": false,
"text": "svnrdump"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/354994",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3047/"
] |
354,998 | <p>I have a MasterPage, with my Usercontrol inside a div.</p>
<p>I can set visible=false to the UserControl and to the containing div, and this works fine.
But the Page_Load of the UserControl is always hit.</p>
<p>Is this by design, or am I missing how to stop page execution going into the Page_Load method of the UserControl.</p>
| [
{
"answer_id": 356353,
"author": "Bert Huijben",
"author_id": 2094,
"author_profile": "https://Stackoverflow.com/users/2094",
"pm_score": 3,
"selected": false,
"text": "svnrdump"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/354998",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6268/"
] |
355,015 | <p>I would like to know if there is a jQuery event that I can use to determine when a particular DIV's <code>top</code> property has changed.</p>
<p>For instance, I have invisible content above a DIV. When that content becomes visible, the DIV is shifted down. I would like to capture that event and then use the <code>offset()</code> function to get the X/Y coordinates.</p>
| [
{
"answer_id": 355022,
"author": "Strelok",
"author_id": 2788,
"author_profile": "https://Stackoverflow.com/users/2788",
"pm_score": 1,
"selected": false,
"text": "$(document).ready( function (){\n $(\"#mydiv\").bind(\"movestart\", function (){ ...remember start position... });\n $(\"#mydiv\").bind(\"moveend\", function (){ ...calculate offsets etc... });\n});\n"
},
{
"answer_id": 30065971,
"author": "Paulo",
"author_id": 4868655,
"author_profile": "https://Stackoverflow.com/users/4868655",
"pm_score": 0,
"selected": false,
"text": "$(\"#someId\").resize(function () {\n\n// your code\n\n});\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355015",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10589/"
] |
355,019 | <p>I have an object in C# on which I need to execute a method on a regular basis. I would like this method to be executed only when other people are using my object, as soon as people stop using my object I would like this background operation to stop. </p>
<p>So here is a simple example is this (which is broken): </p>
<pre><code>class Fish
{
public Fish()
{
Thread t = new Thread(new ThreadStart(BackgroundWork));
t.IsBackground = true;
t.Start();
}
public void BackgroundWork()
{
while(true)
{
this.Swim();
Thread.Sleep(1000);
}
}
public void Swim()
{
Console.WriteLine("The fish is Swimming");
}
}
</code></pre>
<p>The problem is that if I new a Fish object anywhere, it never gets garbage collected, cause there is a background thread referencing it. Here is an illustrated version of broken code. </p>
<pre><code>public void DoStuff()
{
Fish f = new Fish();
}
// after existing from this method my Fish object keeps on swimming.
</code></pre>
<p>I know that the Fish object should be disposable and I should clean up the thread on dispose, but I have no control over my callers and can not ensure dispose is called. </p>
<p>How do I work around this problem and ensure the background threads are automatically disposed even if Dispose is not called explicitly?</p>
| [
{
"answer_id": 355097,
"author": "Excel Kobayashi",
"author_id": 42911,
"author_profile": "https://Stackoverflow.com/users/42911",
"pm_score": 2,
"selected": false,
"text": "class Fish3 : IDisposable\n{\n Thread t;\n private ManualResetEvent terminate = new ManualResetEvent(false);\n private volatile int disposed = 0;\n\n public Fish3()\n {\n t = new Thread(new ThreadStart(BackgroundWork));\n t.IsBackground = true;\n t.Start();\n }\n\n public void BackgroundWork()\n {\n while(!terminate.WaitOne(1000, false))\n {\n Swim(); \n }\n }\n\n public void Swim()\n {\n Console.WriteLine(\"The third fish is Swimming\");\n }\n\n public void Dispose()\n {\n if(Interlocked.Exchange(ref disposed, 1) == 0)\n {\n terminate.Set();\n t.Join();\n GC.SuppressFinalize(this);\n }\n }\n\n ~Fish3()\n {\n if(Interlocked.Exchange(ref disposed, 1) == 0)\n {\n Dispose();\n }\n }\n}\n"
},
{
"answer_id": 1325541,
"author": "Sam Saffron",
"author_id": 17174,
"author_profile": "https://Stackoverflow.com/users/17174",
"pm_score": 3,
"selected": true,
"text": "class Fish : IDisposable \n{\n class Swimmer\n {\n Thread t; \n WeakReference fishRef;\n public ManualResetEvent terminate = new ManualResetEvent(false);\n\n public Swimmer(Fish3 fish)\n {\n this.fishRef = new WeakReference(fish);\n t = new Thread(new ThreadStart(BackgroundWork)); \n t.IsBackground = true;\n t.Start();\n } \n\n public void BackgroundWork()\n {\n bool done = false;\n while(!done)\n {\n done = Swim(); \n if (!done) \n {\n done = terminate.WaitOne(1000, false);\n } \n }\n }\n\n // this is pulled out into a helper method to ensure \n // the Fish object is referenced for the minimal amount of time\n private bool Swim()\n {\n bool done;\n\n Fish fish = Fish; \n if (fish != null)\n {\n fish.Swim(); \n done = false;\n }\n else \n {\n done = true;\n }\n return done;\n }\n\n public Fish Fish\n {\n get { return fishRef.Target as Fish3; }\n }\n }\n\n Swimmer swimmer;\n\n public Fish()\n {\n swimmer = new Swimmer(this);\n }\n\n public void Swim()\n {\n Console.WriteLine(\"The third fish is Swimming\"); \n }\n\n volatile bool disposed = false;\n\n public void Dispose()\n {\n if (!disposed)\n {\n swimmer.terminate.Set();\n disposed = true;\n GC.SuppressFinalize(this);\n } \n }\n\n ~Fish() \n {\n if(!disposed)\n {\n Dispose();\n }\n }\n}\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355019",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17174/"
] |
355,020 | <p>I have a Double which could have a value from around 0.000001 to 1,000,000,000.000</p>
<p>I wish to format this number as a string but conditionally depending on its size. So if it's very small I want to format it with something like:</p>
<pre><code>String.Format("{0:.000000000}", number);
</code></pre>
<p>if it's not that small, say 0.001 then I want to use something like</p>
<pre><code>String.Format("{0:.00000}", number);
</code></pre>
<p>and if it's over, say 1,000 then format it as:</p>
<pre><code>String.Format("{0:.0}", number);
</code></pre>
<p>Is there a clever way to construct this format string based on the size of the value I'm going to format?</p>
| [
{
"answer_id": 355024,
"author": "Andrew Kennan",
"author_id": 22506,
"author_profile": "https://Stackoverflow.com/users/22506",
"pm_score": 2,
"selected": false,
"text": "string.Format(\"{0:#,###,##0.000}\", number);\n"
},
{
"answer_id": 355029,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 5,
"selected": true,
"text": "string s;\ndouble epislon = 0.0000001; // or however near zero you want to consider as zero\nif (Math.Abs(value) < epislon) {\n int digits = Math.Log10( Math.Abs( value ));\n // if (digits >= 0) ++digits; // if you care about the exact number\n if (digits < -5) {\n s = string.Format( \"{0:0.000000000}\", value );\n }\n else if (digits < 0) {\n s = string.Format( \"{0:0.00000})\", value );\n }\n else {\n s = string.Format( \"{0:#,###,###,##0.000}\", value );\n }\n}\nelse {\n s = \"0\";\n}\n"
},
{
"answer_id": 356099,
"author": "Jonas Elfström",
"author_id": 44620,
"author_profile": "https://Stackoverflow.com/users/44620",
"pm_score": 2,
"selected": false,
"text": "String.Format(\"{0:#,##0.########}\", number);\n String.Format(\"{0:#,##0.########}\", number<1000 ? number : Math.Round(number,1));\n"
},
{
"answer_id": 358014,
"author": "OwenP",
"author_id": 2547,
"author_profile": "https://Stackoverflow.com/users/2547",
"pm_score": 1,
"selected": false,
"text": "ToString class FormattedDouble\n{ \n public double Value { get; set; }\n\n protected overrides void ToString()\n {\n // tvanfosson's code to produce the right string\n }\n}\n var myDouble = new FormattedDouble();\nmyDouble.Value = Math.Pi;\nConsole.WriteLine(myDouble);\n"
},
{
"answer_id": 740607,
"author": "tophat02",
"author_id": 89650,
"author_profile": "https://Stackoverflow.com/users/89650",
"pm_score": 2,
"selected": false,
"text": "class MyExtensions \n{\n public static string ToFormmatedString(this double d)\n {\n // Take d and implement tvanfosson's code\n }\n}\n double d = 1.005343;\nstring d_formatted = d.ToFormattedString();\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355020",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1463/"
] |
355,030 | <p>I'd like to use POSIX semaphores to manage atomic get and put from a file representing a queue. I want the flexibility of having something named in the filesystem, so that completely unrelated processes can share a queue. I think this plan rules out pthreads. The named posix semaphores are great for putting something in the filesystem that any process can see, but I can't find the standard CondWait primitive:</p>
<pre><code>... decide we have to wait ....
CondWait(sem, cond);
</code></pre>
<p>When CondWait is called by a process it atomically posts to sem and waits on cond. When some other process posts to cond, the waiting process wakes up only if it can atomically decrement sem as well. The alternative of</p>
<pre><code>... decide we have to wait ....
sem_post(sem);
sem_wait(cond);
sem_wait(sem);
</code></pre>
<p>is subject to a race condition in which some other process signals cond just before this process waits on it.</p>
<p>I hardly ever do any concurrent programming, so I thought I would ask SO: if I use a standard POSIX counting semaphore for the condition variable, is it possible that this race is benign?</p>
<p>Just in case anybody wants the larger context, I am building get and put operations for an atomic queue that can be called from shell scripts. </p>
| [
{
"answer_id": 382554,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 0,
"selected": false,
"text": "sem_trywait() sem_timedwait()"
},
{
"answer_id": 6937221,
"author": "R.. GitHub STOP HELPING ICE",
"author_id": 379897,
"author_profile": "https://Stackoverflow.com/users/379897",
"pm_score": 0,
"selected": false,
"text": "mmap"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355030",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41661/"
] |
355,031 | <p>Is that possible? I mean, can both ends of the many to many relationship point to the same table?</p>
| [
{
"answer_id": 355111,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 2,
"selected": true,
"text": "CREATE TABLE Table1 (pkcol1 ... PRIMARY KEY, ...);\nCREATE TABLE Table2 (pkcol2 ... PRIMARY KEY, ...);\nCREATE TABLE MtoM_Table1_Table2\n(\n pkcol1 ... REFERENCES Table1,\n pkcol2 ... REFERENCES Table2,\n PRIMARY KEY (pkcol1, pkcol2)\n);\n-- CREATE INDEX fk1_mtom_table1_table2 ON MtoM_Table1_Table2(pkcol1);\n-- CREATE INDEX fk2_mtom_table1_table2 ON MtoM_Table1_Table2(pkcol2);\n CREATE TABLE Table1 (pkcol1 ... PRIMARY KEY, ...);\nCREATE TABLE MtoM_Table1_Table1\n(\n pkcol1 ... REFERENCES Table1(pkcol1),\n akcol1 ... REFERENCES Table1(pkcol1),\n PRIMARY KEY (pkcol1, akcol1)\n);\n-- CREATE INDEX fk1_mtom_table1_table1 ON MtoM_Table1_Table1(pkcol1);\n-- CREATE INDEX fk2_mtom_table1_table1 ON MtoM_Table1_Table1(akcol1);\n CREATE TABLE Table1\n(\n pkcol1 ... /* PRIMARY KEY */,\n fkcol1 ... /* FOREIGN KEY REFERENCES Table1(pkcol1) */,\n ...\n);\n-- CREATE INDEX fk1_table1 ON Table1(pkcol1);\n-- CREATE INDEX fk2_table1 ON Table1(fkcol1);\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355031",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38807/"
] |
355,032 | <p>I am trying to creating an optional association between a couple of tables. I have one table called Invoice. The Invoice table has a FK reference to the Customer table through the CustomerId field. The Invoice table also has a not enforced FK reference to the Project able through the ProjectId field.</p>
<p>Is there anyway to set up my Linq-To-Sql classes to have an optional association between the Invoice and the Project table?</p>
<p>I'd like to be able to pick off the Name of Project through this association, if one is available.</p>
<p><strong>Clarification</strong></p>
<p>Is it possible to set this up in the dbml file? I have a partial class that extends the Invoice entity and would like to be able to create a property called ProjectName that wrap Invoice.Project.Name.</p>
<p>Just wondering if this is even possible or if I would have to return the left join value in the query.</p>
| [
{
"answer_id": 355111,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 2,
"selected": true,
"text": "CREATE TABLE Table1 (pkcol1 ... PRIMARY KEY, ...);\nCREATE TABLE Table2 (pkcol2 ... PRIMARY KEY, ...);\nCREATE TABLE MtoM_Table1_Table2\n(\n pkcol1 ... REFERENCES Table1,\n pkcol2 ... REFERENCES Table2,\n PRIMARY KEY (pkcol1, pkcol2)\n);\n-- CREATE INDEX fk1_mtom_table1_table2 ON MtoM_Table1_Table2(pkcol1);\n-- CREATE INDEX fk2_mtom_table1_table2 ON MtoM_Table1_Table2(pkcol2);\n CREATE TABLE Table1 (pkcol1 ... PRIMARY KEY, ...);\nCREATE TABLE MtoM_Table1_Table1\n(\n pkcol1 ... REFERENCES Table1(pkcol1),\n akcol1 ... REFERENCES Table1(pkcol1),\n PRIMARY KEY (pkcol1, akcol1)\n);\n-- CREATE INDEX fk1_mtom_table1_table1 ON MtoM_Table1_Table1(pkcol1);\n-- CREATE INDEX fk2_mtom_table1_table1 ON MtoM_Table1_Table1(akcol1);\n CREATE TABLE Table1\n(\n pkcol1 ... /* PRIMARY KEY */,\n fkcol1 ... /* FOREIGN KEY REFERENCES Table1(pkcol1) */,\n ...\n);\n-- CREATE INDEX fk1_table1 ON Table1(pkcol1);\n-- CREATE INDEX fk2_table1 ON Table1(fkcol1);\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1768/"
] |
355,038 | <p>I see in richfaces that there is a single slider, wondering if anyone has created a dual slider like in Scriptaculous for it.</p>
<p>Is there any concerns in mixing JSF, Richfaces and Scriptaculous in an application?</p>
| [
{
"answer_id": 357398,
"author": "McDowell",
"author_id": 304,
"author_profile": "https://Stackoverflow.com/users/304",
"pm_score": 3,
"selected": true,
"text": "<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>\n<jsp:root xmlns:jsp=\"http://java.sun.com/JSP/Page\" version=\"2.0\"\n xmlns:h=\"http://java.sun.com/jsf/html\"\n xmlns:f=\"http://java.sun.com/jsf/core\">\n <jsp:directive.page language=\"java\"\n contentType=\"text/html; charset=ISO-8859-1\"\n pageEncoding=\"ISO-8859-1\" />\n <jsp:text>\n <![CDATA[ <?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?> ]]>\n </jsp:text>\n <jsp:text>\n <![CDATA[ <!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"> ]]>\n </jsp:text>\n <html xmlns=\"http://www.w3.org/1999/xhtml\">\n <head>\n <meta http-equiv=\"Content-Type\"\n content=\"text/html; charset=ISO-8859-1\" />\n <title>Script Test</title>\n <script src=\"javascripts/prototype.js\" type=\"text/javascript\">/**/</script>\n <script src=\"javascripts/scriptaculous.js\" type=\"text/javascript\">/**/</script>\n <style type=\"text/css\">\ndiv.slider {\n width: 256px;\n margin: 10px 0;\n background-color: #ccc;\n height: 10px;\n position: relative;\n}\n\ndiv.slider div.handle {\n width: 10px;\n height: 15px;\n background-color: #f00;\n cursor: move;\n position: absolute;\n}\n\ndiv#zoom_element {\n width: 50px;\n height: 50px;\n background: #2d86bd;\n position: relative;\n}\n</style>\n </head>\n <body>\n\n <div class=\"demo\">\n <p>Use the slider to change the value</p>\n <div id=\"zoom_slider\" class=\"slider\">\n <div class=\"handle\"></div>\n </div>\n </div>\n\n <f:view>\n <h:form>\n <h:inputText binding=\"#{sliderIdBean.mycontrol}\"\n value=\"#{sliderIdBean.value}\" onchange=\"updateSlider()\">\n <f:validateLongRange minimum=\"0\" maximum=\"10\" />\n </h:inputText>\n <h:commandButton value=\"Submit\" action=\"#{sliderIdBean.action}\" />\n </h:form>\n <h:messages />\n </f:view>\n\n <script type=\"text/javascript\">\n var zoom_slider = $('zoom_slider'),\n mycontrol = $('${sliderIdBean.clientId}');\n\n var ctrl = new Control.Slider(zoom_slider.down('.handle'), zoom_slider, {\n range: $R(0, 10),\n sliderValue: mycontrol.getValue(),\n onSlide: function(value) {\n value = Math.ceil(value);\n mycontrol.setValue(value);\n },\n onChange: function(value) {\n value = Math.ceil(value); \n mycontrol.setStyle(value);\n }\n });\n\n function updateSlider() {\n ctrl.setValue(mycontrol.value);\n }\n </script>\n\n </body>\n </html>\n</jsp:root>\n public class SliderIdBean {\n\n private long value = 0;\n private UIComponent mycontrol;\n\n public long getValue() {\n return value;\n }\n\n public void setValue(long value) {\n this.value = value;\n }\n\n public UIComponent getMycontrol() {\n return mycontrol;\n }\n\n public void setMycontrol(UIComponent mycontrol) {\n this.mycontrol = mycontrol;\n }\n\n public String getClientId() {\n FacesContext context = FacesContext\n .getCurrentInstance();\n return mycontrol.getClientId(context);\n }\n\n public String action() {\n System.out.println(\"Submitted value was: \" + value);\n return null;\n }\n\n}\n <managed-bean>\n <managed-bean-name>sliderIdBean</managed-bean-name>\n <managed-bean-class>scripty.SliderIdBean</managed-bean-class>\n <managed-bean-scope>session</managed-bean-scope>\n</managed-bean>\n"
},
{
"answer_id": 13970089,
"author": "UdayKiran Pulipati",
"author_id": 1624035,
"author_profile": "https://Stackoverflow.com/users/1624035",
"pm_score": 0,
"selected": false,
"text": "<%@ page language=\"java\" import=\"java.util.*\" pageEncoding=\"ISO-8859-1\"%>\n<%@ taglib uri=\"http://java.sun.com/jsf/html\" prefix=\"h\"%>\n<%@ taglib uri=\"http://java.sun.com/jsf/core\" prefix=\"f\"%>\n<%@ taglib uri=\"http://richfaces.org/a4j\" prefix=\"a4j\"%>\n\n<f:view>\n <body>\n <h:form id=\"signup\">\n <table class=\"logo_background\">\n <tr>\n <td valign=\"top\">\n <table style=\"margin-left: 55px; background:#FFCC00\" class=\"tab_background\">\n <tr>\n <td width=\"145px\" style=\"padding-left: 25px;\">\n <a4j:commandLink id=\"linkHowToPlayId\" onclick=\"retTabClick(this.id);\" value=\"howtoplay\"></a4j:commandLink>\n </td>\n <td width=\"100px\" align=\"center\" style=\"padding-left: 5px;\">\n <a4j:commandLink id=\"linkRulesId\" onclick=\"retTabClick(this.id);\" value=\"rules\"/>\n </td>\n <td width=\"5px\">\n </td>\n <td width=\"130px\" align=\"center\" style=\"padding-left: 5px;\">\n <a4j:commandLink id=\"linkChallengesId\" onclick=\"retTabClick(this.id);\" value=\"challenges\"></a4j:commandLink>\n </td>\n <td width=\"5px\">\n </td>\n <td width=\"130px\" align=\"center\" style=\"padding-left: 5px; padding-right: 15px;\">\n <a4j:commandLink id=\"linkPickATeamId\" onclick=\"retTabClick(this.id);\" value=\"pickateam\"/>\n </td>\n </tr>\n </table>\n <table>\n <tr>\n <td width=\"100px\"></td>\n <td valign=\"top\">\n <table class=\"signup_background\" style=\"width: 565px; height: 390px; border: solid 1px #5F8CC2;\">\n <tr>\n <td id=\"content\" style=\"width: 100%;\" valign=\"top\">\n <a4j:region>\n <a4j:poll id=\"poll1\" interval=\"2000\" enabled=\"true\" reRender=\"signup:howtoplay,signup:rules,signup:challenges,signup:pickateam\" oncomplete=\"javascript:loopIt();\"></a4j:poll>\n </a4j:region>\n <a4j:outputPanel id=\"howtoplay\" layout=\"block\" style=\"display:none;\">\n <h:graphicImage value=\"http://connectnigeria.com/articles/wp-content/uploads/2012/12/Google.jpg\"></h:graphicImage>\n </a4j:outputPanel>\n <a4j:outputPanel id=\"rules\" layout=\"block\" style=\"display:none;\">\n <h:graphicImage value=\"http://good-wallpapers.com/pictures/4528/1280_countryside_landscape_wallpaper.jpg\"></h:graphicImage>\n </a4j:outputPanel>\n <a4j:outputPanel id=\"challenges\" layout=\"block\" style=\"display:none;\">\n <h:graphicImage value=\"http://www.hdwallpapers.in/walls/windows_8_official-wide.jpg\"></h:graphicImage>\n </a4j:outputPanel>\n <a4j:outputPanel id=\"pickateam\" layout=\"block\" style=\"display:none;\">\n <h:graphicImage value=\"../../images/87643.jpg\"></h:graphicImage>\n </a4j:outputPanel>\n </td>\n </tr>\n </table>\n </td>\n </tr>\n </table>\n </td>\n </tr>\n </table>\n </h:form>\n\n\n<script type=\"text/javascript\">\n var first= 1;\n if( first == 1)\n {\n document.getElementById(\"signup:howtoplay\").style.display = 'block';\n document.getElementById(\"signup:rules\").style.display = 'none';\n document.getElementById(\"signup:challenges\").style.display = 'none';\n document.getElementById(\"signup:pickateam\").style.display = 'none';\n\n }\n function retTabClick(tabId) {\n if (tabId == \"signup:linkHowToPlayId\") {\n first = \"1\";\n } else if (tabId == \"signup:linkRulesId\") {\n first = \"2\";\n } else if (tabId == \"signup:linkChallengesId\") {\n first = \"3\";\n } else if (tabId == \"signup:linkPickATeamId\") {\n first = \"4\";\n }\n }\n function loopIt()\n {\n if( first == 1)\n {\n document.getElementById(\"signup:howtoplay\").style.display = 'block';\n document.getElementById(\"signup:rules\").style.display = 'none';\n document.getElementById(\"signup:challenges\").style.display = 'none';\n document.getElementById(\"signup:pickateam\").style.display = 'none';\n first = 2;\n }\n else if (first == 2)\n {\n document.getElementById(\"signup:howtoplay\").style.display = 'none';\n document.getElementById(\"signup:rules\").style.display = 'block';\n document.getElementById(\"signup:challenges\").style.display = 'none';\n document.getElementById(\"signup:pickateam\").style.display = 'none';\n\n first = 3;\n }\n else if (first == 3)\n {\n document.getElementById(\"signup:howtoplay\").style.display = 'none';\n document.getElementById(\"signup:rules\").style.display = 'none';\n document.getElementById(\"signup:challenges\").style.display = 'block';\n document.getElementById(\"signup:pickateam\").style.display = 'none';\n\n first = 4;\n }\n else if (first == 4)\n {\n document.getElementById(\"signup:howtoplay\").style.display = 'none';\n document.getElementById(\"signup:rules\").style.display = 'none';\n document.getElementById(\"signup:challenges\").style.display = 'none';\n document.getElementById(\"signup:pickateam\").style.display = 'block';\n\n first = 1;\n }\n }\n </script>\n</body>\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8981/"
] |
355,043 | <p>I am trying to pass a dataString to to an ajax call using JQuery. In the call, I construct the get parameters and then send them to the php page on the receiving end. The trouble is that the data string has ampersands in them and the HTML strict validator is chocking on it.</p>
<p>Here is the code:</p>
<pre><code>$(document).ready(function(){
$("input#email").focus();
$('#login_submit').submit(function(){
var username = $('input#email').val();
var password = $('input#password').val();
var remember = $('input#remember').attr("checked");
var dataString = "email="+username+"&password="+password+"&remember="+remember;
$.post('login.php', dataString, function(data) {
if (data == 'Login Succeeded.') {
location.reload(true);
} else {
$("input#email").focus();
$("#login_msg").html(data).effect("pulsate", {times: 2}, 1000);
}
});
return false;
});
});
</code></pre>
<p>and here is an example of the validator message: cannot generate system identifier for general entity "password".</p>
<pre><code>var dataString = "email="+username+"&password="+password+"&remember="+rememb…
</code></pre>
<p>(in the validator the "p" after the first ampersand is marked red indicating the point of the failure).</p>
| [
{
"answer_id": 355047,
"author": "Marc Novakowski",
"author_id": 27020,
"author_profile": "https://Stackoverflow.com/users/27020",
"pm_score": 6,
"selected": true,
"text": "<script type=\"text/javascript\">\n<![CDATA[\n// content of your Javascript goes here\n]]>\n</script> \n <script type=\"text/javascript\">\n/* <![CDATA[ */\n// content of your Javascript goes here\n/* ]]> */\n</script> \n"
},
{
"answer_id": 355054,
"author": "Luis Melgratti",
"author_id": 17032,
"author_profile": "https://Stackoverflow.com/users/17032",
"pm_score": -1,
"selected": false,
"text": "var dataString = \"email=\"+username+\"&password=\"+password+\"&remember=\"+remember;\n"
},
{
"answer_id": 9057547,
"author": "Dana WIlson",
"author_id": 1177038,
"author_profile": "https://Stackoverflow.com/users/1177038",
"pm_score": 1,
"selected": false,
"text": "\\u0026 & %26 & <![CDATA[ ... ]]>   mathml target nested xml"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4082/"
] |
355,051 | <p>I have a prefix trie. What is the recommended schema for representing this structure in a relational database? I need substring matching to remain efficient.</p>
| [
{
"answer_id": 355064,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 5,
"selected": true,
"text": "CREATE TABLE trie (\n path VARCHAR(<maxdepth>) PRIMARY KEY,\n ...other attributes of a tree node...\n);\n INSERT INTO trie (path) VALUES\n ('s'), ('st'), ('sta'), ('stac'), ('stack'),\n ('stacko'), ('stackov'), ('stackove'), ('stackover'),\n ('stackover'), ('stackoverf'), ('stackoverflo'),\n ('stackoverflow');\n"
},
{
"answer_id": 71980806,
"author": "Marc B",
"author_id": 14655791,
"author_profile": "https://Stackoverflow.com/users/14655791",
"pm_score": 0,
"selected": false,
"text": "CREATE TABLE trie (\n path VARCHAR(<maxdepth>) PRIMARY KEY,\n **node_id NUMBER,**\n **parent_node_id NUMBER,**\n ...other attributes of a tree node...\n);\n SELECT * FROM trie WHERE parent_node_id =\n (select node_id from trie where path='stack')\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355051",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
355,060 | <p>I have heard that the Java implementation of Generics is not as good as the C# implementation. In that the syntax looks similar, what is it that is substandard about the Java implementation, or is it a religious point of view?</p>
| [
{
"answer_id": 355885,
"author": "IgorK",
"author_id": 44647,
"author_profile": "https://Stackoverflow.com/users/44647",
"pm_score": 4,
"selected": false,
"text": "Object Object Object MyClass int Integer List<Integer> List List<Double> List<Integer>"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355060",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5302/"
] |
355,062 | <p>If I have a string with a valid math expression such as:</p>
<pre><code>String s = "1 + 2 * 7";
</code></pre>
<p>Is there a built in library/function in .NET that will parse and evaluate that expression for me and return the result? In this case 15.</p>
| [
{
"answer_id": 392347,
"author": "Guy",
"author_id": 1463,
"author_profile": "https://Stackoverflow.com/users/1463",
"pm_score": 5,
"selected": false,
"text": "double result = (double) HtmlPage.Window.Eval(\"15 + 35\");\n"
},
{
"answer_id": 392355,
"author": "user21826",
"author_id": 21826,
"author_profile": "https://Stackoverflow.com/users/21826",
"pm_score": 7,
"selected": true,
"text": "Dim sc As New MSScriptControl.ScriptControl()\nsc.Language = \"VBScript\"\nDim expression As String = \"1 + 2 * 7\"\nDim result As Double = sc.Eval(expression)\n MSScriptControl.ScriptControl sc = new MSScriptControl.ScriptControl();\nsc.Language = \"VBScript\";\nstring expression = \"1 + 2 * 7\";\nobject result = sc.Eval(expression); \nMessageBox.Show(result.ToString());\n"
},
{
"answer_id": 2196685,
"author": "cbp",
"author_id": 21966,
"author_profile": "https://Stackoverflow.com/users/21966",
"pm_score": 4,
"selected": false,
"text": " public static double Evaluate(string expression)\n {\n var xsltExpression = \n string.Format(\"number({0})\", \n new Regex(@\"([\\+\\-\\*])\").Replace(expression, \" ${1} \")\n .Replace(\"/\", \" div \")\n .Replace(\"%\", \" mod \"));\n\n return (double)new XPathDocument\n (new StringReader(\"<r/>\"))\n .CreateNavigator()\n .Evaluate(xsltExpression);\n }\n"
},
{
"answer_id": 4396704,
"author": "GreyCloud",
"author_id": 397268,
"author_profile": "https://Stackoverflow.com/users/397268",
"pm_score": 5,
"selected": false,
"text": "Expression e = new Expression(\"Round(Pow(Pi, 2) + Pow([Pi2], 2) + X, 2)\"); \n\n e.Parameters[\"Pi2\"] = new Expression(\"Pi * Pi\"); \n e.Parameters[\"X\"] = 10; \n\n e.EvaluateParameter += delegate(string name, ParameterArgs args) \n { \n if (name == \"Pi\") \n args.Result = 3.14; \n }; \n\n Debug.Assert(117.07 == e.Evaluate()); \n"
},
{
"answer_id": 8134875,
"author": "ma81xx",
"author_id": 1047363,
"author_profile": "https://Stackoverflow.com/users/1047363",
"pm_score": 3,
"selected": false,
"text": "DataTable Dim dt As New DataTable\ndt.Columns.Add(\"A\", GetType(Integer))\ndt.Columns.Add(\"B\", GetType(Integer))\ndt.Columns.Add(\"C\", GetType(Integer))\ndt.Rows.Add(New Object() {12, 13, DBNull.Value})\n\nDim boolResult As Boolean = dt.Select(\"A>B-2\").Length > 0\n\ndt.Columns.Add(\"result\", GetType(Integer), \"A+B*2+ISNULL(C,0)\")\nDim valResult As Object = dt.Rows(0)(\"result\")\n"
},
{
"answer_id": 14859374,
"author": "user2069333",
"author_id": 2069333,
"author_profile": "https://Stackoverflow.com/users/2069333",
"pm_score": 1,
"selected": false,
"text": "namespace CalcExp\n{\n internal class Program\n {\n private static void Main(string[] args)\n {\n double res = Evaluate(\"4+5/2-1\");\n\n Console.WriteLine(res);\n\n }\n\n public static double Evaluate(string expression)\n {\n var xsltExpression =\n string.Format(\"number({0})\",\n new Regex(@\"([\\+\\-\\*])\").Replace(expression, \" ${1} \")\n .Replace(\"/\", \" div \")\n .Replace(\"%\", \" mod \"));\n\n// ReSharper disable PossibleNullReferenceException\n return (double)new XPathDocument\n (new StringReader(\"<r/>\"))\n .CreateNavigator()\n .Evaluate(xsltExpression);\n// ReSharper restore PossibleNullReferenceException\n }\n\n }\n}\n"
},
{
"answer_id": 18796518,
"author": "Tim Schmelter",
"author_id": 284240,
"author_profile": "https://Stackoverflow.com/users/284240",
"pm_score": 6,
"selected": false,
"text": "DataTable.Compute double result = Convert.ToDouble(new DataTable().Compute(\"1 + 2 * 7\", null));\n + (addition)\n- (subtraction)\n* (multiplication)\n/ (division)\n% (modulus)\n DataColumn.Expression"
},
{
"answer_id": 31489952,
"author": "ISCI",
"author_id": 1621946,
"author_profile": "https://Stackoverflow.com/users/1621946",
"pm_score": 0,
"selected": false,
"text": "Imports Ciloci.Flee\nImports Ciloci.Flee.CalcEngine\nImports System.Math\n Dim ec As New Ciloci.Flee.ExpressionContext\n Dim ex As IDynamicExpression\n ec.Imports.AddType(GetType(Math))\n\n ec.Variables(\"a\") = 10 \n ec.Variables(\"b\") = 40 \n ex = ec.CompileDynamic(\"a+b\")\n\n Dim evalData \n evalData = ex.Evaluate()\n Console.WriteLine(evalData)\n"
},
{
"answer_id": 34869999,
"author": "schoetbi",
"author_id": 108238,
"author_profile": "https://Stackoverflow.com/users/108238",
"pm_score": 4,
"selected": false,
"text": "public class CSCodeEvaler\n{\n public double EvalCode()\n {\n return last = Convert.ToDouble(%formula%);\n }\n\n public double last = 0;\n public const double pi = Math.PI;\n public const double e = Math.E;\n public double sin(double value) { return Math.Sin(value); }\n public double cos(double value) { return Math.Cos(value); }\n public double tan(double value) { return Math.Tan(value); }\n ...\n"
},
{
"answer_id": 35785072,
"author": "Leroy Kegan",
"author_id": 5999910,
"author_profile": "https://Stackoverflow.com/users/5999910",
"pm_score": 4,
"selected": false,
"text": "Expression e = new Expression(\"1+2*7 + (sin(10) - 2)/3\");\ndouble v = e.calculate();\n Argument x = new Argument(\"x = 5\");\nExpression e = new Expression(\"2*x+3\", x);\ndouble v = e.calculate();\n Function f = new Function(\"f(x,y) = sin(x) / cos(y)\");\nExpression e = new Expression(\"f(pi, 2*pi) - 2\", f);\ndouble v = e.calculate();\n"
},
{
"answer_id": 36156299,
"author": "Crowcoder",
"author_id": 276469,
"author_profile": "https://Stackoverflow.com/users/276469",
"pm_score": 4,
"selected": false,
"text": "using Microsoft.CodeAnalysis.CSharp.Scripting;\nusing System;\n\nnamespace ExpressionParser\n{\n class Program\n {\n static void Main(string[] args)\n {\n //Demonstrate evaluating C# code\n var result = CSharpScript.EvaluateAsync(\"System.DateTime.Now.AddDays(-1) > System.DateTime.Now\").Result;\n Console.WriteLine(result.ToString());\n\n //Demonstrate evaluating simple expressions\n var result2 = CSharpScript.EvaluateAsync(\" 5 * 7\").Result;\n Console.WriteLine(result2);\n Console.ReadKey();\n }\n }\n}\n <package id=\"Microsoft.CodeAnalysis.Analyzers\" version=\"1.1.0\" targetFramework=\"net461\" />\n<package id=\"Microsoft.CodeAnalysis.Common\" version=\"1.1.1\" targetFramework=\"net461\" />\n<package id=\"Microsoft.CodeAnalysis.CSharp\" version=\"1.1.1\" targetFramework=\"net461\" />\n<package id=\"Microsoft.CodeAnalysis.CSharp.Scripting\" version=\"1.1.1\" targetFramework=\"net461\" />\n<package id=\"Microsoft.CodeAnalysis.Scripting\" version=\"1.1.1\" targetFramework=\"net461\" />\n<package id=\"Microsoft.CodeAnalysis.Scripting.Common\" version=\"1.1.1\" targetFramework=\"net461\" />\n"
},
{
"answer_id": 38495434,
"author": "Lorenz Lo Sauer",
"author_id": 901946,
"author_profile": "https://Stackoverflow.com/users/901946",
"pm_score": 2,
"selected": false,
"text": "class RPN\n{\n public static double Parse( Stack<string> strStk )\n {\n if (strStk == null || strStk.Count == 0 )\n {\n return 0;\n }\n Stack<double> numStk = new Stack<double>();\n double result = 0;\n\n Func<double, double> op = null;\n while (strStk.Count > 0)\n {\n var s = strStk.Pop();\n switch (s)\n {\n case \"+\":\n op = ( b ) => { return numStk.Pop() + b; };\n break;\n case \"-\":\n op = ( b ) => { return numStk.Pop() - b; };\n break;\n case \"*\":\n op = ( b ) => { return numStk.Pop() * b; };\n break;\n case \"/\":\n op = ( b ) => { return numStk.Pop() / b; };\n break;\n\n default:\n double.TryParse(s, NumberStyles.Any, out result);\n if (numStk.Count > 0)\n {\n result = op(result);\n }\n numStk.Push(result);\n break;\n }\n }\n return result;\n }\n}\n\n....\nvar str = \" 100.5 + 300.5 - 100 * 10 / 100\"; \nstr = Regex.Replace(str, @\"\\s\", \"\", RegexOptions.Multiline);\nStack<string> strStk = new Stack<string>(\n Regex.Split(str, @\"([()*+\\/-])\", RegexOptions.Multiline).Reverse()\n);\nRPN.Parse(strStk);\n"
},
{
"answer_id": 55050883,
"author": "Second Person Shooter",
"author_id": 397524,
"author_profile": "https://Stackoverflow.com/users/397524",
"pm_score": 1,
"selected": false,
"text": "using System;\nusing static MathNet.Symbolics.SymbolicExpression;\nusing static System.Console;\nusing static System.Numerics.Complex;\nusing Complex = System.Numerics.Complex;\n\nnamespace MathEvaluator\n{\n class Program\n {\n static readonly Complex i = ImaginaryOne;\n\n static void Main(string[] args)\n {\n var z = Variable(\"z\");\n Func<Complex, Complex> f = Parse(\"z * z\").CompileComplex(nameof(z));\n Complex c = 1 / 2 - i / 3;\n WriteLine(f(c));\n\n\n var x = Variable(\"x\");\n Func<double, double> g = Parse(\"x * x + 5 * x + 6\").Compile(nameof(x));\n double a = 1 / 3.0;\n WriteLine(g(a));\n }\n }\n}\n <PackageReference Include=\"MathNet.Symbolics\" Version=\"0.20.0\" />\n"
},
{
"answer_id": 62124016,
"author": "Giorgi",
"author_id": 239438,
"author_profile": "https://Stackoverflow.com/users/239438",
"pm_score": 2,
"selected": false,
"text": "2.5+5.9 17.89-2.47+7.16 5/2/2+1.5*3+4.58 (((9-6/2)*2-4)/2-6-1)/(2+24/(2+4)) var a = 6;\nvar b = 4.32m;\nvar c = 24.15m;\nvar engine = new ExpressionEvaluator();\nengine.Evaluate(\"(((9-a/2)*2-b)/2-a-1)/(2+c/(2+4))\", new { a, b, c});\n dynamic dynamicEngine = new ExpressionEvaluator();\n\nvar a = 6;\nvar b = 4.5m;\nvar c = 2.6m;\n\ndynamicEngine.Evaluate(\"(c+b)*a\", a: 6, b: 4.5, c: 2.6);\n"
},
{
"answer_id": 67949129,
"author": "WhiteBlackGoose",
"author_id": 10586919,
"author_profile": "https://Stackoverflow.com/users/10586919",
"pm_score": 2,
"selected": false,
"text": "using AngouriMath;\nEntity expr = \"1 + 2 + sqrt(2)\";\nvar answer = (double)expr.EvalNumerical();\n Entity expr = \"1 + 2 + sqrt(2) + x + y\";\nFunc<double, double, double> someFunc = expr.Compile<double, double, double>(\"x\", \"y\");\nConsole.WriteLine(someFunc(3, 5));\n using Towel.Mathematics;\nvar expression = Symbolics.Parse<double>(\"(2 + 2 * 2 - (2 ^ 4)) / 2\");\nConsole.WriteLine(expression.Simplify());\n double"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1463/"
] |
355,073 | <p>I have a simple vb6 editor type application which has a richtextbox as the editor page. It allows users to key in stuff and the store it into a file which will keep all the text in RTF stored as CDATA in xml.</p>
<p>When you load back the file, it will read it off the xml and load back the rtf. We allow for unicode editing, but my problem is I have a user which is using Windows XP, and they have some problems reading the chinese characters. They show up as gibberish in their pc.</p>
<p>It displays fine in both mine and a coworker's. I've already checked that they have the proper regional language and settings in their system. The install files for east asian language is already checked. And they can see chinese words on websites and even type them out.</p>
<p>I feel like I'm missing something here but I'm at a lost on what to check next? Any ideas on what I could test or check next?</p>
<p>my bad for the poor description skills, if anything is not clear just ask me.
thanks.
~steve</p>
| [
{
"answer_id": 392347,
"author": "Guy",
"author_id": 1463,
"author_profile": "https://Stackoverflow.com/users/1463",
"pm_score": 5,
"selected": false,
"text": "double result = (double) HtmlPage.Window.Eval(\"15 + 35\");\n"
},
{
"answer_id": 392355,
"author": "user21826",
"author_id": 21826,
"author_profile": "https://Stackoverflow.com/users/21826",
"pm_score": 7,
"selected": true,
"text": "Dim sc As New MSScriptControl.ScriptControl()\nsc.Language = \"VBScript\"\nDim expression As String = \"1 + 2 * 7\"\nDim result As Double = sc.Eval(expression)\n MSScriptControl.ScriptControl sc = new MSScriptControl.ScriptControl();\nsc.Language = \"VBScript\";\nstring expression = \"1 + 2 * 7\";\nobject result = sc.Eval(expression); \nMessageBox.Show(result.ToString());\n"
},
{
"answer_id": 2196685,
"author": "cbp",
"author_id": 21966,
"author_profile": "https://Stackoverflow.com/users/21966",
"pm_score": 4,
"selected": false,
"text": " public static double Evaluate(string expression)\n {\n var xsltExpression = \n string.Format(\"number({0})\", \n new Regex(@\"([\\+\\-\\*])\").Replace(expression, \" ${1} \")\n .Replace(\"/\", \" div \")\n .Replace(\"%\", \" mod \"));\n\n return (double)new XPathDocument\n (new StringReader(\"<r/>\"))\n .CreateNavigator()\n .Evaluate(xsltExpression);\n }\n"
},
{
"answer_id": 4396704,
"author": "GreyCloud",
"author_id": 397268,
"author_profile": "https://Stackoverflow.com/users/397268",
"pm_score": 5,
"selected": false,
"text": "Expression e = new Expression(\"Round(Pow(Pi, 2) + Pow([Pi2], 2) + X, 2)\"); \n\n e.Parameters[\"Pi2\"] = new Expression(\"Pi * Pi\"); \n e.Parameters[\"X\"] = 10; \n\n e.EvaluateParameter += delegate(string name, ParameterArgs args) \n { \n if (name == \"Pi\") \n args.Result = 3.14; \n }; \n\n Debug.Assert(117.07 == e.Evaluate()); \n"
},
{
"answer_id": 8134875,
"author": "ma81xx",
"author_id": 1047363,
"author_profile": "https://Stackoverflow.com/users/1047363",
"pm_score": 3,
"selected": false,
"text": "DataTable Dim dt As New DataTable\ndt.Columns.Add(\"A\", GetType(Integer))\ndt.Columns.Add(\"B\", GetType(Integer))\ndt.Columns.Add(\"C\", GetType(Integer))\ndt.Rows.Add(New Object() {12, 13, DBNull.Value})\n\nDim boolResult As Boolean = dt.Select(\"A>B-2\").Length > 0\n\ndt.Columns.Add(\"result\", GetType(Integer), \"A+B*2+ISNULL(C,0)\")\nDim valResult As Object = dt.Rows(0)(\"result\")\n"
},
{
"answer_id": 14859374,
"author": "user2069333",
"author_id": 2069333,
"author_profile": "https://Stackoverflow.com/users/2069333",
"pm_score": 1,
"selected": false,
"text": "namespace CalcExp\n{\n internal class Program\n {\n private static void Main(string[] args)\n {\n double res = Evaluate(\"4+5/2-1\");\n\n Console.WriteLine(res);\n\n }\n\n public static double Evaluate(string expression)\n {\n var xsltExpression =\n string.Format(\"number({0})\",\n new Regex(@\"([\\+\\-\\*])\").Replace(expression, \" ${1} \")\n .Replace(\"/\", \" div \")\n .Replace(\"%\", \" mod \"));\n\n// ReSharper disable PossibleNullReferenceException\n return (double)new XPathDocument\n (new StringReader(\"<r/>\"))\n .CreateNavigator()\n .Evaluate(xsltExpression);\n// ReSharper restore PossibleNullReferenceException\n }\n\n }\n}\n"
},
{
"answer_id": 18796518,
"author": "Tim Schmelter",
"author_id": 284240,
"author_profile": "https://Stackoverflow.com/users/284240",
"pm_score": 6,
"selected": false,
"text": "DataTable.Compute double result = Convert.ToDouble(new DataTable().Compute(\"1 + 2 * 7\", null));\n + (addition)\n- (subtraction)\n* (multiplication)\n/ (division)\n% (modulus)\n DataColumn.Expression"
},
{
"answer_id": 31489952,
"author": "ISCI",
"author_id": 1621946,
"author_profile": "https://Stackoverflow.com/users/1621946",
"pm_score": 0,
"selected": false,
"text": "Imports Ciloci.Flee\nImports Ciloci.Flee.CalcEngine\nImports System.Math\n Dim ec As New Ciloci.Flee.ExpressionContext\n Dim ex As IDynamicExpression\n ec.Imports.AddType(GetType(Math))\n\n ec.Variables(\"a\") = 10 \n ec.Variables(\"b\") = 40 \n ex = ec.CompileDynamic(\"a+b\")\n\n Dim evalData \n evalData = ex.Evaluate()\n Console.WriteLine(evalData)\n"
},
{
"answer_id": 34869999,
"author": "schoetbi",
"author_id": 108238,
"author_profile": "https://Stackoverflow.com/users/108238",
"pm_score": 4,
"selected": false,
"text": "public class CSCodeEvaler\n{\n public double EvalCode()\n {\n return last = Convert.ToDouble(%formula%);\n }\n\n public double last = 0;\n public const double pi = Math.PI;\n public const double e = Math.E;\n public double sin(double value) { return Math.Sin(value); }\n public double cos(double value) { return Math.Cos(value); }\n public double tan(double value) { return Math.Tan(value); }\n ...\n"
},
{
"answer_id": 35785072,
"author": "Leroy Kegan",
"author_id": 5999910,
"author_profile": "https://Stackoverflow.com/users/5999910",
"pm_score": 4,
"selected": false,
"text": "Expression e = new Expression(\"1+2*7 + (sin(10) - 2)/3\");\ndouble v = e.calculate();\n Argument x = new Argument(\"x = 5\");\nExpression e = new Expression(\"2*x+3\", x);\ndouble v = e.calculate();\n Function f = new Function(\"f(x,y) = sin(x) / cos(y)\");\nExpression e = new Expression(\"f(pi, 2*pi) - 2\", f);\ndouble v = e.calculate();\n"
},
{
"answer_id": 36156299,
"author": "Crowcoder",
"author_id": 276469,
"author_profile": "https://Stackoverflow.com/users/276469",
"pm_score": 4,
"selected": false,
"text": "using Microsoft.CodeAnalysis.CSharp.Scripting;\nusing System;\n\nnamespace ExpressionParser\n{\n class Program\n {\n static void Main(string[] args)\n {\n //Demonstrate evaluating C# code\n var result = CSharpScript.EvaluateAsync(\"System.DateTime.Now.AddDays(-1) > System.DateTime.Now\").Result;\n Console.WriteLine(result.ToString());\n\n //Demonstrate evaluating simple expressions\n var result2 = CSharpScript.EvaluateAsync(\" 5 * 7\").Result;\n Console.WriteLine(result2);\n Console.ReadKey();\n }\n }\n}\n <package id=\"Microsoft.CodeAnalysis.Analyzers\" version=\"1.1.0\" targetFramework=\"net461\" />\n<package id=\"Microsoft.CodeAnalysis.Common\" version=\"1.1.1\" targetFramework=\"net461\" />\n<package id=\"Microsoft.CodeAnalysis.CSharp\" version=\"1.1.1\" targetFramework=\"net461\" />\n<package id=\"Microsoft.CodeAnalysis.CSharp.Scripting\" version=\"1.1.1\" targetFramework=\"net461\" />\n<package id=\"Microsoft.CodeAnalysis.Scripting\" version=\"1.1.1\" targetFramework=\"net461\" />\n<package id=\"Microsoft.CodeAnalysis.Scripting.Common\" version=\"1.1.1\" targetFramework=\"net461\" />\n"
},
{
"answer_id": 38495434,
"author": "Lorenz Lo Sauer",
"author_id": 901946,
"author_profile": "https://Stackoverflow.com/users/901946",
"pm_score": 2,
"selected": false,
"text": "class RPN\n{\n public static double Parse( Stack<string> strStk )\n {\n if (strStk == null || strStk.Count == 0 )\n {\n return 0;\n }\n Stack<double> numStk = new Stack<double>();\n double result = 0;\n\n Func<double, double> op = null;\n while (strStk.Count > 0)\n {\n var s = strStk.Pop();\n switch (s)\n {\n case \"+\":\n op = ( b ) => { return numStk.Pop() + b; };\n break;\n case \"-\":\n op = ( b ) => { return numStk.Pop() - b; };\n break;\n case \"*\":\n op = ( b ) => { return numStk.Pop() * b; };\n break;\n case \"/\":\n op = ( b ) => { return numStk.Pop() / b; };\n break;\n\n default:\n double.TryParse(s, NumberStyles.Any, out result);\n if (numStk.Count > 0)\n {\n result = op(result);\n }\n numStk.Push(result);\n break;\n }\n }\n return result;\n }\n}\n\n....\nvar str = \" 100.5 + 300.5 - 100 * 10 / 100\"; \nstr = Regex.Replace(str, @\"\\s\", \"\", RegexOptions.Multiline);\nStack<string> strStk = new Stack<string>(\n Regex.Split(str, @\"([()*+\\/-])\", RegexOptions.Multiline).Reverse()\n);\nRPN.Parse(strStk);\n"
},
{
"answer_id": 55050883,
"author": "Second Person Shooter",
"author_id": 397524,
"author_profile": "https://Stackoverflow.com/users/397524",
"pm_score": 1,
"selected": false,
"text": "using System;\nusing static MathNet.Symbolics.SymbolicExpression;\nusing static System.Console;\nusing static System.Numerics.Complex;\nusing Complex = System.Numerics.Complex;\n\nnamespace MathEvaluator\n{\n class Program\n {\n static readonly Complex i = ImaginaryOne;\n\n static void Main(string[] args)\n {\n var z = Variable(\"z\");\n Func<Complex, Complex> f = Parse(\"z * z\").CompileComplex(nameof(z));\n Complex c = 1 / 2 - i / 3;\n WriteLine(f(c));\n\n\n var x = Variable(\"x\");\n Func<double, double> g = Parse(\"x * x + 5 * x + 6\").Compile(nameof(x));\n double a = 1 / 3.0;\n WriteLine(g(a));\n }\n }\n}\n <PackageReference Include=\"MathNet.Symbolics\" Version=\"0.20.0\" />\n"
},
{
"answer_id": 62124016,
"author": "Giorgi",
"author_id": 239438,
"author_profile": "https://Stackoverflow.com/users/239438",
"pm_score": 2,
"selected": false,
"text": "2.5+5.9 17.89-2.47+7.16 5/2/2+1.5*3+4.58 (((9-6/2)*2-4)/2-6-1)/(2+24/(2+4)) var a = 6;\nvar b = 4.32m;\nvar c = 24.15m;\nvar engine = new ExpressionEvaluator();\nengine.Evaluate(\"(((9-a/2)*2-b)/2-a-1)/(2+c/(2+4))\", new { a, b, c});\n dynamic dynamicEngine = new ExpressionEvaluator();\n\nvar a = 6;\nvar b = 4.5m;\nvar c = 2.6m;\n\ndynamicEngine.Evaluate(\"(c+b)*a\", a: 6, b: 4.5, c: 2.6);\n"
},
{
"answer_id": 67949129,
"author": "WhiteBlackGoose",
"author_id": 10586919,
"author_profile": "https://Stackoverflow.com/users/10586919",
"pm_score": 2,
"selected": false,
"text": "using AngouriMath;\nEntity expr = \"1 + 2 + sqrt(2)\";\nvar answer = (double)expr.EvalNumerical();\n Entity expr = \"1 + 2 + sqrt(2) + x + y\";\nFunc<double, double, double> someFunc = expr.Compile<double, double, double>(\"x\", \"y\");\nConsole.WriteLine(someFunc(3, 5));\n using Towel.Mathematics;\nvar expression = Symbolics.Parse<double>(\"(2 + 2 * 2 - (2 ^ 4)) / 2\");\nConsole.WriteLine(expression.Simplify());\n double"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355073",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38124/"
] |
355,083 | <p>I wanna add server controls by using javascript. The main purpose of why I want is to add controls without any postback and get them in code-behind.</p>
| [
{
"answer_id": 355120,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 2,
"selected": false,
"text": "Request.Form[\"inputName\"]\n name <input type=\"text\" value=\"blah\" name=\"inputName\" />\n"
},
{
"answer_id": 355122,
"author": "cfbarbero",
"author_id": 2218,
"author_profile": "https://Stackoverflow.com/users/2218",
"pm_score": 3,
"selected": true,
"text": "<input type=\"text\" id=\"testBox\" value=\"blah\" />\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355083",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44852/"
] |
355,084 | <p>I have a <code>ListBox</code> that scrolls images horizontally.</p>
<p>I have the following XAML I used blend to create it. It originally had a x:Key on the <code>Style TaregetType</code> line, MSDN said to remove it, as I was getting errors on that. Now I'm getting this error:</p>
<p><code>Error 3 Operation is not valid while ItemsSource is in use. Access and modify elements with ItemsControl.ItemsSource instead.</code></p>
<p>I don't understand how to apply all of this junk that way, I've tried several things, nothing is working.</p>
<p>My goal is to have the selected item's background be white, not blue. Seems like a lot of work for something so small!</p>
<p>Thanks.</p>
<pre><code> <ListBox ItemsSource="{Binding Source={StaticResource WPFApparelCollection}}"
Grid.Row="1" Margin="2,26,2,104" ScrollViewer.VerticalScrollBarVisibility="Hidden"
ScrollViewer.HorizontalScrollBarVisibility="Hidden" SelectionMode="Single"
x:Name="list1" MouseLeave="List1_MouseLeave" MouseMove="List1_MouseMove" Style="{DynamicResource ListBoxStyle1}" >
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="Background" Value="Transparent"/>
<Setter Property="HorizontalContentAlignment" Value="{Binding Path=HorizontalContentAlignment, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}"/>
<Setter Property="VerticalContentAlignment" Value="{Binding Path=VerticalContentAlignment, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}"/>
<Setter Property="Padding" Value="2,0,0,0"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<Border x:Name="Bd" SnapsToDevicePixels="true" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Padding="{TemplateBinding Padding}">
<ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="true">
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.HighlightTextBrushKey}}"/>
<Setter Property="Background" TargetName="Bd" Value="#FFFFFFFF"/>
</Trigger>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="IsSelected" Value="true"/>
<Condition Property="Selector.IsSelectionActive" Value="false"/>
</MultiTrigger.Conditions>
<Setter Property="Background" TargetName="Bd" Value="{DynamicResource {x:Static SystemColors.ControlBrushKey}}"/>
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
</MultiTrigger>
<Trigger Property="IsEnabled" Value="false">
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel
Orientation="Horizontal"
IsItemsHost="True" />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<Image Source="{Binding Image}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</code></pre>
| [
{
"answer_id": 358106,
"author": "Jobi Joy",
"author_id": 8091,
"author_profile": "https://Stackoverflow.com/users/8091",
"pm_score": 5,
"selected": true,
"text": "<ListBox ItemsSource=\"{Binding Source={StaticResource WPFApparelCollection}}\"\n Grid.Row=\"1\" Margin=\"2,26,2,104\"\n ScrollViewer.VerticalScrollBarVisibility=\"Hidden\"\n ScrollViewer.HorizontalScrollBarVisibility=\"Hidden\" \n SelectionMode=\"Single\"\n x:Name=\"list1\" MouseLeave=\"List1_MouseLeave\" MouseMove=\"List1_MouseMove\" \n Style=\"{DynamicResource ListBoxStyle1}\" >\n\n <ListBox.ItemContainerStyle>\n <Style TargetType=\"{x:Type ListBoxItem}\">\n <Setter Property=\"Background\" Value=\"Transparent\"/>\n </Style>\n<!-- the rest of your code, but close the ItemContainerStyle -->\n </ListBox.ItemContainerStyle> \n </ListBox>\n"
},
{
"answer_id": 8894086,
"author": "Asad Durrani",
"author_id": 1153820,
"author_profile": "https://Stackoverflow.com/users/1153820",
"pm_score": 2,
"selected": false,
"text": "<ListBox.ItemContainerStyle>\n <Style TargetType=\"{x:Type ListBoxItem}\">\n <Setter Property=\"Focusable\" Value=\"False\"/>\n </Style>\n</ListBox.ItemContainerStyle>\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22451/"
] |
355,087 | <p>related to:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/21265/">comparing ieee floats and doubles for equality</a></li>
<li><a href="https://stackoverflow.com/questions/328475/">Should we compare floating point numbers for equality against a <em>relative</em> error</a></li>
<li><a href="https://stackoverflow.com/questions/17333/#17467">Most effective way for float and double comparison</a></li>
</ul>
<p>However with regard to <a href="http://download.intel.com/design/processor/manuals/253665.pdf" rel="nofollow noreferrer">80 bit IEEE floats</a> (see section 8.2) on an x86</p>
<p>In particular I like the <a href="https://stackoverflow.com/questions/21265/comparing-ieee-floats-and-doubles-for-equality#21277">this implementation</a> using a count of representable values between the operands because it scale by default.</p>
<p>One use case would be for numeric approximations where two values approach each other and I need to check to see if they are close enough. </p>
<hr>
<p>p.s. The implementation language will be D but I can translate. Also an implementation that can automatically handle whatever the underlying type is (for instance if only 64bit real was available) would be ideal.</p>
<p><a href="http://www.dsource.org/projects/scrapple/browser/trunk/units/unit.d#L141" rel="nofollow noreferrer">The current code in use:</a></p>
| [
{
"answer_id": 355197,
"author": "BCS",
"author_id": 1343,
"author_profile": "https://Stackoverflow.com/users/1343",
"pm_score": 0,
"selected": false,
"text": "bool Near(real a, real b, int count = 5)\n{\n // Returns the number of mantissa bits which are equal in x and y.\n int i = std.math.feqrel!(real)(a,b);\n return i + count >= real.mant_dig;\n}\n"
},
{
"answer_id": 355198,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 2,
"selected": false,
"text": "if (abs (a - b) < 1e-6) // effectively equal\n if (abs (a - b) < ((a + b) / 2) / 1e6) // effectively equal\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1343/"
] |
355,089 | <p>What is the main difference between <code>StringBuffer</code> and <code>StringBuilder</code>?
Is there any performance issues when deciding on any one of these?</p>
| [
{
"answer_id": 355092,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 12,
"selected": true,
"text": "StringBuffer StringBuilder"
},
{
"answer_id": 355094,
"author": "OscarRyz",
"author_id": 20654,
"author_profile": "https://Stackoverflow.com/users/20654",
"pm_score": 8,
"selected": false,
"text": "StringBuffer StringBuilder Vector ArrayList"
},
{
"answer_id": 355126,
"author": "JRomio",
"author_id": 43513,
"author_profile": "https://Stackoverflow.com/users/43513",
"pm_score": 5,
"selected": false,
"text": "StringBuffer StringBuilder StringBuffer"
},
{
"answer_id": 1951449,
"author": "Ahmad adawi",
"author_id": 237450,
"author_profile": "https://Stackoverflow.com/users/237450",
"pm_score": 2,
"selected": false,
"text": "StringBuffer StringBuilder StringBuilder StringBuffer"
},
{
"answer_id": 2771852,
"author": "polygenelubricants",
"author_id": 276101,
"author_profile": "https://Stackoverflow.com/users/276101",
"pm_score": 10,
"selected": false,
"text": "StringBuilder StringBuffer synchronized public class Main {\n public static void main(String[] args) {\n int N = 77777777;\n long t;\n\n {\n StringBuffer sb = new StringBuffer();\n t = System.currentTimeMillis();\n for (int i = N; i --> 0 ;) {\n sb.append(\"\");\n }\n System.out.println(System.currentTimeMillis() - t);\n }\n\n {\n StringBuilder sb = new StringBuilder();\n t = System.currentTimeMillis();\n for (int i = N; i > 0 ; i--) {\n sb.append(\"\");\n }\n System.out.println(System.currentTimeMillis() - t);\n }\n }\n}\n 2241 ms StringBuffer 753 ms StringBuilder"
},
{
"answer_id": 4203914,
"author": "Ketan Patel",
"author_id": 510708,
"author_profile": "https://Stackoverflow.com/users/510708",
"pm_score": 2,
"selected": false,
"text": "String StringBuffer StringBuffer StringBuilder"
},
{
"answer_id": 4343105,
"author": "subodh ray",
"author_id": 529017,
"author_profile": "https://Stackoverflow.com/users/529017",
"pm_score": 4,
"selected": false,
"text": "StringBuilder StringBuffer StringBuffer StringBuilder StringBuilder StringBuffer StringBuilder StringBuffer StringBuffer StringBuilder"
},
{
"answer_id": 4793400,
"author": "Niclas",
"author_id": 411222,
"author_profile": "https://Stackoverflow.com/users/411222",
"pm_score": 3,
"selected": false,
"text": "StringBuilder StringBuilder StringBuffer"
},
{
"answer_id": 4793437,
"author": "Sébastien Le Callonnec",
"author_id": 289466,
"author_profile": "https://Stackoverflow.com/users/289466",
"pm_score": 3,
"selected": false,
"text": "StringBuilder StringBuffer"
},
{
"answer_id": 4793503,
"author": "Bert F",
"author_id": 11296,
"author_profile": "https://Stackoverflow.com/users/11296",
"pm_score": 8,
"selected": false,
"text": "StringBuilder StringBuilder StringBuffer StringBuffer StringBuilder StringBuffer StringBuilder StringBuffer StringBuffer"
},
{
"answer_id": 13401741,
"author": "Nicolas Zozol",
"author_id": 968988,
"author_profile": "https://Stackoverflow.com/users/968988",
"pm_score": 6,
"selected": false,
"text": "public static void main(String[] args) {\n\n String withString =\"\";\n long t0 = System.currentTimeMillis();\n for (int i = 0 ; i < 100000; i++){\n withString+=\"some string\";\n }\n System.out.println(\"strings:\" + (System.currentTimeMillis() - t0));\n\n t0 = System.currentTimeMillis();\n StringBuffer buf = new StringBuffer();\n for (int i = 0 ; i < 100000; i++){\n buf.append(\"some string\");\n }\n System.out.println(\"Buffers : \"+(System.currentTimeMillis() - t0));\n\n t0 = System.currentTimeMillis();\n StringBuilder building = new StringBuilder();\n for (int i = 0 ; i < 100000; i++){\n building.append(\"some string\");\n }\n System.out.println(\"Builder : \"+(System.currentTimeMillis() - t0));\n}\n public class StringsPerf {\n\n public static void main(String[] args) {\n\n ThreadPoolExecutor executorService = (ThreadPoolExecutor) Executors.newFixedThreadPool(10);\n //With Buffer\n StringBuffer buffer = new StringBuffer();\n for (int i = 0 ; i < 10; i++){\n executorService.execute(new AppendableRunnable(buffer));\n }\n shutdownAndAwaitTermination(executorService);\n System.out.println(\" Thread Buffer : \"+ AppendableRunnable.time);\n\n //With Builder\n AppendableRunnable.time = 0;\n executorService = (ThreadPoolExecutor) Executors.newFixedThreadPool(10);\n StringBuilder builder = new StringBuilder();\n for (int i = 0 ; i < 10; i++){\n executorService.execute(new AppendableRunnable(builder));\n }\n shutdownAndAwaitTermination(executorService);\n System.out.println(\" Thread Builder: \"+ AppendableRunnable.time);\n\n }\n\n static void shutdownAndAwaitTermination(ExecutorService pool) {\n pool.shutdown(); // code reduced from Official Javadoc for Executors\n try {\n if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {\n pool.shutdownNow();\n if (!pool.awaitTermination(60, TimeUnit.SECONDS))\n System.err.println(\"Pool did not terminate\");\n }\n } catch (Exception e) {}\n }\n}\n\nclass AppendableRunnable<T extends Appendable> implements Runnable {\n\n static long time = 0;\n T appendable;\n public AppendableRunnable(T appendable){\n this.appendable = appendable;\n }\n\n @Override\n public void run(){\n long t0 = System.currentTimeMillis();\n for (int j = 0 ; j < 10000 ; j++){\n try {\n appendable.append(\"some string\");\n } catch (IOException e) {}\n }\n time+=(System.currentTimeMillis() - t0);\n }\n}\n"
},
{
"answer_id": 15472226,
"author": "sudhakar",
"author_id": 2181470,
"author_profile": "https://Stackoverflow.com/users/2181470",
"pm_score": 4,
"selected": false,
"text": "String StringBuffer StringBuilder"
},
{
"answer_id": 17850783,
"author": "Shuhail Kadavath",
"author_id": 1896495,
"author_profile": "https://Stackoverflow.com/users/1896495",
"pm_score": 2,
"selected": false,
"text": "StringBuffer StringBuilder"
},
{
"answer_id": 20007695,
"author": "JDGuide",
"author_id": 1249710,
"author_profile": "https://Stackoverflow.com/users/1249710",
"pm_score": 2,
"selected": false,
"text": "StringBuffer StringBuilder StringBuilder StringBuffer"
},
{
"answer_id": 22413197,
"author": "Kevin Lee",
"author_id": 2669960,
"author_profile": "https://Stackoverflow.com/users/2669960",
"pm_score": 3,
"selected": false,
"text": "/**\n * Run this program a couple of times. We see that the StringBuilder does not\n * give us reliable results because its methods are not thread-safe as compared\n * to StringBuffer.\n * \n * For example, the single append in StringBuffer is thread-safe, i.e.\n * only one thread can call append() at any time and would finish writing\n * back to memory one at a time. In contrast, the append() in the StringBuilder \n * class can be called concurrently by many threads, so the final size of the \n * StringBuilder is sometimes less than expected.\n * \n */\npublic class StringBufferVSStringBuilder {\n\n public static void main(String[] args) throws InterruptedException {\n\n int n = 10; \n\n //*************************String Builder Test*******************************//\n StringBuilder sb = new StringBuilder();\n StringBuilderTest[] builderThreads = new StringBuilderTest[n];\n for (int i = 0; i < n; i++) {\n builderThreads[i] = new StringBuilderTest(sb);\n }\n for (int i = 0; i < n; i++) {\n builderThreads[i].start();\n }\n for (int i = 0; i < n; i++) {\n builderThreads[i].join();\n }\n System.out.println(\"StringBuilderTest: Expected result is 1000; got \" + sb.length());\n\n //*************************String Buffer Test*******************************//\n\n StringBuffer sb2 = new StringBuffer();\n StringBufferTest[] bufferThreads = new StringBufferTest[n];\n for (int i = 0; i < n; i++) {\n bufferThreads[i] = new StringBufferTest(sb2);\n }\n for (int i = 0; i < n; i++) {\n bufferThreads[i].start();\n }\n for (int i = 0; i < n; i++) {\n bufferThreads[i].join();\n }\n System.out.println(\"StringBufferTest: Expected result is 1000; got \" + sb2.length());\n\n }\n\n}\n\n// Every run would attempt to append 100 \"A\"s to the StringBuilder.\nclass StringBuilderTest extends Thread {\n\n StringBuilder sb;\n\n public StringBuilderTest (StringBuilder sb) {\n this.sb = sb;\n }\n\n @Override\n public void run() {\n for (int i = 0; i < 100; i++) {\n sb.append(\"A\");\n }\n\n }\n}\n\n\n//Every run would attempt to append 100 \"A\"s to the StringBuffer.\nclass StringBufferTest extends Thread {\n\n StringBuffer sb2;\n\n public StringBufferTest (StringBuffer sb2) {\n this.sb2 = sb2;\n }\n\n @Override\n public void run() {\n for (int i = 0; i < 100; i++) {\n sb2.append(\"A\");\n }\n\n }\n}\n"
},
{
"answer_id": 23021950,
"author": "Sireesh Yarlagadda",
"author_id": 2057902,
"author_profile": "https://Stackoverflow.com/users/2057902",
"pm_score": 5,
"selected": false,
"text": "StringBuffer is synchronized\nStringBuffer is thread-safe\nStringBuffer is slow (try to write a sample program and execute it, it will take more time than StringBuilder)\n StringBuilder is not synchronized \n StringBuilder is not thread-safe\n StringBuilder performance is better than StringBuffer.\n"
},
{
"answer_id": 37132467,
"author": "Pratik Paul",
"author_id": 6302948,
"author_profile": "https://Stackoverflow.com/users/6302948",
"pm_score": 2,
"selected": false,
"text": "StringBuilder StringBuffer StringBuffer StringBuffer StringBuilder StringBuilder StringBuilder"
},
{
"answer_id": 37719225,
"author": "Ravindra babu",
"author_id": 4999394,
"author_profile": "https://Stackoverflow.com/users/4999394",
"pm_score": 2,
"selected": false,
"text": "StringBuffer StringBuilder public StringBuffer(String str) {\n super(str.length() + 16);\n append(str);\n}\n\npublic synchronized StringBuffer append(Object obj) {\n super.append(String.valueOf(obj));\n return this;\n}\n\npublic synchronized StringBuffer append(String str) {\n super.append(str);\n return this;\n}\n public StringBuilder(String str) {\n super(str.length() + 16);\n append(str);\n}\n\npublic StringBuilder append(Object obj) {\n return append(String.valueOf(obj));\n}\n\npublic StringBuilder append(String str) {\n super.append(str);\n return this;\n}\n synchronized StringBuffer StrinbBuilder StringBuilder synchronized"
},
{
"answer_id": 39600508,
"author": "Aftab",
"author_id": 1599792,
"author_profile": "https://Stackoverflow.com/users/1599792",
"pm_score": 5,
"selected": false,
"text": "StringBuffer demo1 = new StringBuffer(“Hello”) ;\n// The above object stored in heap and its value can be changed .\n\ndemo1=new StringBuffer(“Bye”);\n// Above statement is right as it modifies the value which is allowed in the StringBuffer\n StringBuilder demo2= new StringBuilder(“Hello”);\n// The above object too is stored in the heap and its value can be modified\n\ndemo2=new StringBuilder(“Bye”);\n// Above statement is right as it modifies the value which is allowed in the StringBuilder\n"
},
{
"answer_id": 41975323,
"author": "Avinash",
"author_id": 2737885,
"author_profile": "https://Stackoverflow.com/users/2737885",
"pm_score": 2,
"selected": false,
"text": "int one = 1;\nString color = \"red\";\nStringBuilder sb = new StringBuilder();\nsb.append(\"One=\").append(one).append(\", Color=\").append(color).append('\\n');\nSystem.out.print(sb);\n// Prints \"One=1, Colour=red\" followed by an ASCII newline.\n StringBuffer sBuffer = new StringBuffer(\"test\");\nsBuffer.append(\" String Buffer\");\nSystem.out.println(sBuffer); \n"
},
{
"answer_id": 51999952,
"author": "Ganesa Vijayakumar",
"author_id": 1491414,
"author_profile": "https://Stackoverflow.com/users/1491414",
"pm_score": 1,
"selected": false,
"text": "private static void performanceTestStringVsStringbuffereVsStringBuilder() {\n// String vs StringBiffer vs StringBuilder performance Test\n\nint loop = 100000;\nlong start = 0;\n\n// String\nString str = null;\nstart = System.currentTimeMillis();\nfor (int i = 1; i <= loop; i++) {\n str += i + \"test\";\n}\nSystem.out.println(\"String - \" + (System.currentTimeMillis() - start) + \" ms\");\n\n// String buffer\nStringBuffer sbuffer = new StringBuffer();\nstart = System.currentTimeMillis();\nfor (int i = 1; i <= loop; i++) {\n sbuffer.append(i).append(\"test\");\n}\nSystem.out.println(\"String Buffer - \" + (System.currentTimeMillis() - start) + \" ms\");\n\n// String builder\nstart = System.currentTimeMillis();\nStringBuilder sbuilder = new StringBuilder();\nfor (int i = 1; i <= loop; i++) {\n sbuffer.append(i).append(\"test\");\n}\nSystem.out.println(\"String Builder - \" + (System.currentTimeMillis() - start) + \" ms\");\n\n }\n String - 37489 ms\nString Buffer - 5 ms\nString Builder - 4 ms\n String - 389 ms\nString Buffer - 1 ms\nString Builder - 1 ms\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44848/"
] |
355,098 | <p>I have noticed in phpMyAdmin you can click 'optimise' on tables, and it runs:</p>
<pre><code>OPTIMIZE TABLE table_name
</code></pre>
<p>What does this actually do?</p>
<p>Should I have some cron job running daily that runs OPTIMIZE TABLE on my tables?</p>
<p>Thank you</p>
| [
{
"answer_id": 355108,
"author": "Stefan Mai",
"author_id": 13257,
"author_profile": "https://Stackoverflow.com/users/13257",
"pm_score": 4,
"selected": true,
"text": "OPTIMIZE TABLE table_name[,table_name]\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355098",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31671/"
] |
355,099 | <p>I have been able to copy the raw data from an otherwise inaccessible USB drive into a monolithic file of about 250MB. Somewhere in that blob of bytes are about 40 Word documents. </p>
<ol>
<li><p>Where do I find documentation about the internal structure of Word documents such that I can parse the byte-stream, recognise where a Word doc starts and finishes and extract a copy?</p></li>
<li><p>Are there any libraries in any programming language specific to this task?</p></li>
<li><p>Can anyone suggest an already existing software solution to this issue?</p></li>
</ol>
| [
{
"answer_id": 355121,
"author": "Stefan Mai",
"author_id": 13257,
"author_profile": "https://Stackoverflow.com/users/13257",
"pm_score": 4,
"selected": true,
"text": "D0 CF 11 E0 A1 B1 1A E1\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355099",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/426/"
] |
355,141 | <p>I am creating a mock database for import export tests (of the algorithm reading and writing complex data structures to our database, not just to test IO operations), and am trying to decide whether to use a DataSet to store the mock tables (by table name) in the faux-database, or Dictionary()</p>
<p>In terms of retrieving a datatable by name, would I expect better performance from, dataset.Tables["TableName"] or dictionary<"TableName"> (from Dictionary()?</p>
| [
{
"answer_id": 355493,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 4,
"selected": true,
"text": "Dictionary<,> Dictionary<,> Dictionary<T> GetHashCode() string int.GetHashCode() Dictionary<,> List<> Dictionary<,> Lookup<,>"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355141",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5302/"
] |
355,151 | <p>What kind of practical issues are there concerning sending tons of e-mail from a server? Will the likelihood of that e-mail being received be just the same as if it had been sent from g-mail or a personal e-mail account if I for example just blindly call the mail() function in PHP tens of thousands of times a day? </p>
<p><em>(note: you are not helping a spammer here, this relates to a notify feature I'm thinking about for a future link sharing site)</em></p>
| [
{
"answer_id": 355235,
"author": "saschabeaumont",
"author_id": 592,
"author_profile": "https://Stackoverflow.com/users/592",
"pm_score": 1,
"selected": false,
"text": "mail() $headers .= \"X-Mailer: PHP/\".phpversion();\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8005/"
] |
355,165 | <p>In my knowledge, the RESTful WCF still has ".svc" in its URL.</p>
<p>For example, if the service interface is like</p>
<pre><code>[OperationContract]
[WebGet(UriTemplate = "/Value/{value}")]
string GetDataStr(string value);
</code></pre>
<p>The access URI is like "<a href="http://machinename/Service.svc/Value/2" rel="noreferrer">http://machinename/Service.svc/Value/2</a>". In my understanding, part of REST advantage is that it can hide the implementation details. A RESTful URI like "<a href="http://machinename/Service/value/2" rel="noreferrer">http://machinename/Service/value/2</a>" can be implemented by any RESTful framework, but a "<a href="http://machinename/Service.svc/value/2" rel="noreferrer">http://machinename/Service.svc/value/2</a>" exposes its implementation is WCF.</p>
<p>How can I remove this ".svc" host in the access URI?</p>
| [
{
"answer_id": 355471,
"author": "Darin Dimitrov",
"author_id": 29407,
"author_profile": "https://Stackoverflow.com/users/29407",
"pm_score": 6,
"selected": true,
"text": "public class RestModule : IHttpModule\n{\n public void Dispose() { }\n\n public void Init(HttpApplication app)\n {\n app.BeginRequest += delegate\n {\n HttpContext ctx = HttpContext.Current;\n string path = ctx.Request.AppRelativeCurrentExecutionFilePath;\n\n int i = path.IndexOf('/', 2);\n if (i > 0)\n {\n string svc = path.Substring(0, i) + \".svc\";\n string rest = path.Substring(i, path.Length - i);\n ctx.RewritePath(svc, rest, ctx.Request.QueryString.ToString(), false);\n }\n };\n }\n}\n"
},
{
"answer_id": 2069330,
"author": "Cheeso",
"author_id": 48082,
"author_profile": "https://Stackoverflow.com/users/48082",
"pm_score": 2,
"selected": false,
"text": "# Iirf.ini\n#\n\nRewriteEngine ON\nRewriteLog c:\\inetpub\\iirfLogs\\iirf-v2.0.services\nRewriteLogLevel 3\nStatusInquiry ON RemoteOk\nCondSubstringBackrefFlag *\nMaxMatchCount 10\n\n# remove the .svc tag from external URLs\nRewriteRule ^/services/([^/]+)(?<!\\.svc)/(.*)$ /services/$1.svc/$2 [L]\n"
},
{
"answer_id": 2069356,
"author": "Jason Kresowaty",
"author_id": 14280,
"author_profile": "https://Stackoverflow.com/users/14280",
"pm_score": 2,
"selected": false,
"text": "VirtualPathProvider"
},
{
"answer_id": 10842596,
"author": "Thiago Silva",
"author_id": 5101,
"author_profile": "https://Stackoverflow.com/users/5101",
"pm_score": 6,
"selected": false,
"text": "RouteTable.Routes.Add(new ServiceRoute(\"mysvc\", new WebServiceHostFactory(), typeof(MyServiceClass)));\n http://servername/mysvc/value/2\n"
},
{
"answer_id": 30275267,
"author": "Kenneth",
"author_id": 4906708,
"author_profile": "https://Stackoverflow.com/users/4906708",
"pm_score": 1,
"selected": false,
"text": "private void Application_BeginRequest(object sender, EventArgs e)\n{\n Context.RewritePath(System.Text.RegularExpressions.Regex.Replace(\n Request.Path, \"/rest/(.*)/\", \"/$1.svc/\"));\n}\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355165",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26349/"
] |
355,167 | <p>What is the use of anonymous classes in Java? Can we say that usage of anonymous class is one of the advantages of Java?</p>
| [
{
"answer_id": 355177,
"author": "coobird",
"author_id": 17172,
"author_profile": "https://Stackoverflow.com/users/17172",
"pm_score": 10,
"selected": true,
"text": "button.addActionListener(new ActionListener() {\n @Override\n public void actionPerformed(ActionEvent e) {\n // do something\n }\n});\n ActionListener"
},
{
"answer_id": 355180,
"author": "madlep",
"author_id": 14160,
"author_profile": "https://Stackoverflow.com/users/14160",
"pm_score": 4,
"selected": false,
"text": "myButton.addActionListener(new ActionListener(){\n public void actionPerformed(ActionEvent e) {\n // do stuff here...\n }\n});\n"
},
{
"answer_id": 355382,
"author": "Apocalisp",
"author_id": 3434,
"author_profile": "https://Stackoverflow.com/users/3434",
"pm_score": 6,
"selected": false,
"text": "public interface F<A, B> {\n B f(A a);\n}\n public static int larger(final List<Integer> ns, final int i) {\n for (Integer n : ns)\n if (n > i)\n return n;\n return i;\n}\n public static int smaller(final List<Integer> ns, final int i) {\n for (Integer n : ns)\n if (n < i)\n return n;\n return i;\n}\n public static <T> T firstMatch(final List<T> ts, final F<T, Boolean> f, T z) {\n for (T t : ts)\n if (f.f(t))\n return t;\n return z;\n}\n F<Integer, Boolean> greaterThanTen = new F<Integer, Boolean> {\n Boolean f(final Integer n) {\n return n > 10;\n }\n};\nint moreThanMyFingersCanCount = firstMatch(xs, greaterThanTen, x);\n"
},
{
"answer_id": 360872,
"author": "Chase Seibert",
"author_id": 7679,
"author_profile": "https://Stackoverflow.com/users/7679",
"pm_score": 6,
"selected": false,
"text": "Map map = new HashMap() {{\n put(\"key\", \"value\");\n}};\n Map map = new HashMap();\nmap.put(\"key\", \"value\");\n"
},
{
"answer_id": 10724855,
"author": "Kumar Vivek Mitra",
"author_id": 1293744,
"author_profile": "https://Stackoverflow.com/users/1293744",
"pm_score": 3,
"selected": false,
"text": "button.addActionListener(new ActionListener(){\n\n public void actionPerformed(ActionEvent arg0) {\n // TODO Auto-generated method stub\n\n }\n});\n"
},
{
"answer_id": 14068232,
"author": "Hazhir",
"author_id": 546130,
"author_profile": "https://Stackoverflow.com/users/546130",
"pm_score": 1,
"selected": false,
"text": "super.finalize() public class HeavyClass{\n private final Object finalizerGuardian = new Object() {\n @Override\n protected void finalize() throws Throwable{\n //Finalize outer HeavyClass object\n }\n };\n}\n super.finalize() HeavyClass"
},
{
"answer_id": 15540478,
"author": "raja",
"author_id": 1199342,
"author_profile": "https://Stackoverflow.com/users/1199342",
"pm_score": 3,
"selected": false,
"text": "new Thread() {\n public void run() {\n try {\n Thread.sleep(300);\n } catch (InterruptedException e) {\n System.out.println(\"Exception message: \" + e.getMessage());\n System.out.println(\"Exception cause: \" + e.getCause());\n }\n }\n }.start();\n"
},
{
"answer_id": 19287625,
"author": "user2837260",
"author_id": 2837260,
"author_profile": "https://Stackoverflow.com/users/2837260",
"pm_score": 2,
"selected": false,
"text": "new Thread(new Runnable() {\n public void run() {\n // you code\n }\n}).start();\n"
},
{
"answer_id": 22286426,
"author": "Sandeep Kumar",
"author_id": 2786474,
"author_profile": "https://Stackoverflow.com/users/2786474",
"pm_score": 6,
"selected": false,
"text": "class A{\n public void methodA() {\n System.out.println(\"methodA\");\n }\n}\n\nclass B{\n A a = new A() {\n public void methodA() {\n System.out.println(\"anonymous methodA\");\n }\n };\n}\n interface InterfaceA{\n public void methodA();\n}\n\nclass B{\n InterfaceA a = new InterfaceA() {\n public void methodA() {\n System.out.println(\"anonymous methodA implementer\");\n }\n };\n}\n interface Foo {\n void methodFoo();\n}\n\nclass B{\n void do(Foo f) { }\n}\n\nclass A{\n void methodA() {\n B b = new B();\n b.do(new Foo() {\n public void methodFoo() {\n System.out.println(\"methodFoo\");\n } \n });\n } \n} \n"
},
{
"answer_id": 31207900,
"author": "Saurabh",
"author_id": 2078672,
"author_profile": "https://Stackoverflow.com/users/2078672",
"pm_score": 1,
"selected": false,
"text": "TreeSet treeSetObj = new TreeSet(new Comparator()\n{\n public int compare(String i1,String i2)\n {\n return i2.compareTo(i1);\n }\n});\n"
},
{
"answer_id": 39005385,
"author": "vsminkov",
"author_id": 3239417,
"author_profile": "https://Stackoverflow.com/users/3239417",
"pm_score": 1,
"selected": false,
"text": "public abstract class TypeHolder<T> {\n private final Type type;\n\n public TypeReference() {\n // you may do do additional sanity checks here\n final Type superClass = getClass().getGenericSuperclass();\n this.type = ((ParameterizedType) superClass).getActualTypeArguments()[0];\n }\n\n public final Type getType() {\n return this.type;\n }\n}\n TypeHolder<List<String>, Map<Ineger, Long>> holder = \n new TypeHolder<List<String>, Map<Ineger, Long>>() {};\n holder new T()"
},
{
"answer_id": 40650596,
"author": "akhil_mittal",
"author_id": 1216775,
"author_profile": "https://Stackoverflow.com/users/1216775",
"pm_score": 2,
"selected": false,
"text": "Person public class Person {\n\n public enum Sex {\n MALE, FEMALE\n }\n\n String name;\n LocalDate birthday;\n Sex gender;\n String emailAddress;\n\n public int getAge() {\n // ...\n }\n\n public void printPerson() {\n // ...\n }\n}\n public static void printPersons(\n List<Person> roster, CheckPerson tester) {\n for (Person p : roster) {\n if (tester.test(p)) {\n p.printPerson();\n }\n }\n}\n CheckPerson interface CheckPerson {\n boolean test(Person p);\n}\n printPersons(\n roster,\n new CheckPerson() {\n public boolean test(Person p) {\n return p.getGender() == Person.Sex.MALE\n && p.getAge() >= 18\n && p.getAge() <= 25;\n }\n }\n);\n CheckPerson printPersons(\n roster,\n (Person p) -> p.getGender() == Person.Sex.MALE\n && p.getAge() >= 18\n && p.getAge() <= 25\n );\n Predicate CheckPerson"
},
{
"answer_id": 45676637,
"author": "Shivendra Pandey",
"author_id": 4729076,
"author_profile": "https://Stackoverflow.com/users/4729076",
"pm_score": 0,
"selected": false,
"text": "import java.util.Scanner;\nabstract class AnonymousInner {\n abstract void sum();\n}\n\nclass AnonymousInnerMain {\n public static void main(String []k){\n Scanner sn = new Scanner(System.in);\n System.out.println(\"Enter two vlaues\");\n int a= Integer.parseInt(sn.nextLine());\n int b= Integer.parseInt(sn.nextLine()); \n AnonymousInner ac = new AnonymousInner(){\n void sum(){\n int c= a+b;\n System.out.println(\"Sum of two number is: \"+c);\n }\n };\n ac.sum();\n }\n\n}\n"
},
{
"answer_id": 49406296,
"author": "Avishka Ariyaratne",
"author_id": 7773519,
"author_profile": "https://Stackoverflow.com/users/7773519",
"pm_score": 1,
"selected": false,
"text": "new { } ThreadClass task = new ThreadClass();\nThread runner = new Thread(task);\nrunner.start();\n ThreadClass Runnable ThreadClass run() Runnable ThreadClass Thread runner = new Thread(new Runnable() {\n public void run() {\n //Thread does it's work here\n }\n});\nrunner.start();\n task Thread() Runnable run() run()"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40933/"
] |
355,168 | <p>I am programming an iPhone app, and I need to force it to exit due to certain user actions. After cleaning up memory the app allocated, what's the appropriate method to call to terminate the application?</p>
| [
{
"answer_id": 355173,
"author": "Brett",
"author_id": 37848,
"author_profile": "https://Stackoverflow.com/users/37848",
"pm_score": 9,
"selected": true,
"text": "exit(0) [[NSThread mainThread] exit]"
},
{
"answer_id": 358241,
"author": "Rob",
"author_id": 386102,
"author_profile": "https://Stackoverflow.com/users/386102",
"pm_score": 2,
"selected": false,
"text": "if ([[UIApplication sharedApplication] respondsToSelector:@selector(terminate)]) {\n [[UIApplication sharedApplication] performSelector:@selector(terminate)];\n} else {\n kill(getpid(), SIGINT); \n}\n"
},
{
"answer_id": 874997,
"author": "Romain Champourlier",
"author_id": 108427,
"author_profile": "https://Stackoverflow.com/users/108427",
"pm_score": 4,
"selected": false,
"text": "[UIApplication sharedApplication] - (void)applicationWillTerminate:(UIApplication *)application exit(0); - (void)applicationWillTerminate:(UIApplication *)application - (void)applicationWillTerminate:(UIApplication *)application exit(0);"
},
{
"answer_id": 1225316,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "UIAlertView *anAlert = [[UIAlertView alloc] initWithTitle:@\"Hit Home Button to Exit\" message:@\"Tell em why they're quiting\" delegate:self cancelButtonTitle:nil otherButtonTitles:nil];\n[anAlert show];\n"
},
{
"answer_id": 1681100,
"author": "shiva",
"author_id": 203517,
"author_profile": "https://Stackoverflow.com/users/203517",
"pm_score": 1,
"selected": false,
"text": "[[UIApplication sharedApplication] terminateWithSuccess];\n - (void)applicationWillTerminateUIApplication *)application delegate.\n @interface UIApplication(MyExtras)\n - (void)terminateWithSuccess;\n@end \n"
},
{
"answer_id": 2980740,
"author": "Wagh",
"author_id": 228202,
"author_profile": "https://Stackoverflow.com/users/228202",
"pm_score": 5,
"selected": false,
"text": "exit exit -applicationWillTerminate: UIApplicationDelegate abort assert"
},
{
"answer_id": 3466790,
"author": "L'g",
"author_id": 368571,
"author_profile": "https://Stackoverflow.com/users/368571",
"pm_score": 3,
"selected": false,
"text": "- (void)applicationWillResignActive:(UIApplication *)application {\n exit(0);\n"
},
{
"answer_id": 6607662,
"author": "Aman Agarwal",
"author_id": 567001,
"author_profile": "https://Stackoverflow.com/users/567001",
"pm_score": 4,
"selected": false,
"text": "UIApplicationExitsOnSuspend application-info.plist true"
},
{
"answer_id": 17802404,
"author": "MaxEcho",
"author_id": 2459296,
"author_profile": "https://Stackoverflow.com/users/2459296",
"pm_score": 6,
"selected": false,
"text": "-(IBAction)doExit\n{\n //show confirmation message to user\n UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@\"Confirmation\"\n message:@\"Do you want to exit?\"\n delegate:self\n cancelButtonTitle:@\"Cancel\"\n otherButtonTitles:@\"OK\", nil];\n [alert show];\n}\n\n-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex\n{\n if (buttonIndex != 0) // 0 == the cancel button\n {\n //home button press programmatically\n UIApplication *app = [UIApplication sharedApplication];\n [app performSelector:@selector(suspend)];\n\n //wait 2 seconds while app is going background\n [NSThread sleepForTimeInterval:2.0];\n\n //exit app when app is in background\n exit(0);\n }\n}\n"
},
{
"answer_id": 18849231,
"author": "Prabhu Natarajan",
"author_id": 2469722,
"author_profile": "https://Stackoverflow.com/users/2469722",
"pm_score": 2,
"selected": false,
"text": "- (IBAction)logOutButton:(id)sender\n{\n //show confirmation message to user\n CustomAlert* alert = [[CustomAlert alloc] initWithTitle:@\"Confirmation\" message:@\"Do you want to exit?\" delegate:self cancelButtonTitle:@\"Cancel\" otherButtonTitles:@\"OK\", nil];\n alert.style = AlertStyleWhite;\n [alert setFontName:@\"Helvetica\" fontColor:[UIColor blackColor] fontShadowColor:[UIColor clearColor]];\n [alert show];\n}\n- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex\n{\n\n if (buttonIndex != 0) // 0 == the cancel button\n {\n //home button press programmatically\n UIApplication *app = [UIApplication sharedApplication];\n [app performSelector:@selector(suspend)];\n //wait 2 seconds while app is going background\n [NSThread sleepForTimeInterval:2.0];\n //exit app when app is in background\n NSLog(@\"exit(0)\");\n exit(0);\n }\n}\n"
},
{
"answer_id": 21384019,
"author": "Geri Borbás",
"author_id": 215282,
"author_profile": "https://Stackoverflow.com/users/215282",
"pm_score": 0,
"selected": false,
"text": "void crash()\n{ [[NSMutableArray new] addObject:NSStringFromClass(nil)]; }\n"
},
{
"answer_id": 33086414,
"author": "frankodwyer",
"author_id": 42404,
"author_profile": "https://Stackoverflow.com/users/42404",
"pm_score": 0,
"selected": false,
"text": "- (void)applicationDidEnterBackground:(UIApplication *)application\n{\n if (/* logged out */) {\n exit(0);\n } else {\n // normal handling.\n }\n}\n [[UIApplication sharedApplication] backgroundTimeRemaining] - (void)applicationDidEnterBackground:(UIApplication *)application\n{\n if (/* logged out */) {\n // stop requesting location updates if not already done so\n // tidy up as app will soon be terminated (run a background task using beginBackgroundTaskWithExpirationHandler if needed).\n } else {\n // normal handling.\n }\n}\n exit(0)"
},
{
"answer_id": 36915997,
"author": "technerd",
"author_id": 3045336,
"author_profile": "https://Stackoverflow.com/users/3045336",
"pm_score": 2,
"selected": false,
"text": "exit(0) abort()"
},
{
"answer_id": 54922740,
"author": "Saranjith",
"author_id": 5215474,
"author_profile": "https://Stackoverflow.com/users/5215474",
"pm_score": 0,
"selected": false,
"text": "Darvin import Darwin\n\nexit(0) // Here you go\n"
},
{
"answer_id": 56646677,
"author": "TheTiger",
"author_id": 1140335,
"author_profile": "https://Stackoverflow.com/users/1140335",
"pm_score": 3,
"selected": false,
"text": "exit(0) func askForQuit(_ completion:@escaping (_ canQuit: Bool) -> Void) {\n let alert = UIAlertController(title: \"Confirmation!\", message: \"Do you want to quit the application\", preferredStyle: .alert)\n alert.addAction(UIAlertAction(title: \"Yes\", style: UIAlertAction.Style.default, handler: { (action) in\n alert.dismiss(animated: true, completion: nil)\n completion(true)\n }))\n alert.addAction(UIAlertAction(title: \"No\", style: UIAlertAction.Style.cancel, handler: { (action) in\n alert.dismiss(animated: true, completion: nil)\n completion(false)\n }))\n self.present(alert, animated: true, completion: nil)\n}\n\n/// Will quit the application with animation\nfunc quit() {\n UIApplication.shared.perform(#selector(NSXPCConnection.suspend))\n /// Sleep for a while to let the app goes in background\n sleep(2)\n exit(0)\n}\n self.askForQuit { (canQuit) in\n if canQuit {\n self.quit()\n }\n}\n"
},
{
"answer_id": 58979656,
"author": "Klaas",
"author_id": 292145,
"author_profile": "https://Stackoverflow.com/users/292145",
"pm_score": 0,
"selected": false,
"text": "for session in UIApplication.shared.openSessions {\n UIApplication.shared.requestSceneSessionDestruction(session, options: nil, errorHandler: nil)\n}\n applicationWillTerminate(_ application: UIApplication)"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355168",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21293/"
] |
355,171 | <p>I would like to know how I can refer to a list item object if I had for example the following html list </p>
<pre><code><div id="subdiv_2">
<div id="subdiv_3">
<ul>
<li><a href="">Item1</a></li>
<li><a href="">Item2</a></li>
<li><a href="">Item3</a></li>
</ul>
</div>
</div>
</code></pre>
<p>How is it possible to register an onclick to the Item2 li without it having to have a unique elementId
eg I can do so for subdiv_3 because it has a unique ID and isn't in the list by </p>
<pre><code>document.getElementById('subdiv_3').addEventListener('click', function();, false);
</code></pre>
<p>My goal is ultimately to assign a function to each list object, for the number of list objects with unique parameters based upon the list object number eg: </p>
<pre><code>for(i=0;i<list.length;i++){
"document.getElementById(list.item"+i+").addEventListener(\'click\',function("+i+");,false);";
}
</code></pre>
| [
{
"answer_id": 355188,
"author": "Benry",
"author_id": 28408,
"author_profile": "https://Stackoverflow.com/users/28408",
"pm_score": 3,
"selected": true,
"text": "subdiv_3 <li> div = document.getElementById('subdiv_3');\nels = div.getElementsByTagName('li');\n\nfor (var i=0, len=els.length; i<len; i++) {\n alert(i); // add your functions here \n}\n"
},
{
"answer_id": 355245,
"author": "Supernovah",
"author_id": 36076,
"author_profile": "https://Stackoverflow.com/users/36076",
"pm_score": 0,
"selected": false,
"text": "function attachToList(){\ndiv = document.getElementById('menu2');\nels = div.getElementsByTagName('li');\nfor (var i=0, len=els.length; i<len; i++) {\nsetTimeout('els['+i+'].style.backgroundColor=\\\"#FFFFCC\\\";',(250*i));\n}\n}\n"
},
{
"answer_id": 355375,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 1,
"selected": false,
"text": "setTimeot() function attachToList() {\n var div = document.getElementById('menu2');\n var els = div.getElementsByTagName('li');\n // create a closure returning an anonymous inner function\n var fn = function(li) {\n return function() {\n li.style.backgroundColor = \"#FFFFCC\";\n };\n };\n for (var i=0, len=els.length; i<len; i++) {\n // create function instance suitable for current iteration\n var changeLi = fn(els[i]);\n // pass function reference to setTimeout()\n setTimeout(changeLi, 250*i);\n }\n}\n setTimeout() setTimeout()"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36076/"
] |
355,172 | <p>I'm learning about DDD, and have come across the statement that "value-objects" should be immutable. I understand that this means that the objects state should not change after it has been created. This is kind of a new way of thinking for me, but it makes sense in many cases.</p>
<p>Ok, so I start creating immutable value-objects. </p>
<ul>
<li>I make sure they take the entire state as parameters to the constructor, </li>
<li>I don't add property setters, </li>
<li>and make sure no methods are allowed to modify the content (only return new instances).</li>
</ul>
<p>But now I want to create this value object that will contain 8 different numeric values. If I create a constructor having 8 numeric parameters I feel that it will not be very easy to use, or rather - it will be easy to make a mistake when passing in the numbers. This can't be good design.</p>
<p><em>So the questions is:</em> Are there any other ways of making my immutable object better.., any magic that can be done in C# to overcome a long parameter list in the constructor? I'm very interested in hearing your ideas..</p>
<p><strong>UPDATE:</strong> Before anyone mentions it, one idea has been discussed here:
<a href="https://stackoverflow.com/questions/263585/immutable-object-pattern-in-c-what-do-you-think">Immutable object pattern in C# - what do you think?</a></p>
<p>Would be interested in hearing other suggestions or comments though.</p>
| [
{
"answer_id": 355186,
"author": "Andrew Kennan",
"author_id": 22506,
"author_profile": "https://Stackoverflow.com/users/22506",
"pm_score": 6,
"selected": true,
"text": "public class Entity\n{\n public class Builder\n {\n private int _field1;\n private int _field2;\n private int _field3;\n\n public Builder WithField1(int value) { _field1 = value; return this; }\n public Builder WithField2(int value) { _field2 = value; return this; }\n public Builder WithField3(int value) { _field3 = value; return this; }\n\n public Entity Build() { return new Entity(_field1, _field2, _field3); }\n }\n\n private int _field1;\n private int _field2;\n private int _field3;\n\n private Entity(int field1, int field2, int field3) \n {\n // Set the fields.\n }\n\n public int Field1 { get { return _field1; } }\n public int Field2 { get { return _field2; } }\n public int Field3 { get { return _field3; } }\n\n public static Builder Build() { return new Builder(); }\n}\n Entity myEntity = Entity.Build()\n .WithField1(123)\n .WithField2(456)\n .WithField3(789)\n .Build()\n"
},
{
"answer_id": 355209,
"author": "Bevan",
"author_id": 30280,
"author_profile": "https://Stackoverflow.com/users/30280",
"pm_score": 2,
"selected": false,
"text": "var factory = new ObjectFactory();\nfactory.Fimble = 32;\nfactory.Flummix = \"Nearly\";\nvar mine = factory.CreateInstance();\n var mine = new myImmutableObject();\nmine.Fimble = 32;\nmine.Flummix = \"Nearly\";\nmine.Lock(); // Now it's immutable.\n"
},
{
"answer_id": 355419,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 3,
"selected": false,
"text": " Person p = new Person ( forename: \"Fred\", surname: \"Flintstone\" );\n Person p = new Person { Forename = \"Fred\", Surname = \"Flintstone\" };\n"
},
{
"answer_id": 24431627,
"author": "CountOren",
"author_id": 1457216,
"author_profile": "https://Stackoverflow.com/users/1457216",
"pm_score": 1,
"selected": false,
"text": "public class ImmutableObject<T>\n{\n private readonly Func<IEnumerable<KeyValuePair<string, object>>> initContainer;\n\n protected ImmutableObject() {}\n\n protected ImmutableObject(IEnumerable<KeyValuePair<string,object>> properties)\n {\n var fields = GetType().GetFields().Where(f=> f.IsPublic);\n\n var fieldsAndValues =\n from fieldInfo in fields\n join keyValuePair in properties on fieldInfo.Name.ToLower() equals keyValuePair.Key.ToLower()\n select new {fieldInfo, keyValuePair.Value};\n\n fieldsAndValues.ToList().ForEach(fv=> fv.fieldInfo.SetValue(this,fv.Value));\n\n }\n\n protected ImmutableObject(Func<IEnumerable<KeyValuePair<string,object>>> init)\n {\n initContainer = init;\n }\n\n protected T setProperty(string propertyName, object propertyValue, bool lazy = true)\n {\n\n Func<IEnumerable<KeyValuePair<string, object>>> mergeFunc = delegate\n {\n var propertyDict = initContainer == null ? ObjectToDictonary () : initContainer();\n return propertyDict.Select(p => p.Key == propertyName? new KeyValuePair<string, object>(propertyName, propertyValue) : p).ToList();\n };\n\n var containerConstructor = typeof(T).GetConstructors()\n .First( ce => ce.GetParameters().Count() == 1 && ce.GetParameters()[0].ParameterType.Name == \"Func`1\");\n\n return (T) (lazy ? containerConstructor.Invoke(new[] {mergeFunc}) : DictonaryToObject<T>(mergeFunc()));\n }\n\n private IEnumerable<KeyValuePair<string,object>> ObjectToDictonary()\n {\n var fields = GetType().GetFields().Where(f=> f.IsPublic);\n return fields.Select(f=> new KeyValuePair<string,object>(f.Name, f.GetValue(this))).ToList();\n }\n\n private static object DictonaryToObject<T>(IEnumerable<KeyValuePair<string,object>> objectProperties)\n {\n var mainConstructor = typeof (T).GetConstructors()\n .First(c => c.GetParameters().Count()== 1 && c.GetParameters().Any(p => p.ParameterType.Name == \"IEnumerable`1\") );\n return mainConstructor.Invoke(new[]{objectProperties});\n }\n\n public T ToObject()\n {\n var properties = initContainer == null ? ObjectToDictonary() : initContainer();\n return (T) DictonaryToObject<T>(properties);\n }\n}\n public class State:ImmutableObject<State>\n{\n public State(){}\n public State(IEnumerable<KeyValuePair<string,object>> properties):base(properties) {}\n public State(Func<IEnumerable<KeyValuePair<string, object>>> func):base(func) {}\n\n public readonly int SomeInt;\n public State someInt(int someInt)\n {\n return setProperty(\"SomeInt\", someInt);\n }\n\n public readonly string SomeString;\n public State someString(string someString)\n {\n return setProperty(\"SomeString\", someString);\n }\n}\n //creating new empty object\nvar state = new State();\n\n// Set fields, will return an empty object with the \"chained methods\".\nvar s2 = state.someInt(3).someString(\"a string\");\n// Resolves all the \"chained methods\" and initialize the object setting all the fields by reflection.\nvar s3 = s2.ToObject();\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355172",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22621/"
] |
355,185 | <p>I am trying to access XMLHTTPRequest.open Method I have even included netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");</p>
<p>but still its not working. </p>
<p>I am using javascript and HTML to access the WebService.</p>
<p>Any Help would be really great</p>
<p>Code</p>
<p><pre><code></p>
<p><html>
<Head>
<Title>Calling A WebService from HTML </Title>
</Head></p>
<p><Body onload='GetDataFrmWS()'>
<form name="Form1" id="Form1" runat="server" method="post">
<div id="DisplayData" > </div>
<div id="Menu2"></div></p>
<p></form></p>
<p><script language='javascript'></p>
<p>var objHttp;
var objXmlDoc;</p>
<p>function GetDataFrmWS()
{
alert('I M Here');
var func = getDataFromWS();</p>
<p>}</p>
<p>function getDataFromWS()
{</p>
<p>if(window.ActiveXObject)
{
try
{
objHttp = new ActiveXObject('Msxml2.XMLHTTP');</p>
<pre><code> }
catch (ex)
{
objHttp = new ActiveXObject('Microsoft.XMLHTTP');
}
</code></pre>
<p>}
else if (window.XMLHttpRequest)
{
objHttp = new window.XMLHttpRequest();
netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
}</p>
<p>strEnvelope = '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">' +
'<soap:Body>' +
' <HelloWorld xmlns="http://tempuri.org/">' +
' <Dummy xsi:type="xsd:string">Hello</Dummy>'+
' </HelloWorld>'+
'</soap:Body>' +
'</soap:Envelope>' ;</p>
<p>var szUrl;
szUrl = '<a href="http://kamadhenu/Quoteme/GetCategories.asmx?op=HelloWorld" rel="nofollow noreferrer">http://kamadhenu/Quoteme/GetCategories.asmx?op=HelloWorld</a>';
objHttp.onreadystatechange = HandleResponse;</p>
<p>objHttp.open('POST', szUrl, true);
objHttp.setRequestHeader('Content-Type', 'text/xml');
objHttp.setRequestHeader('SOAPAction','<a href="http://tempuri.org/HelloWorld" rel="nofollow noreferrer">http://tempuri.org/HelloWorld</a>');
objHttp.send(strEnvelope);</p>
<p>}</p>
<p>function HandleResponse()
{<br>
if (objHttp.readyState == 4)
{</p>
<p>if (window.ActiveXObject)
{
objXmlDoc = new ActiveXObject("Microsoft.XMLDOM");
objXmlDoc.async="false";
objXmlDoc.loadXML(objHttp.responseText);
var nodeSelect = objXmlDoc.getElementsByTagName("Menu1").item(0);
var Menu2=objXmlDoc.getElementsByTagName("Menu2").item(0);
document.getElementById('DisplayData').innerHTML=nodeSelect.text;<br>
document.getElementById('Menu2').innerHTML=Menu2.text;
}
else
{
var Text=objHttp.responseText;
var parser=new DOMParser();
objXmlDoc = parser.parseFromString(Text,'text/xml');
var Value=objXmlDoc.documentElement.childNodes[0].childNodes[0].childNodes[0].childNodes[0].childNodes[0].childNodes[0].childNodes[0].nodeValue;
var Menu2=objXmlDoc.documentElement.childNodes[0].childNodes[0].childNodes[0].childNodes[0].childNodes[0].childNodes[1].childNodes[0].nodeValue;
var Menu3=objXmlDoc.documentElement.childNodes[0].childNodes[0].childNodes[0].childNodes[0].childNodes[0].childNodes[1].childNodes[1].nodeValue;
document.getElementById('DisplayData').innerHTML=Value;<br>
document.getElementById('Menu2').innerHTML=Menu2;
document.getElementById('Menu2').innerHTML+=Menu3;
}
}</p>
<p>} </p>
<p></script>
<input type='Button' Text='Click Me' onclick='GetDataFrmWS()' value="Click Me!"/>
°
</Body>
</HTML></pre></code></p>
| [
{
"answer_id": 355255,
"author": "M.N",
"author_id": 18615,
"author_profile": "https://Stackoverflow.com/users/18615",
"pm_score": 2,
"selected": false,
"text": "/* Function to create an XMLHTTP object for all browsers */\nfunction getXMLHTTPObject(){\n var xmlHttp;\n try{\n // Firefox, Opera 8.0+, Safari\n xmlHttp=new XMLHttpRequest();\n } catch (e){\n // Internet Explorer\n try{\n xmlHttp=new ActiveXObject(\"Msxml2.XMLHTTP\");\n }catch (e){\n try{\n xmlHttp=new ActiveXObject(\"Microsoft.XMLHTTP\");\n }catch (e){\n alert(\"Your browser does not support AJAX!\");\n return false;\n }\n }\n }\n return xmlHttp;\n} \n/* End Function */\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42070/"
] |
355,192 | <p>I am doing some TTF work for MOSA (the correlating body between all the C# operating systems). Me and Colin Burn are currently working on getting some TTF code working (less me these days :) - he made a lot of progress).</p>
<p>In any case, the TTF spec allows for an arbitrary amount of control points between the 'handles' and <strong>gasp</strong> NO handles at all (the TTF has an example of a circle demonstrating it - well done idiots - you saved 10 bytes).</p>
<p>Can anyone give me a pointer on how this could be done? I looked at the Bezier article on Wikipedia but it wasn't really that much help - they show it happening, but don't give any math. Something 'program' ready would help (my Calculus isn't what it should be) - some pseudocode or something.</p>
<p>Thanks guys.</p>
| [
{
"answer_id": 355246,
"author": "Spoike",
"author_id": 3713,
"author_profile": "https://Stackoverflow.com/users/3713",
"pm_score": 2,
"selected": false,
"text": "// Quadratic spline, with three given points\n// B(t) = (1-t)^2P(0) + 2*tP(1) + t^2P(2)\n// where T is a real number in the interval [0, 1]\n\npublic void DrawQuadSpline(Point p0, Point p1, Point p2, int steps) \n{\n Point next = p0;\n Point previous = p0;\n double tStep = 1 / ((float) steps);\n double t = 0;\n for (int i = 0; i < steps; i++) \n {\n float x = CalculateQuadSpline(P0.x, P1.x, P2.x, t);\n float y = CalculateQuadSpline(P0.y, P1.y, P2.y, t);\n Point next = new Point(x, y);\n drawLine(previous, next);\n previous = next;\n t = t + tStep;\n }\n} \n\nprivate void CalculateQuadSpline(float z0, float z1, float z2, float t) \n{\n return (1.0-t)*(1.0-t)*z0 + 2.0*t*z1 + t*t*z2;\n}\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355192",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24064/"
] |
355,196 | <p>IIS does not work when I start applications like Skype since it also uses port 80.</p>
<p>Which port can I use to run IIS other than 80? (8080 does not work)</p>
| [
{
"answer_id": 355221,
"author": "netic",
"author_id": 44534,
"author_profile": "https://Stackoverflow.com/users/44534",
"pm_score": 3,
"selected": false,
"text": "netstat"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355196",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38997/"
] |
355,202 | <p>I want to connect and execute one (or sometimes several) SQL statements, and NOT have those replicated to the slaves.</p>
<p>I have no replicate-do or replicate-ignore configs, so I can't <code>use</code> some non-replicated database to send the commands from. And I know about:</p>
<pre><code>set global sql_slave_skip_counter = 1
</code></pre>
<p>But that's on the slave. I'd like to be able to run a similar command on the master and have the following N commands not sent out to the slaves (which I guess means not logged in the binlogs, either).</p>
| [
{
"answer_id": 355268,
"author": "derobert",
"author_id": 27727,
"author_profile": "https://Stackoverflow.com/users/27727",
"pm_score": 5,
"selected": true,
"text": "SET sql_log_bin=0 SET sql_log_bin=0;\nUPDATE ... ;\nINSERT ... ;\nDELETE ... ;\nSET sql_log_bin=1 ;\n"
},
{
"answer_id": 8055852,
"author": "sambanxxx",
"author_id": 1036300,
"author_profile": "https://Stackoverflow.com/users/1036300",
"pm_score": 2,
"selected": false,
"text": "SET sql_log_bin=0;"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355202",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11044/"
] |
355,212 | <p>After returning to an old Rails project I found none of the destroy/delete links worked and clicking cancel on the confirmation popup would still submit the link.</p>
<p>Example of my code is:</p>
<pre><code><%= link_to 'Delete', admin_user_path(@user), :confirm => 'Are you sure?', :method => :delete %>
</code></pre>
| [
{
"answer_id": 16229670,
"author": "Jimmy Dee",
"author_id": 875725,
"author_profile": "https://Stackoverflow.com/users/875725",
"pm_score": 0,
"selected": false,
"text": ";(function($){\n $(function(){\n $('input.destroy').click(function(){\n return confirm($(this).attr('data-confirm'));\n });\n });\n})(jQuery);\n = button_to 'Delete', polygon, :method => :delete, :class => \"destroy\", :confirm => \"Are you sure?\"\n"
},
{
"answer_id": 17505635,
"author": "Sooth",
"author_id": 1072521,
"author_profile": "https://Stackoverflow.com/users/1072521",
"pm_score": 0,
"selected": false,
"text": "$(document).ready(function () {\n $('*[data-confirm]').click(function(){\n return confirm($(this).attr('data-confirm'));\n });\n});\n"
},
{
"answer_id": 29943426,
"author": "Ameen",
"author_id": 1688060,
"author_profile": "https://Stackoverflow.com/users/1688060",
"pm_score": 0,
"selected": false,
"text": "<%= link_to 'Delete', admin_user_path(@user), 'data-confirm' => 'Are you sure?', :method => :delete %>\n"
},
{
"answer_id": 37938791,
"author": "John",
"author_id": 6492961,
"author_profile": "https://Stackoverflow.com/users/6492961",
"pm_score": 0,
"selected": false,
"text": "<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js\"></script> \n <%= javascript_include_tag \"application\" %> \n //= require jquery\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355212",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31810/"
] |
355,217 | <p>Notice how the default domain for stackoverflow is <a href="http://stackoverflow.com">http://stackoverflow.com</a> and if you try to goto <a href="http://www.stackoverflow.com">http://www.stackoverflow.com</a> it bounces you to <a href="http://stackoverflow.com">http://stackoverflow.com</a> ?</p>
<p>What is the reason for this? Not the tech reason (as in the http code, etc) but why would the site owners want to do this?</p>
<p>I know it's purely aesthetic and I always have host-headers for both www and not, but is there a reason to bounce a user to a single domain, subheaded or not?</p>
<h2>Update 1</h2>
<h2>Not having a subdomain is called a <em>bare domain</em>. Thanks peeps! never knew it had a term :)
Update 2</h2>
<p>Thanks for the answers so far - please note I understand that <a href="http://www.domain.com" rel="nofollow noreferrer">www.domain.com</a> can point to domain.com. This is not a question about if i should offer both or either/or, it's asking why some sites default to a baredomain instead of www subdomains, or vice-versa. Cheers.</p>
<p>Jeff Atwood actually HAS explained why he's gone for bare domains <a href="https://blog.stackoverflow.com/2008/06/dropping-the-www-prefix/">here</a> and <a href="https://blog.codinghorror.com/the-great-dub-dub-dub-debate/" rel="nofollow noreferrer">here</a>. (Nod to <a href="https://stackoverflow.com/users/1918/jonas-pegerfalk">Jonas Pegerfalk</a> for the post :) )</p>
<p>Jeff's post (and others in this thread) also talk about the problems of a bare domain with cookies and static images. Basically, if you have cookies on in a bare domain, then all subdomains are forced also. The solution is to purchase another domain, as posted by the <a href="http://developer.yahoo.com/performance/rules.html#cookie_free" rel="nofollow noreferrer">Yahoo Perf Team here</a>.</p>
| [
{
"answer_id": 355238,
"author": "qyb2zm302",
"author_id": 44862,
"author_profile": "https://Stackoverflow.com/users/44862",
"pm_score": 4,
"selected": false,
"text": "www.example.com example.com www CNAME A RECORD"
},
{
"answer_id": 355265,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 3,
"selected": false,
"text": "www www. www. http:// http:// www."
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355217",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30674/"
] |
355,220 | <p>I have a C project where all code is organized in <code>*.c</code>/<code>*.h</code> file pairs, and I need to define a constant value in one file, which will be however also be used in other files. How should I declare and define this value?</p>
<p>Should it be as <code>static const ...</code> in the <code>*.h</code> file? As <code>extern const ...</code> in the <code>*.h</code> file and defined in the <code>*.c</code> file? In what way does it matter if the value is not a primitive datatype (<code>int</code>, <code>double</code>, etc), but a <code>char *</code> or a <code>struct</code>? (Though in my case it is a <code>double</code>.)</p>
<p>Defining stuff inside <code>*.h</code> files doesn't seem like a good idea generally; one should declare things in the <code>*.h</code> file, but define them in the <code>*.c</code> file. However, the <code>extern const ...</code> approach seems inefficient, as the compiler wouldn't be able to inline the value, it instead having to be accessed via its address all the time.</p>
<p>I guess the essence of this question is: Should one define <code>static const ...</code> values in <code>*.h</code> files in C, in order to use them in more that one place?</p>
| [
{
"answer_id": 355239,
"author": "AlfaZulu",
"author_id": 44060,
"author_profile": "https://Stackoverflow.com/users/44060",
"pm_score": 0,
"selected": false,
"text": "const static static const const const"
},
{
"answer_id": 355277,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 4,
"selected": true,
"text": "#define typedef extern int x int x const int x const int x = 7; x static const int x"
},
{
"answer_id": 355379,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 1,
"selected": false,
"text": "static static static #define extern const"
},
{
"answer_id": 357958,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 2,
"selected": false,
"text": "enum {\n FOO_SIZE = 1234,\n BAR_SIZE = 5678\n};\n\n#define FOO_SIZE 1234\n#define BAR_SIZE 5678\n\nstatic const int FOO_SIZE = 1234;\nstatic const int BAR_SIZE = 5678;\n"
},
{
"answer_id": 358123,
"author": "FryGuy",
"author_id": 28776,
"author_profile": "https://Stackoverflow.com/users/28776",
"pm_score": 0,
"selected": false,
"text": "const int SOME_CONST = 17;\n #define SOME_CONST 17\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355220",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35324/"
] |
355,248 | <p>Is there a way to change several textbox's readonly attribute programatically in .net.</p>
| [
{
"answer_id": 355257,
"author": "Tarik",
"author_id": 44852,
"author_profile": "https://Stackoverflow.com/users/44852",
"pm_score": 0,
"selected": false,
"text": "txt.Attributes[\"ReadOnly\"] = \"true\";\n txt.Attributes.Add(\"ReadOnly\",\"true\");\n"
},
{
"answer_id": 355259,
"author": "fARcRY",
"author_id": 38498,
"author_profile": "https://Stackoverflow.com/users/38498",
"pm_score": 0,
"selected": false,
"text": "foreach(TextBox txt in List<TextBox>)\n{\n txt.ReadOnly = true;\n}\n"
},
{
"answer_id": 355306,
"author": "Matt Hanson",
"author_id": 5473,
"author_profile": "https://Stackoverflow.com/users/5473",
"pm_score": 0,
"selected": false,
"text": "Dim textBoxes() As TextBox = {TextBox1, TextBox2, TextBox3}\nFor Each item As TextBox In textBoxes\n item.ReadOnly = True\nNext\n"
},
{
"answer_id": 355369,
"author": "Neil",
"author_id": 44869,
"author_profile": "https://Stackoverflow.com/users/44869",
"pm_score": 2,
"selected": false,
"text": "string commonTextBoxPrefix = \"txt\";\nforeach (Control c in this.Controls)\n{\n if (c.GetType() == typeof(TextBox) &&\n c.Name.StartsWith(commonTextBoxPrefix))\n {\n ((TextBox)c).ReadOnly = True;\n }\n}\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355248",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
355,258 | <p>Why must class members declared as <code>const</code> be initialized in the constructor initializer list rather than in the constructor body?</p>
<p>What is the difference between the two?</p>
| [
{
"answer_id": 355292,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 3,
"selected": false,
"text": "const class Something \n { \n private: \n const int m_nValue; \n public: \n Something() \n { \n m_nValue = 5; \n } \n };\n const int nValue; // error, const vars must be assigned values immediately \nnValue = 5; \n int nValue = 5; // explicit assignment \ndouble dValue(4.7); // implicit assignment \n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355258",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38038/"
] |
355,267 | <p>I’ve got several Perl modules installed on my hosting machine in <code>~/perl</code>, how do I add them to Perl module path? Setting <code>PERL5LIB</code> or <code>unshift</code>ing the paths to <code>@INC</code> surely works, but the environment variable does not help when running as a CGI script and the <code>@INC</code> way is not very portable. Is there a better way? This has to be a common problem, am I missing something?</p>
| [
{
"answer_id": 355293,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 3,
"selected": false,
"text": "use lib \"/path/\" ; \n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17279/"
] |
355,299 | <pre>
<code>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Calling a Web Service Using XmlHttpRequest</title>
<script type="text/javascript" language="javascript">
var xmlhttp;
var XMLContent='<XML ID="Transaction"><Transaction>'+
'<LoginDetails>'+
'<Email>artur</Email>'+
'<Password>demos2</Password>'+
'</LoginDetails>'+
'<JobDetails>'+
'<JobId>40170978</JobId>'+
'<JobRefNo>prod84</JobRefNo>'+
'<JobTitle>'+
'<![CDATA[ Director of R&D Software product (Multimedia)]]>'+
'</JobTitle>'+
'<JobExpiry>30</JobExpiry>'+
'<JobContactName>'+
'<![CDATA[ Brian Mc Fadden]]>'+
'</JobContactName>'+
'<JobContactEmail>brian.mcfadden@recruiters.ie</JobContactEmail>'+
'<JobShortDesc>'+
'<![CDATA[ Director of R&D Software product concepts Multimedia Web 2.0]]> '+
'</JobShortDesc>'+
'<JobDetDesc><![CDATA[ <P class=MsoNormal style="MARGIN: 0cm 0cm 0pt; mso-margin-top-alt: auto; mso-margin-bottom-alt: auto"><STRONG>Director of R&D Software product concepts to</STRONG> build a the new prototyping team and processes from the ground up, utilizing an agile development model, manage the R&D team develop a strong vision and be able to clearly articulate the direction the group will take in terms of methodologies and tools in technologies such as J2EE, .NET, Flash, AJAX, DHTML, JavaScript, take marketing requirements from the principal investigators and write functional requirement documents, manage budget for R&D development, manage the projects developed by the internal team and vendors. </P> <P class=MsoNormal style="MARGIN: 0cm 0cm 0pt; mso-margin-top-alt: auto; mso-margin-bottom-alt: auto">To get this new role you will have a degree in IT / Software and over 5 years plus doing cutting edge development in R&D/ prototyping and leading cutting edge development teams in a software production / product environment, project management and process management skills (AGILE) and demonstrated experience working on product innovation and releases. You may be working in educational gaming, social networking, Web 2.0 applications, mobile technologies, learning management systems, online courseware or shareware. </P> <P class=MsoNormal style="MARGIN: 0cm 0cm 0pt; mso-margin-top-alt: auto; mso-margin-bottom-alt: auto"> </P> <P class=MsoNormal style="MARGIN: 0cm 0cm 0pt">The package is to €105K + Bonus + VHI + Pension + relocation package where applicable + stock options may be negotiated. There are great career advancement opportunities. To discuss this and other opportunities please send an up-to-date resume to <A href="mailto:brian.mcfadden@recruiters.ie">brian.mcfadden@recruiters.ie</A> or call +353 1 6489113 in confidence. Your details will not be sent to any third party without your consent. </P> <P class=MsoNormal style="MARGIN: 0cm 0cm 0pt"> </P>]]>'+
'</JobDetDesc>'+
'<JobSalary>90000</JobSalary>'+
'<JobSalaryMax>105000</JobSalaryMax>'+
'<JobQues1><![CDATA[ ]]>'+
'</JobQues1>'+
'<JobQues2><![CDATA[ ]]>'+
'</JobQues2>'+
'<JobQues3><![CDATA[ ]]>'+
'</JobQues3>'+
'<JobType>0|0</JobType>'+
'<JobAddnlBens>17,14,23,1,5,9,12,10</JobAddnlBens>'+
'<JobLocations>96,98,97</JobLocations>'+
'<JobEducations>8</JobEducations>'+
'<JobExperiences>10</JobExperiences>'+
'<JobCategories>1043,1050</JobCategories>'+
'<JobSubcategories>69896,69869</JobSubcategories>'+
'</JobDetails>'+
'</Transaction>'+
'</XML>';
function on_click()
{
if(window.ActiveXObject)
{
try
{
xmlhttp = new ActiveXObject('Msxml2.XMLHTTP');
}
catch (ex)
{
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
}
else if (window.XMLHttpRequest)
{
xmlhttp = new window.XMLHttpRequest();
netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
}
var xmlToSend = '<?xml version="1.0" encoding="utf-8"?>'+
'<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">'+
'<soap:Body>'+
'<InsertXML xmlns="http://recpushdata.cyndigo.com/">'+
'<Jobs>'+XMLContent+'</Jobs>'+
'</InsertXML>'+
'</soap:Body>'+
'</soap:Envelope>';
var szUrl;
szUrl = 'http://recpushdata.cyndigo.com/Jobs.asmx?op=InsertXML';
xmlhttp.onreadystatechange = state_Change;
xmlhttp.open("Post", szUrl, true);
xmlhttp.setRequestHeader ("SOAPAction", "http://recpushdata.cyndigo.com/InsertXML");
xmlhttp.setRequestHeader ("Content-Type", "text/xml");
xmlhttp.send(xmlToSend);
}
function state_Change()
{
// if xmlhttp shows "loaded"
if (xmlhttp.readyState==4)
{
// if "OK"
if (xmlhttp.status==200)
{
alert("OK"+xmlhttp.responseText);
}
else
{
alert("Problem retrieving XML data "+xmlhttp.responseText);
}
}
}
</script>
</head>
<body>
<div>
<h1>
Click the button to call the web service</h1>
<input type="button" onclick="return on_click();" value="OK" />
</div>
<div id="responseDiv">
</div>
</body>
</html>
</code>
</pre>
| [
{
"answer_id": 355303,
"author": "Chris",
"author_id": 34942,
"author_profile": "https://Stackoverflow.com/users/34942",
"pm_score": 3,
"selected": false,
"text": "http://www.example.com/page1\n http://www.sample.com/webservice\n"
},
{
"answer_id": 355360,
"author": "Jonathan Lonowski",
"author_id": 15031,
"author_profile": "https://Stackoverflow.com/users/15031",
"pm_score": 0,
"selected": false,
"text": "Content-type UTF-8 application/xml xmlhttp.setRequestHeader(\"Content-Type\", \"application/xml; charset=utf-8\");\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355299",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42070/"
] |
355,311 | <p>We have a Perl program to validate XML which is invoked from a Java program. It is not able to write to standard error and hanging in the print location. </p>
<p>Perl is writing to STDERR and a java program is reading the STDERR using getErrorStream() function. But the Perl program is hanging to write to STDERR. I suspect Java function is blocking the STDERR stream completely and Perl is waiting for this stream to be released. </p>
<p>Is there a way in Perl to overcome this blockage and write to standard error forcefully? Since Java is doing only a read the API should not be locking the STDERR stream as per java doc.</p>
<p>Perl Code snippet is:</p>
<pre><code>sub print_error
{
print STDERR shift;
}
</code></pre>
<p>Java code snippet is:</p>
<pre><code>while ( getErrorStream() != null )
{
SOP errorMessage;
}
</code></pre>
<p>Appreciate the help in advance.</p>
<p>Thanks,
Mathew Liju</p>
| [
{
"answer_id": 355350,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 2,
"selected": false,
"text": "use IO::Handle;\nSTDOUT->autoflush(1);\nSTDERR->autoflush(1);\n"
},
{
"answer_id": 355362,
"author": "Adrian Pronk",
"author_id": 41861,
"author_profile": "https://Stackoverflow.com/users/41861",
"pm_score": 4,
"selected": true,
"text": "Inputstream errors = getErrorStream();\nwhile (errors.read(buffer) > 0) {\n SOP buffer;\n}\n"
},
{
"answer_id": 1791949,
"author": "Robert",
"author_id": 218022,
"author_profile": "https://Stackoverflow.com/users/218022",
"pm_score": 0,
"selected": false,
"text": "STDOUT->autoflush(1);\nSTDERR->autoflush(1);\n autoflush(1) STDERR STDOUT"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355311",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18657/"
] |
355,312 | <p>Let's say I have a generic pointer in objective-c. This pointer could either be a <code>Class</code> object, or it could be an <i>instance</i> of that class. Is there any way to tell the difference between the two?</p>
<p>Example:</p>
<pre><code>
id pointerA = [someClass class];
id pointerB = [[someClass alloc] init];
bool pointerAIsAClass = is_this_a_Class(pointerA); // should be true
bool pointerBIsAClass = is_this_a_Class(pointerB); // should be false
</code></pre>
<p>How would I write the <code><code>is_this_a_Class</code></code> function so that it returns the proper <code>bool</code> value?</p>
<pre><code>bool is_this_a_Class(id somePointer)
{
// your code goes here
}</code></pre>
| [
{
"answer_id": 355361,
"author": "Ashley Clark",
"author_id": 4556,
"author_profile": "https://Stackoverflow.com/users/4556",
"pm_score": 2,
"selected": false,
"text": "BOOL pointer_isClass(id object) {\n return [object respondsToSelector:@selector(instancesRespondToSelector:)];\n}\n Class -instancesRespondToSelector: objc_* -class -class -self BOOL pointer_isClass(id object) {\n return object == [object class];\n}\n -instancesRespondToSelector:"
},
{
"answer_id": 6796941,
"author": "user102008",
"author_id": 102008,
"author_profile": "https://Stackoverflow.com/users/102008",
"pm_score": 3,
"selected": true,
"text": "BOOL object_isClass(id object) {\n return class_isMetaClass(object_getClass(object));\n}\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33686/"
] |
355,313 | <p>I have a link on my webpage to print the webpage. However, the link is also visible in the printout itself.</p>
<p>Is there javascript or HTML code which would hide the link button when I click the print link?</p>
<p>Example:</p>
<pre class="lang-none prettyprint-override"><code> "Good Evening"
Print (click Here To Print)
</code></pre>
<p>I want to hide this "Print" label when it prints the text "Good Evening". The "Print" label should not show on the printout itself.</p>
| [
{
"answer_id": 355335,
"author": "Justin Scott",
"author_id": 44883,
"author_profile": "https://Stackoverflow.com/users/44883",
"pm_score": 4,
"selected": false,
"text": "<div id=\"printOption\">\n <a href=\"javascript:void();\" \n onclick=\"document.getElementById('printOption').style.visibility = 'hidden'; \n document.print(); \n return true;\">\n Print\n </a>\n</div>\n printOption"
},
{
"answer_id": 355342,
"author": "Andreas Grech",
"author_id": 44084,
"author_profile": "https://Stackoverflow.com/users/44084",
"pm_score": 7,
"selected": false,
"text": "media print <link rel=\"stylesheet\" type=\"text/css\" href=\"print.css\" media=\"print\" />\n"
},
{
"answer_id": 356123,
"author": "Diodeus - James MacFarlane",
"author_id": 12579,
"author_profile": "https://Stackoverflow.com/users/12579",
"pm_score": 10,
"selected": false,
"text": "@media print\n{ \n .no-print, .no-print *\n {\n display: none !important;\n }\n}\n class='no-print'"
},
{
"answer_id": 34330516,
"author": "user3806549",
"author_id": 3806549,
"author_profile": "https://Stackoverflow.com/users/3806549",
"pm_score": 4,
"selected": false,
"text": "@media print\n{\n #pager,\n form,\n .no-print\n {\n display: none !important;\n height: 0;\n }\n\n\n .no-print, .no-print *{\n display: none !important;\n height: 0;\n }\n}\n <link href=\"/theme/css/ui/ui.print.css?version=x.x.x\" media=\"print\" rel=\"stylesheet\" type=\"text/css\" >\n <div class=\"no-print\"></div>\n"
},
{
"answer_id": 36352263,
"author": "Bijan",
"author_id": 306478,
"author_profile": "https://Stackoverflow.com/users/306478",
"pm_score": 8,
"selected": false,
"text": "hidden-print\n @media print {\n .hidden-print {\n display: none !important;\n }\n}\n .d-print-none\n"
},
{
"answer_id": 44724517,
"author": "Nesar Ahmad Nori",
"author_id": 5923210,
"author_profile": "https://Stackoverflow.com/users/5923210",
"pm_score": 6,
"selected": false,
"text": "@media print{\n .noprint{\n display:none;\n }\n}\n <div class=\"noprint\">\n element that need to be hidden when printing\n</div>\n"
},
{
"answer_id": 46965391,
"author": "Mike Rapadas",
"author_id": 2078664,
"author_profile": "https://Stackoverflow.com/users/2078664",
"pm_score": 3,
"selected": false,
"text": "@media print {\n .no-print {\n visibility: hidden;\n }\n} <div class=\"no-print\">\n Nope\n</div>\n\n<div>\n Yup\n</div>"
},
{
"answer_id": 48483884,
"author": "webs",
"author_id": 3629945,
"author_profile": "https://Stackoverflow.com/users/3629945",
"pm_score": 2,
"selected": false,
"text": " media=\"screen, print\" \n media=\"screen\"\n <link rel=\"stylesheet\" href=\"my_cssfile.css\" media=\"screen, print\"type=\"text/css\">\n <link rel=\"stylesheet\" href=\"my_cssfile.css\" media=\"screen\" type=\"text/css\">\n"
},
{
"answer_id": 53535500,
"author": "Elias Hasle",
"author_id": 4071801,
"author_profile": "https://Stackoverflow.com/users/4071801",
"pm_score": 2,
"selected": false,
"text": "!important onbeforeprint onafterprint"
},
{
"answer_id": 70914961,
"author": "BogisW",
"author_id": 13192551,
"author_profile": "https://Stackoverflow.com/users/13192551",
"pm_score": 1,
"selected": false,
"text": "!important no-print var noPrintElements = [];\n\nwindow.addEventListener(\"beforeprint\", function(event) {\n var hideMe = document.getElementsByClassName(\"no-print\");\n noPrintElements = [];\n Array.prototype.forEach.call(hideMe, function(item, index) {\n noPrintElements.push({\"element\": item, \"display\": item.style.display });\n item.style.display = 'none'; // hide the element\n }); \n});\n\nwindow.addEventListener(\"afterprint\", function(event) {\n Array.prototype.forEach.call(noPrintElements, function(item, index) {\n item.element.style.display = item.display; // restore the element\n }); \n noPrintElements = []; // just to be on the safe side\n});\n"
}
] | 2008/12/10 | [
"https://Stackoverflow.com/questions/355313",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.